<commit_before>/**
* Copyright (c) Microsoft.  All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*   http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

'use strict';

var utils = require('../../util/utils');
var serviceFabricUtils = require('./serviceFabricUtils');
var serviceFabricClient = require('azure-servicefabric');
var util = require('util');
var path = require('path');
var fs = require('fs');
var request = require('request');
var url = require('url');
var async = require('async');
var $ = utils.getLocaleString;

exports.init = function (cli) {
  var log = cli.output;

  var serviceFabric = cli.category('servicefabric')
    .description($('Commands to manage your Azure Service Fabric'));

  var application = serviceFabric.category('application')
    .description($('Commands to manage your application'));

  var applicationPackage = application.category('package')
    .description($('Commands to manage your application package'));

  // bug, applicationPackagePathInImageStore isn't used
  applicationPackage.command('copy [applicationPackagePath] [imageStoreConnectionString]')
    .description($('Copy application package, Example: azure servicefabric application package copy --application-package-path /tmp/package1 --image-store-connection-string fabric:ImageStore'))
    .option('-p --application-package-path <applicationPackagePath>', $('the path of the application package'))
    .option('-c --image-store-connection-string <imageStoreConnectionString>', $('the string of the image store connection'))
    .execute(function (applicationPackagePath, imageStoreConnectionString, options, _) {
      applicationPackagePath = cli.interaction.promptIfNotGiven($('applicationPackagePath:'), applicationPackagePath, _);
      imageStoreConnectionString = cli.interaction.promptIfNotGiven($('imageStoreConnectionString:'), imageStoreConnectionString, _);
      applicationPackagePath = path.resolve(applicationPackagePath);

      var progress = cli.interaction.progress($('Copy application package'));

      try {
        var config = serviceFabricUtils.readServiceFabricConfig(progress, _);

        var connectionUrl = serviceFabricUtils.createConnectionUrl(config, _);
        var clientOptions = serviceFabricUtils.getClientOptions(config, _).requestOptions;

        var files = serviceFabricUtils.walkDirTree(applicationPackagePath);
        var totalSize = 0;
        files.forEach_(_, function (_, file) {
          totalSize += file.size;
        });
        var isApplicationPackagePathDir = fs.statSync(applicationPackagePath).isDirectory();// Special case, applicationPackagePath is file
        var currentTotalSize = 0;
        var currentSize = 0;
        var currentFilesCount = 0;
        var res = async.eachSeries(files, function (file, callback) {
          var finalPath = url.resolve('/ImageStore/', (isApplicationPackagePathDir ? path.join(path.basename(applicationPackagePath), file.path) : file.path) + '?api-version=1.0');
          var finalUrl = url.resolve(connectionUrl, finalPath);
          clientOptions.url = finalUrl;
          clientOptions.headers = {
            'Content-Type': 'application/octet-stream'
          };
          var updateProgress = function () {
            progress.write(function () {}, util.format('[%d%%] %d/%d files, %d/%d bytes', Math.floor((currentTotalSize + currentSize) / totalSize * 100), currentFilesCount, files.length, currentTotalSize + currentSize, totalSize));
          };
          if (file.path.endsWith('_.dir')) {
            request.put(clientOptions, function () {
              currentFilesCount++;
              updateProgress();
              callback();
            });
          }
          else {
            var fullFilePath = isApplicationPackagePathDir ? path.join(applicationPackagePath, file.path) : path.join(path.dirname(applicationPackagePath), file.path);
            var readStream = fs.createReadStream(fullFilePath);
            var writeStream = readStream.pipe(request.put(clientOptions));
            var progressInterval = setInterval(function () {
              if (!writeStream.req || !writeStream.req.connection || !writeStream.req.connection._bytesDispatched) {
                return;
              }
              currentSize = writeStream.req.connection._bytesDispatched;
              updateProgress();
            }, 100);
            writeStream.on('end', function () {
              currentSize = 0;
              currentTotalSize += file.size;
              currentFilesCount++;
              clearInterval(progressInterval);
              updateProgress();
              callback();
            });
            writeStream.on('error', function (err) {
              callback(err);
            });
          }
        }, _);

        progress.end();

        cli.interaction.formatOutput(res, function (data) {
          log.json(data);
        });
      } catch (e) {
        progress.end();
        throw e;
      }
    });

  var code = serviceFabric.category('code')
    .description($('Commands to manage your code'));

  var codePackage = code.category('package')
    .description($('Commands to manage your code package'));

  var codePackageDeployed = codePackage.category('deployed')
    .description($('Commands to manage your deployed code package'));

  codePackageDeployed.command('show [nodeName] [applicationName]')
    .description($('Show deployed application health'))
    .option('-n --node-name <nodeName>', $('the name of the node'))
    .option('-a --application-name <applicationName>', $('the name of the application'))
    .option('--select <fields>', $('select fields to show, call without this parameter to see all fields'))
    .execute(function (nodeName, applicationName, options, _) {
      var progress = cli.interaction.progress($('Show deployed code package'));

      try {
        var config = serviceFabricUtils.readServiceFabricConfig(progress, _);

        var client = new serviceFabricClient('3.0-preview', serviceFabricUtils.createConnectionUrl(config, _), serviceFabricUtils.getClientOptions(config, _));
        applicationName = serviceFabricUtils.parseUrl(applicationName, _);
        var res = client.deployedCodePackages.get(nodeName, applicationName, options, _);
        if (options.select) {
          res = serviceFabricUtils.pick(res, options.select, _);
        }
        serviceFabricUtils.setPackageEnumVal(res);

        progress.end();

        cli.interaction.formatOutput(res, function (data) {
          log.json(data);
        });
      } catch (e) {
        progress.end();
        throw e;
      }
    });

  var service = serviceFabric.category('service')
    .description($('Commands to manage your service'));

  var servicePackage = service.category('package')
    .description($('Commands to send your service package'));

  var servicePackageDeployed = servicePackage.category('deployed')
    .description($('Commands to send your deployed service package'));

  servicePackageDeployed.command('show [nodeName] [applicationName]')
    .description($('Show deployed service package'))
    .option('-n --node-name <nodeName>', $('the name of the node'))
    .option('-a --application-name <applicationName>', $('the name of the application'))
    .option('--select <fields>', $('select fields to show, call without this parameter to see all fields'))
    .execute(function (nodeName, applicationName, options, _) {
      var progress = cli.interaction.progress($('Show deployed service package'));

      try {
        var config = serviceFabricUtils.readServiceFabricConfig(progress, _);

        var client = new serviceFabricClient('3.0-preview', serviceFabricUtils.createConnectionUrl(config, _), serviceFabricUtils.getClientOptions(config, _));
        applicationName = serviceFabricUtils.parseUrl(applicationName, _);
        var res = client.deployedServicePackages.get(nodeName, applicationName, options, _);
        if (options.select) {
          res = serviceFabricUtils.pick(res, options.select, _);
        }
        serviceFabricUtils.setPackageEnumVal(res);

        progress.end();

        cli.interaction.formatOutput(res, function (data) {
          log.json(data);
        });
      } catch (e) {
        progress.end();
        throw e;
      }
    });

  var servicePackageDeployedHealth  = servicePackageDeployed.category('health')
    .description($('Commands to manage your deployed service package health'));

  servicePackageDeployedHealth.command('show [nodeName] [applicationName] [servicePackageName]')
    .description($('Show deployed service package health'))
    .option('-n --node-name <nodeName>', $('the name of the node'))
    .option('-a --application-name <applicationName>', $('the name of the application'))
    .option('-p --service-package-name <servicePackageName>', $('the name of the service package'))
    .option('-f --events-health-state-filter <eventsHealthStateFilter>', $('the filter of the events health state, values are [Default|None|Ok|Warning|Error|All]'))
    .option('--select <fields>', $('select fields to show, call without this parameter to see all fields'))
    .execute(function (nodeName, applicationName, servicePackageName, options, _) {
      var progress = cli.interaction.progress($('Show deployed service package'));

      try {
        var config = serviceFabricUtils.readServiceFabricConfig(progress, _);

        var client = new serviceFabricClient('3.0-preview', serviceFabricUtils.createConnectionUrl(config, _), serviceFabricUtils.getClientOptions(config, _));
        applicationName = serviceFabricUtils.parseUrl(applicationName, _);
        if (servicePackageName) options.servicePackageName = servicePackageName;
        var res = client.deployedServicePackageHealths.get(nodeName, applicationName, options, _);
        if (options.select) {
          res = serviceFabricUtils.pick(res, options.select, _);
        }
        serviceFabricUtils.setPackageEnumVal(res);

        progress.end();

        cli.interaction.formatOutput(res, function (data) {
          log.json(data);
        });
      } catch (e) {
        progress.end();
        throw e;
      }
    });

  servicePackageDeployedHealth.command('send [nodeName] [applicationName] [serviceManifestName] [sourceId] [property] [healthState]')
    .description($('Send deployed service package health, Example: azure servicefabric application health send --node-name node1 fabric:app --source-id monitor --property pc --health-state Ok --description healthy'))
    .option('-n --node-name <nodeName>', $('the name of the node'))
    .option('-a --application-name <applicationName>', $('the name of the application'))
    .option('-m --service-manifest-name <serviceManifestName>', $('the name of the service manifest'))
    .option('-i --source-id <sourceId>', $('the id of the source'))
    .option('-p --property <property>', $('the property'))
    .option('-e --health-state <healthState>', $('the state of the health, values are [Ok|Warning|Error|Unknown]'))
    .option('-d --description <description>', $('the description'))
    .option('-l --time-to-live-in-milliseconds <timeToLiveInMilliseconds>', $('the time in milliseconds for live'))
    .option('-q --sequence-number <sequenceNumber>', $('the number of the sequence'))
    .option('-w --remove-when-expired', $('the boolean of the remove when expired'))
    .execute(function (nodeName, applicationName, serviceManifestName, sourceId, property, healthState, options, _) {
      var progress = cli.interaction.progress($('Send deployed service package health'));

      try {
        var config = serviceFabricUtils.readServiceFabricConfig(progress, _);
        var client = new serviceFabricClient('3.0-preview', serviceFabricUtils.createConnectionUrl(config, _), serviceFabricUtils.getClientOptions(config, _));
        applicationName = serviceFabricUtils.parseUrl(applicationName, _);
        var applicationHealthReport = {};
        if (sourceId) applicationHealthReport.sourceId = sourceId;
        if (property) applicationHealthReport.property = property;
        if (healthState) applicationHealthReport.healthState = serviceFabricUtils.getEnumVal('healthState', healthState);
        if (options.description) applicationHealthReport.description = options.description;
        if (options.timeToLiveInMilliseconds) applicationHealthReport.timeToLiveInMilliSeconds = options.timeToLiveInMilliseconds;
        if (options.sequenceNumber) applicationHealthReport.sequenceNumber = options.sequenceNumber;
        if (options.removeWhenExpired) {
          applicationHealthReport.removeWhenExpired = true;
        }
        var res = client.deployedServicePackageHealths.send(nodeName, applicationName, serviceManifestName, applicationHealthReport, options, _);
        serviceFabricUtils.setPackageEnumVal(res);

        progress.end();

        cli.interaction.formatOutput(res, function (data) {
          log.json(data);
        });
      } catch (e) {
        progress.end();
        throw e;
      }
    });
};
<commit_msg>Service fabric app package copy to use persist connection<commit_after>/**
* Copyright (c) Microsoft.  All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*   http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

'use strict';

var utils = require('../../util/utils');
var serviceFabricUtils = require('./serviceFabricUtils');
var serviceFabricClient = require('azure-servicefabric');
var util = require('util');
var path = require('path');
var fs = require('fs');
var request = require('request');
var url = require('url');
var async = require('async');
var $ = utils.getLocaleString;

exports.init = function (cli) {
  var log = cli.output;

  var serviceFabric = cli.category('servicefabric')
    .description($('Commands to manage your Azure Service Fabric'));

  var application = serviceFabric.category('application')
    .description($('Commands to manage your application'));

  var applicationPackage = application.category('package')
    .description($('Commands to manage your application package'));

  // bug, applicationPackagePathInImageStore isn't used
  applicationPackage.command('copy [applicationPackagePath] [imageStoreConnectionString]')
    .description($('Copy application package, Example: azure servicefabric application package copy --application-package-path /tmp/package1 --image-store-connection-string fabric:ImageStore'))
    .option('-p --application-package-path <applicationPackagePath>', $('the path of the application package'))
    .option('-c --image-store-connection-string <imageStoreConnectionString>', $('the string of the image store connection'))
    .execute(function (applicationPackagePath, imageStoreConnectionString, options, _) {
      applicationPackagePath = cli.interaction.promptIfNotGiven($('applicationPackagePath:'), applicationPackagePath, _);
      imageStoreConnectionString = cli.interaction.promptIfNotGiven($('imageStoreConnectionString:'), imageStoreConnectionString, _);
      applicationPackagePath = path.resolve(applicationPackagePath);

      var progress = cli.interaction.progress($('Copy application package'));

      try {
        var config = serviceFabricUtils.readServiceFabricConfig(progress, _);

        var connectionUrl = serviceFabricUtils.createConnectionUrl(config, _);
        var clientOptions = serviceFabricUtils.getClientOptions(config, _).requestOptions;

        var files = serviceFabricUtils.walkDirTree(applicationPackagePath);
        var totalSize = 0;
        files.forEach_(_, function (_, file) {
          totalSize += file.size;
        });
        var isApplicationPackagePathDir = fs.statSync(applicationPackagePath).isDirectory();// Special case, applicationPackagePath is file
        var currentTotalSize = 0;
        var currentSize = 0;
        var currentFilesCount = 0;
        var res = async.eachSeries(files, function (file, callback) {
          var finalPath = url.resolve('/ImageStore/', (isApplicationPackagePathDir ? path.join(path.basename(applicationPackagePath), file.path) : file.path) + '?api-version=1.0');
          var finalUrl = url.resolve(connectionUrl, finalPath);
          clientOptions.url = finalUrl;
          clientOptions.headers = {
            'Content-Type': 'application/octet-stream'
          };
          clientOptions.forever = true;
          var updateProgress = function () {
            progress.write(function () {}, util.format('[%d%%] %d/%d files, %d/%d KBs', Math.floor((currentTotalSize + currentSize) / totalSize * 100), currentFilesCount, files.length, Math.round((currentTotalSize + currentSize) / 1024), Math.round(totalSize /1024)));
          };
          if (file.path.endsWith('_.dir')) {
            request.put(clientOptions, function () {
              currentFilesCount++;
              updateProgress();
              callback();
            });
          }
          else {
            var fullFilePath = isApplicationPackagePathDir ? path.join(applicationPackagePath, file.path) : path.join(path.dirname(applicationPackagePath), file.path);
            var readStream = fs.createReadStream(fullFilePath);
            var writeStream = readStream.pipe(request.put(clientOptions));
            var progressInterval = setInterval(function () {
              if (!writeStream.req || !writeStream.req.connection || !writeStream.req.connection._bytesDispatched) {
                return;
              }
              currentSize = writeStream.req.connection._bytesDispatched - currentTotalSize;
              updateProgress();
            }, 100);
            writeStream.on('end', function () {
              currentSize = writeStream.req.connection._bytesDispatched - currentTotalSize;
              var bytesDiff = currentSize - file.size;
              totalSize += bytesDiff;
              currentSize = 0;
              currentTotalSize = writeStream.req.connection._bytesDispatched;
              currentFilesCount++;
              clearInterval(progressInterval);
              updateProgress();
              callback();
            });
            writeStream.on('error', function (err) {
              callback(err);
            });
          }
        }, _);

        progress.end();

        cli.interaction.formatOutput(res, function (data) {
          log.json(data);
        });
      } catch (e) {
        progress.end();
        throw e;
      }
    });

  var code = serviceFabric.category('code')
    .description($('Commands to manage your code'));

  var codePackage = code.category('package')
    .description($('Commands to manage your code package'));

  var codePackageDeployed = codePackage.category('deployed')
    .description($('Commands to manage your deployed code package'));

  codePackageDeployed.command('show [nodeName] [applicationName]')
    .description($('Show deployed application health'))
    .option('-n --node-name <nodeName>', $('the name of the node'))
    .option('-a --application-name <applicationName>', $('the name of the application'))
    .option('--select <fields>', $('select fields to show, call without this parameter to see all fields'))
    .execute(function (nodeName, applicationName, options, _) {
      var progress = cli.interaction.progress($('Show deployed code package'));

      try {
        var config = serviceFabricUtils.readServiceFabricConfig(progress, _);

        var client = new serviceFabricClient('3.0-preview', serviceFabricUtils.createConnectionUrl(config, _), serviceFabricUtils.getClientOptions(config, _));
        applicationName = serviceFabricUtils.parseUrl(applicationName, _);
        var res = client.deployedCodePackages.get(nodeName, applicationName, options, _);
        if (options.select) {
          res = serviceFabricUtils.pick(res, options.select, _);
        }
        serviceFabricUtils.setPackageEnumVal(res);

        progress.end();

        cli.interaction.formatOutput(res, function (data) {
          log.json(data);
        });
      } catch (e) {
        progress.end();
        throw e;
      }
    });

  var service = serviceFabric.category('service')
    .description($('Commands to manage your service'));

  var servicePackage = service.category('package')
    .description($('Commands to send your service package'));

  var servicePackageDeployed = servicePackage.category('deployed')
    .description($('Commands to send your deployed service package'));

  servicePackageDeployed.command('show [nodeName] [applicationName]')
    .description($('Show deployed service package'))
    .option('-n --node-name <nodeName>', $('the name of the node'))
    .option('-a --application-name <applicationName>', $('the name of the application'))
    .option('--select <fields>', $('select fields to show, call without this parameter to see all fields'))
    .execute(function (nodeName, applicationName, options, _) {
      var progress = cli.interaction.progress($('Show deployed service package'));

      try {
        var config = serviceFabricUtils.readServiceFabricConfig(progress, _);

        var client = new serviceFabricClient('3.0-preview', serviceFabricUtils.createConnectionUrl(config, _), serviceFabricUtils.getClientOptions(config, _));
        applicationName = serviceFabricUtils.parseUrl(applicationName, _);
        var res = client.deployedServicePackages.get(nodeName, applicationName, options, _);
        if (options.select) {
          res = serviceFabricUtils.pick(res, options.select, _);
        }
        serviceFabricUtils.setPackageEnumVal(res);

        progress.end();

        cli.interaction.formatOutput(res, function (data) {
          log.json(data);
        });
      } catch (e) {
        progress.end();
        throw e;
      }
    });

  var servicePackageDeployedHealth  = servicePackageDeployed.category('health')
    .description($('Commands to manage your deployed service package health'));

  servicePackageDeployedHealth.command('show [nodeName] [applicationName] [servicePackageName]')
    .description($('Show deployed service package health'))
    .option('-n --node-name <nodeName>', $('the name of the node'))
    .option('-a --application-name <applicationName>', $('the name of the application'))
    .option('-p --service-package-name <servicePackageName>', $('the name of the service package'))
    .option('-f --events-health-state-filter <eventsHealthStateFilter>', $('the filter of the events health state, values are [Default|None|Ok|Warning|Error|All]'))
    .option('--select <fields>', $('select fields to show, call without this parameter to see all fields'))
    .execute(function (nodeName, applicationName, servicePackageName, options, _) {
      var progress = cli.interaction.progress($('Show deployed service package'));

      try {
        var config = serviceFabricUtils.readServiceFabricConfig(progress, _);

        var client = new serviceFabricClient('3.0-preview', serviceFabricUtils.createConnectionUrl(config, _), serviceFabricUtils.getClientOptions(config, _));
        applicationName = serviceFabricUtils.parseUrl(applicationName, _);
        if (servicePackageName) options.servicePackageName = servicePackageName;
        var res = client.deployedServicePackageHealths.get(nodeName, applicationName, options, _);
        if (options.select) {
          res = serviceFabricUtils.pick(res, options.select, _);
        }
        serviceFabricUtils.setPackageEnumVal(res);

        progress.end();

        cli.interaction.formatOutput(res, function (data) {
          log.json(data);
        });
      } catch (e) {
        progress.end();
        throw e;
      }
    });

  servicePackageDeployedHealth.command('send [nodeName] [applicationName] [serviceManifestName] [sourceId] [property] [healthState]')
    .description($('Send deployed service package health, Example: azure servicefabric application health send --node-name node1 fabric:app --source-id monitor --property pc --health-state Ok --description healthy'))
    .option('-n --node-name <nodeName>', $('the name of the node'))
    .option('-a --application-name <applicationName>', $('the name of the application'))
    .option('-m --service-manifest-name <serviceManifestName>', $('the name of the service manifest'))
    .option('-i --source-id <sourceId>', $('the id of the source'))
    .option('-p --property <property>', $('the property'))
    .option('-e --health-state <healthState>', $('the state of the health, values are [Ok|Warning|Error|Unknown]'))
    .option('-d --description <description>', $('the description'))
    .option('-l --time-to-live-in-milliseconds <timeToLiveInMilliseconds>', $('the time in milliseconds for live'))
    .option('-q --sequence-number <sequenceNumber>', $('the number of the sequence'))
    .option('-w --remove-when-expired', $('the boolean of the remove when expired'))
    .execute(function (nodeName, applicationName, serviceManifestName, sourceId, property, healthState, options, _) {
      var progress = cli.interaction.progress($('Send deployed service package health'));

      try {
        var config = serviceFabricUtils.readServiceFabricConfig(progress, _);
        var client = new serviceFabricClient('3.0-preview', serviceFabricUtils.createConnectionUrl(config, _), serviceFabricUtils.getClientOptions(config, _));
        applicationName = serviceFabricUtils.parseUrl(applicationName, _);
        var applicationHealthReport = {};
        if (sourceId) applicationHealthReport.sourceId = sourceId;
        if (property) applicationHealthReport.property = property;
        if (healthState) applicationHealthReport.healthState = serviceFabricUtils.getEnumVal('healthState', healthState);
        if (options.description) applicationHealthReport.description = options.description;
        if (options.timeToLiveInMilliseconds) applicationHealthReport.timeToLiveInMilliSeconds = options.timeToLiveInMilliseconds;
        if (options.sequenceNumber) applicationHealthReport.sequenceNumber = options.sequenceNumber;
        if (options.removeWhenExpired) {
          applicationHealthReport.removeWhenExpired = true;
        }
        var res = client.deployedServicePackageHealths.send(nodeName, applicationName, serviceManifestName, applicationHealthReport, options, _);
        serviceFabricUtils.setPackageEnumVal(res);

        progress.end();

        cli.interaction.formatOutput(res, function (data) {
          log.json(data);
        });
      } catch (e) {
        progress.end();
        throw e;
      }
    });
};
<|endoftext|>


<commit_before>/**
 * Welcome to Pebble.js!
 *
 * This is where you write your app.
 */

