Commit 96d216bd authored by Sven Franck's avatar Sven Franck

cleanup old files

parent 761440c1
{
"property_dict": {},
"children": [
{
"generate": "widget",
"type": "page",
"property_dict": {
"theme": "slapos-white"
},
"view_dict": {
"default": [
{
"generate": "widget",
"type": "controlbar",
"property_dict": {
"class_list": "span_1 responsive"
},
"children": [
{
"generate": "widget",
"type": "carousel",
"property_dict": {
"handles": true,
"map_children": "listItem"
},
"children": [
{"type": "item", "href": "#", "center": [{"type": "image", "src": "img/website-Bleu.png", "alt": ""}]},
{"type": "item", "href": "#", "center": [{"type": "image", "src": "img/website-Pub.png", "alt": ""}]},
{"type": "item", "href": "#", "center": [{"type": "image", "src": "img/website-Vert.png", "alt": ""}]}
]
}
]
},
{
"generate": "widget",
"type": "controlbar",
"property_dict": {
"class_list": "responsive"
},
"children":[
{
"type": "div",
"direct": {"className": "span_3"},
"children": [
{
"type": "div",
"direct": {"className": "offer violet background ui-corner-all"},
"children": [{
"type": "img",
"direct": {"src": "img/website-Logo-offre.png", "alt": "Bip&Go"}
},{
"type": "h3",
"direct": {"className": "translate offer_tag"},
"attributes": {"data-i18n": "global_dict.fixed"}
}, {
"type": "a",
"direct": {"href": "#", "className": "ui-link"},
"logic": {"plain_link":true},
"children": [{
"type": "span",
"direct": {"className": "translate"},
"attributes": {"data-i18n": "global_dict.once_a_month"}
}, {
"type": "span",
"direct": {"className": "translate offer_tag"},
"attributes": {"data-i18n": "global_dict.once_price"}
}, {
"type": "span",
"direct": {"className": "translate"},
"attributes": {"data-i18n": "global_dict.find_out_more"}
}]
}, {
"type": "a",
"direct": {"className": "translate ui-btn-inline ui-btn ui-corner-all ui-icon-carat-r ui-btn-icon-right", "href": "#subscription"},
"attributes": {"data-i18n": "global_dict.subscribe"}
}
]
}
]
}, {
"type": "div",
"direct": {"className": "span_3"},
"children": [{
"type": "div",
"direct": {"className": "offer rose background ui-corner-all"},
"children": [{
"type": "img",
"direct": {"src": "img/website-Logo-offre.png", "alt": "Bip&Go"}
},{
"type": "h3",
"direct": {"className": "translate offer_tag"},
"attributes": {"data-i18n": "global_dict.pay_as_you_go"}
}, {
"type": "a",
"direct": {"href": "#", "className": "ui-link"},
"logic": {"plain_link":true},
"children": [{
"type": "span",
"direct": {"className": "translate"},
"attributes": {"data-i18n": "global_dict.view_info"}
}, {
"type": "span",
"direct": {"className": "translate offer_tag"},
"attributes": {"data-i18n": "global_dict.view_times"}
}, {
"type": "span",
"direct": {"className": "translate"},
"attributes": {"data-i18n": "global_dict.find_out_more"}
}]
}, {
"type": "a",
"direct": {"className": "translate ui-btn ui-corner-all ui-icon-carat-r ui-btn-icon-right ui-btn-inline", "href": "#subscription"},
"attributes": {"data-i18n": "global_dict.subscribe"}
}]
}
]
}, {
"type": "div",
"direct": {"className": "span_3"},
"children": [{
"type": "div",
"direct": {"className": "offer bleu background ui-corner-all"},
"children": [{
"type": "img",
"direct": {"src": "img/website-Logo-offre.png", "alt": "Bip&Go"}
},{
"type": "h3",
"direct": {"className": "translate offer_tag"},
"attributes": {"data-i18n": "global_dict.pro"}
}, {
"type": "a",
"direct": {"href": "#", "className": "ui-link"},
"logic": {"plain_link":true},
"children": [{
"type": "span",
"direct": {"className": "translate"},
"attributes": {"data-i18n": "global_dict.enterprise"}
}, {
"type": "span",
"direct": {"className": "translate offer_tag"},
"attributes": {"data-i18n": "global_dict.enterprise_price"}
}, {
"type": "span",
"direct": {"className": "translate"},
"attributes": {"data-i18n": "global_dict.find_out_more"}
}]
}, {
"type": "a",
"direct": {"className": "translate pad ui-btn-inline ui-btn ui-corner-all ui-icon-carat-r ui-btn-icon-right", "href": "#subscription"},
"attributes": {"data-i18n": "global_dict.subscribe"}
}]
}
]
}, {
"type": "div",
"direct": {"className": "span_1 custom_side_by_side"},
"children":[{
"type": "div",
"direct": {"className": "offer custom_offer rouge background ui-corner-all"},
"children": [{
"type": "img",
"direct": {"src": "img/website-Logo-offre.png", "alt": "Bip&Go"}
},{
"type": "h3",
"direct": {"className": "translate offer_tag"},
"attributes": {"data-i18n": "global_dict.vacances"}
}, {
"type": "a",
"direct": {"href": "#", "className": "ui-link"},
"logic": {"plain_link":true},
"children": [{
"type": "span",
"direct": {"className": "translate offer_tag"},
"attributes": {"data-i18n": "global_dict.holiday"}
}, {
"type": "span",
"direct": {"className": "translate custom_find_out"},
"attributes": {"data-i18n": "global_dict.find_out_more"}
}]
}, {
"type": "a",
"direct": {"className": "translate custom_button right ui-btn-inline ui-btn ui-corner-all ui-icon-carat-r ui-btn-icon-right", "href": "#subscription"},
"attributes": {"data-i18n": "global_dict.subscribe"}
}]
}
]
}
]
}, {
"generate": "widget",
"type": "controlbar",
"property_dict": {
"class_list": "responsive span_1"
},
"children": [{
"type": "div",
"direct": {"className": "span_2 custom_bar left"},
"children":[{
"type": "h3",
"direct": {"className": "translate custom_bar_header"},
"attributes": {"data-i18n":"global_dict.traffic_control"}
}, {
"type": "img",
"direct": {"src": "img/website-Visuel-home.png", "alt": ""}
}, {
"type": "a",
"direct": {"className": "translate custom_profit right ui-btn-inline ui-btn ui-corner-all ui-icon-carat-r ui-btn-icon-right", "href": "#"},
"attributes": {"data-i18n": "global_dict.find_out_more"}
}]
}, {
"type": "div",
"direct": {"className": "span_2 custom_bar right"},
"children":[{
"type": "h3",
"direct": {"className": "translate custom_bar_header"},
"attributes": {"data-i18n": "global_dict.advice"}
}, {
"type": "img",
"direct": {"src": "img/website-Visuel-home2.png", "alt": ""}
}, {
"type": "a",
"direct": {"className": "translate custom_profit right ui-btn-inline ui-btn ui-corner-all ui-icon-carat-r ui-btn-icon-right", "href": "#"},
"attributes": {"data-i18n": "global_dict.find_out_more"}
}]
}]
}]
}
}
]
}
/*
* JIO extension for resource replication.
* Copyright (C) 2013 Nexedi SA
*
* This library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*jslint indent: 2, nomen: true, unparam: true */
/*global jIO, UriTemplate, FormData, RSVP, URI */
(function (jIO, URI) {
"use strict";
/**
* The JIO ERP5storage extension
*
* @class ERP5Storage
* @constructor
* @param {Object} spec Storage definition
*/
function ERP5Storage(spec) {
if (typeof spec.url !== 'string' && !spec.url) {
throw new TypeError("ERP5 'url' must be a string " +
"which contains more than one character.");
}
this._url = spec.url;
}
/**
* Get a document ("me" or regular document)
*
* @method _getDoc
* @param {Object} command The JIO command
* @param {Object} site_hal The object to lookup needed href for request
* @param {Object} param The given parameters
* @param {Object} options The command options (including custom options!)
* @return {Object} the requested document
*/
ERP5Storage.prototype._getDoc = function (command, hal, param, options) {
var fetch, force, item = (param || {})._id || (hal._links.me || {}).href;
if (!item) {
command.error(401);
}
// HACK: remove, when forcing ALLDOCS over a GET (installed_instances eg.)
if (options._id) {
force = "urn:jio:get:" + options._id;
}
fetch = new URI(force || item);
return this._getBase(
hal._links.traverse.href,
{"relative_url": fetch.segment(2) || item, "view": options._view}
);
};
/**
* Retrieves document defined in _getDoc. Called directly to get "root"
* with both parameters undefined
*
* @method _getBase
* @param {String} traverse The url to call ("" falls back to this._url!)
* @param {Object} expando The url parameters for the UriTemplate
* @return {Object} the requested document
*/
ERP5Storage.prototype._getBase = function (traverse, expando) {
var url = UriTemplate.parse(traverse || "").expand(expando || {});
return jIO.util.ajax({
"type": "GET",
"url": url || this._url,
"xhrFields": {
"withCredentials": true
}
}).then(function (response) {
return JSON.parse(response.target.responseText);
});
};
/**
* Retrieves a parameter from an object or array
*
* @method _getParam
* @param {Object} haystack The object/array to search
* @param {String} needle The value to search
* @return {String} the requested parameter
*/
ERP5Storage.prototype._getParam = function (haystack, needle) {
var i, key, list, len;
if (!haystack.length && haystack.name === needle) {
return haystack._query;
}
list = haystack || [];
len = list.length;
for (i = 0; i < len; i += 1) {
key = list[i];
if (key.name === needle) {
return key._query;
}
}
return undefined;
};
/**
* Get a document
*
* @method get
* @param {Object} command The JIO command
* @param {Object} param The given parameters
* @param {Object} options The command options
*/
ERP5Storage.prototype.get = function (command, param, options) {
var that = this;
return that._getBase()
.then(function (site_hal) {
return that._getDoc(command, site_hal, param, options);
})
.then(function (response) {
response._id = param._id;
command.success({"data": response});
})
.fail(function (error) {
command.error(error.target.status);
});
};
/**
* Get an attachment
*
* @method getAttachment
* @param {Object} command The JIO command
* @param {Object} param The given parameters
*/
ERP5Storage.prototype.getAttachment = function (command, param) {
command.error(501);
};
/**
* Remove a document
*
* @method get
* @param {Object} command The JIO command
* @param {Object} param The given parameters
* @param {Object} options The command options
*/
ERP5Storage.prototype.remove = function (command, param, options) {
command.error(501);
};
/**
* Remove an attachment
*
* @method removeAttachment
* @param {Object} command The JIO command
* @param {Object} param The given parameters
*/
ERP5Storage.prototype.removeAttachment = function (command, param) {
command.error(501);
};
/**
* Create a document
*
* @method post
* @param {Object} command The JIO command
* @param {Object} metadata The metadata to store
* @param {Object} options The command options
*/
ERP5Storage.prototype.post = function (command, metadata, options) {
var hal, that = this;
return that._getBase()
.then(function (site_hal) {
hal = site_hal;
return that._getDoc(command, hal, undefined, options);
})
.then(function (result) {
var key, custom_action = result._actions[options._action],
post_action = custom_action || hal._actions.add,
data = new FormData();
for (key in metadata) {
if (metadata.hasOwnProperty(key)) {
// XXX Not a form dialog in this case but distant script
data.append(key, metadata[key]);
}
}
return jIO.util.ajax({
"type": post_action.method,
"url": post_action.href,
"data": data,
"xhrFields": {
"withCredentials": true
}
});
}).then(function (doc) {
// XXX Really depend on server response...
var uri = new URI(doc.target.getResponseHeader("X-Location"));
command.success({"id": uri.segment(2)});
}).fail(function (error) {
command.error(error.target.status);
});
};
/**
* Create or update a document
*
* @method post
* @param {Object} command The JIO command
* @param {Object} metadata The metadata to store
* @param {Object} options The command options
*/
ERP5Storage.prototype.put = function (command, metadata, options) {
var that = this, custom_action = (options || {})._action;
return that._getBase()
.then(function (site_hal) {
var param;
// force another id over "me"
// HACK: reference for service_installation (= server to install on)
if (custom_action || metadata._id) {
param = {"_id": metadata._reference || metadata._id};
}
return that._getDoc(command, site_hal, param, options);
})
.then(function (result) {
var key, renderer_form,
data = new FormData(),
put_action = result._actions[custom_action] ||
result._embedded._view._actions.put;
renderer_form = result._embedded._view;
data.append(
renderer_form.form_id.key,
renderer_form.form_id['default']
);
for (key in metadata) {
if (metadata.hasOwnProperty(key)) {
if (key !== "_id" && !metadata._reference) {
// HACK: update_scope does not implement my_
if (options._force_data) {
data.append(key, metadata[key]);
} else {
// Hardcoded my_ ERP5 behaviour - fails so silently...!!!!!
try {
if (renderer_form.hasOwnProperty("my_" + key)) {
data.append(renderer_form["my_" + key].key, metadata[key]);
}
} catch (e) {
throw new Error("Can not save property " + key);
}
}
}
}
}
return jIO.util.ajax({
"type": put_action.method,
"url": put_action.href,
"data": data,
"xhrFields": {
"withCredentials": true
}
});
})
.then(function (event) {
var response, answer = event.target.responseText;
if (answer !== "") {
response = {
"status": event.target.status,
"_temp": JSON.parse(answer)
};
}
command.success(response || event);
})
.fail(function (error) {
// DEBUG EXAMPLE
// if (error instanceof ProgressEvent) {
// return command.error(
// error.target.status,
// error.target.statusText,
// "custom message"
// );
// }
command.error(error.target.status);
});
};
/**
* Add an attachment to a document
*
* @method putAttachment
* @param {Object} command The JIO command
* @param {Object} param The given parameters
*/
ERP5Storage.prototype.putAttachment = function (command, param) {
command.error(501);
};
/**
* Get all filenames (and files)
*
* @method allDocs
* @param {Object} command The JIO command
* @param {Object} param The given parameters
* @param {Object} options The command options (HACKED, because needed)
*/
ERP5Storage.prototype.allDocs = function (command, param, options) {
var that = this, search_pointer;
return that._getBase()
.then(function (site_hal) {
search_pointer = site_hal._links.raw_search.href;
return that._getDoc(command, site_hal, param, options);
})
.then(function (opts) {
// HACK: options._id needed when forcing GET through ALLDOCS
if (param._jump && (options.query || options._id)) {
options.query = that._getParam(opts._links.slapos_jump, param._jump);
}
return that._getBase(
search_pointer,
{
"query": options.query,
// XXX Force erp5 to return embedded document
"select_list": options.select_list || ["title", "reference"],
"limit": options.limit
}
);
})
.then(function (catalog_json) {
var i, uri, item,
result = [],
promise_list = [result],
data = catalog_json._embedded.contents,
count = data.length;
for (i = 0; i < count; i += 1) {
item = data[i];
uri = new URI(item._links.self.href);
result.push({
id: uri.segment(2),
key: uri.segment(2),
doc: {},
value: item
});
// if (options.include_docs) {
// promise_list.push(RSVP.Queue().push(function () {
// return this._get({_id: item.name}, {_view: "View"});
// }).push
// }
}
return RSVP.all(promise_list);
})
.then(function (promise_list) {
var result = promise_list[0],
count = result.length;
command.success({"data": {"rows": result, "total_rows": count}});
})
.fail(function (error) {
command.error(error.target.status);
});
};
jIO.addStorage("erp5", ERP5Storage);
}(jIO, URI));
/*
* Copyright 2013, Nexedi SA
* Released under the LGPL license.
* http://www.gnu.org/licenses/lgpl.html
*/
// JIO Hateoas Storage Description :
// {
// type: "hateoas"
// url: {string}
// }
/*jslint nomen: true, unparam: true */
/*global jIO, complex_queries, console, UriTemplate, FormData, RSVP */
(function (jIO, complex_queries) {
"use strict";
function HateoasStorage(spec) {
if (typeof spec.url !== 'string' && !spec.url) {
throw new TypeError("Hateoas 'url' must be a string " +
"which contains more than one character.");
}
this._url = spec.url;
}
HateoasStorage.prototype._getSiteDocument = function () {
return jIO.util.ajax({
"type": "GET",
"url": this._url,
"xhrFields": {
withCredentials: true
}
}).then(function (response) {
return JSON.parse(response.target.responseText);
});
};
HateoasStorage.prototype._get = function (param, options) {
return this._getSiteDocument()
.then(function (site_hal) {
return jIO.util.ajax({
"type": "GET",
"url": UriTemplate.parse(site_hal._links.traverse.href)
.expand({
relative_url: param._id,
view: options._view
}),
"xhrFields": {
withCredentials: true
}
});
})
.then(function (response) {
var result = JSON.parse(response.target.responseText);
result._id = param._id;
return result;
});
};
HateoasStorage.prototype.get = function (command, param, options) {
this._get(param, options)
.then(function (response) {
command.success({"data": response});
})
.fail(function (error) {
console.error(error);
// XXX How to propagate the error
command.error(
"not_found",
"missing",
"Cannot find document"
);
});
};
HateoasStorage.prototype.post = function (command, metadata, options) {
return this._getSiteDocument()
// HACK: get me... default _add, otherwise passed through options!
.then(function (site_hal) {
return jIO.util.ajax({
"url": site_hal._links.me.href,
"xhrFields": {
"withCredentials": true
}
})z
})
.then(function (opts) {
var doc_hal, custom_action, post_action, data, key;
doc_hal = JSON.parse(opts.target.responseText);
custom_action = doc_hal._actions[options.call];
post_action = custom_action || site_hal._actions.add;
data = new FormData();
for (key in metadata) {
if (metadata.hasOwnProperty(key)) {
// XXX Not a form dialog in this case but distant script
data.append(key, metadata[key]);
}
}
return jIO.util.ajax({
"type": post_action.method,
"url": post_action.href,
"data": data,
"xhrFields": {
"withCredentials": true
}
});
})
.then(function (doc) {
// XXX Really depend on server response...
var new_document_url = doc.target.getResponseHeader("Location");
return jIO.util.ajax({
"type": "GET",
"url": new_document_url,
"xhrFields": {
"withCredentials": true
}
});
}).then(function (response) {
var doc_hal = JSON.parse(response.target.responseText);
if (doc_hal !== null) {
command.success({"id": doc_hal._relative_url});
} else {
command.error(
"not_found",
"missing",
"Cannot find document"
);
}
}, function (error) {
console.error(error);
command.error(
500,
"Too bad...",
"Unable to post doc"
);
});
};
HateoasStorage.prototype.put = function (command, metadata, options) {
return this._get(metadata, options)
.then(function (result) {
var put_action = result._embedded._view._actions.put,
renderer_form = result._embedded._view,
data = new FormData(),
key;
data.append(renderer_form.form_id.key,
renderer_form.form_id['default']);
for (key in metadata) {
if (metadata.hasOwnProperty(key)) {
if (key !== "_id") {
// Hardcoded my_ ERP5 behaviour
if (renderer_form.hasOwnProperty("my_" + key)) {
data.append(renderer_form["my_" + key].key, metadata[key]);
} else {
throw new Error("Can not save property " + key);
}
}
}
}
return jIO.util.ajax({
"type": put_action.method,
"url": put_action.href,
"data": data,
"xhrFields": {
"withCredentials": true
}
});
})
.then(function (result) {
command.success(result);
})
.fail(function (error) {
console.error(error);
command.error(
"error",
"did not work as expected",
"Unable to call allDocs"
);
});
};
HateoasStorage.prototype.allDocs = function (command, param, options) {
return this._getSiteDocument()
.then(function (site_hal) {
return jIO.util.ajax({
"type": "GET",
"url": UriTemplate.parse(site_hal._links.raw_search.href)
.expand({
query: options.query,
// XXX Force erp5 to return embedded document
select_list: options.select_list || ["title", "reference"],
limit: options.limit
}),
"xhrFields": {
withCredentials: true
}
});
})
.then(function (response) {
return JSON.parse(response.target.responseText);
})
.then(function (catalog_json) {
var data = catalog_json._embedded.contents,
count = data.length,
i,
item,
result = [],
promise_list = [result];
for (i = 0; i < count; i += 1) {
item = data[i];
item._id = item._relative_url;
result.push({
id: item._relative_url,
key: item._relative_url,
doc: {},
value: item
});
// if (options.include_docs) {
// promise_list.push(RSVP.Queue().push(function () {
// return this._get({_id: item.name}, {_view: "View"});
// }).push
// }
}
return RSVP.all(promise_list);
})
.then(function (promise_list) {
var result = promise_list[0],
count = result.length;
command.success({"data": {"rows": result, "total_rows": count}});
})
.fail(function (error) {
console.error(error);
command.error(
"error",
"did not work as expected",
"Unable to call allDocs"
);
});
};
jIO.addStorage("hateoas", HateoasStorage);
}(jIO, complex_queries));
/*jslint indent: 2, maxlen: 80, nomen: true */
/*global jIO, define */
/**
* JIO Replicate Revision Storage.
* It manages storages that manage revisions and conflicts.
* Description:
* {
* "type": "replicaterevision",
* "storage_list": [
* <sub storage description>,
* ...
* ]
* }
*/
// define([module_name], [dependencies], module);
(function (dependencies, module) {
"use strict";
if (typeof define === 'function' && define.amd) {
return define(dependencies, module);
}
module(jIO);
}(['jio'], function (jIO) {
"use strict";
jIO.addStorage('replicaterevision', function (spec) {
var that = this, priv = {};
spec = spec || {};
priv.storage_list_key = "storage_list";
priv.storage_list = spec[priv.storage_list_key];
priv.emptyFunction = function () {
return;
};
/**
* Generate a new uuid
*
* @return {string} The new uuid
*/
priv.generateUuid = function () {
var S4 = function () {
var i, string = Math.floor(
Math.random() * 0x10000 /* 65536 */
).toString(16);
for (i = string.length; i < 4; i += 1) {
string = "0" + string;
}
return string;
};
return S4() + S4() + "-" +
S4() + "-" +
S4() + "-" +
S4() + "-" +
S4() + S4() + S4();
};
/**
* Create an array containing dictionnary keys
*
* @param {object} dict The object to convert
* @return {array} The array of keys
*/
priv.dictKeys2Array = function (dict) {
var k, newlist = [];
for (k in dict) {
if (dict.hasOwnProperty(k)) {
newlist.push(k);
}
}
return newlist;
};
/**
* Checks a revision format
*
* @param {string} revision The revision string
* @return {boolean} True if ok, else false
*/
priv.checkRevisionFormat = function (revision) {
return (/^[0-9]+-[0-9a-zA-Z_]+$/.test(revision));
};
/**
* Clones an object in deep (without functions)
*
* @param {any} object The object to clone
* @return {any} The cloned object
*/
priv.clone = function (object) {
var tmp = JSON.stringify(object);
if (tmp === undefined) {
return undefined;
}
return JSON.parse(tmp);
};
/**
* Like addJob but also return the method and the index of the storage
*
* @param {string} method The request method
* @param {number} index The storage index
* @param {object} doc The document object
* @param {object} option The request object
* @param {function} callback The callback. Parameters:
* - {string} The request method
* - {number} The storage index
* - {object} The error object
* - {object} The response object
*/
priv.send = function (command, method, index, doc, option, callback) {
var wrapped_callback_success, wrapped_callback_error;
callback = callback || priv.emptyFunction;
wrapped_callback_success = function (response) {
callback(method, index, undefined, response);
};
wrapped_callback_error = function (err) {
callback(method, index, err, undefined);
};
if (method === 'allDocs') {
command.storage(priv.storage_list[index]).allDocs(option).
then(wrapped_callback_success, wrapped_callback_error);
} else {
command.storage(priv.storage_list[index])[method](doc, option).
then(wrapped_callback_success, wrapped_callback_error);
}
};
/**
* Use "send" method to all sub storages.
* Calling "callback" for each storage response.
*
* @param {string} method The request method
* @param {object} doc The document object
* @param {object} option The request option
* @param {function} callback The callback. Parameters:
* - {string} The request method
* - {number} The storage index
* - {object} The error object
* - {object} The response object
*/
priv.sendToAll = function (command, method, doc, option, callback) {
var i;
for (i = 0; i < priv.storage_list.length; i += 1) {
priv.send(command, method, i, doc, option, callback);
}
};
/**
* Use "send" method to all sub storages.
* Calling "callback" only with the first response
*
* @param {string} method The request method
* @param {object} doc The document object
* @param {object} option The request option
* @param {function} callback The callback. Parameters:
* - {string} The request method
* - {object} The error object
* - {object} The response object
*/
priv.sendToAllFastestResponseOnly = function (command, method,
doc, option, callback) {
var i, callbackWrapper, error_count;
error_count = 0;
callbackWrapper = function (method, index, err, response) {
/*jslint unparam: true */
if (err) {
error_count += 1;
if (error_count === priv.storage_list.length) {
return callback(method, err, response);
}
}
callback(method, err, response);
};
for (i = 0; i < priv.storage_list.length; i += 1) {
priv.send(command, method, i, doc, option, callbackWrapper);
}
};
/**
* Use "sendToAll" method, calling "callback" at the last response with
* the response list
*
* @param {string} method The request method
* @param {object} doc The document object
* @param {object} option The request option
* @return {function} callback The callback. Parameters:
* - {string} The request method
* - {object} The error object
* - {object} The response object
*/
priv.sendToAllGetResponseList = function (command, method,
doc, option, callback) {
var wrapper, callback_count = 0, response_list = [], error_list = [];
response_list.length = priv.storage_list.length;
wrapper = function (method, index, err, response) {
/*jslint unparam: true */
error_list[index] = err;
response_list[index] = response;
callback_count += 1;
if (callback_count === priv.storage_list.length) {
callback(error_list, response_list);
}
};
priv.sendToAll(command, method, doc, option, wrapper);
};
/**
* Checks if the sub storage are identical
* @method check
* @param {object} command The JIO command
*/
that.check = function (command, param, option) {
function callback(err) {
if (err) {
return command.error(err);
}
command.success();
}
if (!param._id) {
return callback({"status": 501});
}
priv.check(command, param, option, callback);
};
/**
* Repair the sub storages to make them identical
* @method repair
* @param {object} command The JIO command
*/
that.repair = function (command, param, option) {
function callback(err) {
if (err) {
return command.error(err);
}
command.success();
}
if (!param._id) {
return callback({
"status": 501
});
}
priv.repair(
command,
param,
option,
true,
callback
);
};
priv.check = function (command, doc, option, success, error) {
priv.repair(command, doc, option, false, success, error);
};
priv.repair = function (command, doc, option, repair, callback) {
var functions = {};
callback = callback || priv.emptyFunction;
option = option || {};
functions.begin = function () {
// // XXX make revision storage check and repair
// // to enable check/repair sub storage from this storage
// // by calling this function just below
// //functions.repairAllSubStorages();
// // else we assume that sub storages are good
// functions.getAllDocuments(functions.newParam(
// doc,
// option,
// repair
// ));
// };
// functions.repairAllSubStorages = function () {
var i;
for (i = 0; i < priv.storage_list.length; i += 1) {
priv.send(
command,
repair ? "repair" : "check",
i,
doc,
option,
functions.repairAllSubStoragesCallback
);
}
};
functions.repair_sub_storages_count = 0;
functions.repairAllSubStoragesCallback = function (method,
index, err, response) {
/*jslint unparam: true */
if (err) {
return command.error(err);
}
functions.repair_sub_storages_count += 1;
if (functions.repair_sub_storages_count === priv.storage_list.length) {
functions.getAllDocuments(functions.newParam(
doc,
option,
repair
));
}
};
functions.newParam = function (doc, option, repair) {
var param = {
"doc": doc, // the document to repair
"option": option,
"repair": repair,
"responses": {
"count": 0,
"list": [
// 0: response0
// 1: response1
// 2: response2
],
"stats": {
// responseA: [0, 1]
// responseB: [2]
},
"stats_items": [
// 0: [responseA, [0, 1]]
// 1: [responseB, [2]]
],
"attachments": {
// attachmentA : {_id: attachmentA, _revs_info, _content_type: ..}
// attachmentB : {_id: attachmentB, _revs_info, _content_type: ..}
}
},
"conflicts": {
// revC: true
// revD: true
},
"deal_result_state": "ok",
"my_rev": undefined
};
param.responses.list.length = priv.storage_list.length;
return param;
};
functions.getAllDocuments = function (param) {
var i, metadata, cloned_option;
metadata = priv.clone(param.doc);
cloned_option = priv.clone(param.option);
cloned_option.conflicts = true;
cloned_option.revs = true;
cloned_option.revs_info = true;
for (i = 0; i < priv.storage_list.length; i += 1) {
// if the document is not loaded
priv.send(command, "get", i,
metadata, cloned_option, functions.dealResults(param));
}
functions.finished_count += 1;
};
functions.dealResults = function (param) {
return function (method, index, err, response) {
/*jslint unparam: true */
var response_object = {};
if (param.deal_result_state !== "ok") {
// deal result is in a wrong state, exit
return;
}
if (err) {
if (err.status !== 404) {
// get document failed, exit
param.deal_result_state = "error";
callback({
"status": 409,
"message": "An error occured on the sub storage",
"reason": err.reason
}, undefined);
return;
}
}
response = response.data;
// success to get the document
// add the response in memory
param.responses.count += 1;
param.responses.list[index] = response;
// add the conflicting revision for other synchronizations
functions.addConflicts(param, (response || {})._conflicts);
if (param.responses.count !== param.responses.list.length) {
// this is not the last response, wait for the next response
return;
}
// this is now the last response
functions.makeResponsesStats(param.responses);
//console.log(JSON.parse(JSON.stringify(param.responses)));
if (param.responses.stats_items.length === 1) {
// the responses are equals!
response_object.ok = true;
response_object.id = param.doc._id;
if (doc._rev) {
response_object.rev = doc._rev;
// "rev": (typeof param.responses.list[0] === "object" ?
// param.responses.list[0]._rev : undefined)
}
callback(undefined, response_object);
return;
}
// the responses are different
if (param.repair === false) {
// do not repair
callback({
"status": 409,
"message": "Some documents are different in the sub storages",
"reason": "Storage contents differ"
}, undefined);
return;
}
// repair
functions.getAttachments(param);
};
};
functions.addConflicts = function (param, list) {
var i;
list = list || [];
for (i = 0; i < list.length; i += 1) {
param.conflicts[list[i]] = true;
}
};
functions.makeResponsesStats = function (responses) {
var i, str_response;
for (i = 0; i < responses.count; i += 1) {
str_response = JSON.stringify(responses.list[i]);
if (responses.stats[str_response] === undefined) {
responses.stats[str_response] = [];
responses.stats_items.push([
str_response,
responses.stats[str_response]
]);
}
responses.stats[str_response].push(i);
}
};
functions.getAttachments = function (param) {
var response, parsed_response, attachment;
for (response in param.responses.stats) {
if (param.responses.stats.hasOwnProperty(response)) {
parsed_response = JSON.parse(response);
for (attachment in parsed_response._attachments) {
if ((parsed_response._attachments).hasOwnProperty(attachment)) {
functions.get_attachment_count += 1;
priv.send(
command,
"getAttachment",
param.responses.stats[response][0],
{
"_id": param.doc._id,
"_attachment": attachment,
"_rev": JSON.parse(response)._rev
},
param.option,
functions.getAttachmentsCallback(
param,
attachment,
param.responses.stats[response]
)
);
}
}
}
}
};
functions.get_attachment_count = 0;
functions.getAttachmentsCallback = function (param, attachment_id) {
return function (method, index, err, response) {
/*jslint unparam: true */
if (err) {
callback({
"status": 409,
"message": "Unable to retreive attachments",
"reason": err.reason
}, undefined);
return;
}
response = response.data;
functions.get_attachment_count -= 1;
param.responses.attachments[attachment_id] = response;
if (functions.get_attachment_count === 0) {
functions.synchronizeAllSubStorage(param);
if (param.option.synchronize_conflicts !== false) {
functions.synchronizeConflicts(param);
}
}
};
};
functions.synchronizeAllSubStorage = function (param) {
var i, j, len = param.responses.stats_items.length;
for (i = 0; i < len; i += 1) {
// browsing responses
for (j = 0; j < len; j += 1) {
// browsing storage list
if (i !== j) {
functions.synchronizeResponseToSubStorage(
param,
param.responses.stats_items[i][0],
param.responses.stats_items[j][1]
);
}
}
}
functions.finished_count -= 1;
};
functions.synchronizeResponseToSubStorage = function (
param,
response,
storage_list
) {
var i, new_doc, attachment_to_put = [];
if (response === undefined) {
// no response to sync
return;
}
new_doc = JSON.parse(response);
new_doc._revs = new_doc._revisions;
delete new_doc._rev;
delete new_doc._revisions;
delete new_doc._conflicts;
for (i in new_doc._attachments) {
if (new_doc._attachments.hasOwnProperty(i)) {
attachment_to_put.push({
"_id": i,
"_content_type": new_doc._attachments[i].content_type,
"_revs_info": new_doc._revs_info
});
}
}
for (i = 0; i < storage_list.length; i += 1) {
functions.finished_count += attachment_to_put.length || 1;
priv.send(
command,
"put",
storage_list[i],
new_doc,
param.option,
functions.putAttachments(param, attachment_to_put)
);
}
functions.finished_count += 1;
functions.finished();
};
functions.synchronizeConflicts = function (param) {
var rev, new_doc, new_option;
new_option = priv.clone(param.option);
new_option.synchronize_conflict = false;
for (rev in param.conflicts) {
if (param.conflicts.hasOwnProperty(rev)) {
new_doc = priv.clone(param.doc);
new_doc._rev = rev;
// no need to synchronize all the conflicts again, do it once
functions.getAllDocuments(functions.newParam(
new_doc,
new_option,
param.repair
));
}
}
};
functions.putAttachments = function (param, attachment_to_put) {
return function (method, index, err, response) {
/*jslint unparam: true */
var i, attachment;
if (err) {
return callback({
"status": 409,
"message": "Unable to copy attachments",
"reason": err.reason
}, undefined);
}
for (i = 0; i < attachment_to_put.length; i += 1) {
attachment = {
"_id": param.doc._id,
"_attachment": attachment_to_put[i]._id,
"_content_type": attachment_to_put[i]._content_type,
"_revs_info": attachment_to_put[i]._revs_info,
// "_revs_info": param.responses.list[index]._revs_info,
"_data": param.responses.attachments[attachment_to_put[i]._id]
};
priv.send(
command,
"putAttachment",
index,
attachment,
option,
functions.putAttachmentCallback(param)
);
}
if (attachment_to_put.length === 0) {
functions.finished();
}
};
};
functions.putAttachmentCallback = function (param) {
/*jslint unparam: true */
return function (method, index, err, response) {
if (err) {
return callback(err, undefined);
}
functions.finished();
};
};
functions.finished_count = 0;
functions.finished = function () {
var response_object = {};
functions.finished_count -= 1;
if (functions.finished_count === 0) {
response_object.ok = true;
response_object.id = doc._id;
if (doc._rev) {
response_object.rev = doc._rev;
}
callback(undefined, response_object);
}
};
functions.begin();
};
/**
* The generic method to use
* @method genericRequest
* @param {object} command The JIO command
* @param {string} method The method to use
*/
that.genericRequest = function (command, method, param, option) {
var doc = param;
doc._id = doc._id || priv.generateUuid();
priv.sendToAllFastestResponseOnly(
command,
method,
doc,
option,
function (method, err, response) {
/*jslint unparam: true */
if (err) {
return command.error(err);
}
command.success(response);
}
);
};
/**
* Post the document metadata to all sub storages
* @method post
* @param {object} command The JIO command
*/
that.post = function (command, metadata, option) {
that.genericRequest(command, "post", metadata, option);
};
/**
* Put the document metadata to all sub storages
* @method put
* @param {object} command The JIO command
*/
that.put = function (command, metadata, option) {
that.genericRequest(command, "put", metadata, option);
};
/**
* Put an attachment to a document to all sub storages
* @method putAttachment
* @param {object} command The JIO command
*/
that.putAttachment = function (command, param, option) {
that.genericRequest(command, "putAttachment", param, option);
};
/**
* Get the document from all sub storages, get the fastest.
* @method get
* @param {object} command The JIO command
*/
that.get = function (command, param, option) {
that.genericRequest(command, "get", param, option);
};
/**
* Get the attachment from all sub storages, get the fastest.
* @method getAttachment
* @param {object} command The JIO command
*/
that.getAttachment = function (command, param, option) {
that.genericRequest(command, "getAttachment", param, option);
};
/**
* Remove the document from all sub storages.
* @method remove
* @param {object} command The JIO command
*/
that.remove = function (command, param, option) {
that.genericRequest(command, "remove", param, option);
};
/**
* Remove the attachment from all sub storages.
* @method remove
* @param {object} command The JIO command
*/
that.removeAttachment = function (command, param, option) {
that.genericRequest(command, "removeAttachment", param, option);
};
});
}));
/*
* JIO extension for resource replication.
* Copyright (C) 2013 Nexedi SA
*
* This library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*jslint indent: 2, maxlen: 80, nomen: true */
/*global define, module, require, jIO, RSVP, JSON */
(function (root, dependencies, factory) {
"use strict";
if (typeof define === 'function' && define.amd) {
return define(dependencies, function () {
return factory(require);
});
}
if (typeof require === 'function') {
module.exports = factory(require);
return;
}
root.replicate_storage = factory(function (name) {
return {
"jio": jIO,
"rsvp": RSVP
}[name];
});
}(this, ['jio', 'rsvp'], function (require) {
"use strict";
var Promise = require('rsvp').Promise,
all = require('rsvp').all,
dictUpdate = require('jio').util.dictUpdate,
addStorageFunction = require('jio').addStorage;
/**
* Make a clone of an object WITHOUT _xxx (except _id). This is what is
* compared when compared when checking answers from multiple storages
* @method cleanClone
* @param {Object} obj to clone
* @return {Object} clones object
**/
function cleanClone (obj) {
var prop, r = {};
for (prop in obj) {
if (obj.hasOwnProperty(prop)) {
if (prop.charCodeAt(0) !== 95 || prop === "_id") {
r[prop] = obj[prop];
}
}
}
return r;
};
/**
* Generate a checksum from a passed string to compare the response returned
* by multiple storages for the same requests.
* @method checksum
* @param {Object} obj to generate a checksum for
* @return {Integer} checksum
**/
function checksum (obj) {
var r, i, str = JSON.stringify(obj);
for(r = 0, i = 0; i < str.length; i += 1) {
r = (r << 5) - r + str.charCodeAt(i);
r &= r;
}
return r;
};
/**
* Executes a sequence of *then* callbacks. It acts like
* `smth().then(callback).then(callback)...`. The first callback is called
* with no parameter.
*
* Elements of `then_list` array can be a function or an array contaning at
* most three *then* callbacks: *onFulfilled*, *onRejected*, *onNotified*.
*
* When `cancel()` is executed, each then promises are cancelled at the same
* time.
*
* sequence(then_list): Promise
*
* @param {Array} then_list An array of *then* callbacks
* @return {Promise} A new promise
*/
function sequence(then_list) {
var promise_list = [];
return new Promise(function (resolve, reject, notify) {
var i, length = then_list.length;
promise_list[0] = new Promise(function (resolve) {
resolve();
});
for (i = 0; i < length; i += 1) {
if (Array.isArray(then_list[i])) {
promise_list[i + 1] = promise_list[i].
then(then_list[i][0], then_list[i][1], then_list[i][2]);
} else {
promise_list[i + 1] = promise_list[i].then(then_list[i]);
}
}
promise_list[i].then(resolve, reject, notify);
}, function () {
var i, length = promise_list.length;
for (i = 0; i < length; i += 1) {
promise_list[i].cancel();
}
});
}
function success(promise) {
return new Promise(function (resolve, reject, notify) {
/*jslint unparam: true*/
promise.then(resolve, resolve, notify);
}, function () {
promise.cancel();
});
}
/**
* Responds with the last resolved promise answer recieved. If all promises
* are rejected, it returns the latest rejected promise answer
* received. Promises are cancelled only by calling
* `last(promise_list).cancel()`.
*
* last(promise_list): Promise
*
* @param {Array} promise_list An array of promises
* @param {Integer} master The "promise" with id authority
* @param {Object} temp Any temporary data created by master
* @return {Promise} A new promise
*/
// NOTE: added master parameter for master-slave storage
function last(promise_list, master, temp) {
var length = promise_list.length;
promise_list = promise_list.slice();
return new Promise(function (resolve, reject, notify) {
var index, last_answer, count = 0, error_count = 0;
function resolver() {
return function (answer) {
count += 1;
if (count === length) {
if (temp) {
answer._temp = temp;
}
return resolve(answer);
}
last_answer = answer;
};
}
function rejecter() {
return function (answer) {
error_count += 1;
if (error_count === length) {
return reject(answer);
}
count += 1;
if (count === length) {
if (temp) {
answer._temp = temp;
}
return resolve(last_answer);
}
};
}
function notifier(index) {
return function (notification) {
notify({
"index": index,
"value": notification
});
};
}
if (typeof master === "number") {
length = 1;
promise_list[master].then(resolver(), rejecter(), notifier(master));
} else {
for (index = 0; index < length; index += 1) {
promise_list[index].then(resolver(), rejecter(), notifier(index));
}
}
}, function () {
var index;
for (index = 0; index < length; index += 1) {
promise_list[index].cancel();
}
});
}
/**
* Test responses of a GET request for coherence (will set _conflict)
* and missing (will set _missing) on the returned document
* @method checkAndReturn
* @param {Object} promise_list List of responses received
* @return {Promise} A new promise
**/
function checkAndReturn(promise_list) {
var length = promise_list.length;
promise_list = promise_list.slice();
return new Promise(function (resolve, reject, notify) {
var index, trace, conflict_list, count, error_count, tag, doc;
count = 0;
error_count = 0;
conflict_list = [];
tag = function (reply) {
if (conflict_list.length) {
reply._conflict_list = conflict_list;
}
if (error_count) {
reply._missing = true;
}
return reply;
};
function resolver(answer) {
if (trace === undefined) {
doc = answer;
trace = checksum(cleanClone(answer.data));
} else {
if (trace !== checksum(cleanClone(answer.data))) {
conflict_list.push(cleanClone(answer.data));
}
}
count += 1;
if (count === length) {
return resolve(tag(answer));
}
}
function rejecter(answer) {
error_count += 1;
if (error_count === length) {
return reject(answer);
}
count += 1;
if (count === length) {
return resolve(tag(doc));
}
}
function notifier(index) {
return function (notification) {
notify({
"index": index,
"value": notification
});
};
}
for (index = 0; index < length; index += 1) {
promise_list[index].then(resolver, rejecter, notifier(index));
}
}, function () {
var index;
for (index = 0; index < length; index += 1) {
promise_list[index].cancel();
}
});
}
function ReplicateStorage(spec) {
if (!Array.isArray(spec.storage_list)) {
throw new TypeError("ReplicateStorage(): " +
"storage_list is not of type array");
}
this._storage_list = spec.storage_list;
this._master = spec.master;
};
ReplicateStorage.prototype.post = function (command, metadata, option) {
var index, subindex,
storages = this._storage_list,
promise_list = [],
priority_list = [],
length = storages.length,
master = this._master;
// first run priority storage
if (master !== undefined) {
priority_list[0] = success(
command.storage(storages[master]).post(metadata, option)
);
} else {
for (index = 0; index < length; index += 1) {
promise_list[index] = success(
command.storage(storages[index]).post(metadata, option)
);
}
}
// first master, then slave
sequence([
function () {
if (master !== undefined) {
return last(priority_list, master);
}
return {};
},
function (response) {
var method, subindex = 0;
if (response.id) {
metadata._id = response.id;
method = "put";
} else {
// TODO: no-access master 404/offline handling
}
for (index = 0; index < length; index += 1) {
if (index !== master) {
promise_list[subindex] = success(
command.storage(storages[index])
[method || "post"](metadata, option)
);
subindex += 1;
}
}
return last(promise_list);
},
[command.success, command.error]
]);
};
ReplicateStorage.prototype.put = function (command, metadata, option) {
var index, subindex,
storages = this._storage_list,
promise_list = [],
priority_list = [],
length = storages.length,
master = this._master;
// setup master storage or all
if (master !== undefined) {
priority_list[0] = success(
command.storage(storages[master]).put(metadata, option)
);
} else {
for (index = 0; index < length; index += 1) {
promise_list[index] = success(
command.storage(storages[index]).put(metadata, option)
);
}
}
// run master, then slave
sequence([
function () {
return last(priority_list, master);
},
function (response) {
var subindex;
switch (true) {
// NOTE: this means if the master is 503, nothing will be saved on
// the slave? Is this what I would want? YES
// NOTE: leaving this will allow test pages to be saved, but
// will break at another place where 500 should not pass
case response.status >= 500:
// command.error(response);
// break;
// HACK: why does 204 return status code 0 on promises?
case response.status === 0:
default:
for (index = 0, subindex = 0; index < length; index += 1) {
if (index !== master) {
promise_list[subindex] = success(
command.storage(storages[index]).put(metadata, option)
);
subindex += 1;
}
}
return last(promise_list, undefined, response._temp);
}
},
[command.success, command.error]
]);
};
ReplicateStorage.prototype.putAttachment = function (command, param, option) {
var promise_list = [], index, length = this._storage_list.length;
for (index = 0; index < length; index += 1) {
promise_list[index] = success(
command.storage(this._storage_list[index]).putAttachment(param, option)
);
}
sequence([function () {
return last(promise_list);
}, [command.success, command.error]]);
};
ReplicateStorage.prototype.remove = function (command, param, option) {
var promise_list = [], index, length = this._storage_list.length;
for (index = 0; index < length; index += 1) {
promise_list[index] = success(
command.storage(this._storage_list[index]).remove(param, option)
);
}
sequence([function () {
return last(promise_list);
}, [command.success, command.error]]);
};
ReplicateStorage.prototype.removeAttachment = function (
command,
param,
option
) {
var promise_list = [], index, length = this._storage_list.length;
for (index = 0; index < length; index += 1) {
promise_list[index] = success(
command.storage(this._storage_list[index]).
removeAttachment(param, option)
);
}
sequence([function () {
return last(promise_list);
}, [command.success, command.error]]);
};
ReplicateStorage.prototype.get = function (command, param, option) {
var promise_list = [], index, length = this._storage_list.length;
for (index = 0; index < length; index += 1) {
promise_list[index] =
command.storage(this._storage_list[index]).get(param, option);
}
sequence([function () {
return checkAndReturn(promise_list);
}, [command.success, command.error]]);
};
ReplicateStorage.prototype.getAttachment = function (command, param, option) {
var promise_list = [], index, length = this._storage_list.length;
for (index = 0; index < length; index += 1) {
promise_list[index] = success(
command.storage(this._storage_list[index]).getAttachment(param, option)
);
}
sequence([function () {
return last(promise_list);
}, [command.success, command.error]]);
};
ReplicateStorage.prototype.allDocs = function (command, param, option) {
/*jslint unparam: true */
var promise_list = [], index, length = this._storage_list.length;
for (index = 0; index < length; index += 1) {
promise_list[index] =
success(command.storage(this._storage_list[index]).allDocs(option, param));
}
sequence([function () {
return all(promise_list);
}, function (answers) {
var i, j, k, l, record, reply, count, total, base, test, must_add,
empty_reply, rows_len, rows, len = answers.length;
for (i = 0; i < len; i += 1) {
reply = answers[i];
if (reply.result === "success") {
total = reply.data.total_rows;
if (total === 0) {
empty_reply = true;
}
// loop records returned in response
for (j = 0; j < total; j += 1) {
record = reply.data.rows[j];
must_add = undefined;
if (rows === undefined) {
rows = [record];
} else {
count = rows.length;
// loop records already in rows object
for (k = 0; k < count; k += 1) {
base = rows[k];
// record exists, test for coherence
if (base.id === record.id) {
must_add = undefined;
if (checksum(cleanClone(base)) !== checksum(record)) {
if (!base._conflict_list) {
base._conflict_list = [base];
}
base._conflict_list.push(record);
}
// record does not exists, must add
} else {
must_add = true;
}
}
// add missing record
if (must_add) {
// if on 2+ iteration, this means a 404 on previous storages
if (i > 0) {
record._missing = true;
}
rows.push(record);
}
}
}
}
}
// if a storage returns rows = 0, make sure all records are labelled
rows_len = (rows || []).length;
if (empty_reply && rows_len > 0) {
for (l = 0; l < rows_len; l += 1) {
rows[l]._missing = true;
}
}
return {"data": {"total_rows": (rows || []).length, "rows": rows || []}};
}, [command.success, command.error]]);
};
ReplicateStorage.prototype.check = function (command, param, option) {
return command.error(501);
};
ReplicateStorage.prototype.repair = function (command, param) {
var i, promise_list, length, index, that;
promise_list = [];
length = this._storage_list.length;
// NOTE: we can't pass full document, because of select_list...
for (i = 0; i < length; i += 1) {
promise_list[i] = command.storage(this._storage_list[i]).put(param);
}
sequence([function () {
return all(promise_list);
}, function (answers) {
var i;
for (i = 0; i < answers.length; i += 1) {
if (answers[i].result !== "success") {
return command.error(409);
}
}
command.success();
}]);
};
addStorageFunction('replicate', ReplicateStorage);
}));
/*jslint indent: 2, maxlen: 80, nomen: true */
/*global jIO, hex_sha256, define */
/**
* JIO Revision Storage.
* It manages document version and can generate conflicts.
* Description:
* {
* "type": "revision",
* "sub_storage": <sub storage description>
* }
*/
// define([module_name], [dependencies], module);
(function (dependencies, module) {
"use strict";
if (typeof define === 'function' && define.amd) {
return define(dependencies, module);
}
module(jIO, {hex_sha256: hex_sha256});
}(['jio', 'sha256'], function (jIO, sha256) {
"use strict";
var tool = {
"readBlobAsBinaryString": jIO.util.readBlobAsBinaryString,
"uniqueJSONStringify": jIO.util.uniqueJSONStringify
};
jIO.addStorage("revision", function (spec) {
var that = this, priv = {};
spec = spec || {};
// ATTRIBUTES //
priv.doc_tree_suffix = ".revision_tree.json";
priv.sub_storage = spec.sub_storage;
// METHODS //
/**
* Clones an object in deep (without functions)
* @method clone
* @param {any} object The object to clone
* @return {any} The cloned object
*/
priv.clone = function (object) {
var tmp = JSON.stringify(object);
if (tmp === undefined) {
return undefined;
}
return JSON.parse(tmp);
};
/**
* Generate a new uuid
* @method generateUuid
* @return {string} The new uuid
*/
priv.generateUuid = function () {
var S4 = function () {
/* 65536 */
var i, string = Math.floor(
Math.random() * 0x10000
).toString(16);
for (i = string.length; i < 4; i += 1) {
string = '0' + string;
}
return string;
};
return S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() +
S4() + S4();
};
/**
* Generates a hash code of a string
* @method hashCode
* @param {string} string The string to hash
* @return {string} The string hash code
*/
priv.hashCode = function (string) {
return sha256.hex_sha256(string);
};
/**
* Checks a revision format
* @method checkDocumentRevisionFormat
* @param {object} doc The document object
* @return {object} null if ok, else error object
*/
priv.checkDocumentRevisionFormat = function (doc) {
var send_error = function (message) {
return {
"status": 409,
"message": message,
"reason": "Wrong revision"
};
};
if (typeof doc._rev === "string") {
if (/^[0-9]+-[0-9a-zA-Z]+$/.test(doc._rev) === false) {
return send_error("The document revision does not match " +
"^[0-9]+-[0-9a-zA-Z]+$");
}
}
if (typeof doc._revs === "object") {
if (typeof doc._revs.start !== "number" ||
typeof doc._revs.ids !== "object" ||
typeof doc._revs.ids.length !== "number") {
return send_error(
"The document revision history is not well formated"
);
}
}
if (typeof doc._revs_info === "object") {
if (typeof doc._revs_info.length !== "number") {
return send_error("The document revision information " +
"is not well formated");
}
}
};
/**
* Creates a new document tree
* @method newDocTree
* @return {object} The new document tree
*/
priv.newDocTree = function () {
return {"children": []};
};
/**
* Convert revs_info to a simple revisions history
* @method revsInfoToHistory
* @param {array} revs_info The revs info
* @return {object} The revisions history
*/
priv.revsInfoToHistory = function (revs_info) {
var i, revisions = {
"start": 0,
"ids": []
};
revs_info = revs_info || [];
if (revs_info.length > 0) {
revisions.start = parseInt(revs_info[0].rev.split('-')[0], 10);
}
for (i = 0; i < revs_info.length; i += 1) {
revisions.ids.push(revs_info[i].rev.split('-')[1]);
}
return revisions;
};
/**
* Convert the revision history object to an array of revisions.
* @method revisionHistoryToList
* @param {object} revs The revision history
* @return {array} The revision array
*/
priv.revisionHistoryToList = function (revs) {
var i, start = revs.start, new_list = [];
for (i = 0; i < revs.ids.length; i += 1, start -= 1) {
new_list.push(start + "-" + revs.ids[i]);
}
return new_list;
};
/**
* Convert revision list to revs info.
* @method revisionListToRevsInfo
* @param {array} revision_list The revision list
* @param {object} doc_tree The document tree
* @return {array} The document revs info
*/
priv.revisionListToRevsInfo = function (revision_list, doc_tree) {
var revisionListToRevsInfoRec, revs_info = [], j;
for (j = 0; j < revision_list.length; j += 1) {
revs_info.push({"rev": revision_list[j], "status": "missing"});
}
revisionListToRevsInfoRec = function (index, doc_tree) {
var child, i;
if (index < 0) {
return;
}
for (i = 0; i < doc_tree.children.length; i += 1) {
child = doc_tree.children[i];
if (child.rev === revision_list[index]) {
revs_info[index].status = child.status;
revisionListToRevsInfoRec(index - 1, child);
}
}
};
revisionListToRevsInfoRec(revision_list.length - 1, doc_tree);
return revs_info;
};
/**
* Update a document metadata revision properties
* @method fillDocumentRevisionProperties
* @param {object} doc The document object
* @param {object} doc_tree The document tree
*/
priv.fillDocumentRevisionProperties = function (doc, doc_tree) {
if (doc._revs_info) {
doc._revs = priv.revsInfoToHistory(doc._revs_info);
} else if (doc._revs) {
doc._revs_info = priv.revisionListToRevsInfo(
priv.revisionHistoryToList(doc._revs),
doc_tree
);
} else if (doc._rev) {
doc._revs_info = priv.getRevisionInfo(doc._rev, doc_tree);
doc._revs = priv.revsInfoToHistory(doc._revs_info);
} else {
doc._revs_info = [];
doc._revs = {"start": 0, "ids": []};
}
if (doc._revs.start > 0) {
doc._rev = doc._revs.start + "-" + doc._revs.ids[0];
} else {
delete doc._rev;
}
};
/**
* Generates the next revision of a document.
* @methode generateNextRevision
* @param {object} doc The document metadata
* @param {boolean} deleted_flag The deleted flag
* @return {array} 0:The next revision number and 1:the hash code
*/
priv.generateNextRevision = function (doc, deleted_flag) {
var string, revision_history, revs_info;
doc = priv.clone(doc) || {};
revision_history = doc._revs;
revs_info = doc._revs_info;
delete doc._rev;
delete doc._revs;
delete doc._revs_info;
string = tool.uniqueJSONStringify(doc) +
tool.uniqueJSONStringify(revision_history) +
JSON.stringify(deleted_flag ? true : false);
revision_history.start += 1;
revision_history.ids.unshift(priv.hashCode(string));
doc._revs = revision_history;
doc._rev = revision_history.start + "-" + revision_history.ids[0];
revs_info.unshift({
"rev": doc._rev,
"status": deleted_flag ? "deleted" : "available"
});
doc._revs_info = revs_info;
return doc;
};
/**
* Gets the revs info from the document tree
* @method getRevisionInfo
* @param {string} revision The revision to search for
* @param {object} doc_tree The document tree
* @return {array} The revs info
*/
priv.getRevisionInfo = function (revision, doc_tree) {
var getRevisionInfoRec;
getRevisionInfoRec = function (doc_tree) {
var i, child, revs_info;
for (i = 0; i < doc_tree.children.length; i += 1) {
child = doc_tree.children[i];
if (child.rev === revision) {
return [{"rev": child.rev, "status": child.status}];
}
revs_info = getRevisionInfoRec(child);
if (revs_info.length > 0 || revision === undefined) {
revs_info.push({"rev": child.rev, "status": child.status});
return revs_info;
}
}
return [];
};
return getRevisionInfoRec(doc_tree);
};
priv.updateDocumentTree = function (doc, doc_tree) {
var revs_info, updateDocumentTreeRec;
doc = priv.clone(doc);
revs_info = doc._revs_info;
updateDocumentTreeRec = function (doc_tree, revs_info) {
var i, child, info;
if (revs_info.length === 0) {
return;
}
info = revs_info.pop();
for (i = 0; i < doc_tree.children.length; i += 1) {
child = doc_tree.children[i];
if (child.rev === info.rev) {
return updateDocumentTreeRec(child, revs_info);
}
}
doc_tree.children.unshift({
"rev": info.rev,
"status": info.status,
"children": []
});
updateDocumentTreeRec(doc_tree.children[0], revs_info);
};
updateDocumentTreeRec(doc_tree, priv.clone(revs_info));
};
priv.send = function (command, method, doc, option, callback) {
var storage = command.storage(priv.sub_storage);
function onSuccess(success) {
callback(undefined, success);
}
function onError(err) {
callback(err, undefined);
}
if (method === 'allDocs') {
storage.allDocs(option).then(onSuccess, onError);
} else {
storage[method](doc, option).then(onSuccess, onError);
}
};
priv.getWinnerRevsInfo = function (doc_tree) {
var revs_info = [], getWinnerRevsInfoRec;
getWinnerRevsInfoRec = function (doc_tree, tmp_revs_info) {
var i;
if (doc_tree.rev) {
tmp_revs_info.unshift({
"rev": doc_tree.rev,
"status": doc_tree.status
});
}
if (doc_tree.children.length === 0) {
if (revs_info.length === 0 ||
(revs_info[0].status !== "available" &&
tmp_revs_info[0].status === "available") ||
(tmp_revs_info[0].status === "available" &&
revs_info.length < tmp_revs_info.length)) {
revs_info = priv.clone(tmp_revs_info);
}
}
for (i = 0; i < doc_tree.children.length; i += 1) {
getWinnerRevsInfoRec(doc_tree.children[i], tmp_revs_info);
}
tmp_revs_info.shift();
};
getWinnerRevsInfoRec(doc_tree, []);
return revs_info;
};
priv.getConflicts = function (revision, doc_tree) {
var conflicts = [], getConflictsRec;
getConflictsRec = function (doc_tree) {
var i;
if (doc_tree.rev === revision) {
return;
}
if (doc_tree.children.length === 0) {
if (doc_tree.status !== "deleted") {
conflicts.push(doc_tree.rev);
}
}
for (i = 0; i < doc_tree.children.length; i += 1) {
getConflictsRec(doc_tree.children[i]);
}
};
getConflictsRec(doc_tree);
return conflicts.length === 0 ? undefined : conflicts;
};
priv.get = function (command, doc, option, callback) {
priv.send(command, "get", doc, option, callback);
};
priv.put = function (command, doc, option, callback) {
priv.send(command, "put", doc, option, callback);
};
priv.remove = function (command, doc, option, callback) {
priv.send(command, "remove", doc, option, callback);
};
priv.getAttachment = function (command, attachment, option, callback) {
priv.send(command, "getAttachment", attachment, option, callback);
};
priv.putAttachment = function (command, attachment, option, callback) {
priv.send(command, "putAttachment", attachment, option, callback);
};
priv.removeAttachment = function (command, attachment, option, callback) {
priv.send(command, "removeAttachment", attachment, option, callback);
};
priv.getDocument = function (command, doc, option, callback) {
doc = priv.clone(doc);
doc._id = doc._id + "." + doc._rev;
delete doc._attachment;
delete doc._rev;
delete doc._revs;
delete doc._revs_info;
priv.get(command, doc, option, callback);
};
priv.putDocument = function (command, doc, option, callback) {
doc = priv.clone(doc);
doc._id = doc._id + "." + doc._rev;
delete doc._attachment;
delete doc._data;
delete doc._mimetype;
delete doc._content_type;
delete doc._rev;
delete doc._revs;
delete doc._revs_info;
priv.put(command, doc, option, callback);
};
priv.getRevisionTree = function (command, doc, option, callback) {
doc = priv.clone(doc);
doc._id = doc._id + priv.doc_tree_suffix;
priv.get(command, doc, option, function (err, response) {
if (err) {
return callback(err, response);
}
if (response.data && response.data.children) {
response.data.children = JSON.parse(response.data.children);
}
return callback(err, response);
});
};
priv.getAttachmentList = function (command, doc, option, callback) {
var attachment_id, dealResults, state = "ok", result_list = [], count = 0;
dealResults = function (attachment_id, attachment_meta) {
return function (err, response) {
if (state !== "ok") {
return;
}
count -= 1;
if (err) {
if (err.status === 404) {
result_list.push(undefined);
} else {
state = "error";
return callback(err, undefined);
}
}
result_list.push({
"_attachment": attachment_id,
"_data": response.data,
"_content_type": attachment_meta.content_type
});
if (count === 0) {
state = "finished";
callback(undefined, {"data": result_list});
}
};
};
for (attachment_id in doc._attachments) {
if (doc._attachments.hasOwnProperty(attachment_id)) {
count += 1;
priv.getAttachment(
command,
{"_id": doc._id, "_attachment": attachment_id},
option,
dealResults(attachment_id, doc._attachments[attachment_id])
);
}
}
if (count === 0) {
callback(undefined, {"data": []});
}
};
priv.putAttachmentList = function (command, doc, option,
attachment_list, callback) {
var i, dealResults, state = "ok", count = 0, attachment;
attachment_list = attachment_list || [];
dealResults = function () {
return function (err) {
if (state !== "ok") {
return;
}
count -= 1;
if (err) {
state = "error";
return callback(err, undefined);
}
if (count === 0) {
state = "finished";
callback(undefined, {});
}
};
};
for (i = 0; i < attachment_list.length; i += 1) {
attachment = attachment_list[i];
if (attachment !== undefined) {
count += 1;
attachment._id = doc._id + "." + doc._rev;
priv.putAttachment(command, attachment, option, dealResults(i));
}
}
if (count === 0) {
return callback(undefined, {});
}
};
priv.putDocumentTree = function (command, doc, option, doc_tree, callback) {
doc_tree = priv.clone(doc_tree);
doc_tree._id = doc._id + priv.doc_tree_suffix;
if (doc_tree.children) {
doc_tree.children = JSON.stringify(doc_tree.children);
}
priv.put(command, doc_tree, option, callback);
};
priv.notFoundError = function (message, reason) {
return {
"status": 404,
"message": message,
"reason": reason
};
};
priv.conflictError = function (message, reason) {
return {
"status": 409,
"message": message,
"reason": reason
};
};
priv.revisionGenericRequest = function (command, doc, option,
specific_parameter, onEnd) {
var prev_doc, doc_tree, attachment_list, callback = {};
if (specific_parameter.doc_id) {
doc._id = specific_parameter.doc_id;
}
if (specific_parameter.attachment_id) {
doc._attachment = specific_parameter.attachment_id;
}
callback.begin = function () {
var check_error;
doc._id = doc._id || priv.generateUuid(); // XXX should not generate id
if (specific_parameter.revision_needed && !doc._rev) {
return onEnd(priv.conflictError(
"Document update conflict",
"No document revision was provided"
), undefined);
}
// check revision format
check_error = priv.checkDocumentRevisionFormat(doc);
if (check_error !== undefined) {
return onEnd(check_error, undefined);
}
priv.getRevisionTree(command, doc, option, callback.getRevisionTree);
};
callback.getRevisionTree = function (err, response) {
var winner_info, previous_revision, generate_new_revision;
previous_revision = doc._rev;
generate_new_revision = doc._revs || doc._revs_info ? false : true;
if (err) {
if (err.status !== 404) {
err.message = "Cannot get document revision tree";
return onEnd(err, undefined);
}
}
doc_tree = (response && response.data) || priv.newDocTree();
if (specific_parameter.get || specific_parameter.getAttachment) {
if (!doc._rev) {
winner_info = priv.getWinnerRevsInfo(doc_tree);
if (winner_info.length === 0) {
return onEnd(priv.notFoundError(
"Document not found",
"missing"
), undefined);
}
if (winner_info[0].status === "deleted") {
return onEnd(priv.notFoundError(
"Document not found",
"deleted"
), undefined);
}
doc._rev = winner_info[0].rev;
}
priv.fillDocumentRevisionProperties(doc, doc_tree);
return priv.getDocument(command, doc, option, callback.getDocument);
}
priv.fillDocumentRevisionProperties(doc, doc_tree);
if (generate_new_revision) {
if (previous_revision && doc._revs_info.length === 0) {
// the document history has changed, it means that the document
// revision was wrong. Add a pseudo history to the document
doc._rev = previous_revision;
doc._revs = {
"start": parseInt(previous_revision.split("-")[0], 10),
"ids": [previous_revision.split("-")[1]]
};
doc._revs_info = [{"rev": previous_revision, "status": "missing"}];
}
doc = priv.generateNextRevision(
doc,
specific_parameter.remove
);
}
if (doc._revs_info.length > 1) {
prev_doc = {
"_id": doc._id,
"_rev": doc._revs_info[1].rev
};
if (!generate_new_revision && specific_parameter.putAttachment) {
prev_doc._rev = doc._revs_info[0].rev;
}
}
// force revs_info status
doc._revs_info[0].status = (specific_parameter.remove ?
"deleted" : "available");
priv.updateDocumentTree(doc, doc_tree);
if (prev_doc) {
return priv.getDocument(command, prev_doc,
option, callback.getDocument);
}
if (specific_parameter.remove || specific_parameter.removeAttachment) {
return onEnd(priv.notFoundError(
"Unable to remove an inexistent document",
"missing"
), undefined);
}
priv.putDocument(command, doc, option, callback.putDocument);
};
callback.getDocument = function (err, res_doc) {
var k, conflicts;
if (err) {
if (err.status === 404) {
if (specific_parameter.remove ||
specific_parameter.removeAttachment) {
return onEnd(priv.conflictError(
"Document update conflict",
"Document is missing"
), undefined);
}
if (specific_parameter.get) {
return onEnd(priv.notFoundError(
"Unable to find the document",
"missing"
), undefined);
}
res_doc = {"data": {}};
} else {
err.message = "Cannot get document";
return onEnd(err, undefined);
}
}
res_doc = res_doc.data;
if (specific_parameter.get) {
res_doc._id = doc._id;
res_doc._rev = doc._rev;
if (option.conflicts === true) {
conflicts = priv.getConflicts(doc._rev, doc_tree);
if (conflicts) {
res_doc._conflicts = conflicts;
}
}
if (option.revs === true) {
res_doc._revisions = doc._revs;
}
if (option.revs_info === true) {
res_doc._revs_info = doc._revs_info;
}
return onEnd(undefined, {"data": res_doc});
}
if (specific_parameter.putAttachment ||
specific_parameter.removeAttachment) {
// copy metadata (not beginning by "_" to document
for (k in res_doc) {
if (res_doc.hasOwnProperty(k) && !k.match("^_")) {
doc[k] = res_doc[k];
}
}
}
if (specific_parameter.remove) {
priv.putDocumentTree(command, doc, option,
doc_tree, callback.putDocumentTree);
} else {
priv.getAttachmentList(command, res_doc, option,
callback.getAttachmentList);
}
};
callback.getAttachmentList = function (err, res_list) {
var i, attachment_found = false;
if (err) {
err.message = "Cannot get attachment";
return onEnd(err, undefined);
}
res_list = res_list.data;
attachment_list = res_list || [];
if (specific_parameter.getAttachment) {
// getting specific attachment
for (i = 0; i < attachment_list.length; i += 1) {
if (attachment_list[i] &&
doc._attachment ===
attachment_list[i]._attachment) {
return onEnd(undefined, {"data": attachment_list[i]._data});
}
}
return onEnd(priv.notFoundError(
"Unable to get an inexistent attachment",
"missing"
), undefined);
}
if (specific_parameter.remove_from_attachment_list) {
// removing specific attachment
for (i = 0; i < attachment_list.length; i += 1) {
if (attachment_list[i] &&
specific_parameter.remove_from_attachment_list._attachment ===
attachment_list[i]._attachment) {
attachment_found = true;
attachment_list[i] = undefined;
break;
}
}
if (!attachment_found) {
return onEnd(priv.notFoundError(
"Unable to remove an inexistent attachment",
"missing"
), undefined);
}
}
priv.putDocument(command, doc, option, callback.putDocument);
};
callback.putDocument = function (err) {
var i, attachment_found = false;
if (err) {
err.message = "Cannot post the document";
return onEnd(err, undefined);
}
if (specific_parameter.add_to_attachment_list) {
// adding specific attachment
attachment_list = attachment_list || [];
for (i = 0; i < attachment_list.length; i += 1) {
if (attachment_list[i] &&
specific_parameter.add_to_attachment_list._attachment ===
attachment_list[i]._attachment) {
attachment_found = true;
attachment_list[i] = specific_parameter.add_to_attachment_list;
break;
}
}
if (!attachment_found) {
attachment_list.unshift(specific_parameter.add_to_attachment_list);
}
}
priv.putAttachmentList(
command,
doc,
option,
attachment_list,
callback.putAttachmentList
);
};
callback.putAttachmentList = function (err) {
if (err) {
err.message = "Cannot copy attacments to the document";
return onEnd(err, undefined);
}
priv.putDocumentTree(command, doc, option,
doc_tree, callback.putDocumentTree);
};
callback.putDocumentTree = function (err) {
var response_object;
if (err) {
err.message = "Cannot update the document history";
return onEnd(err, undefined);
}
response_object = {
"id": doc._id,
"rev": doc._rev
};
if (specific_parameter.putAttachment ||
specific_parameter.removeAttachment ||
specific_parameter.getAttachment) {
response_object.attachment = doc._attachment;
}
onEnd(undefined, response_object);
// if (option.keep_revision_history !== true) {
// // priv.remove(command, prev_doc, option, function () {
// // - change "available" status to "deleted"
// // - remove attachments
// // - done, no callback
// // });
// }
};
callback.begin();
};
/**
* Post the document metadata and create or update a document tree.
* Options:
* - {boolean} keep_revision_history To keep the previous revisions
* (false by default) (NYI).
* @method post
* @param {object} command The JIO command
*/
that.post = function (command, metadata, option) {
priv.revisionGenericRequest(
command,
metadata,
option,
{},
function (err, response) {
if (err) {
return command.error(err);
}
command.success({"id": response.id, "rev": response.rev});
}
);
};
/**
* Put the document metadata and create or update a document tree.
* Options:
* - {boolean} keep_revision_history To keep the previous revisions
* (false by default) (NYI).
* @method put
* @param {object} command The JIO command
*/
that.put = function (command, metadata, option) {
priv.revisionGenericRequest(
command,
metadata,
option,
{},
function (err, response) {
if (err) {
return command.error(err);
}
command.success({"rev": response.rev});
}
);
};
that.putAttachment = function (command, param, option) {
tool.readBlobAsBinaryString(param._blob).then(function (event) {
param._content_type = param._blob.type;
param._data = event.target.result;
delete param._blob;
priv.revisionGenericRequest(
command,
param,
option,
{
"doc_id": param._id,
"attachment_id": param._attachment,
"add_to_attachment_list": {
"_attachment": param._attachment,
"_content_type": param._content_type,
"_data": param._data
},
"putAttachment": true
},
function (err, response) {
if (err) {
return command.error(err);
}
command.success({"rev": response.rev});
}
);
}, function () {
command.error("conflict", "broken blob", "Cannot read data to put");
});
};
that.remove = function (command, param, option) {
priv.revisionGenericRequest(
command,
param,
option,
{
"revision_needed": true,
"remove": true
},
function (err, response) {
if (err) {
return command.error(err);
}
command.success({"rev": response.rev});
}
);
};
that.removeAttachment = function (command, param, option) {
priv.revisionGenericRequest(
command,
param,
option,
{
"doc_id": param._id,
"attachment_id": param._attachment,
"revision_needed": true,
"removeAttachment": true,
"remove_from_attachment_list": {
"_attachment": param._attachment
}
},
function (err, response) {
if (err) {
return command.error(err);
}
command.success({"rev": response.rev});
}
);
};
that.get = function (command, param, option) {
priv.revisionGenericRequest(
command,
param,
option,
{
"get": true
},
function (err, response) {
if (err) {
return command.error(err);
}
command.success({"data": response.data});
}
);
};
that.getAttachment = function (command, param, option) {
priv.revisionGenericRequest(
command,
param,
option,
{
"doc_id": param._id,
"attachment_id": param._attachment,
"getAttachment": true
},
function (err, response) {
if (err) {
return command.error(err);
}
command.success({"data": response.data});
}
);
};
that.allDocs = function (command, param, option) {
/*jslint unparam: true */
var rows, result = {"total_rows": 0, "rows": []}, functions = {};
functions.finished = 0;
functions.falseResponseGenerator = function (response, callback) {
callback(undefined, response);
};
functions.fillResultGenerator = function (doc_id) {
return function (err, doc_tree) {
var document_revision, row, revs_info;
if (err) {
return command.error(err);
}
doc_tree = doc_tree.data;
if (typeof doc_tree.children === 'string') {
doc_tree.children = JSON.parse(doc_tree.children);
}
revs_info = priv.getWinnerRevsInfo(doc_tree);
document_revision =
rows.document_revisions[doc_id + "." + revs_info[0].rev];
if (document_revision) {
row = {
"id": doc_id,
"key": doc_id,
"value": {
"rev": revs_info[0].rev
}
};
if (document_revision.doc && option.include_docs) {
document_revision.doc._id = doc_id;
document_revision.doc._rev = revs_info[0].rev;
row.doc = document_revision.doc;
}
result.rows.push(row);
result.total_rows += 1;
}
functions.success();
};
};
functions.success = function () {
functions.finished -= 1;
if (functions.finished === 0) {
command.success({"data": result});
}
};
priv.send(command, "allDocs", null, option, function (err, response) {
var i, row, selector, selected;
if (err) {
return command.error(err);
}
response = response.data;
selector = /\.revision_tree\.json$/;
rows = {
"revision_trees": {
// id.revision_tree.json: {
// id: blabla
// doc: {...}
// }
},
"document_revisions": {
// id.rev: {
// id: blabla
// rev: 1-1
// doc: {...}
// }
}
};
while (response.rows.length > 0) {
// filling rows
row = response.rows.shift();
selected = selector.exec(row.id);
if (selected) {
selected = selected.input.substring(0, selected.index);
// this is a revision tree
rows.revision_trees[row.id] = {
"id": selected
};
if (row.doc) {
rows.revision_trees[row.id].doc = row.doc;
}
} else {
// this is a simple revision
rows.document_revisions[row.id] = {
"id": row.id.split(".").slice(0, -1),
"rev": row.id.split(".").slice(-1)
};
if (row.doc) {
rows.document_revisions[row.id].doc = row.doc;
}
}
}
functions.finished += 1;
for (i in rows.revision_trees) {
if (rows.revision_trees.hasOwnProperty(i)) {
functions.finished += 1;
if (rows.revision_trees[i].doc) {
functions.falseResponseGenerator(
{"data": rows.revision_trees[i].doc},
functions.fillResultGenerator(rows.revision_trees[i].id)
);
} else {
priv.getRevisionTree(
command,
{"_id": rows.revision_trees[i].id},
option,
functions.fillResultGenerator(rows.revision_trees[i].id)
);
}
}
}
functions.success();
});
};
// XXX
that.check = function (command) {
command.success();
};
// XXX
that.repair = function (command) {
command.success();
};
}); // end RevisionStorage
}));
This source diff could not be displayed because it is too large. You can view the blob instead.
/** @preserve jsPDF 0.9.0rc2 ( ${buildDate} ${commitID} )
Copyright (c) 2010-2012 James Hall, james@snapshotmedia.co.uk, https://github.com/MrRio/jsPDF
Copyright (c) 2012 Willow Systems Corporation, willow-systems.com
MIT license.
*/
/*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
* ====================================================================
*/
/**
Creates new jsPDF document object instance
@class
@param orientation One of "portrait" or "landscape" (or shortcuts "p" (Default), "l")
@param unit Measurement unit to be used when coordinates are specified. One of "pt" (points), "mm" (Default), "cm", "in"
@param format One of 'a0', 'a1', 'a2', 'a3', 'a4' (Default) etc to 'a10', 'b0' to 'b10', 'c0' to 'c10', 'letter', 'government-letter', 'legal', 'junior-legal', 'ledger' or 'tabloid'
@returns {jsPDF}
@name jsPDF
*/
var jsPDF = (function () {
'use strict';
/*jslint browser:true, plusplus: true, bitwise: true, nomen: true */
/*global document: false, btoa, atob, zpipe, Uint8Array, ArrayBuffer, Blob, saveAs, adler32cs, Deflater */
// this will run on <=IE9, possibly some niche browsers
// new webkit-based, FireFox, IE10 already have native version of this.
if (typeof btoa === 'undefined') {
window.btoa = function (data) {
// DO NOT ADD UTF8 ENCODING CODE HERE!!!!
// UTF8 encoding encodes bytes over char code 128
// and, essentially, turns an 8-bit binary streams
// (that base64 can deal with) into 7-bit binary streams.
// (by default server does not know that and does not recode the data back to 8bit)
// You destroy your data.
// binary streams like jpeg image data etc, while stored in JavaScript strings,
// (which are 16bit arrays) are in 8bit format already.
// You do NOT need to char-encode that before base64 encoding.
// if you, by act of fate
// have string which has individual characters with code
// above 255 (pure unicode chars), encode that BEFORE you base64 here.
// you can use absolutely any approch there, as long as in the end,
// base64 gets an 8bit (char codes 0 - 255) stream.
// when you get it on the server after un-base64, you must
// UNencode it too, to get back to 16, 32bit or whatever original bin stream.
// Note, Yes, JavaScript strings are, in most cases UCS-2 -
// 16-bit character arrays. This does not mean, however,
// that you always have to UTF8 it before base64.
// it means that if you have actual characters anywhere in
// that string that have char code above 255, you need to
// recode *entire* string from 16-bit (or 32bit) to 8-bit array.
// You can do binary split to UTF16 (BE or LE)
// you can do utf8, you can split the thing by hand and prepend BOM to it,
// but whatever you do, make sure you mirror the opposite on
// the server. If server does not expect to post-process un-base64
// 8-bit binary stream, think very very hard about messing around with encoding.
// so, long story short:
// DO NOT ADD UTF8 ENCODING CODE HERE!!!!
/* @preserve
====================================================================
base64 encoder
MIT, GPL
version: 1109.2015
discuss at: http://phpjs.org/functions/base64_encode
+ original by: Tyler Akins (http://rumkin.com)
+ improved by: Bayron Guevara
+ improved by: Thunder.m
+ improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
+ bugfixed by: Pellentesque Malesuada
+ improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
+ improved by: Rafal Kukawski (http://kukawski.pl)
+ Daniel Dotsenko, Willow Systems Corp, willow-systems.com
====================================================================
*/
var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
b64a = b64.split(''),
o1,
o2,
o3,
h1,
h2,
h3,
h4,
bits,
i = 0,
ac = 0,
enc = "",
tmp_arr = [],
r;
do { // pack three octets into four hexets
o1 = data.charCodeAt(i++);
o2 = data.charCodeAt(i++);
o3 = data.charCodeAt(i++);
bits = o1 << 16 | o2 << 8 | o3;
h1 = bits >> 18 & 0x3f;
h2 = bits >> 12 & 0x3f;
h3 = bits >> 6 & 0x3f;
h4 = bits & 0x3f;
// use hexets to index into b64, and append result to encoded string
tmp_arr[ac++] = b64a[h1] + b64a[h2] + b64a[h3] + b64a[h4];
} while (i < data.length);
enc = tmp_arr.join('');
r = data.length % 3;
return (r ? enc.slice(0, r - 3) : enc) + '==='.slice(r || 3);
// end of base64 encoder MIT, GPL
};
}
if (typeof atob === 'undefined') {
window.atob = function (data) {
// http://kevin.vanzonneveld.net
// + original by: Tyler Akins (http://rumkin.com)
// + improved by: Thunder.m
// + input by: Aman Gupta
// + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + bugfixed by: Onno Marsman
// + bugfixed by: Pellentesque Malesuada
// + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + input by: Brett Zamir (http://brett-zamir.me)
// + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// * example 1: base64_decode('S2V2aW4gdmFuIFpvbm5ldmVsZA==');
// * returns 1: 'Kevin van Zonneveld'
// mozilla has this native
// - but breaks in 2.0.0.12!
//if (typeof this.window['atob'] == 'function') {
// return atob(data);
//}
var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
o1,
o2,
o3,
h1,
h2,
h3,
h4,
bits,
i = 0,
ac = 0,
dec = "",
tmp_arr = [];
if (!data) {
return data;
}
data += '';
do { // unpack four hexets into three octets using index points in b64
h1 = b64.indexOf(data.charAt(i++));
h2 = b64.indexOf(data.charAt(i++));
h3 = b64.indexOf(data.charAt(i++));
h4 = b64.indexOf(data.charAt(i++));
bits = h1 << 18 | h2 << 12 | h3 << 6 | h4;
o1 = bits >> 16 & 0xff;
o2 = bits >> 8 & 0xff;
o3 = bits & 0xff;
if (h3 === 64) {
tmp_arr[ac++] = String.fromCharCode(o1);
} else if (h4 === 64) {
tmp_arr[ac++] = String.fromCharCode(o1, o2);
} else {
tmp_arr[ac++] = String.fromCharCode(o1, o2, o3);
}
} while (i < data.length);
dec = tmp_arr.join('');
return dec;
};
}
var getObjectLength = typeof Object.keys === 'function' ?
function (object) {
return Object.keys(object).length;
} :
function (object) {
var i = 0, e;
for (e in object) {
if (object.hasOwnProperty(e)) {
i++;
}
}
return i;
},
/**
PubSub implementation
@class
@name PubSub
*/
PubSub = function (context) {
/** @preserve
-----------------------------------------------------------------------------------------------
JavaScript PubSub library
2012 (c) ddotsenko@willowsystems.com
based on Peter Higgins (dante@dojotoolkit.org)
Loosely based on Dojo publish/subscribe API, limited in scope. Rewritten blindly.
Original is (c) Dojo Foundation 2004-2010. Released under either AFL or new BSD, see:
http://dojofoundation.org/license for more information.
-----------------------------------------------------------------------------------------------
*/
/**
@private
@fieldOf PubSub
*/
this.topics = {};
/**
Stores what will be `this` within the callback functions.
@private
@fieldOf PubSub#
*/
this.context = context;
/**
Allows caller to emit an event and pass arguments to event listeners.
@public
@function
@param topic {String} Name of the channel on which to voice this event
@param args Any number of arguments you want to pass to the listeners of this event.
@methodOf PubSub#
@name publish
*/
this.publish = function (topic, args) {
if (this.topics[topic]) {
var currentTopic = this.topics[topic],
toremove = [],
fn,
i,
l,
pair,
emptyFunc = function () {};
args = Array.prototype.slice.call(arguments, 1);
for (i = 0, l = currentTopic.length; i < l; i++) {
pair = currentTopic[i]; // this is a [function, once_flag] array
fn = pair[0];
if (pair[1]) { /* 'run once' flag set */
pair[0] = emptyFunc;
toremove.push(i);
}
fn.apply(this.context, args);
}
for (i = 0, l = toremove.length; i < l; i++) {
currentTopic.splice(toremove[i], 1);
}
}
};
/**
Allows listener code to subscribe to channel and be called when data is available
@public
@function
@param topic {String} Name of the channel on which to voice this event
@param callback {Function} Executable (function pointer) that will be ran when event is voiced on this channel.
@param once {Boolean} (optional. False by default) Flag indicating if the function is to be triggered only once.
@returns {Object} A token object that cen be used for unsubscribing.
@methodOf PubSub#
@name subscribe
*/
this.subscribe = function (topic, callback, once) {
if (!this.topics[topic]) {
this.topics[topic] = [[callback, once]];
} else {
this.topics[topic].push([callback, once]);
}
return {
"topic": topic,
"callback": callback
};
};
/**
Allows listener code to unsubscribe from a channel
@public
@function
@param token {Object} A token object that was returned by `subscribe` method
@methodOf PubSub#
@name unsubscribe
*/
this.unsubscribe = function (token) {
if (this.topics[token.topic]) {
var currentTopic = this.topics[token.topic], i, l;
for (i = 0, l = currentTopic.length; i < l; i++) {
if (currentTopic[i][0] === token.callback) {
currentTopic.splice(i, 1);
}
}
}
};
};
/**
@constructor
@private
*/
function jsPDF(orientation, unit, format, compressPdf) { /** String orientation, String unit, String format, Boolean compressed */
// Default parameter values
if (typeof orientation === 'undefined') {
orientation = 'p';
} else {
orientation = orientation.toString().toLowerCase();
}
if (typeof unit === 'undefined') { unit = 'mm'; }
if (typeof format === 'undefined') { format = 'a4'; }
if (typeof compressPdf === 'undefined' && typeof zpipe === 'undefined') { compressPdf = false; }
var format_as_string = format.toString().toLowerCase(),
version = '0.9.0rc2',
content = [],
content_length = 0,
compress = compressPdf,
pdfVersion = '1.3', // PDF Version
pageFormats = { // Size in pt of various paper formats
'a0': [2383.94, 3370.39],
'a1': [1683.78, 2383.94],
'a2': [1190.55, 1683.78],
'a3': [841.89, 1190.55],
'a4': [595.28, 841.89],
'a5': [419.53, 595.28],
'a6': [297.64, 419.53],
'a7': [209.76, 297.64],
'a8': [147.4 , 209.76],
'a9': [104.88, 147.4],
'a10': [73.7, 104.88],
'b0': [2834.65, 4008.19],
'b1': [2004.09, 2834.65],
'b2': [1417.32, 2004.09],
'b3': [1000.63, 1417.32],
'b4': [708.66, 1000.63],
'b5': [498.9, 708.66],
'b6': [354.33, 498.9],
'b7': [249.45, 354.33],
'b8': [175.75, 249.45],
'b9': [124.72, 175.75],
'b10': [87.87, 124.72],
'c0': [2599.37, 3676.54],
'c1': [1836.85, 2599.37],
'c2': [1298.27, 1836.85],
'c3': [918.43, 1298.27],
'c4': [649.13, 918.43],
'c5': [459.21, 649.13],
'c6': [323.15, 459.21],
'c7': [229.61, 323.15],
'c8': [161.57, 229.61],
'c9': [113.39, 161.57],
'c10': [79.37, 113.39],
'letter': [612, 792],
'government-letter': [576, 756],
'legal': [612, 1008],
'junior-legal': [576, 360],
'ledger': [1224, 792],
'tabloid': [792, 1224]
},
textColor = '0 g',
drawColor = '0 G',
page = 0,
pages = [],
objectNumber = 2, // 'n' Current object number
outToPages = false, // switches where out() prints. outToPages true = push to pages obj. outToPages false = doc builder content
offsets = [], // List of offsets. Activated and reset by buildDocument(). Pupulated by various calls buildDocument makes.
fonts = {}, // collection of font objects, where key is fontKey - a dynamically created label for a given font.
fontmap = {}, // mapping structure fontName > fontStyle > font key - performance layer. See addFont()
activeFontSize = 16,
activeFontKey, // will be string representing the KEY of the font as combination of fontName + fontStyle
lineWidth = 0.200025, // 2mm
lineHeightProportion = 1.15,
pageHeight,
pageWidth,
k, // Scale factor
documentProperties = {'title': '', 'subject': '', 'author': '', 'keywords': '', 'creator': ''},
lineCapID = 0,
lineJoinID = 0,
API = {},
events = new PubSub(API),
tmp,
plugin,
/////////////////////
// Private functions
/////////////////////
// simplified (speedier) replacement for sprintf's %.2f conversion
f2 = function (number) {
return number.toFixed(2);
},
// simplified (speedier) replacement for sprintf's %.3f conversion
f3 = function (number) {
return number.toFixed(3);
},
// simplified (speedier) replacement for sprintf's %02d
padd2 = function (number) {
var n = (number).toFixed(0);
if (number < 10) {
return '0' + n;
} else {
return n;
}
},
// simplified (speedier) replacement for sprintf's %02d
padd10 = function (number) {
var n = (number).toFixed(0);
if (n.length < 10) {
return new Array( 11 - n.length ).join('0') + n;
} else {
return n;
}
},
out = function (string) {
if (outToPages) { /* set by beginPage */
pages[page].push(string);
} else {
content.push(string);
content_length += string.length + 1; // +1 is for '\n' that will be used to join contents of content
}
},
newObject = function () {
// Begin a new object
objectNumber++;
offsets[objectNumber] = content_length;
out(objectNumber + ' 0 obj');
return objectNumber;
},
putStream = function (str) {
out('stream');
out(str);
out('endstream');
},
wPt,
hPt,
kids,
i,
putPages = function () {
wPt = pageWidth * k;
hPt = pageHeight * k;
// outToPages = false as set in endDocument(). out() writes to content.
var n, p, arr, uint, i, deflater, adler32;
for (n = 1; n <= page; n++) {
newObject();
out('<</Type /Page');
out('/Parent 1 0 R');
out('/Resources 2 0 R');
out('/Contents ' + (objectNumber + 1) + ' 0 R>>');
out('endobj');
// Page content
p = pages[n].join('\n');
newObject();
if (compress) {
arr = [];
for (i = 0; i < p.length; ++i) {
arr[i] = p.charCodeAt(i);
}
adler32 = adler32cs.from(p);
deflater = new Deflater(6);
deflater.append(new Uint8Array(arr));
p = deflater.flush();
arr = [new Uint8Array([120, 156]), new Uint8Array(p),
new Uint8Array([adler32 & 0xFF, (adler32 >> 8) & 0xFF, (adler32 >> 16) & 0xFF, (adler32 >> 24) & 0xFF])];
p = '';
for (i in arr) {
if (arr.hasOwnProperty(i)) {
p += String.fromCharCode.apply(null, arr[i]);
}
}
out('<</Length ' + p.length + ' /Filter [/FlateDecode]>>');
} else {
out('<</Length ' + p.length + '>>');
}
putStream(p);
out('endobj');
}
offsets[1] = content_length;
out('1 0 obj');
out('<</Type /Pages');
kids = '/Kids [';
for (i = 0; i < page; i++) {
kids += (3 + 2 * i) + ' 0 R ';
}
out(kids + ']');
out('/Count ' + page);
out('/MediaBox [0 0 ' + f2(wPt) + ' ' + f2(hPt) + ']');
out('>>');
out('endobj');
},
putFont = function (font) {
font.objectNumber = newObject();
out('<</BaseFont/' + font.PostScriptName + '/Type/Font');
if (typeof font.encoding === 'string') {
out('/Encoding/' + font.encoding);
}
out('/Subtype/Type1>>');
out('endobj');
},
putFonts = function () {
var fontKey;
for (fontKey in fonts) {
if (fonts.hasOwnProperty(fontKey)) {
putFont(fonts[fontKey]);
}
}
},
putXobjectDict = function () {
// Loop through images, or other data objects
events.publish('putXobjectDict');
},
putResourceDictionary = function () {
out('/ProcSet [/PDF /Text /ImageB /ImageC /ImageI]');
out('/Font <<');
// Do this for each font, the '1' bit is the index of the font
var fontKey;
for (fontKey in fonts) {
if (fonts.hasOwnProperty(fontKey)) {
out('/' + fontKey + ' ' + fonts[fontKey].objectNumber + ' 0 R');
}
}
out('>>');
out('/XObject <<');
putXobjectDict();
out('>>');
},
putResources = function () {
putFonts();
events.publish('putResources');
// Resource dictionary
offsets[2] = content_length;
out('2 0 obj');
out('<<');
putResourceDictionary();
out('>>');
out('endobj');
events.publish('postPutResources');
},
addToFontDictionary = function (fontKey, fontName, fontStyle) {
// this is mapping structure for quick font key lookup.
// returns the KEY of the font (ex: "F1") for a given pair of font name and type (ex: "Arial". "Italic")
var undef;
if (fontmap[fontName] === undef) {
fontmap[fontName] = {}; // fontStyle is a var interpreted and converted to appropriate string. don't wrap in quotes.
}
fontmap[fontName][fontStyle] = fontKey;
},
/**
FontObject describes a particular font as member of an instnace of jsPDF
It's a collection of properties like 'id' (to be used in PDF stream),
'fontName' (font's family name), 'fontStyle' (font's style variant label)
@class
@public
@property id {String} PDF-document-instance-specific label assinged to the font.
@property PostScriptName {String} PDF specification full name for the font
@property encoding {Object} Encoding_name-to-Font_metrics_object mapping.
@name FontObject
*/
FontObject = {},
addFont = function (PostScriptName, fontName, fontStyle, encoding) {
var fontKey = 'F' + (getObjectLength(fonts) + 1).toString(10),
// This is FontObject
font = fonts[fontKey] = {
'id': fontKey,
// , 'objectNumber': will be set by putFont()
'PostScriptName': PostScriptName,
'fontName': fontName,
'fontStyle': fontStyle,
'encoding': encoding,
'metadata': {}
};
addToFontDictionary(fontKey, fontName, fontStyle);
events.publish('addFont', font);
return fontKey;
},
addFonts = function () {
var HELVETICA = "helvetica",
TIMES = "times",
COURIER = "courier",
NORMAL = "normal",
BOLD = "bold",
ITALIC = "italic",
BOLD_ITALIC = "bolditalic",
encoding = 'StandardEncoding',
standardFonts = [
['Helvetica', HELVETICA, NORMAL],
['Helvetica-Bold', HELVETICA, BOLD],
['Helvetica-Oblique', HELVETICA, ITALIC],
['Helvetica-BoldOblique', HELVETICA, BOLD_ITALIC],
['Courier', COURIER, NORMAL],
['Courier-Bold', COURIER, BOLD],
['Courier-Oblique', COURIER, ITALIC],
['Courier-BoldOblique', COURIER, BOLD_ITALIC],
['Times-Roman', TIMES, NORMAL],
['Times-Bold', TIMES, BOLD],
['Times-Italic', TIMES, ITALIC],
['Times-BoldItalic', TIMES, BOLD_ITALIC]
],
i,
l,
fontKey,
parts;
for (i = 0, l = standardFonts.length; i < l; i++) {
fontKey = addFont(
standardFonts[i][0],
standardFonts[i][1],
standardFonts[i][2],
encoding
);
// adding aliases for standard fonts, this time matching the capitalization
parts = standardFonts[i][0].split('-');
addToFontDictionary(fontKey, parts[0], parts[1] || '');
}
events.publish('addFonts', {'fonts': fonts, 'dictionary': fontmap});
},
/**
@public
@function
@param text {String}
@param flags {Object} Encoding flags.
@returns {String} Encoded string
*/
to8bitStream = function (text, flags) {
/* PDF 1.3 spec:
"For text strings encoded in Unicode, the first two bytes must be 254 followed by
255, representing the Unicode byte order marker, U+FEFF. (This sequence conflicts
with the PDFDocEncoding character sequence thorn ydieresis, which is unlikely
to be a meaningful beginning of a word or phrase.) The remainder of the
string consists of Unicode character codes, according to the UTF-16 encoding
specified in the Unicode standard, version 2.0. Commonly used Unicode values
are represented as 2 bytes per character, with the high-order byte appearing first
in the string."
In other words, if there are chars in a string with char code above 255, we
recode the string to UCS2 BE - string doubles in length and BOM is prepended.
HOWEVER!
Actual *content* (body) text (as opposed to strings used in document properties etc)
does NOT expect BOM. There, it is treated as a literal GID (Glyph ID)
Because of Adobe's focus on "you subset your fonts!" you are not supposed to have
a font that maps directly Unicode (UCS2 / UTF16BE) code to font GID, but you could
fudge it with "Identity-H" encoding and custom CIDtoGID map that mimics Unicode
code page. There, however, all characters in the stream are treated as GIDs,
including BOM, which is the reason we need to skip BOM in content text (i.e. that
that is tied to a font).
To signal this "special" PDFEscape / to8bitStream handling mode,
API.text() function sets (unless you overwrite it with manual values
given to API.text(.., flags) )
flags.autoencode = true
flags.noBOM = true
*/
/*
`flags` properties relied upon:
.sourceEncoding = string with encoding label.
"Unicode" by default. = encoding of the incoming text.
pass some non-existing encoding name
(ex: 'Do not touch my strings! I know what I am doing.')
to make encoding code skip the encoding step.
.outputEncoding = Either valid PDF encoding name
(must be supported by jsPDF font metrics, otherwise no encoding)
or a JS object, where key = sourceCharCode, value = outputCharCode
missing keys will be treated as: sourceCharCode === outputCharCode
.noBOM
See comment higher above for explanation for why this is important
.autoencode
See comment higher above for explanation for why this is important
*/
var i, l, undef, sourceEncoding, encodingBlock, outputEncoding, newtext, isUnicode, ch, bch;
if (flags === undef) {
flags = {};
}
sourceEncoding = flags.sourceEncoding ? sourceEncoding : 'Unicode';
outputEncoding = flags.outputEncoding;
// This 'encoding' section relies on font metrics format
// attached to font objects by, among others,
// "Willow Systems' standard_font_metrics plugin"
// see jspdf.plugin.standard_font_metrics.js for format
// of the font.metadata.encoding Object.
// It should be something like
// .encoding = {'codePages':['WinANSI....'], 'WinANSI...':{code:code, ...}}
// .widths = {0:width, code:width, ..., 'fof':divisor}
// .kerning = {code:{previous_char_code:shift, ..., 'fof':-divisor},...}
if ((flags.autoencode || outputEncoding) &&
fonts[activeFontKey].metadata &&
fonts[activeFontKey].metadata[sourceEncoding] &&
fonts[activeFontKey].metadata[sourceEncoding].encoding
) {
encodingBlock = fonts[activeFontKey].metadata[sourceEncoding].encoding;
// each font has default encoding. Some have it clearly defined.
if (!outputEncoding && fonts[activeFontKey].encoding) {
outputEncoding = fonts[activeFontKey].encoding;
}
// Hmmm, the above did not work? Let's try again, in different place.
if (!outputEncoding && encodingBlock.codePages) {
outputEncoding = encodingBlock.codePages[0]; // let's say, first one is the default
}
if (typeof outputEncoding === 'string') {
outputEncoding = encodingBlock[outputEncoding];
}
// we want output encoding to be a JS Object, where
// key = sourceEncoding's character code and
// value = outputEncoding's character code.
if (outputEncoding) {
isUnicode = false;
newtext = [];
for (i = 0, l = text.length; i < l; i++) {
ch = outputEncoding[text.charCodeAt(i)];
if (ch) {
newtext.push(
String.fromCharCode(ch)
);
} else {
newtext.push(
text[i]
);
}
// since we are looping over chars anyway, might as well
// check for residual unicodeness
if (newtext[i].charCodeAt(0) >> 8) { /* more than 255 */
isUnicode = true;
}
}
text = newtext.join('');
}
}
i = text.length;
// isUnicode may be set to false above. Hence the triple-equal to undefined
while (isUnicode === undef && i !== 0) {
if (text.charCodeAt(i - 1) >> 8) { /* more than 255 */
isUnicode = true;
}
i--;
}
if (!isUnicode) {
return text;
} else {
newtext = flags.noBOM ? [] : [254, 255];
for (i = 0, l = text.length; i < l; i++) {
ch = text.charCodeAt(i);
bch = ch >> 8; // divide by 256
if (bch >> 8) { /* something left after dividing by 256 second time */
throw new Error("Character at position " + i.toString(10) + " of string '" + text + "' exceeds 16bits. Cannot be encoded into UCS-2 BE");
}
newtext.push(bch);
newtext.push(ch - (bch << 8));
}
return String.fromCharCode.apply(undef, newtext);
}
},
// Replace '/', '(', and ')' with pdf-safe versions
pdfEscape = function (text, flags) {
// doing to8bitStream does NOT make this PDF display unicode text. For that
// we also need to reference a unicode font and embed it - royal pain in the rear.
// There is still a benefit to to8bitStream - PDF simply cannot handle 16bit chars,
// which JavaScript Strings are happy to provide. So, while we still cannot display
// 2-byte characters property, at least CONDITIONALLY converting (entire string containing)
// 16bit chars to (USC-2-BE) 2-bytes per char + BOM streams we ensure that entire PDF
// is still parseable.
// This will allow immediate support for unicode in document properties strings.
return to8bitStream(text, flags).replace(/\\/g, '\\\\').replace(/\(/g, '\\(').replace(/\)/g, '\\)');
},
putInfo = function () {
out('/Producer (jsPDF ' + version + ')');
if (documentProperties.title) {
out('/Title (' + pdfEscape(documentProperties.title) + ')');
}
if (documentProperties.subject) {
out('/Subject (' + pdfEscape(documentProperties.subject) + ')');
}
if (documentProperties.author) {
out('/Author (' + pdfEscape(documentProperties.author) + ')');
}
if (documentProperties.keywords) {
out('/Keywords (' + pdfEscape(documentProperties.keywords) + ')');
}
if (documentProperties.creator) {
out('/Creator (' + pdfEscape(documentProperties.creator) + ')');
}
var created = new Date();
out('/CreationDate (D:' +
[
created.getFullYear(),
padd2(created.getMonth() + 1),
padd2(created.getDate()),
padd2(created.getHours()),
padd2(created.getMinutes()),
padd2(created.getSeconds())
].join('') +
')'
);
},
putCatalog = function () {
out('/Type /Catalog');
out('/Pages 1 0 R');
// @TODO: Add zoom and layout modes
out('/OpenAction [3 0 R /FitH null]');
out('/PageLayout /OneColumn');
events.publish('putCatalog');
},
putTrailer = function () {
out('/Size ' + (objectNumber + 1));
out('/Root ' + objectNumber + ' 0 R');
out('/Info ' + (objectNumber - 1) + ' 0 R');
},
beginPage = function () {
page++;
// Do dimension stuff
outToPages = true;
pages[page] = [];
},
_addPage = function () {
beginPage();
// Set line width
out(f2(lineWidth * k) + ' w');
// Set draw color
out(drawColor);
// resurrecting non-default line caps, joins
if (lineCapID !== 0) {
out(lineCapID.toString(10) + ' J');
}
if (lineJoinID !== 0) {
out(lineJoinID.toString(10) + ' j');
}
events.publish('addPage', {'pageNumber': page});
},
/**
Returns a document-specific font key - a label assigned to a
font name + font type combination at the time the font was added
to the font inventory.
Font key is used as label for the desired font for a block of text
to be added to the PDF document stream.
@private
@function
@param fontName {String} can be undefined on "falthy" to indicate "use current"
@param fontStyle {String} can be undefined on "falthy" to indicate "use current"
@returns {String} Font key.
*/
getFont = function (fontName, fontStyle) {
var key, undef;
if (fontName === undef) {
fontName = fonts[activeFontKey].fontName;
}
if (fontStyle === undef) {
fontStyle = fonts[activeFontKey].fontStyle;
}
try {
key = fontmap[fontName][fontStyle]; // returns a string like 'F3' - the KEY corresponding tot he font + type combination.
} catch (e) {
key = undef;
}
if (!key) {
throw new Error("Unable to look up font label for font '" + fontName + "', '" + fontStyle + "'. Refer to getFontList() for available fonts.");
}
return key;
},
buildDocument = function () {
outToPages = false; // switches out() to content
content = [];
offsets = [];
// putHeader()
out('%PDF-' + pdfVersion);
putPages();
putResources();
// Info
newObject();
out('<<');
putInfo();
out('>>');
out('endobj');
// Catalog
newObject();
out('<<');
putCatalog();
out('>>');
out('endobj');
// Cross-ref
var o = content_length, i;
out('xref');
out('0 ' + (objectNumber + 1));
out('0000000000 65535 f ');
for (i = 1; i <= objectNumber; i++) {
out(padd10(offsets[i]) + ' 00000 n ');
}
// Trailer
out('trailer');
out('<<');
putTrailer();
out('>>');
out('startxref');
out(o);
out('%%EOF');
outToPages = true;
return content.join('\n');
},
getStyle = function (style) {
// see Path-Painting Operators of PDF spec
var op = 'S'; // stroke
if (style === 'F') {
op = 'f'; // fill
} else if (style === 'FD' || style === 'DF') {
op = 'B'; // both
}
return op;
},
/**
Generates the PDF document.
Possible values:
datauristring (alias dataurlstring) - Data-Url-formatted data returned as string.
datauri (alias datauri) - Data-Url-formatted data pushed into current window's location (effectively reloading the window with contents of the PDF).
If `type` argument is undefined, output is raw body of resulting PDF returned as a string.
@param {String} type A string identifying one of the possible output types.
@param {Object} options An object providing some additional signalling to PDF generator.
@function
@returns {jsPDF}
@methodOf jsPDF#
@name output
*/
output = function (type, options) {
var undef, data, length, array, i, blob;
switch (type) {
case undef:
return buildDocument();
case 'save':
if (navigator.getUserMedia) {
if (window.URL === undefined) {
return API.output('dataurlnewwindow');
} else if (window.URL.createObjectURL === undefined) {
return API.output('dataurlnewwindow');
}
}
data = buildDocument();
// Need to add the file to BlobBuilder as a Uint8Array
length = data.length;
array = new Uint8Array(new ArrayBuffer(length));
for (i = 0; i < length; i++) {
array[i] = data.charCodeAt(i);
}
// here sven !!!
//blob = new Blob([array], {type: "application/pdf"});
blob = new Blob([array.buffer], {type: "application/pdf"});
saveAs(blob, options);
break;
case 'datauristring':
case 'dataurlstring':
return 'data:application/pdf;base64,' + btoa(buildDocument());
case 'datauri':
case 'dataurl':
document.location.href = 'data:application/pdf;base64,' + btoa(buildDocument());
break;
case 'dataurlnewwindow':
window.open('data:application/pdf;base64,' + btoa(buildDocument()));
break;
default:
throw new Error('Output type "' + type + '" is not supported.');
}
// @TODO: Add different output options
};
if (unit === 'pt') {
k = 1;
} else if (unit === 'mm') {
k = 72 / 25.4;
} else if (unit === 'cm') {
k = 72 / 2.54;
} else if (unit === 'in') {
k = 72;
} else {
throw ('Invalid unit: ' + unit);
}
// Dimensions are stored as user units and converted to points on output
if (pageFormats.hasOwnProperty(format_as_string)) {
pageHeight = pageFormats[format_as_string][1] / k;
pageWidth = pageFormats[format_as_string][0] / k;
} else {
try {
pageHeight = format[1];
pageWidth = format[0];
} catch (err) {
throw ('Invalid format: ' + format);
}
}
if (orientation === 'p' || orientation === 'portrait') {
orientation = 'p';
if (pageWidth > pageHeight) {
tmp = pageWidth;
pageWidth = pageHeight;
pageHeight = tmp;
}
} else if (orientation === 'l' || orientation === 'landscape') {
orientation = 'l';
if (pageHeight > pageWidth) {
tmp = pageWidth;
pageWidth = pageHeight;
pageHeight = tmp;
}
} else {
throw ('Invalid orientation: ' + orientation);
}
//---------------------------------------
// Public API
/*
Object exposing internal API to plugins
@public
*/
API.internal = {
'pdfEscape': pdfEscape,
'getStyle': getStyle,
/**
Returns {FontObject} describing a particular font.
@public
@function
@param fontName {String} (Optional) Font's family name
@param fontStyle {String} (Optional) Font's style variation name (Example:"Italic")
@returns {FontObject}
*/
'getFont': function () { return fonts[getFont.apply(API, arguments)]; },
'getFontSize': function () { return activeFontSize; },
'getLineHeight': function () { return activeFontSize * lineHeightProportion; },
'btoa': btoa,
'write': function (string1, string2, string3, etc) {
out(
arguments.length === 1 ? string1 : Array.prototype.join.call(arguments, ' ')
);
},
'getCoordinateString': function (value) {
return f2(value * k);
},
'getVerticalCoordinateString': function (value) {
return f2((pageHeight - value) * k);
},
'collections': {},
'newObject': newObject,
'putStream': putStream,
'events': events,
// ratio that you use in multiplication of a given "size" number to arrive to 'point'
// units of measurement.
// scaleFactor is set at initialization of the document and calculated against the stated
// default measurement units for the document.
// If default is "mm", k is the number that will turn number in 'mm' into 'points' number.
// through multiplication.
'scaleFactor': k,
'pageSize': {'width': pageWidth, 'height': pageHeight},
'output': function (type, options) {
return output(type, options);
},
'getNumberOfPages': function () {return pages.length - 1; },
'pages': pages
};
/**
Adds (and transfers the focus to) new page to the PDF document.
@function
@returns {jsPDF}
@methodOf jsPDF#
@name addPage
*/
API.addPage = function () {
_addPage();
return this;
};
/**
Adds text to page. Supports adding multiline text when 'text' argument is an Array of Strings.
@function
@param {String|Array} text String or array of strings to be added to the page. Each line is shifted one line down per font, spacing settings declared before this call.
@param {Number} x Coordinate (in units declared at inception of PDF document) against left edge of the page
@param {Number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page
@param {Object} flags Collection of settings signalling how the text must be encoded. Defaults are sane. If you think you want to pass some flags, you likely can read the source.
@returns {jsPDF}
@methodOf jsPDF#
@name text
*/
API.text = function (text, x, y, flags) {
/**
* Inserts something like this into PDF
BT
/F1 16 Tf % Font name + size
16 TL % How many units down for next line in multiline text
0 g % color
28.35 813.54 Td % position
(line one) Tj
T* (line two) Tj
T* (line three) Tj
ET
*/
var undef, _first, _second, _third, newtext, str, i;
// Pre-August-2012 the order of arguments was function(x, y, text, flags)
// in effort to make all calls have similar signature like
// function(data, coordinates... , miscellaneous)
// this method had its args flipped.
// code below allows backward compatibility with old arg order.
if (typeof text === 'number') {
_first = y;
_second = text;
_third = x;
text = _first;
x = _second;
y = _third;
}
// If there are any newlines in text, we assume
// the user wanted to print multiple lines, so break the
// text up into an array. If the text is already an array,
// we assume the user knows what they are doing.
if (typeof text === 'string' && text.match(/[\n\r]/)) {
text = text.split(/\r\n|\r|\n/g);
}
if (typeof flags === 'undefined') {
flags = {'noBOM': true, 'autoencode': true};
} else {
if (flags.noBOM === undef) {
flags.noBOM = true;
}
if (flags.autoencode === undef) {
flags.autoencode = true;
}
}
if (typeof text === 'string') {
str = pdfEscape(text, flags);
} else if (text instanceof Array) { /* Array */
// we don't want to destroy original text array, so cloning it
newtext = text.concat();
// we do array.join('text that must not be PDFescaped")
// thus, pdfEscape each component separately
for (i = newtext.length - 1; i !== -1; i--) {
newtext[i] = pdfEscape(newtext[i], flags);
}
str = newtext.join(") Tj\nT* (");
} else {
throw new Error('Type of text must be string or Array. "' + text + '" is not recognized.');
}
// Using "'" ("go next line and render text" mark) would save space but would complicate our rendering code, templates
// BT .. ET does NOT have default settings for Tf. You must state that explicitely every time for BT .. ET
// if you want text transformation matrix (+ multiline) to work reliably (which reads sizes of things from font declarations)
// Thus, there is NO useful, *reliable* concept of "default" font for a page.
// The fact that "default" (reuse font used before) font worked before in basic cases is an accident
// - readers dealing smartly with brokenness of jsPDF's markup.
out(
'BT\n/' +
activeFontKey + ' ' + activeFontSize + ' Tf\n' + // font face, style, size
(activeFontSize * lineHeightProportion) + ' TL\n' + // line spacing
textColor +
'\n' + f2(x * k) + ' ' + f2((pageHeight - y) * k) + ' Td\n(' +
str +
') Tj\nET'
);
return this;
};
API.line = function (x1, y1, x2, y2) {
out(
f2(x1 * k) + ' ' + f2((pageHeight - y1) * k) + ' m ' +
f2(x2 * k) + ' ' + f2((pageHeight - y2) * k) + ' l S'
);
return this;
};
/**
Adds series of curves (straight lines or cubic bezier curves) to canvas, starting at `x`, `y` coordinates.
All data points in `lines` are relative to last line origin.
`x`, `y` become x1,y1 for first line / curve in the set.
For lines you only need to specify [x2, y2] - (ending point) vector against x1, y1 starting point.
For bezier curves you need to specify [x2,y2,x3,y3,x4,y4] - vectors to control points 1, 2, ending point. All vectors are against the start of the curve - x1,y1.
@example .lines([[2,2],[-2,2],[1,1,2,2,3,3],[2,1]], 212,110, 10) // line, line, bezier curve, line
@param {Array} lines Array of *vector* shifts as pairs (lines) or sextets (cubic bezier curves).
@param {Number} x Coordinate (in units declared at inception of PDF document) against left edge of the page
@param {Number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page
@param {Number} scale (Defaults to [1.0,1.0]) x,y Scaling factor for all vectors. Elements can be any floating number Sub-one makes drawing smaller. Over-one grows the drawing. Negative flips the direction.
@param {String} style One of 'S' (the default), 'F', 'FD' or 'DF'. 'S' draws just the curve. 'F' fills the region defined by the curves. 'DF' or 'FD' draws the curves and fills the region.
@param {Boolean} closed If true, the path is closed with a straight line from the end of the last curve to the starting point.
@function
@returns {jsPDF}
@methodOf jsPDF#
@name lines
*/
API.lines = function (lines, x, y, scale, style, closed) {
var undef, _first, _second, _third, scalex, scaley, i, l, leg, x2, y2, x3, y3, x4, y4;
// Pre-August-2012 the order of arguments was function(x, y, lines, scale, style)
// in effort to make all calls have similar signature like
// function(content, coordinateX, coordinateY , miscellaneous)
// this method had its args flipped.
// code below allows backward compatibility with old arg order.
if (typeof lines === 'number') {
_first = y;
_second = lines;
_third = x;
lines = _first;
x = _second;
y = _third;
}
style = getStyle(style);
scale = scale === undef ? [1, 1] : scale;
// starting point
out(f3(x * k) + ' ' + f3((pageHeight - y) * k) + ' m ');
scalex = scale[0];
scaley = scale[1];
l = lines.length;
//, x2, y2 // bezier only. In page default measurement "units", *after* scaling
//, x3, y3 // bezier only. In page default measurement "units", *after* scaling
// ending point for all, lines and bezier. . In page default measurement "units", *after* scaling
x4 = x; // last / ending point = starting point for first item.
y4 = y; // last / ending point = starting point for first item.
for (i = 0; i < l; i++) {
leg = lines[i];
if (leg.length === 2) {
// simple line
x4 = leg[0] * scalex + x4; // here last x4 was prior ending point
y4 = leg[1] * scaley + y4; // here last y4 was prior ending point
out(f3(x4 * k) + ' ' + f3((pageHeight - y4) * k) + ' l');
} else {
// bezier curve
x2 = leg[0] * scalex + x4; // here last x4 is prior ending point
y2 = leg[1] * scaley + y4; // here last y4 is prior ending point
x3 = leg[2] * scalex + x4; // here last x4 is prior ending point
y3 = leg[3] * scaley + y4; // here last y4 is prior ending point
x4 = leg[4] * scalex + x4; // here last x4 was prior ending point
y4 = leg[5] * scaley + y4; // here last y4 was prior ending point
out(
f3(x2 * k) + ' ' +
f3((pageHeight - y2) * k) + ' ' +
f3(x3 * k) + ' ' +
f3((pageHeight - y3) * k) + ' ' +
f3(x4 * k) + ' ' +
f3((pageHeight - y4) * k) + ' c'
);
}
}
if (closed == true) {
out(' h');
}
// stroking / filling / both the path
out(style);
return this;
};
/**
Adds a rectangle to PDF
@param {Number} x Coordinate (in units declared at inception of PDF document) against left edge of the page
@param {Number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page
@param {Number} w Width (in units declared at inception of PDF document)
@param {Number} h Height (in units declared at inception of PDF document)
@param {String} style (Defaults to active fill/stroke style) A string signalling if stroke, fill or both are to be applied.
@function
@returns {jsPDF}
@methodOf jsPDF#
@name rect
*/
API.rect = function (x, y, w, h, style) {
var op = getStyle(style);
out([
f2(x * k),
f2((pageHeight - y) * k),
f2(w * k),
f2(-h * k),
're',
op
].join(' '));
return this;
};
/**
Adds a triangle to PDF
@param {Number} x1 Coordinate (in units declared at inception of PDF document) against left edge of the page
@param {Number} y1 Coordinate (in units declared at inception of PDF document) against upper edge of the page
@param {Number} x2 Coordinate (in units declared at inception of PDF document) against left edge of the page
@param {Number} y2 Coordinate (in units declared at inception of PDF document) against upper edge of the page
@param {Number} x3 Coordinate (in units declared at inception of PDF document) against left edge of the page
@param {Number} y3 Coordinate (in units declared at inception of PDF document) against upper edge of the page
@param {String} style (Defaults to active fill/stroke style) A string signalling if stroke, fill or both are to be applied.
@function
@returns {jsPDF}
@methodOf jsPDF#
@name triangle
*/
API.triangle = function (x1, y1, x2, y2, x3, y3, style) {
this.lines(
[
[ x2 - x1, y2 - y1 ], // vector to point 2
[ x3 - x2, y3 - y2 ], // vector to point 3
[ x1 - x3, y1 - y3 ] // closing vector back to point 1
],
x1,
y1, // start of path
[1, 1],
style,
true
);
return this;
};
/**
Adds a rectangle with rounded corners to PDF
@param {Number} x Coordinate (in units declared at inception of PDF document) against left edge of the page
@param {Number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page
@param {Number} w Width (in units declared at inception of PDF document)
@param {Number} h Height (in units declared at inception of PDF document)
@param {Number} rx Radius along x axis (in units declared at inception of PDF document)
@param {Number} rx Radius along y axis (in units declared at inception of PDF document)
@param {String} style (Defaults to active fill/stroke style) A string signalling if stroke, fill or both are to be applied.
@function
@returns {jsPDF}
@methodOf jsPDF#
@name roundedRect
*/
API.roundedRect = function (x, y, w, h, rx, ry, style) {
var MyArc = 4 / 3 * (Math.SQRT2 - 1);
this.lines(
[
[ (w - 2 * rx), 0 ],
[ (rx * MyArc), 0, rx, ry - (ry * MyArc), rx, ry ],
[ 0, (h - 2 * ry) ],
[ 0, (ry * MyArc), -(rx * MyArc), ry, -rx, ry],
[ (-w + 2 * rx), 0],
[ -(rx * MyArc), 0, -rx, -(ry * MyArc), -rx, -ry],
[ 0, (-h + 2 * ry)],
[ 0, -(ry * MyArc), (rx * MyArc), -ry, rx, -ry]
],
x + rx,
y, // start of path
[1, 1],
style
);
return this;
};
/**
Adds an ellipse to PDF
@param {Number} x Coordinate (in units declared at inception of PDF document) against left edge of the page
@param {Number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page
@param {Number} rx Radius along x axis (in units declared at inception of PDF document)
@param {Number} rx Radius along y axis (in units declared at inception of PDF document)
@param {String} style (Defaults to active fill/stroke style) A string signalling if stroke, fill or both are to be applied.
@function
@returns {jsPDF}
@methodOf jsPDF#
@name ellipse
*/
API.ellipse = function (x, y, rx, ry, style) {
var op = getStyle(style),
lx = 4 / 3 * (Math.SQRT2 - 1) * rx,
ly = 4 / 3 * (Math.SQRT2 - 1) * ry;
out([
f2((x + rx) * k),
f2((pageHeight - y) * k),
'm',
f2((x + rx) * k),
f2((pageHeight - (y - ly)) * k),
f2((x + lx) * k),
f2((pageHeight - (y - ry)) * k),
f2(x * k),
f2((pageHeight - (y - ry)) * k),
'c'
].join(' '));
out([
f2((x - lx) * k),
f2((pageHeight - (y - ry)) * k),
f2((x - rx) * k),
f2((pageHeight - (y - ly)) * k),
f2((x - rx) * k),
f2((pageHeight - y) * k),
'c'
].join(' '));
out([
f2((x - rx) * k),
f2((pageHeight - (y + ly)) * k),
f2((x - lx) * k),
f2((pageHeight - (y + ry)) * k),
f2(x * k),
f2((pageHeight - (y + ry)) * k),
'c'
].join(' '));
out([
f2((x + lx) * k),
f2((pageHeight - (y + ry)) * k),
f2((x + rx) * k),
f2((pageHeight - (y + ly)) * k),
f2((x + rx) * k),
f2((pageHeight - y) * k),
'c',
op
].join(' '));
return this;
};
/**
Adds an circle to PDF
@param {Number} x Coordinate (in units declared at inception of PDF document) against left edge of the page
@param {Number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page
@param {Number} r Radius (in units declared at inception of PDF document)
@param {String} style (Defaults to active fill/stroke style) A string signalling if stroke, fill or both are to be applied.
@function
@returns {jsPDF}
@methodOf jsPDF#
@name circle
*/
API.circle = function (x, y, r, style) {
return this.ellipse(x, y, r, r, style);
};
/**
Adds a properties to the PDF document
@param {Object} A property_name-to-property_value object structure.
@function
@returns {jsPDF}
@methodOf jsPDF#
@name setProperties
*/
API.setProperties = function (properties) {
// copying only those properties we can render.
var property;
for (property in documentProperties) {
if (documentProperties.hasOwnProperty(property) && properties[property]) {
documentProperties[property] = properties[property];
}
}
return this;
};
/**
Sets font size for upcoming text elements.
@param {Number} size Font size in points.
@function
@returns {jsPDF}
@methodOf jsPDF#
@name setFontSize
*/
API.setFontSize = function (size) {
activeFontSize = size;
return this;
};
/**
Sets text font face, variant for upcoming text elements.
See output of jsPDF.getFontList() for possible font names, styles.
@param {String} fontName Font name or family. Example: "times"
@param {String} fontStyle Font style or variant. Example: "italic"
@function
@returns {jsPDF}
@methodOf jsPDF#
@name setFont
*/
API.setFont = function (fontName, fontStyle) {
activeFontKey = getFont(fontName, fontStyle);
// if font is not found, the above line blows up and we never go further
return this;
};
/**
Switches font style or variant for upcoming text elements,
while keeping the font face or family same.
See output of jsPDF.getFontList() for possible font names, styles.
@param {String} style Font style or variant. Example: "italic"
@function
@returns {jsPDF}
@methodOf jsPDF#
@name setFontStyle
*/
API.setFontStyle = API.setFontType = function (style) {
var undef;
activeFontKey = getFont(undef, style);
// if font is not found, the above line blows up and we never go further
return this;
};
/**
Returns an object - a tree of fontName to fontStyle relationships available to
active PDF document.
@public
@function
@returns {Object} Like {'times':['normal', 'italic', ... ], 'arial':['normal', 'bold', ... ], ... }
@methodOf jsPDF#
@name getFontList
*/
API.getFontList = function () {
// TODO: iterate over fonts array or return copy of fontmap instead in case more are ever added.
var list = {},
fontName,
fontStyle,
tmp;
for (fontName in fontmap) {
if (fontmap.hasOwnProperty(fontName)) {
list[fontName] = tmp = [];
for (fontStyle in fontmap[fontName]) {
if (fontmap[fontName].hasOwnProperty(fontStyle)) {
tmp.push(fontStyle);
}
}
}
}
return list;
};
/**
Sets line width for upcoming lines.
@param {Number} width Line width (in units declared at inception of PDF document)
@function
@returns {jsPDF}
@methodOf jsPDF#
@name setLineWidth
*/
API.setLineWidth = function (width) {
out((width * k).toFixed(2) + ' w');
return this;
};
/**
Sets the stroke color for upcoming elements.
Depending on the number of arguments given, Gray, RGB, or CMYK
color space is implied.
When only ch1 is given, "Gray" color space is implied and it
must be a value in the range from 0.00 (solid black) to to 1.00 (white)
if values are communicated as String types, or in range from 0 (black)
to 255 (white) if communicated as Number type.
The RGB-like 0-255 range is provided for backward compatibility.
When only ch1,ch2,ch3 are given, "RGB" color space is implied and each
value must be in the range from 0.00 (minimum intensity) to to 1.00
(max intensity) if values are communicated as String types, or
from 0 (min intensity) to to 255 (max intensity) if values are communicated
as Number types.
The RGB-like 0-255 range is provided for backward compatibility.
When ch1,ch2,ch3,ch4 are given, "CMYK" color space is implied and each
value must be a in the range from 0.00 (0% concentration) to to
1.00 (100% concentration)
Because JavaScript treats fixed point numbers badly (rounds to
floating point nearest to binary representation) it is highly advised to
communicate the fractional numbers as String types, not JavaScript Number type.
@param {Number|String} ch1 Color channel value
@param {Number|String} ch2 Color channel value
@param {Number|String} ch3 Color channel value
@param {Number|String} ch4 Color channel value
@function
@returns {jsPDF}
@methodOf jsPDF#
@name setDrawColor
*/
API.setDrawColor = function (ch1, ch2, ch3, ch4) {
var color;
if (ch2 === undefined || (ch4 === undefined && ch1 === ch2 === ch3)) {
// Gray color space.
if (typeof ch1 === 'string') {
color = ch1 + ' G';
} else {
color = f2(ch1 / 255) + ' G';
}
} else if (ch4 === undefined) {
// RGB
if (typeof ch1 === 'string') {
color = [ch1, ch2, ch3, 'RG'].join(' ');
} else {
color = [f2(ch1 / 255), f2(ch2 / 255), f2(ch3 / 255), 'RG'].join(' ');
}
} else {
// CMYK
if (typeof ch1 === 'string') {
color = [ch1, ch2, ch3, ch4, 'K'].join(' ');
} else {
color = [f2(ch1), f2(ch2), f2(ch3), f2(ch4), 'K'].join(' ');
}
}
out(color);
return this;
};
/**
Sets the fill color for upcoming elements.
Depending on the number of arguments given, Gray, RGB, or CMYK
color space is implied.
When only ch1 is given, "Gray" color space is implied and it
must be a value in the range from 0.00 (solid black) to to 1.00 (white)
if values are communicated as String types, or in range from 0 (black)
to 255 (white) if communicated as Number type.
The RGB-like 0-255 range is provided for backward compatibility.
When only ch1,ch2,ch3 are given, "RGB" color space is implied and each
value must be in the range from 0.00 (minimum intensity) to to 1.00
(max intensity) if values are communicated as String types, or
from 0 (min intensity) to to 255 (max intensity) if values are communicated
as Number types.
The RGB-like 0-255 range is provided for backward compatibility.
When ch1,ch2,ch3,ch4 are given, "CMYK" color space is implied and each
value must be a in the range from 0.00 (0% concentration) to to
1.00 (100% concentration)
Because JavaScript treats fixed point numbers badly (rounds to
floating point nearest to binary representation) it is highly advised to
communicate the fractional numbers as String types, not JavaScript Number type.
@param {Number|String} ch1 Color channel value
@param {Number|String} ch2 Color channel value
@param {Number|String} ch3 Color channel value
@param {Number|String} ch4 Color channel value
@function
@returns {jsPDF}
@methodOf jsPDF#
@name setFillColor
*/
API.setFillColor = function (ch1, ch2, ch3, ch4) {
var color;
if (ch2 === undefined || (ch4 === undefined && ch1 === ch2 === ch3)) {
// Gray color space.
if (typeof ch1 === 'string') {
color = ch1 + ' g';
} else {
color = f2(ch1 / 255) + ' g';
}
} else if (ch4 === undefined) {
// RGB
if (typeof ch1 === 'string') {
color = [ch1, ch2, ch3, 'rg'].join(' ');
} else {
color = [f2(ch1 / 255), f2(ch2 / 255), f2(ch3 / 255), 'rg'].join(' ');
}
} else {
// CMYK
if (typeof ch1 === 'string') {
color = [ch1, ch2, ch3, ch4, 'k'].join(' ');
} else {
color = [f2(ch1), f2(ch2), f2(ch3), f2(ch4), 'k'].join(' ');
}
}
out(color);
return this;
};
/**
Sets the text color for upcoming elements.
If only one, first argument is given,
treats the value as gray-scale color value.
@param {Number} r Red channel color value in range 0-255 or {String} r color value in hexadecimal, example: '#FFFFFF'
@param {Number} g Green channel color value in range 0-255
@param {Number} b Blue channel color value in range 0-255
@function
@returns {jsPDF}
@methodOf jsPDF#
@name setTextColor
*/
API.setTextColor = function (r, g, b) {
var patt = /#[0-9A-Fa-f]{6}/;
if ((typeof r == 'string') && patt.test(r)) {
var hex = r.replace('#','');
var bigint = parseInt(hex, 16);
r = (bigint >> 16) & 255;
g = (bigint >> 8) & 255;
b = bigint & 255;
}
if ((r === 0 && g === 0 && b === 0) || (typeof g === 'undefined')) {
textColor = f3(r / 255) + ' g';
} else {
textColor = [f3(r / 255), f3(g / 255), f3(b / 255), 'rg'].join(' ');
}
return this;
};
/**
Is an Object providing a mapping from human-readable to
integer flag values designating the varieties of line cap
and join styles.
@returns {Object}
@fieldOf jsPDF#
@name CapJoinStyles
*/
API.CapJoinStyles = {
0: 0,
'butt': 0,
'but': 0,
'miter': 0,
1: 1,
'round': 1,
'rounded': 1,
'circle': 1,
2: 2,
'projecting': 2,
'project': 2,
'square': 2,
'bevel': 2
};
/**
Sets the line cap styles
See {jsPDF.CapJoinStyles} for variants
@param {String|Number} style A string or number identifying the type of line cap
@function
@returns {jsPDF}
@methodOf jsPDF#
@name setLineCap
*/
API.setLineCap = function (style) {
var id = this.CapJoinStyles[style];
if (id === undefined) {
throw new Error("Line cap style of '" + style + "' is not recognized. See or extend .CapJoinStyles property for valid styles");
}
lineCapID = id;
out(id.toString(10) + ' J');
return this;
};
/**
Sets the line join styles
See {jsPDF.CapJoinStyles} for variants
@param {String|Number} style A string or number identifying the type of line join
@function
@returns {jsPDF}
@methodOf jsPDF#
@name setLineJoin
*/
API.setLineJoin = function (style) {
var id = this.CapJoinStyles[style];
if (id === undefined) {
throw new Error("Line join style of '" + style + "' is not recognized. See or extend .CapJoinStyles property for valid styles");
}
lineJoinID = id;
out(id.toString(10) + ' j');
return this;
};
// Output is both an internal (for plugins) and external function
API.output = output;
/**
* Saves as PDF document. An alias of jsPDF.output('save', 'filename.pdf')
* @param {String} filename The filename including extension.
*
* @function
* @returns {jsPDF}
* @methodOf jsPDF#
* @name save
*/
API.save = function (filename) {
API.output('save', filename);
};
// applying plugins (more methods) ON TOP of built-in API.
// this is intentional as we allow plugins to override
// built-ins
for (plugin in jsPDF.API) {
if (jsPDF.API.hasOwnProperty(plugin)) {
if (plugin === 'events' && jsPDF.API.events.length) {
(function (events, newEvents) {
// jsPDF.API.events is a JS Array of Arrays
// where each Array is a pair of event name, handler
// Events were added by plugins to the jsPDF instantiator.
// These are always added to the new instance and some ran
// during instantiation.
var eventname, handler_and_args, i;
for (i = newEvents.length - 1; i !== -1; i--) {
// subscribe takes 3 args: 'topic', function, runonce_flag
// if undefined, runonce is false.
// users can attach callback directly,
// or they can attach an array with [callback, runonce_flag]
// that's what the "apply" magic is for below.
eventname = newEvents[i][0];
handler_and_args = newEvents[i][1];
events.subscribe.apply(
events,
[eventname].concat(
typeof handler_and_args === 'function' ?
[ handler_and_args ] :
handler_and_args
)
);
}
}(events, jsPDF.API.events));
} else {
API[plugin] = jsPDF.API[plugin];
}
}
}
/////////////////////////////////////////
// continuing initilisation of jsPDF Document object
/////////////////////////////////////////
// Add the first page automatically
addFonts();
activeFontKey = 'F1';
_addPage();
events.publish('initialized');
return API;
}
/**
jsPDF.API is a STATIC property of jsPDF class.
jsPDF.API is an object you can add methods and properties to.
The methods / properties you add will show up in new jsPDF objects.
One property is prepopulated. It is the 'events' Object. Plugin authors can add topics, callbacks to this object. These will be reassigned to all new instances of jsPDF.
Examples:
jsPDF.API.events['initialized'] = function(){ 'this' is API object }
jsPDF.API.events['addFont'] = function(added_font_object){ 'this' is API object }
@static
@public
@memberOf jsPDF
@name API
@example
jsPDF.API.mymethod = function(){
// 'this' will be ref to internal API object. see jsPDF source
// , so you can refer to built-in methods like so:
// this.line(....)
// this.text(....)
}
var pdfdoc = new jsPDF()
pdfdoc.mymethod() // <- !!!!!!
*/
jsPDF.API = {'events': []};
return jsPDF;
}());
/*! normalize.css v3.0.0 | MIT License | git.io/normalize */
/**
* 1. Set default font family to sans-serif.
* 2. Prevent iOS text size adjust after orientation change, without disabling
* user zoom.
*/
html {
font-family: sans-serif; /* 1 */
-ms-text-size-adjust: 100%; /* 2 */
-webkit-text-size-adjust: 100%; /* 2 */
}
/**
* Remove default margin.
*/
body {
margin: 0;
}
/* HTML5 display definitions
========================================================================== */
/**
* Correct `block` display not defined in IE 8/9.
*/
article,
aside,
details,
figcaption,
figure,
footer,
header,
hgroup,
main,
nav,
section,
summary {
display: block;
}
/**
* 1. Correct `inline-block` display not defined in IE 8/9.
* 2. Normalize vertical alignment of `progress` in Chrome, Firefox, and Opera.
*/
audio,
canvas,
progress,
video {
display: inline-block; /* 1 */
vertical-align: baseline; /* 2 */
}
/**
* Prevent modern browsers from displaying `audio` without controls.
* Remove excess height in iOS 5 devices.
*/
audio:not([controls]) {
display: none;
height: 0;
}
/**
* Address `[hidden]` styling not present in IE 8/9.
* Hide the `template` element in IE, Safari, and Firefox < 22.
*/
[hidden],
template {
display: none;
}
/* Links
========================================================================== */
/**
* Remove the gray background color from active links in IE 10.
*/
a {
background: transparent;
}
/**
* Improve readability when focused and also mouse hovered in all browsers.
*/
a:active,
a:hover {
outline: 0;
}
/* Text-level semantics
========================================================================== */
/**
* Address styling not present in IE 8/9, Safari 5, and Chrome.
*/
abbr[title] {
border-bottom: 1px dotted;
}
/**
* Address style set to `bolder` in Firefox 4+, Safari 5, and Chrome.
*/
b,
strong {
font-weight: bold;
}
/**
* Address styling not present in Safari 5 and Chrome.
*/
dfn {
font-style: italic;
}
/**
* Address variable `h1` font-size and margin within `section` and `article`
* contexts in Firefox 4+, Safari 5, and Chrome.
*/
h1 {
font-size: 2em;
margin: 0.67em 0;
}
/**
* Address styling not present in IE 8/9.
*/
mark {
background: #ff0;
color: #000;
}
/**
* Address inconsistent and variable font size in all browsers.
*/
small {
font-size: 80%;
}
/**
* Prevent `sub` and `sup` affecting `line-height` in all browsers.
*/
sub,
sup {
font-size: 75%;
line-height: 0;
position: relative;
vertical-align: baseline;
}
sup {
top: -0.5em;
}
sub {
bottom: -0.25em;
}
/* Embedded content
========================================================================== */
/**
* Remove border when inside `a` element in IE 8/9.
*/
img {
border: 0;
}
/**
* Correct overflow displayed oddly in IE 9.
*/
svg:not(:root) {
overflow: hidden;
}
/* Grouping content
========================================================================== */
/**
* Address margin not present in IE 8/9 and Safari 5.
*/
figure {
margin: 1em 40px;
}
/**
* Address differences between Firefox and other browsers.
*/
hr {
-moz-box-sizing: content-box;
box-sizing: content-box;
height: 0;
}
/**
* Contain overflow in all browsers.
*/
pre {
overflow: auto;
}
/**
* Address odd `em`-unit font size rendering in all browsers.
*/
code,
kbd,
pre,
samp {
font-family: monospace, monospace;
font-size: 1em;
}
/* Forms
========================================================================== */
/**
* Known limitation: by default, Chrome and Safari on OS X allow very limited
* styling of `select`, unless a `border` property is set.
*/
/**
* 1. Correct color not being inherited.
* Known issue: affects color of disabled elements.
* 2. Correct font properties not being inherited.
* 3. Address margins set differently in Firefox 4+, Safari 5, and Chrome.
*/
button,
input,
optgroup,
select,
textarea {
color: inherit; /* 1 */
font: inherit; /* 2 */
margin: 0; /* 3 */
}
/**
* Address `overflow` set to `hidden` in IE 8/9/10.
*/
button {
overflow: visible;
}
/**
* Address inconsistent `text-transform` inheritance for `button` and `select`.
* All other form control elements do not inherit `text-transform` values.
* Correct `button` style inheritance in Firefox, IE 8+, and Opera
* Correct `select` style inheritance in Firefox.
*/
button,
select {
text-transform: none;
}
/**
* 1. Avoid the WebKit bug in Android 4.0.* where (2) destroys native `audio`
* and `video` controls.
* 2. Correct inability to style clickable `input` types in iOS.
* 3. Improve usability and consistency of cursor style between image-type
* `input` and others.
*/
button,
html input[type="button"], /* 1 */
input[type="reset"],
input[type="submit"] {
-webkit-appearance: button; /* 2 */
cursor: pointer; /* 3 */
}
/**
* Re-set default cursor for disabled elements.
*/
button[disabled],
html input[disabled] {
cursor: default;
}
/**
* Remove inner padding and border in Firefox 4+.
*/
button::-moz-focus-inner,
input::-moz-focus-inner {
border: 0;
padding: 0;
}
/**
* Address Firefox 4+ setting `line-height` on `input` using `!important` in
* the UA stylesheet.
*/
input {
line-height: normal;
}
/**
* It's recommended that you don't attempt to style these elements.
* Firefox's implementation doesn't respect box-sizing, padding, or width.
*
* 1. Address box sizing set to `content-box` in IE 8/9/10.
* 2. Remove excess padding in IE 8/9/10.
*/
input[type="checkbox"],
input[type="radio"] {
box-sizing: border-box; /* 1 */
padding: 0; /* 2 */
}
/**
* Fix the cursor style for Chrome's increment/decrement buttons. For certain
* `font-size` values of the `input`, it causes the cursor style of the
* decrement button to change from `default` to `text`.
*/
input[type="number"]::-webkit-inner-spin-button,
input[type="number"]::-webkit-outer-spin-button {
height: auto;
}
/**
* 1. Address `appearance` set to `searchfield` in Safari 5 and Chrome.
* 2. Address `box-sizing` set to `border-box` in Safari 5 and Chrome
* (include `-moz` to future-proof).
*/
input[type="search"] {
-webkit-appearance: textfield; /* 1 */
-moz-box-sizing: content-box;
-webkit-box-sizing: content-box; /* 2 */
box-sizing: content-box;
}
/**
* Remove inner padding and search cancel button in Safari and Chrome on OS X.
* Safari (but not Chrome) clips the cancel button when the search input has
* padding (and `textfield` appearance).
*/
input[type="search"]::-webkit-search-cancel-button,
input[type="search"]::-webkit-search-decoration {
-webkit-appearance: none;
}
/**
* Define consistent border, margin, and padding.
*/
fieldset {
border: 1px solid #c0c0c0;
margin: 0 2px;
padding: 0.35em 0.625em 0.75em;
}
/**
* 1. Correct `color` not being inherited in IE 8/9.
* 2. Remove padding so people aren't caught out if they zero out fieldsets.
*/
legend {
border: 0; /* 1 */
padding: 0; /* 2 */
}
/**
* Remove default vertical scrollbar in IE 8/9.
*/
textarea {
overflow: auto;
}
/**
* Don't inherit the `font-weight` (applied by a rule above).
* NOTE: the default cannot safely be changed in Chrome and Safari on OS X.
*/
optgroup {
font-weight: bold;
}
/* Tables
========================================================================== */
/**
* Remove most spacing between table cells.
*/
table {
border-collapse: collapse;
border-spacing: 0;
}
td,
th {
padding: 0;
}
/*
selectivizr v1.0.2 - (c) Keith Clark, freely distributable under the terms
of the MIT license.
selectivizr.com
*/
/*
Notes about this source
-----------------------
* The #DEBUG_START and #DEBUG_END comments are used to mark blocks of code
that will be removed prior to building a final release version (using a
pre-compression script)
References:
-----------
* CSS Syntax : http://www.w3.org/TR/2003/WD-css3-syntax-20030813/#style
* Selectors : http://www.w3.org/TR/css3-selectors/#selectors
* IE Compatability : http://msdn.microsoft.com/en-us/library/cc351024(VS.85).aspx
* W3C Selector Tests : http://www.w3.org/Style/CSS/Test/CSS3/Selectors/current/html/tests/
*/
(function(win) {
// If browser isn't IE, then stop execution! This handles the script
// being loaded by non IE browsers because the developer didn't use
// conditional comments.
if (/*@cc_on!@*/true) return;
// =========================== Init Objects ============================
var doc = document;
var root = doc.documentElement;
var xhr = getXHRObject();
var ieVersion = /MSIE (\d+)/.exec(navigator.userAgent)[1];
// If were not in standards mode, IE is too old / new or we can't create
// an XMLHttpRequest object then we should get out now.
if (doc.compatMode != 'CSS1Compat' || ieVersion<6 || ieVersion>8 || !xhr) {
return;
}
// ========================= Common Objects ============================
// Compatiable selector engines in order of CSS3 support. Note: '*' is
// a placholder for the object key name. (basically, crude compression)
var selectorEngines = {
"NW" : "*.Dom.select",
"MooTools" : "$$",
"DOMAssistant" : "*.$",
"Prototype" : "$$",
"YAHOO" : "*.util.Selector.query",
"Sizzle" : "*",
"jQuery" : "*",
"dojo" : "*.query"
};
var selectorMethod;
var enabledWatchers = []; // array of :enabled/:disabled elements to poll
var ie6PatchID = 0; // used to solve ie6's multiple class bug
var patchIE6MultipleClasses = true; // if true adds class bloat to ie6
var namespace = "slvzr";
// Stylesheet parsing regexp's
var RE_COMMENT = /(\/\*[^*]*\*+([^\/][^*]*\*+)*\/)\s*/g;
var RE_IMPORT = /@import\s*(?:(?:(?:url\(\s*(['"]?)(.*)\1)\s*\))|(?:(['"])(.*)\3))[^;]*;/g;
var RE_ASSET_URL = /\burl\(\s*(["']?)(?!data:)([^"')]+)\1\s*\)/g;
var RE_PSEUDO_STRUCTURAL = /^:(empty|(first|last|only|nth(-last)?)-(child|of-type))$/;
var RE_PSEUDO_ELEMENTS = /:(:first-(?:line|letter))/g;
var RE_SELECTOR_GROUP = /(^|})\s*([^\{]*?[\[:][^{]+)/g;
var RE_SELECTOR_PARSE = /([ +~>])|(:[a-z-]+(?:\(.*?\)+)?)|(\[.*?\])/g;
var RE_LIBRARY_INCOMPATIBLE_PSEUDOS = /(:not\()?:(hover|enabled|disabled|focus|checked|target|active|visited|first-line|first-letter)\)?/g;
var RE_PATCH_CLASS_NAME_REPLACE = /[^\w-]/g;
// HTML UI element regexp's
var RE_INPUT_ELEMENTS = /^(INPUT|SELECT|TEXTAREA|BUTTON)$/;
var RE_INPUT_CHECKABLE_TYPES = /^(checkbox|radio)$/;
// Broken attribute selector implementations (IE7/8 native [^=""], [$=""] and [*=""])
var BROKEN_ATTR_IMPLEMENTATIONS = ieVersion>6 ? /[\$\^*]=(['"])\1/ : null;
// Whitespace normalization regexp's
var RE_TIDY_TRAILING_WHITESPACE = /([(\[+~])\s+/g;
var RE_TIDY_LEADING_WHITESPACE = /\s+([)\]+~])/g;
var RE_TIDY_CONSECUTIVE_WHITESPACE = /\s+/g;
var RE_TIDY_TRIM_WHITESPACE = /^\s*((?:[\S\s]*\S)?)\s*$/;
// String constants
var EMPTY_STRING = "";
var SPACE_STRING = " ";
var PLACEHOLDER_STRING = "$1";
// =========================== Patching ================================
// --[ patchStyleSheet() ]----------------------------------------------
// Scans the passed cssText for selectors that require emulation and
// creates one or more patches for each matched selector.
function patchStyleSheet( cssText ) {
return cssText.replace(RE_PSEUDO_ELEMENTS, PLACEHOLDER_STRING).
replace(RE_SELECTOR_GROUP, function(m, prefix, selectorText) {
var selectorGroups = selectorText.split(",");
for (var c = 0, cs = selectorGroups.length; c < cs; c++) {
var selector = normalizeSelectorWhitespace(selectorGroups[c]) + SPACE_STRING;
var patches = [];
selectorGroups[c] = selector.replace(RE_SELECTOR_PARSE,
function(match, combinator, pseudo, attribute, index) {
if (combinator) {
if (patches.length>0) {
applyPatches( selector.substring(0, index), patches );
patches = [];
}
return combinator;
}
else {
var patch = (pseudo) ? patchPseudoClass( pseudo ) : patchAttribute( attribute );
if (patch) {
patches.push(patch);
return "." + patch.className;
}
return match;
}
}
);
}
return prefix + selectorGroups.join(",");
});
};
// --[ patchAttribute() ]-----------------------------------------------
// returns a patch for an attribute selector.
function patchAttribute( attr ) {
return (!BROKEN_ATTR_IMPLEMENTATIONS || BROKEN_ATTR_IMPLEMENTATIONS.test(attr)) ?
{ className: createClassName(attr), applyClass: true } : null;
};
// --[ patchPseudoClass() ]---------------------------------------------
// returns a patch for a pseudo-class
function patchPseudoClass( pseudo ) {
var applyClass = true;
var className = createClassName(pseudo.slice(1));
var isNegated = pseudo.substring(0, 5) == ":not(";
var activateEventName;
var deactivateEventName;
// if negated, remove :not()
if (isNegated) {
pseudo = pseudo.slice(5, -1);
}
// bracket contents are irrelevant - remove them
var bracketIndex = pseudo.indexOf("(")
if (bracketIndex > -1) {
pseudo = pseudo.substring(0, bracketIndex);
}
// check we're still dealing with a pseudo-class
if (pseudo.charAt(0) == ":") {
switch (pseudo.slice(1)) {
case "root":
applyClass = function(e) {
return isNegated ? e != root : e == root;
}
break;
case "target":
// :target is only supported in IE8
if (ieVersion == 8) {
applyClass = function(e) {
var handler = function() {
var hash = location.hash;
var hashID = hash.slice(1);
return isNegated ? (hash == EMPTY_STRING || e.id != hashID) : (hash != EMPTY_STRING && e.id == hashID);
};
addEvent( win, "hashchange", function() {
toggleElementClass(e, className, handler());
})
return handler();
}
break;
}
return false;
case "checked":
applyClass = function(e) {
if (RE_INPUT_CHECKABLE_TYPES.test(e.type)) {
addEvent( e, "propertychange", function() {
if (event.propertyName == "checked") {
toggleElementClass( e, className, e.checked !== isNegated );
}
})
}
return e.checked !== isNegated;
}
break;
case "disabled":
isNegated = !isNegated;
case "enabled":
applyClass = function(e) {
if (RE_INPUT_ELEMENTS.test(e.tagName)) {
addEvent( e, "propertychange", function() {
if (event.propertyName == "$disabled") {
toggleElementClass( e, className, e.$disabled === isNegated );
}
});
enabledWatchers.push(e);
e.$disabled = e.disabled;
return e.disabled === isNegated;
}
return pseudo == ":enabled" ? isNegated : !isNegated;
}
break;
case "focus":
activateEventName = "focus";
deactivateEventName = "blur";
case "hover":
if (!activateEventName) {
activateEventName = "mouseenter";
deactivateEventName = "mouseleave";
}
applyClass = function(e) {
addEvent( e, isNegated ? deactivateEventName : activateEventName, function() {
toggleElementClass( e, className, true );
})
addEvent( e, isNegated ? activateEventName : deactivateEventName, function() {
toggleElementClass( e, className, false );
})
return isNegated;
}
break;
// everything else
default:
// If we don't support this pseudo-class don't create
// a patch for it
if (!RE_PSEUDO_STRUCTURAL.test(pseudo)) {
return false;
}
break;
}
}
return { className: className, applyClass: applyClass };
};
// --[ applyPatches() ]-------------------------------------------------
// uses the passed selector text to find DOM nodes and patch them
function applyPatches(selectorText, patches) {
var elms;
// Although some selector libraries can find :checked :enabled etc.
// we need to find all elements that could have that state because
// it can be changed by the user.
var domSelectorText = selectorText.replace(RE_LIBRARY_INCOMPATIBLE_PSEUDOS, EMPTY_STRING);
// If the dom selector equates to an empty string or ends with
// whitespace then we need to append a universal selector (*) to it.
if (domSelectorText == EMPTY_STRING || domSelectorText.charAt(domSelectorText.length - 1) == SPACE_STRING) {
domSelectorText += "*";
}
// Ensure we catch errors from the selector library
try {
elms = selectorMethod( domSelectorText );
} catch (ex) {
// #DEBUG_START
log( "Selector '" + selectorText + "' threw exception '" + ex + "'" );
// #DEBUG_END
}
if (elms) {
for (var d = 0, dl = elms.length; d < dl; d++) {
var elm = elms[d];
var cssClasses = elm.className;
for (var f = 0, fl = patches.length; f < fl; f++) {
var patch = patches[f];
if (!hasPatch(elm, patch)) {
if (patch.applyClass && (patch.applyClass === true || patch.applyClass(elm) === true)) {
cssClasses = toggleClass(cssClasses, patch.className, true );
}
}
}
elm.className = cssClasses;
}
}
};
// --[ hasPatch() ]-----------------------------------------------------
// checks for the exsistence of a patch on an element
function hasPatch( elm, patch ) {
return new RegExp("(^|\\s)" + patch.className + "(\\s|$)").test(elm.className);
};
// =========================== Utility =================================
function createClassName( className ) {
return namespace + "-" + ((ieVersion == 6 && patchIE6MultipleClasses) ?
ie6PatchID++
:
className.replace(RE_PATCH_CLASS_NAME_REPLACE, function(a) { return a.charCodeAt(0) }));
};
// --[ log() ]----------------------------------------------------------
// #DEBUG_START
function log( message ) {
if (win.console) {
win.console.log(message);
}
};
// #DEBUG_END
// --[ trim() ]---------------------------------------------------------
// removes leading, trailing whitespace from a string
function trim( text ) {
return text.replace(RE_TIDY_TRIM_WHITESPACE, PLACEHOLDER_STRING);
};
// --[ normalizeWhitespace() ]------------------------------------------
// removes leading, trailing and consecutive whitespace from a string
function normalizeWhitespace( text ) {
return trim(text).replace(RE_TIDY_CONSECUTIVE_WHITESPACE, SPACE_STRING);
};
// --[ normalizeSelectorWhitespace() ]----------------------------------
// tidies whitespace around selector brackets and combinators
function normalizeSelectorWhitespace( selectorText ) {
return normalizeWhitespace(selectorText.
replace(RE_TIDY_TRAILING_WHITESPACE, PLACEHOLDER_STRING).
replace(RE_TIDY_LEADING_WHITESPACE, PLACEHOLDER_STRING)
);
};
// --[ toggleElementClass() ]-------------------------------------------
// toggles a single className on an element
function toggleElementClass( elm, className, on ) {
var oldClassName = elm.className;
var newClassName = toggleClass(oldClassName, className, on);
if (newClassName != oldClassName) {
elm.className = newClassName;
elm.parentNode.className += EMPTY_STRING;
}
};
// --[ toggleClass() ]--------------------------------------------------
// adds / removes a className from a string of classNames. Used to
// manage multiple class changes without forcing a DOM redraw
function toggleClass( classList, className, on ) {
var re = RegExp("(^|\\s)" + className + "(\\s|$)");
var classExists = re.test(classList);
if (on) {
return classExists ? classList : classList + SPACE_STRING + className;
} else {
return classExists ? trim(classList.replace(re, PLACEHOLDER_STRING)) : classList;
}
};
// --[ addEvent() ]-----------------------------------------------------
function addEvent(elm, eventName, eventHandler) {
elm.attachEvent("on" + eventName, eventHandler);
};
// --[ getXHRObject() ]-------------------------------------------------
function getXHRObject()
{
if (win.XMLHttpRequest) {
return new XMLHttpRequest;
}
try {
return new ActiveXObject('Microsoft.XMLHTTP');
} catch(e) {
return null;
}
};
// --[ loadStyleSheet() ]-----------------------------------------------
function loadStyleSheet( url ) {
xhr.open("GET", url, false);
xhr.send();
return (xhr.status==200) ? xhr.responseText : EMPTY_STRING;
};
// --[ resolveUrl() ]---------------------------------------------------
// Converts a URL fragment to a fully qualified URL using the specified
// context URL. Returns null if same-origin policy is broken
function resolveUrl( url, contextUrl ) {
function getProtocolAndHost( url ) {
return url.substring(0, url.indexOf("/", 8));
};
// absolute path
if (/^https?:\/\//i.test(url)) {
return getProtocolAndHost(contextUrl) == getProtocolAndHost(url) ? url : null;
}
// root-relative path
if (url.charAt(0)=="/") {
return getProtocolAndHost(contextUrl) + url;
}
// relative path
var contextUrlPath = contextUrl.split(/[?#]/)[0]; // ignore query string in the contextUrl
if (url.charAt(0) != "?" && contextUrlPath.charAt(contextUrlPath.length - 1) != "/") {
contextUrlPath = contextUrlPath.substring(0, contextUrlPath.lastIndexOf("/") + 1);
}
return contextUrlPath + url;
};
// --[ parseStyleSheet() ]----------------------------------------------
// Downloads the stylesheet specified by the URL, removes it's comments
// and recursivly replaces @import rules with their contents, ultimately
// returning the full cssText.
function parseStyleSheet( url ) {
if (url) {
return loadStyleSheet(url).replace(RE_COMMENT, EMPTY_STRING).
replace(RE_IMPORT, function( match, quoteChar, importUrl, quoteChar2, importUrl2 ) {
return parseStyleSheet(resolveUrl(importUrl || importUrl2, url));
}).
replace(RE_ASSET_URL, function( match, quoteChar, assetUrl ) {
quoteChar = quoteChar || EMPTY_STRING;
return " url(" + quoteChar + resolveUrl(assetUrl, url) + quoteChar + ") ";
});
}
return EMPTY_STRING;
};
// --[ init() ]---------------------------------------------------------
function init() {
// honour the <base> tag
var url, stylesheet;
var baseTags = doc.getElementsByTagName("BASE");
var baseUrl = (baseTags.length > 0) ? baseTags[0].href : doc.location.href;
/* Note: This code prevents IE from freezing / crashing when using
@font-face .eot files but it modifies the <head> tag and could
trigger the IE stylesheet limit. It will also cause FOUC issues.
If you choose to use it, make sure you comment out the for loop
directly below this comment.
var head = doc.getElementsByTagName("head")[0];
for (var c=doc.styleSheets.length-1; c>=0; c--) {
stylesheet = doc.styleSheets[c]
head.appendChild(doc.createElement("style"))
var patchedStylesheet = doc.styleSheets[doc.styleSheets.length-1];
if (stylesheet.href != EMPTY_STRING) {
url = resolveUrl(stylesheet.href, baseUrl)
if (url) {
patchedStylesheet.cssText = patchStyleSheet( parseStyleSheet( url ) )
stylesheet.disabled = true
setTimeout( function () {
stylesheet.owningElement.parentNode.removeChild(stylesheet.owningElement)
})
}
}
}
*/
for (var c = 0; c < doc.styleSheets.length; c++) {
stylesheet = doc.styleSheets[c]
if (stylesheet.href != EMPTY_STRING) {
url = resolveUrl(stylesheet.href, baseUrl);
if (url) {
stylesheet.cssText = patchStyleSheet( parseStyleSheet( url ) );
}
}
}
// :enabled & :disabled polling script (since we can't hook
// onpropertychange event when an element is disabled)
if (enabledWatchers.length > 0) {
setInterval( function() {
for (var c = 0, cl = enabledWatchers.length; c < cl; c++) {
var e = enabledWatchers[c];
if (e.disabled !== e.$disabled) {
if (e.disabled) {
e.disabled = false;
e.$disabled = true;
e.disabled = true;
}
else {
e.$disabled = e.disabled;
}
}
}
},250)
}
};
// Bind selectivizr to the ContentLoaded event.
ContentLoaded(win, function() {
// Determine the "best fit" selector engine
for (var engine in selectorEngines) {
var members, member, context = win;
if (win[engine]) {
members = selectorEngines[engine].replace("*", engine).split(".");
while ((member = members.shift()) && (context = context[member])) {}
if (typeof context == "function") {
selectorMethod = context;
init();
return;
}
}
}
});
/*!
* ContentLoaded.js by Diego Perini, modified for IE<9 only (to save space)
*
* Author: Diego Perini (diego.perini at gmail.com)
* Summary: cross-browser wrapper for DOMContentLoaded
* Updated: 20101020
* License: MIT
* Version: 1.2
*
* URL:
* http://javascript.nwbox.com/ContentLoaded/
* http://javascript.nwbox.com/ContentLoaded/MIT-LICENSE
*
*/
// @w window reference
// @f function reference
function ContentLoaded(win, fn) {
var done = false, top = true,
init = function(e) {
if (e.type == "readystatechange" && doc.readyState != "complete") return;
(e.type == "load" ? win : doc).detachEvent("on" + e.type, init, false);
if (!done && (done = true)) fn.call(win, e.type || e);
},
poll = function() {
try { root.doScroll("left"); } catch(e) { setTimeout(poll, 50); return; }
init('poll');
};
if (doc.readyState == "complete") fn.call(win, EMPTY_STRING);
else {
if (doc.createEventObject && root.doScroll) {
try { top = !win.frameElement; } catch(e) { }
if (top) poll();
}
addEvent(doc,"readystatechange", init);
addEvent(win,"load", init);
}
};
})(this);
\ No newline at end of file
/*
Javascript State Machine Library - https://github.com/jakesgordon/javascript-state-machine
Copyright (c) 2012, 2013 Jake Gordon and contributors
Released under the MIT license - https://github.com/jakesgordon/javascript-state-machine/blob/master/LICENSE
*/
(function (window) {
var StateMachine = {
//---------------------------------------------------------------------------
VERSION: "2.2.0",
//---------------------------------------------------------------------------
Result: {
SUCCEEDED: 1, // the event transitioned successfully from one state to another
NOTRANSITION: 2, // the event was successfull but no state transition was necessary
CANCELLED: 3, // the event was cancelled by the caller in a beforeEvent callback
PENDING: 4 // the event is asynchronous and the caller is in control of when the transition occurs
},
Error: {
INVALID_TRANSITION: 100, // caller tried to fire an event that was innapropriate in the current state
PENDING_TRANSITION: 200, // caller tried to fire an event while an async transition was still pending
INVALID_CALLBACK: 300 // caller provided callback function threw an exception
},
WILDCARD: '*',
ASYNC: 'async',
//---------------------------------------------------------------------------
create: function(cfg, target) {
var initial = (typeof cfg.initial == 'string') ? { state: cfg.initial } : cfg.initial; // allow for a simple string, or an object with { state: 'foo', event: 'setup', defer: true|false }
var terminal = cfg.terminal || cfg['final'];
var fsm = target || cfg.target || {};
var events = cfg.events || [];
var callbacks = cfg.callbacks || {};
var map = {};
var add = function(e) {
var from = (e.from instanceof Array) ? e.from : (e.from ? [e.from] : [StateMachine.WILDCARD]); // allow 'wildcard' transition if 'from' is not specified
map[e.name] = map[e.name] || {};
for (var n = 0 ; n < from.length ; n++)
map[e.name][from[n]] = e.to || from[n]; // allow no-op transition if 'to' is not specified
};
if (initial) {
initial.event = initial.event || 'startup';
add({ name: initial.event, from: 'none', to: initial.state });
}
for(var n = 0 ; n < events.length ; n++)
add(events[n]);
for(var name in map) {
if (map.hasOwnProperty(name))
fsm[name] = StateMachine.buildEvent(name, map[name]);
}
for(var name in callbacks) {
if (callbacks.hasOwnProperty(name))
fsm[name] = callbacks[name]
}
fsm.current = 'none';
fsm.is = function(state) { return (state instanceof Array) ? (state.indexOf(this.current) >= 0) : (this.current === state); };
fsm.can = function(event) { return !this.transition && (map[event].hasOwnProperty(this.current) || map[event].hasOwnProperty(StateMachine.WILDCARD)); }
fsm.cannot = function(event) { return !this.can(event); };
fsm.error = cfg.error || function(name, from, to, args, error, msg, e) { throw e || msg; }; // default behavior when something unexpected happens is to throw an exception, but caller can override this behavior if desired (see github issue #3 and #17)
fsm.isFinished = function() { return this.is(terminal); };
if (initial && !initial.defer)
fsm[initial.event]();
return fsm;
},
//===========================================================================
doCallback: function(fsm, func, name, from, to, args) {
if (func) {
try {
return func.apply(fsm, [name, from, to].concat(args));
}
catch(e) {
return fsm.error(name, from, to, args, StateMachine.Error.INVALID_CALLBACK, "an exception occurred in a caller-provided callback function", e);
}
}
},
beforeAnyEvent: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onbeforeevent'], name, from, to, args); },
afterAnyEvent: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onafterevent'] || fsm['onevent'], name, from, to, args); },
leaveAnyState: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onleavestate'], name, from, to, args); },
enterAnyState: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onenterstate'] || fsm['onstate'], name, from, to, args); },
changeState: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onchangestate'], name, from, to, args); },
beforeThisEvent: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onbefore' + name], name, from, to, args); },
afterThisEvent: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onafter' + name] || fsm['on' + name], name, from, to, args); },
leaveThisState: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onleave' + from], name, from, to, args); },
enterThisState: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onenter' + to] || fsm['on' + to], name, from, to, args); },
beforeEvent: function(fsm, name, from, to, args) {
if ((false === StateMachine.beforeThisEvent(fsm, name, from, to, args)) ||
(false === StateMachine.beforeAnyEvent( fsm, name, from, to, args)))
return false;
},
afterEvent: function(fsm, name, from, to, args) {
StateMachine.afterThisEvent(fsm, name, from, to, args);
StateMachine.afterAnyEvent( fsm, name, from, to, args);
},
leaveState: function(fsm, name, from, to, args) {
var specific = StateMachine.leaveThisState(fsm, name, from, to, args),
general = StateMachine.leaveAnyState( fsm, name, from, to, args);
if ((false === specific) || (false === general))
return false;
else if ((StateMachine.ASYNC === specific) || (StateMachine.ASYNC === general))
return StateMachine.ASYNC;
},
enterState: function(fsm, name, from, to, args) {
StateMachine.enterThisState(fsm, name, from, to, args);
StateMachine.enterAnyState( fsm, name, from, to, args);
},
//===========================================================================
buildEvent: function(name, map) {
return function() {
var from = this.current;
var to = map[from] || map[StateMachine.WILDCARD] || from;
var args = Array.prototype.slice.call(arguments); // turn arguments into pure array
if (this.transition)
return this.error(name, from, to, args, StateMachine.Error.PENDING_TRANSITION, "event " + name + " inappropriate because previous transition did not complete");
if (this.cannot(name))
return this.error(name, from, to, args, StateMachine.Error.INVALID_TRANSITION, "event " + name + " inappropriate in current state " + this.current);
if (false === StateMachine.beforeEvent(this, name, from, to, args))
return StateMachine.Result.CANCELLED;
if (from === to) {
StateMachine.afterEvent(this, name, from, to, args);
return StateMachine.Result.NOTRANSITION;
}
// prepare a transition method for use EITHER lower down, or by caller if they want an async transition (indicated by an ASYNC return value from leaveState)
var fsm = this;
this.transition = function() {
fsm.transition = null; // this method should only ever be called once
fsm.current = to;
StateMachine.enterState( fsm, name, from, to, args);
StateMachine.changeState(fsm, name, from, to, args);
StateMachine.afterEvent( fsm, name, from, to, args);
return StateMachine.Result.SUCCEEDED;
};
this.transition.cancel = function() { // provide a way for caller to cancel async transition if desired (issue #22)
fsm.transition = null;
StateMachine.afterEvent(fsm, name, from, to, args);
}
var leave = StateMachine.leaveState(this, name, from, to, args);
if (false === leave) {
this.transition = null;
return StateMachine.Result.CANCELLED;
}
else if (StateMachine.ASYNC === leave) {
return StateMachine.Result.PENDING;
}
else {
if (this.transition) // need to check in case user manually called transition() but forgot to return StateMachine.ASYNC
return this.transition();
}
};
}
}; // StateMachine
//===========================================================================
if ("function" === typeof define) {
define(function(require) { return StateMachine; });
}
else {
window.StateMachine = StateMachine;
}
}(this));
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