require(['diysdk.jquery'], function ($) {
var serializeDate = function(date) {
return date.date;
};
var webcomponentInstanceButtons = [
{
name: 'Edit View',
handler: function(wci) {
restUI.cleanUp();
restUI.viewWebcomponentInstance(wci, 'web', false, function() {
restUI.viewWebcomponentInstance(wci, 'edit', true);
});
}
},
{
name: 'Web Preview',
handler: function(wci) {
restUI.viewWebsitePreview(wci);
}
},
{
name: 'Delete',
handler: function(wci) {
restUI.deleteWebcomponentInstance(wci);
}
},
{
name: 'Clone',
handler: function(wci) {
restUI.cloneWebcomponentInstance(wci);
}
}
];
var appInstanceButtons = [
{
name: 'Show Metadata',
handler: function(appi){
restUI.showAppInstance(appi);
}
},
{
name: 'Delete',
handler: function(appi){
restUI.deleteAppInstance(appi);
}
}
];
var restUI = {
defaultUser : $('body').attr('data-defaultUser'),
settingsDefaults : {
'renderOption' : {
'width' : 550,
'upgradeable' : 1,
'packagetransition' : 'none'
}
},
currentWci : null,
hiddenColumns : {
'url' : true,
'dataEntity' : true,
'appName' : true,
'webcomponentName' : true
},
specialColumns : {
'createdAt' : serializeDate,
'modifiedAt' : serializeDate,
'deletedAt' : serializeDate
},
baseSaveUrl : '',
refreshListFunction : null,
init : function() {
// register button click events
$('button#apps').click(function() {
restUI.getAppsList();
});
$('button#webcomponentinstances').click(function() {
restUI.getWebcomponentInstances();
});
$('button#refresh').click(function() {
restUI.refreshList();
});
$('button#settings').click(function() {
restUI.openSettings();
});
$('button#resetSettings').click(function() {
restUI.resetSettings();
});
$('button#applySettings').click(function() {
restUI.applySettings();
});
restUI.loadSettings();
// read id from hash
var hash = window.location.hash;
if( hash.length > 1 ) {
var url = decodeURIComponent(hash.substring(1));
var appName = url.substring(url.indexOf(':')+1);
url = url.substring(0, url.indexOf(':'));
restUI.getWebcomponentInstance({ url: url, appName: appName });
} else {
restUI.getAppsList();
}
},
getAppsList : function() {
restUI.refreshListFunction = function() {
restUI.getAppsList();
};
restUI._ajax({
url: '/api/app/',
success: function(data) {
$('#output').empty();
restUI._getObjectAsTable(
data,
// on row click handler
function(app) {
restUI.getApp(app);
},
// special buttons for this row
[
{
name: function(app) {
return app.state === 'DISABLED' ? 'Enable' : 'Disable';
},
handler: function(app) {
restUI.updateApp(
app,
{state: (app.state === 'DISABLED' ? 'ENABLED' : 'DISABLED')}
);
}
},
{
name: 'Delete',
handler: restUI.deleteApp
},
{
name: 'Show instances',
handler: restUI.getAppInstances
}
]
).appendTo('#output');
$('#tablebuttons').empty();
restUI._button("Add App")
.click(function() {
restUI.createApp(
{
'name' : prompt("Please enter a name for your new App:", "")
}
);
})
.appendTo('#tablebuttons');
}
});
},
getApp : function(app) {
restUI.refreshListFunction = function() {
restUI.getApp(app);
};
restUI._ajax({
url: '/api/app/'+app.name+';'+app.version+'/wc',
success: function(data) {
$('#output').empty();
var success = function() {restUI.getApp(app);};
restUI._getObjectAsTable(data, //'restUI.getWebcomponent(this.id);');
function(wc) {
restUI.getWebcomponentInstances(wc);
},
[
{
name: function(wc) {
return wc.state === 'DISABLED' ? 'Enable' : 'Disable';
},
handler: function(wc) {
restUI.updateWebcomponent(
wc,
{state: (wc.state === 'DISABLED' ? 'ENABLED' : 'DISABLED')},
success
);
}
},
{
name: 'Edit',
handler: function(wc) {
restUI.editWebcomponent(wc, success);
}
},
{
name: 'Delete',
handler: function(wc) {
restUI.deleteWebcomponent(wc, success);
}
}
]
).appendTo('#output');
$('#tablebuttons').empty();
restUI._button('Add Webcomponent')
.click(function() {
restUI.addWebcomponent(app);
})
.appendTo('#tablebuttons');
}
});
},
addWebcomponent : function(app) {
var WebcomponentTitle = prompt("Please enter a name for your new Webcomponent:", "");
restUI.createWebcomponent(app,
{
'name' : WebcomponentTitle
}
);
},
getWebcomponent : function(wc) {
restUI.refreshListFunction = function() {
restUI.getWebcomponent(wc);
};
restUI._ajax({
url: '/api/app/'+wc.appName+';'+wc.appVersion+'/wc/'+wc.name,
success: function(data) {
$('#output').empty();
restUI._getObjectAsTable(data, function(wc) {
restUI.getWebcomponentInstances(wc);
})
.appendTo('#output');
$('#tablebuttons').empty();
restUI._button(data.state === 'DISABLED' ? 'Enable' : 'Disable')
.click(function() {
restUI.updateWebcomponent(wc, {state: (data.state === 'DISABLED' ? 'ENABLED' : 'DISABLED')});
})
.appendTo('#tablebuttons');
restUI._button('Edit')
.click(function() {
restUI.editWebcomponent(wc);
})
.appendTo('#tablebuttons');
restUI._button('Delete')
.click(function() {
restUI.deleteWebcomponent(wc);
})
.appendTo('#tablebuttons');
restUI._button('Create Instance')
.click(function() {
restUI.addWebcomponentInstance(wc);
})
.appendTo('#tablebuttons');
}
});
},
editWebcomponent : function(wc, success) {
restUI._ajax({
url: '/api/app/'+wc.appName+';'+wc.appVersion+'/wc/'+wc.name,
success: function(data) {
var webcomponentTitle = prompt("Please enter a new name for your Webcomponent:", data.name);
if (webcomponentTitle) {
restUI.updateWebcomponent(
wc,
{
'name' : webcomponentTitle
},
success
);
}
}
});
},
updateApp : function (app, dataSet, success) {
if (typeof dataSet !== 'undefined') {
restUI._ajax({
url: '/api/app/'+app.name+';'+app.version,
type : 'POST',
data: JSON.stringify(dataSet),
success: function(data) {
restUI.getAppsList(data);
}
});
} else {
console.log('Exception: No DataSet');
}
},
updateWebcomponent : function (wc, dataSet, success) {
if (typeof dataSet !== 'undefined') {
restUI._ajax({
url: '/api/app/'+wc.appName+';'+wc.appVersion+'/wc/'+wc.name,
type : 'POST',
data: JSON.stringify(dataSet),
success: success
});
} else {
console.log('Exception: No DataSet');
}
},
createApp : function(dataSet) {
if (typeof dataSet.name !== 'undefined' && dataSet.name !== null) {
restUI._ajax({
url: '/api/app',
type : 'POST',
data: JSON.stringify(dataSet),
success: function() {
restUI.getAppsList();
}
});
} else {
console.log('Exception: No component-title defined!');
}
},
deleteApp : function(app) {
restUI._ajax({
url: '/api/app/'+app.name+';'+app.version,
type : 'DELETE',
success: function() {
restUI.getAppsList();
}
});
},
createWebcomponent : function(app, dataSet) {
if (app && dataSet.name) {
restUI._ajax({
url: '/api/app/'+app.name+';'+app.version+'/wc',
type : 'POST',
data: JSON.stringify(dataSet),
success: function() {
restUI.getApp(app);
}
});
} else {
console.log('Exception: No component-title defined!');
}
},
deleteWebcomponent : function(wc, success) {
restUI._ajax({
url: '/api/app/'+wc.appName+';'+wc.appVersion+'/wc/'+wc.name,
type : 'DELETE',
success: success
});
},
/*
* Instances
*/
getAppInstances : function(app){
restUI.refreshListFunction = function() {
restUI.getAppInstances(app);
};
var appName = (typeof app === 'string') ? app : app.name;
restUI._ajax({
url: '/api/app/'+appName+'/instances',
success: function(data){
$('#output').empty();
restUI._getObjectAsTable(data, function(appi){}, appInstanceButtons)
.appendTo('#output');
$('#tablebuttons').empty();
restUI._button('Add new '+appName+' instance').click(function(){
restUI.createAppInstance(appName);
return false;
})
.appendTo('#tablebuttons');
}
});
},
createAppInstance: function(appName){
restUI._ajax({
type: 'POST',
url: '/api/app/'+appName+'/instances',
success: function(){
restUI.getAppInstances(appName);
}
});
},
showAppInstance : function(appi){
restUI.refreshListFunction = function() {
restUI.showAppInstance(appi);
};
var createKeyValueDiv = function(domain, key, value){
var div = $('
');
var keyValue = $(' :
');
var removeButton =
restUI._button('Remove', 'secondary')
.click(function(){
$(this).parent().remove();
return false;
});
div.append(keyValue).append(removeButton);
return div;
};
var createFieldSet = function(name, id, list){
var legend = $('');
var listDiv = $('').appendTo(legend);
if(list){
$.each(list, function(key, value){
var entryDiv = createKeyValueDiv(id, key, value);
listDiv.append(entryDiv);
});
}
var addButton =
$('')
.append(
restUI._button('Add new '+name, 'secondary')
.click(function(){
var newEntry = createKeyValueDiv(id,'','');
newEntry.insertBefore($(this));
return false;
})
)
.appendTo(listDiv);
return legend;
};
// create form
var metadataForm =
$('')
.append(createFieldSet('Features','features', appi.features))
.append(createFieldSet('Configuration','configuration', appi.configuration))
.append(createFieldSet('contractData','contractData', appi.contractData));
var metaData = {};
// create save button
var saveButton =
restUI._button('Save Metadata & Refresh')
.click(function(){
var formData = metadataForm.serializeArray();
for(var i = 0;i< formData.length; i=i+2){
var metaDataDomain = formData[i].name.split('-')[0];
if(metaData[metaDataDomain] == null || metaData[metaDataDomain] == undefined){
metaData[metaDataDomain] = {};
}
var metaDataKey = formData[i].value;
var metaDataValue = formData[i+1].value;
metaData[metaDataDomain][metaDataKey] = metaDataValue;
}
restUI.saveAppInstance(appi, metaData);
return false;
});
$('#instanceoutput').empty().append(metadataForm).append(saveButton).show();
},
saveAppInstance : function(appi, newData){
restUI._ajax({
type: 'POST',
url: '/api/'+appi.url,
data: JSON.stringify(newData),
contentType: 'application/json',
success: function(){
$('#instanceoutput').hide().empty();
restUI.getAppInstances(appi.component.replace('-',';'));
}
});
},
deleteAppInstance : function(appi){
console.log('Delete App instance ('+appi.id+')');
restUI._ajax({
type:'DELETE',
url: '/api/app/'+appi.component.replace('-',';')+'/instances/'+appi.id,
contentType: 'application/json',
success: function(){
$('#instanceoutput').hide().empty();
restUI.getAppInstances(appi.component.replace('-',';'));
}
});
},
getWebcomponentInstances : function(wc) {
restUI.refreshListFunction = function() {
restUI.getWebcomponentInstances(wc);
};
restUI._ajax({
url: wc ?
'/api/app/'+wc.appName+';'+wc.appVersion+'/wc/'+wc.name+'/instances' :
'/api/wci/',
success: function(data) {
$('#output').empty();
restUI._getObjectAsTable(data, function(wci) {
restUI.getWebcomponentInstance($.extend(wci, { appName: wci.appName }));
},
webcomponentInstanceButtons)
.appendTo('#output');
if (wc) {
$('#tablebuttons').empty();
restUI._button('Add ' + wc.name + ' instance')
.click(function() {
restUI.addWebcomponentInstance(wc);
})
.appendTo('#tablebuttons');
}
}
});
},
getWebcomponentInstance : function(wci) {
restUI.refreshListFunction = function() {
restUI.getWebcomponentInstance(wci);
};
restUI._ajax({
url: '/api/'+wci.url,
userName : wci.appName,
success: function(data) {
$('#output').empty();
restUI._getObjectAsTable(data, null, webcomponentInstanceButtons)
.appendTo('#output');
restUI.viewWebcomponentInstance(wci, 'web', false, function() {
restUI.viewWebcomponentInstance(wci, 'edit', true);
});
// update hash
window.location.hash = encodeURIComponent(wci.url + ":" + wci.appName);
}
});
},
viewWebsitePreview : function(wci){
var url = "/restui/preview/" + wci.id + '?' + $.param({
renderOption : this.settings.renderOption
});
window.open(url, "_blank");
return false;
},
viewWebcomponentInstance : function(wci, viewMode, append, success) {
this.currentWci = wci;
restUI._ajax({
hideInstanceOutput : false,
url: '/api/'+wci.url+'/view/'+viewMode,
data : {
renderOption : this.settings.renderOption
},
success: function(data) {
restUI._renderInstanceOutput(data, viewMode, append, success);
}
});
},
addWebcomponentInstance : function(wc) {
restUI._ajax({
url: '/api/app/'+wc.appName+';'+wc.appVersion+'/wc/'+wc.name+'/instances',
type : 'POST',
success: function() {
restUI.getWebcomponentInstances(wc);
}
});
},
editWebcomponentInstance : function(wci) {
console.log('edit instance '+wci.id);
},
deleteWebcomponentInstance : function(wci) {
if (typeof wci !== 'undefined') {
restUI._ajax({
url: '/api/'+wci.url,
type : 'DELETE',
success: function(data, result, transferObject) {
restUI.getWebcomponentInstances();
}
});
} else {
console.log('Exception: No Webcomponent Instance defined!');
}
},
cloneWebcomponentInstance : function(wci) {
if (typeof wci !== 'undefined') {
restUI._ajax({
url: '/api/'+wci.url+'/clone',
type : 'GET',
success: function(data, result, transferObject) {
restUI.getWebcomponentInstances();
}
});
} else {
console.log('Exception: No Webcomponent Instance defined!');
}
},
cleanUp : function() {
$.each(diysdk.webcomponents, function(i, wc) {
$.each(wc.views, function(j, view) {
if (typeof view.cleanUp === 'function') {
view.cleanUp();
}
});
});
},
refreshList : function() {
if (typeof restUI.refreshListFunction === "function") {
restUI.refreshListFunction();
}
},
loadSettings : function() {
this.settings = $.extend(true, {}, this.settingsDefaults);
$('#renderOptionsWidth').val(this.settings.renderOption.width);
},
openSettings : function() {
if(!this.settingsDialog) {
this.settingsDialog = $('#settingsDialog').diysdk_dialog({
title : 'Settings',
closeButton: true
});
} else {
this.settingsDialog.diysdk_dialog('open');
}
},
resetSettings : function() {
this.loadSettings();
},
applySettings : function() {
this.settings.renderOption.width = parseInt($('#renderOptionsWidth').val());
this.settingsDialog.diysdk_dialog('close');
this.reloadWci();
},
reloadWci : function() {
if(this.currentWci) {
this.cleanUp();
this.viewWebcomponentInstance(this.currentWci, 'web', false, $.proxy(function() {
this.viewWebcomponentInstance(this.currentWci, 'edit', true);
},this));
}
},
/*
* "private" methods
*/
_getObjectAsTable : function(object, rowClickAction, buttons) {
if (typeof object !== 'undefined' && object !== null) {
var table = $('');
var getTr = function(value, odd) {
var rowClickHandler = typeof rowClickAction === "function" ?
function() { rowClickAction(value); } :
null;
var tr = $(restUI._activeRow(value.id, null, odd));
$.each(value, function(indexindex, indexvalue) {
if (restUI.hiddenColumns[indexindex]) {
return;
} else if (indexvalue && typeof restUI.specialColumns[indexindex] === "function") {
indexvalue = restUI.specialColumns[indexindex](indexvalue);
}
var td = $(' | ');
if(typeof indexvalue !== 'object') {
td.text(indexvalue);
} else {
td.append(JSON.stringify(indexvalue));
}
td.click(rowClickHandler);
tr.append(td);
});
$.each(buttons, function(i, button) {
var text = typeof button.name === 'function' ?
button.name(value) : button.name;
var buttonAction = function() {
button.handler(value);
};
$(' | ').append(
restUI._button(text, 'secondary').click(buttonAction)
).appendTo(tr);
});
if (typeof rowClickHandler === "function") {
tr.addClass('clickable');
}
return tr;
};
var additionalColumns = $.isArray(buttons) ? buttons.length : 0;
if ($.isArray(object)) {
if (object.length > 0) {
table.append(restUI._tableHeader(object[0], additionalColumns));
$.each(object, function(index, value) {
var tr = getTr(value, (index % 2) === 1);
table.append(tr);
});
} else {
return $('no instances found
');
}
} else if (restUI._length(object) > 0) {
table.append(restUI._tableHeader(object, additionalColumns));
var tr = getTr(object);
table.append(tr);
}
return table;
}
return null;
},
_renderInstanceOutput : function(data, viewMode, append, success) {
if (!append) {
$('#instanceoutput').empty().show();
}
var viewJQ = $(data.html);
var editJQ = null;
var output = $('#instanceoutput');
if (viewMode === 'edit') {
editJQ = $(''
+ (data.instance.localizedName || '<Webcomponent Name>')
+ '
');
editJQ.find('.module_config_content')
.append(viewJQ);
editJQ.appendTo(output);
if (append) {
var contentJQ = $('#instanceoutput .module_content');
var overlay = $('');
contentJQ.wrap(overlay);
}
} else {
var mainJQ = $('')
.append(viewJQ);
mainJQ.appendTo(output);
}
var saveButton = null;
if (viewMode === 'edit') {
saveButton = restUI._button('Save');
saveButton.attr('id', 'modul_save_button');
var cancelButton = restUI._button('Cancel', 'secondary');
$('')
.append(saveButton)
.append(cancelButton)
.appendTo(editJQ.find('.module-config-outer-container'));
}
var instanceCreator = new diysdk.webcomponentIntegrator();
instanceCreator.create(data, this.baseSaveUrl, function(data, instance) {
if (saveButton) {
saveButton.click(function() { instance.saveEditData(); });
}
if (typeof success === "function") {
success();
}
});
var widgetiframe = $('.diysdk_ui_widgetiframe');
if (widgetiframe.length) {
widgetiframe.bind('load.restui', function() {
widgetiframe.outerHeight(true);
});
}
},
_tableHeader : function(fields, additionalColumns) {
var tableHeader = '';
$.each(fields, function(indexindex, indexvalue) {
if (!restUI.hiddenColumns[indexindex]) {
tableHeader += ''+indexindex+' | ';
}
});
for (var i = 0; i < additionalColumns; i++) {
tableHeader += ' | ';
}
tableHeader += '
';
return tableHeader;
},
_activeRow : function(id, rowClickAction, odd) {
var tr = $("
");
if (typeof rowClickAction === 'function') {
tr.click(rowClickAction);
}
if (typeof id !== 'undefined') {
tr.attr('id', id);
}
if (odd) {
tr.addClass('odd');
}
return tr;
},
_button : function(text, type) {
//type = type || 'primary';
var cssClasses = 'ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only';
if (type === 'secondary') {
cssClasses = 'button-cancel ' + cssClasses;
}
return $('');
},
_length : function (obj) {
var count = 0;
for (var i in obj) {
if (obj.hasOwnProperty(i)) {
count++;
}
}
return count;
},
/**
* Execute an AJAX request
* @param options : object {
* type : string - the HTTP type
* url : string - the url
* data : string - the data to send
* beforeSend : function - callback to execute before sending
* success : function - callback to execute on success
* error : function - callback to execute on error
* }
*/
_ajax : function(options) {
if (typeof options.hideInstanceOutput === 'undefined' ||
options.hideInstanceOutput === true)
{
// TODO clear hash when not in right context
// window.location.hash = "";
$('#instanceoutput').hide();
}
if(typeof(options.userName) != 'undefined') {
options.url = '/~' + options.userName + options.url;
} else {
if(this.defaultUser && this.defaultUser.length > 0)
options.url = '/~' + this.defaultUser + options.url;
}
var success = options.success;
var error = options.error;
$.ajax($.extend({
type: "GET",
dataType: 'json',
contentType: 'application/json',
beforeSend : function(xhr) {
xhr.setRequestHeader("Authorization","Basic c2l0ZWJ1aWxkZXI6c3lITFE1OExta2dOSjVNZA==");
}
}, options, {
success : function(data, result, transferObject) {
restUI._updateStatus(transferObject);
if (typeof success === "function") {
success(data, result, transferObject);
}
},
error: $.proxy(function(xhr, textStatus, errorThrown) {
restUI._ajaxError(xhr, textStatus, errorThrown);
if (typeof error === "function") {
error(xhr, textStatus, errorThrown);
}
}, this)
}));
},
/**
* Called if an ajax-error occurs - logs the error in console
*/
_ajaxError : function(xhr, textStatus, errorThrown)
{
restUI._updateStatus(xhr);
console.log("Ajax Error: " + textStatus);
try {
var json = $.parseJSON(xhr.responseText);
if (json) {
if (json.exception) {
console.log(json.exception);
}
if (json.message) {
alert(json.message);
}
}
} catch(ex) { }
if (errorThrown) {
console.log(errorThrown);
}
},
/**
* Update the status code
* @param transferObject XMLHttpRequest
*/
_updateStatus : function(transferObject)
{
var statusType = Math.floor(transferObject.status / 100);
$('#status').empty();
$('')
.css('color',
statusType === 2 ? '#0a0' :
statusType === 3 ? '#aa0' :
statusType === 4 || statusType === 5 ? '#f00' :
'#000'
)
.text(transferObject.status+' ('+transferObject.statusText+')')
.appendTo(
$('Status: ').appendTo('#status')
);
}
};
/*
* eventtrigger
*/
$(restUI.init);
});