var UI = require('ui');
var Vector2 = require('vector2');

var main = new UI.Card({
  title: 'tile5',
  icon: 'images/menu_icon.png',
  subtitle: 'True time tower defense',
  body: 'Press any button.'
});

main.show();

main.on('click', 'up', function(e) {
  var menu = new UI.Menu({
    sections: [{
      items: [{
        title: 'Pebble.js',
        icon: 'images/menu_icon.png',
        subtitle: 'Can do Menus'
      }, {
        title: 'Second Item',
        subtitle: 'Subtitle Text'
      }]
    }]
  });
  menu.on('select', function(e) {
    console.log('Selected item #' + e.itemIndex + ' of section #' + e.sectionIndex);
    console.log('The item is titled "' + e.item.title + '"');
  });
  menu.show();
});

main.on('click', 'select', function(e) {
  var wind = new UI.Window();
  var textfield = new UI.Text({
    position: new Vector2(0, 50),
    size: new Vector2(144, 30),
    font: 'gothic-24-bold',
    text: 'Text Anywhere!',
    textAlign: 'center'
  });
  wind.add(textfield);
  wind.show();
});

main.on('click', 'down', function(e) {
  var card = new UI.Card();
  card.title('A Card');
  card.subtitle('Is a Window');
  card.body('The simplest window type in Pebble.js.');
  card.show();
});
<commit_msg>Middle button is menu<commit_after>/**
 * Welcome to Pebble.js!
 *
 * This is where you write your app.
 */

