Commit bc0059f4 authored by Sven Franck's avatar Sven Franck

first promise generated gadget

parent 6a62e0bb
...@@ -1671,6 +1671,13 @@ ...@@ -1671,6 +1671,13 @@
}; };
erp5.map_portal_types = {
"app": "app",
"invoices": "invoices",
"invoices_01": "invoices_01",
"Sale Invoice Transaction": "invoices_fields"
};
erp5.action_handlers = { erp5.action_handlers = {
/** /**
...@@ -1692,68 +1699,30 @@ ...@@ -1692,68 +1699,30 @@
* @param {object} config JSON configuration of this gadget * @param {object} config JSON configuration of this gadget
* @returns {objects} fragment * @returns {objects} fragment
*/ */
constructListbox: function (config) { constructListbox: function (config, answer, field_definitions) {
var fragment_container, var fragment, bar, wrap, arr, local_popup, global_popup, set;
config,
bar,
wrap,
arr,
path,
split,
item,
reference,
local_popup,
global_popup,
field_definitions,
settings = config,
portal_type = settings ? settings.portal_type_title : undefined;
// extract reference (e.g. user) and item id from path
// TODO: refactor, user should be availabe from ??? cookie???
path = location.href.split("?");
if (path[1]) {
split = path[1].split("&");
if (split.length > 0) {
for (j = 0; j < split.length; j += 1) {
key = split[j].split("=");
switch (key[0]) {
case "r":
reference = key[1];
break;
case "i":
item = key[1]
break;
}
}
}
}
// retrieve and update field definitions for this portal_type if (config) {
console.log("constructListbox!"); fragment = window.document.createDocumentFragment();
console.log(settings); set = config.configuration;
if (settings) {
fragment_container = window.document.createDocumentFragment();
config = settings.configuration;
// add controlbar // add controlbar
if (config.controlbar.length > 0) { if (set.controlbar.length > 0) {
bar = factory.generateElement("div", {"className":"ui-controlbar"}); bar = factory.generateElement("div", {"className":"ui-controlbar"});
arr = factory.generateBar(config.controlbar); arr = factory.generateBar(set.controlbar);
bar.appendChild(arr[0]); bar.appendChild(arr[0]);
// TODO: improve, too much code, array pass-arounds // TODO: improve, too much code, array pass-arounds
global_popup = arr[1].global_popup; global_popup = arr[1].global_popup;
local_popup = arr[1].local_popup; local_popup = arr[1].local_popup;
fragment_container.appendChild(bar); fragment.appendChild(bar);
} }
// add wrapper // add wrapper
if (config.wrapper.length > 0) { if (set.wrapper.length > 0) {
arr = factory.generateBar(config.wrapper, true); arr = factory.generateBar(set.wrapper, true);
fragment_container.appendChild(arr[0]); fragment.appendChild(arr[0]);
// TODO: too much popup handling here // TODO: too much popup handling here
if (global_popup === undefined) { if (global_popup === undefined) {
...@@ -1769,7 +1738,7 @@ ...@@ -1769,7 +1738,7 @@
active_page = init.getActivePageId(); active_page = init.getActivePageId();
if (document.getElementById(active_page) if (document.getElementById(active_page)
.querySelectorAll("div.local_popup") === null) { .querySelectorAll("div.local_popup") === null) {
fragment_container.appendChild( fragment.appendChild(
factory.generatePopup(undefined, active_page) factory.generatePopup(undefined, active_page)
); );
} }
...@@ -1784,31 +1753,32 @@ ...@@ -1784,31 +1753,32 @@
// TODO: pre-enhance! // TODO: pre-enhance!
// table // table
settings.base_element.attributes["data-role"] = "table"; config.base_element.attributes["data-role"] = "table";
table = factory.generateElement( table = factory.generateElement(
settings.base_element.type, config.base_element.type,
settings.base_element.direct, config.base_element.direct,
settings.base_element.attributes, config.base_element.attributes,
settings.base_element.logic config.base_element.logic
); );
table.appendChild( table.appendChild(
factory.generateTableHeader(settings, portal_type, field_definitions) factory.generateTableHeader(config, field_definitions)
); );
table.appendChild(factory.generateTableBody(settings, answer, portal_type)); table.appendChild(
// table.appendChild(factory.generateTableFooter(settings, portal_type); factory.generateTableBody(config, answer)
);
// table.appendChild(factory.generateTableFooter(config, portal_type);
// done // done
fragment_container.appendChild( table ); fragment.appendChild(table);
if (settings.actions) { if (config.actions) {
for (l = 0; l < settings.actions.length; l += 1) { for (l = 0; l < config.actions.length; l += 1) {
fragment_container.appendChild(factory.generateControlgroup(settings.actions[l])); fragment.appendChild(
factory.generateControlgroup(config.actions[l])
);
} }
} }
return fragment;
// single element
return fragment_container;
} }
return factory.generateErrorMessage("Error. No configuration found", ""); return factory.generateErrorMessage("Error. No configuration found", "");
...@@ -1821,9 +1791,10 @@ ...@@ -1821,9 +1791,10 @@
var factory = {}; var factory = {};
/* ********************************************************************** */ /* ********************************************************************** */
/* "map to erp5" */ /* "mapping to erp5" */
/* ********************************************************************** */ /* ********************************************************************** */
factory.map_buttons = erp5.mapERP5_buttons; factory.map_buttons = erp5.mapERP5_buttons;
factory.map_dataTypes = erp5.map_portal_types;
factory.action_handlers = erp5.action_handlers; factory.action_handlers = erp5.action_handlers;
factory.gadget_handlers = erp5.gadget_handlers; factory.gadget_handlers = erp5.gadget_handlers;
...@@ -1916,10 +1887,10 @@ ...@@ -1916,10 +1887,10 @@
* Generates a table header based on configuration and portal_type * Generates a table header based on configuration and portal_type
* @method generateTableHeader * @method generateTableHeader
* @param {object} settings Configuration for table to create * @param {object} settings Configuration for table to create
* @param {string} portal_type The portal type for this element * @param {object} fields Field configurations for this portal Type
*/ */
// TODO: single row ok. multi row to make // TODO: single row ok. multi row to make
factory.generateTableHeader = function (settings, portal_type) { factory.generateTableHeader = function (settings, fields) {
var k, var k,
l, l,
cell, cell,
...@@ -1942,8 +1913,16 @@ ...@@ -1942,8 +1913,16 @@
cell = factory.generateElement("th",{},{},{}); cell = factory.generateElement("th",{},{},{});
config = { config = {
"type":"input", "type":"input",
"direct": {"id": portal_type + "_tick_all", "className": "action", "type":"checkbox"}, "direct": {
"attributes": {"type": "checkbox", "value": "Select All/Unselect All", "data-iconpos":"notext", "data-reference":"select_all"}, "id": settings.portal_type_title + "_tick_all",
"className": "action", "type":"checkbox"
},
"attributes": {
"type": "checkbox",
"value": "Select All/Unselect All",
"data-iconpos":"notext",
"data-reference":"select_all"
},
"logic": {} "logic": {}
} }
cell.appendChild(factory.generateFormElement(config, false, true)); cell.appendChild(factory.generateFormElement(config, false, true));
...@@ -1962,12 +1941,7 @@ ...@@ -1962,12 +1941,7 @@
field_config = {}; field_config = {};
if (field.show) { if (field.show) {
// fetch field_config. This should be loaded by now, because field_config = fields[settings[property]];
// we want to display a certain portal_type and to do so,
// we need all the field configurations associated with this
// portal_type config["data-i18n":
// TODO: field definitions?
//field_config = priv.field_definitions[portal_type][property];
if (field.merge === undefined) { if (field.merge === undefined) {
if (field_config) { if (field_config) {
...@@ -1991,7 +1965,10 @@ ...@@ -1991,7 +1965,10 @@
{"text": title } {"text": title }
); );
if (merger) { if (merger) {
row.insertBefore(cell, (set === undefined ? null : row.childNodes[check ? 1 : 0]) ); row.insertBefore(
cell,
(set === undefined ? null : row.childNodes[check ? 1 : 0])
);
set = true; set = true;
} else { } else {
row.appendChild(cell); row.appendChild(cell);
...@@ -2012,10 +1989,9 @@ ...@@ -2012,10 +1989,9 @@
* @method generateTableRow * @method generateTableRow
* @param {object} settings Configuration for table row to create * @param {object} settings Configuration for table row to create
* @param {object} item Data for this table row * @param {object} item Data for this table row
* @param {string} portal_type The portal type for the object displayed
* @returns table_row * @returns table_row
*/ */
factory.generateTableRow = function (settings, item, portal_type) { factory.generateTableRow = function (settings, item) {
var k, var k,
l, l,
i, i,
...@@ -2043,14 +2019,24 @@ ...@@ -2043,14 +2019,24 @@
cell.appendChild(factory.generateFormElement( cell.appendChild(factory.generateFormElement(
{ {
"type":"input", "type":"input",
"direct": {"id": item._id, "name":item._id, "className": "action", "type":"checkbox"}, "direct": {
"attributes": {"type": "checkbox", "value": "Select " + item.title, "data-iconpos":"notext", "data-reference":"select_item"}, "id": item._id,
"name":item._id,
"className": "action",
"type":"checkbox"
},
"attributes": {
"type": "checkbox",
"value": "Select " + item.title,
"data-iconpos":"notext",
"data-reference":"select_item"
},
"logic": {} "logic": {}
}, },
false, false,
true true
)); ));
row.appendChild( cell ); row.appendChild(cell);
} }
// reverse if mergable columns // reverse if mergable columns
...@@ -2067,7 +2053,7 @@ ...@@ -2067,7 +2053,7 @@
if (field.show) { if (field.show) {
if (field.merge === undefined) { if (field.merge === undefined) {
cell = factory.generateElement("td",{},{},{}); cell = factory.generateElement("td",{},{},{});
link = "object.html?type=" + portal_type + "&mode=edit" + "&item=" + item._id; link = "object.html?type=" + settings.portal_type_title + "&mode=edit" + "&item=" + item._id;
// TODO: crap...refactor whole section // TODO: crap...refactor whole section
// fetch non portal_type values // fetch non portal_type values
...@@ -2148,27 +2134,23 @@ ...@@ -2148,27 +2134,23 @@
* @method generateTableBody * @method generateTableBody
* @param {object} settings Configuration for table body to create * @param {object} settings Configuration for table body to create
* @param {object} answer from JIO * @param {object} answer from JIO
* @param {string} portal_type The portal type for this element
* @returns {object} table_body * @returns {object} table_body
*/ */
factory.generateTableBody = function (settings, answer, portal_type) { factory.generateTableBody = function (settings, answer) {
var l, var l,
row, row,
item, item,
property, property,
field, field,
error, error,
max,
table_body = factory.generateElement("tbody",{},{},{}); table_body = factory.generateElement("tbody",{},{},{});
// data
// TODO: we HACK
if (answer === undefined) {
// answer = priv.getFakeRecords[portal_type];
}
if (answer && answer.length > 0) { if (answer && answer.length > 0) {
for (l = 0; l < answer.length; l += 1) { max = settings.max_records || answer.length;
item = answer[l].doc; for (l = 0; l < max; l += 1) {
row = factory.generateTableRow(settings, item, portal_type); item = answer[l];
row = factory.generateTableRow(settings, item);
table_body.appendChild(row); table_body.appendChild(row);
} }
} else { } else {
...@@ -2466,7 +2448,7 @@ ...@@ -2466,7 +2448,7 @@
{ {
"className":"ui-footer " + "className":"ui-footer " +
(config.widget_class || " ") + (config.widget_class || " ") +
(config.fixed ? "ui-footer-fixed " : " ") + "slideup ui-bar-" + (config.fixed ? "ui-footer-fixed " : " ") + "slidedown ui-bar-" +
(config.theme || "inherit"), (config.theme || "inherit"),
}, },
{ {
...@@ -3289,251 +3271,6 @@ ...@@ -3289,251 +3271,6 @@
*/ */
init.storages; init.storages;
/**
* Get the active JQM page in JavaScript-only
* @method getActivePageId
* @return {string} id of active page
*/
init.getActivePageId = function () {
var i, kids = document.body.children;
for (i = 0; i < kids.length; i += 1) {
// this always tests the last page = active page
if (util.testForClass(kids[i].className, "ui-page")) {
return kids[i].id;
}
}
return undefined;
};
/**
* Get target element to append elements to
* @method getTargetElement
* @param {string} global Flag
* @return {object} HTML element
*/
init.getTargetElement = function (global) {
if (global) {
return document.body;
}
return document.getElementById(init.getActivePageId());
};
/**
* sets up JIO based on a loaded JSON "recipe"
* @method setupStorages
* @param {object} config Configuration for a storage to create
*/
init.setupStorages = function (config) {
var i, store, promises = [];
for (i = 0; i < config.length; i += 1) {
store = config[i].definition;
promises[i]
= init.storages[store.application_name]
= jIO.createJIO(store);
}
return RSVP.all(promises);
};
/**
* load files into JIO that are missing
* @method getFromDisk
* @param {object} storage JIO object
* @param {string} file Document title
* @param {string} attachment Attachment title
*/
init.getFromDisk = function (storage, file, attachment) {
var response, put, putAttachment;
put = function(e) {
response = e.target.response;
return storage.put({"_id": file});
};
putAttachment = function (e) {
return storage.putAttachment({
"_id": file,
"_attachment": attachment,
"_data": JSON.stringify(response),
"_mimetype": "application/json"
});
};
return jIO.util
.ajax({"url": "data/" + attachment + ".json", "dataType":'json'})
.then(put)
.then(putAttachment)
.then(function(){
// stored in JIO, continue
return response;
}
)
.fail(function(err){
document.getElementById(init.getActivePageId())
.getElementsByTagName("div")[0]
.appendChild(
util.generateErrorMessage("Error: Could not load data", "")
);
throw err;
});
};
/**
* Try fetching a configuration file (attachment) from storage. Fallback to
* file. Successfull fallback file fetches will be stored in JIO.
* @method fetchConfigurationFile
* @param {string} storage jIO instance to use
* @param {string} file Name of the file in question
* @param {string} attachment Name of the attachment to fetch
*/
// NOTE: assumes all files being loaded fully as text
init.fetchConfigurationFile = function (storage, file, attachment) {
var store = init.storages[storage];
return store.getAttachment({"_id": file, "_attachment": attachment})
.then(function (response) {
return jIO.util.readBlobAsText(response.data);
})
.then(
function (answer) {
return JSON.parse(answer.target.result);
},
function (error) {
if (error.status === 404 && error.id === file) {
return init.getFromDisk(store, file, attachment);
}
throw error;
}
);
};
/**
* Sets up a global application element
* @method setupGlobalElement
* @param {object} config JSON configuration
* @return {object} HTML fragment
*/
init.setupGobalElement = function (config) {
var target;
// TODO: all global... so... don't getTargetElement
switch (config.widget) {
case "header":
init.getTargetElement(config.global)
.appendChild(factory.generateHeader(config));
break;
case "footer":
init.getTargetElement(config.global)
.appendChild(factory.generateFooter(config));
break;
case "popup":
init.getTargetElement(config.global)
.appendChild(factory.generatePopup(config));
break;
case "panel":
init.getTargetElement(config.global)
.appendChild(factory.generatePanel(config));
break;
}
};
/**
* Iterates over the application configuration and generates the
* defined elements
* @method setupGlobalElements
* @param {object} config Application configuration
*/
init.setupGlobalElements = function (config) {
var i, target, element, promises = [];
target = document.getElementById(init.getActivePageId())
.getElementsByTagName("div")[0];
if (config && config.length) {
for (i = 0; i < config.length; i += 1) {
init.setupGobalElement(config[i]);
};
} else {
target.appendChild(util.generateErrorMessage("Error: No app data found", ""));
}
};
/**
* Setup element to display on the respective page being shown
* @method setupPageElements
* @param {object} config JSON config for this page
*/
init.setupPageElements = function (config) {
var i, header, active, method, pointer, gadgets, gadget;
active = document.getElementById(init.getActivePageId());
// set title
if (config.title) {
// WARNING: IE8- children() retrieves comments, too
header = document.getElementById("global_header") ||
active.children()[0];
if (util.testForClass(header.className, "ui-header")) {
title = header.getElementsByTagName("h1")[0];
title.innerHTML = config.title;
title.setAttribute("data-i18n", config.title_i18n);
}
}
// load gadgets on this page
// TODO: better way?
gadgets = active.querySelectorAll("[data-gadget]");
console.log("found gadgets");
console.log(gadgets);
for (i = 0; i < gadgets.length; i += 1) {
gadget = gadgets[i];
method = "construct" + util.capFirstLetter(
gadget.getAttribute("data-gadget")
);
pointer = factory.gadget_handlers[method];
if (pointer) {
// retrieve gadget info, store and return gadget
init.fetchConfigurationFile(
"settings",
"gadgets",
gadget.getAttribute("data-gadget-id"),
pointer
).always(function(fragment) {
console.log("gotcha");
console.log(fragment);
//$(gadget.parentNode).empty().append( fragment ).enhanceWithin();
});
} else {
active.getElementsByTagName("div")[0].appendChild(
util.generateErrorMessage(
"Error: Could not load config for " +
gadget.getAttribute("data-gadget") + ".", ""
)
);
}
}
};
/**
* Set the page currently being displayed
* @method setupPage
* @param {object} storage JIO
* @param {string} id Page id
*/
init.setupPage = function (storage, id) {
return init.fetchConfigurationFile(
storage, "pages", id
);
};
/* ====================================================================== */ /* ====================================================================== */
/* BINDINGS */ /* BINDINGS */
/* ====================================================================== */ /* ====================================================================== */
...@@ -3763,11 +3500,420 @@ ...@@ -3763,11 +3500,420 @@
// } // }
// }); // });
}; };
/* ====================================================================== */
/* METHODS */
/* ====================================================================== */
/** /**
* Set all application bindings * Get the active JQM page in JavaScript-only
* @method setGlobalBindings * @method getActivePageId
* @param {object} e Custom event object * @return {string} id of active page
*/
init.getActivePageId = function () {
var i, kid, kids = document.body.children;
// reverse, because in JQM last page is the active page!
for (i = kids.length-1; i >= 0 ; i -= 1) {
kid = kids[i];
if (kid.tagName === "DIV") {
if (util.testForClass(kids[i].className, "ui-page")) {
return kids[i].id;
}
}
}
return undefined;
};
/**
* Setup element to display on the respective page being shown
* @method setupPageElements
* @param {object} config JSON config for this page
*/
init.setupPageElements = function (config) {
var i,
header,
active,
method,
fetch,
query,
query_string,
query_limit,
path,
split,
key,
reference,
item,
gadgets,
gadget,
gadget_id,
gadget_config,
portal_type,
fields,
fragment;
active = document.getElementById(init.getActivePageId());
// set title
if (config.title) {
// WARNING: IE8- children() retrieves comments, too
header = document.getElementById("global_header") ||
active.children()[0];
if (util.testForClass(header.className, "ui-header")) {
title = header.getElementsByTagName("h1")[0];
title.innerHTML = config.title;
title.setAttribute("data-i18n", config.title_i18n);
}
}
// pick item id from URL
// TODO: refactor, reference is crap, wait until login works!
path = location.href.split("?");
if (path[1]) {
split = path[1].split("&");
if (split.length > 0) {
for (j = 0; j < split.length; j += 1) {
key = split[j].split("=");
switch (key[0]) {
case "r":
reference = key[1];
break;
case "i":
item = key[1]
break;
}
}
}
}
// fetch gadgets
// WARNING: slow & IE8 compliant?
gadgets = active.querySelectorAll("[data-gadget]");
// load gadgets
for (i = 0; i < gadgets.length; i += 1) {
gadget = gadgets[i];
gadget_id = gadget.getAttribute("data-gadget-id");
method = "construct" + util.capFirstLetter(
gadget.getAttribute("data-gadget")
);
// go fetching...
init.fetchConfiguration("settings", "gadgets", gadget_id)
.then(function (gadget_configuration) {
gadget_config = gadget_configuration;
portal_type = gadget_config.portal_type_source;
// build query object for later
query_string = '(portal_type:"% ' + portal_type + '")';
query_limit = gadget_config.max_records;
if (item) {
query_string += 'AND (id:"% ' + item + '")';
query_limit = 1;
}
query = {
query: query_string,
limit: [0, query_limit],
sort_on: [],
select_list:[],
wildcard_character: '%'
};
})
.then(function() {
return init.fetchConfiguration("settings", "portal_types", portal_type)
})
.then(function (field_definitions) {
fields = field_definitions;
})
// ==================================================
// TODO: remove this and all FakeData methods once ERP5 access is ok
// ==================================================
.then(init.testForFakeDump("items", portal_type))
.then(function(item_check) {
// while JIO returns undefined
if (item_check === undefined) {
fetch = true;
} else if (item_check.data.total_rows === 0) {
fetch = true;
}
})
.then(function() {
return init.fetchFakeData(gadget_id);
})
.then(function(fake_items) {
if (fetch) {
return init.dumpFakeData(fake_items, gadget_id, "items");
}
})
// ===============================================
.then(init.fetchData("items", query))
.then(function (items) {
fragment = factory.gadget_handlers[method](
gadget_config,
items,
fields
);
$(gadget.parentNode).empty().append( fragment ).enhanceWithin();
})
.fail(function(err) {
console.log(err);
active.getElementsByTagName("div")[0].appendChild(
util.generateErrorMessage(
"Error: Could not generate gadget " +
gadget.getAttribute("data-gadget") + ".", ""
)
);
});
}
};
/**
* sets up JIO based on a loaded JSON "recipe"
* @method setupStorages
* @param {object} config Configuration for a storage to create
*/
init.setupStorages = function (config) {
var i, store, promises = [];
for (i = 0; i < config.length; i += 1) {
store = config[i].definition;
promises[i]
= init.storages[store.application_name]
= jIO.createJIO(store);
}
return RSVP.all(promises);
};
/**
* load files into JIO that are missing
* @method getFromDisk
* @param {object} storage JIO object
* @param {string} file Document title
* @param {string} attachment Attachment title
*/
init.getFromDisk = function (storage, file, attachment) {
var response, url, put, putAttachment;
put = function(e) {
response = e.target.response;
return storage.put({"_id": file});
};
putAttachment = function (e) {
return storage.putAttachment({
"_id": file,
"_attachment": attachment,
"_data": JSON.stringify(response),
"_mimetype": "application/json"
});
};
url = "data/" + factory.map_dataTypes[attachment] + ".json";
return jIO.util
.ajax({"url": url, "dataType":'json'})
.then(put)
.then(putAttachment)
.then(function(){
// stored in JIO, continue
return response;
}
)
.fail(function(err){
document.getElementById(init.getActivePageId())
.getElementsByTagName("div")[0]
.appendChild(
util.generateErrorMessage("Error: Could not load data", "")
);
throw err;
});
};
/**
* Try fetching a configuration file (attachment) from storage. Fallback to
* file. Successfull fallback file fetches will be stored in JIO.
* @method fetchData
* @param {string} storage jIO instance to use
* @param {string} portal_type Portal type to fetch
* @param {object} query
* @returns {object} promise object
*/
// NOTE: until we have real data we load fake data on application init!
init.fetchData = function (storage, portal_type, query) {
var store = init.storages[storage];
console.log("calling allDocs, query");
console.log(query);
return store.allDocs(query)
.then(
function (response) {
return response;
},
function (err) {
return err;
}
);
};
/**
* Test dump for a portal_type to prevent re-dumping
* @method testForFakeDump
* @param {string} storage Storage to test
* @param {string} portal_type Portal Type to test for
*/
init.testForFakeDump = function (storage, portal_type) {
return init.fetchData(storage, {
query: '(portal_type:"% ' + portal_type + '")',
limit: [0, 1],
sort_on: [],
select_list: ['portal_type'],
wildcard_character: '%'
});
};
/**
* Create FAKE data entries in JIO
* @method dumpFakeData
* @param {array} dump Records to add
* @param {string} type Portal_type
* @param {string} store jIO instance to store
* @returns {object} promise object
*/
init.dumpFakeData = function (dump, type, storage) {
var i,
obj,
key,
store = init.storages[storage],
promises = [];
if (store && dump && dump.length) {
for (i = 0; i < dump.length; i += 1) {
record = dump[i];
obj = {};
for (key in record) {
if (record.hasOwnProperty(key)) {
obj[key] = record[key];
}
}
obj.portal_type = type;
promises[i] = store.post(obj);
}
return RSVP.all(promises);
} else {
// error
}
};
/**
* get fake data when a page is loaded
* @method fetchFakeData
* @param {id}
* @returns {object} promise object
*/
init.fetchFakeData = function (id) {
if (jIO) {
// hum
return jIO.util.ajax({
"url": "data/" + id + "_data.json", "dataType":"json"
}).then(
function(e) {
return e.target.response;
},
function(err){
document.getElementById(init.getActivePageId())
.getElementsByTagName("div")[0]
.appendChild(
util.generateErrorMessage("Error: Can't load data", "")
);
throw err;
});
} else {
// error
}
};
/**
* Try fetching a configuration file (attachment) from storage. Fallback to
* file. Successfull fallback file fetches will be stored in JIO.
* @method fetchConfiguration
* @param {string} storage jIO instance to use
* @param {string} file Name of the file in question
* @param {string} attachment Name of the attachment to fetch
*/
// NOTE: assumes all files being loaded fully as text
init.fetchConfiguration = function (storage, file, attachment) {
var store = init.storages[storage];
return store.getAttachment({"_id": file, "_attachment": attachment})
.then(function (response) {
return jIO.util.readBlobAsText(response.data);
})
.then(
function (answer) {
return JSON.parse(answer.target.result);
},
function (error) {
if (error.status === 404 && error.id === file) {
return init.getFromDisk(store, file, attachment);
}
throw error;
}
);
};
/**
* Sets up a global application element
* @method setupGlobalElement
* @param {object} config JSON configuration
* @return {object} HTML fragment
*/
init.setupGobalElement = function (config) {
switch (config.widget) {
case "header":
document.body.appendChild(factory.generateHeader(config));
break;
case "footer":
document.body.appendChild(factory.generateFooter(config));
break;
case "popup":
document.body.appendChild(factory.generatePopup(config));
break;
case "panel":
document.body.appendChild(factory.generatePanel(config));
break;
}
};
/**
* Iterates over the application configuration and generates the
* defined elements
* @method setupGlobalElements
* @param {object} config Application configuration
*/
init.setupGlobalElements = function (config) {
var i, target, element, promises = [];
target = document.getElementById(init.getActivePageId())
.getElementsByTagName("div")[0];
if (config && config.length) {
for (i = 0; i < config.length; i += 1) {
init.setupGobalElement(config[i]);
};
} else {
target.appendChild(util.generateErrorMessage("Error: No app data found", ""));
}
};
/**
* Set all application bindings
* @method setGlobalBindings
* @param {object} e Custom event object
*/ */
init.setGlobalBindings = function (e) { init.setGlobalBindings = function (e) {
...@@ -3844,6 +3990,15 @@ ...@@ -3844,6 +3990,15 @@
}; };
/**
* Set the page currently being displayed
* @method setupPage
* @param {object} storage JIO
* @param {string} id Page id
*/
init.setupPage = function (storage, id) {
return init.fetchConfiguration( storage, "pages", id);
};
/** /**
* fetch application configuration, store in JIO and setup application * fetch application configuration, store in JIO and setup application
...@@ -3863,7 +4018,7 @@ ...@@ -3863,7 +4018,7 @@
if (init.storages[attachment]) { if (init.storages[attachment]) {
return; return;
} else { } else {
// get storage definition and set up storages before continuing // actually this is the only case we end up at
return jIO.util.ajax({ return jIO.util.ajax({
"url": "data/" + attachment + ".json", "dataType":"json" "url": "data/" + attachment + ".json", "dataType":"json"
}) })
...@@ -3890,28 +4045,23 @@ ...@@ -3890,28 +4045,23 @@
* @method loadApplicationSettings * @method loadApplicationSettings
*/ */
init.loadApplicationSettings = function () { init.loadApplicationSettings = function () {
return init.fetchConfigurationFile("settings", "configuration", "app"); return init.fetchConfiguration("settings", "configuration", "app");
}; };
/** /**
* Run page "domino" * Run page "domino"
* @method runPageSetup * @method runPageSetup
* @param {string} storage Which storage to fetch the setup from
* @param {string} id Page id
*/ */
init.runPageSetup = function (storage, id) { init.runPageSetup = function (storage, id) {
return init.setupPage(storage, id)
init.setupPage(storage, id) .then(init.setupPageElements)
.then(function (page_config) { .then(init.setupPageBindings)
init.setupPageElements(page_config); .fail(function(err) {
}, function (err) { // error
throw err; console.log(err);
})
.then(function () {
init.setPageBindings();
}, function (err) {
throw err;
})
.fail(function (err) {
console.log(err)
}); });
}; };
...@@ -3933,31 +4083,17 @@ ...@@ -3933,31 +4083,17 @@
// setup application // setup application
init.runApplicationSetup("settings", "storages") init.runApplicationSetup("settings", "storages")
.then(init.loadApplicationSettings)
.then(init.setupGlobalElements)
.then(init.setGlobalBindings)
.then(function () { .then(function () {
return init.loadApplicationSettings() return init.runPageSetup("settings", e.target.id);
}, function (err) {
throw err;
})
.then(function (app_config) {
init.setupGlobalElements(app_config);
}, function (err) {
throw err;
})
.then(function () {
init.setGlobalBindings();
}, function (err) {
throw err;
})
.then(function () {
init.runPageSetup("settings", e.target.id);
}, function (err) {
throw err;
}) })
.fail(function (err) { .fail(function (err) {
console.log(err); console.log(err);
}); });
} else { } else {
init.runPageSetup("settings", e.target.id); return init.runPageSetup("settings", e.target.id);
} }
}); });
......
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