Contains UWA utils functions that is not part of the Core or Native Objects for manipulate String (URLs, Simple Cryptography), Array, and inject CSS styles.
Index
Members
- UWA.Utils.parseUrl
- UWA.Utils.loadXml
- UWA.Utils.loadHtml
- UWA.Utils.xmlToString
- UWA.Utils.setCss
- getUniqueId
- UWA.Utils.getCRC32
- UWA.Utils.clearImmediate
- UWA.Utils.setImmediate
Methods
- UWA.Utils.buildUrl
- UWA.Utils.composeUrl
- UWA.Utils.matchUrl
- UWA.Utils.isAbsoluteUrl
- UWA.Utils.isValidUrl
- UWA.Utils.encodeUrl
- UWA.Utils.parseQuery
- UWA.Utils.toQueryString
- UWA.Utils.getQueryString
- UWA.Utils.xmlToHtml
- UWA.Utils.toArray
- UWA.Utils.splat
- UWA.Utils.getUUID
- UWA.Utils.getCheckSum
- UWA.Utils.base64Encode
- UWA.Utils.base64Decode
- UWA.Utils.attempt
- UWA.Utils.memoize
- UWA.Utils.getOwnPropertyMatchName
- UWA.Utils.getOwnPropertyMatchValue
- UWA.Utils.clearImmediate
Members
-
<static> UWA.Utils.parseUrl
-
Parse an Url to extract uri parts (protocol, domain, ...). The URL should include the protocol (http://).
Example
UWA.Utils.parseUrl("http://me@example.com:80"); // will return {"source":"http://me@example.com:80","protocol":"http","authority":"me@example.com:80","domain":"me@example.com","port":"80",...}
-
<static> UWA.Utils.loadXml
-
Convert a String into an XML Document.
You can navigate into the document nodes using childNodes, attributes, nodeType, nodeName and nodeValue properties.
Example
UWA.Utils.loadXml( '<items title="titleAttribute">' + ' <item name="item1" foo="bar">item1TagValue</item>' + ' <item name="item2" foo="bar">item2TagValue</item>' + ' <label>label1TagValue</label>' + ' <label>label2TagValue</label>' + ' <title type="foo">titleTagValue</title>' + '</items>' ); // will return a Document object.
Example with xsl parameter:
var data = '<?xml version="1.0" encoding="utf-8"?>' + '<catalog>' + ' <cd>' + ' <title>Empire Burlesque</title>' + ' <artist>Bob Dylan</artist>' + ' <country>USA</country>' + ' <company>Columbia</company>' + ' <price>10.90</price>' + ' <year>1985</year>' + ' </cd>' + ' <cd>' + ' <title>Hide your heart</title> ' + ' <artist>Bonnie Tyler</artist> ' + ' <country>UK</country>' + ' <company>CBS Records</company> ' + ' <price>9.90</price>' + ' <year>1988</year>' + ' </cd>' + '</catalog>', template = '<?xml version="1.0" encoding="utf-8"?>' + '<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">' + '<xsl:template match="/">' + ' <div>' + ' <h2>My CD Collection</h2>' + ' <table width="100%">' + ' <tr bgcolor="#9acd32">' + ' <th>Title</th>' + ' <th>Artist</th>' + ' </tr>' + ' <xsl:for-each select="catalog/cd">' + ' <tr>' + ' <td><xsl:value-of select="title"/></td>' + ' <td><xsl:value-of select="artist"/></td>' + ' </tr>' + ' </xsl:for-each>' + ' </table>' + ' </div>' + '</xsl:template>' + '</xsl:stylesheet>'; UWA.Utils.loadXml(data, template); // will return a Document object.
-
<static> UWA.Utils.loadHtml
-
Convert a String into an HTML Document.
Notes: This function support also non XHTML markup (e.g <img> VS <img/>) You can navigate into the document nodes using childNodes, attributes, nodeType, nodeName and nodeValue properties. * following tags may ignored for security reason on old platform: script, embed, object, frameset, frame, iframe, meta, link, style.
-
<static> UWA.Utils.xmlToString
-
Convert a XML document into an indented XML string.
Example
UWA.Utils.xmlToString(UWA.Utils.loadXml( '<items title="titleAttribute">' + ' <item name="item1" foo="bar">item1TagValue</item>' + ' <item name="item2" foo="bar">item2TagValue</item>' + ' <label>label1TagValue</label>' + ' <label>label2TagValue</label>' + ' <title type="foo">titleTagValue</title>' + " <text><![CDATA[ Hello \r\n\t\r\n World! ]]></text>" + '</items>' )); // will return a String.
-
<static> UWA.Utils.setCss
-
Add a <styles> tag to current document with specific id.
Example
UWA.Utils.setCss("myStyle", "a.myClass { color: red; }", ".myNamespace"); // will insert: <style id="myStyle"> .myNamespace a.myClass { color: red; } </style> UWA.Utils.setCss("myStyle", "body a.myClass { color: red; }", ".myNamespace"); // will insert: <style id="myStyle">body .myNamespace a.myClass { color: red; } </style> UWA.Utils.setCss( "myStyle", ".firstClass ul>li, .secondClass { font: 1.1em/1.3em Tahoma, Bitstream Vera Sans, sans-serif;} .thirdClass {}", ".myNamespace" ); // will insert: <style id="myStyle"> .myNamespace .firstClass ul>li, .myNamespace .secondClass { font: 1.1em/1.3em Tahoma, Bitstream Vera Sans, sans-serif;} .myNamespace .thirdClass { }" </style> UWA.Utils.setCss("myStyle", "a.myClass { color: red; }"); // will insert with no namespace: <style id="myStyle"> a.myClass { color: red; } </style>
-
<static> getUniqueId
-
Return an id random enough to be considered unique. The generated id is suitable for use as an HTML id or classname.
Example
UWA.Utils.getUniqueId(); // could return "u3j9u0012"
-
<static> UWA.Utils.getCRC32
-
Get current CRC32 checksum of the string parameter.
Example
UWA.Utils.getCRC32('123456'); // will return "158520161"
-
<static> UWA.Utils.clearImmediate
-
Schedule a function to be executed very soon.
Example
// This is an infinite calculation that doesn't block the UI. findPrimes = function (currentNumber) { if (isPrime(currentNumber)) console.log(currentNumber); UWA.Utils.setImmediate(findPrimes.bind(null, currentNumber + 1)); }; findPrimes(1);
-
<static> UWA.Utils.setImmediate
-
Cancels an Immediate that hasn't executed yet.
Methods
-
<static> UWA.Utils.buildUrl(url, href) → {String}
-
Build an url from linkHref param in same context than widgetUrl param.
Example
UWA.Utils.buildUrl("http://example.org/mywidget.html", "/index.html"); // will return "http://example.org/index.html"
Parameters
Name Type Description url
String A full absolute url (e.g "http://example.org")
href
String Another url or simple file path (e.g. "/index.html")
Returns
A new url related to widgetUrl url absolute value.
- Type
- String
-
<static> UWA.Utils.composeUrl(parts) → {String}
-
Build an Url to from uri parts (protocol, domain, ...).
Example
UWA.Utils.composeUrl({ protocol: "https", subprotocol: "feed", authority: "example.org:8080", domain: "example.org", port: "8080", path: "/mypath/mywidget.html", directoryPath: "/mypath/", fileName: "mywidget.html", query: "lorem=ipsum&hello=world", anchor: "sit" }); // will return "feed:https://example.org:8080/mypath/mywidget.html?lorem=ipsum&hello=world#sit"
Parameters
Name Type Description parts
String An object with following properties: source, protocol, authority, domain, port, path, directoryPath, fileName, query, anchor
Returns
A valid url (e.g. "http://netvibes.com").
- Type
- String
-
<static> UWA.Utils.matchUrl(originaUrl, requestUrl) → {Boolean}
-
Compare two url to check if their domain, protocol and port match.
Example
// Following will return `true` UWA.Utils.matchUrl('http://example.com/mypath/index.html', '/mypath/index.html'); UWA.Utils.matchUrl('http://example.com/mypath/index.html', 'mypath/index.html'); UWA.Utils.matchUrl('http://example.com/mypath/index.html', 'http://example.com/index.html'); // Following will return `false` UWA.Utils.matchUrl('http://example.com/mypath/index.html', 'http://example.org/mypath/index.html'); UWA.Utils.matchUrl('http://example.com/mypath/index.html', 'https://example.com/mypath/index.html');
Parameters
Name Type Description originaUrl
String First url to compare
requestUrl
String Second url to compare
Returns
true
if urls match elsefalse
.- Type
- Boolean
-
<static> UWA.Utils.isAbsoluteUrl(url) → {Boolean}
-
Test if an URL is absolute.
Example
UWA.Utils.isAbsoluteUrl('http://foo.com'); // will return true UWA.Utils.isAbsoluteUrl('/foo'); // will return false
Parameters
Name Type Description url
String the url to check
Returns
true
if the URL is absolute.- Type
- Boolean
-
<static> UWA.Utils.isValidUrl(url) → {Boolean}
-
Test if an URL is valid.
Example
UWA.Utils.isValidUrl('http://foo.com'); // will return true UWA.Utils.isValidUrl('/foo'); // will return true UWA.Utils.isValidUrl('//foo'); // will return false
Parameters
Name Type Description url
String the url to check
Returns
true
if the URL is valid.- Type
- Boolean
-
<static> UWA.Utils.encodeUrl(str) → {String}
-
Simple encodeURIComponent wrapper to escape "." to "%2e" also.
Example
UWA.Utils.encodeUrl("hello?/e;&."); // will return "hello%3F%2Fe%3B%26%2e"
Parameters
Name Type Description str
String String to encode
Returns
Encoded string.
- Type
- String
-
<static> UWA.Utils.parseQuery(queryString) → {Object}
-
Decode an url string query string to an Object.
Example
UWA.Utils.parseQuery('?example=1&array[0]=hello&array[1]=world'); // will return {"example":"1","array":{"0":"hello","1":"world"}}"
Parameters
Name Type Description queryString
String Query string to decode
Returns
Decoded query string indexed by query param key.
- Type
- Object
-
<static> UWA.Utils.toQueryString(myObject, base) → {String}
-
Encode an Object to a url string.
Example
UWA.Utils.toQueryString({ example: 1, array: ['hello', 'world'], object: {key: 'value'} }); // will return "example=1&array[0]=hello&array[1]=world" UWA.Utils.toQueryString({ toQueryString: function () { return 'hello' } }); // will return "hello"
Parameters
Name Type Description myObject
Object Object to encode
base
Object Sub object to encode
Returns
Encoded string.
- Type
- String
-
<static> UWA.Utils.getQueryString(query, key, Fallback) → {Void}
-
Get GET param value from a query string.
Example
UWA.Utils.getQueryString('example=hello', 'example'); // will return "hello" UWA.Utils.getQueryString('http://example.com?example=hello', 'example'); // will return "hello" UWA.Utils.getQueryString('http://example.com?example=hello', 'status'); // will return undefined UWA.Utils.getQueryString('http://example.com?example=hello', 'status', 'bye'); // will return 'bye'
Parameters
Name Type Description query
Object Query to use as source
key
Object GET param key
Fallback
Object default value if missing
Returns
GET param value if available else fallback parameter value.
- Type
- Void
-
<static> UWA.Utils.xmlToHtml(string) → {Element}
-
Convert an XML document into DOM elements tree.
Example
UWA.Utils.xmlToHtml( '<items title="titleAttribute">' + ' <item name="item1" foo="bar">item1TagValue</item>' + ' <item name="item2" foo="bar">item2TagValue</item>' + ' <label>label1TagValue</label>' + ' <label>label2TagValue</label>' + ' <title type="foo">titleTagValue</title>' + '</items>' ); // will return a Element object.
Parameters
Name Type Description string
String | Document XML String source or Document instance result from UWA.Data.getXML or UWA.Utils.loadXml.
Returns
Root node that result of XML to XHTML conversion.
- Type
- Element
-
<static> UWA.Utils.toArray(iterable) → {Array}
-
Convert an object to an Array.
Example
UWA.Utils.toArray(widget.body.getElementsByClassName('item'));
Parameters
Name Type Description iterable
Void Variable need to be an iterable object
Returns
Same array than param if array param is an array else an array with array param has value.
- Type
- Array
-
<static> UWA.Utils.splat(object) → {Array}
-
Converts the argument passed in to an array if it is defined and not already an array.
Example
var myBadArray = "abc"; UWA.Utils.splat(myBadArray); // will return ["abc"]
Parameters
Name Type Description object
String Variable need to be cast has array
Returns
Same array than param if array param is an array else an array with array param has value.
- Type
- Array
-
<static> UWA.Utils.getUUID() → {String}
-
Return a Universally Unique IDentifier (UUID) URN Namespace based on RFC 4122, section 4.4 (Algorithms for Creating a UUID from Truly Random or Pseudo-Random Number).
Example
UWA.Utils.uuid(); // will return "f8572d53-0fc5-43f2-bb1f-19eb1395d2ba"
Returns
an UUID string (e.g: xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx).
- Type
- String
-
<static> UWA.Utils.getCheckSum(string, salt) → {String}
-
Get current checksum of the string parameter.
Example
UWA.Utils.getCheckSum('hello my name is bob!'); // will return "51ul56" UWA.Utils.getCheckSum('hello my name is bob!', 0x666666); // will return "407so"
Parameters
Name Type Description string
String String to checksum
salt
Number Checksum salt (default: 0x12345678)
Returns
String checksum.
- Type
- String
-
<static> UWA.Utils.base64Encode(str) → {String}
-
Creates a base-64 encoded ASCII string from a "string" of binary data. This btoa method support Unicode compare to the native window.btoa.
Examples
UWA.Utils.base64Encode('✓ à la mode'); // will return "4pyTIMOgIGxhIG1vZGU="
window.btoa('✓ à la mode'); // Error: InvalidCharacterError: DOM Exception 5
Parameters
Name Type Description str
String String to encode
Returns
Base-64 for string passed as argument.
- Type
- String
-
<static> UWA.Utils.base64Decode(str) → {String}
-
Decodes a string of data which has been encoded using base-64 encoding. This atob method support Unicode compare to the native window.atob.
Examples
UWA.Utils.base64Decode('4pyTIMOgIGxhIG1vZGU='); // will return "✓ à la mode"
window.atob('4pyTIMOgIGxhIG1vZGU='); // will return "â Ã la mode"
Parameters
Name Type Description str
String Base-64 string to decode
Returns
Decoded base-64 string for passed argument.
- Type
- String
-
<static> UWA.Utils.attempt(func, fail, context)
-
Safely execute a function who can throw an exception. If UWA is in debug mode (UWA.debug is
true
), it runs the function and do NOT catch any exception, so it can easily be debugged with a browser developper console. Else, the exception will be catched and the 'fail' callback will be executed with the error as first argument.Prefer using this method to run critical foreign functions instead of try / catches, as it is simpler to debug.
Extra arguments are passed to func and fail functions.
Example
function userDefinedFunction(foo) { foo.bar = 42; return 32; } UWA.Utils.attempt(userDefinedFunction, function (error, foo) { // Deal with the error UWA.log('Calling userDefinedFunction with ' + foo + ' as first argument has failed unexpectedly:' + error); return 21; }, {}, null); // Will return 21 and log the error message
Parameters
Name Type Argument Description func
Function The function to execute
fail
Function <optional>
A callback to execute if the function fails, with the error as first argument and the other arguments afterward.
context
Object <optional>
Passed as context to func and fail functions
Returns
The result of func or fail
-
<static> UWA.Utils.memoize(func, serializer) → {Function}
-
Decorator around functions that cache the inner function's return values. Its return value may only depend on its arguments and 'this' context.
There may be further restrictions on the arguments depending on the capabilities of the serializer used.
Example
var nbFunctionCall = 0, myFunction = function () { // Your heavy javascript computation return nbFunctionCall += 1; }, myFunctionCache = UWA.Utils.memoize(myFunction); myFunctionCache(1); // will return 1 myFunctionCache(2); // will return 2 myFunctionCache(1); // will return 1
Parameters
Name Type Description func
Function serializer
Object A function to serialize function's arguments. By default serializer is
JSON.stringify
.Returns
The wrapped function.
- Type
- Function
-
<static> UWA.Utils.getOwnPropertyMatchName(obj, property) → {String}
-
Get the first property name of an object that match using an case insensitive property name.
Example
o = new Object(); o.prop = 'exists'; UWA.Utils.getOwnPropertyMatchName(o, 'Prop'); // returns "prop" UWA.Utils.getOwnPropertyMatchName(o, 'PROP'); // returns "prop" UWA.Utils.getOwnPropertyMatchName(o, 'prop'); // returns "prop"
Parameters
Name Type Description obj
Object The object whose tested.
property
String The name of the property to test.
Returns
the real property name.
- Type
- String
-
<static> UWA.Utils.getOwnPropertyMatchValue(obj, property) → {String}
-
Get the first property value of an object that match using an case insensitive property name.
Example
o = new Object(); o.prop = 'exists'; UWA.Utils.getOwnPropertyMatchValue(o, 'Prop'); // returns "exists" UWA.Utils.getOwnPropertyMatchValue(o, 'PROP'); // returns "exists" UWA.Utils.getOwnPropertyMatchValue(o, 'prop'); // returns "exists"
Parameters
Name Type Description obj
Object The object whose tested.
property
String The name of the property to test.
Returns
the real property value.
- Type
- String
-
<static> UWA.Utils.clearImmediate(min, max) → {Number}
-
Produces a random integer between
min
andmax
(inclusive). If only one argument is provided a number between0
and the given integer is returned.Example
UWA.Utils.random(0, 5); // returns an integer between 0 and 5 inclusive UWA.Utils.random(5); // also returns an integer between 0 and 5 inclusive
Parameters
Name Type Description min
Number The minimum possible value.
max
Number The maximum possible value.
Returns
Returns the random number.
- Type
- Number