Merge pull request #74 from arjunballa/master

doneSuccess and doneFailure callback functions and display resources in list and expanded view
This commit is contained in:
Ayush Gupta
2012-11-04 18:26:29 -08:00
4 changed files with 335 additions and 322 deletions

1
.gitignore vendored
View File

@@ -19,3 +19,4 @@ reports/*
.sass-cache .sass-cache
swagger-ui.sublime-workspace swagger-ui.sublime-workspace
.idea .idea
.project

View File

@@ -1,73 +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.success = => @render(options)
@options.progress = (d) => @showMessage(d) @options.progress = (d) => @showMessage(d)
@options.failure = (d) => @onLoadFailure(d) @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: -> 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()
setTimeout( switch options.docStyle
=> when "expand" then Docs.expandOperationsForResource('')
Docs.shebang() when "list" then Docs.collapseOperationsForResource('')
400 options.doneSuccess() if options.doneSuccess
) setTimeout(
=>
# Shows message on topbar of the ui Docs.shebang()
showMessage: (data = '') -> 400
$('#message-bar').removeClass 'message-fail' )
$('#message-bar').addClass 'message-success'
$('#message-bar').html data # Shows message on topbar of the ui
showMessage: (data = '') ->
# shows message in red $('#message-bar').removeClass 'message-fail'
onLoadFailure: (data = '') -> $('#message-bar').addClass 'message-success'
$('#message-bar').removeClass 'message-success' $('#message-bar').html data
$('#message-bar').addClass 'message-fail'
$('#message-bar').html data # shows message in red
onLoadFailure: (data = '', doneFailure) ->
$('#message-bar').removeClass 'message-success'
window.SwaggerUi = SwaggerUi $('#message-bar').addClass 'message-fail'
val = $('#message-bar').html data
doneFailure() if doneFailure
val
window.SwaggerUi = SwaggerUi

View File

@@ -1,88 +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(){
console.log("DONE!!!")
window.swaggerUi.load(); },
}); // "" - default behavior
// list - list view of all resources
</script> // expand - expanded view of all resources
</head> docStyle: ""
});
<body>
<div id='header'> window.swaggerUi.load();
<div class="swagger-ui-wrap"> });
<a id="logo" href="http://swagger.wordnik.com">swagger</a>
</script>
<form id='api_selector'> </head>
<div class='input icon-btn'>
<img id="show-pet-store-icon" src="images/pet_store_api.png" title="Show Swagger Petstore Example Apis"> <body>
</div> <div id='header'>
<div class='input icon-btn'> <div class="swagger-ui-wrap">
<img id="show-wordnik-dev-icon" src="images/wordnik_api.png" title="Show Wordnik Developer Apis"> <a id="logo" href="http://swagger.wordnik.com">swagger</a>
</div>
<div class='input'><input placeholder="http://example.com/api" id="input_baseUrl" name="baseUrl" <form id='api_selector'>
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-pet-store-icon" src="images/pet_store_api.png" title="Show Swagger Petstore Example Apis">
<div class='input'><a id="explore" href="#">Explore</a></div> </div>
</form> <div class='input icon-btn'>
</div> <img id="show-wordnik-dev-icon" src="images/wordnik_api.png" title="Show Wordnik Developer Apis">
</div> </div>
<div class='input'><input placeholder="http://example.com/api" id="input_baseUrl" name="baseUrl"
<div id="message-bar" class="swagger-ui-wrap"> type="text"/></div>
&nbsp; <div class='input'><input placeholder="api_key" id="input_apiKey" name="apiKey" type="text"/></div>
</div> <div class='input'><a id="explore" href="#">Explore</a></div>
</form>
<div id="swagger-ui-container" class="swagger-ui-wrap"> </div>
</div>
</div>
<div id="message-bar" class="swagger-ui-wrap">
</body> &nbsp;
</div>
</html>
<div id="swagger-ui-container" class="swagger-ui-wrap">
</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();
} }
}; };