spiritjs
Version:
The animation toolkit for the web
119 lines (115 loc) • 2.92 kB
JavaScript
;
exports.__esModule = true;
exports.create = create;
exports.load = load;
var _utils = require("../utils");
var _group = require("../group");
/**
* Create groups factory
*
* @return {{add: {function} add, groups: {array|Groups} groups}}
*/
function groupsFactory() {
var list = [];
var getGroupsByRoot = function getGroupsByRoot(root) {
for (var i = 0; i < list.length; i++) {
var groups = list[i];
if (groups.rootEl === root) {
return groups;
}
}
return null;
};
return {
add: function add(root, group) {
var groups = getGroupsByRoot(root);
if (!groups) {
groups = new _group.Groups(root, []);
list.push(groups);
}
if (group) {
group._list = groups;
group.resolve();
groups.add(group);
}
},
groups: function groups() {
return list.length === 1 ? list[0] : list;
}
};
}
/**
* Parse groups
*
* @param {object|Array} data animation data
* @param {Element} root the root element for animation groups
* @returns Groups
*/
function create(data, root) {
if (root === void 0) {
root = undefined;
}
if (!_utils.context.isBrowser()) {
throw new Error('Invalid context. spirit.create() can only be executed in the browser.');
}
var resolveRoot = false;
// ensure root element
if (!(root instanceof window.Element)) {
resolveRoot = true;
root = document.body || document.documentElement;
}
if (_utils.is.isObject(data) && data['groups'] && Array.isArray(data['groups'])) {
data = data['groups'];
}
if (!Array.isArray(data)) {
data = [data];
}
var factory = groupsFactory();
if (data.length === 0) {
factory.add(root, null);
}
data.forEach(function (g) {
var groupRoot = root;
if (resolveRoot && g.root) {
groupRoot = _utils.resolver.resolveElement(root, g.root);
if (!groupRoot) {
groupRoot = root;
}
}
var d = {
name: g.name,
timeScale: g.timeScale || 1,
timelines: []
};
var timelines = g.timelines || [];
timelines.forEach(function (timeline) {
d.timelines.push({
type: timeline.type,
props: timeline.props,
label: timeline.label || timeline.id || timeline.path,
path: timeline.path || null,
id: timeline.id || null
});
});
factory.add(groupRoot, new _group.Group(d));
});
return factory.groups();
}
/**
* Load data and apply it to element
*
* @param {string} url
* @param {Element} root
* @returns {Promise}
*/
function load(url, root) {
if (root === void 0) {
root = undefined;
}
if (!_utils.context.isBrowser()) {
return Promise.reject(new Error('Invalid context: spirit.load() can only be executed in the browser.'));
}
return (0, _utils.jsonloader)(url).then(function (data) {
return create(data, root);
});
}