var UI = require('ui');
var Vector2 = require('vector2');

var main = new UI.Card({
  title: 'tile5',
  icon: 'images/menu_icon.png',
  subtitle: 'True time tower defense',
  body: 'Press any button.'
});

main.show();

/*main.on('click', 'up', function(e) {
  var menu = new UI.Menu({
    sections: [{
      items: [{
        title: 'Pebble.js',
        icon: 'images/menu_icon.png',
        subtitle: 'Can do Menus'
      }, {
        title: 'Second Item',
        subtitle: 'Subtitle Text'
      }]
    }]
  });
  menu.on('select', function(e) {
    console.log('Selected item #' + e.itemIndex + ' of section #' + e.sectionIndex);
    console.log('The item is titled "' + e.item.title + '"');
  });
  menu.show();
});

main.on('click', 'select', function(e) {
  var wind = new UI.Window();
  var textfield = new UI.Text({
    position: new Vector2(0, 50),
    size: new Vector2(144, 30),
    font: 'gothic-24-bold',
    text: 'Text Anywhere!',
    textAlign: 'center'
  });
  wind.add(textfield);
  wind.show();
});

main.on('click', 'down', function(e) {
  var card = new UI.Card();
  card.title('A Card');
  card.subtitle('Is a Window');
  card.body('The simplest window type in Pebble.js.');
  card.show();
});*/

main.on('click', 'select', function(e) {
  var menu = new UI.Menu({
    sections: [{
      items: [{
        title: 'Pebble.js',
        icon: 'images/menu_icon.png',
        subtitle: 'Can do Menus'
      }, {
        title: 'Second Item',
        subtitle: 'Subtitle Text'
      }]
    }]
  });
  menu.on('select', function(e) {
    console.log('Selected item #' + e.itemIndex + ' of section #' + e.sectionIndex);
    console.log('The item is titled "' + e.item.title + '"');
  });
  menu.show();
});<|endoftext|>


<commit_before>
console.log("your mom")
console.log("zzz")

// global variables galore
var current_tab = null;
var interestContext = null;
var ChartObject = null;

// week select function
function week_select (e) {
    e.preventDefault()
    // generate graph data here
    var computed_data = []
    // need to calculate how far back to look
    // get current date and subtract 7 days (604800000 ms)
    var today = new Date();
    var today_ms = Date.parse(today); // get today in ms since sometime in 1970
    var past_ms = today_ms - 604800000;
    var past = new Date(past_ms);
    // based on currently selected tab, selector is going to vary
    var data_pointer = null;
    if(current_tab == "spending") {
        items.find({date_acquired: {$gte: past}})
    } else if (current_tab == "stock") {

    } else if (current_tab == "waste") {

    } else {
        alert("error! error! D: wahhh")
    }

    var data = {
        labels : ["6 days","5 days","4 days","3 days","2 days","1 day","today"],
        datasets : [
        {
            fillColor : "rgba(151,187,205,0.5)",
            strokeColor : "rgba(151,187,205,1)",
            pointColor : "rgba(151,187,205,1)",
            pointStrokeColor : "#fff",
            data : computed_data
        }
        ]
    }

    $("#chart").attr('width', '300px');
    $("#chart").attr('height', '300px');

    ChartObject.Line(data);

    $("#spendingLabel").html("Spent $43");
    $("#stockLabel").html("Had 17 items");
    $("#wasteLabel").html("Lost $43");
    $("#dropdown_title").html("Past week");

}

$(document).ready(function () {
    console.log("got here")

    console.log($("#chart"))
    console.log($("#chart").get(0))

    interestContext = $("#chart").get(0).getContext("2d");
    ChartObject = new Chart(interestContext);

    // all the odds and ends
	var dropdown = $("#timeSelectDropdown");
	$("#timeSelectDropdownMenu").offset({left: dropdown.offset().left});
    $('#timeOptions li').on('click', function() {
        $('#dropdown_title').html("Last ".concat($(this).find('a').html()));
    });
    $("#chart").attr('width', '300px');
    $("#chart").attr('height', '300px');

    // code for handling tab switches
    // needs to call timeframe select method upon switch
    $('#spending').click(function (e) {
    	e.preventDefault()
        current_tab = "spending"
    	$(this).tab('show')
    })
    $('#stock').click(function (e) {
    	e.preventDefault()
        current_tab = "stock"
    	$(this).tab('show')
    })
    $('#waste').click(function (e) {
    	e.preventDefault()
        current_tab = "waste"
    	$(this).tab('show')
    })
    $('#weekSelect').click()
    $('#monthSelect').click(function (e) {
    	e.preventDefault()
        // generate graph data here
        var data = {
        	labels : ["1 month","3 weeks","2 weeks","1 week","today"],
        	datasets : [
        	{
        		fillColor : "rgba(151,187,205,0.5)",
        		strokeColor : "rgba(151,187,205,1)",
        		pointColor : "rgba(151,187,205,1)",
        		pointStrokeColor : "#fff",
        		data : [80,50,23,11,43]
        	}
        	]
        }
        ChartObject.Line(data);

        $("#spendingLabel").html("Spent $163");
        $("#stockLabel").html("Had 33 items");
        $("#wasteLabel").html("Lost $45");
        $("#dropdown_title").html("Past month");
    })
    $('#threeMonthSelect').click(function (e) {
    	e.preventDefault()
        // generate graph data here
        var data = {
        	labels : ["3 months","2 months","1 month","today"],
        	datasets : [
        	{
        		fillColor : "rgba(151,187,205,0.5)",
        		strokeColor : "rgba(151,187,205,1)",
        		pointColor : "rgba(151,187,205,1)",
        		pointStrokeColor : "#fff",
        		data : [80,70,95,44,12]
        	}
        	]
        }
        ChartObject.Line(data);

        $("#spendingLabel").html("Spent $344");
        $("#stockLabel").html("Had 65 items");
        $("#wasteLabel").html("Lost $99");
        $("#dropdown_title").html("Past 3 months");
    })

    ChartObject.Line(data);

    $("#spendingLabel").html("Spent $43")
    $("#stockLabel").html("Had 17 items")
    $("#wasteLabel").html("Lost $43")
    $("#dropdown_title").html("Past week");
});<commit_msg>Makes javascript wait to run until HTML is loaded<commit_after>
console.log("your mom")
console.log("zzz")

// global variables galore
var current_tab = null;
var interestContext = null;
var ChartObject = null;

// week select function
function week_select (e) {
    e.preventDefault()
    // generate graph data here
    var computed_data = []
    // need to calculate how far back to look
    // get current date and subtract 7 days (604800000 ms)
    var today = new Date();
    var today_ms = Date.parse(today); // get today in ms since sometime in 1970
    var past_ms = today_ms - 604800000;
    var past = new Date(past_ms);
    // based on currently selected tab, selector is going to vary
    var data_pointer = null;
    if(current_tab == "spending") {
        items.find({date_acquired: {$gte: past}})
    } else if (current_tab == "stock") {

    } else if (current_tab == "waste") {

    } else {
        alert("error! error! D: wahhh")
    }

    var data = {
        labels : ["6 days","5 days","4 days","3 days","2 days","1 day","today"],
        datasets : [
        {
            fillColor : "rgba(151,187,205,0.5)",
            strokeColor : "rgba(151,187,205,1)",
            pointColor : "rgba(151,187,205,1)",
            pointStrokeColor : "#fff",
            data : computed_data
        }
        ]
    }

    $("#chart").attr('width', '300px');
    $("#chart").attr('height', '300px');

    ChartObject.Line(data);

    $("#spendingLabel").html("Spent $43");
    $("#stockLabel").html("Had 17 items");
    $("#wasteLabel").html("Lost $43");
    $("#dropdown_title").html("Past week");

}

//$(document).ready(function () {
Template.trends.rendered = function () {
    console.log("got here")

    console.log($("#chart"))
    console.log($("#chart").get(0))

    interestContext = $("#chart").get(0).getContext("2d");
    ChartObject = new Chart(interestContext);

    // all the odds and ends
	var dropdown = $("#timeSelectDropdown");
	$("#timeSelectDropdownMenu").offset({left: dropdown.offset().left});
    $('#timeOptions li').on('click', function() {
        $('#dropdown_title').html("Last ".concat($(this).find('a').html()));
    });
    $("#chart").attr('width', '300px');
    $("#chart").attr('height', '300px');

    // code for handling tab switches
    // needs to call timeframe select method upon switch
    $('#spending').click(function (e) {
    	e.preventDefault()
        current_tab = "spending"
    	$(this).tab('show')
    })
    $('#stock').click(function (e) {
    	e.preventDefault()
        current_tab = "stock"
    	$(this).tab('show')
    })
    $('#waste').click(function (e) {
    	e.preventDefault()
        current_tab = "waste"
    	$(this).tab('show')
    })
    $('#weekSelect').click()
    $('#monthSelect').click(function (e) {
    	e.preventDefault()
        // generate graph data here
        var data = {
        	labels : ["1 month","3 weeks","2 weeks","1 week","today"],
        	datasets : [
        	{
        		fillColor : "rgba(151,187,205,0.5)",
        		strokeColor : "rgba(151,187,205,1)",
        		pointColor : "rgba(151,187,205,1)",
        		pointStrokeColor : "#fff",
        		data : [80,50,23,11,43]
        	}
        	]
        }
        ChartObject.Line(data);

        $("#spendingLabel").html("Spent $163");
        $("#stockLabel").html("Had 33 items");
        $("#wasteLabel").html("Lost $45");
        $("#dropdown_title").html("Past month");
    })
    $('#threeMonthSelect').click(function (e) {
    	e.preventDefault()
        // generate graph data here
        var data = {
        	labels : ["3 months","2 months","1 month","today"],
        	datasets : [
        	{
        		fillColor : "rgba(151,187,205,0.5)",
        		strokeColor : "rgba(151,187,205,1)",
        		pointColor : "rgba(151,187,205,1)",
        		pointStrokeColor : "#fff",
        		data : [80,70,95,44,12]
        	}
        	]
        }
        ChartObject.Line(data);

        $("#spendingLabel").html("Spent $344");
        $("#stockLabel").html("Had 65 items");
        $("#wasteLabel").html("Lost $99");
        $("#dropdown_title").html("Past 3 months");
    })

    ChartObject.Line(data);

    $("#spendingLabel").html("Spent $43")
    $("#stockLabel").html("Had 17 items")
    $("#wasteLabel").html("Lost $43")
    $("#dropdown_title").html("Past week");
};<|endoftext|>


