code to display resources in default/list/expended style. style can be

passed as a option while creating swagerUi object.
In future I would like to achieve this by passing options to templates
and have a template helper method manipulate dom and apply correct
classes.This approach will improve the performance as we need not go
over the entire dom and call Doc.collapseOperationsForResource or
Doc.expandOperationsForResource on each matched element
This commit is contained in:
Arjun Balla
2012-10-23 11:42:26 -07:00
parent 1fc4caae2e
commit 6beaa62b71
3 changed files with 334 additions and 327 deletions

View File

@@ -1,75 +1,78 @@
class SwaggerUi extends Backbone.Router class SwaggerUi extends Backbone.Router
# Defaults # Defaults
dom_id: "swagger_ui" dom_id: "swagger_ui"
# Attributes # Attributes
options: null options: null
api: null api: null
headerView: null headerView: null
mainView: null mainView: null
# SwaggerUi accepts all the same options as SwaggerApi # SwaggerUi accepts all the same options as SwaggerApi
initialize: (options={}) -> initialize: (options={}) ->
# Allow dom_id to be overridden # Allow dom_id to be overridden
if options.dom_id? if options.dom_id?
@dom_id = options.dom_id @dom_id = options.dom_id
delete options.dom_id delete options.dom_id
# Create an empty div which contains the dom_id # Create an empty div which contains the dom_id
$('body').append('<div id="' + @dom_id + '"></div>') if not $('#' + @dom_id)? $('body').append('<div id="' + @dom_id + '"></div>') if not $('#' + @dom_id)?
@options = options @options = options
# Set the callbacks # Set the callbacks
@options.success = => @render(options) @options.success = => @render(options)
@options.progress = (d) => @showMessage(d) @options.progress = (d) => @showMessage(d)
@options.failure = (d) => @onLoadFailure(d, options.doneFailure) @options.failure = (d) => @onLoadFailure(d, options.doneFailure)
# Create view to handle the header inputs # Create view to handle the header inputs
@headerView = new HeaderView({el: $('#header')}) @headerView = new HeaderView({el: $('#header')})
# Event handler for when the baseUrl/apiKey is entered by user # Event handler for when the baseUrl/apiKey is entered by user
@headerView.on 'update-swagger-ui', (data) => @updateSwaggerUi(data) @headerView.on 'update-swagger-ui', (data) => @updateSwaggerUi(data)
# Event handler for when url/key is received from user # Event handler for when url/key is received from user
updateSwaggerUi: (data) -> updateSwaggerUi: (data) ->
@options.discoveryUrl = data.discoveryUrl @options.discoveryUrl = data.discoveryUrl
@options.apiKey = data.apiKey @options.apiKey = data.apiKey
@load() @load()
# Create an api and render # Create an api and render
load: -> load: ->
# Initialize the API object # Initialize the API object
@mainView?.clear() @mainView?.clear()
@headerView.update(@options.discoveryUrl, @options.apiKey) @headerView.update(@options.discoveryUrl, @options.apiKey)
@api = new SwaggerApi(@options) @api = new SwaggerApi(@options)
# This is bound to success handler for SwaggerApi # This is bound to success handler for SwaggerApi
# so it gets called when SwaggerApi completes loading # so it gets called when SwaggerApi completes loading
render:(options) -> render:(options) ->
@showMessage('Finished Loading Resource Information. Rendering Swagger UI...') @showMessage('Finished Loading Resource Information. Rendering Swagger UI...')
@mainView = new MainView({model: @api, el: $('#' + @dom_id)}).render() @mainView = new MainView({model: @api, el: $('#' + @dom_id)}).render()
@showMessage() @showMessage()
options.doneSuccess() if options.doneSuccess switch options.docStyle
setTimeout( when "expand" then Docs.expandOperationsForResource('')
=> when "list" then Docs.collapseOperationsForResource('')
Docs.shebang() options.doneSuccess() if options.doneSuccess
400 setTimeout(
) =>
Docs.shebang()
# Shows message on topbar of the ui 400
showMessage: (data = '') -> )
$('#message-bar').removeClass 'message-fail'
$('#message-bar').addClass 'message-success' # Shows message on topbar of the ui
$('#message-bar').html data showMessage: (data = '') ->
$('#message-bar').removeClass 'message-fail'
# shows message in red $('#message-bar').addClass 'message-success'
onLoadFailure: (data = '', doneFailure) -> $('#message-bar').html data
$('#message-bar').removeClass 'message-success'
$('#message-bar').addClass 'message-fail' # shows message in red
val = $('#message-bar').html data onLoadFailure: (data = '', doneFailure) ->
doneFailure() if doneFailure $('#message-bar').removeClass 'message-success'
val $('#message-bar').addClass 'message-fail'
val = $('#message-bar').html data
window.SwaggerUi = SwaggerUi doneFailure() if doneFailure
val
window.SwaggerUi = SwaggerUi

