From 63af84ab2eaeb20e5c4c27148ec8331cc93d1ea8 Mon Sep 17 00:00:00 2001 From: jlukic Date: Sat, 11 Oct 2014 15:24:41 -0400 Subject: [PATCH] Updates to API docs --- server/documents/modules/api.html.eco | 358 +++++++++++++----- server/files/javascript/api.js | 8 +- .../javascript/library/serialize-object.js | 152 ++++++++ server/files/stylesheets/semantic.css | 21 +- 4 files changed, 429 insertions(+), 110 deletions(-) create mode 100644 server/files/javascript/library/serialize-object.js diff --git a/server/documents/modules/api.html.eco b/server/documents/modules/api.html.eco index 1522d687a..620f65eea 100644 --- a/server/documents/modules/api.html.eco +++ b/server/documents/modules/api.html.eco @@ -7,6 +7,7 @@ description : 'API allows elements to trigger actions on a server' type : 'UI Behavior' --- + @@ -68,49 +69,55 @@ type : 'UI Behavior'

Defining Your API

-

Creating Server Actions

+

Setting API Endpoints

API works best by defining named API actions which can be converted to URLs for each request.

You must define your endpoints once in your application before making requests. Usually this is done in a central configuration file included on each page.

URLs listed in your API can include required parameters and optional parameters which may be adjusted for each call.

-
-
-
Required Parameters
-
-
Uses format {variable}
-
Will abort the request if they cannot be found.
-
-
-
-
Optional Parameters
-
-
Uses format {/variable}
-
Will abort the request if they cannot be found.
-
Will be removed from the url automatically if not available.
-
Any preceding slash before an optional parameter will be removed from the URL, allowing you to include them in resource paths.
-
-
+
Required Parameters
+
+
Uses format {variable}
+
Will abort the request if they cannot be found.
+
+
Optional Parameters
+
+
Uses format {/variable}
+
Will abort the request if they cannot be found.
+
Will be removed from the url automatically if not available.
+
Any preceding slash before an optional parameter will be removed from the URL, allowing you to include them in resource paths.
/* Define API endpoints once globally */ $.fn.api.settings.api = { 'get followers' : '/followers/{id}?results={count}', + 'create user' : '/create', 'follow user' : '/follow/{id}', 'search' : '/search/?query={value}' };
+
+

Working with URLs

+

Named API actions are offered for convenience and maintanability, but are not required. You can also specify the url in each request, templated or not.

+
+ $('.search.button') + .api({ + url: 'http://www.google.com?q={value}' + }) + ; +
+

Querying API Actions

-
+
Open Your Web Console
The following examples work best while viewing logs in your web console. This experienced is optimized for Firebug, but will also appear in webkit browsers with minor issues.
-
+
API requests for the following demos have been faked using SinonJS to avoid rate throttling from public APIs. No actual data is returned.
-

Attaching API to UI

+

Attaching API Events

Any element can have an API action attached directly to it. By default the action will occur on the most appropriate event for the type of element. For example a button will assume onclick or an input oninput, or a form onsubmit.

@@ -121,10 +128,21 @@ type : 'UI Behavior' }) ;
+
Or
+
+ +
+
+ $('.follow.button') + .api() + ; +
-

Specifying Events

+

Specifying DOM Events

If you need to override what action an API event occurs on you can use the on parameter.

$('.follow.button') @@ -168,9 +186,6 @@ type : 'UI Behavior'

URL Variables

If your API urls include templated variables they will be replaced during your request by one of four possible ways (listed in order of inheritance).