<commit_before>import React, { PropTypes } from 'react';
import { Link } from 'react-router';

class Header extends React.Component {
  static propTypes = {
    isLoggedIn: PropTypes.bool.isRequired,
    logoutUser: PropTypes.func.isRequired,
    user: PropTypes.object,
    isMusician: PropTypes.bool.isRequired
  };

  render() {
    const loggedIn = (

        Hello, <Link to={this.props.isMusician ? '/musicianProfile' : 'organizerProfile'}>{this.props.user.email}</Link>
        {' '}
        <button className="button" onClick={this.props.logoutUser}>Log out</button>

    );
    const loggedOut = (
      <Link className="button" to="/login">Log in</Link>
    );
    return (

          <Link to={this.props.isLoggedIn ? '/events' : '/'}></Link>

          {this.props.isLoggedIn ? loggedIn : loggedOut}

    );
  }
}

export default Header;
<commit_msg>fixed typo so orgprofile is now absolute linl<commit_after>import React, { PropTypes } from 'react';
import { Link } from 'react-router';

class Header extends React.Component {
  static propTypes = {
    isLoggedIn: PropTypes.bool.isRequired,
    logoutUser: PropTypes.func.isRequired,
    user: PropTypes.object,
    isMusician: PropTypes.bool.isRequired
  };

  render() {
    const loggedIn = (

        Hello, <Link to={this.props.isMusician ? '/musicianProfile' : '/organizerProfile'}>{this.props.user.email}</Link>
        {' '}
        <button className="button" onClick={this.props.logoutUser}>Log out</button>

    );
    const loggedOut = (
      <Link className="button" to="/login">Log in</Link>
    );
    return (

          <Link to={this.props.isLoggedIn ? '/events' : '/'}></Link>

          {this.props.isLoggedIn ? loggedIn : loggedOut}

    );
  }
}

export default Header;
<|endoftext|>