View File

@@ -1,91 +1,95 @@
<html> <html>
<head> <head>
<title>Swagger UI</title> <title>Swagger UI</title>
<link href='http://fonts.googleapis.com/css?family=Droid+Sans:400,700' rel='stylesheet' type='text/css'/> <link href='http://fonts.googleapis.com/css?family=Droid+Sans:400,700' rel='stylesheet' type='text/css'/>
<link href='css/screen.css' media='screen' rel='stylesheet' type='text/css'/> <link href='css/screen.css' media='screen' rel='stylesheet' type='text/css'/>
<script src='lib/jquery-1.8.0.min.js' type='text/javascript'></script> <script src='lib/jquery-1.8.0.min.js' type='text/javascript'></script>
<script src='lib/jquery.slideto.min.js' type='text/javascript'></script> <script src='lib/jquery.slideto.min.js' type='text/javascript'></script>
<script src='lib/jquery.wiggle.min.js' type='text/javascript'></script> <script src='lib/jquery.wiggle.min.js' type='text/javascript'></script>
<script src='lib/jquery.ba-bbq.min.js' type='text/javascript'></script> <script src='lib/jquery.ba-bbq.min.js' type='text/javascript'></script>
<script src='lib/handlebars.runtime-1.0.0.beta.6.js' type='text/javascript'></script> <script src='lib/handlebars.runtime-1.0.0.beta.6.js' type='text/javascript'></script>
<script src='lib/underscore-min.js' type='text/javascript'></script> <script src='lib/underscore-min.js' type='text/javascript'></script>
<script src='lib/backbone-min.js' type='text/javascript'></script> <script src='lib/backbone-min.js' type='text/javascript'></script>
<script src='lib/swagger.js' type='text/javascript'></script> <script src='lib/swagger.js' type='text/javascript'></script>
<script src='swagger-ui.js' type='text/javascript'></script> <script src='swagger-ui.js' type='text/javascript'></script>
<style type="text/css"> <style type="text/css">
.swagger-ui-wrap { .swagger-ui-wrap {
max-width: 960px; max-width: 960px;
margin-left: auto; margin-left: auto;
margin-right: auto; margin-right: auto;
} }
.icon-btn { .icon-btn {
cursor: pointer; cursor: pointer;
} }
#message-bar { #message-bar {
min-height: 30px; min-height: 30px;
text-align: center; text-align: center;
padding-top: 10px; padding-top: 10px;
} }
.message-success { .message-success {
color: #89BF04; color: #89BF04;
} }
.message-fail { .message-fail {
color: #cc0000; color: #cc0000;
} }
</style> </style>
<script type="text/javascript"> <script type="text/javascript">
$(function () { $(function () {
window.swaggerUi = new SwaggerUi({ window.swaggerUi = new SwaggerUi({
discoveryUrl:"http://petstore.swagger.wordnik.com/api/resources.json", discoveryUrl:"http://petstore.swagger.wordnik.com/api/resources.json",
apiKey:"special-key", apiKey:"special-key",
dom_id:"swagger-ui-container", dom_id:"swagger-ui-container",
supportHeaderParams: false, supportHeaderParams: false,
supportedSubmitMethods: ['get', 'post', 'put'], supportedSubmitMethods: ['get', 'post', 'put'],
doneSuccess: function(){ doneSuccess: function(){
console.log("DONE!!!") console.log("DONE!!!")
} },
}); // "" - default behavior
// list - list view of all resources
window.swaggerUi.load(); // expand - expanded view of all resources
}); docStyle: ""
});
</script>
</head> window.swaggerUi.load();
});
<body>
<div id='header'> </script>
<div class="swagger-ui-wrap"> </head>
<a id="logo" href="http://swagger.wordnik.com">swagger</a>
<body>
<form id='api_selector'> <div id='header'>
<div class='input icon-btn'> <div class="swagger-ui-wrap">
<img id="show-pet-store-icon" src="images/pet_store_api.png" title="Show Swagger Petstore Example Apis"> <a id="logo" href="http://swagger.wordnik.com">swagger</a>
</div>
<div class='input icon-btn'> <form id='api_selector'>
<img id="show-wordnik-dev-icon" src="images/wordnik_api.png" title="Show Wordnik Developer Apis"> <div class='input icon-btn'>
</div> <img id="show-pet-store-icon" src="images/pet_store_api.png" title="Show Swagger Petstore Example Apis">
<div class='input'><input placeholder="http://example.com/api" id="input_baseUrl" name="baseUrl" </div>
type="text"/></div> <div class='input icon-btn'>
<div class='input'><input placeholder="api_key" id="input_apiKey" name="apiKey" type="text"/></div> <img id="show-wordnik-dev-icon" src="images/wordnik_api.png" title="Show Wordnik Developer Apis">
<div class='input'><a id="explore" href="#">Explore</a></div> </div>
</form> <div class='input'><input placeholder="http://example.com/api" id="input_baseUrl" name="baseUrl"
</div> type="text"/></div>
</div> <div class='input'><input placeholder="api_key" id="input_apiKey" name="apiKey" type="text"/></div>
<div class='input'><a id="explore" href="#">Explore</a></div>
<div id="message-bar" class="swagger-ui-wrap"> </form>
&nbsp; </div>
</div> </div>
<div id="swagger-ui-container" class="swagger-ui-wrap"> <div id="message-bar" class="swagger-ui-wrap">
&nbsp;
</div> </div>
</body> <div id="swagger-ui-container" class="swagger-ui-wrap">
</html> </div>
</body>
</html>

