pitaya-launcher/js/app.js

127 lines
2.8 KiB
JavaScript

(function(Papaye, window) {
"use strict";
// Load dependencies
var path = require('path');
var fs = require('fs');
var Handlebars = require('handlebars');
var cp = require("child_process");
var gui = require('nw.gui');
var minimist = require('minimist');
// Load templates
var itemsListTpl = Handlebars.compile(Papaye.DOM.select('#items-list-tpl').innerHTML);
// Internal constants
var DEFAULT_PROFILE = './default-profile.json';
/**
* Start the app
*
* @param rootEl The application root element selector
* @return Papaye
*/
Papaye.start = function(rootEl) {
Papaye._opts = minimist(gui.App.argv);
Papaye._rootEl = Papaye.DOM.select(rootEl);
Papaye._initListeners();
var profilePath = Papaye._opts.profile || DEFAULT_PROFILE;
return Papaye.loadProfile(profilePath)
.then(function() {
return Papaye;
})
;
};
/**
* Load a profile file and render the application
*
* @param profilePath The path of the profile file
* @return Promise
*/
Papaye.loadProfile = function(profilePath) {
return Papaye._loadJSONFile(profilePath)
.then(function(profile) {
Papaye._profile = profile;
Papaye.render();
return profile;
})
;
};
/**
* Update the application view
*
* @return Papaye
*/
Papaye.render = function() {
var rootEl = Papaye._rootEl;
var profile = Papaye._profile;
rootEl.innerHTML = itemsListTpl(profile);
};
/**
* Initialize DOM event listeners
* @private
*/
Papaye._initListeners = function() {
var rootEl = Papaye._rootEl;
rootEl.addEventListener('click', Papaye._onItemClick);
};
/**
* App item click handler
* @private
*/
Papaye._onItemClick = function(evt) {
var appItemEl = evt.srcElement.matches( '.app-item') ? evt.srcElement :
Papaye.DOM.getClosestAncestor(evt.srcElement, '.app-item')
;
if( !appItemEl ) return;
var execPath = appItemEl.dataset.exec;
console.info('Launching application "'+execPath+'"...');
if(execPath) {
appItemEl.classList.add('loading');
cp.exec(execPath, function(err) {
appItemEl.classList.remove('loading');
if(err) return console.error(err.stack || err);
console.info('Application closed "'+execPath+'".');
});
}
};
/**
* Load a JSON file
*
* @private
* @param filePath The path of the json file
* @return Promise
*/
Papaye._loadJSONFile = function(filePath) {
return new Promise(function(resolve, reject) {
fs.readFile(filePath, 'utf8', function(err, fileContent) {
if(err) return reject(err);
try {
var json = JSON.parse(fileContent);
return resolve(json);
} catch(err) {
return reject(err);
}
});
});
};
}(window.Papaye = window.Papaye || {}, window));