<commit_before>define(['jquery', 'libs/finderSelect/jquery.finderSelect.min'], function($){
  console.log('table')
  $.widget("ui.table", {
    options: {
      url: null,
      checkbox: true,
      columns:[],
      /** Tipo de vistas, inline, agrega el formulario abajo de la vista */
      type:'default',
      pagination: {
        'total':0,
        'per_page':15,
        'current_page':1,
        'last_page':0,
        'from':0,
        'to':0
      }
    },

    _create: function() {
      var self = this;

      self.element.append(
          self._createControlsHeader(),
          self._createTable(),
          self._createForm()
        );
      self._buildPage();

      self.tHead.find("input[type='checkbox']").change(function () {
        if ($(this).is(':checked')) {
          self.tBody.finderSelect('highlightAll');
        } else {
          self.tBody.finderSelect('unHighlightAll');
        }
      });

      if(self.options.collection) {
        self.options.collection.on('add', function(aModel) {
          self._addRow(aModel.attributes);
          self._updateUI();
        })
        self.options.collection.on('change', function(aModel)  {
          self._addRow(aModel.attributes);
          self._updateUI();
        })
      }
    },

    _createControlsHeader: function() {
      var self = this, controls = $('
', {'class':'controlsheader'}), btnNew, btnRemove, list = $('
');

      btnNew = $('', {'class': 'btn btn-primary btn-mini btn-new', href:self.options.btnNew}).html('New');
      btnRemove = $('<button/>', {'class': 'btn btn-primary btn-mini btn-trash'}).hide().html('Send Selected to Trash');
      console.debug(self.options.type)
      if(self.options.type != 'inline')
        list.append($('
').append(btnNew));
      list.append($('
').append(btnRemove));

      btnRemove.on('click', function(){self._removeAllSelected()});

      self.controlsHeader = controls.append(list);
      return controls;
    },

    _createTable: function() {
      this.tBody = this._createTableBody();
      return $('
', {'class':'table table-condensed'}).append(this._createTableHeader(), this.tBody);
    },

    _createForm: function() {
      var self = this;
      if(self.options.type != 'inline')
        return null;

      $form = $('
');
      var containerButton = $('
', {'class':'containerButtonAdd'}).append(
        $('<button/>', {'class': 'btn btn-default btn-sm'}).html('Add...').on('click', function(){
          self._open();
        })
      );
      $form.append(
        containerButton
      );
      /*
      require(['views/forms/inlineForm', 'Vm'], function(BasicForm, Vm){
        var aModel = aModelEdit || new self.options.collection.model();
        var detailForm = Vm.create(appView, (aModelEdit ? 'editDetailForm' : 'detailForm'), BasicForm, {model:aModel, collection: self.options.collection});
        if(!aModelEdit) {
          var detailFormContainer = $('
').append(detailForm.render()).hide();
          var containerButton = $('
', {'class':'containerButtonAdd'}).append(
                  $('<button/>', {'class': 'btn btn-default btn-sm'}).html('Add ' + aModel.label).on('click', function(){
                    detailFormContainer.show();
                    containerButton.hide();
                  })
                );
          $form.append(
              containerButton,
              detailFormContainer
            );
        } else {
          $form.append(detailForm.render());
          detailForm.hideButtons();
        }
      })*/

      return $form;
    },

    _createTableHeader: function() {
      var tHead = $('
'), columns = this.options.columns, myTR = $('
');
      if(this.options.checkbox) {
        myTR.append($('', {'class':'checked'}).append($('<input/>', {type:'checkbox'})));
      }
      if(this.options.sortable) {
        myTR.append($('', {'class':'handle'}));
      }
      for(var i=0; i<columns.length; i++) {
        myTR.append($('').html(columns[i].label));
      }
      this.tHead = tHead;
      return tHead.append(myTR);
    },

    _createTableBody: function() {
      return $('
');
    },

    _buildPage: function() {
      var self = this;
      if(self.options.url) {
        $.ajax({url:self.options.url, data:{}}).then(function(res){
          self._onAfterCreatePage();
        }, function(res) {

        });
      } else {
        if(self.options.data) {
          for(var i = 0; i<self.options.data.length; i++) {
            self._addRow(self.options.data[i]);
          }
        } else if (self.options.collection) {
          self.options.collection.forEach(function(aModel) {
            self._addRow(aModel.toJSON());
          })
        }
        self._onAfterCreatePage();
      }
    },

    _addRow: function(row) {
      var self = this, myTR = self.tBody.find('TR[data-id="'+ row.id +'"]'), columns = self.options.columns, myTD, bEdit = false, sValue;

      if(myTR.length == 0) {
        myTR = $("
");
      } else {
        myTR.empty();
        bEdit = true;
      }
      myTR.attr('id', 'item_' + row.id);
      myTR.data('id', row.id).attr('data-id', row.id);
      if(self.options.checkbox) {
        myTR.append('<input type="checkbox" />	');
      }
      if(self.options.sortable) {
        myTR.append('	');
      }
      for(var i = 0; i<columns.length; i++) {
        myTD = $('');
        sValue = row[columns[i].name];
        if($.isPlainObject(sValue)) {
          for(var key in sValue) break;
          sValue = sValue[key];
        }
        switch(columns[i].type) {
          case 'link':
            myTD.html($('', {href:sValue}).html(columns[i].label)).addClass('safezone link');
            break;
          default:
            myTD.append($('', {'class':'safezone open'}).html(sValue));
        }
        myTR.append(myTD);
      }
      myTR.find(".safezone").on("click", function(e){
        return false;
      });
      myTR.find('.handle').on('mouseenter', function(e) {
         return false;
      })
      myTR.find('.safezone.open').on('click', function(e) {
        self._open(row.id);
      })
      myTR.find('.safezone.link').on('click', function(e) {
        var sUrl = $(this).find('a').attr('href');
        if(sUrl)
          Backbone.history.navigate(sUrl, { trigger : true });
      })
      if(!bEdit)
        self.tBody.append(myTR);
    },

    _open: function(id) {
      var self = this, aModel, bisEdit = false;

      if(!id) {
        aModel = new self.options.collection.model();
        aModel.set('sortableKey', self.options.collection.length);
      } else {
        aModel = self.options.collection.get(id);
        bisEdit = true;
      }

      require(['views/modal/basicModal', 'views/forms/inlineForm', 'vm'], function(BasicModal, BasicForm, Vm){
        var detailForm = Vm.create(appView, (bisEdit ? 'editDetailForm' : 'detailForm'), BasicForm, {model:aModel, collection: (bisEdit ? null : self.options.collection)});
        var $form = detailForm.render()
        detailForm.hideButtons();
        var aModal = Vm.create(appView, 'modal', BasicModal, {modalTitle: (bisEdit ? 'Edit...' : 'Add'), callback: function(){
          if(detailForm.submit()) {
            $modal.modal('hide')/*.remove();
            aModal.remove();*/
          }
        }});
        var $modal = aModal.render();
        $modal.find('.modal-body').append($form);
        $('body').append($modal);
      })
    },

    _removeAllSelected: function() {
      var self = this;
      this.tBody.find("input[type='checkbox']:checked").parents('TR').each(function(i, element) {
        var aId = $(element).data('id'),
        aModel = self.options.collection.get(aId);
        self.options.collection.remove(aModel);
        aModel.destroy();
        $(element).remove();
      })
      if(this.tBody.find("input[type='checkbox']").length == 0) {
        this.controlsHeader.find('.btn-trash').hide();
        this.tHead.find("input[type='checkbox']").prop('checked', false);
      }
      this._updateUI();
    },

    _onAfterCreatePage: function() {
      this._updateUI();
    },

    _updateUI: function() {
      var self = this;
      if(this.tBody.find('tr').not('.nodata').length) {
        if (!this.tBody.hasClass('finderSelect')) {
          this.tBody.addClass('finderSelect');
          this.tBody.finderSelect({enableDesktopCtrlDefault:true, dragEvent:'', event:'click'});
          self.tBody.finderSelect('addHook','highlight:before', function(el) {
            el.find('input').prop('checked', true);
            !el.length || self.controlsHeader.find('.btn-trash').show();
          });
          self.tBody.finderSelect('addHook','unHighlight:before', function(el) {
            el.find('input').prop('checked', false);
            if(self.tBody.find("input[type='checkbox']:checked").length==0) {
              self.tHead.find("input[type='checkbox']").prop('checked', false);
              self.controlsHeader.find('.btn-trash').hide();
            }
          });
          self.tBody.on("click", ":checkbox", function(e){
            //e.preventDefault();
          });
        } else {
          this.tBody.finderSelect('update');
        }

        this.tBody.find('.nodata').remove();

        if(self.options.sortable) {
          self.tBody.sortable({ handle: ".handle .fa-sort", axis: "y", forceHelperSize: true, forcePlaceholderSize: true, opacity: 0.5, cursor: "move" });
          self.tBody.sortable({
            update: function( event, ui ) {
              var res = self.tBody.sortable( "toArray", { attribute: "data-id"/*, expression: /(.+)[_=-](.+)/*/ } )
              for(var i = 0; i < res.length; i++) {
                var aModel = self.options.collection.get(res[i]);
                if(aModel) {
                  aModel.set('sortableKey', i);
                }
              }
            }
          });
        }
      } else {
        if(!this.tBody.find('.nodata').length)
          this.tBody.append('
No se encontraron datos
')
      }
    },

    myPublicFunction: function() {
    },
    destroy: function() {}
  });
})<commit_msg>Correccion al agregar un nuevo registro de detalle.<commit_after>define(['jquery', 'libs/finderSelect/jquery.finderSelect.min'], function($){
  console.log('table')
  $.widget("ui.table", {
    options: {
      url: null,
      checkbox: true,
      columns:[],
      /** Tipo de vistas, inline, agrega el formulario abajo de la vista */
      type:'default',
      pagination: {
        'total':0,
        'per_page':15,
        'current_page':1,
        'last_page':0,
        'from':0,
        'to':0
      }
    },

    _create: function() {
      var self = this;

      self.element.append(
          self._createControlsHeader(),
          self._createTable(),
          self._createForm()
        );
      self._buildPage();

      self.tHead.find("input[type='checkbox']").change(function () {
        if ($(this).is(':checked')) {
          self.tBody.finderSelect('highlightAll');
        } else {
          self.tBody.finderSelect('unHighlightAll');
        }
      });

      if(self.options.collection) {
        self.options.collection.on('add', function(aModel) {
          self._addRow(aModel.attributes);
          self._updateUI();
        })
        self.options.collection.on('change', function(aModel)  {
          if(aModel.previous('id') < 0 && aModel.id > 0) {
            self._addRow(aModel.attributes, aModel.previous('id'));
          } else {
            self._addRow(aModel.attributes);
          }
          self._updateUI();
        })
      }
    },

    _createControlsHeader: function() {
      var self = this, controls = $('
', {'class':'controlsheader'}), btnNew, btnRemove, list = $('
');

      btnNew = $('', {'class': 'btn btn-primary btn-mini btn-new', href:self.options.btnNew}).html('New');
      btnRemove = $('<button/>', {'class': 'btn btn-primary btn-mini btn-trash'}).hide().html('Send Selected to Trash');
      console.debug(self.options.type)
      if(self.options.type != 'inline')
        list.append($('
').append(btnNew));
      list.append($('
').append(btnRemove));

      btnRemove.on('click', function(){self._removeAllSelected()});

      self.controlsHeader = controls.append(list);
      return controls;
    },

    _createTable: function() {
      this.tBody = this._createTableBody();
      return $('
', {'class':'table table-condensed'}).append(this._createTableHeader(), this.tBody);
    },

    _createForm: function() {
      var self = this;
      if(self.options.type != 'inline')
        return null;

      $form = $('
');
      var containerButton = $('
', {'class':'containerButtonAdd'}).append(
        $('<button/>', {'class': 'btn btn-default btn-sm'}).html('Add...').on('click', function(){
          self._open();
        })
      );
      $form.append(
        containerButton
      );
      /*
      require(['views/forms/inlineForm', 'Vm'], function(BasicForm, Vm){
        var aModel = aModelEdit || new self.options.collection.model();
        var detailForm = Vm.create(appView, (aModelEdit ? 'editDetailForm' : 'detailForm'), BasicForm, {model:aModel, collection: self.options.collection});
        if(!aModelEdit) {
          var detailFormContainer = $('
').append(detailForm.render()).hide();
          var containerButton = $('
', {'class':'containerButtonAdd'}).append(
                  $('<button/>', {'class': 'btn btn-default btn-sm'}).html('Add ' + aModel.label).on('click', function(){
                    detailFormContainer.show();
                    containerButton.hide();
                  })
                );
          $form.append(
              containerButton,
              detailFormContainer
            );
        } else {
          $form.append(detailForm.render());
          detailForm.hideButtons();
        }
      })*/

      return $form;
    },

    _createTableHeader: function() {
      var tHead = $('
'), columns = this.options.columns, myTR = $('
');
      if(this.options.checkbox) {
        myTR.append($('', {'class':'checked'}).append($('<input/>', {type:'checkbox'})));
      }
      if(this.options.sortable) {
        myTR.append($('', {'class':'handle'}));
      }
      for(var i=0; i<columns.length; i++) {
        myTR.append($('').html(columns[i].label));
      }
      this.tHead = tHead;
      return tHead.append(myTR);
    },

    _createTableBody: function() {
      return $('
');
    },

    _buildPage: function() {
      var self = this;
      if(self.options.url) {
        $.ajax({url:self.options.url, data:{}}).then(function(res){
          self._onAfterCreatePage();
        }, function(res) {

        });
      } else {
        if(self.options.data) {
          for(var i = 0; i<self.options.data.length; i++) {
            self._addRow(self.options.data[i]);
          }
        } else if (self.options.collection) {
          self.options.collection.forEach(function(aModel) {
            self._addRow(aModel.toJSON());
          })
        }
        self._onAfterCreatePage();
      }
    },

    _addRow: function(row, previusId) {
      var self = this, myTR = self.tBody.find('TR[data-id="'+ row.id +'"]'), columns = self.options.columns, myTD, bEdit = false, sValue;
      if(previusId) {
        myTR = self.tBody.find('TR[data-id="'+ previusId +'"]');
      }
      if(myTR.length == 0) {
        myTR = $("
");
      } else {
        myTR.empty();
        bEdit = true;
      }
      myTR.attr('id', 'item_' + row.id);
      myTR.data('id', row.id).attr('data-id', row.id);
      if(self.options.checkbox) {
        myTR.append('<input type="checkbox" />	');
      }
      if(self.options.sortable) {
        myTR.append('	');
      }
      for(var i = 0; i<columns.length; i++) {
        myTD = $('');
        sValue = row[columns[i].name];
        if($.isPlainObject(sValue)) {
          for(var key in sValue) break;
          sValue = sValue[key];
        }
        switch(columns[i].type) {
          case 'link':
            myTD.html($('', {href:sValue}).html(columns[i].label)).addClass('safezone link');
            break;
          default:
            myTD.append($('', {'class':'safezone open'}).html(sValue));
        }
        myTR.append(myTD);
      }
      myTR.find(".safezone").on("click", function(e){
        return false;
      });
      myTR.find('.handle').on('mouseenter', function(e) {
         return false;
      })
      myTR.find('.safezone.open').on('click', function(e) {
        self._open(row.id);
      })
      myTR.find('.safezone.link').on('click', function(e) {
        var sUrl = $(this).find('a').attr('href');
        if(sUrl)
          Backbone.history.navigate(sUrl, { trigger : true });
      })
      if(!bEdit)
        self.tBody.append(myTR);
    },

    _open: function(id) {
      var self = this, aModel, bisEdit = false;

      if(!id) {
        aModel = new self.options.collection.model();
        aModel.set('sortableKey', self.options.collection.length);
      } else {
        aModel = self.options.collection.get(id);
        bisEdit = true;
      }

      require(['views/modal/basicModal', 'views/forms/inlineForm', 'vm'], function(BasicModal, BasicForm, Vm){
        var detailForm = Vm.create(appView, (bisEdit ? 'editDetailForm' : 'detailForm'), BasicForm, {model:aModel, collection: (bisEdit ? null : self.options.collection)});
        var $form = detailForm.render()
        detailForm.hideButtons();
        var aModal = Vm.create(appView, 'modal', BasicModal, {modalTitle: (bisEdit ? 'Edit...' : 'Add'), callback: function(){
          if(detailForm.submit()) {
            $modal.modal('hide')/*.remove();
            aModal.remove();*/
          }
        }});
        var $modal = aModal.render();
        $modal.find('.modal-body').append($form);
        $('body').append($modal);
      })
    },

    _removeAllSelected: function() {
      var self = this;
      this.tBody.find("input[type='checkbox']:checked").parents('TR').each(function(i, element) {
        var aId = $(element).data('id'),
        aModel = self.options.collection.get(aId);
        self.options.collection.remove(aModel);
        aModel.destroy();
        $(element).remove();
      })
      if(this.tBody.find("input[type='checkbox']").length == 0) {
        this.controlsHeader.find('.btn-trash').hide();
        this.tHead.find("input[type='checkbox']").prop('checked', false);
      }
      this._updateUI();
    },

    _onAfterCreatePage: function() {
      this._updateUI();
    },

    _updateUI: function() {
      var self = this;
      if(this.tBody.find('tr').not('.nodata').length) {
        if (!this.tBody.hasClass('finderSelect')) {
          this.tBody.addClass('finderSelect');
          this.tBody.finderSelect({enableDesktopCtrlDefault:true, dragEvent:'', event:'click'});
          self.tBody.finderSelect('addHook','highlight:before', function(el) {
            el.find('input').prop('checked', true);
            !el.length || self.controlsHeader.find('.btn-trash').show();
          });
          self.tBody.finderSelect('addHook','unHighlight:before', function(el) {
            el.find('input').prop('checked', false);
            if(self.tBody.find("input[type='checkbox']:checked").length==0) {
              self.tHead.find("input[type='checkbox']").prop('checked', false);
              self.controlsHeader.find('.btn-trash').hide();
            }
          });
          self.tBody.on("click", ":checkbox", function(e){
            //e.preventDefault();
          });
        } else {
          this.tBody.finderSelect('update');
        }

        this.tBody.find('.nodata').remove();

        if(self.options.sortable) {
          self.tBody.sortable({ handle: ".handle .fa-sort", axis: "y", forceHelperSize: true, forcePlaceholderSize: true, opacity: 0.5, cursor: "move" });
          self.tBody.sortable({
            update: function( event, ui ) {
              var res = self.tBody.sortable( "toArray", { attribute: "data-id"/*, expression: /(.+)[_=-](.+)/*/ } )
              for(var i = 0; i < res.length; i++) {
                var aModel = self.options.collection.get(res[i]);
                if(aModel) {
                  aModel.set('sortableKey', i);
                }
              }
            }
          });
        }
      } else {
        if(!this.tBody.find('.nodata').length)
          this.tBody.append('
No se encontraron datos
')
      }
    },

    myPublicFunction: function() {
    },
    destroy: function() {}
  });
})<|endoftext|>


<commit_before>// @flow

import React from 'react';
import Relay from 'react-relay/classic';
import { CSSTransition } from 'react-transition-group';
import classNames from 'classnames';
import { hour, seconds } from 'metrick/duration';

import PusherStore from '../../../../stores/PusherStore';
import Button from '../../../shared/Button';
import Spinner from '../../../shared/Spinner';
import Dropdown from '../../../shared/Dropdown';
import Icon from '../../../shared/Icon';
import Badge from '../../../shared/Badge';

import Build from './build';
import DropdownButton from './../dropdown-button';

type ViewerPartial = {
  scheduledBuilds: {
    count: number
  },
  runningBuilds: {
    count: number
  },
  user: Object
};

type Props = {
  viewer?: ViewerPartial,
  relay: Object
};

type State = {
  isDropdownVisible: boolean,
  scheduledBuildsCount: number,
  runningBuildsCount: number
};

// This component caches the current builds count between page refreshes so
// that we don't animate in the value once it loads via relay. Because of this
// we do some munging of props into state. Pusher updates tell Relay to refetch
// the GraphQL query which updates the props, and we turn that into derived
// state for rendering.  We also look at the state and cache it on component
// update. Sorry.
class MyBuilds extends React.Component<Props, State> {
  constructor(props) {
    super(props);

    const cachedState = MyBuilds.getCachedState();

    const initialState = {
      isDropdownVisible: false,
      scheduledBuildsCount: (
        this.props.viewer && this.props.viewer.scheduledBuilds
          ? this.props.viewer.scheduledBuilds.count
          : (cachedState && cachedState.scheduledBuildsCount ? cachedState.scheduledBuildsCount : 0)
      ),
      runningBuildsCount: (
        this.props.viewer && this.props.viewer.runningBuilds
          ? this.props.viewer.runningBuilds.count
          : (cachedState && cachedState.runningBuildsCount ? cachedState.runningBuildsCount : 0)
      )
    };

    this.state = initialState;
  }

  static getDerivedStateFromProps(props) {
    const derivedState = {};

    if (props.viewer && props.viewer.scheduledBuilds && props.viewer.scheduledBuilds.count) {
      derivedState.scheduledBuildsCount = props.viewer.scheduledBuilds.count;
    }

    if (props.viewer && props.viewer.runningBuilds && props.viewer.runningBuilds.count) {
      derivedState.runningBuildsCount = props.viewer.runningBuilds.count;
    }

    return derivedState;
  }

  static getCachedState() {
    const serializedState = localStorage['CachedState:MyBuilds:'];

    if (!serializedState) {
      return {};
    }

    const { state, expiresAt } = JSON.parse(serializedState);

    if (!state || (expiresAt && expiresAt < Date.now())) {
      return {};
    }

    return state;
  }

  static setCachedState(state = {}) {
    localStorage['CachedState:MyBuilds:'] = JSON.stringify({
      state,
      expiresAt: Date.now() + hour.bind(1)
    });
  }

  componentDidMount() {
    PusherStore.on("user_stats:change", this.handlePusherWebsocketEvent);

    // Now that "My Builds" has been mounted on the page and Pusher has
    // connected, we should force a refetch of the latest `scheduledBuilds` and
    // `runningBuilds` counts from GraphQL.
    PusherStore.on("connected", this.handlePusherConnected);

    // If pusher doesn't connect in 3 seconds, just force the callback
    // manually.  This can happen if Pusher is being a bit weird, or when
    // Pusher isn't connected at all (like in the case of automated tests)
    setTimeout(this.handlePusherConnected, seconds.bind(3));
  }

  componentDidUpdate(prevProps, prevState) {
    const { scheduledBuildsCount, runningBuildsCount } = this.state;
    const { scheduledBuildsCount: prevScheduledBuildsCount, runningBuildsCount: prevRunningBuildsCount } = prevState;

    if (scheduledBuildsCount !== prevScheduledBuildsCount || runningBuildsCount !== prevRunningBuildsCount) {
      MyBuilds.setCachedState({ scheduledBuildsCount, runningBuildsCount });
    }
  }

  componentWillUnmount() {
    PusherStore.off("user_stats:change", this.handlePusherWebsocketEvent);
    PusherStore.off("connected", this.handlePusherConnected);
  }

  render() {
    return (
      <Dropdown width={320} className="flex ml-auto" onToggle={this.handleDropdownToggle}>
        <DropdownButton className={classNames("flex-none py0", { "lime": this.state.isDropdownVisible })} onMouseEnter={this.handleButtonMouseEnter}>
          {'My Builds '}

            <CSSTransition
              in={this.getBuildsCount() > 0}
              classNames="transition-appear-pop"
              timeout={{
                enter: 200,
                exit: 200
              }}
            >
              {this.renderBadge()}
            </CSSTransition>

          <Icon
            icon="down-triangle"
            className="flex-none"
            style={{
              width: 7,
              height: 7,
              marginLeft: '.5em'
            }}
          />
        </DropdownButton>

        {this.renderDropdown()}
      </Dropdown>
    );
  }

  getBuildsCount() {
    return this.state.runningBuildsCount + this.state.scheduledBuildsCount;
  }

  renderBadge() {
    const buildsCount = this.getBuildsCount();

    // Render nothing (an empty span) if we've not got a number to show
    if (!buildsCount) {
      return ;
    }

    return (
      <Badge className={classNames("hover-lime-child", { "bg-lime": this.state.isDropdownVisible })}>
        {buildsCount}
      </Badge>
    );
  }

  renderDropdown() {
    // If `builds` here is null, that means that Relay hasn't fetched the data
    // for it yet. It will become an Array once it's loaded.
    if (!this.props.viewer || !this.props.viewer.user.builds) {
      return this.renderSpinner();
    }

    // Once we've got an array of builds, we either show what we have, or the
    // setup instructions.
    if (this.props.viewer.user.builds.edges.length > 0) {
      return this.renderBuilds();
    }

    return this.renderSetupInstructions();
  }

  renderBuilds() {
    if (!this.props.viewer) {
      return;
    }

    return (

          {this.props.viewer.user.builds.edges.map((edge) => <Build key={edge.node.id} build={edge.node} />)}

          <Button href="/builds" theme="default" outline={true} className="center" style={{ width: "100%" }}>More Builds</Button>

    );
  }

  renderSetupInstructions() {
    return (

To have your builds appear here, make sure that your commit email address (e.g. git config user.email) is added and verified in your list of personal email addresses.

        <Button href="/user/emails" theme="default" outline={true} className="center" style={{ width: "100%" }}>Update Email Addresses</Button>

    );
  }

  renderSpinner() {
    return (

        <Spinner />

    );
  }

  handleDropdownToggle = (visible) => {
    // If `includeBuilds` hasn't been set to `true` yet (perhaps the mouseEnter
    // event never got triggered because we're on a mobile device) trigger a
    // load of the builds as the dropdown opens.
    if (!this.props.relay.variables.includeBuilds) {
      this.props.relay.forceFetch({ includeBuilds: true });
    }

    this.setState({ isDropdownVisible: visible });
  };

  handlePusherConnected = () => {
    if (!this.props.relay.variables.includeBuildCounts) {
      this.props.relay.forceFetch({ includeBuildCounts: true });
    }
  };

  // If the user is hovering over the "My Builds" button, be sneaky and start
  // loading the build data in the background.
  handleButtonMouseEnter = () => {
    if (!this.props.relay.variables.includeBuilds) {
      this.props.relay.forceFetch({ includeBuilds: true });
    }
  };

  // When we recieve a Pusher event, check to see if the build counts have
  // changed (meaning a new build has probably started or finished). In that
  // case, we'll perform a full refersh of the My Builds data (including new
  // numbers for the nav and the builds themselves).
  //
  // We don't use the data from the payload otherwise the UI would update, and
  // then the builds would update a few moments later when the GraphQL query
  // finishes, which would be a bit weird.
  handlePusherWebsocketEvent = (payload) => {
    const scheduledBuildsCountChanged = this.state.scheduledBuildsCount !== payload.scheduledBuildsCount;
    const runningBuildsCountChanged = this.state.runningBuildsCount !== payload.runningBuildsCount;

    if (scheduledBuildsCountChanged || runningBuildsCountChanged) {
      this.props.relay.forceFetch();
    }
  };
}

export default Relay.createContainer(MyBuilds, {
  initialVariables: {
    includeBuilds: false,
    includeBuildCounts: false
  },

  fragments: {
    viewer: () => Relay.QL`
      fragment on Viewer {
        user {
          builds(first: 5) @include(if: $includeBuilds) {
            edges {
              node {
                id
                ${Build.getFragment('build')}
              }
            }
          }
        }
        runningBuilds: builds(state: RUNNING) @include(if: $includeBuildCounts) {
          count
        }
        scheduledBuilds: builds(state: SCHEDULED) @include(if: $includeBuildCounts) {
          count
        }
      }
    `
  }
});
<commit_msg>Omg javascript<commit_after>// @flow

import React from 'react';
import Relay from 'react-relay/classic';
import { CSSTransition } from 'react-transition-group';
import classNames from 'classnames';
import { hour, seconds } from 'metrick/duration';

import PusherStore from '../../../../stores/PusherStore';
import Button from '../../../shared/Button';
import Spinner from '../../../shared/Spinner';
import Dropdown from '../../../shared/Dropdown';
import Icon from '../../../shared/Icon';
import Badge from '../../../shared/Badge';

import Build from './build';
import DropdownButton from './../dropdown-button';

type ViewerPartial = {
  scheduledBuilds: {
    count: number
  },
  runningBuilds: {
    count: number
  },
  user: Object
};

type Props = {
  viewer?: ViewerPartial,
  relay: Object
};

type State = {
  isDropdownVisible: boolean,
  scheduledBuildsCount: number,
  runningBuildsCount: number
};

// This component caches the current builds count between page refreshes so
// that we don't animate in the value once it loads via relay. Because of this
// we do some munging of props into state. Pusher updates tell Relay to refetch
// the GraphQL query which updates the props, and we turn that into derived
// state for rendering.  We also look at the state and cache it on component
// update. Sorry.
class MyBuilds extends React.Component<Props, State> {
  constructor(props) {
    super(props);

    const cachedState = MyBuilds.getCachedState();

    const initialState = {
      isDropdownVisible: false,
      scheduledBuildsCount: (
        this.props.viewer && this.props.viewer.scheduledBuilds
          ? this.props.viewer.scheduledBuilds.count
          : (cachedState && cachedState.scheduledBuildsCount ? cachedState.scheduledBuildsCount : 0)
      ),
      runningBuildsCount: (
        this.props.viewer && this.props.viewer.runningBuilds
          ? this.props.viewer.runningBuilds.count
          : (cachedState && cachedState.runningBuildsCount ? cachedState.runningBuildsCount : 0)
      )
    };

    this.state = initialState;
  }

  static getDerivedStateFromProps(props) {
    const derivedState = {};

    if (props.viewer && props.viewer.scheduledBuilds) {
      derivedState.scheduledBuildsCount = props.viewer.scheduledBuilds.count;
    }

    if (props.viewer && props.viewer.runningBuilds) {
      derivedState.runningBuildsCount = props.viewer.runningBuilds.count;
    }

    return derivedState;
  }

  static getCachedState() {
    const serializedState = localStorage['CachedState:MyBuilds:'];

    if (!serializedState) {
      return {};
    }

    const { state, expiresAt } = JSON.parse(serializedState);

    if (!state || (expiresAt && expiresAt < Date.now())) {
      return {};
    }

    return state;
  }

  static setCachedState(state = {}) {
    localStorage['CachedState:MyBuilds:'] = JSON.stringify({
      state,
      expiresAt: Date.now() + hour.bind(1)
    });
  }

  componentDidMount() {
    PusherStore.on("user_stats:change", this.handlePusherWebsocketEvent);

    // Now that "My Builds" has been mounted on the page and Pusher has
    // connected, we should force a refetch of the latest `scheduledBuilds` and
    // `runningBuilds` counts from GraphQL.
    PusherStore.on("connected", this.handlePusherConnected);

    // If pusher doesn't connect in 3 seconds, just force the callback
    // manually.  This can happen if Pusher is being a bit weird, or when
    // Pusher isn't connected at all (like in the case of automated tests)
    setTimeout(this.handlePusherConnected, seconds.bind(3));
  }

  componentDidUpdate(prevProps, prevState) {
    const { scheduledBuildsCount, runningBuildsCount } = this.state;
    const { scheduledBuildsCount: prevScheduledBuildsCount, runningBuildsCount: prevRunningBuildsCount } = prevState;

    if (scheduledBuildsCount !== prevScheduledBuildsCount || runningBuildsCount !== prevRunningBuildsCount) {
      MyBuilds.setCachedState({ scheduledBuildsCount, runningBuildsCount });
    }
  }

  componentWillUnmount() {
    PusherStore.off("user_stats:change", this.handlePusherWebsocketEvent);
    PusherStore.off("connected", this.handlePusherConnected);
  }

  render() {
    return (
      <Dropdown width={320} className="flex ml-auto" onToggle={this.handleDropdownToggle}>
        <DropdownButton className={classNames("flex-none py0", { "lime": this.state.isDropdownVisible })} onMouseEnter={this.handleButtonMouseEnter}>
          {'My Builds '}

            <CSSTransition
              in={this.getBuildsCount() > 0}
              classNames="transition-appear-pop"
              timeout={{
                enter: 200,
                exit: 200
              }}
            >
              {this.renderBadge()}
            </CSSTransition>

          <Icon
            icon="down-triangle"
            className="flex-none"
            style={{
              width: 7,
              height: 7,
              marginLeft: '.5em'
            }}
          />
        </DropdownButton>

        {this.renderDropdown()}
      </Dropdown>
    );
  }

  getBuildsCount() {
    return this.state.runningBuildsCount + this.state.scheduledBuildsCount;
  }

  renderBadge() {
    const buildsCount = this.getBuildsCount();

    // Render nothing (an empty span) if we've not got a number to show
    if (!buildsCount) {
      return ;
    }

    return (
      <Badge className={classNames("hover-lime-child", { "bg-lime": this.state.isDropdownVisible })}>
        {buildsCount}
      </Badge>
    );
  }

  renderDropdown() {
    // If `builds` here is null, that means that Relay hasn't fetched the data
    // for it yet. It will become an Array once it's loaded.
    if (!this.props.viewer || !this.props.viewer.user.builds) {
      return this.renderSpinner();
    }

    // Once we've got an array of builds, we either show what we have, or the
    // setup instructions.
    if (this.props.viewer.user.builds.edges.length > 0) {
      return this.renderBuilds();
    }

    return this.renderSetupInstructions();
  }

  renderBuilds() {
    if (!this.props.viewer) {
      return;
    }

    return (

          {this.props.viewer.user.builds.edges.map((edge) => <Build key={edge.node.id} build={edge.node} />)}

          <Button href="/builds" theme="default" outline={true} className="center" style={{ width: "100%" }}>More Builds</Button>

    );
  }

  renderSetupInstructions() {
    return (

To have your builds appear here, make sure that your commit email address (e.g. git config user.email) is added and verified in your list of personal email addresses.

        <Button href="/user/emails" theme="default" outline={true} className="center" style={{ width: "100%" }}>Update Email Addresses</Button>

    );
  }

  renderSpinner() {
    return (

        <Spinner />

    );
  }

  handleDropdownToggle = (visible) => {
    // If `includeBuilds` hasn't been set to `true` yet (perhaps the mouseEnter
    // event never got triggered because we're on a mobile device) trigger a
    // load of the builds as the dropdown opens.
    if (!this.props.relay.variables.includeBuilds) {
      this.props.relay.forceFetch({ includeBuilds: true });
    }

    this.setState({ isDropdownVisible: visible });
  };

  handlePusherConnected = () => {
    if (!this.props.relay.variables.includeBuildCounts) {
      this.props.relay.forceFetch({ includeBuildCounts: true });
    }
  };

  // If the user is hovering over the "My Builds" button, be sneaky and start
  // loading the build data in the background.
  handleButtonMouseEnter = () => {
    if (!this.props.relay.variables.includeBuilds) {
      this.props.relay.forceFetch({ includeBuilds: true });
    }
  };

  // When we recieve a Pusher event, check to see if the build counts have
  // changed (meaning a new build has probably started or finished). In that
  // case, we'll perform a full refersh of the My Builds data (including new
  // numbers for the nav and the builds themselves).
  //
  // We don't use the data from the payload otherwise the UI would update, and
  // then the builds would update a few moments later when the GraphQL query
  // finishes, which would be a bit weird.
  handlePusherWebsocketEvent = (payload) => {
    const scheduledBuildsCountChanged = this.state.scheduledBuildsCount !== payload.scheduledBuildsCount;
    const runningBuildsCountChanged = this.state.runningBuildsCount !== payload.runningBuildsCount;

    if (scheduledBuildsCountChanged || runningBuildsCountChanged) {
      this.props.relay.forceFetch();
    }
  };
}

export default Relay.createContainer(MyBuilds, {
  initialVariables: {
    includeBuilds: false,
    includeBuildCounts: false
  },

  fragments: {
    viewer: () => Relay.QL`
      fragment on Viewer {
        user {
          builds(first: 5) @include(if: $includeBuilds) {
            edges {
              node {
                id
                ${Build.getFragment('build')}
              }
            }
          }
        }
        runningBuilds: builds(state: RUNNING) @include(if: $includeBuildCounts) {
          count
        }
        scheduledBuilds: builds(state: SCHEDULED) @include(if: $includeBuildCounts) {
          count
        }
      }
    `
  }
});
<|endoftext|>


<commit_before>/**
 * Shopware 4.0
 * Copyright © 2012 shopware AG
 *
 * According to our dual licensing model, this program can be used either
 * under the terms of the GNU Affero General Public License, version 3,
 * or under a proprietary license.
 *
 * The texts of the GNU Affero General Public License with an additional
 * permission and of our proprietary license can be found at and
 * in the LICENSE file you have received along with this program.
 *
 * This program 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 Affero General Public License for more details.
 *
 * "Shopware" is a registered trademark of shopware AG.
 * The licensing of the program under the AGPLv3 does not imply a
 * trademark license. Therefore any rights, title and interest in
 * our trademarks remain entirely with us.
 *
 * @category   Shopware
 * @package    MediaManager
 * @subpackage Controller
 * @copyright  Copyright (c) 2012, shopware AG (http://www.shopware.de)
 * @version    $Id$
 * @author shopware AG
 */

/**
 * Shopware UI - Media Manager Main Controller
 *
 * This file contains the business logic for the User Manager module. The module
 * handles the whole administration of the backend users.
 */

//{block name="backend/media_manager/controller/main"}
Ext.define('Shopware.apps.MediaManager.controller.Main', {

    /**
     * Extend from the standard ExtJS 4 controller
     * @string
     */
	extend: 'Ext.app.Controller',

    requires: [
        'Shopware.apps.MediaManager.controller.Album',
        'Shopware.apps.MediaManager.controller.Media'
    ],

	/**
	 * Creates the necessary event listener for this
	 * specific controller and opens a new Ext.window.Window
	 * to display the subapplication
     *
     * @return void
	 */
	init: function() {
        var me = this;

        var albumStore = me.subApplication.getStore('Album'),
            mediaStore = me.subApplication.getStore('Media'),
            forceToFront = me.subApplication.forceToFront || false;

        if (me.subApplication.params && me.subApplication.params.albumId !== null) {
            if (Ext.isArray(me.subApplication.params.albumId)) {
                albumStore.getProxy().extraParams.albumId = me.subApplication.params.albumId.join(',');
            } else {
                albumStore.getProxy().extraParams.albumId = me.subApplication.params.albumId;
            }
        } else {
            albumStore.getProxy().extraParams.albumId = null;
        }

        if(me.subApplication.layout && me.subApplication.layout == 'small') {
            me.getView('main.Selection').create({
                albumStore: albumStore,
                mediaStore: mediaStore,
                selectionHandler: me.subApplication.mediaSelectionCallback,
                eventScope: me.subApplication.eventScope,
                selectionMode: me.subApplication.selectionMode,
                validTypes: me.subApplication.validTypes,
                forceToFront: forceToFront
            });
        } else {
            me.mainWindow = me.getView('main.Window').create({
                albumStore: albumStore,
                mediaStore: mediaStore,
                validTypes: me.validTypes
            });
        }

        me.callParent(arguments);
    }
});
//{/block}
<commit_msg>SW-5052 - Fixed: Cleared the second load request in the media manager module. The module now requests the necessary controllers only once<commit_after>/**
 * Shopware 4.0
 * Copyright © 2012 shopware AG
 *
 * According to our dual licensing model, this program can be used either
 * under the terms of the GNU Affero General Public License, version 3,
 * or under a proprietary license.
 *
 * The texts of the GNU Affero General Public License with an additional
 * permission and of our proprietary license can be found at and
 * in the LICENSE file you have received along with this program.
 *
 * This program 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 Affero General Public License for more details.
 *
 * "Shopware" is a registered trademark of shopware AG.
 * The licensing of the program under the AGPLv3 does not imply a
 * trademark license. Therefore any rights, title and interest in
 * our trademarks remain entirely with us.
 *
 * @category   Shopware
 * @package    MediaManager
 * @subpackage Controller
 * @copyright  Copyright (c) 2012, shopware AG (http://www.shopware.de)
 * @version    $Id$
 * @author shopware AG
 */

/**
 * Shopware UI - Media Manager Main Controller
 *
 * This file contains the business logic for the User Manager module. The module
 * handles the whole administration of the backend users.
 */

//{block name="backend/media_manager/controller/main"}
Ext.define('Shopware.apps.MediaManager.controller.Main', {

    /**
     * Extend from the standard ExtJS 4 controller
     * @string
     */
	extend: 'Ext.app.Controller',

	/**
	 * Creates the necessary event listener for this
	 * specific controller and opens a new Ext.window.Window
	 * to display the subapplication
     *
     * @return void
	 */
	init: function() {
        var me = this;

        var albumStore = me.subApplication.getStore('Album'),
            mediaStore = me.subApplication.getStore('Media'),
            forceToFront = me.subApplication.forceToFront || false;

        if (me.subApplication.params && me.subApplication.params.albumId !== null) {
            if (Ext.isArray(me.subApplication.params.albumId)) {
                albumStore.getProxy().extraParams.albumId = me.subApplication.params.albumId.join(',');
            } else {
                albumStore.getProxy().extraParams.albumId = me.subApplication.params.albumId;
            }
        } else {
            albumStore.getProxy().extraParams.albumId = null;
        }

        if(me.subApplication.layout && me.subApplication.layout == 'small') {
            me.getView('main.Selection').create({
                albumStore: albumStore,
                mediaStore: mediaStore,
                selectionHandler: me.subApplication.mediaSelectionCallback,
                eventScope: me.subApplication.eventScope,
                selectionMode: me.subApplication.selectionMode,
                validTypes: me.subApplication.validTypes,
                forceToFront: forceToFront
            });
        } else {
            me.mainWindow = me.getView('main.Window').create({
                albumStore: albumStore,
                mediaStore: mediaStore,
                validTypes: me.validTypes
            });
        }

        me.callParent(arguments);
    }
});
//{/block}
<|endoftext|>


<commit_before>/*jslint node: true */
'use strict';
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var browserify = require('browserify');
var watchify = require('watchify');
var buffer = require('vinyl-buffer');
var source = require('vinyl-source-stream');
var sequence = require('run-sequence');
var browserSync = require('browser-sync');
var fs = require('fs');
var spawn = require('child_process').spawn;

var config = {
  fileSaver: {
    scripts: './src/*.js',
  },
  docs: {
    src: './docs/src',
    index: './docs/index.html',
    styles: './docs/assets/stylesheets/**/*.css',
    dest: './docs/dist'
  },
  browserSync: {
    port: '3000',
    server: './docs'
  },
  // Predefined browserify configs to keep tasks DRY
  browserify: {
    fileSaver: {
      type: 'dragular',
      entryPoint: './src/angular-file-saver.js',
      bundleName: 'angular-file-saver.js',
      dest: './dist',
    },
    docs: {
      type: 'docs',
      entryPoint: './docs/assets/js/custom.js',
      bundleName: 'examples.js',
      dest: './docs/dist'
    }
  },
  tests: {
    karma: 'test/karma.conf.js'
  },
  // A flag attribute to switch modes.
  isProd: false
};

var browserifyDefaults = config.browserify.fileSaver;

function handleErrors(err) {
  $.util.log(err.toString());
  this.emit('end');
}

/*
* Get arguments for release task from CLI
*/
function getUpdateType() {
  var env = $.util.env;

  if (env.type) {
    return { type: env.type };
  }

  if (env.version) {
    return { version: env.version };
  }

  return { type: 'patch' };
}

function getPackageJsonVersion() {
    return JSON.parse(fs.readFileSync('./package.json', 'utf8')).version;
}

/*
* See http://blog.avisi.nl/2014/04/25/how-to-keep-a-fast-build-with-browserify-and-reactjs/
*/
function buildScript() {

  var bundler = browserify({
    entries: browserifyDefaults.entryPoint,
    debug: false,
    cache: {},
    packageCache: {},
    fullPaths: false,
    standalone: 'angular-file-saver',
  }, watchify.args);

  // Watch files for changes and only rebuilds what it needs to
  if (!config.isProd) {
    bundler = watchify(bundler);
    bundler.on('update', function() {
      rebundle();
    });
  }

  function rebundle() {
    var stream = bundler.bundle();

    return stream.on('error', handleErrors)
      .pipe(source(browserifyDefaults.bundleName))
      .pipe(buffer())
      .pipe(gulp.dest(browserifyDefaults.dest))
      .pipe($.if(config.isProd, $.uglify({
        compress: { drop_console: true }
      })))
      .pipe($.if(config.isProd, $.rename({
        suffix: '.min'
      })))
      .pipe($.size({
        title: 'Scripts: '
      }))
      .pipe(gulp.dest(browserifyDefaults.dest))
      .pipe($.if(browserSync.active, browserSync.stream()));
  }

  return rebundle();
}

gulp.task('browserify', function() {
  return buildScript();
});

gulp.task('styles:docs', function() {

  return gulp.src([
    config.docs.styles
  ])
  .pipe($.concat('examples.css'))
  .pipe(gulp.dest(config.docs.dest))
  .pipe($.if(browserSync.active, browserSync.stream()));
});

gulp.task('serve', function () {

  browserSync({
    port: config.browserSync.port,
    server: {
      baseDir: config.browserSync.server,
    },
    logConnections: true,
    logFileChanges: true,
    notify: true
  });
});

gulp.task('deploy:docs', function() {
  return gulp.src('./docs/**/*')
    .pipe($.ghPages());
});

gulp.task('build', function() {
  sequence('build:src');
  sequence('build:docs');
});

gulp.task('build:src', function() {
  config.isProd = true;
  browserifyDefaults = config.browserify.fileSaver;

  sequence('browserify', 'build:docs');
});

gulp.task('build:docs', function() {
  config.isProd = true;
  browserifyDefaults = config.browserify.docs;

  sequence(['browserify', 'styles:docs']);
});

gulp.task('dev:docs', function() {
  config.isProd = false;
  browserifyDefaults = config.browserify.docs;

  sequence(['browserify', 'styles:docs'], 'watch:docs');
});

gulp.task('watch:docs', ['serve'], function() {
  gulp.watch(config.docs.styles,  ['styles:docs']);
});

gulp.task('release:bump', function() {

  return gulp.src('./*.json')
    .pipe($.bump(getUpdateType()))
    .pipe(gulp.dest('./'));
});

gulp.task('release:commit', ['release:bump'], function (cb) {
  var version = getPackageJsonVersion();

  return gulp.src('.')
    .pipe($.git.add())
    .pipe($.git.commit(':octocat: Bump to ' + version, cb));
});

gulp.task('release:push', ['release:bump', 'release:commit'], function (cb) {
   return $.git.push('origin', 'master', cb);
});

gulp.task('release:tag', ['release:bump', 'release:commit', 'release:push'], function (cb) {
  var version = getPackageJsonVersion();

  return $.git.tag(version, 'Tag: ' + version, function (err) {
    if (err) {
      return cb(err);
    }
    $.git.push('origin', 'master', {args: '--tags'}, cb);
  });
});

gulp.task('unit', function() {
  // Nonsensical source to fall back to files listed in karma.conf.js.
  // See https://github.com/lazd/gulp-karma/issues/9
  return gulp.src('./foobar')
    .pipe($.karma({
      configFile: config.tests.karma,
      action: 'run'
    }))
    .on('error', function(err) {
      throw err;
    });
});

gulp.task('release:npm', ['release:bump', 'release:commit', 'release:push', 'release:tag'], function (done) {
  spawn('npm', ['publish'], { stdio: 'inherit' }).on('close', done);
});

/*
* Automate npm & bower updates.
* $ gulp release --type major - using gulp-bump versioning
* $ gulp release --version 1.1.1 - using explicit version number
*/
gulp.task('release', ['release:bump', 'release:commit', 'release:push', 'release:tag', 'release:npm']);

gulp.task('default', ['build']);
<commit_msg>Pass a cb to run run-sequence tasks synchronically<commit_after>/*jslint node: true */
'use strict';
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var browserify = require('browserify');
var watchify = require('watchify');
var buffer = require('vinyl-buffer');
var source = require('vinyl-source-stream');
var sequence = require('run-sequence');
var browserSync = require('browser-sync');
var fs = require('fs');
var spawn = require('child_process').spawn;

var config = {
  fileSaver: {
    scripts: './src/*.js',
  },
  docs: {
    src: './docs/src',
    index: './docs/index.html',
    styles: './docs/assets/stylesheets/**/*.css',
    dest: './docs/dist'
  },
  browserSync: {
    port: '3000',
    server: './docs'
  },
  // Predefined browserify configs to keep tasks DRY
  browserify: {
    fileSaver: {
      type: 'dragular',
      entryPoint: './src/angular-file-saver.js',
      bundleName: 'angular-file-saver.js',
      dest: './dist'
    },
    docs: {
      type: 'docs',
      entryPoint: './docs/assets/js/custom.js',
      bundleName: 'examples.js',
      dest: './docs/dist'
    }
  },
  tests: {
    karma: 'test/karma.conf.js'
  },
  // A flag attribute to switch modes.
  isProd: false
};

var browserifyDefaults = config.browserify.fileSaver;

function handleErrors(err) {
  $.util.log(err.toString());
  this.emit('end');
}

/*
* Get arguments for release task from CLI
*/
function getUpdateType() {
  var env = $.util.env;

  if (env.type) {
    return { type: env.type };
  }

  if (env.version) {
    return { version: env.version };
  }

  return { type: 'patch' };
}

function getPackageJsonVersion() {
    return JSON.parse(fs.readFileSync('./package.json', 'utf8')).version;
}

/*
* See http://blog.avisi.nl/2014/04/25/how-to-keep-a-fast-build-with-browserify-and-reactjs/
*/
function buildScript() {

  var bundler = browserify({
    entries: browserifyDefaults.entryPoint,
    debug: false,
    cache: {},
    packageCache: {},
    fullPaths: false,
    standalone: 'angular-file-saver',
  }, watchify.args);

  // Watch files for changes and only rebuilds what it needs to
  if (!config.isProd) {
    bundler = watchify(bundler);
    bundler.on('update', function() {
      rebundle();
    });
  }

  function rebundle() {
    var stream = bundler.bundle();

    return stream.on('error', handleErrors)
      .pipe(source(browserifyDefaults.bundleName))
      .pipe(buffer())
      .pipe(gulp.dest(browserifyDefaults.dest))
      .pipe($.if(config.isProd, $.uglify({
        compress: { drop_console: true }
      })))
      .pipe($.if(config.isProd, $.rename({
        suffix: '.min'
      })))
      .pipe($.size({
        title: 'Scripts: '
      }))
      .pipe(gulp.dest(browserifyDefaults.dest))
      .pipe($.if(browserSync.active, browserSync.stream()));
  }

  return rebundle();
}

gulp.task('browserify', function() {
  return buildScript();
});

gulp.task('styles:docs', function() {

  return gulp.src([
    config.docs.styles
  ])
  .pipe($.concat('examples.css'))
  .pipe(gulp.dest(config.docs.dest))
  .pipe($.if(browserSync.active, browserSync.stream()));
});

gulp.task('serve', function () {

  browserSync({
    port: config.browserSync.port,
    server: {
      baseDir: config.browserSync.server,
    },
    logConnections: true,
    logFileChanges: true,
    notify: true
  });
});

gulp.task('deploy:docs', function() {
  return gulp.src('./docs/**/*')
    .pipe($.ghPages());
});

gulp.task('build', function(cb) {
  sequence('build:src', 'build:docs', cb);
});

gulp.task('build:src', function(cb) {
  config.isProd = true;
  browserifyDefaults = config.browserify.fileSaver;

  sequence('browserify', 'build:docs', cb);
});

gulp.task('build:docs', function(cb) {
  config.isProd = true;
  browserifyDefaults = config.browserify.docs;

  sequence(['browserify', 'styles:docs'], cb);
});

gulp.task('dev:docs', function() {
  config.isProd = false;
  browserifyDefaults = config.browserify.docs;

  sequence(['browserify', 'styles:docs'], 'watch:docs');
});

gulp.task('watch:docs', ['serve'], function() {
  gulp.watch(config.docs.styles,  ['styles:docs']);
});

gulp.task('release:bump', function() {

  return gulp.src('./*.json')
    .pipe($.bump(getUpdateType()))
    .pipe(gulp.dest('./'));
});

gulp.task('release:commit', ['release:bump'], function (cb) {
  var version = getPackageJsonVersion();

  return gulp.src('.')
    .pipe($.git.add())
    .pipe($.git.commit(':octocat: Bump to ' + version, cb));
});

gulp.task('release:push', ['release:bump', 'release:commit'], function (cb) {
   return $.git.push('origin', 'master', cb);
});

gulp.task('release:tag', ['release:bump', 'release:commit', 'release:push'], function (cb) {
  var version = getPackageJsonVersion();

  return $.git.tag(version, 'Tag: ' + version, function (err) {
    if (err) {
      return cb(err);
    }
    $.git.push('origin', 'master', {args: '--tags'}, cb);
  });
});

gulp.task('unit', function() {
  // Nonsensical source to fall back to files listed in karma.conf.js.
  // See https://github.com/lazd/gulp-karma/issues/9
  return gulp.src('./foobar')
    .pipe($.karma({
      configFile: config.tests.karma,
      action: 'run'
    }))
    .on('error', function(err) {
      throw err;
    });
});

gulp.task('release:npm', ['release:bump', 'release:commit', 'release:push', 'release:tag'], function (done) {
  spawn('npm', ['publish'], { stdio: 'inherit' }).on('close', done);
});

/*
* Automate npm & bower updates.
* $ gulp release --type major - using gulp-bump versioning
* $ gulp release --version 1.1.1 - using explicit version number
*/
gulp.task('release', ['release:bump', 'release:commit', 'release:push', 'release:tag', 'release:npm']);

gulp.task('default', ['build']);
<|endoftext|>