View File

@@ -1,162 +1,162 @@
$(function() { $(function() {
// Helper function for vertically aligning DOM elements // Helper function for vertically aligning DOM elements
// http://www.seodenver.com/simple-vertical-align-plugin-for-jquery/ // http://www.seodenver.com/simple-vertical-align-plugin-for-jquery/
$.fn.vAlign = function() { $.fn.vAlign = function() {
return this.each(function(i){ return this.each(function(i){
var ah = $(this).height(); var ah = $(this).height();
var ph = $(this).parent().height(); var ph = $(this).parent().height();
var mh = (ph - ah) / 2; var mh = (ph - ah) / 2;
$(this).css('margin-top', mh); $(this).css('margin-top', mh);
}); });
}; };
$.fn.stretchFormtasticInputWidthToParent = function() { $.fn.stretchFormtasticInputWidthToParent = function() {
return this.each(function(i){ return this.each(function(i){
var p_width = $(this).closest("form").innerWidth(); var p_width = $(this).closest("form").innerWidth();
var p_padding = parseInt($(this).closest("form").css('padding-left') ,10) + parseInt($(this).closest("form").css('padding-right'), 10); var p_padding = parseInt($(this).closest("form").css('padding-left') ,10) + parseInt($(this).closest("form").css('padding-right'), 10);
var this_padding = parseInt($(this).css('padding-left'), 10) + parseInt($(this).css('padding-right'), 10); var this_padding = parseInt($(this).css('padding-left'), 10) + parseInt($(this).css('padding-right'), 10);
$(this).css('width', p_width - p_padding - this_padding); $(this).css('width', p_width - p_padding - this_padding);
}); });
}; };
$('form.formtastic li.string input, form.formtastic textarea').stretchFormtasticInputWidthToParent(); $('form.formtastic li.string input, form.formtastic textarea').stretchFormtasticInputWidthToParent();
// Vertically center these paragraphs // Vertically center these paragraphs
// Parent may need a min-height for this to work.. // Parent may need a min-height for this to work..
$('ul.downplayed li div.content p').vAlign(); $('ul.downplayed li div.content p').vAlign();
// When a sandbox form is submitted.. // When a sandbox form is submitted..
$("form.sandbox").submit(function(){ $("form.sandbox").submit(function(){
var error_free = true; var error_free = true;
// Cycle through the forms required inputs // Cycle through the forms required inputs
$(this).find("input.required").each(function() { $(this).find("input.required").each(function() {
// Remove any existing error styles from the input // Remove any existing error styles from the input
$(this).removeClass('error'); $(this).removeClass('error');
// Tack the error style on if the input is empty.. // Tack the error style on if the input is empty..
if ($(this).val() == '') { if ($(this).val() == '') {
$(this).addClass('error'); $(this).addClass('error');
$(this).wiggle(); $(this).wiggle();
error_free = false; error_free = false;
} }
}); });
return error_free; return error_free;
}); });
}); });
function clippyCopiedCallback(a) { function clippyCopiedCallback(a) {
$('#api_key_copied').fadeIn().delay(1000).fadeOut(); $('#api_key_copied').fadeIn().delay(1000).fadeOut();
// var b = $("#clippy_tooltip_" + a); // var b = $("#clippy_tooltip_" + a);
// b.length != 0 && (b.attr("title", "copied!").trigger("tipsy.reload"), setTimeout(function() { // b.length != 0 && (b.attr("title", "copied!").trigger("tipsy.reload"), setTimeout(function() {
// b.attr("title", "copy to clipboard") // b.attr("title", "copy to clipboard")
// }, // },
// 500)) // 500))
} }
// Logging function that accounts for browsers that don't have window.console // Logging function that accounts for browsers that don't have window.console
function log() { function log() {
if (window.console) console.log.apply(console,arguments); if (window.console) console.log.apply(console,arguments);
} }
var Docs = { var Docs = {
shebang: function() { shebang: function() {
// If shebang has an operation nickname in it.. // If shebang has an operation nickname in it..
// e.g. /docs/#!/words/get_search // e.g. /docs/#!/words/get_search
var fragments = $.param.fragment().split('/'); var fragments = $.param.fragment().split('/');
fragments.shift(); // get rid of the bang fragments.shift(); // get rid of the bang
switch (fragments.length) { switch (fragments.length) {
case 1: case 1:
// Expand all operations for the resource and scroll to it // Expand all operations for the resource and scroll to it
// log('shebang resource:' + fragments[0]); // log('shebang resource:' + fragments[0]);
var dom_id = 'resource_' + fragments[0]; var dom_id = 'resource_' + fragments[0];
Docs.expandEndpointListForResource(fragments[0]); Docs.expandEndpointListForResource(fragments[0]);
$("#"+dom_id).slideto({highlight: false}); $("#"+dom_id).slideto({highlight: false});
break; break;
case 2: case 2:
// Refer to the endpoint DOM element, e.g. #words_get_search // Refer to the endpoint DOM element, e.g. #words_get_search
// log('shebang endpoint: ' + fragments.join('_')); // log('shebang endpoint: ' + fragments.join('_'));
// Expand Resource // Expand Resource
Docs.expandEndpointListForResource(fragments[0]); Docs.expandEndpointListForResource(fragments[0]);
$("#"+dom_id).slideto({highlight: false}); $("#"+dom_id).slideto({highlight: false});
// Expand operation // Expand operation
var li_dom_id = fragments.join('_'); var li_dom_id = fragments.join('_');
var li_content_dom_id = li_dom_id + "_content"; var li_content_dom_id = li_dom_id + "_content";
// log("li_dom_id " + li_dom_id); // log("li_dom_id " + li_dom_id);
// log("li_content_dom_id " + li_content_dom_id); // log("li_content_dom_id " + li_content_dom_id);
Docs.expandOperation($('#'+li_content_dom_id)); Docs.expandOperation($('#'+li_content_dom_id));
$('#'+li_dom_id).slideto({highlight: false}); $('#'+li_dom_id).slideto({highlight: false});
break; break;
} }
}, },
toggleEndpointListForResource: function(resource) { toggleEndpointListForResource: function(resource) {
var elem = $('li#resource_' + Docs.escapeResourceName(resource) + ' ul.endpoints'); var elem = $('li[id^=resource_' + Docs.escapeResourceName(resource) + '] ul.endpoints');
if (elem.is(':visible')) { if (elem.is(':visible')) {
Docs.collapseEndpointListForResource(resource); Docs.collapseEndpointListForResource(resource);
} else { } else {
Docs.expandEndpointListForResource(resource); Docs.expandEndpointListForResource(resource);
} }
}, },
// Expand resource // Expand resource
expandEndpointListForResource: function(resource) { expandEndpointListForResource: function(resource) {
$('#resource_' + resource).addClass('active'); $('[id^=resource_' + resource + ']').addClass('active');
var elem = $('li#resource_' + Docs.escapeResourceName(resource) + ' ul.endpoints'); var elem = $('li[id^=resource_' + Docs.escapeResourceName(resource) + '] ul.endpoints');
elem.slideDown(); elem.slideDown();
}, },
// Collapse resource and mark as explicitly closed // Collapse resource and mark as explicitly closed
collapseEndpointListForResource: function(resource) { collapseEndpointListForResource: function(resource) {
$('#resource_' + resource).removeClass('active'); $('[id^=resource_' + resource + ']').removeClass('active');
var elem = $('li#resource_' + Docs.escapeResourceName(resource) + ' ul.endpoints'); var elem = $('li[id^=resource_' + Docs.escapeResourceName(resource) + '] ul.endpoints');
elem.slideUp(); elem.slideUp();
}, },
expandOperationsForResource: function(resource) { expandOperationsForResource: function(resource) {
// Make sure the resource container is open.. // Make sure the resource container is open..
Docs.expandEndpointListForResource(resource); Docs.expandEndpointListForResource(resource);
$('li#resource_' + Docs.escapeResourceName(resource) + ' li.operation div.content').each(function() { $('li[id^=resource_' + Docs.escapeResourceName(resource) + '] li.operation div.content').each(function() {
Docs.expandOperation($(this)); Docs.expandOperation($(this));
}); });
}, },
collapseOperationsForResource: function(resource) { collapseOperationsForResource: function(resource) {
// Make sure the resource container is open.. // Make sure the resource container is open..
Docs.expandEndpointListForResource(resource); Docs.expandEndpointListForResource(resource);
$('li#resource_' + Docs.escapeResourceName(resource) + ' li.operation div.content').each(function() { $('li[id^=resource_' + Docs.escapeResourceName(resource) + '] li.operation div.content').each(function() {
Docs.collapseOperation($(this)); Docs.collapseOperation($(this));
}); });
}, },
escapeResourceName: function(resource) { escapeResourceName: function(resource) {
return resource.replace(/[!"#$%&'()*+,.\/:;<=>?@\[\\\]\^`{|}~]/g, "\\$&") return resource.replace(/[!"#$%&'()*+,.\/:;<=>?@\[\\\]\^`{|}~]/g, "\\$&")
}, },
expandOperation: function(elem) { expandOperation: function(elem) {
elem.slideDown(); elem.slideDown();
}, },
collapseOperation: function(elem) { collapseOperation: function(elem) {
elem.slideUp(); elem.slideUp();
} }
}; };