-
- Only variables specified in your URL will be searched for in metadata. Adding metadata attributes will not be automatically included in GET or POST values. -
@@ -204,13 +219,12 @@ type : 'UI Behavior'
- $.fn.api.settings.api = { - 'search' : '/search/?query={value}' - }; + $.fn.api.settings.api.search = '/search/?query={value}'; + $('.search input') .api({ action: 'search', - // this setting will be explained later + // what receives state class names stateContext: '.ui.input' }) ; @@ -221,6 +235,9 @@ type : 'UI Behavior'

Data Attributes

You can include url values as metadata inside the DOM.

This is often easiest to include unique url data for each triggering element. For example, many follow buttons will trigger the same endpoint, but each will have its own user id.

+
+ Only variables specified in your API's URL will be searched for in metadata. +
-

....in Javascript

-

URL variables can be specified at run-time in the javascript object

+

Data specified in Javascript

+

URL variable, and GET/POST data can be specified at run-time in the javascript object

$('.follow.button') .api({ - action: 'follow user', + action : 'follow user', + method : 'POST', + // Substituted into URL urlData: { id: 22 + }, + // passed via POST + data: { + name: 'Joe Henderson' } }) ; @@ -254,9 +277,11 @@ type : 'UI Behavior'
-

...specified in beforeSend Callback

+

Modifying Data and Settings Just Before Sending

All run settings, not just url data, can be adjusted in a special callback beforeSend which occurs before the API request is sent.

-

You can also use this callback to adjust other settings before each API call

+
+ An additional callback beforeXHR lets you modify the XHR object before sending. This is different than beforeSend. +
$('.follow.button') .api({ @@ -267,25 +292,123 @@ type : 'UI Behavior' }; return settings; } + // basic auth login + beforeXHR: function(xhr) { + xhr.setRequestHeader ('Authorization', 'Basic XXXXXX'); + } }) ;
-

Routing GET/POST Data

-
-

...specified in beforeSend Callback

-

All run settings, not just url data, can be adjusted in a special callback beforeSend which occurs before the API request is sent.

-

You can also use this callback to adjust other settings before each API call

-
+

Cancelling Requests

+

BeforeSend can also be used to check for special conditions for a request to be made. It the beforeSend callback returns false, the request will be cancelled.

+
+ // set somewhere in your code + window.isLoggedIn = false; + $('.follow.button') .api({ action: 'follow user', + // cancels request beforeSend: function(settings) { - settings.urlData = { - id: 22 - }; + return isLoggedIn; + } + }) + ; +
+
+ +

Including Server Data

+ +
+

Automatically Routed

+

Calling API on any element inside of a form, will automatically include serialized form content in your request when using a special setting serializeForm, or using a form as the stateContext.

+
+ Using serializeForm requires including the serialize-object dependency. +
+

Unlike jQuery's serialize, data will be serialized as a javascript object using macek's serialize object. +

Benefits of Structured Data
+
    +
  • Serialized Form Data can be modified in javascript in beforeSend
  • +
  • Structured data can be used by using names like name="user[name]" in your form
  • +
  • Form data will automatically be converted to useful values, for instance, checkbox to to boolean values.
  • +

    +

    +
    +
    + +
    +
    + +
    +
    + +
    +
    +
    +
    + + +
    +
    +
    +
    + +
    + + +
    +
    +
    + +
    + + +
    +
    +
    +
    Submit
    +
    +
    + $('form .submit.button') + .api({ + action: 'create user', + serializeForm: true, + beforeSend: function(settings) { + // open console to inspect object + console.log(settings.data); + return settings; + } + }) + ; +
    +
+ + +
+

Included in Javascript

+

POST or GET data can be included, when setting up API requests, through automatic inclusion, or during the beforeSend callback. This data will be joined together

+
+ $('.form .submit') + .api({ + action: 'create user', + serializeForm: true, + data: { + sessionID: '232' + }, + beforeSend: function(settings) { + settings.data.token = window.generateToken(); + // will include serialized data, session id, and token return settings; } }) @@ -299,7 +422,7 @@ type : 'UI Behavior'

Determining Success

API is designed to work with APIs that return JSON objects. Instead of providiing success and failure callbacks based on the HTTP response of the request. A request is considered succesful only if the returned JSON value passes a successTest.

For example you might expect all successful JSON responses to return a top level property signifying the success of the response

-

+
{ "success": true, "message": "We've retreived your data from the server" @@ -308,7 +431,8 @@ type : 'UI Behavior' } }
-

The success test function recieves the servers json response, and returns whether the result should be considered successful. Succesful results will trigger onSuccess unsuccesful results onFailure but not onError, this is reserved for responses which return XHR errors.

+

The success test function recieves the servers json response, and returns whether the result should be considered successful. Succesful results will trigger onSuccess, invalid results onFailure.

+

onError will only trigger on XHR errors (except due to page navigation like clicking a link), but not invalid JSON responses.

$('.follow.button') .api({ @@ -316,13 +440,16 @@ type : 'UI Behavior' return response.success || false; } onSuccess: function() { - // valid response and action succeeded + // valid response and response.success = true }, onFailure: function() { - // valid response but action failed + // valid response but response.success = false }, onError: function() { // invalid response + }, + onAbort: function() { + // user cancelled request } }) ; @@ -374,7 +501,9 @@ type : 'UI Behavior'
$('.follow.button') - .api('setting', 'on', 'auto') + .api({ + action: 'follow user' + }) .state({ text: { inactive : 'Follow', @@ -401,6 +530,7 @@ type : 'UI Behavior' inactive Default state + active @@ -494,35 +624,28 @@ type : 'UI Behavior' stateContext - this (selector/DOM element) + this UI state will be applied to this element, defaults to triggering element. defaultData true - Whether to include default data like {value} and {text} + Whether to automatically include default data like {value} and {text} serializeForm - (true, false) + false Whether to serialize closest form and include in request - throttle + loadingDuration 0 - If a request is pending, additional requests will be throttled by this duration in ms. (Setting above 0 will allow multiple simultaneous requests) + Minimum duration to show loading indication - regExp - -
- regExp : { - required: /\{\$*[A-z0-9]+\}/g, - optional: /\{\/\$*[A-z0-9]+\}/g, - } -
- - Regular expressions used for finding variables in templated urls + errorDuration + 2000 + Duration in milliseconds to show error state after request error. @@ -574,20 +697,6 @@ type : 'UI Behavior' POST/GET Data to Send with Request - - filter - -
- .disabled -
- - Selector filter for elements that should not be triggerable - - - stateContext - this (selector/DOM element) - UI state will be applied to this element, defaults to triggering element. - @@ -603,19 +712,39 @@ type : 'UI Behavior' - onOpen - active content - Callback on element open + beforeSend(settings) + initialized element + Allows modifying settings before request, or cancelling request + + + beforeXHR(xhrObject) + + Allows modifying XHR object for request + + + onSuccess(response, element) + state context + Callback on response object that passed successTest - onClose - active content - Callback on element close + onFailure(response, element) + state context + Callback on response object that fails successTest - onChange - active content - Callback on element open or close + onError(errorMessage, element) + state context + Callback on server error from returned status code, or XHR failure. + + + onAbort(errorMessage, element) + state context + Callback on abort caused by user clicking a link or manually cancelling request + + + onComplete(response, element) + state context + Callback on request complete regardless of conditions @@ -635,22 +764,32 @@ type : 'UI Behavior' name - Accordion + API Name used in log statements namespace - accordion + api Event namespace. Makes sure module teardown does not effect other events attached to an element. + + regExp + +
+ regExp : { + required: /\{\$*[A-z0-9]+\}/g, + optional: /\{\/\$*[A-z0-9]+\}/g, + } +
+ + Regular expressions used for template matching + selector
- selector : { - accordion : '.accordion', - title : '.title', - content : '.content' + selector: { + form: 'form' }
@@ -660,13 +799,27 @@ type : 'UI Behavior' className
- className : { - active : 'active' + className: { + loading : 'loading', + error : 'error' }
Class names used to determine element state + + metadata + +
+ metadata: { + action : 'action', + request : 'request', + xhr : 'xhr' + } +
+ + Metadata used to store xhr and response promise + debug false @@ -686,8 +839,21 @@ type : 'UI Behavior' errors
- error : { - method : 'The method you called is not defined.' + // errors + error : { + beforeSend : 'The before send function has aborted the request', + error : 'There was an error with your request', + exitConditions : 'API Request Aborted. Exit conditions met', + JSONParse : 'JSON could not be parsed during error handling', + legacyParameters : 'You are using legacy API success callback names', + missingAction : 'API action used but no url was defined', + missingSerialize : 'Required dependency jquery-serialize-object missing, using basic serialize', + missingURL : 'No URL specified for api event', + noReturnedValue : 'The beforeSend callback must return a settings object, beforeSend ignored.', + parseError : 'There was an error parsing your request', + requiredParameter : 'Missing a required URL parameter: ', + statusMessage : 'Server gave an error: ', + timeout : 'Your request timed out' }
diff --git a/server/files/javascript/api.js b/server/files/javascript/api.js index 847d12e5c..8ee73c851 100755 --- a/server/files/javascript/api.js +++ b/server/files/javascript/api.js @@ -1,9 +1,10 @@ -/* Define API endpoints once globally */ $.fn.api.settings.debug = true; + /* Define API endpoints once globally */ $.fn.api.settings.api = { 'get followers' : '/followers/{id}?results={count}', + 'create user' : '/create', 'follow user' : '/follow/{id}', 'search' : '/search/?query={value}' }; @@ -31,6 +32,11 @@ semantic.api.ready = function() { server .respondWith(/\/search\/(.*)/, [responseCode, headers, body]) ; + + $('form .ui.dropdown') + .dropdown() + ; + }; diff --git a/server/files/javascript/library/serialize-object.js b/server/files/javascript/library/serialize-object.js new file mode 100644 index 000000000..c8b36c41b --- /dev/null +++ b/server/files/javascript/library/serialize-object.js @@ -0,0 +1,152 @@ +/** + * jQuery serializeObject + * @copyright 2014, macek + * @link https://github.com/macek/jquery-serialize-object + * @license BSD + * @version 2.4.3 + */ +(function(root, factory) { + + // AMD + if (typeof define === "function" && define.amd) { + define(["exports", "jquery"], function(exports, $) { + return factory(exports, $); + }); + } + + // CommonJS + else if (typeof exports !== "undefined") { + var $ = require("jquery"); + factory(exports, $); + } + + // Browser + else { + factory(root, (root.jQuery || root.Zepto || root.ender || root.$)); + } + +}(this, function(exports, $) { + + var patterns = { + validate: /^[a-z_][a-z0-9_]*(?:\[(?:\d*|[a-z0-9_]+)\])*$/i, + key: /[a-z0-9_]+|(?=\[\])/gi, + push: /^$/, + fixed: /^\d+$/, + named: /^[a-z0-9_]+$/i + }; + + function FormSerializer(helper, $form) { + + // private variables + var data = {}, + pushes = {}; + + // private API + function build(base, key, value) { + base[key] = value; + return base; + } + + function makeObject(root, value) { + + var keys = root.match(patterns.key), k; + + // nest, nest, ..., nest + while ((k = keys.pop()) !== undefined) { + // foo[] + if (patterns.push.test(k)) { + var idx = incrementPush(root.replace(/\[\]$/, '')); + value = build([], idx, value); + } + + // foo[n] + else if (patterns.fixed.test(k)) { + value = build([], k, value); + } + + // foo; foo[bar] + else if (patterns.named.test(k)) { + value = build({}, k, value); + } + } + + return value; + } + + function incrementPush(key) { + if (pushes[key] === undefined) { + pushes[key] = 0; + } + return pushes[key]++; + } + + function encode(pair) { + switch ($('[name="' + pair.name + '"]', $form).attr("type")) { + case "checkbox": + return pair.value === "on" ? true : pair.value; + default: + return pair.value; + } + } + + function addPair(pair) { + if (!patterns.validate.test(pair.name)) return this; + var obj = makeObject(pair.name, encode(pair)); + data = helper.extend(true, data, obj); + return this; + } + + function addPairs(pairs) { + if (!helper.isArray(pairs)) { + throw new Error("formSerializer.addPairs expects an Array"); + } + for (var i=0, len=pairs.length; i 1) { + return new Error("jquery-serialize-object can only serialize one form at a time"); + } + return new FormSerializer($, this). + addPairs(this.serializeArray()). + serialize(); + }; + + FormSerializer.serializeJSON = function serializeJSON() { + if (this.length > 1) { + return new Error("jquery-serialize-object can only serialize one form at a time"); + } + return new FormSerializer($, this). + addPairs(this.serializeArray()). + serializeJSON(); + }; + + if (typeof $.fn !== "undefined") { + $.fn.serializeObject = FormSerializer.serializeObject; + $.fn.serializeJSON = FormSerializer.serializeJSON; + } + + exports.FormSerializer = FormSerializer; + + return FormSerializer; +})); \ No newline at end of file diff --git a/server/files/stylesheets/semantic.css b/server/files/stylesheets/semantic.css index ce1f93bc3..91db41ddf 100755 --- a/server/files/stylesheets/semantic.css +++ b/server/files/stylesheets/semantic.css @@ -103,15 +103,13 @@ pre.console { } code { background-color: rgba(0, 0, 0, 0.02); - border-radius: 0.2em; box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.1); - color: rgba(0, 0, 0, 0.75); - font-weight: bold; display: inline-block; font-family: "Monaco","Menlo","Ubuntu Mono","Consolas","source-code-pro",monospace; - font-size: 14px; - margin: 0; - padding: 0.1em 0.4em; + font-size: 12px; + font-weight: bold; + margin: 0 2px 0px 0px; + padding: 2px 4px; vertical-align: baseline; } .ui.message code { @@ -122,12 +120,6 @@ pre code { border: none; padding: 0px; } -table pre, -table code { - margin: 0px !important; - padding: 0px; - background-color: transparent; -} p { margin: 1em 0em; } @@ -724,9 +716,12 @@ body#example.hide { position: relative; margin: 5rem 0rem 3rem; } +#example .main.container .examples > .rail + h2, +#example .main.container > .rail + h2, +#example .main.container > .tab > .rail + h2, #example .main.container .examples > h2:first-child, #example .main.container > h2:first-child, -#example .main.container > .tab > h2:first-child{ +#example .main.container > .tab > h2:first-child { margin-top: 0em; } #example .main.container .examples > h2 + p,