Commit a0e2a30a authored by Romain Courteaud's avatar Romain Courteaud

Release version 0.7.0

Drop EventTarget support on Gadget.
Add declareAcquiredMethod, allowPublicAcquisition.
Prefix attribute non part of the API by __. Such method/property can be rename
in next versions without any compatibility support.
Use base element in iframe to get the same link behaviour with or without
iframe.
parent 81140f2f
/*
* js_channel is a very lightweight abstraction on top of
* postMessage which defines message formats and semantics
* to support interactions more rich than just message passing
* js_channel supports:
* + query/response - traditional rpc
* + query/update/response - incremental async return of results
* to a query
* + notifications - fire and forget
* + error handling
*
* js_channel is based heavily on json-rpc, but is focused at the
* problem of inter-iframe RPC.
*
* Message types:
* There are 5 types of messages that can flow over this channel,
* and you may determine what type of message an object is by
* examining its parameters:
* 1. Requests
* + integer id
* + string method
* + (optional) any params
* 2. Callback Invocations (or just "Callbacks")
* + integer id
* + string callback
* + (optional) params
* 3. Error Responses (or just "Errors)
* + integer id
* + string error
* + (optional) string message
* 4. Responses
* + integer id
* + (optional) any result
* 5. Notifications
* + string method
* + (optional) any params
*/
;var Channel = (function() {
"use strict";
// current transaction id, start out at a random *odd* number between 1 and a million
// There is one current transaction counter id per page, and it's shared between
// channel instances. That means of all messages posted from a single javascript
// evaluation context, we'll never have two with the same id.
var s_curTranId = Math.floor(Math.random()*1000001);
// no two bound channels in the same javascript evaluation context may have the same origin, scope, and window.
// futher if two bound channels have the same window and scope, they may not have *overlapping* origins
// (either one or both support '*'). This restriction allows a single onMessage handler to efficiently
// route messages based on origin and scope. The s_boundChans maps origins to scopes, to message
// handlers. Request and Notification messages are routed using this table.
// Finally, channels are inserted into this table when built, and removed when destroyed.
var s_boundChans = { };
// add a channel to s_boundChans, throwing if a dup exists
function s_addBoundChan(win, origin, scope, handler) {
function hasWin(arr) {
for (var i = 0; i < arr.length; i++) if (arr[i].win === win) return true;
return false;
}
// does she exist?
var exists = false;
if (origin === '*') {
// we must check all other origins, sadly.
for (var k in s_boundChans) {
if (!s_boundChans.hasOwnProperty(k)) continue;
if (k === '*') continue;
if (typeof s_boundChans[k][scope] === 'object') {
exists = hasWin(s_boundChans[k][scope]);
if (exists) break;
}
}
} else {
// we must check only '*'
if ((s_boundChans['*'] && s_boundChans['*'][scope])) {
exists = hasWin(s_boundChans['*'][scope]);
}
if (!exists && s_boundChans[origin] && s_boundChans[origin][scope])
{
exists = hasWin(s_boundChans[origin][scope]);
}
}
if (exists) throw "A channel is already bound to the same window which overlaps with origin '"+ origin +"' and has scope '"+scope+"'";
if (typeof s_boundChans[origin] != 'object') s_boundChans[origin] = { };
if (typeof s_boundChans[origin][scope] != 'object') s_boundChans[origin][scope] = [ ];
s_boundChans[origin][scope].push({win: win, handler: handler});
}
function s_removeBoundChan(win, origin, scope) {
var arr = s_boundChans[origin][scope];
for (var i = 0; i < arr.length; i++) {
if (arr[i].win === win) {
arr.splice(i,1);
}
}
if (s_boundChans[origin][scope].length === 0) {
delete s_boundChans[origin][scope];
}
}
function s_isArray(obj) {
if (Array.isArray) return Array.isArray(obj);
else {
return (obj.constructor.toString().indexOf("Array") != -1);
}
}
// No two outstanding outbound messages may have the same id, period. Given that, a single table
// mapping "transaction ids" to message handlers, allows efficient routing of Callback, Error, and
// Response messages. Entries are added to this table when requests are sent, and removed when
// responses are received.
var s_transIds = { };
// class singleton onMessage handler
// this function is registered once and all incoming messages route through here. This
// arrangement allows certain efficiencies, message data is only parsed once and dispatch
// is more efficient, especially for large numbers of simultaneous channels.
var s_onMessage = function(e) {
try {
var m = JSON.parse(e.data);
if (typeof m !== 'object' || m === null) throw "malformed";
} catch(e) {
// just ignore any posted messages that do not consist of valid JSON
return;
}
var w = e.source;
var o = e.origin;
var s, i, meth;
if (typeof m.method === 'string') {
var ar = m.method.split('::');
if (ar.length == 2) {
s = ar[0];
meth = ar[1];
} else {
meth = m.method;
}
}
if (typeof m.id !== 'undefined') i = m.id;
// w is message source window
// o is message origin
// m is parsed message
// s is message scope
// i is message id (or undefined)
// meth is unscoped method name
// ^^ based on these factors we can route the message
// if it has a method it's either a notification or a request,
// route using s_boundChans
if (typeof meth === 'string') {
var delivered = false;
if (s_boundChans[o] && s_boundChans[o][s]) {
for (var j = 0; j < s_boundChans[o][s].length; j++) {
if (s_boundChans[o][s][j].win === w) {
s_boundChans[o][s][j].handler(o, meth, m);
delivered = true;
break;
}
}
}
if (!delivered && s_boundChans['*'] && s_boundChans['*'][s]) {
for (var j = 0; j < s_boundChans['*'][s].length; j++) {
if (s_boundChans['*'][s][j].win === w) {
s_boundChans['*'][s][j].handler(o, meth, m);
break;
}
}
}
}
// otherwise it must have an id (or be poorly formed
else if (typeof i != 'undefined') {
if (s_transIds[i]) s_transIds[i](o, meth, m);
}
};
// Setup postMessage event listeners
if (window.addEventListener) window.addEventListener('message', s_onMessage, false);
else if(window.attachEvent) window.attachEvent('onmessage', s_onMessage);
/* a messaging channel is constructed from a window and an origin.
* the channel will assert that all messages received over the
* channel match the origin
*
* Arguments to Channel.build(cfg):
*
* cfg.window - the remote window with which we'll communicate
* cfg.origin - the expected origin of the remote window, may be '*'
* which matches any origin
* cfg.scope - the 'scope' of messages. a scope string that is
* prepended to message names. local and remote endpoints
* of a single channel must agree upon scope. Scope may
* not contain double colons ('::').
* cfg.debugOutput - A boolean value. If true and window.console.log is
* a function, then debug strings will be emitted to that
* function.
* cfg.debugOutput - A boolean value. If true and window.console.log is
* a function, then debug strings will be emitted to that
* function.
* cfg.postMessageObserver - A function that will be passed two arguments,
* an origin and a message. It will be passed these immediately
* before messages are posted.
* cfg.gotMessageObserver - A function that will be passed two arguments,
* an origin and a message. It will be passed these arguments
* immediately after they pass scope and origin checks, but before
* they are processed.
* cfg.onReady - A function that will be invoked when a channel becomes "ready",
* this occurs once both sides of the channel have been
* instantiated and an application level handshake is exchanged.
* the onReady function will be passed a single argument which is
* the channel object that was returned from build().
*/
return {
build: function(cfg) {
var debug = function(m) {
if (cfg.debugOutput && window.console && window.console.log) {
// try to stringify, if it doesn't work we'll let javascript's built in toString do its magic
try { if (typeof m !== 'string') m = JSON.stringify(m); } catch(e) { }
console.log("["+chanId+"] " + m);
}
};
/* browser capabilities check */
if (!window.postMessage) throw("jschannel cannot run this browser, no postMessage");
if (!window.JSON || !window.JSON.stringify || ! window.JSON.parse) {
throw("jschannel cannot run this browser, no JSON parsing/serialization");
}
/* basic argument validation */
if (typeof cfg != 'object') throw("Channel build invoked without a proper object argument");
if (!cfg.window || !cfg.window.postMessage) throw("Channel.build() called without a valid window argument");
/* we'd have to do a little more work to be able to run multiple channels that intercommunicate the same
* window... Not sure if we care to support that */
if (window === cfg.window) throw("target window is same as present window -- not allowed");
// let's require that the client specify an origin. if we just assume '*' we'll be
// propagating unsafe practices. that would be lame.
var validOrigin = false;
if (typeof cfg.origin === 'string') {
var oMatch;
if (cfg.origin === "*") validOrigin = true;
// allow valid domains under http and https. Also, trim paths off otherwise valid origins.
else if (null !== (oMatch = cfg.origin.match(/^https?:\/\/(?:[-a-zA-Z0-9_\.])+(?::\d+)?/))) {
cfg.origin = oMatch[0].toLowerCase();
validOrigin = true;
}
}
if (!validOrigin) throw ("Channel.build() called with an invalid origin");
if (typeof cfg.scope !== 'undefined') {
if (typeof cfg.scope !== 'string') throw 'scope, when specified, must be a string';
if (cfg.scope.split('::').length > 1) throw "scope may not contain double colons: '::'";
}
/* private variables */
// generate a random and psuedo unique id for this channel
var chanId = (function () {
var text = "";
var alpha = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
for(var i=0; i < 5; i++) text += alpha.charAt(Math.floor(Math.random() * alpha.length));
return text;
})();
// registrations: mapping method names to call objects
var regTbl = { };
// current oustanding sent requests
var outTbl = { };
// current oustanding received requests
var inTbl = { };
// are we ready yet? when false we will block outbound messages.
var ready = false;
var pendingQueue = [ ];
var createTransaction = function(id,origin,callbacks) {
var shouldDelayReturn = false;
var completed = false;
return {
origin: origin,
invoke: function(cbName, v) {
// verify in table
if (!inTbl[id]) throw "attempting to invoke a callback of a nonexistent transaction: " + id;
// verify that the callback name is valid
var valid = false;
for (var i = 0; i < callbacks.length; i++) if (cbName === callbacks[i]) { valid = true; break; }
if (!valid) throw "request supports no such callback '" + cbName + "'";
// send callback invocation
postMessage({ id: id, callback: cbName, params: v});
},
error: function(error, message) {
completed = true;
// verify in table
if (!inTbl[id]) throw "error called for nonexistent message: " + id;
// remove transaction from table
delete inTbl[id];
// send error
postMessage({ id: id, error: error, message: message });
},
complete: function(v) {
completed = true;
// verify in table
if (!inTbl[id]) throw "complete called for nonexistent message: " + id;
// remove transaction from table
delete inTbl[id];
// send complete
postMessage({ id: id, result: v });
},
delayReturn: function(delay) {
if (typeof delay === 'boolean') {
shouldDelayReturn = (delay === true);
}
return shouldDelayReturn;
},
completed: function() {
return completed;
}
};
};
var setTransactionTimeout = function(transId, timeout, method) {
return window.setTimeout(function() {
if (outTbl[transId]) {
// XXX: what if client code raises an exception here?
var msg = "timeout (" + timeout + "ms) exceeded on method '" + method + "'";
(1,outTbl[transId].error)("timeout_error", msg);
delete outTbl[transId];
delete s_transIds[transId];
}
}, timeout);
};
var onMessage = function(origin, method, m) {
// if an observer was specified at allocation time, invoke it
if (typeof cfg.gotMessageObserver === 'function') {
// pass observer a clone of the object so that our
// manipulations are not visible (i.e. method unscoping).
// This is not particularly efficient, but then we expect
// that message observers are primarily for debugging anyway.
try {
cfg.gotMessageObserver(origin, m);
} catch (e) {
debug("gotMessageObserver() raised an exception: " + e.toString());
}
}
// now, what type of message is this?
if (m.id && method) {
// a request! do we have a registered handler for this request?
if (regTbl[method]) {
var trans = createTransaction(m.id, origin, m.callbacks ? m.callbacks : [ ]);
inTbl[m.id] = { };
try {
// callback handling. we'll magically create functions inside the parameter list for each
// callback
if (m.callbacks && s_isArray(m.callbacks) && m.callbacks.length > 0) {
for (var i = 0; i < m.callbacks.length; i++) {
var path = m.callbacks[i];
var obj = m.params;
var pathItems = path.split('/');
for (var j = 0; j < pathItems.length - 1; j++) {
var cp = pathItems[j];
if (typeof obj[cp] !== 'object') obj[cp] = { };
obj = obj[cp];
}
obj[pathItems[pathItems.length - 1]] = (function() {
var cbName = path;
return function(params) {
return trans.invoke(cbName, params);
};
})();
}
}
var resp = regTbl[method](trans, m.params);
if (!trans.delayReturn() && !trans.completed()) trans.complete(resp);
} catch(e) {
// automagic handling of exceptions:
var error = "runtime_error";
var message = null;
// * if it's a string then it gets an error code of 'runtime_error' and string is the message
if (typeof e === 'string') {
message = e;
} else if (typeof e === 'object') {
// either an array or an object
// * if it's an array of length two, then array[0] is the code, array[1] is the error message
if (e && s_isArray(e) && e.length == 2) {
error = e[0];
message = e[1];
}
// * if it's an object then we'll look form error and message parameters
else if (typeof e.error === 'string') {
error = e.error;
if (!e.message) message = "";
else if (typeof e.message === 'string') message = e.message;
else e = e.message; // let the stringify/toString message give us a reasonable verbose error string
}
}
// message is *still* null, let's try harder
if (message === null) {
try {
message = JSON.stringify(e);
/* On MSIE8, this can result in 'out of memory', which
* leaves message undefined. */
if (typeof(message) == 'undefined')
message = e.toString();
} catch (e2) {
message = e.toString();
}
}
trans.error(error,message);
}
}
} else if (m.id && m.callback) {
if (!outTbl[m.id] ||!outTbl[m.id].callbacks || !outTbl[m.id].callbacks[m.callback])
{
debug("ignoring invalid callback, id:"+m.id+ " (" + m.callback +")");
} else {
// XXX: what if client code raises an exception here?
outTbl[m.id].callbacks[m.callback](m.params);
}
} else if (m.id) {
if (!outTbl[m.id]) {
debug("ignoring invalid response: " + m.id);
} else {
// XXX: what if client code raises an exception here?
if (m.error) {
(1,outTbl[m.id].error)(m.error, m.message);
} else {
if (m.result !== undefined) (1,outTbl[m.id].success)(m.result);
else (1,outTbl[m.id].success)();
}
delete outTbl[m.id];
delete s_transIds[m.id];
}
} else if (method) {
// tis a notification.
if (regTbl[method]) {
// yep, there's a handler for that.
// transaction has only origin for notifications.
regTbl[method]({ origin: origin }, m.params);
// if the client throws, we'll just let it bubble out
// what can we do? Also, here we'll ignore return values
}
}
};
// now register our bound channel for msg routing
s_addBoundChan(cfg.window, cfg.origin, ((typeof cfg.scope === 'string') ? cfg.scope : ''), onMessage);
// scope method names based on cfg.scope specified when the Channel was instantiated
var scopeMethod = function(m) {
if (typeof cfg.scope === 'string' && cfg.scope.length) m = [cfg.scope, m].join("::");
return m;
};
// a small wrapper around postmessage whose primary function is to handle the
// case that clients start sending messages before the other end is "ready"
var postMessage = function(msg, force) {
if (!msg) throw "postMessage called with null message";
// delay posting if we're not ready yet.
var verb = (ready ? "post " : "queue ");
debug(verb + " message: " + JSON.stringify(msg));
if (!force && !ready) {
pendingQueue.push(msg);
} else {
if (typeof cfg.postMessageObserver === 'function') {
try {
cfg.postMessageObserver(cfg.origin, msg);
} catch (e) {
debug("postMessageObserver() raised an exception: " + e.toString());
}
}
cfg.window.postMessage(JSON.stringify(msg), cfg.origin);
}
};
var onReady = function(trans, type) {
debug('ready msg received');
if (ready) throw "received ready message while in ready state. help!";
if (type === 'ping') {
chanId += '-R';
} else {
chanId += '-L';
}
obj.unbind('__ready'); // now this handler isn't needed any more.
ready = true;
debug('ready msg accepted.');
if (type === 'ping') {
obj.notify({ method: '__ready', params: 'pong' });
}
// flush queue
while (pendingQueue.length) {
postMessage(pendingQueue.pop());
}
// invoke onReady observer if provided
if (typeof cfg.onReady === 'function') cfg.onReady(obj);
};
var obj = {
// tries to unbind a bound message handler. returns false if not possible
unbind: function (method) {
if (regTbl[method]) {
if (!(delete regTbl[method])) throw ("can't delete method: " + method);
return true;
}
return false;
},
bind: function (method, cb) {
if (!method || typeof method !== 'string') throw "'method' argument to bind must be string";
if (!cb || typeof cb !== 'function') throw "callback missing from bind params";
if (regTbl[method]) throw "method '"+method+"' is already bound!";
regTbl[method] = cb;
return this;
},
call: function(m) {
if (!m) throw 'missing arguments to call function';
if (!m.method || typeof m.method !== 'string') throw "'method' argument to call must be string";
if (!m.success || typeof m.success !== 'function') throw "'success' callback missing from call";
// now it's time to support the 'callback' feature of jschannel. We'll traverse the argument
// object and pick out all of the functions that were passed as arguments.
var callbacks = { };
var callbackNames = [ ];
var pruneFunctions = function (path, obj) {
if (typeof obj === 'object') {
for (var k in obj) {
if (!obj.hasOwnProperty(k)) continue;
var np = path + (path.length ? '/' : '') + k;
if (typeof obj[k] === 'function') {
callbacks[np] = obj[k];
callbackNames.push(np);
delete obj[k];
} else if (typeof obj[k] === 'object') {
pruneFunctions(np, obj[k]);
}
}
}
};
pruneFunctions("", m.params);
// build a 'request' message and send it
var msg = { id: s_curTranId, method: scopeMethod(m.method), params: m.params };
if (callbackNames.length) msg.callbacks = callbackNames;
if (m.timeout)
// XXX: This function returns a timeout ID, but we don't do anything with it.
// We might want to keep track of it so we can cancel it using clearTimeout()
// when the transaction completes.
setTransactionTimeout(s_curTranId, m.timeout, scopeMethod(m.method));
// insert into the transaction table
outTbl[s_curTranId] = { callbacks: callbacks, error: m.error, success: m.success };
s_transIds[s_curTranId] = onMessage;
// increment current id
s_curTranId++;
postMessage(msg);
},
notify: function(m) {
if (!m) throw 'missing arguments to notify function';
if (!m.method || typeof m.method !== 'string') throw "'method' argument to notify must be string";
// no need to go into any transaction table
postMessage({ method: scopeMethod(m.method), params: m.params });
},
destroy: function () {
s_removeBoundChan(cfg.window, cfg.origin, ((typeof cfg.scope === 'string') ? cfg.scope : ''));
if (window.removeEventListener) window.removeEventListener('message', onMessage, false);
else if(window.detachEvent) window.detachEvent('onmessage', onMessage);
ready = false;
regTbl = { };
inTbl = { };
outTbl = { };
cfg.origin = null;
pendingQueue = [ ];
debug("channel destroyed");
chanId = "";
}
};
obj.bind('__ready', onReady);
setTimeout(function() {
postMessage({ method: scopeMethod('__ready'), params: "ping" }, true);
}, 0);
return obj;
}
};
})();
;/*
* DOMParser HTML extension
* 2012-09-04
*
* By Eli Grey, http://eligrey.com
* Public domain.
* NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
*/
/*! @source https://gist.github.com/1129031 */
(function (DOMParser) {
"use strict";
var DOMParser_proto = DOMParser.prototype,
real_parseFromString = DOMParser_proto.parseFromString;
// Firefox/Opera/IE throw errors on unsupported types
try {
// WebKit returns null on unsupported types
if ((new DOMParser()).parseFromString("", "text/html")) {
// text/html parsing is natively supported
return;
}
} catch (ignore) {}
DOMParser_proto.parseFromString = function (markup, type) {
var result, doc, doc_elt, first_elt;
if (/^\s*text\/html\s*(?:;|$)/i.test(type)) {
doc = document.implementation.createHTMLDocument("");
doc_elt = doc.documentElement;
doc_elt.innerHTML = markup;
first_elt = doc_elt.firstElementChild;
if (doc_elt.childElementCount === 1
&& first_elt.localName.toLowerCase() === "html") {
doc.replaceChild(first_elt, doc_elt);
}
result = doc;
} else {
result = real_parseFromString.apply(this, arguments);
}
return result;
};
}(DOMParser));
;/*! RenderJs */
/*jslint nomen: true*/
/*
* renderJs - Generic Gadget library renderer.
* http://www.renderjs.org/documentation
*/
(function (document, window, RSVP, DOMParser, Channel, undefined) {
"use strict";
var gadget_model_dict = {},
javascript_registration_dict = {},
stylesheet_registration_dict = {},
gadget_loading_klass,
loading_gadget_promise,
renderJS;
function removeHash(url) {
var index = url.indexOf('#');
if (index > 0) {
url = url.substring(0, index);
}
return url;
}
/////////////////////////////////////////////////////////////////
// RenderJSGadget
/////////////////////////////////////////////////////////////////
function RenderJSGadget() {
if (!(this instanceof RenderJSGadget)) {
return new RenderJSGadget();
}
}
RenderJSGadget.prototype.__title = "";
RenderJSGadget.prototype.__interface_list = [];
RenderJSGadget.prototype.__path = "";
RenderJSGadget.prototype.__html = "";
RenderJSGadget.prototype.__required_css_list = [];
RenderJSGadget.prototype.__required_js_list = [];
function clearGadgetInternalParameters(g) {
g.__sub_gadget_dict = {};
}
RenderJSGadget.__ready_list = [clearGadgetInternalParameters];
RenderJSGadget.ready = function (callback) {
this.__ready_list.push(callback);
return this;
};
/////////////////////////////////////////////////////////////////
// RenderJSGadget.declareMethod
/////////////////////////////////////////////////////////////////
RenderJSGadget.declareMethod = function (name, callback) {
this.prototype[name] = function () {
var context = this,
argument_list = arguments;
return new RSVP.Queue()
.push(function () {
return callback.apply(context, argument_list);
});
};
// Allow chain
return this;
};
RenderJSGadget
.declareMethod('getInterfaceList', function () {
// Returns the list of gadget prototype
return this.__interface_list;
})
.declareMethod('getRequiredCSSList', function () {
// Returns a list of CSS required by the gadget
return this.__required_css_list;
})
.declareMethod('getRequiredJSList', function () {
// Returns a list of JS required by the gadget
return this.__required_js_list;
})
.declareMethod('getPath', function () {
// Returns the path of the code of a gadget
return this.__path;
})
.declareMethod('getTitle', function () {
// Returns the title of a gadget
return this.__title;
})
.declareMethod('getElement', function () {
// Returns the DOM Element of a gadget
if (this.__element === undefined) {
throw new Error("No element defined");
}
return this.__element;
});
/////////////////////////////////////////////////////////////////
// RenderJSGadget.declareAcquiredMethod
/////////////////////////////////////////////////////////////////
function acquire(child_gadget, method_name, argument_list) {
var gadget = this,
key,
gadget_scope;
for (key in gadget.__sub_gadget_dict) {
if (gadget.__sub_gadget_dict.hasOwnProperty(key)) {
if (gadget.__sub_gadget_dict[key] === child_gadget) {
gadget_scope = key;
}
}
}
return new RSVP.Queue()
.push(function () {
// Do not specify default __acquired_method_dict on prototype
// to prevent modifying this default value (with
// allowPublicAcquiredMethod for example)
var aq_dict = gadget.__acquired_method_dict || {};
if (aq_dict.hasOwnProperty(method_name)) {
return aq_dict[method_name].apply(gadget,
[argument_list, gadget_scope]);
}
throw new renderJS.AcquisitionError("aq_dynamic is not defined");
})
.push(undefined, function (error) {
if (error instanceof renderJS.AcquisitionError) {
return gadget.__aq_parent(method_name, argument_list);
}
throw error;
});
}
RenderJSGadget.declareAcquiredMethod =
function (name, method_name_to_acquire) {
this.prototype[name] = function () {
var argument_list = Array.prototype.slice.call(arguments, 0),
gadget = this;
return new RSVP.Queue()
.push(function () {
return gadget.__aq_parent(method_name_to_acquire, argument_list);
});
};
// Allow chain
return this;
};
/////////////////////////////////////////////////////////////////
// RenderJSGadget.allowPublicAcquisition
/////////////////////////////////////////////////////////////////
RenderJSGadget.allowPublicAcquisition =
function (method_name, callback) {
this.prototype.__acquired_method_dict[method_name] = callback;
// Allow chain
return this;
};
// Set aq_parent on gadget_instance which call acquire on parent_gadget
function setAqParent(gadget_instance, parent_gadget) {
gadget_instance.__aq_parent = function (method_name, argument_list) {
return acquire.apply(parent_gadget, [gadget_instance, method_name,
argument_list]);
};
}
/////////////////////////////////////////////////////////////////
// RenderJSEmbeddedGadget
/////////////////////////////////////////////////////////////////
// Class inheritance
function RenderJSEmbeddedGadget() {
if (!(this instanceof RenderJSEmbeddedGadget)) {
return new RenderJSEmbeddedGadget();
}
RenderJSGadget.call(this);
}
RenderJSEmbeddedGadget.__ready_list = RenderJSGadget.__ready_list.slice();
RenderJSEmbeddedGadget.ready =
RenderJSGadget.ready;
RenderJSEmbeddedGadget.prototype = new RenderJSGadget();
RenderJSEmbeddedGadget.prototype.constructor = RenderJSEmbeddedGadget;
/////////////////////////////////////////////////////////////////
// privateDeclarePublicGadget
/////////////////////////////////////////////////////////////////
function privateDeclarePublicGadget(url, options, parent_gadget) {
var gadget_instance;
if (options.element === undefined) {
options.element = document.createElement("div");
}
function loadDependency(method, url) {
return function () {
return method(url);
};
}
return new RSVP.Queue()
.push(function () {
return renderJS.declareGadgetKlass(url);
})
// Get the gadget class and instanciate it
.push(function (Klass) {
var i,
template_node_list = Klass.__template_element.body.childNodes;
gadget_loading_klass = Klass;
gadget_instance = new Klass();
gadget_instance.__element = options.element;
for (i = 0; i < template_node_list.length; i += 1) {
gadget_instance.__element.appendChild(
template_node_list[i].cloneNode(true)
);
}
setAqParent(gadget_instance, parent_gadget);
// Load dependencies if needed
return RSVP.all([
gadget_instance.getRequiredJSList(),
gadget_instance.getRequiredCSSList()
]);
})
// Load all JS/CSS
.push(function (all_list) {
var q = new RSVP.Queue(),
i;
// Load JS
for (i = 0; i < all_list[0].length; i += 1) {
q.push(loadDependency(renderJS.declareJS, all_list[0][i]));
}
// Load CSS
for (i = 0; i < all_list[1].length; i += 1) {
q.push(loadDependency(renderJS.declareCSS, all_list[1][i]));
}
return q;
})
.push(function () {
return gadget_instance;
});
}
/////////////////////////////////////////////////////////////////
// RenderJSIframeGadget
/////////////////////////////////////////////////////////////////
function RenderJSIframeGadget() {
if (!(this instanceof RenderJSIframeGadget)) {
return new RenderJSIframeGadget();
}
RenderJSGadget.call(this);
}
RenderJSIframeGadget.__ready_list = RenderJSGadget.__ready_list.slice();
RenderJSIframeGadget.ready =
RenderJSGadget.ready;
RenderJSIframeGadget.prototype = new RenderJSGadget();
RenderJSIframeGadget.prototype.constructor = RenderJSIframeGadget;
/////////////////////////////////////////////////////////////////
// privateDeclareIframeGadget
/////////////////////////////////////////////////////////////////
function privateDeclareIframeGadget(url, options, parent_gadget) {
var gadget_instance,
iframe,
node,
iframe_loading_deferred = RSVP.defer();
if (options.element === undefined) {
throw new Error("DOM element is required to create Iframe Gadget " +
url);
}
// Check if the element is attached to the DOM
node = options.element.parentNode;
while (node !== null) {
if (node === document) {
break;
}
node = node.parentNode;
}
if (node === null) {
throw new Error("The parent element is not attached to the DOM for " +
url);
}
gadget_instance = new RenderJSIframeGadget();
setAqParent(gadget_instance, parent_gadget);
iframe = document.createElement("iframe");
// gadget_instance.element.setAttribute("seamless", "seamless");
iframe.setAttribute("src", url);
gadget_instance.__path = url;
gadget_instance.__element = options.element;
// Attach it to the DOM
options.element.appendChild(iframe);
// XXX Manage unbind when deleting the gadget
// Create the communication channel with the iframe
gadget_instance.__chan = Channel.build({
window: iframe.contentWindow,
origin: "*",
scope: "renderJS"
});
// Create new method from the declareMethod call inside the iframe
gadget_instance.__chan.bind("declareMethod",
function (trans, method_name) {
gadget_instance[method_name] = function () {
var argument_list = arguments;
return new RSVP.Promise(function (resolve, reject) {
gadget_instance.__chan.call({
method: "methodCall",
params: [
method_name,
Array.prototype.slice.call(argument_list, 0)],
success: function (s) {
resolve(s);
},
error: function (e) {
reject(e);
}
});
});
};
return "OK";
});
// Wait for the iframe to be loaded before continuing
gadget_instance.__chan.bind("ready", function (trans) {
iframe_loading_deferred.resolve(gadget_instance);
return "OK";
});
gadget_instance.__chan.bind("failed", function (trans, params) {
iframe_loading_deferred.reject(params);
return "OK";
});
gadget_instance.__chan.bind("acquire", function (trans, params) {
gadget_instance.__aq_parent.apply(gadget_instance, params)
.then(function (g) {
trans.complete(g);
}).fail(function (e) {
trans.error(e.toString());
});
trans.delayReturn(true);
});
return RSVP.any([
iframe_loading_deferred.promise,
// Timeout to prevent non renderJS embeddable gadget
// XXX Maybe using iframe.onload/onerror would be safer?
RSVP.timeout(5000)
]);
}
/////////////////////////////////////////////////////////////////
// RenderJSGadget.declareGadget
/////////////////////////////////////////////////////////////////
RenderJSGadget
.declareMethod('declareGadget', function (url, options) {
var queue,
parent_gadget = this,
previous_loading_gadget_promise = loading_gadget_promise;
if (options === undefined) {
options = {};
}
if (options.sandbox === undefined) {
options.sandbox = "public";
}
// transform url to absolute url if it is relative
url = renderJS.getAbsoluteURL(url, this.__path);
// Change the global variable to update the loading queue
queue = new RSVP.Queue()
// Wait for previous gadget loading to finish first
.push(function () {
return previous_loading_gadget_promise;
})
.push(undefined, function () {
// Forget previous declareGadget error
return;
})
.push(function () {
var method;
if (options.sandbox === "public") {
method = privateDeclarePublicGadget;
} else if (options.sandbox === "iframe") {
method = privateDeclareIframeGadget;
} else {
throw new Error("Unsupported sandbox options '" +
options.sandbox + "'");
}
return method(url, options, parent_gadget);
})
// Set the HTML context
.push(function (gadget_instance) {
var i;
// Drop the current loading klass info used by selector
gadget_loading_klass = undefined;
// Trigger calling of all ready callback
function ready_wrapper() {
return gadget_instance;
}
for (i = 0; i < gadget_instance.constructor.__ready_list.length;
i += 1) {
// Put a timeout?
queue.push(gadget_instance.constructor.__ready_list[i]);
// Always return the gadget instance after ready function
queue.push(ready_wrapper);
}
// Store local reference to the gadget instance
if (options.scope !== undefined) {
parent_gadget.__sub_gadget_dict[options.scope] = gadget_instance;
}
return gadget_instance;
})
.push(undefined, function (e) {
// Drop the current loading klass info used by selector
// even in case of error
gadget_loading_klass = undefined;
throw e;
});
loading_gadget_promise = queue;
return loading_gadget_promise;
})
.declareMethod('getDeclaredGadget', function (gadget_scope) {
if (!this.__sub_gadget_dict.hasOwnProperty(gadget_scope)) {
throw new Error("Gadget scope '" + gadget_scope + "' is not known.");
}
return this.__sub_gadget_dict[gadget_scope];
})
.declareMethod('dropGadget', function (gadget_scope) {
if (!this.__sub_gadget_dict.hasOwnProperty(gadget_scope)) {
throw new Error("Gadget scope '" + gadget_scope + "' is not known.");
}
// http://perfectionkills.com/understanding-delete/
delete this.__sub_gadget_dict[gadget_scope];
});
/////////////////////////////////////////////////////////////////
// renderJS selector
/////////////////////////////////////////////////////////////////
renderJS = function (selector) {
var result;
if (selector === window) {
// window is the 'this' value when loading a javascript file
// In this case, use the current loading gadget constructor
result = gadget_loading_klass;
}
if (result === undefined) {
throw new Error("Unknown selector '" + selector + "'");
}
return result;
};
/////////////////////////////////////////////////////////////////
// renderJS.AcquisitionError
/////////////////////////////////////////////////////////////////
renderJS.AcquisitionError = function (message) {
this.name = "AcquisitionError";
if ((message !== undefined) && (typeof message !== "string")) {
throw new TypeError('You must pass a string.');
}
this.message = message || "Acquisition failed";
};
renderJS.AcquisitionError.prototype = new Error();
renderJS.AcquisitionError.prototype.constructor =
renderJS.AcquisitionError;
/////////////////////////////////////////////////////////////////
// renderJS.getAbsoluteURL
/////////////////////////////////////////////////////////////////
renderJS.getAbsoluteURL = function (url, base_url) {
var doc, base, link,
html = "<!doctype><html><head></head></html>",
isAbsoluteOrDataURL = new RegExp('^(?:[a-z]+:)?//|data:', 'i');
if (url && base_url && !isAbsoluteOrDataURL.test(url)) {
doc = (new DOMParser()).parseFromString(html, 'text/html');
base = doc.createElement('base');
link = doc.createElement('link');
doc.head.appendChild(base);
doc.head.appendChild(link);
base.href = base_url;
link.href = url;
return link.href;
}
return url;
};
/////////////////////////////////////////////////////////////////
// renderJS.declareJS
/////////////////////////////////////////////////////////////////
renderJS.declareJS = function (url) {
// Prevent infinite recursion if loading render.js
// more than once
var result;
if (javascript_registration_dict.hasOwnProperty(url)) {
result = RSVP.resolve();
} else {
result = new RSVP.Promise(function (resolve, reject) {
var newScript;
newScript = document.createElement('script');
newScript.type = 'text/javascript';
newScript.src = url;
newScript.onload = function () {
javascript_registration_dict[url] = null;
resolve();
};
newScript.onerror = function (e) {
reject(e);
};
document.head.appendChild(newScript);
});
}
return result;
};
/////////////////////////////////////////////////////////////////
// renderJS.declareCSS
/////////////////////////////////////////////////////////////////
renderJS.declareCSS = function (url) {
// https://github.com/furf/jquery-getCSS/blob/master/jquery.getCSS.js
// No way to cleanly check if a css has been loaded
// So, always resolve the promise...
// http://requirejs.org/docs/faq-advanced.html#css
var result;
if (stylesheet_registration_dict.hasOwnProperty(url)) {
result = RSVP.resolve();
} else {
result = new RSVP.Promise(function (resolve, reject) {
var link;
link = document.createElement('link');
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = url;
link.onload = function () {
stylesheet_registration_dict[url] = null;
resolve();
};
link.onerror = function (e) {
reject(e);
};
document.head.appendChild(link);
});
}
return result;
};
/////////////////////////////////////////////////////////////////
// renderJS.declareGadgetKlass
/////////////////////////////////////////////////////////////////
renderJS.declareGadgetKlass = function (url) {
var result,
xhr;
function parse() {
var tmp_constructor,
key,
parsed_html;
if (!gadget_model_dict.hasOwnProperty(url)) {
// Class inheritance
tmp_constructor = function () {
RenderJSGadget.call(this);
};
tmp_constructor.__ready_list = RenderJSGadget.__ready_list.slice();
tmp_constructor.declareMethod =
RenderJSGadget.declareMethod;
tmp_constructor.declareAcquiredMethod =
RenderJSGadget.declareAcquiredMethod;
tmp_constructor.allowPublicAcquisition =
RenderJSGadget.allowPublicAcquisition;
tmp_constructor.ready =
RenderJSGadget.ready;
tmp_constructor.prototype = new RenderJSGadget();
tmp_constructor.prototype.constructor = tmp_constructor;
tmp_constructor.prototype.__path = url;
tmp_constructor.prototype.__acquired_method_dict = {};
// https://developer.mozilla.org/en-US/docs/HTML_in_XMLHttpRequest
// https://developer.mozilla.org/en-US/docs/Web/API/DOMParser
// https://developer.mozilla.org/en-US/docs/Code_snippets/HTML_to_DOM
tmp_constructor.__template_element =
(new DOMParser()).parseFromString(xhr.responseText, "text/html");
parsed_html = renderJS.parseGadgetHTMLDocument(
tmp_constructor.__template_element,
url
);
for (key in parsed_html) {
if (parsed_html.hasOwnProperty(key)) {
tmp_constructor.prototype['__' + key] = parsed_html[key];
}
}
gadget_model_dict[url] = tmp_constructor;
}
return gadget_model_dict[url];
}
function resolver(resolve, reject) {
function handler() {
var tmp_result;
try {
if (xhr.readyState === 0) {
// UNSENT
reject(xhr);
} else if (xhr.readyState === 4) {
// DONE
if ((xhr.status < 200) || (xhr.status >= 300) ||
(!/^text\/html[;]?/.test(
xhr.getResponseHeader("Content-Type") || ""
))) {
reject(xhr);
} else {
tmp_result = parse();
resolve(tmp_result);
}
}
} catch (e) {
reject(e);
}
}
xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.onreadystatechange = handler;
xhr.setRequestHeader('Accept', 'text/html');
xhr.withCredentials = true;
xhr.send();
}
function canceller() {
if ((xhr !== undefined) && (xhr.readyState !== xhr.DONE)) {
xhr.abort();
}
}
if (gadget_model_dict.hasOwnProperty(url)) {
// Return klass object if it already exists
result = RSVP.resolve(gadget_model_dict[url]);
} else {
// Fetch the HTML page and parse it
result = new RSVP.Promise(resolver, canceller);
}
return result;
};
/////////////////////////////////////////////////////////////////
// renderJS.clearGadgetKlassList
/////////////////////////////////////////////////////////////////
// For test purpose only
renderJS.clearGadgetKlassList = function () {
gadget_model_dict = {};
javascript_registration_dict = {};
stylesheet_registration_dict = {};
};
/////////////////////////////////////////////////////////////////
// renderJS.parseGadgetHTMLDocument
/////////////////////////////////////////////////////////////////
renderJS.parseGadgetHTMLDocument = function (document_element, url) {
var settings = {
title: "",
interface_list: [],
required_css_list: [],
required_js_list: []
},
i,
element,
isAbsoluteURL = new RegExp('^(?:[a-z]+:)?//', 'i');
if (!url || !isAbsoluteURL.test(url)) {
throw new Error("The second parameter should be an absolute url");
}
if (document_element.nodeType === 9) {
settings.title = document_element.title;
for (i = 0; i < document_element.head.children.length; i += 1) {
element = document_element.head.children[i];
if (element.href !== null) {
// XXX Manage relative URL during extraction of URLs
// element.href returns absolute URL in firefox but "" in chrome;
if (element.rel === "stylesheet") {
settings.required_css_list.push(
renderJS.getAbsoluteURL(element.getAttribute("href"), url)
);
} else if (element.nodeName === "SCRIPT" &&
(element.type === "text/javascript" ||
!element.type)) {
settings.required_js_list.push(
renderJS.getAbsoluteURL(element.getAttribute("src"), url)
);
} else if (element.rel === "http://www.renderjs.org/rel/interface") {
settings.interface_list.push(
renderJS.getAbsoluteURL(element.getAttribute("href"), url)
);
}
}
}
} else {
throw new Error("The first parameter should be an HTMLDocument");
}
return settings;
};
/////////////////////////////////////////////////////////////////
// global
/////////////////////////////////////////////////////////////////
window.rJS = window.renderJS = renderJS;
window.__RenderJSGadget = RenderJSGadget;
window.__RenderJSEmbeddedGadget = RenderJSEmbeddedGadget;
window.__RenderJSIframeGadget = RenderJSIframeGadget;
///////////////////////////////////////////////////
// Bootstrap process. Register the self gadget.
///////////////////////////////////////////////////
function bootstrap() {
var url = removeHash(window.location.href),
tmp_constructor,
root_gadget,
declare_method_count = 0,
embedded_channel,
notifyReady,
notifyDeclareMethod,
gadget_ready = false,
last_acquisition_gadget;
// Create the gadget class for the current url
if (gadget_model_dict.hasOwnProperty(url)) {
throw new Error("bootstrap should not be called twice");
}
loading_gadget_promise = new RSVP.Promise(function (resolve, reject) {
if (window.self === window.top) {
last_acquisition_gadget = new RenderJSGadget();
last_acquisition_gadget.__acquired_method_dict = {
getTopURL: function () {
return url;
}
};
// Stop acquisition on the last acquisition gadget
// Do not put this on the klass, as their could be multiple instances
last_acquisition_gadget.__aq_parent = function (method_name) {
throw new renderJS.AcquisitionError(
"No gadget provides " + method_name
);
};
// XXX Copy/Paste from declareGadgetKlass
tmp_constructor = function () {
RenderJSGadget.call(this);
};
tmp_constructor.declareMethod = RenderJSGadget.declareMethod;
tmp_constructor.declareAcquiredMethod =
RenderJSGadget.declareAcquiredMethod;
tmp_constructor.allowPublicAcquisition =
RenderJSGadget.allowPublicAcquisition;
tmp_constructor.__ready_list = RenderJSGadget.__ready_list.slice();
tmp_constructor.ready = RenderJSGadget.ready;
tmp_constructor.prototype = new RenderJSGadget();
tmp_constructor.prototype.constructor = tmp_constructor;
tmp_constructor.prototype.__path = url;
gadget_model_dict[url] = tmp_constructor;
// Create the root gadget instance and put it in the loading stack
root_gadget = new gadget_model_dict[url]();
setAqParent(root_gadget, last_acquisition_gadget);
} else {
// Create the communication channel
embedded_channel = Channel.build({
window: window.parent,
origin: "*",
scope: "renderJS"
});
// Create the root gadget instance and put it in the loading stack
tmp_constructor = RenderJSEmbeddedGadget;
tmp_constructor.__ready_list = RenderJSGadget.__ready_list.slice();
tmp_constructor.prototype.__path = url;
root_gadget = new RenderJSEmbeddedGadget();
// Bind calls to renderJS method on the instance
embedded_channel.bind("methodCall", function (trans, v) {
root_gadget[v[0]].apply(root_gadget, v[1]).then(function (g) {
trans.complete(g);
}).fail(function (e) {
trans.error(e.toString());
});
trans.delayReturn(true);
});
// Notify parent about gadget instanciation
notifyReady = function () {
if ((declare_method_count === 0) && (gadget_ready === true)) {
embedded_channel.notify({method: "ready"});
}
};
// Inform parent gadget about declareMethod calls here.
notifyDeclareMethod = function (name) {
declare_method_count += 1;
embedded_channel.call({
method: "declareMethod",
params: name,
success: function () {
declare_method_count -= 1;
notifyReady();
},
error: function () {
declare_method_count -= 1;
}
});
};
notifyDeclareMethod("getInterfaceList");
notifyDeclareMethod("getRequiredCSSList");
notifyDeclareMethod("getRequiredJSList");
notifyDeclareMethod("getPath");
notifyDeclareMethod("getTitle");
// Surcharge declareMethod to inform parent window
tmp_constructor.declareMethod = function (name, callback) {
var result = RenderJSGadget.declareMethod.apply(
this,
[name, callback]
);
notifyDeclareMethod(name);
return result;
};
tmp_constructor.declareAcquiredMethod =
RenderJSGadget.declareAcquiredMethod;
tmp_constructor.allowPublicAcquisition =
RenderJSGadget.allowPublicAcquisition;
// Define __aq_parent to inform parent window
tmp_constructor.prototype.__aq_parent = function (method_name,
argument_list) {
return new RSVP.Promise(function (resolve, reject) {
embedded_channel.call({
method: "acquire",
params: [
method_name,
argument_list
],
success: function (s) {
resolve(s);
},
error: function (e) {
reject(e);
}
});
});
};
}
tmp_constructor.prototype.__acquired_method_dict = {};
gadget_loading_klass = tmp_constructor;
function init() {
// XXX HTML properties can only be set when the DOM is fully loaded
var settings = renderJS.parseGadgetHTMLDocument(document, url),
j,
key;
for (key in settings) {
if (settings.hasOwnProperty(key)) {
tmp_constructor.prototype['__' + key] = settings[key];
}
}
tmp_constructor.__template_element = document.createElement("div");
root_gadget.__element = document.body;
for (j = 0; j < root_gadget.__element.childNodes.length; j += 1) {
tmp_constructor.__template_element.appendChild(
root_gadget.__element.childNodes[j].cloneNode(true)
);
}
RSVP.all([root_gadget.getRequiredJSList(),
root_gadget.getRequiredCSSList()])
.then(function (all_list) {
var i,
js_list = all_list[0],
css_list = all_list[1],
queue;
for (i = 0; i < js_list.length; i += 1) {
javascript_registration_dict[js_list[i]] = null;
}
for (i = 0; i < css_list.length; i += 1) {
stylesheet_registration_dict[css_list[i]] = null;
}
gadget_loading_klass = undefined;
queue = new RSVP.Queue();
function ready_wrapper() {
return root_gadget;
}
if (window.top !== window.self) {
tmp_constructor.ready(function () {
var base = document.createElement('base');
return root_gadget.__aq_parent('getTopURL', [])
.then(function (topURL) {
base.href = topURL;
base.target = "_top";
document.head.appendChild(base);
});
});
}
queue.push(ready_wrapper);
for (i = 0; i < tmp_constructor.__ready_list.length; i += 1) {
// Put a timeout?
queue.push(tmp_constructor.__ready_list[i])
// Always return the gadget instance after ready function
.push(ready_wrapper);
}
queue.push(resolve, function (e) {
reject(e);
throw e;
});
return queue;
}).fail(function (e) {
reject(e);
/*global console */
console.error(e);
});
}
document.addEventListener('DOMContentLoaded', init, false);
});
if (window.self !== window.top) {
// Inform parent window that gadget is correctly loaded
loading_gadget_promise.then(function () {
gadget_ready = true;
notifyReady();
}).fail(function (e) {
embedded_channel.notify({method: "failed", params: e.toString()});
throw e;
});
}
}
bootstrap();
}(document, window, RSVP, DOMParser, Channel));
var Channel=function(){"use strict";function a(a,b,c,d){function f(b){for(var c=0;c<b.length;c++)if(b[c].win===a)return!0;return!1}var g=!1;if("*"===b){for(var h in e)if(e.hasOwnProperty(h)&&"*"!==h&&"object"==typeof e[h][c]&&(g=f(e[h][c])))break}else e["*"]&&e["*"][c]&&(g=f(e["*"][c])),!g&&e[b]&&e[b][c]&&(g=f(e[b][c]));if(g)throw"A channel is already bound to the same window which overlaps with origin '"+b+"' and has scope '"+c+"'";"object"!=typeof e[b]&&(e[b]={}),"object"!=typeof e[b][c]&&(e[b][c]=[]),e[b][c].push({win:a,handler:d})}function b(a,b,c){for(var d=e[b][c],f=0;f<d.length;f++)d[f].win===a&&d.splice(f,1);0===e[b][c].length&&delete e[b][c]}function c(a){return Array.isArray?Array.isArray(a):-1!=a.constructor.toString().indexOf("Array")}var d=Math.floor(1000001*Math.random()),e={},f={},g=function(a){try{var b=JSON.parse(a.data);if("object"!=typeof b||null===b)throw"malformed"}catch(a){return}var c,d,g,h=a.source,i=a.origin;if("string"==typeof b.method){var j=b.method.split("::");2==j.length?(c=j[0],g=j[1]):g=b.method}if("undefined"!=typeof b.id&&(d=b.id),"string"==typeof g){var k=!1;if(e[i]&&e[i][c])for(var l=0;l<e[i][c].length;l++)if(e[i][c][l].win===h){e[i][c][l].handler(i,g,b),k=!0;break}if(!k&&e["*"]&&e["*"][c])for(var l=0;l<e["*"][c].length;l++)if(e["*"][c][l].win===h){e["*"][c][l].handler(i,g,b);break}}else"undefined"!=typeof d&&f[d]&&f[d](i,g,b)};return window.addEventListener?window.addEventListener("message",g,!1):window.attachEvent&&window.attachEvent("onmessage",g),{build:function(e){var g=function(a){if(e.debugOutput&&window.console&&window.console.log){try{"string"!=typeof a&&(a=JSON.stringify(a))}catch(b){}console.log("["+j+"] "+a)}};if(!window.postMessage)throw"jschannel cannot run this browser, no postMessage";if(!window.JSON||!window.JSON.stringify||!window.JSON.parse)throw"jschannel cannot run this browser, no JSON parsing/serialization";if("object"!=typeof e)throw"Channel build invoked without a proper object argument";if(!e.window||!e.window.postMessage)throw"Channel.build() called without a valid window argument";if(window===e.window)throw"target window is same as present window -- not allowed";var h=!1;if("string"==typeof e.origin){var i;"*"===e.origin?h=!0:null!==(i=e.origin.match(/^https?:\/\/(?:[-a-zA-Z0-9_\.])+(?::\d+)?/))&&(e.origin=i[0].toLowerCase(),h=!0)}if(!h)throw"Channel.build() called with an invalid origin";if("undefined"!=typeof e.scope){if("string"!=typeof e.scope)throw"scope, when specified, must be a string";if(e.scope.split("::").length>1)throw"scope may not contain double colons: '::'"}var j=function(){for(var a="",b="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",c=0;5>c;c++)a+=b.charAt(Math.floor(Math.random()*b.length));return a}(),k={},l={},m={},n=!1,o=[],p=function(a,b,c){var d=!1,e=!1;return{origin:b,invoke:function(b,d){if(!m[a])throw"attempting to invoke a callback of a nonexistent transaction: "+a;for(var e=!1,f=0;f<c.length;f++)if(b===c[f]){e=!0;break}if(!e)throw"request supports no such callback '"+b+"'";t({id:a,callback:b,params:d})},error:function(b,c){if(e=!0,!m[a])throw"error called for nonexistent message: "+a;delete m[a],t({id:a,error:b,message:c})},complete:function(b){if(e=!0,!m[a])throw"complete called for nonexistent message: "+a;delete m[a],t({id:a,result:b})},delayReturn:function(a){return"boolean"==typeof a&&(d=a===!0),d},completed:function(){return e}}},q=function(a,b,c){return window.setTimeout(function(){if(l[a]){var d="timeout ("+b+"ms) exceeded on method '"+c+"'";l[a].error("timeout_error",d),delete l[a],delete f[a]}},b)},r=function(a,b,d){if("function"==typeof e.gotMessageObserver)try{e.gotMessageObserver(a,d)}catch(h){g("gotMessageObserver() raised an exception: "+h.toString())}if(d.id&&b){if(k[b]){var i=p(d.id,a,d.callbacks?d.callbacks:[]);m[d.id]={};try{if(d.callbacks&&c(d.callbacks)&&d.callbacks.length>0)for(var j=0;j<d.callbacks.length;j++){for(var n=d.callbacks[j],o=d.params,q=n.split("/"),r=0;r<q.length-1;r++){var s=q[r];"object"!=typeof o[s]&&(o[s]={}),o=o[s]}o[q[q.length-1]]=function(){var a=n;return function(b){return i.invoke(a,b)}}()}var t=k[b](i,d.params);i.delayReturn()||i.completed()||i.complete(t)}catch(h){var u="runtime_error",v=null;if("string"==typeof h?v=h:"object"==typeof h&&(h&&c(h)&&2==h.length?(u=h[0],v=h[1]):"string"==typeof h.error&&(u=h.error,h.message?"string"==typeof h.message?v=h.message:h=h.message:v="")),null===v)try{v=JSON.stringify(h),"undefined"==typeof v&&(v=h.toString())}catch(w){v=h.toString()}i.error(u,v)}}}else d.id&&d.callback?l[d.id]&&l[d.id].callbacks&&l[d.id].callbacks[d.callback]?l[d.id].callbacks[d.callback](d.params):g("ignoring invalid callback, id:"+d.id+" ("+d.callback+")"):d.id?l[d.id]?(d.error?l[d.id].error(d.error,d.message):void 0!==d.result?l[d.id].success(d.result):l[d.id].success(),delete l[d.id],delete f[d.id]):g("ignoring invalid response: "+d.id):b&&k[b]&&k[b]({origin:a},d.params)};a(e.window,e.origin,"string"==typeof e.scope?e.scope:"",r);var s=function(a){return"string"==typeof e.scope&&e.scope.length&&(a=[e.scope,a].join("::")),a},t=function(a,b){if(!a)throw"postMessage called with null message";var c=n?"post ":"queue ";if(g(c+" message: "+JSON.stringify(a)),b||n){if("function"==typeof e.postMessageObserver)try{e.postMessageObserver(e.origin,a)}catch(d){g("postMessageObserver() raised an exception: "+d.toString())}e.window.postMessage(JSON.stringify(a),e.origin)}else o.push(a)},u=function(a,b){if(g("ready msg received"),n)throw"received ready message while in ready state. help!";for(j+="ping"===b?"-R":"-L",v.unbind("__ready"),n=!0,g("ready msg accepted."),"ping"===b&&v.notify({method:"__ready",params:"pong"});o.length;)t(o.pop());"function"==typeof e.onReady&&e.onReady(v)},v={unbind:function(a){if(k[a]){if(!delete k[a])throw"can't delete method: "+a;return!0}return!1},bind:function(a,b){if(!a||"string"!=typeof a)throw"'method' argument to bind must be string";if(!b||"function"!=typeof b)throw"callback missing from bind params";if(k[a])throw"method '"+a+"' is already bound!";return k[a]=b,this},call:function(a){if(!a)throw"missing arguments to call function";if(!a.method||"string"!=typeof a.method)throw"'method' argument to call must be string";if(!a.success||"function"!=typeof a.success)throw"'success' callback missing from call";var b={},c=[],e=function(a,d){if("object"==typeof d)for(var f in d)if(d.hasOwnProperty(f)){var g=a+(a.length?"/":"")+f;"function"==typeof d[f]?(b[g]=d[f],c.push(g),delete d[f]):"object"==typeof d[f]&&e(g,d[f])}};e("",a.params);var g={id:d,method:s(a.method),params:a.params};c.length&&(g.callbacks=c),a.timeout&&q(d,a.timeout,s(a.method)),l[d]={callbacks:b,error:a.error,success:a.success},f[d]=r,d++,t(g)},notify:function(a){if(!a)throw"missing arguments to notify function";if(!a.method||"string"!=typeof a.method)throw"'method' argument to notify must be string";t({method:s(a.method),params:a.params})},destroy:function(){b(e.window,e.origin,"string"==typeof e.scope?e.scope:""),window.removeEventListener?window.removeEventListener("message",r,!1):window.detachEvent&&window.detachEvent("onmessage",r),n=!1,k={},m={},l={},e.origin=null,o=[],g("channel destroyed"),j=""}};return v.bind("__ready",u),setTimeout(function(){t({method:s("__ready"),params:"ping"},!0)},0),v}}}();!function(a){"use strict";var b=a.prototype,c=b.parseFromString;try{if((new a).parseFromString("","text/html"))return}catch(d){}b.parseFromString=function(a,b){var d,e,f,g;return/^\s*text\/html\s*(?:;|$)/i.test(b)?(e=document.implementation.createHTMLDocument(""),f=e.documentElement,f.innerHTML=a,g=f.firstElementChild,1===f.childElementCount&&"html"===g.localName.toLowerCase()&&e.replaceChild(g,f),d=e):d=c.apply(this,arguments),d}}(DOMParser),function(a,b,c,d,e,f){"use strict";function g(a){var b=a.indexOf("#");return b>0&&(a=a.substring(0,b)),a}function h(){return this instanceof h?void 0:new h}function i(a){a.__sub_gadget_dict={}}function j(a,b,d){var e,g,h=this;for(e in h.__sub_gadget_dict)h.__sub_gadget_dict.hasOwnProperty(e)&&h.__sub_gadget_dict[e]===a&&(g=e);return(new c.Queue).push(function(){var a=h.__acquired_method_dict||{};if(a.hasOwnProperty(b))return a[b].apply(h,[d,g]);throw new s.AcquisitionError("aq_dynamic is not defined")}).push(f,function(a){if(a instanceof s.AcquisitionError)return h.__aq_parent(b,d);throw a})}function k(a,b){a.__aq_parent=function(c,d){return j.apply(b,[a,c,d])}}function l(){return this instanceof l?(h.call(this),void 0):new l}function m(b,d,e){function g(a,b){return function(){return a(b)}}var h;return d.element===f&&(d.element=a.createElement("div")),(new c.Queue).push(function(){return s.declareGadgetKlass(b)}).push(function(a){var b,f=a.__template_element.body.childNodes;for(q=a,h=new a,h.__element=d.element,b=0;b<f.length;b+=1)h.__element.appendChild(f[b].cloneNode(!0));return k(h,e),c.all([h.getRequiredJSList(),h.getRequiredCSSList()])}).push(function(a){var b,d=new c.Queue;for(b=0;b<a[0].length;b+=1)d.push(g(s.declareJS,a[0][b]));for(b=0;b<a[1].length;b+=1)d.push(g(s.declareCSS,a[1][b]));return d}).push(function(){return h})}function n(){return this instanceof n?(h.call(this),void 0):new n}function o(b,d,g){var h,i,j,l=c.defer();if(d.element===f)throw new Error("DOM element is required to create Iframe Gadget "+b);for(j=d.element.parentNode;null!==j&&j!==a;)j=j.parentNode;if(null===j)throw new Error("The parent element is not attached to the DOM for "+b);return h=new n,k(h,g),i=a.createElement("iframe"),i.setAttribute("src",b),h.__path=b,h.__element=d.element,d.element.appendChild(i),h.__chan=e.build({window:i.contentWindow,origin:"*",scope:"renderJS"}),h.__chan.bind("declareMethod",function(a,b){return h[b]=function(){var a=arguments;return new c.Promise(function(c,d){h.__chan.call({method:"methodCall",params:[b,Array.prototype.slice.call(a,0)],success:function(a){c(a)},error:function(a){d(a)}})})},"OK"}),h.__chan.bind("ready",function(){return l.resolve(h),"OK"}),h.__chan.bind("failed",function(a,b){return l.reject(b),"OK"}),h.__chan.bind("acquire",function(a,b){h.__aq_parent.apply(h,b).then(function(b){a.complete(b)}).fail(function(b){a.error(b.toString())}),a.delayReturn(!0)}),c.any([l.promise,c.timeout(5e3)])}function p(){var d,i,j,m,n,o,p=g(b.location.href),w=0,x=!1;if(t.hasOwnProperty(p))throw new Error("bootstrap should not be called twice");r=new c.Promise(function(g,r){function y(){var e,h,j=s.parseGadgetHTMLDocument(a,p);for(h in j)j.hasOwnProperty(h)&&(d.prototype["__"+h]=j[h]);for(d.__template_element=a.createElement("div"),i.__element=a.body,e=0;e<i.__element.childNodes.length;e+=1)d.__template_element.appendChild(i.__element.childNodes[e].cloneNode(!0));c.all([i.getRequiredJSList(),i.getRequiredCSSList()]).then(function(e){function h(){return i}var j,k,l=e[0],m=e[1];for(j=0;j<l.length;j+=1)u[l[j]]=null;for(j=0;j<m.length;j+=1)v[m[j]]=null;for(q=f,k=new c.Queue,b.top!==b.self&&d.ready(function(){var b=a.createElement("base");return i.__aq_parent("getTopURL",[]).then(function(c){b.href=c,b.target="_top",a.head.appendChild(b)})}),k.push(h),j=0;j<d.__ready_list.length;j+=1)k.push(d.__ready_list[j]).push(h);return k.push(g,function(a){throw r(a),a}),k}).fail(function(a){r(a),console.error(a)})}b.self===b.top?(o=new h,o.__acquired_method_dict={getTopURL:function(){return p}},o.__aq_parent=function(a){throw new s.AcquisitionError("No gadget provides "+a)},d=function(){h.call(this)},d.declareMethod=h.declareMethod,d.declareAcquiredMethod=h.declareAcquiredMethod,d.allowPublicAcquisition=h.allowPublicAcquisition,d.__ready_list=h.__ready_list.slice(),d.ready=h.ready,d.prototype=new h,d.prototype.constructor=d,d.prototype.__path=p,t[p]=d,i=new t[p],k(i,o)):(j=e.build({window:b.parent,origin:"*",scope:"renderJS"}),d=l,d.__ready_list=h.__ready_list.slice(),d.prototype.__path=p,i=new l,j.bind("methodCall",function(a,b){i[b[0]].apply(i,b[1]).then(function(b){a.complete(b)}).fail(function(b){a.error(b.toString())}),a.delayReturn(!0)}),m=function(){0===w&&x===!0&&j.notify({method:"ready"})},n=function(a){w+=1,j.call({method:"declareMethod",params:a,success:function(){w-=1,m()},error:function(){w-=1}})},n("getInterfaceList"),n("getRequiredCSSList"),n("getRequiredJSList"),n("getPath"),n("getTitle"),d.declareMethod=function(a,b){var c=h.declareMethod.apply(this,[a,b]);return n(a),c},d.declareAcquiredMethod=h.declareAcquiredMethod,d.allowPublicAcquisition=h.allowPublicAcquisition,d.prototype.__aq_parent=function(a,b){return new c.Promise(function(c,d){j.call({method:"acquire",params:[a,b],success:function(a){c(a)},error:function(a){d(a)}})})}),d.prototype.__acquired_method_dict={},q=d,a.addEventListener("DOMContentLoaded",y,!1)}),b.self!==b.top&&r.then(function(){x=!0,m()}).fail(function(a){throw j.notify({method:"failed",params:a.toString()}),a})}var q,r,s,t={},u={},v={};h.prototype.__title="",h.prototype.__interface_list=[],h.prototype.__path="",h.prototype.__html="",h.prototype.__required_css_list=[],h.prototype.__required_js_list=[],h.__ready_list=[i],h.ready=function(a){return this.__ready_list.push(a),this},h.declareMethod=function(a,b){return this.prototype[a]=function(){var a=this,d=arguments;return(new c.Queue).push(function(){return b.apply(a,d)})},this},h.declareMethod("getInterfaceList",function(){return this.__interface_list}).declareMethod("getRequiredCSSList",function(){return this.__required_css_list}).declareMethod("getRequiredJSList",function(){return this.__required_js_list}).declareMethod("getPath",function(){return this.__path}).declareMethod("getTitle",function(){return this.__title}).declareMethod("getElement",function(){if(this.__element===f)throw new Error("No element defined");return this.__element}),h.declareAcquiredMethod=function(a,b){return this.prototype[a]=function(){var a=Array.prototype.slice.call(arguments,0),d=this;return(new c.Queue).push(function(){return d.__aq_parent(b,a)})},this},h.allowPublicAcquisition=function(a,b){return this.prototype.__acquired_method_dict[a]=b,this},l.__ready_list=h.__ready_list.slice(),l.ready=h.ready,l.prototype=new h,l.prototype.constructor=l,n.__ready_list=h.__ready_list.slice(),n.ready=h.ready,n.prototype=new h,n.prototype.constructor=n,h.declareMethod("declareGadget",function(a,b){var d,e=this,g=r;return b===f&&(b={}),b.sandbox===f&&(b.sandbox="public"),a=s.getAbsoluteURL(a,this.__path),d=(new c.Queue).push(function(){return g}).push(f,function(){}).push(function(){var c;if("public"===b.sandbox)c=m;else{if("iframe"!==b.sandbox)throw new Error("Unsupported sandbox options '"+b.sandbox+"'");c=o}return c(a,b,e)}).push(function(a){function c(){return a}var g;for(q=f,g=0;g<a.constructor.__ready_list.length;g+=1)d.push(a.constructor.__ready_list[g]),d.push(c);return b.scope!==f&&(e.__sub_gadget_dict[b.scope]=a),a}).push(f,function(a){throw q=f,a}),r=d}).declareMethod("getDeclaredGadget",function(a){if(!this.__sub_gadget_dict.hasOwnProperty(a))throw new Error("Gadget scope '"+a+"' is not known.");return this.__sub_gadget_dict[a]}).declareMethod("dropGadget",function(a){if(!this.__sub_gadget_dict.hasOwnProperty(a))throw new Error("Gadget scope '"+a+"' is not known.");delete this.__sub_gadget_dict[a]}),s=function(a){var c;if(a===b&&(c=q),c===f)throw new Error("Unknown selector '"+a+"'");return c},s.AcquisitionError=function(a){if(this.name="AcquisitionError",a!==f&&"string"!=typeof a)throw new TypeError("You must pass a string.");this.message=a||"Acquisition failed"},s.AcquisitionError.prototype=new Error,s.AcquisitionError.prototype.constructor=s.AcquisitionError,s.getAbsoluteURL=function(a,b){var c,e,f,g="<!doctype><html><head></head></html>",h=new RegExp("^(?:[a-z]+:)?//|data:","i");return a&&b&&!h.test(a)?(c=(new d).parseFromString(g,"text/html"),e=c.createElement("base"),f=c.createElement("link"),c.head.appendChild(e),c.head.appendChild(f),e.href=b,f.href=a,f.href):a},s.declareJS=function(b){var d;return d=u.hasOwnProperty(b)?c.resolve():new c.Promise(function(c,d){var e;e=a.createElement("script"),e.type="text/javascript",e.src=b,e.onload=function(){u[b]=null,c()},e.onerror=function(a){d(a)},a.head.appendChild(e)})},s.declareCSS=function(b){var d;return d=v.hasOwnProperty(b)?c.resolve():new c.Promise(function(c,d){var e;e=a.createElement("link"),e.rel="stylesheet",e.type="text/css",e.href=b,e.onload=function(){v[b]=null,c()},e.onerror=function(a){d(a)},a.head.appendChild(e)})},s.declareGadgetKlass=function(a){function b(){var b,c,e;if(!t.hasOwnProperty(a)){b=function(){h.call(this)},b.__ready_list=h.__ready_list.slice(),b.declareMethod=h.declareMethod,b.declareAcquiredMethod=h.declareAcquiredMethod,b.allowPublicAcquisition=h.allowPublicAcquisition,b.ready=h.ready,b.prototype=new h,b.prototype.constructor=b,b.prototype.__path=a,b.prototype.__acquired_method_dict={},b.__template_element=(new d).parseFromString(j.responseText,"text/html"),e=s.parseGadgetHTMLDocument(b.__template_element,a);for(c in e)e.hasOwnProperty(c)&&(b.prototype["__"+c]=e[c]);t[a]=b}return t[a]}function e(c,d){function e(){var a;try{0===j.readyState?d(j):4===j.readyState&&(j.status<200||j.status>=300||!/^text\/html[;]?/.test(j.getResponseHeader("Content-Type")||"")?d(j):(a=b(),c(a)))}catch(e){d(e)}}j=new XMLHttpRequest,j.open("GET",a),j.onreadystatechange=e,j.setRequestHeader("Accept","text/html"),j.withCredentials=!0,j.send()}function g(){j!==f&&j.readyState!==j.DONE&&j.abort()}var i,j;return i=t.hasOwnProperty(a)?c.resolve(t[a]):new c.Promise(e,g)},s.clearGadgetKlassList=function(){t={},u={},v={}},s.parseGadgetHTMLDocument=function(a,b){var c,d,e={title:"",interface_list:[],required_css_list:[],required_js_list:[]},f=new RegExp("^(?:[a-z]+:)?//","i");if(!b||!f.test(b))throw new Error("The second parameter should be an absolute url");if(9!==a.nodeType)throw new Error("The first parameter should be an HTMLDocument");for(e.title=a.title,c=0;c<a.head.children.length;c+=1)d=a.head.children[c],null!==d.href&&("stylesheet"===d.rel?e.required_css_list.push(s.getAbsoluteURL(d.getAttribute("href"),b)):"SCRIPT"!==d.nodeName||"text/javascript"!==d.type&&d.type?"http://www.renderjs.org/rel/interface"===d.rel&&e.interface_list.push(s.getAbsoluteURL(d.getAttribute("href"),b)):e.required_js_list.push(s.getAbsoluteURL(d.getAttribute("src"),b)));return e},b.rJS=b.renderJS=s,b.__RenderJSGadget=h,b.__RenderJSEmbeddedGadget=l,b.__RenderJSIframeGadget=n,p()}(document,window,RSVP,DOMParser,Channel);
\ No newline at end of file
...@@ -658,6 +658,7 @@ ...@@ -658,6 +658,7 @@
}(DOMParser)); }(DOMParser));
;/*! RenderJs */ ;/*! RenderJs */
/*jslint nomen: true*/
/* /*
* renderJs - Generic Gadget library renderer. * renderJs - Generic Gadget library renderer.
...@@ -673,6 +674,14 @@ ...@@ -673,6 +674,14 @@
loading_gadget_promise, loading_gadget_promise,
renderJS; renderJS;
function removeHash(url) {
var index = url.indexOf('#');
if (index > 0) {
url = url.substring(0, index);
}
return url;
}
///////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////
// RenderJSGadget // RenderJSGadget
///////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////
...@@ -681,18 +690,20 @@ ...@@ -681,18 +690,20 @@
return new RenderJSGadget(); return new RenderJSGadget();
} }
} }
RenderJSGadget.prototype.title = ""; RenderJSGadget.prototype.__title = "";
RenderJSGadget.prototype.interface_list = []; RenderJSGadget.prototype.__interface_list = [];
RenderJSGadget.prototype.path = ""; RenderJSGadget.prototype.__path = "";
RenderJSGadget.prototype.html = ""; RenderJSGadget.prototype.__html = "";
RenderJSGadget.prototype.required_css_list = []; RenderJSGadget.prototype.__required_css_list = [];
RenderJSGadget.prototype.required_js_list = []; RenderJSGadget.prototype.__required_js_list = [];
RSVP.EventTarget.mixin(RenderJSGadget.prototype); function clearGadgetInternalParameters(g) {
g.__sub_gadget_dict = {};
}
RenderJSGadget.ready_list = []; RenderJSGadget.__ready_list = [clearGadgetInternalParameters];
RenderJSGadget.ready = function (callback) { RenderJSGadget.ready = function (callback) {
this.ready_list.push(callback); this.__ready_list.push(callback);
return this; return this;
}; };
...@@ -716,50 +727,101 @@ ...@@ -716,50 +727,101 @@
RenderJSGadget RenderJSGadget
.declareMethod('getInterfaceList', function () { .declareMethod('getInterfaceList', function () {
// Returns the list of gadget prototype // Returns the list of gadget prototype
return this.interface_list; return this.__interface_list;
}) })
.declareMethod('getRequiredCSSList', function () { .declareMethod('getRequiredCSSList', function () {
// Returns a list of CSS required by the gadget // Returns a list of CSS required by the gadget
return this.required_css_list; return this.__required_css_list;
}) })
.declareMethod('getRequiredJSList', function () { .declareMethod('getRequiredJSList', function () {
// Returns a list of JS required by the gadget // Returns a list of JS required by the gadget
return this.required_js_list; return this.__required_js_list;
}) })
.declareMethod('getPath', function () { .declareMethod('getPath', function () {
// Returns the path of the code of a gadget // Returns the path of the code of a gadget
return this.path; return this.__path;
}) })
.declareMethod('getTitle', function () { .declareMethod('getTitle', function () {
// Returns the title of a gadget // Returns the title of a gadget
return this.title; return this.__title;
}) })
.declareMethod('getElement', function () { .declareMethod('getElement', function () {
// Returns the DOM Element of a gadget // Returns the DOM Element of a gadget
if (this.element === undefined) { if (this.__element === undefined) {
throw new Error("No element defined"); throw new Error("No element defined");
} }
return this.element; return this.__element;
})
.declareMethod('acquire', function () {
var gadget = this,
argument_list = arguments;
return new RSVP.Queue()
.push(function () {
var aq_dynamic = gadget.aq_dynamic;
if (aq_dynamic !== undefined) {
return aq_dynamic.apply(gadget, argument_list);
}
throw new renderJS.AcquisitionError("aq_dynamic is not defined");
})
.push(undefined, function (error) {
if (error instanceof renderJS.AcquisitionError) {
return gadget.aq_parent.apply(gadget, argument_list);
}
throw error;
});
}); });
/////////////////////////////////////////////////////////////////
// RenderJSGadget.declareAcquiredMethod
/////////////////////////////////////////////////////////////////
function acquire(child_gadget, method_name, argument_list) {
var gadget = this,
key,
gadget_scope;
for (key in gadget.__sub_gadget_dict) {
if (gadget.__sub_gadget_dict.hasOwnProperty(key)) {
if (gadget.__sub_gadget_dict[key] === child_gadget) {
gadget_scope = key;
}
}
}
return new RSVP.Queue()
.push(function () {
// Do not specify default __acquired_method_dict on prototype
// to prevent modifying this default value (with
// allowPublicAcquiredMethod for example)
var aq_dict = gadget.__acquired_method_dict || {};
if (aq_dict.hasOwnProperty(method_name)) {
return aq_dict[method_name].apply(gadget,
[argument_list, gadget_scope]);
}
throw new renderJS.AcquisitionError("aq_dynamic is not defined");
})
.push(undefined, function (error) {
if (error instanceof renderJS.AcquisitionError) {
return gadget.__aq_parent(method_name, argument_list);
}
throw error;
});
}
RenderJSGadget.declareAcquiredMethod =
function (name, method_name_to_acquire) {
this.prototype[name] = function () {
var argument_list = Array.prototype.slice.call(arguments, 0),
gadget = this;
return new RSVP.Queue()
.push(function () {
return gadget.__aq_parent(method_name_to_acquire, argument_list);
});
};
// Allow chain
return this;
};
/////////////////////////////////////////////////////////////////
// RenderJSGadget.allowPublicAcquisition
/////////////////////////////////////////////////////////////////
RenderJSGadget.allowPublicAcquisition =
function (method_name, callback) {
this.prototype.__acquired_method_dict[method_name] = callback;
// Allow chain
return this;
};
// Set aq_parent on gadget_instance which call acquire on parent_gadget
function setAqParent(gadget_instance, parent_gadget) {
gadget_instance.__aq_parent = function (method_name, argument_list) {
return acquire.apply(parent_gadget, [gadget_instance, method_name,
argument_list]);
};
}
///////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////
// RenderJSEmbeddedGadget // RenderJSEmbeddedGadget
///////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////
...@@ -770,7 +832,7 @@ ...@@ -770,7 +832,7 @@
} }
RenderJSGadget.call(this); RenderJSGadget.call(this);
} }
RenderJSEmbeddedGadget.ready_list = []; RenderJSEmbeddedGadget.__ready_list = RenderJSGadget.__ready_list.slice();
RenderJSEmbeddedGadget.ready = RenderJSEmbeddedGadget.ready =
RenderJSGadget.ready; RenderJSGadget.ready;
RenderJSEmbeddedGadget.prototype = new RenderJSGadget(); RenderJSEmbeddedGadget.prototype = new RenderJSGadget();
...@@ -779,7 +841,7 @@ ...@@ -779,7 +841,7 @@
///////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////
// privateDeclarePublicGadget // privateDeclarePublicGadget
///////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////
function privateDeclarePublicGadget(url, options) { function privateDeclarePublicGadget(url, options, parent_gadget) {
var gadget_instance; var gadget_instance;
if (options.element === undefined) { if (options.element === undefined) {
options.element = document.createElement("div"); options.element = document.createElement("div");
...@@ -798,15 +860,16 @@ ...@@ -798,15 +860,16 @@
// Get the gadget class and instanciate it // Get the gadget class and instanciate it
.push(function (Klass) { .push(function (Klass) {
var i, var i,
template_node_list = Klass.template_element.body.childNodes; template_node_list = Klass.__template_element.body.childNodes;
gadget_loading_klass = Klass; gadget_loading_klass = Klass;
gadget_instance = new Klass(); gadget_instance = new Klass();
gadget_instance.element = options.element; gadget_instance.__element = options.element;
for (i = 0; i < template_node_list.length; i += 1) { for (i = 0; i < template_node_list.length; i += 1) {
gadget_instance.element.appendChild( gadget_instance.__element.appendChild(
template_node_list[i].cloneNode(true) template_node_list[i].cloneNode(true)
); );
} }
setAqParent(gadget_instance, parent_gadget);
// Load dependencies if needed // Load dependencies if needed
return RSVP.all([ return RSVP.all([
gadget_instance.getRequiredJSList(), gadget_instance.getRequiredJSList(),
...@@ -841,7 +904,7 @@ ...@@ -841,7 +904,7 @@
} }
RenderJSGadget.call(this); RenderJSGadget.call(this);
} }
RenderJSIframeGadget.ready_list = []; RenderJSIframeGadget.__ready_list = RenderJSGadget.__ready_list.slice();
RenderJSIframeGadget.ready = RenderJSIframeGadget.ready =
RenderJSGadget.ready; RenderJSGadget.ready;
RenderJSIframeGadget.prototype = new RenderJSGadget(); RenderJSIframeGadget.prototype = new RenderJSGadget();
...@@ -850,12 +913,11 @@ ...@@ -850,12 +913,11 @@
///////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////
// privateDeclareIframeGadget // privateDeclareIframeGadget
///////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////
function privateDeclareIframeGadget(url, options) { function privateDeclareIframeGadget(url, options, parent_gadget) {
var gadget_instance, var gadget_instance,
iframe, iframe,
node, node,
iframe_loading_deferred = RSVP.defer(); iframe_loading_deferred = RSVP.defer();
if (options.element === undefined) { if (options.element === undefined) {
throw new Error("DOM element is required to create Iframe Gadget " + throw new Error("DOM element is required to create Iframe Gadget " +
url); url);
...@@ -875,60 +937,58 @@ ...@@ -875,60 +937,58 @@
} }
gadget_instance = new RenderJSIframeGadget(); gadget_instance = new RenderJSIframeGadget();
setAqParent(gadget_instance, parent_gadget);
iframe = document.createElement("iframe"); iframe = document.createElement("iframe");
// gadget_instance.element.setAttribute("seamless", "seamless"); // gadget_instance.element.setAttribute("seamless", "seamless");
iframe.setAttribute("src", url); iframe.setAttribute("src", url);
gadget_instance.path = url; gadget_instance.__path = url;
gadget_instance.element = options.element; gadget_instance.__element = options.element;
// Attach it to the DOM // Attach it to the DOM
options.element.appendChild(iframe); options.element.appendChild(iframe);
// XXX Manage unbind when deleting the gadget // XXX Manage unbind when deleting the gadget
// Create the communication channel with the iframe // Create the communication channel with the iframe
gadget_instance.chan = Channel.build({ gadget_instance.__chan = Channel.build({
window: iframe.contentWindow, window: iframe.contentWindow,
origin: "*", origin: "*",
scope: "renderJS" scope: "renderJS"
}); });
// Create new method from the declareMethod call inside the iframe // Create new method from the declareMethod call inside the iframe
gadget_instance.chan.bind("declareMethod", function (trans, method_name) { gadget_instance.__chan.bind("declareMethod",
gadget_instance[method_name] = function () { function (trans, method_name) {
var argument_list = arguments; gadget_instance[method_name] = function () {
return new RSVP.Promise(function (resolve, reject) { var argument_list = arguments;
gadget_instance.chan.call({ return new RSVP.Promise(function (resolve, reject) {
method: "methodCall", gadget_instance.__chan.call({
params: [ method: "methodCall",
method_name, params: [
Array.prototype.slice.call(argument_list, 0)], method_name,
success: function (s) { Array.prototype.slice.call(argument_list, 0)],
resolve(s); success: function (s) {
}, resolve(s);
error: function (e) { },
reject(e); error: function (e) {
} reject(e);
}
});
}); });
}); };
}; return "OK";
return "OK"; });
});
// Wait for the iframe to be loaded before continuing // Wait for the iframe to be loaded before continuing
gadget_instance.chan.bind("ready", function (trans) { gadget_instance.__chan.bind("ready", function (trans) {
iframe_loading_deferred.resolve(gadget_instance); iframe_loading_deferred.resolve(gadget_instance);
return "OK"; return "OK";
}); });
gadget_instance.chan.bind("failed", function (trans, params) { gadget_instance.__chan.bind("failed", function (trans, params) {
iframe_loading_deferred.reject(params); iframe_loading_deferred.reject(params);
return "OK"; return "OK";
}); });
gadget_instance.chan.bind("trigger", function (trans, params) { gadget_instance.__chan.bind("acquire", function (trans, params) {
return gadget_instance.trigger(params.event_name, params.options); gadget_instance.__aq_parent.apply(gadget_instance, params)
});
gadget_instance.chan.bind("acquire", function (trans, params) {
gadget_instance.acquire.apply(gadget_instance, params)
.then(function (g) { .then(function (g) {
trans.complete(g); trans.complete(g);
}).fail(function (e) { }).fail(function (e) {
...@@ -948,71 +1008,88 @@ ...@@ -948,71 +1008,88 @@
///////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////
// RenderJSGadget.declareGadget // RenderJSGadget.declareGadget
///////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////
RenderJSGadget.prototype.declareGadget = function (url, options) { RenderJSGadget
var queue, .declareMethod('declareGadget', function (url, options) {
parent_gadget = this, var queue,
previous_loading_gadget_promise = loading_gadget_promise; parent_gadget = this,
previous_loading_gadget_promise = loading_gadget_promise;
if (options === undefined) { if (options === undefined) {
options = {}; options = {};
} }
if (options.sandbox === undefined) { if (options.sandbox === undefined) {
options.sandbox = "public"; options.sandbox = "public";
} }
// Change the global variable to update the loading queue // transform url to absolute url if it is relative
queue = new RSVP.Queue() url = renderJS.getAbsoluteURL(url, this.__path);
// Wait for previous gadget loading to finish first // Change the global variable to update the loading queue
.push(function () { queue = new RSVP.Queue()
return previous_loading_gadget_promise; // Wait for previous gadget loading to finish first
}) .push(function () {
.push(undefined, function () { return previous_loading_gadget_promise;
// Forget previous declareGadget error })
return; .push(undefined, function () {
}) // Forget previous declareGadget error
.push(function () { return;
var method; })
if (options.sandbox === "public") { .push(function () {
method = privateDeclarePublicGadget; var method;
} else if (options.sandbox === "iframe") { if (options.sandbox === "public") {
method = privateDeclareIframeGadget; method = privateDeclarePublicGadget;
} else { } else if (options.sandbox === "iframe") {
throw new Error("Unsupported sandbox options '" + method = privateDeclareIframeGadget;
options.sandbox + "'"); } else {
} throw new Error("Unsupported sandbox options '" +
return method(url, options); options.sandbox + "'");
}) }
// Set the HTML context return method(url, options, parent_gadget);
.push(function (gadget_instance) { })
var i; // Set the HTML context
// Define aq_parent to reach parent gadget .push(function (gadget_instance) {
gadget_instance.aq_parent = function (method_name, argument_list) { var i;
return parent_gadget.acquire(method_name, argument_list); // Drop the current loading klass info used by selector
}; gadget_loading_klass = undefined;
// Drop the current loading klass info used by selector // Trigger calling of all ready callback
gadget_loading_klass = undefined; function ready_wrapper() {
// Trigger calling of all ready callback return gadget_instance;
function ready_wrapper() { }
for (i = 0; i < gadget_instance.constructor.__ready_list.length;
i += 1) {
// Put a timeout?
queue.push(gadget_instance.constructor.__ready_list[i]);
// Always return the gadget instance after ready function
queue.push(ready_wrapper);
}
// Store local reference to the gadget instance
if (options.scope !== undefined) {
parent_gadget.__sub_gadget_dict[options.scope] = gadget_instance;
}
return gadget_instance; return gadget_instance;
} })
for (i = 0; i < gadget_instance.constructor.ready_list.length; .push(undefined, function (e) {
i += 1) { // Drop the current loading klass info used by selector
// Put a timeout? // even in case of error
queue.push(gadget_instance.constructor.ready_list[i]); gadget_loading_klass = undefined;
// Always return the gadget instance after ready function throw e;
queue.push(ready_wrapper); });
} loading_gadget_promise = queue;
return gadget_instance; return loading_gadget_promise;
}) })
.push(undefined, function (e) { .declareMethod('getDeclaredGadget', function (gadget_scope) {
// Drop the current loading klass info used by selector if (!this.__sub_gadget_dict.hasOwnProperty(gadget_scope)) {
// even in case of error throw new Error("Gadget scope '" + gadget_scope + "' is not known.");
gadget_loading_klass = undefined; }
throw e; return this.__sub_gadget_dict[gadget_scope];
}); })
loading_gadget_promise = queue; .declareMethod('dropGadget', function (gadget_scope) {
return loading_gadget_promise; if (!this.__sub_gadget_dict.hasOwnProperty(gadget_scope)) {
}; throw new Error("Gadget scope '" + gadget_scope + "' is not known.");
}
// http://perfectionkills.com/understanding-delete/
delete this.__sub_gadget_dict[gadget_scope];
});
///////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////
// renderJS selector // renderJS selector
...@@ -1044,6 +1121,27 @@ ...@@ -1044,6 +1121,27 @@
renderJS.AcquisitionError.prototype.constructor = renderJS.AcquisitionError.prototype.constructor =
renderJS.AcquisitionError; renderJS.AcquisitionError;
/////////////////////////////////////////////////////////////////
// renderJS.getAbsoluteURL
/////////////////////////////////////////////////////////////////
renderJS.getAbsoluteURL = function (url, base_url) {
var doc, base, link,
html = "<!doctype><html><head></head></html>",
isAbsoluteOrDataURL = new RegExp('^(?:[a-z]+:)?//|data:', 'i');
if (url && base_url && !isAbsoluteOrDataURL.test(url)) {
doc = (new DOMParser()).parseFromString(html, 'text/html');
base = doc.createElement('base');
link = doc.createElement('link');
doc.head.appendChild(base);
doc.head.appendChild(link);
base.href = base_url;
link.href = url;
return link.href;
}
return url;
};
///////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////
// renderJS.declareJS // renderJS.declareJS
///////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////
...@@ -1119,25 +1217,31 @@ ...@@ -1119,25 +1217,31 @@
tmp_constructor = function () { tmp_constructor = function () {
RenderJSGadget.call(this); RenderJSGadget.call(this);
}; };
tmp_constructor.ready_list = []; tmp_constructor.__ready_list = RenderJSGadget.__ready_list.slice();
tmp_constructor.declareMethod = tmp_constructor.declareMethod =
RenderJSGadget.declareMethod; RenderJSGadget.declareMethod;
tmp_constructor.declareAcquiredMethod =
RenderJSGadget.declareAcquiredMethod;
tmp_constructor.allowPublicAcquisition =
RenderJSGadget.allowPublicAcquisition;
tmp_constructor.ready = tmp_constructor.ready =
RenderJSGadget.ready; RenderJSGadget.ready;
tmp_constructor.prototype = new RenderJSGadget(); tmp_constructor.prototype = new RenderJSGadget();
tmp_constructor.prototype.constructor = tmp_constructor; tmp_constructor.prototype.constructor = tmp_constructor;
tmp_constructor.prototype.path = url; tmp_constructor.prototype.__path = url;
tmp_constructor.prototype.__acquired_method_dict = {};
// https://developer.mozilla.org/en-US/docs/HTML_in_XMLHttpRequest // https://developer.mozilla.org/en-US/docs/HTML_in_XMLHttpRequest
// https://developer.mozilla.org/en-US/docs/Web/API/DOMParser // https://developer.mozilla.org/en-US/docs/Web/API/DOMParser
// https://developer.mozilla.org/en-US/docs/Code_snippets/HTML_to_DOM // https://developer.mozilla.org/en-US/docs/Code_snippets/HTML_to_DOM
tmp_constructor.template_element = tmp_constructor.__template_element =
(new DOMParser()).parseFromString(xhr.responseText, "text/html"); (new DOMParser()).parseFromString(xhr.responseText, "text/html");
parsed_html = renderJS.parseGadgetHTMLDocument( parsed_html = renderJS.parseGadgetHTMLDocument(
tmp_constructor.template_element tmp_constructor.__template_element,
url
); );
for (key in parsed_html) { for (key in parsed_html) {
if (parsed_html.hasOwnProperty(key)) { if (parsed_html.hasOwnProperty(key)) {
tmp_constructor.prototype[key] = parsed_html[key]; tmp_constructor.prototype['__' + key] = parsed_html[key];
} }
} }
...@@ -1208,7 +1312,7 @@ ...@@ -1208,7 +1312,7 @@
///////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////
// renderJS.parseGadgetHTMLDocument // renderJS.parseGadgetHTMLDocument
///////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////
renderJS.parseGadgetHTMLDocument = function (document_element) { renderJS.parseGadgetHTMLDocument = function (document_element, url) {
var settings = { var settings = {
title: "", title: "",
interface_list: [], interface_list: [],
...@@ -1216,7 +1320,13 @@ ...@@ -1216,7 +1320,13 @@
required_js_list: [] required_js_list: []
}, },
i, i,
element; element,
isAbsoluteURL = new RegExp('^(?:[a-z]+:)?//', 'i');
if (!url || !isAbsoluteURL.test(url)) {
throw new Error("The second parameter should be an absolute url");
}
if (document_element.nodeType === 9) { if (document_element.nodeType === 9) {
settings.title = document_element.title; settings.title = document_element.title;
...@@ -1226,11 +1336,19 @@ ...@@ -1226,11 +1336,19 @@
// XXX Manage relative URL during extraction of URLs // XXX Manage relative URL during extraction of URLs
// element.href returns absolute URL in firefox but "" in chrome; // element.href returns absolute URL in firefox but "" in chrome;
if (element.rel === "stylesheet") { if (element.rel === "stylesheet") {
settings.required_css_list.push(element.getAttribute("href")); settings.required_css_list.push(
} else if (element.type === "text/javascript") { renderJS.getAbsoluteURL(element.getAttribute("href"), url)
settings.required_js_list.push(element.getAttribute("src")); );
} else if (element.nodeName === "SCRIPT" &&
(element.type === "text/javascript" ||
!element.type)) {
settings.required_js_list.push(
renderJS.getAbsoluteURL(element.getAttribute("src"), url)
);
} else if (element.rel === "http://www.renderjs.org/rel/interface") { } else if (element.rel === "http://www.renderjs.org/rel/interface") {
settings.interface_list.push(element.getAttribute("href")); settings.interface_list.push(
renderJS.getAbsoluteURL(element.getAttribute("href"), url)
);
} }
} }
} }
...@@ -1244,25 +1362,24 @@ ...@@ -1244,25 +1362,24 @@
// global // global
///////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////
window.rJS = window.renderJS = renderJS; window.rJS = window.renderJS = renderJS;
window.RenderJSGadget = RenderJSGadget; window.__RenderJSGadget = RenderJSGadget;
window.RenderJSEmbeddedGadget = RenderJSEmbeddedGadget; window.__RenderJSEmbeddedGadget = RenderJSEmbeddedGadget;
window.RenderJSIframeGadget = RenderJSIframeGadget; window.__RenderJSIframeGadget = RenderJSIframeGadget;
/////////////////////////////////////////////////// ///////////////////////////////////////////////////
// Bootstrap process. Register the self gadget. // Bootstrap process. Register the self gadget.
/////////////////////////////////////////////////// ///////////////////////////////////////////////////
function bootstrap() { function bootstrap() {
var url = window.location.href, var url = removeHash(window.location.href),
tmp_constructor, tmp_constructor,
root_gadget, root_gadget,
declare_method_count = 0, declare_method_count = 0,
embedded_channel, embedded_channel,
notifyReady, notifyReady,
notifyDeclareMethod, notifyDeclareMethod,
notifyTrigger, gadget_ready = false,
gadget_ready = false; last_acquisition_gadget;
// Create the gadget class for the current url // Create the gadget class for the current url
if (gadget_model_dict.hasOwnProperty(url)) { if (gadget_model_dict.hasOwnProperty(url)) {
...@@ -1270,28 +1387,41 @@ ...@@ -1270,28 +1387,41 @@
} }
loading_gadget_promise = new RSVP.Promise(function (resolve, reject) { loading_gadget_promise = new RSVP.Promise(function (resolve, reject) {
if (window.self === window.top) { if (window.self === window.top) {
last_acquisition_gadget = new RenderJSGadget();
last_acquisition_gadget.__acquired_method_dict = {
getTopURL: function () {
return url;
}
};
// Stop acquisition on the last acquisition gadget
// Do not put this on the klass, as their could be multiple instances
last_acquisition_gadget.__aq_parent = function (method_name) {
throw new renderJS.AcquisitionError(
"No gadget provides " + method_name
);
};
// XXX Copy/Paste from declareGadgetKlass // XXX Copy/Paste from declareGadgetKlass
tmp_constructor = function () { tmp_constructor = function () {
RenderJSGadget.call(this); RenderJSGadget.call(this);
}; };
tmp_constructor.declareMethod = RenderJSGadget.declareMethod; tmp_constructor.declareMethod = RenderJSGadget.declareMethod;
tmp_constructor.ready_list = []; tmp_constructor.declareAcquiredMethod =
RenderJSGadget.declareAcquiredMethod;
tmp_constructor.allowPublicAcquisition =
RenderJSGadget.allowPublicAcquisition;
tmp_constructor.__ready_list = RenderJSGadget.__ready_list.slice();
tmp_constructor.ready = RenderJSGadget.ready; tmp_constructor.ready = RenderJSGadget.ready;
tmp_constructor.prototype = new RenderJSGadget(); tmp_constructor.prototype = new RenderJSGadget();
tmp_constructor.prototype.constructor = tmp_constructor; tmp_constructor.prototype.constructor = tmp_constructor;
tmp_constructor.prototype.path = url; tmp_constructor.prototype.__path = url;
gadget_model_dict[url] = tmp_constructor; gadget_model_dict[url] = tmp_constructor;
// Create the root gadget instance and put it in the loading stack // Create the root gadget instance and put it in the loading stack
root_gadget = new gadget_model_dict[url](); root_gadget = new gadget_model_dict[url]();
// Stop acquisition on the original root gadget setAqParent(root_gadget, last_acquisition_gadget);
// Do not put this on the klass, as their could be multiple instances
root_gadget.aq_parent = function (method_name) {
throw new renderJS.AcquisitionError(
"No gadget provides " + method_name
);
};
} else { } else {
// Create the communication channel // Create the communication channel
...@@ -1302,6 +1432,8 @@ ...@@ -1302,6 +1432,8 @@
}); });
// Create the root gadget instance and put it in the loading stack // Create the root gadget instance and put it in the loading stack
tmp_constructor = RenderJSEmbeddedGadget; tmp_constructor = RenderJSEmbeddedGadget;
tmp_constructor.__ready_list = RenderJSGadget.__ready_list.slice();
tmp_constructor.prototype.__path = url;
root_gadget = new RenderJSEmbeddedGadget(); root_gadget = new RenderJSEmbeddedGadget();
// Bind calls to renderJS method on the instance // Bind calls to renderJS method on the instance
...@@ -1353,28 +1485,13 @@ ...@@ -1353,28 +1485,13 @@
return result; return result;
}; };
notifyTrigger = function (eventName, options) { tmp_constructor.declareAcquiredMethod =
embedded_channel.notify({ RenderJSGadget.declareAcquiredMethod;
method: "trigger", tmp_constructor.allowPublicAcquisition =
params: { RenderJSGadget.allowPublicAcquisition;
event_name: eventName,
options: options
}
});
};
// Surcharge trigger to inform parent window // Define __aq_parent to inform parent window
tmp_constructor.prototype.trigger = function (eventName, options) { tmp_constructor.prototype.__aq_parent = function (method_name,
var result = RenderJSGadget.prototype.trigger.apply(
this,
[eventName, options]
);
notifyTrigger(eventName, options);
return result;
};
// Define aq_parent to inform parent window
tmp_constructor.prototype.aq_parent = function (method_name,
argument_list) { argument_list) {
return new RSVP.Promise(function (resolve, reject) { return new RSVP.Promise(function (resolve, reject) {
embedded_channel.call({ embedded_channel.call({
...@@ -1394,23 +1511,24 @@ ...@@ -1394,23 +1511,24 @@
}; };
} }
tmp_constructor.prototype.__acquired_method_dict = {};
gadget_loading_klass = tmp_constructor; gadget_loading_klass = tmp_constructor;
function init() { function init() {
// XXX HTML properties can only be set when the DOM is fully loaded // XXX HTML properties can only be set when the DOM is fully loaded
var settings = renderJS.parseGadgetHTMLDocument(document), var settings = renderJS.parseGadgetHTMLDocument(document, url),
j, j,
key; key;
for (key in settings) { for (key in settings) {
if (settings.hasOwnProperty(key)) { if (settings.hasOwnProperty(key)) {
tmp_constructor.prototype[key] = settings[key]; tmp_constructor.prototype['__' + key] = settings[key];
} }
} }
tmp_constructor.template_element = document.createElement("div"); tmp_constructor.__template_element = document.createElement("div");
root_gadget.element = document.body; root_gadget.__element = document.body;
for (j = 0; j < root_gadget.element.childNodes.length; j += 1) { for (j = 0; j < root_gadget.__element.childNodes.length; j += 1) {
tmp_constructor.template_element.appendChild( tmp_constructor.__template_element.appendChild(
root_gadget.element.childNodes[j].cloneNode(true) root_gadget.__element.childNodes[j].cloneNode(true)
); );
} }
RSVP.all([root_gadget.getRequiredJSList(), RSVP.all([root_gadget.getRequiredJSList(),
...@@ -1431,10 +1549,23 @@ ...@@ -1431,10 +1549,23 @@
function ready_wrapper() { function ready_wrapper() {
return root_gadget; return root_gadget;
} }
if (window.top !== window.self) {
tmp_constructor.ready(function () {
var base = document.createElement('base');
return root_gadget.__aq_parent('getTopURL', [])
.then(function (topURL) {
base.href = topURL;
base.target = "_top";
document.head.appendChild(base);
});
});
}
queue.push(ready_wrapper); queue.push(ready_wrapper);
for (i = 0; i < tmp_constructor.ready_list.length; i += 1) { for (i = 0; i < tmp_constructor.__ready_list.length; i += 1) {
// Put a timeout? // Put a timeout?
queue.push(tmp_constructor.ready_list[i]) queue.push(tmp_constructor.__ready_list[i])
// Always return the gadget instance after ready function // Always return the gadget instance after ready function
.push(ready_wrapper); .push(ready_wrapper);
} }
......
var Channel=function(){"use strict";function a(a,b,c,d){function f(b){for(var c=0;c<b.length;c++)if(b[c].win===a)return!0;return!1}var g=!1;if("*"===b){for(var h in e)if(e.hasOwnProperty(h)&&"*"!==h&&"object"==typeof e[h][c]&&(g=f(e[h][c])))break}else e["*"]&&e["*"][c]&&(g=f(e["*"][c])),!g&&e[b]&&e[b][c]&&(g=f(e[b][c]));if(g)throw"A channel is already bound to the same window which overlaps with origin '"+b+"' and has scope '"+c+"'";"object"!=typeof e[b]&&(e[b]={}),"object"!=typeof e[b][c]&&(e[b][c]=[]),e[b][c].push({win:a,handler:d})}function b(a,b,c){for(var d=e[b][c],f=0;f<d.length;f++)d[f].win===a&&d.splice(f,1);0===e[b][c].length&&delete e[b][c]}function c(a){return Array.isArray?Array.isArray(a):-1!=a.constructor.toString().indexOf("Array")}var d=Math.floor(1000001*Math.random()),e={},f={},g=function(a){try{var b=JSON.parse(a.data);if("object"!=typeof b||null===b)throw"malformed"}catch(a){return}var c,d,g,h=a.source,i=a.origin;if("string"==typeof b.method){var j=b.method.split("::");2==j.length?(c=j[0],g=j[1]):g=b.method}if("undefined"!=typeof b.id&&(d=b.id),"string"==typeof g){var k=!1;if(e[i]&&e[i][c])for(var l=0;l<e[i][c].length;l++)if(e[i][c][l].win===h){e[i][c][l].handler(i,g,b),k=!0;break}if(!k&&e["*"]&&e["*"][c])for(var l=0;l<e["*"][c].length;l++)if(e["*"][c][l].win===h){e["*"][c][l].handler(i,g,b);break}}else"undefined"!=typeof d&&f[d]&&f[d](i,g,b)};return window.addEventListener?window.addEventListener("message",g,!1):window.attachEvent&&window.attachEvent("onmessage",g),{build:function(e){var g=function(a){if(e.debugOutput&&window.console&&window.console.log){try{"string"!=typeof a&&(a=JSON.stringify(a))}catch(b){}console.log("["+j+"] "+a)}};if(!window.postMessage)throw"jschannel cannot run this browser, no postMessage";if(!window.JSON||!window.JSON.stringify||!window.JSON.parse)throw"jschannel cannot run this browser, no JSON parsing/serialization";if("object"!=typeof e)throw"Channel build invoked without a proper object argument";if(!e.window||!e.window.postMessage)throw"Channel.build() called without a valid window argument";if(window===e.window)throw"target window is same as present window -- not allowed";var h=!1;if("string"==typeof e.origin){var i;"*"===e.origin?h=!0:null!==(i=e.origin.match(/^https?:\/\/(?:[-a-zA-Z0-9_\.])+(?::\d+)?/))&&(e.origin=i[0].toLowerCase(),h=!0)}if(!h)throw"Channel.build() called with an invalid origin";if("undefined"!=typeof e.scope){if("string"!=typeof e.scope)throw"scope, when specified, must be a string";if(e.scope.split("::").length>1)throw"scope may not contain double colons: '::'"}var j=function(){for(var a="",b="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",c=0;5>c;c++)a+=b.charAt(Math.floor(Math.random()*b.length));return a}(),k={},l={},m={},n=!1,o=[],p=function(a,b,c){var d=!1,e=!1;return{origin:b,invoke:function(b,d){if(!m[a])throw"attempting to invoke a callback of a nonexistent transaction: "+a;for(var e=!1,f=0;f<c.length;f++)if(b===c[f]){e=!0;break}if(!e)throw"request supports no such callback '"+b+"'";t({id:a,callback:b,params:d})},error:function(b,c){if(e=!0,!m[a])throw"error called for nonexistent message: "+a;delete m[a],t({id:a,error:b,message:c})},complete:function(b){if(e=!0,!m[a])throw"complete called for nonexistent message: "+a;delete m[a],t({id:a,result:b})},delayReturn:function(a){return"boolean"==typeof a&&(d=a===!0),d},completed:function(){return e}}},q=function(a,b,c){return window.setTimeout(function(){if(l[a]){var d="timeout ("+b+"ms) exceeded on method '"+c+"'";l[a].error("timeout_error",d),delete l[a],delete f[a]}},b)},r=function(a,b,d){if("function"==typeof e.gotMessageObserver)try{e.gotMessageObserver(a,d)}catch(h){g("gotMessageObserver() raised an exception: "+h.toString())}if(d.id&&b){if(k[b]){var i=p(d.id,a,d.callbacks?d.callbacks:[]);m[d.id]={};try{if(d.callbacks&&c(d.callbacks)&&d.callbacks.length>0)for(var j=0;j<d.callbacks.length;j++){for(var n=d.callbacks[j],o=d.params,q=n.split("/"),r=0;r<q.length-1;r++){var s=q[r];"object"!=typeof o[s]&&(o[s]={}),o=o[s]}o[q[q.length-1]]=function(){var a=n;return function(b){return i.invoke(a,b)}}()}var t=k[b](i,d.params);i.delayReturn()||i.completed()||i.complete(t)}catch(h){var u="runtime_error",v=null;if("string"==typeof h?v=h:"object"==typeof h&&(h&&c(h)&&2==h.length?(u=h[0],v=h[1]):"string"==typeof h.error&&(u=h.error,h.message?"string"==typeof h.message?v=h.message:h=h.message:v="")),null===v)try{v=JSON.stringify(h),"undefined"==typeof v&&(v=h.toString())}catch(w){v=h.toString()}i.error(u,v)}}}else d.id&&d.callback?l[d.id]&&l[d.id].callbacks&&l[d.id].callbacks[d.callback]?l[d.id].callbacks[d.callback](d.params):g("ignoring invalid callback, id:"+d.id+" ("+d.callback+")"):d.id?l[d.id]?(d.error?l[d.id].error(d.error,d.message):void 0!==d.result?l[d.id].success(d.result):l[d.id].success(),delete l[d.id],delete f[d.id]):g("ignoring invalid response: "+d.id):b&&k[b]&&k[b]({origin:a},d.params)};a(e.window,e.origin,"string"==typeof e.scope?e.scope:"",r);var s=function(a){return"string"==typeof e.scope&&e.scope.length&&(a=[e.scope,a].join("::")),a},t=function(a,b){if(!a)throw"postMessage called with null message";var c=n?"post ":"queue ";if(g(c+" message: "+JSON.stringify(a)),b||n){if("function"==typeof e.postMessageObserver)try{e.postMessageObserver(e.origin,a)}catch(d){g("postMessageObserver() raised an exception: "+d.toString())}e.window.postMessage(JSON.stringify(a),e.origin)}else o.push(a)},u=function(a,b){if(g("ready msg received"),n)throw"received ready message while in ready state. help!";for(j+="ping"===b?"-R":"-L",v.unbind("__ready"),n=!0,g("ready msg accepted."),"ping"===b&&v.notify({method:"__ready",params:"pong"});o.length;)t(o.pop());"function"==typeof e.onReady&&e.onReady(v)},v={unbind:function(a){if(k[a]){if(!delete k[a])throw"can't delete method: "+a;return!0}return!1},bind:function(a,b){if(!a||"string"!=typeof a)throw"'method' argument to bind must be string";if(!b||"function"!=typeof b)throw"callback missing from bind params";if(k[a])throw"method '"+a+"' is already bound!";return k[a]=b,this},call:function(a){if(!a)throw"missing arguments to call function";if(!a.method||"string"!=typeof a.method)throw"'method' argument to call must be string";if(!a.success||"function"!=typeof a.success)throw"'success' callback missing from call";var b={},c=[],e=function(a,d){if("object"==typeof d)for(var f in d)if(d.hasOwnProperty(f)){var g=a+(a.length?"/":"")+f;"function"==typeof d[f]?(b[g]=d[f],c.push(g),delete d[f]):"object"==typeof d[f]&&e(g,d[f])}};e("",a.params);var g={id:d,method:s(a.method),params:a.params};c.length&&(g.callbacks=c),a.timeout&&q(d,a.timeout,s(a.method)),l[d]={callbacks:b,error:a.error,success:a.success},f[d]=r,d++,t(g)},notify:function(a){if(!a)throw"missing arguments to notify function";if(!a.method||"string"!=typeof a.method)throw"'method' argument to notify must be string";t({method:s(a.method),params:a.params})},destroy:function(){b(e.window,e.origin,"string"==typeof e.scope?e.scope:""),window.removeEventListener?window.removeEventListener("message",r,!1):window.detachEvent&&window.detachEvent("onmessage",r),n=!1,k={},m={},l={},e.origin=null,o=[],g("channel destroyed"),j=""}};return v.bind("__ready",u),setTimeout(function(){t({method:s("__ready"),params:"ping"},!0)},0),v}}}();!function(a){"use strict";var b=a.prototype,c=b.parseFromString;try{if((new a).parseFromString("","text/html"))return}catch(d){}b.parseFromString=function(a,b){var d,e,f,g;return/^\s*text\/html\s*(?:;|$)/i.test(b)?(e=document.implementation.createHTMLDocument(""),f=e.documentElement,f.innerHTML=a,g=f.firstElementChild,1===f.childElementCount&&"html"===g.localName.toLowerCase()&&e.replaceChild(g,f),d=e):d=c.apply(this,arguments),d}}(DOMParser),function(a,b,c,d,e,f){"use strict";function g(){return this instanceof g?void 0:new g}function h(){return this instanceof h?(g.call(this),void 0):new h}function i(b,d){function e(a,b){return function(){return a(b)}}var g;return d.element===f&&(d.element=a.createElement("div")),(new c.Queue).push(function(){return o.declareGadgetKlass(b)}).push(function(a){var b,e=a.template_element.body.childNodes;for(m=a,g=new a,g.element=d.element,b=0;b<e.length;b+=1)g.element.appendChild(e[b].cloneNode(!0));return c.all([g.getRequiredJSList(),g.getRequiredCSSList()])}).push(function(a){var b,d=new c.Queue;for(b=0;b<a[0].length;b+=1)d.push(e(o.declareJS,a[0][b]));for(b=0;b<a[1].length;b+=1)d.push(e(o.declareCSS,a[1][b]));return d}).push(function(){return g})}function j(){return this instanceof j?(g.call(this),void 0):new j}function k(b,d){var g,h,i,k=c.defer();if(d.element===f)throw new Error("DOM element is required to create Iframe Gadget "+b);for(i=d.element.parentNode;null!==i&&i!==a;)i=i.parentNode;if(null===i)throw new Error("The parent element is not attached to the DOM for "+b);return g=new j,h=a.createElement("iframe"),h.setAttribute("src",b),g.path=b,g.element=d.element,d.element.appendChild(h),g.chan=e.build({window:h.contentWindow,origin:"*",scope:"renderJS"}),g.chan.bind("declareMethod",function(a,b){return g[b]=function(){var a=arguments;return new c.Promise(function(c,d){g.chan.call({method:"methodCall",params:[b,Array.prototype.slice.call(a,0)],success:function(a){c(a)},error:function(a){d(a)}})})},"OK"}),g.chan.bind("ready",function(){return k.resolve(g),"OK"}),g.chan.bind("failed",function(a,b){return k.reject(b),"OK"}),g.chan.bind("trigger",function(a,b){return g.trigger(b.event_name,b.options)}),g.chan.bind("acquire",function(a,b){g.acquire.apply(g,b).then(function(b){a.complete(b)}).fail(function(b){a.error(b.toString())}),a.delayReturn(!0)}),c.any([k.promise,c.timeout(5e3)])}function l(){var d,i,j,k,l,s,t=b.location.href,u=0,v=!1;if(p.hasOwnProperty(t))throw new Error("bootstrap should not be called twice");n=new c.Promise(function(n,w){function x(){var b,e,g=o.parseGadgetHTMLDocument(a);for(e in g)g.hasOwnProperty(e)&&(d.prototype[e]=g[e]);for(d.template_element=a.createElement("div"),i.element=a.body,b=0;b<i.element.childNodes.length;b+=1)d.template_element.appendChild(i.element.childNodes[b].cloneNode(!0));c.all([i.getRequiredJSList(),i.getRequiredCSSList()]).then(function(a){function b(){return i}var e,g,h=a[0],j=a[1];for(e=0;e<h.length;e+=1)q[h[e]]=null;for(e=0;e<j.length;e+=1)r[j[e]]=null;for(m=f,g=new c.Queue,g.push(b),e=0;e<d.ready_list.length;e+=1)g.push(d.ready_list[e]).push(b);return g.push(n,function(a){throw w(a),a}),g}).fail(function(a){w(a),console.error(a)})}b.self===b.top?(d=function(){g.call(this)},d.declareMethod=g.declareMethod,d.ready_list=[],d.ready=g.ready,d.prototype=new g,d.prototype.constructor=d,d.prototype.path=t,p[t]=d,i=new p[t],i.aq_parent=function(a){throw new o.AcquisitionError("No gadget provides "+a)}):(j=e.build({window:b.parent,origin:"*",scope:"renderJS"}),d=h,i=new h,j.bind("methodCall",function(a,b){i[b[0]].apply(i,b[1]).then(function(b){a.complete(b)}).fail(function(b){a.error(b.toString())}),a.delayReturn(!0)}),k=function(){0===u&&v===!0&&j.notify({method:"ready"})},l=function(a){u+=1,j.call({method:"declareMethod",params:a,success:function(){u-=1,k()},error:function(){u-=1}})},l("getInterfaceList"),l("getRequiredCSSList"),l("getRequiredJSList"),l("getPath"),l("getTitle"),d.declareMethod=function(a,b){var c=g.declareMethod.apply(this,[a,b]);return l(a),c},s=function(a,b){j.notify({method:"trigger",params:{event_name:a,options:b}})},d.prototype.trigger=function(a,b){var c=g.prototype.trigger.apply(this,[a,b]);return s(a,b),c},d.prototype.aq_parent=function(a,b){return new c.Promise(function(c,d){j.call({method:"acquire",params:[a,b],success:function(a){c(a)},error:function(a){d(a)}})})}),m=d,a.addEventListener("DOMContentLoaded",x,!1)}),b.self!==b.top&&n.then(function(){v=!0,k()}).fail(function(a){throw j.notify({method:"failed",params:a.toString()}),a})}var m,n,o,p={},q={},r={};g.prototype.title="",g.prototype.interface_list=[],g.prototype.path="",g.prototype.html="",g.prototype.required_css_list=[],g.prototype.required_js_list=[],c.EventTarget.mixin(g.prototype),g.ready_list=[],g.ready=function(a){return this.ready_list.push(a),this},g.declareMethod=function(a,b){return this.prototype[a]=function(){var a=this,d=arguments;return(new c.Queue).push(function(){return b.apply(a,d)})},this},g.declareMethod("getInterfaceList",function(){return this.interface_list}).declareMethod("getRequiredCSSList",function(){return this.required_css_list}).declareMethod("getRequiredJSList",function(){return this.required_js_list}).declareMethod("getPath",function(){return this.path}).declareMethod("getTitle",function(){return this.title}).declareMethod("getElement",function(){if(this.element===f)throw new Error("No element defined");return this.element}).declareMethod("acquire",function(){var a=this,b=arguments;return(new c.Queue).push(function(){var c=a.aq_dynamic;if(c!==f)return c.apply(a,b);throw new o.AcquisitionError("aq_dynamic is not defined")}).push(f,function(c){if(c instanceof o.AcquisitionError)return a.aq_parent.apply(a,b);throw c})}),h.ready_list=[],h.ready=g.ready,h.prototype=new g,h.prototype.constructor=h,j.ready_list=[],j.ready=g.ready,j.prototype=new g,j.prototype.constructor=j,g.prototype.declareGadget=function(a,b){var d,e=this,g=n;return b===f&&(b={}),b.sandbox===f&&(b.sandbox="public"),d=(new c.Queue).push(function(){return g}).push(f,function(){}).push(function(){var c;if("public"===b.sandbox)c=i;else{if("iframe"!==b.sandbox)throw new Error("Unsupported sandbox options '"+b.sandbox+"'");c=k}return c(a,b)}).push(function(a){function b(){return a}var c;for(a.aq_parent=function(a,b){return e.acquire(a,b)},m=f,c=0;c<a.constructor.ready_list.length;c+=1)d.push(a.constructor.ready_list[c]),d.push(b);return a}).push(f,function(a){throw m=f,a}),n=d},o=function(a){var c;if(a===b&&(c=m),c===f)throw new Error("Unknown selector '"+a+"'");return c},o.AcquisitionError=function(a){if(this.name="AcquisitionError",a!==f&&"string"!=typeof a)throw new TypeError("You must pass a string.");this.message=a||"Acquisition failed"},o.AcquisitionError.prototype=new Error,o.AcquisitionError.prototype.constructor=o.AcquisitionError,o.declareJS=function(b){var d;return d=q.hasOwnProperty(b)?c.resolve():new c.Promise(function(c,d){var e;e=a.createElement("script"),e.type="text/javascript",e.src=b,e.onload=function(){q[b]=null,c()},e.onerror=function(a){d(a)},a.head.appendChild(e)})},o.declareCSS=function(b){var d;return d=r.hasOwnProperty(b)?c.resolve():new c.Promise(function(c,d){var e;e=a.createElement("link"),e.rel="stylesheet",e.type="text/css",e.href=b,e.onload=function(){r[b]=null,c()},e.onerror=function(a){d(a)},a.head.appendChild(e)})},o.declareGadgetKlass=function(a){function b(){var b,c,e;if(!p.hasOwnProperty(a)){b=function(){g.call(this)},b.ready_list=[],b.declareMethod=g.declareMethod,b.ready=g.ready,b.prototype=new g,b.prototype.constructor=b,b.prototype.path=a,b.template_element=(new d).parseFromString(j.responseText,"text/html"),e=o.parseGadgetHTMLDocument(b.template_element);for(c in e)e.hasOwnProperty(c)&&(b.prototype[c]=e[c]);p[a]=b}return p[a]}function e(c,d){function e(){var a;try{0===j.readyState?d(j):4===j.readyState&&(j.status<200||j.status>=300||!/^text\/html[;]?/.test(j.getResponseHeader("Content-Type")||"")?d(j):(a=b(),c(a)))}catch(e){d(e)}}j=new XMLHttpRequest,j.open("GET",a),j.onreadystatechange=e,j.setRequestHeader("Accept","text/html"),j.withCredentials=!0,j.send()}function h(){j!==f&&j.readyState!==j.DONE&&j.abort()}var i,j;return i=p.hasOwnProperty(a)?c.resolve(p[a]):new c.Promise(e,h)},o.clearGadgetKlassList=function(){p={},q={},r={}},o.parseGadgetHTMLDocument=function(a){var b,c,d={title:"",interface_list:[],required_css_list:[],required_js_list:[]};if(9!==a.nodeType)throw new Error("The first parameter should be an HTMLDocument");for(d.title=a.title,b=0;b<a.head.children.length;b+=1)c=a.head.children[b],null!==c.href&&("stylesheet"===c.rel?d.required_css_list.push(c.getAttribute("href")):"text/javascript"===c.type?d.required_js_list.push(c.getAttribute("src")):"http://www.renderjs.org/rel/interface"===c.rel&&d.interface_list.push(c.getAttribute("href")));return d},b.rJS=b.renderJS=o,b.RenderJSGadget=g,b.RenderJSEmbeddedGadget=h,b.RenderJSIframeGadget=j,l()}(document,window,RSVP,DOMParser,Channel); var Channel=function(){"use strict";function a(a,b,c,d){function f(b){for(var c=0;c<b.length;c++)if(b[c].win===a)return!0;return!1}var g=!1;if("*"===b){for(var h in e)if(e.hasOwnProperty(h)&&"*"!==h&&"object"==typeof e[h][c]&&(g=f(e[h][c])))break}else e["*"]&&e["*"][c]&&(g=f(e["*"][c])),!g&&e[b]&&e[b][c]&&(g=f(e[b][c]));if(g)throw"A channel is already bound to the same window which overlaps with origin '"+b+"' and has scope '"+c+"'";"object"!=typeof e[b]&&(e[b]={}),"object"!=typeof e[b][c]&&(e[b][c]=[]),e[b][c].push({win:a,handler:d})}function b(a,b,c){for(var d=e[b][c],f=0;f<d.length;f++)d[f].win===a&&d.splice(f,1);0===e[b][c].length&&delete e[b][c]}function c(a){return Array.isArray?Array.isArray(a):-1!=a.constructor.toString().indexOf("Array")}var d=Math.floor(1000001*Math.random()),e={},f={},g=function(a){try{var b=JSON.parse(a.data);if("object"!=typeof b||null===b)throw"malformed"}catch(a){return}var c,d,g,h=a.source,i=a.origin;if("string"==typeof b.method){var j=b.method.split("::");2==j.length?(c=j[0],g=j[1]):g=b.method}if("undefined"!=typeof b.id&&(d=b.id),"string"==typeof g){var k=!1;if(e[i]&&e[i][c])for(var l=0;l<e[i][c].length;l++)if(e[i][c][l].win===h){e[i][c][l].handler(i,g,b),k=!0;break}if(!k&&e["*"]&&e["*"][c])for(var l=0;l<e["*"][c].length;l++)if(e["*"][c][l].win===h){e["*"][c][l].handler(i,g,b);break}}else"undefined"!=typeof d&&f[d]&&f[d](i,g,b)};return window.addEventListener?window.addEventListener("message",g,!1):window.attachEvent&&window.attachEvent("onmessage",g),{build:function(e){var g=function(a){if(e.debugOutput&&window.console&&window.console.log){try{"string"!=typeof a&&(a=JSON.stringify(a))}catch(b){}console.log("["+j+"] "+a)}};if(!window.postMessage)throw"jschannel cannot run this browser, no postMessage";if(!window.JSON||!window.JSON.stringify||!window.JSON.parse)throw"jschannel cannot run this browser, no JSON parsing/serialization";if("object"!=typeof e)throw"Channel build invoked without a proper object argument";if(!e.window||!e.window.postMessage)throw"Channel.build() called without a valid window argument";if(window===e.window)throw"target window is same as present window -- not allowed";var h=!1;if("string"==typeof e.origin){var i;"*"===e.origin?h=!0:null!==(i=e.origin.match(/^https?:\/\/(?:[-a-zA-Z0-9_\.])+(?::\d+)?/))&&(e.origin=i[0].toLowerCase(),h=!0)}if(!h)throw"Channel.build() called with an invalid origin";if("undefined"!=typeof e.scope){if("string"!=typeof e.scope)throw"scope, when specified, must be a string";if(e.scope.split("::").length>1)throw"scope may not contain double colons: '::'"}var j=function(){for(var a="",b="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",c=0;5>c;c++)a+=b.charAt(Math.floor(Math.random()*b.length));return a}(),k={},l={},m={},n=!1,o=[],p=function(a,b,c){var d=!1,e=!1;return{origin:b,invoke:function(b,d){if(!m[a])throw"attempting to invoke a callback of a nonexistent transaction: "+a;for(var e=!1,f=0;f<c.length;f++)if(b===c[f]){e=!0;break}if(!e)throw"request supports no such callback '"+b+"'";t({id:a,callback:b,params:d})},error:function(b,c){if(e=!0,!m[a])throw"error called for nonexistent message: "+a;delete m[a],t({id:a,error:b,message:c})},complete:function(b){if(e=!0,!m[a])throw"complete called for nonexistent message: "+a;delete m[a],t({id:a,result:b})},delayReturn:function(a){return"boolean"==typeof a&&(d=a===!0),d},completed:function(){return e}}},q=function(a,b,c){return window.setTimeout(function(){if(l[a]){var d="timeout ("+b+"ms) exceeded on method '"+c+"'";l[a].error("timeout_error",d),delete l[a],delete f[a]}},b)},r=function(a,b,d){if("function"==typeof e.gotMessageObserver)try{e.gotMessageObserver(a,d)}catch(h){g("gotMessageObserver() raised an exception: "+h.toString())}if(d.id&&b){if(k[b]){var i=p(d.id,a,d.callbacks?d.callbacks:[]);m[d.id]={};try{if(d.callbacks&&c(d.callbacks)&&d.callbacks.length>0)for(var j=0;j<d.callbacks.length;j++){for(var n=d.callbacks[j],o=d.params,q=n.split("/"),r=0;r<q.length-1;r++){var s=q[r];"object"!=typeof o[s]&&(o[s]={}),o=o[s]}o[q[q.length-1]]=function(){var a=n;return function(b){return i.invoke(a,b)}}()}var t=k[b](i,d.params);i.delayReturn()||i.completed()||i.complete(t)}catch(h){var u="runtime_error",v=null;if("string"==typeof h?v=h:"object"==typeof h&&(h&&c(h)&&2==h.length?(u=h[0],v=h[1]):"string"==typeof h.error&&(u=h.error,h.message?"string"==typeof h.message?v=h.message:h=h.message:v="")),null===v)try{v=JSON.stringify(h),"undefined"==typeof v&&(v=h.toString())}catch(w){v=h.toString()}i.error(u,v)}}}else d.id&&d.callback?l[d.id]&&l[d.id].callbacks&&l[d.id].callbacks[d.callback]?l[d.id].callbacks[d.callback](d.params):g("ignoring invalid callback, id:"+d.id+" ("+d.callback+")"):d.id?l[d.id]?(d.error?l[d.id].error(d.error,d.message):void 0!==d.result?l[d.id].success(d.result):l[d.id].success(),delete l[d.id],delete f[d.id]):g("ignoring invalid response: "+d.id):b&&k[b]&&k[b]({origin:a},d.params)};a(e.window,e.origin,"string"==typeof e.scope?e.scope:"",r);var s=function(a){return"string"==typeof e.scope&&e.scope.length&&(a=[e.scope,a].join("::")),a},t=function(a,b){if(!a)throw"postMessage called with null message";var c=n?"post ":"queue ";if(g(c+" message: "+JSON.stringify(a)),b||n){if("function"==typeof e.postMessageObserver)try{e.postMessageObserver(e.origin,a)}catch(d){g("postMessageObserver() raised an exception: "+d.toString())}e.window.postMessage(JSON.stringify(a),e.origin)}else o.push(a)},u=function(a,b){if(g("ready msg received"),n)throw"received ready message while in ready state. help!";for(j+="ping"===b?"-R":"-L",v.unbind("__ready"),n=!0,g("ready msg accepted."),"ping"===b&&v.notify({method:"__ready",params:"pong"});o.length;)t(o.pop());"function"==typeof e.onReady&&e.onReady(v)},v={unbind:function(a){if(k[a]){if(!delete k[a])throw"can't delete method: "+a;return!0}return!1},bind:function(a,b){if(!a||"string"!=typeof a)throw"'method' argument to bind must be string";if(!b||"function"!=typeof b)throw"callback missing from bind params";if(k[a])throw"method '"+a+"' is already bound!";return k[a]=b,this},call:function(a){if(!a)throw"missing arguments to call function";if(!a.method||"string"!=typeof a.method)throw"'method' argument to call must be string";if(!a.success||"function"!=typeof a.success)throw"'success' callback missing from call";var b={},c=[],e=function(a,d){if("object"==typeof d)for(var f in d)if(d.hasOwnProperty(f)){var g=a+(a.length?"/":"")+f;"function"==typeof d[f]?(b[g]=d[f],c.push(g),delete d[f]):"object"==typeof d[f]&&e(g,d[f])}};e("",a.params);var g={id:d,method:s(a.method),params:a.params};c.length&&(g.callbacks=c),a.timeout&&q(d,a.timeout,s(a.method)),l[d]={callbacks:b,error:a.error,success:a.success},f[d]=r,d++,t(g)},notify:function(a){if(!a)throw"missing arguments to notify function";if(!a.method||"string"!=typeof a.method)throw"'method' argument to notify must be string";t({method:s(a.method),params:a.params})},destroy:function(){b(e.window,e.origin,"string"==typeof e.scope?e.scope:""),window.removeEventListener?window.removeEventListener("message",r,!1):window.detachEvent&&window.detachEvent("onmessage",r),n=!1,k={},m={},l={},e.origin=null,o=[],g("channel destroyed"),j=""}};return v.bind("__ready",u),setTimeout(function(){t({method:s("__ready"),params:"ping"},!0)},0),v}}}();!function(a){"use strict";var b=a.prototype,c=b.parseFromString;try{if((new a).parseFromString("","text/html"))return}catch(d){}b.parseFromString=function(a,b){var d,e,f,g;return/^\s*text\/html\s*(?:;|$)/i.test(b)?(e=document.implementation.createHTMLDocument(""),f=e.documentElement,f.innerHTML=a,g=f.firstElementChild,1===f.childElementCount&&"html"===g.localName.toLowerCase()&&e.replaceChild(g,f),d=e):d=c.apply(this,arguments),d}}(DOMParser),function(a,b,c,d,e,f){"use strict";function g(a){var b=a.indexOf("#");return b>0&&(a=a.substring(0,b)),a}function h(){return this instanceof h?void 0:new h}function i(a){a.__sub_gadget_dict={}}function j(a,b,d){var e,g,h=this;for(e in h.__sub_gadget_dict)h.__sub_gadget_dict.hasOwnProperty(e)&&h.__sub_gadget_dict[e]===a&&(g=e);return(new c.Queue).push(function(){var a=h.__acquired_method_dict||{};if(a.hasOwnProperty(b))return a[b].apply(h,[d,g]);throw new s.AcquisitionError("aq_dynamic is not defined")}).push(f,function(a){if(a instanceof s.AcquisitionError)return h.__aq_parent(b,d);throw a})}function k(a,b){a.__aq_parent=function(c,d){return j.apply(b,[a,c,d])}}function l(){return this instanceof l?(h.call(this),void 0):new l}function m(b,d,e){function g(a,b){return function(){return a(b)}}var h;return d.element===f&&(d.element=a.createElement("div")),(new c.Queue).push(function(){return s.declareGadgetKlass(b)}).push(function(a){var b,f=a.__template_element.body.childNodes;for(q=a,h=new a,h.__element=d.element,b=0;b<f.length;b+=1)h.__element.appendChild(f[b].cloneNode(!0));return k(h,e),c.all([h.getRequiredJSList(),h.getRequiredCSSList()])}).push(function(a){var b,d=new c.Queue;for(b=0;b<a[0].length;b+=1)d.push(g(s.declareJS,a[0][b]));for(b=0;b<a[1].length;b+=1)d.push(g(s.declareCSS,a[1][b]));return d}).push(function(){return h})}function n(){return this instanceof n?(h.call(this),void 0):new n}function o(b,d,g){var h,i,j,l=c.defer();if(d.element===f)throw new Error("DOM element is required to create Iframe Gadget "+b);for(j=d.element.parentNode;null!==j&&j!==a;)j=j.parentNode;if(null===j)throw new Error("The parent element is not attached to the DOM for "+b);return h=new n,k(h,g),i=a.createElement("iframe"),i.setAttribute("src",b),h.__path=b,h.__element=d.element,d.element.appendChild(i),h.__chan=e.build({window:i.contentWindow,origin:"*",scope:"renderJS"}),h.__chan.bind("declareMethod",function(a,b){return h[b]=function(){var a=arguments;return new c.Promise(function(c,d){h.__chan.call({method:"methodCall",params:[b,Array.prototype.slice.call(a,0)],success:function(a){c(a)},error:function(a){d(a)}})})},"OK"}),h.__chan.bind("ready",function(){return l.resolve(h),"OK"}),h.__chan.bind("failed",function(a,b){return l.reject(b),"OK"}),h.__chan.bind("acquire",function(a,b){h.__aq_parent.apply(h,b).then(function(b){a.complete(b)}).fail(function(b){a.error(b.toString())}),a.delayReturn(!0)}),c.any([l.promise,c.timeout(5e3)])}function p(){var d,i,j,m,n,o,p=g(b.location.href),w=0,x=!1;if(t.hasOwnProperty(p))throw new Error("bootstrap should not be called twice");r=new c.Promise(function(g,r){function y(){var e,h,j=s.parseGadgetHTMLDocument(a,p);for(h in j)j.hasOwnProperty(h)&&(d.prototype["__"+h]=j[h]);for(d.__template_element=a.createElement("div"),i.__element=a.body,e=0;e<i.__element.childNodes.length;e+=1)d.__template_element.appendChild(i.__element.childNodes[e].cloneNode(!0));c.all([i.getRequiredJSList(),i.getRequiredCSSList()]).then(function(e){function h(){return i}var j,k,l=e[0],m=e[1];for(j=0;j<l.length;j+=1)u[l[j]]=null;for(j=0;j<m.length;j+=1)v[m[j]]=null;for(q=f,k=new c.Queue,b.top!==b.self&&d.ready(function(){var b=a.createElement("base");return i.__aq_parent("getTopURL",[]).then(function(c){b.href=c,b.target="_top",a.head.appendChild(b)})}),k.push(h),j=0;j<d.__ready_list.length;j+=1)k.push(d.__ready_list[j]).push(h);return k.push(g,function(a){throw r(a),a}),k}).fail(function(a){r(a),console.error(a)})}b.self===b.top?(o=new h,o.__acquired_method_dict={getTopURL:function(){return p}},o.__aq_parent=function(a){throw new s.AcquisitionError("No gadget provides "+a)},d=function(){h.call(this)},d.declareMethod=h.declareMethod,d.declareAcquiredMethod=h.declareAcquiredMethod,d.allowPublicAcquisition=h.allowPublicAcquisition,d.__ready_list=h.__ready_list.slice(),d.ready=h.ready,d.prototype=new h,d.prototype.constructor=d,d.prototype.__path=p,t[p]=d,i=new t[p],k(i,o)):(j=e.build({window:b.parent,origin:"*",scope:"renderJS"}),d=l,d.__ready_list=h.__ready_list.slice(),d.prototype.__path=p,i=new l,j.bind("methodCall",function(a,b){i[b[0]].apply(i,b[1]).then(function(b){a.complete(b)}).fail(function(b){a.error(b.toString())}),a.delayReturn(!0)}),m=function(){0===w&&x===!0&&j.notify({method:"ready"})},n=function(a){w+=1,j.call({method:"declareMethod",params:a,success:function(){w-=1,m()},error:function(){w-=1}})},n("getInterfaceList"),n("getRequiredCSSList"),n("getRequiredJSList"),n("getPath"),n("getTitle"),d.declareMethod=function(a,b){var c=h.declareMethod.apply(this,[a,b]);return n(a),c},d.declareAcquiredMethod=h.declareAcquiredMethod,d.allowPublicAcquisition=h.allowPublicAcquisition,d.prototype.__aq_parent=function(a,b){return new c.Promise(function(c,d){j.call({method:"acquire",params:[a,b],success:function(a){c(a)},error:function(a){d(a)}})})}),d.prototype.__acquired_method_dict={},q=d,a.addEventListener("DOMContentLoaded",y,!1)}),b.self!==b.top&&r.then(function(){x=!0,m()}).fail(function(a){throw j.notify({method:"failed",params:a.toString()}),a})}var q,r,s,t={},u={},v={};h.prototype.__title="",h.prototype.__interface_list=[],h.prototype.__path="",h.prototype.__html="",h.prototype.__required_css_list=[],h.prototype.__required_js_list=[],h.__ready_list=[i],h.ready=function(a){return this.__ready_list.push(a),this},h.declareMethod=function(a,b){return this.prototype[a]=function(){var a=this,d=arguments;return(new c.Queue).push(function(){return b.apply(a,d)})},this},h.declareMethod("getInterfaceList",function(){return this.__interface_list}).declareMethod("getRequiredCSSList",function(){return this.__required_css_list}).declareMethod("getRequiredJSList",function(){return this.__required_js_list}).declareMethod("getPath",function(){return this.__path}).declareMethod("getTitle",function(){return this.__title}).declareMethod("getElement",function(){if(this.__element===f)throw new Error("No element defined");return this.__element}),h.declareAcquiredMethod=function(a,b){return this.prototype[a]=function(){var a=Array.prototype.slice.call(arguments,0),d=this;return(new c.Queue).push(function(){return d.__aq_parent(b,a)})},this},h.allowPublicAcquisition=function(a,b){return this.prototype.__acquired_method_dict[a]=b,this},l.__ready_list=h.__ready_list.slice(),l.ready=h.ready,l.prototype=new h,l.prototype.constructor=l,n.__ready_list=h.__ready_list.slice(),n.ready=h.ready,n.prototype=new h,n.prototype.constructor=n,h.declareMethod("declareGadget",function(a,b){var d,e=this,g=r;return b===f&&(b={}),b.sandbox===f&&(b.sandbox="public"),a=s.getAbsoluteURL(a,this.__path),d=(new c.Queue).push(function(){return g}).push(f,function(){}).push(function(){var c;if("public"===b.sandbox)c=m;else{if("iframe"!==b.sandbox)throw new Error("Unsupported sandbox options '"+b.sandbox+"'");c=o}return c(a,b,e)}).push(function(a){function c(){return a}var g;for(q=f,g=0;g<a.constructor.__ready_list.length;g+=1)d.push(a.constructor.__ready_list[g]),d.push(c);return b.scope!==f&&(e.__sub_gadget_dict[b.scope]=a),a}).push(f,function(a){throw q=f,a}),r=d}).declareMethod("getDeclaredGadget",function(a){if(!this.__sub_gadget_dict.hasOwnProperty(a))throw new Error("Gadget scope '"+a+"' is not known.");return this.__sub_gadget_dict[a]}).declareMethod("dropGadget",function(a){if(!this.__sub_gadget_dict.hasOwnProperty(a))throw new Error("Gadget scope '"+a+"' is not known.");delete this.__sub_gadget_dict[a]}),s=function(a){var c;if(a===b&&(c=q),c===f)throw new Error("Unknown selector '"+a+"'");return c},s.AcquisitionError=function(a){if(this.name="AcquisitionError",a!==f&&"string"!=typeof a)throw new TypeError("You must pass a string.");this.message=a||"Acquisition failed"},s.AcquisitionError.prototype=new Error,s.AcquisitionError.prototype.constructor=s.AcquisitionError,s.getAbsoluteURL=function(a,b){var c,e,f,g="<!doctype><html><head></head></html>",h=new RegExp("^(?:[a-z]+:)?//|data:","i");return a&&b&&!h.test(a)?(c=(new d).parseFromString(g,"text/html"),e=c.createElement("base"),f=c.createElement("link"),c.head.appendChild(e),c.head.appendChild(f),e.href=b,f.href=a,f.href):a},s.declareJS=function(b){var d;return d=u.hasOwnProperty(b)?c.resolve():new c.Promise(function(c,d){var e;e=a.createElement("script"),e.type="text/javascript",e.src=b,e.onload=function(){u[b]=null,c()},e.onerror=function(a){d(a)},a.head.appendChild(e)})},s.declareCSS=function(b){var d;return d=v.hasOwnProperty(b)?c.resolve():new c.Promise(function(c,d){var e;e=a.createElement("link"),e.rel="stylesheet",e.type="text/css",e.href=b,e.onload=function(){v[b]=null,c()},e.onerror=function(a){d(a)},a.head.appendChild(e)})},s.declareGadgetKlass=function(a){function b(){var b,c,e;if(!t.hasOwnProperty(a)){b=function(){h.call(this)},b.__ready_list=h.__ready_list.slice(),b.declareMethod=h.declareMethod,b.declareAcquiredMethod=h.declareAcquiredMethod,b.allowPublicAcquisition=h.allowPublicAcquisition,b.ready=h.ready,b.prototype=new h,b.prototype.constructor=b,b.prototype.__path=a,b.prototype.__acquired_method_dict={},b.__template_element=(new d).parseFromString(j.responseText,"text/html"),e=s.parseGadgetHTMLDocument(b.__template_element,a);for(c in e)e.hasOwnProperty(c)&&(b.prototype["__"+c]=e[c]);t[a]=b}return t[a]}function e(c,d){function e(){var a;try{0===j.readyState?d(j):4===j.readyState&&(j.status<200||j.status>=300||!/^text\/html[;]?/.test(j.getResponseHeader("Content-Type")||"")?d(j):(a=b(),c(a)))}catch(e){d(e)}}j=new XMLHttpRequest,j.open("GET",a),j.onreadystatechange=e,j.setRequestHeader("Accept","text/html"),j.withCredentials=!0,j.send()}function g(){j!==f&&j.readyState!==j.DONE&&j.abort()}var i,j;return i=t.hasOwnProperty(a)?c.resolve(t[a]):new c.Promise(e,g)},s.clearGadgetKlassList=function(){t={},u={},v={}},s.parseGadgetHTMLDocument=function(a,b){var c,d,e={title:"",interface_list:[],required_css_list:[],required_js_list:[]},f=new RegExp("^(?:[a-z]+:)?//","i");if(!b||!f.test(b))throw new Error("The second parameter should be an absolute url");if(9!==a.nodeType)throw new Error("The first parameter should be an HTMLDocument");for(e.title=a.title,c=0;c<a.head.children.length;c+=1)d=a.head.children[c],null!==d.href&&("stylesheet"===d.rel?e.required_css_list.push(s.getAbsoluteURL(d.getAttribute("href"),b)):"SCRIPT"!==d.nodeName||"text/javascript"!==d.type&&d.type?"http://www.renderjs.org/rel/interface"===d.rel&&e.interface_list.push(s.getAbsoluteURL(d.getAttribute("href"),b)):e.required_js_list.push(s.getAbsoluteURL(d.getAttribute("src"),b)));return e},b.rJS=b.renderJS=s,b.__RenderJSGadget=h,b.__RenderJSEmbeddedGadget=l,b.__RenderJSIframeGadget=n,p()}(document,window,RSVP,DOMParser,Channel);
\ No newline at end of file \ No newline at end of file
{ {
"name": "renderjs", "name": "renderjs",
"version": "0.6.1", "version": "0.7.0",
"description": "RenderJs provides HTML5 gadgets", "description": "RenderJs provides HTML5 gadgets",
"main": "dist/renderjs-latest.js", "main": "dist/renderjs-latest.js",
"dependencies": { "dependencies": {
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment