<commit_before>// See http://www.bitsofpancake.com/programming/markov-chain-text-generator/

(function () {
  'use strict';

  // var fs = require('fs');

  var cache = require('./slipsum-cache.json', 'utf-8');

  // var buildCache = function () {
  //   if (cache) {
  //     return;
  //   }
  //   else {
  //     cache = {
  //       '_START': []
  //     }
  //   }
  //
  //   // Get the source text and split it into words
  //   var text = fs.existsSync('./slipsum-seed.txt') ?
  //     fs.readFileSync('./slipsum-seed.txt', 'utf-8').split(/\s+/g) :
  //     null
  //   ;
  //
  //   if (!text) {
  //     return;
  //   }
  //
  //   // Add it to the start node's list of possibility
  //   cache['_START'].push(text[0]);
  //
  //   // Go through each word and add it to the previous word's node
  //   for (var i = 0; i < text.length - 1; i++) {
  //     if (!cache[text[i]]) {
  //       cache[text[i]] = [];
  //     }
  //
  //     cache[text[i]].push(text[i + 1]);
  //
  //     // If it's the beginning of a sentence, add the next word to the start node too
  //     if (text[i].match(/\.$/)) {
  //       cache['_START'].push(text[i + 1]);
  //     }
  //
  //     if (i === (text.length-2)) {
  //       fs.writeFile('./slipsum-cache.json', JSON.stringify(cache, null, 2));
  //     }
  //   }
  // };

  function randomIntFromInterval(min,max)
  {
      return Math.floor(Math.random()*(max-min+1)+min);
  }

  var sentences = function (targetNumSentences) {
    var currentWord = '_START';
    var str = '';

    var numSentences = 0;
    while (numSentences < targetNumSentences) {
      // Follow a random node, append it to the string, and move to that node
      var rand = Math.floor(Math.random() * cache[currentWord].length);
      str += cache[currentWord][rand];

      // No more nodes to follow? Start again. (Add a period to make things look better.)
      if (!cache[cache[currentWord][rand]]) {
        currentWord = '_START';
        if (!cache[currentWord][rand].match(/\.$/)) {
          str += '. ';
          numSentences += 1;
          break;
        }
        else {
          str += ' ';
        }
      }
      else {
        currentWord = cache[currentWord][rand];
        var pattern = /[.!?](\s?)$/g;

        if (currentWord.match(pattern)) {
          var r = Math.floor(Math.random() * 19) + 1;

          if (r === 1) {
            currentWord.replace(pattern, '?!$1');
          }
          else if (r >= 2 && r < 4) {
            currentWord.replace(pattern, '?$1');
          }
          else if (r >= 4 && r < 7) {
            currentWord.replace(pattern, '!$1');
          }

          numSentences += 1;
        }

        if (numSentences !== targetNumSentences) {
          str += ' ';
        }
      }
    }

    return str;
  }

  var paragraphs = function (targetNumParagraphs) {
    var paras = '';

    for (var i = 0; i < targetNumParagraphs; i++) {
      var rand = randomIntFromInterval(4, 8);
      paras += sentences(rand);
      paras += '\n\n';
    }

    paras.replace(/[\s\n]+$/g, '');
    return paras;
  }

  var slipsum = {
    sentences: sentences,
    paragraphs: paragraphs
  }

  module.exports = {
    slipsum: slipsum
  }

  if (typeof exports !== 'undefined') {
    if(typeof module !== 'undefined' && module.exports) {
      exports = module.exports = slipsum;
    }
    exports.slipsum = slipsum;
  }
  else {
    root.slipsum = slipsum;
  }
}).call(this);
<commit_msg>Update unnamespaced ref.<commit_after>// See http://www.bitsofpancake.com/programming/markov-chain-text-generator/

(function () {
  'use strict';

  // var fs = require('fs');

  var cache = require('./rocketbelt.slipsum-cache.json', 'utf-8');

  // var buildCache = function () {
  //   if (cache) {
  //     return;
  //   }
  //   else {
  //     cache = {
  //       '_START': []
  //     }
  //   }
  //
  //   // Get the source text and split it into words
  //   var text = fs.existsSync('./slipsum-seed.txt') ?
  //     fs.readFileSync('./slipsum-seed.txt', 'utf-8').split(/\s+/g) :
  //     null
  //   ;
  //
  //   if (!text) {
  //     return;
  //   }
  //
  //   // Add it to the start node's list of possibility
  //   cache['_START'].push(text[0]);
  //
  //   // Go through each word and add it to the previous word's node
  //   for (var i = 0; i < text.length - 1; i++) {
  //     if (!cache[text[i]]) {
  //       cache[text[i]] = [];
  //     }
  //
  //     cache[text[i]].push(text[i + 1]);
  //
  //     // If it's the beginning of a sentence, add the next word to the start node too
  //     if (text[i].match(/\.$/)) {
  //       cache['_START'].push(text[i + 1]);
  //     }
  //
  //     if (i === (text.length-2)) {
  //       fs.writeFile('./slipsum-cache.json', JSON.stringify(cache, null, 2));
  //     }
  //   }
  // };

  function randomIntFromInterval(min,max)
  {
      return Math.floor(Math.random()*(max-min+1)+min);
  }

  var sentences = function (targetNumSentences) {
    var currentWord = '_START';
    var str = '';

    var numSentences = 0;
    while (numSentences < targetNumSentences) {
      // Follow a random node, append it to the string, and move to that node
      var rand = Math.floor(Math.random() * cache[currentWord].length);
      str += cache[currentWord][rand];

      // No more nodes to follow? Start again. (Add a period to make things look better.)
      if (!cache[cache[currentWord][rand]]) {
        currentWord = '_START';
        if (!cache[currentWord][rand].match(/\.$/)) {
          str += '. ';
          numSentences += 1;
          break;
        }
        else {
          str += ' ';
        }
      }
      else {
        currentWord = cache[currentWord][rand];
        var pattern = /[.!?](\s?)$/g;

        if (currentWord.match(pattern)) {
          var r = Math.floor(Math.random() * 19) + 1;

          if (r === 1) {
            currentWord.replace(pattern, '?!$1');
          }
          else if (r >= 2 && r < 4) {
            currentWord.replace(pattern, '?$1');
          }
          else if (r >= 4 && r < 7) {
            currentWord.replace(pattern, '!$1');
          }

          numSentences += 1;
        }

        if (numSentences !== targetNumSentences) {
          str += ' ';
        }
      }
    }

    return str;
  }

  var paragraphs = function (targetNumParagraphs) {
    var paras = '';

    for (var i = 0; i < targetNumParagraphs; i++) {
      var rand = randomIntFromInterval(4, 8);
      paras += sentences(rand);
      paras += '\n\n';
    }

    paras.replace(/[\s\n]+$/g, '');
    return paras;
  }

  var slipsum = {
    sentences: sentences,
    paragraphs: paragraphs
  }

  module.exports = {
    slipsum: slipsum
  }

  if (typeof exports !== 'undefined') {
    if(typeof module !== 'undefined' && module.exports) {
      exports = module.exports = slipsum;
    }
    exports.slipsum = slipsum;
  }
  else {
    root.slipsum = slipsum;
  }
}).call(this);
<|endoftext|>


<commit_before>(function(){
'use strict';
window.pengine = window.pengine||{};
/**
 * Manage meshes and sprites in the scene
 * @return {}
 */
window.pengine.sceneBuilder = function(){

    var BLOCK_SIZE = 200;

    function drawHexas(blockMapArray, scene){
        for (var ix= 0; ix < blockMapArray.length; ix++) {
            for (var iy= 0; iy < blockMapArray.length; iy++) {
                var thisBlock = blockMapArray[ix][iy];
                if(thisBlock &&  thisBlock.height > 0){
                    addHexa(ix, thisBlock.height, iy,  scene );
                }else{
                    addHexaPlaneGround(ix,iy,scene, thisBlock.type );
                }
            }
        }
    }

    /**
     *
     * @param blockMap
     * @param scene
     */
    function drawBoxes(blockMapArray, scene){
        for (var ix= 0; ix < blockMapArray.length; ix++) {
            for (var iy= 0; iy < blockMapArray.length; iy++) {
                var thisBlock = blockMapArray[ix][iy];
                if(thisBlock &&  thisBlock.height > 0){
                    addBox(ix, thisBlock.height,iy,  scene );
                }else{
                    addPlaneGround(ix,iy,scene, thisBlock.type );
                }
            }
        }
    }

    /**
     *
     * @param gameMapArray
     * @param scene
     */
    function drawEntities(gameMapArray, scene, blockMapArray){
        for (var ix= 0; ix < gameMapArray.length; ix++) {
            for (var iz= 0; iz < gameMapArray.length; iz++) {
                var thisBlock = gameMapArray[ix][iz];
                if(thisBlock &&  thisBlock.type){
                    addSprite(ix,iz,blockMapArray[ix][iz].height,thisBlock,scene );
                }
            }
        }
    }

    function getHexaPlaneGeometry(){
        var geometry = getHexaGeometry();
        return geometry;
    }

    function getHexaGeometry(){
        var shape = new THREE.Shape();

        var center = new THREE.Vector2(0,0);

        var i = 0;
        var angle, x_i, y_i;
        var size = BLOCK_SIZE/2;
        while(i<6){
            angle = 2 * Math.PI / 6 * i;
            x_i = center.x + size * Math.cos(angle);
            y_i = center.y + size * Math.sin(angle);
            if (i === 0){
                shape.moveTo(x_i, y_i);
            }else{
                shape.lineTo(x_i, y_i);
            }
            i++;
        }

        var geometry = new THREE.ShapeGeometry(shape);

        geometry.faces.push( new THREE.Face3( 0, 2, 1 ) );
        geometry.computeFaceNormals();
        geometry.applyMatrix( new THREE.Matrix4().makeTranslation( 1, 0.1, 0.1 ) );
        geometry.verticesNeedUpdate = true;
        return geometry;
    }

    /**
     *
     * @param x
     * @param y
     * @param z
     * @param scene
     */
    function addHexa(x,y,z,scene){
        var geo = getHexaGeometry();

        var mat = new THREE.MeshPhongMaterial( { color: 0xddBB99, specular: 0x111111, shiness: 20 });
        var mesh = new THREE.Mesh( geo, mat );
        mesh.rotation.x = - Math.PI / 2;

        mesh.position.x = x*200;
        mesh.position.y = y*100/2;
        mesh.position.z = z*200;

        mesh.receiveShadow = true;
        mesh.castShadow = true;
        scene.add( mesh );
    }

    /**
     *
     * @param x
     * @param y
     * @param z
     * @param geo
     * @param mat
     * @param scene
     */
    function addBox(x, y, z, scene){
        var geo = new THREE.CubeGeometry( 200, 50*y , 200 );
        var mat = new THREE.MeshPhongMaterial( { color: 0xddBB99, specular: 0x111111, shiness: 20 });
        var mesh = new THREE.Mesh( geo, mat );
        mesh.position.x = x*200;
        mesh.position.y = y*50/2;
        mesh.position.z = z*200;
        mesh.receiveShadow = true;
        mesh.castShadow = true;
        scene.add( mesh );
    }

    /**
     *
     * @param x
     * @param z
     * @param scene
     * @param type
     */
    function addHexaPlaneGround(x,z, scene, type){
        var geo = getHexaPlaneGeometry();
        var mat = new THREE.MeshPhongMaterial( { color: 0xddBB99, specular: 0x111111, shiness: 20 });
        var mesh = new THREE.Mesh( geo, mat );
        var width = 100;
        var height = Math.sqrt(3)/2 * width;

        mesh.rotation.x = - Math.PI / 2;
        mesh.position.x = x*150;

        if(isEven(x)){
            mesh.position.z = z*height*2-height/2;
        }else{
            mesh.position.z = z*height*2+height/2;
        }

        mesh.receiveShadow = true;
        mesh.castShadow = true;
        //set custom properties
        mesh.ox = x;
        mesh.oz = z;
        mesh.type = type;
        scene.add( mesh );
    }

    function isEven(num){
        return num%2 === 0;
    }

    /**
     *
     * @param x
     * @param z
     * @param scene
     * @param type
     */
    function addPlaneGround(x,z, scene, type){
        var geo = new THREE.PlaneGeometry( 200, 200);
        var color = type=="water"?0x0000ff:0xffffff;

        var mat = new THREE.MeshPhongMaterial( {color: color, specular: 0x111111, shiness: 0 });
        var mesh = new THREE.Mesh( geo, mat );
        mesh.position.x = x*200;
        mesh.position.y = 1;
        mesh.position.z = z*200;
        mesh.rotation.x = - Math.PI / 2;
        mesh.receiveShadow = true;
        mesh.castShadow = true;
        scene.add( mesh );
    }

    /**
     *
     * @param x
     * @param z
     * @param entity
     * @param scene
     */
    function addSprite(x,z,y,entity,scene){
        var texture = THREE.ImageUtils.loadTexture( 'textures/' + entity.type + '.png' );
        var crateMaterial = new THREE.SpriteMaterial( { map: texture, useScreenCoordinates: false } );
        var sprite2 = new THREE.Sprite( crateMaterial );
        sprite2.position.x = x*200;
        sprite2.position.z = z*200;
        sprite2.position.y = y*50+49;
        sprite2.scale.set( 200, 200, 1.0 ); // imageWidth, imageHeight
        scene.add( sprite2 );
    }

    /**
     *
     * @param x
     * @param z
     * @param h
     * @param mesh
     * @param scene
     */
    function setHeight(x,z,h,mesh, scene){
        scene.remove( mesh );
        if(h==0||h=="0"){
            pengine.sceneBuilder.addPlaneGround(x, z, scene, "earth");
        }else{
            pengine.sceneBuilder.addBox(x, h, z,  scene );
        }
    }

    /**
     *
     * @param scene
     * @return {THREE.Scene}
     */
    function createScene(scene){
        scene = new THREE.Scene();
        scene.fog = new THREE.Fog( 0xcce0ff, 500, 10000 );
        return scene;
    }

    /**
     * NOT USED
     * @param scene
     */
    function createGround(scene){
        var initColor = new THREE.Color( 0x497f13 );
        var initTexture = THREE.ImageUtils.generateDataTexture( 1, 1, initColor );

        var groundMaterial = new THREE.MeshPhongMaterial( { color: 0xffffff, specular: 0x111111, map: initTexture } );
        var groundTexture = THREE.ImageUtils.loadTexture( "../examples/textures/terrain/grasslight-big.jpg", undefined, function() { groundMaterial.map = groundTexture } );

        groundTexture.wrapS = groundTexture.wrapT = THREE.RepeatWrapping;
        groundTexture.repeat.set( 25, 25 );
        groundTexture.anisotropy = 16;

        var mesh = new THREE.Mesh( new THREE.PlaneGeometry( 20000, 20000 ), groundMaterial );
        mesh.position.y = 0;
        mesh.rotation.x = - Math.PI / 2;
        mesh.receiveShadow = true;
        scene.add( mesh );
    }

    return {
        drawBoxes:drawBoxes,
        drawHexas:drawHexas,
        drawEntities:drawEntities,
        addPlaneGround:addPlaneGround,
        addHexaPlaneGround:addHexaPlaneGround,
        addBox:addBox,
        setHeight:setHeight,
        createScene:createScene,
        createGround:createGround
    }
}();
})();<commit_msg>PI-105 Fix set correct color by type at start<commit_after>(function(){
'use strict';
window.pengine = window.pengine||{};
/**
 * Manage meshes and sprites in the scene
 * @return {}
 */
window.pengine.sceneBuilder = function(){

    var BLOCK_SIZE = 200;
    var COLORS = {
        water:0x0000ff,
        normal:0xddBB99
    };
    var TYPES = {
        water:'water'
    };

    /**
     *
     * @param blockMapArray
     * @param scene
     */
    function drawHexagons(blockMapArray, scene){
        for (var ix= 0; ix < blockMapArray.length; ix++) {
            for (var iy= 0; iy < blockMapArray.length; iy++) {
                var thisBlock = blockMapArray[ix][iy];
                if(thisBlock &&  thisBlock.height > 0){
                    addHexa(ix, thisBlock.height, iy,  scene );
                }else{
                    addHexagonalGround(ix,iy,scene, thisBlock.type );
                }
            }
        }
    }

    /**
     *
     * @param blockMap
     * @param scene
     */
    function drawBoxes(blockMapArray, scene){
        for (var ix= 0; ix < blockMapArray.length; ix++) {
            for (var iy= 0; iy < blockMapArray.length; iy++) {
                var thisBlock = blockMapArray[ix][iy];
                if(thisBlock &&  thisBlock.height > 0){
                    addBox(ix, thisBlock.height,iy,  scene );
                }else{
                    addPlaneGround(ix,iy,scene, thisBlock.type );
                }
            }
        }
    }

    /**
     *
     * @param gameMapArray
     * @param scene
     */
    function drawEntities(gameMapArray, scene, blockMapArray){
        for (var ix= 0; ix < gameMapArray.length; ix++) {
            for (var iz= 0; iz < gameMapArray.length; iz++) {
                var thisBlock = gameMapArray[ix][iz];
                if(thisBlock &&  thisBlock.type){
                    addSprite(ix,iz,blockMapArray[ix][iz].height,thisBlock,scene );
                }
            }
        }
    }

    /**
     *
     * @returns {THREE.Geometry}
     */
    function getHexaPlaneGeometry(){
        var geometry = getHexaGeometry();
        return geometry;
    }

    /**
     *
     * @returns {THREE.Geometry}
     */
    function getHexaGeometry(){
        var shape = new THREE.Shape();

        var center = new THREE.Vector2(0,0);

        var i = 0;
        var angle, x_i, y_i;
        var size = BLOCK_SIZE/2;
        while(i<6){
            angle = 2 * Math.PI / 6 * i;
            x_i = center.x + size * Math.cos(angle);
            y_i = center.y + size * Math.sin(angle);
            if (i === 0){
                shape.moveTo(x_i, y_i);
            }else{
                shape.lineTo(x_i, y_i);
            }
            i++;
        }

        var geometry = new THREE.ShapeGeometry(shape);

        geometry.faces.push( new THREE.Face3( 0, 2, 1 ) );
        geometry.computeFaceNormals();
        geometry.applyMatrix( new THREE.Matrix4().makeTranslation( 1, 0.1, 0.1 ) );
        geometry.verticesNeedUpdate = true;
        return geometry;
    }

    /**
     *
     * @param x
     * @param y
     * @param z
     * @param scene
     */
    function addHexa(x,y,z,scene){
        var geo = getHexaGeometry();

        var mat = new THREE.MeshPhongMaterial( { color: COLORS.normal, specular: 0x111111, shiness: 20 });
        var mesh = new THREE.Mesh( geo, mat );
        mesh.rotation.x = - Math.PI / 2;

        mesh.position.x = x*200;
        mesh.position.y = y*100/2;
        mesh.position.z = z*200;

        mesh.receiveShadow = true;
        mesh.castShadow = true;
        scene.add( mesh );
    }

    /**
     *
     * @param x
     * @param y
     * @param z
     * @param geo
     * @param mat
     * @param scene
     */
    function addBox(x, y, z, scene){
        var geo = new THREE.CubeGeometry( 200, 50*y , 200 );
        var mat = new THREE.MeshPhongMaterial( { color: COLORS.normal, specular: 0x111111, shiness: 20 });
        var mesh = new THREE.Mesh( geo, mat );
        mesh.position.x = x*200;
        mesh.position.y = y*50/2;
        mesh.position.z = z*200;
        mesh.receiveShadow = true;
        mesh.castShadow = true;
        scene.add( mesh );
    }

    /**
     *
     * @param x
     * @param z
     * @param scene
     * @param type
     */
    function addHexagonalGround(x,z, scene, type){
        var geo = getHexaPlaneGeometry();
        var mat = new THREE.MeshPhongMaterial( { color: type===TYPES.water?COLORS.water:COLORS.normal, specular: 0x111111, shiness: 20 });
        var mesh = new THREE.Mesh( geo, mat );
        var width = 100;
        var height = Math.sqrt(3)/2 * width;

        mesh.rotation.x = - Math.PI / 2;
        mesh.position.x = x*150;

        if(isEven(x)){
            mesh.position.z = z*height*2-height/2;
        }else{
            mesh.position.z = z*height*2+height/2;
        }

        mesh.receiveShadow = true;
        mesh.castShadow = true;
        //set custom properties
        mesh.ox = x;
        mesh.oz = z;
        mesh.type = type;
        scene.add( mesh );
    }

    function isEven(num){
        return num%2 === 0;
    }

    /**
     *
     * @param x
     * @param z
     * @param scene
     * @param type
     */
    function addPlaneGround(x,z, scene, type){
        var geo = new THREE.PlaneGeometry( 200, 200);
        var color = type===TYPES.water?COLORS.water:COLORS.normal;
        var mat = new THREE.MeshPhongMaterial( {color: color, specular: 0x111111, shiness: 0 });
        var mesh = new THREE.Mesh( geo, mat );
        mesh.position.x = x*200;
        mesh.position.y = 1;
        mesh.position.z = z*200;
        mesh.rotation.x = - Math.PI / 2;
        mesh.receiveShadow = true;
        mesh.castShadow = true;
        scene.add( mesh );
    }

    /**
     *
     * @param x
     * @param z
     * @param entity
     * @param scene
     */
    function addSprite(x,z,y,entity,scene){
        var texture = THREE.ImageUtils.loadTexture( 'textures/' + entity.type + '.png' );
        var crateMaterial = new THREE.SpriteMaterial( { map: texture, useScreenCoordinates: false } );
        var sprite2 = new THREE.Sprite( crateMaterial );
        sprite2.position.x = x*200;
        sprite2.position.z = z*200;
        sprite2.position.y = y*50+49;
        sprite2.scale.set( 200, 200, 1.0 ); // imageWidth, imageHeight
        scene.add( sprite2 );
    }

    /**
     *
     * @param x
     * @param z
     * @param h
     * @param mesh
     * @param scene
     */
    function setHeight(x,z,h,mesh, scene){
        scene.remove( mesh );
        if(h==0||h=="0"){
            pengine.sceneBuilder.addPlaneGround(x, z, scene, "earth");
        }else{
            pengine.sceneBuilder.addBox(x, h, z,  scene );
        }
    }

    /**
     *
     * @param scene
     * @return {THREE.Scene}
     */
    function createScene(scene){
        scene = new THREE.Scene();
        scene.fog = new THREE.Fog( 0xcce0ff, 500, 10000 );
        return scene;
    }

    /**
     * NOT USED
     * @param scene
     */
    function createGround(scene){
        var initColor = new THREE.Color( 0x497f13 );
        var initTexture = THREE.ImageUtils.generateDataTexture( 1, 1, initColor );

        var groundMaterial = new THREE.MeshPhongMaterial( { color: 0xffffff, specular: 0x111111, map: initTexture } );
        var groundTexture = THREE.ImageUtils.loadTexture( "../examples/textures/terrain/grasslight-big.jpg", undefined, function() { groundMaterial.map = groundTexture } );

        groundTexture.wrapS = groundTexture.wrapT = THREE.RepeatWrapping;
        groundTexture.repeat.set( 25, 25 );
        groundTexture.anisotropy = 16;

        var mesh = new THREE.Mesh( new THREE.PlaneGeometry( 20000, 20000 ), groundMaterial );
        mesh.position.y = 0;
        mesh.rotation.x = - Math.PI / 2;
        mesh.receiveShadow = true;
        scene.add( mesh );
    }

    return {
        drawBoxes:drawBoxes,
        drawHexas:drawHexagons,
        drawEntities:drawEntities,
        addPlaneGround:addPlaneGround,
        addHexaPlaneGround:addHexagonalGround,
        addBox:addBox,
        setHeight:setHeight,
        createScene:createScene,
        createGround:createGround
    }
}();
})();<|endoftext|>


<commit_before>(function (vc, vm) {

    vc.extends({
        data: {
            editInspectionPlanInfo: {
                inspectionPlanId: '',
                inspectionPlanName: '',
                inspectionRouteId: '',
                inspectionPlanPeriod: '',
                staffId: '',
                staffName: '',
                startTime: '',
                endTime: '',
                signType: '',
                signTypes:[],
                inspectionPlanPeriods: [],
                states: [],
                isDefault:'',
                state: '',
                remark: '',
                companyId:'',
                companyName:'',
                departmentId:'',
                departmentName:'',
                createUserId:'',
                createUserName:''
            }
        },
        _initMethod: function () {
            vc.getDict('inspection_plan',"sign_type",function(_data){
                vc.component.editInspectionPlanInfo.signTypes = _data;
            });
            vc.getDict('inspection_plan',"inspection_plan_period",function(_data){
                vc.component.editInspectionPlanInfo.inspectionPlanPeriods = _data;
            });
            vc.getDict('inspection_plan',"state",function(_data){
                vc.component.editInspectionPlanInfo.states = _data;
            });

        },
        _initEvent: function () {
            vc.component._initEditInspectionPlanDateInfo();
            vc.on('editInspectionPlan', 'openEditInspectionPlanModal', function (_params) {
                vc.component.refreshEditInspectionPlanInfo();
                $('#editInspectionPlanModel').modal('show');
                vc.copyObject(_params, vc.component.editInspectionPlanInfo);
                vc.component.editInspectionPlanInfo.communityId = vc.getCurrentCommunity().communityId;
                //公司select2
                vc.emit('editInspectionPlan', 'orgSelect2', 'setOrg', {
                    orgId: vc.component.editInspectionPlanInfo.companyId,
                    orgName: vc.component.editInspectionPlanInfo.companyName,
                });

                //部门select2
                vc.emit('editInspectionPlan', 'departmentSelect2', 'setDepartment', {
                    orgId: vc.component.editInspectionPlanInfo.departmentId,
                    orgName: vc.component.editInspectionPlanInfo.departmentName,
                });

                //员工select2
                vc.emit('editInspectionPlan', 'staffSelect2', 'setStaff', {
                    staffId: vc.component.editInspectionPlanInfo.staffId,
                    staffName: vc.component.editInspectionPlanInfo.staffName,
                });

            });
        },
        methods: {
            editInspectionPlanValidate: function () {
                return vc.validate.validate({
                    editInspectionPlanInfo: vc.component.editInspectionPlanInfo
                }, {
                    'editInspectionPlanInfo.inspectionPlanName': [
                        {
                            limit: "required",
                            param: "",
                            errInfo: "计划名称不能为空"
                        },
                        {
                            limit: "maxin",
                            param: "1,100",
                            errInfo: "巡检计划名称不能超过100位"
                        },
                    ],
                    'editInspectionPlanInfo.inspectionRouteId': [
                        {
                            limit: "required",
                            param: "",
                            errInfo: "巡检路线不能为空"
                        },
                        {
                            limit: "maxin",
                            param: "1,30",
                            errInfo: "巡检路线不能超过30位"
                        },
                    ],
                    'editInspectionPlanInfo.inspectionPlanPeriod': [
                        {
                            limit: "required",
                            param: "",
                            errInfo: "执行周期不能为空"
                        },
                        {
                            limit: "maxin",
                            param: "1,12",
                            errInfo: "执行周期格式错误"
                        },
                    ],
                    'editInspectionPlanInfo.staffId': [
                        {
                            limit: "required",
                            param: "",
                            errInfo: "执行人员不能为空"
                        },
                        {
                            limit: "maxin",
                            param: "1,30",
                            errInfo: "执行人员不能超过30位"
                        },
                    ],
                    'editInspectionPlanInfo.startTime': [
                        {
                            limit: "required",
                            param: "",
                            errInfo: "开始时间不能为空"
                        },
                        {
                            limit: "dateTime",
                            param: "",
                            errInfo: "计计划开始时间不是有效的时间格式"
                        },
                    ],
                    'editInspectionPlanInfo.endTime': [
                        {
                            limit: "required",
                            param: "",
                            errInfo: "结束时间不能为空"
                        },
                        {
                            limit: "dateTime",
                            param: "",
                            errInfo: "计划结束时间不是有效的时间格式"
                        },
                    ],
                    'editInspectionPlanInfo.signType': [
                        {
                            limit: "required",
                            param: "",
                            errInfo: "签到方式不能为空"
                        },
                        {
                            limit: "num",
                            param: "",
                            errInfo: "签到方式格式错误"
                        },
                    ],
                    'editInspectionPlanInfo.state': [
                        {
                            limit: "required",
                            param: "",
                            errInfo: "状态不能为空"
                        },
                        {
                            limit: "num",
                            param: "",
                            errInfo: "签到方式格式错误"
                        },
                    ],
                    'editInspectionPlanInfo.remark': [
                        {
                            limit: "maxLength",
                            param: "200",
                            errInfo: "备注信息不能超过200位"
                        },
                    ],
                    'editInspectionPlanInfo.inspectionPlanId': [
                        {
                            limit: "required",
                            param: "",
                            errInfo: "巡检计划名称不能为空"
                        }]

                });
            },
            editInspectionPlan: function () {
                if (!vc.component.editInspectionPlanValidate()) {
                    vc.toast(vc.validate.errInfo);
                    return;
                }

                vc.http.post(
                    'editInspectionPlan',
                    'update',
                    JSON.stringify(vc.component.editInspectionPlanInfo),
                    {
                        emulateJSON: true
                    },
                    function (json, res) {
                        //vm.menus = vm.refreshMenuActive(JSON.parse(json),0);
                        if (res.status == 200) {
                            //关闭model
                            $('#editInspectionPlanModel').modal('hide');
                            vc.emit('inspectionPlanManage', 'listInspectionPlan', {});
                            return;
                        }
                        vc.message(json);
                    },
                    function (errInfo, error) {
                        console.log('请求失败处理');

                        vc.message(errInfo);
                    });
            },
            refreshEditInspectionPlanInfo: function () {
                var signTypes = vc.component.editInspectionPlanInfo.signTypes;
                var states = vc.component.editInspectionPlanInfo.states;
                var inspectionPlanPeriods = vc.component.editInspectionPlanInfo.inspectionPlanPeriods;
                vc.component.editInspectionPlanInfo = {
                    inspectionPlanId: '',
                    inspectionPlanName: '',
                    inspectionRouteId: '',
                    inspectionPlanPeriod: '',
                    staffId: '',
                    staffName: '',
                    startTime: '',
                    endTime: '',
                    signType: '',
                    state: '',
                    remark: '',
                    companyId:'',
                    companyName:'',
                    departmentId:'',
                    departmentName:'',
                    createUserId:'',
                    createUserName:''
                };
                vc.component.editInspectionPlanInfo.signTypes = signTypes;
                vc.component.editInspectionPlanInfo.states = states;
                vc.component.editInspectionPlanInfo.inspectionPlanPeriods = inspectionPlanPeriods;
            },
            _initEditInspectionPlanDateInfo:function(){
                $('.editInspectionPlanStartTime').datetimepicker({
                    language: 'zh-CN',
                    format: 'yyyy-mm-dd hh:ii:ss',
                    initTime: true,
                    initialDate: new Date(),
                    autoClose: 1,
                    todayBtn: true

                });
                $('.editInspectionPlanStartTime').datetimepicker()
                    .on('changeDate', function (ev) {
                        var value = $(".editInspectionPlanStartTime").val();
                        vc.component.editInspectionPlanInfo.startTime = value;
                    });
                $('.editInspectionPlanEndTime').datetimepicker({
                    language: 'zh-CN',
                    format: 'yyyy-mm-dd hh:ii:ss',
                    initTime: true,
                    initialDate: new Date(),
                    autoClose: 1,
                    todayBtn: true
                });
                $('.editInspectionPlanEndTime').datetimepicker()
                    .on('changeDate', function (ev) {
                        var value = $(".editInspectionPlanEndTime").val();
                        vc.component.editInspectionPlanInfo.endTime = value;
                    });
            }
        }
    });

})(window.vc, window.vc.component);
<commit_msg>优化巡检计划前端组件<commit_after>(function (vc, vm) {

    vc.extends({
        data: {
            editInspectionPlanInfo: {
                inspectionPlanId: '',
                inspectionPlanName: '',
                inspectionRouteId: '',
                inspectionPlanPeriod: '',
                staffId: '',
                staffName: '',
                startTime: '',
                endTime: '',
                signType: '',
                signTypes:[],
                inspectionPlanPeriods: [],
                states: [],
                isDefault:'',
                state: '',
                remark: '',
                companyId:'',
                companyName:'',
                departmentId:'',
                departmentName:'',
                createUserId:'',
                createUserName:''
            }
        },
        _initMethod: function () {
            vc.getDict('inspection_plan',"sign_type",function(_data){
                vc.component.editInspectionPlanInfo.signTypes = _data;
            });
            vc.getDict('inspection_plan',"inspection_plan_period",function(_data){
                vc.component.editInspectionPlanInfo.inspectionPlanPeriods = _data;
            });
            vc.getDict('inspection_plan',"state",function(_data){
                vc.component.editInspectionPlanInfo.states = _data;
            });

        },
        _initEvent: function () {
            vc.component._initEditInspectionPlanDateInfo();
            vc.on('editInspectionPlan', 'openEditInspectionPlanModal', function (_params) {
                vc.component.refreshEditInspectionPlanInfo();
                vc.copyObject(_params, vc.component.editInspectionPlanInfo);
                vc.component.editInspectionPlanInfo.communityId = vc.getCurrentCommunity().communityId;
                //公司select2
                vc.emit('editInspectionPlan', 'orgSelect2', 'setOrg', {
                    orgId: vc.component.editInspectionPlanInfo.companyId,
                    orgName: vc.component.editInspectionPlanInfo.companyName,
                });

                //部门select2
                vc.emit('editInspectionPlan', 'departmentSelect2', 'setDepartment', {
                    departmentId: vc.component.editInspectionPlanInfo.departmentId,
                    departmentName: vc.component.editInspectionPlanInfo.departmentName,
                });

                //员工select2
                vc.emit('editInspectionPlan', 'staffSelect2', 'setStaff', {
                    staffId: vc.component.editInspectionPlanInfo.staffId,
                    staffName: vc.component.editInspectionPlanInfo.staffName,
                });

                $('#editInspectionPlanModel').modal('show');

            });
        },
        methods: {
            editInspectionPlanValidate: function () {
                return vc.validate.validate({
                    editInspectionPlanInfo: vc.component.editInspectionPlanInfo
                }, {
                    'editInspectionPlanInfo.inspectionPlanName': [
                        {
                            limit: "required",
                            param: "",
                            errInfo: "计划名称不能为空"
                        },
                        {
                            limit: "maxin",
                            param: "1,100",
                            errInfo: "巡检计划名称不能超过100位"
                        },
                    ],
                    'editInspectionPlanInfo.inspectionRouteId': [
                        {
                            limit: "required",
                            param: "",
                            errInfo: "巡检路线不能为空"
                        },
                        {
                            limit: "maxin",
                            param: "1,30",
                            errInfo: "巡检路线不能超过30位"
                        },
                    ],
                    'editInspectionPlanInfo.inspectionPlanPeriod': [
                        {
                            limit: "required",
                            param: "",
                            errInfo: "执行周期不能为空"
                        },
                        {
                            limit: "maxin",
                            param: "1,12",
                            errInfo: "执行周期格式错误"
                        },
                    ],
                    'editInspectionPlanInfo.staffId': [
                        {
                            limit: "required",
                            param: "",
                            errInfo: "执行人员不能为空"
                        },
                        {
                            limit: "maxin",
                            param: "1,30",
                            errInfo: "执行人员不能超过30位"
                        },
                    ],
                    'editInspectionPlanInfo.startTime': [
                        {
                            limit: "required",
                            param: "",
                            errInfo: "开始时间不能为空"
                        },
                        {
                            limit: "dateTime",
                            param: "",
                            errInfo: "计计划开始时间不是有效的时间格式"
                        },
                    ],
                    'editInspectionPlanInfo.endTime': [
                        {
                            limit: "required",
                            param: "",
                            errInfo: "结束时间不能为空"
                        },
                        {
                            limit: "dateTime",
                            param: "",
                            errInfo: "计划结束时间不是有效的时间格式"
                        },
                    ],
                    'editInspectionPlanInfo.signType': [
                        {
                            limit: "required",
                            param: "",
                            errInfo: "签到方式不能为空"
                        },
                        {
                            limit: "num",
                            param: "",
                            errInfo: "签到方式格式错误"
                        },
                    ],
                    'editInspectionPlanInfo.state': [
                        {
                            limit: "required",
                            param: "",
                            errInfo: "状态不能为空"
                        },
                        {
                            limit: "num",
                            param: "",
                            errInfo: "签到方式格式错误"
                        },
                    ],
                    'editInspectionPlanInfo.remark': [
                        {
                            limit: "maxLength",
                            param: "200",
                            errInfo: "备注信息不能超过200位"
                        },
                    ],
                    'editInspectionPlanInfo.inspectionPlanId': [
                        {
                            limit: "required",
                            param: "",
                            errInfo: "巡检计划名称不能为空"
                        }]

                });
            },
            editInspectionPlan: function () {
                if (!vc.component.editInspectionPlanValidate()) {
                    vc.toast(vc.validate.errInfo);
                    return;
                }

                vc.http.post(
                    'editInspectionPlan',
                    'update',
                    JSON.stringify(vc.component.editInspectionPlanInfo),
                    {
                        emulateJSON: true
                    },
                    function (json, res) {
                        //vm.menus = vm.refreshMenuActive(JSON.parse(json),0);
                        if (res.status == 200) {
                            //关闭model
                            $('#editInspectionPlanModel').modal('hide');
                            vc.emit('inspectionPlanManage', 'listInspectionPlan', {});
                            return;
                        }
                        vc.message(json);
                    },
                    function (errInfo, error) {
                        console.log('请求失败处理');

                        vc.message(errInfo);
                    });
            },
            refreshEditInspectionPlanInfo: function () {
                var signTypes = vc.component.editInspectionPlanInfo.signTypes;
                var states = vc.component.editInspectionPlanInfo.states;
                var inspectionPlanPeriods = vc.component.editInspectionPlanInfo.inspectionPlanPeriods;
                vc.component.editInspectionPlanInfo = {
                    inspectionPlanId: '',
                    inspectionPlanName: '',
                    inspectionRouteId: '',
                    inspectionPlanPeriod: '',
                    staffId: '',
                    staffName: '',
                    startTime: '',
                    endTime: '',
                    signType: '',
                    state: '',
                    remark: '',
                    companyId:'',
                    companyName:'',
                    departmentId:'',
                    departmentName:'',
                    createUserId:'',
                    createUserName:''
                };
                vc.component.editInspectionPlanInfo.signTypes = signTypes;
                vc.component.editInspectionPlanInfo.states = states;
                vc.component.editInspectionPlanInfo.inspectionPlanPeriods = inspectionPlanPeriods;
            },
            _initEditInspectionPlanDateInfo:function(){
                $('.editInspectionPlanStartTime').datetimepicker({
                    language: 'zh-CN',
                    format: 'yyyy-mm-dd hh:ii:ss',
                    initTime: true,
                    initialDate: new Date(),
                    autoClose: 1,
                    todayBtn: true

                });
                $('.editInspectionPlanStartTime').datetimepicker()
                    .on('changeDate', function (ev) {
                        var value = $(".editInspectionPlanStartTime").val();
                        vc.component.editInspectionPlanInfo.startTime = value;
                    });
                $('.editInspectionPlanEndTime').datetimepicker({
                    language: 'zh-CN',
                    format: 'yyyy-mm-dd hh:ii:ss',
                    initTime: true,
                    initialDate: new Date(),
                    autoClose: 1,
                    todayBtn: true
                });
                $('.editInspectionPlanEndTime').datetimepicker()
                    .on('changeDate', function (ev) {
                        var value = $(".editInspectionPlanEndTime").val();
                        vc.component.editInspectionPlanInfo.endTime = value;
                    });
            }
        }
    });

})(window.vc, window.vc.component);
<|endoftext|>


<commit_before>define('app/views/script_add', ['app/views/controlled'],
    //
    //  Script Add View
    //
    //  @returns Class
    //
    function (ControlledComponent) {

        'use strict';

        var DEFAULT_URL = 'http://';
        var DEFAULT_GITHUB_URL = 'https://github.com/owner/repo';
        var DEFAULT_SCRIPT = '#!/bin/bash\necho "hello world"';
        var DEFAULT_ANSIBLE_SCRIPT = '- name: Dummy ansible playbook\n' +
            '   hosts: localhost\n' +
            '   tasks:\n' +
            '    - name: Dummy task\n' +
            '      debug:\n' +
            '        msg: "Hello World"\n';

        return App.ScriptAddComponent = ControlledComponent.extend({

            //
            //  Properties
            //

            layoutName: 'script_add',
            controllerName: 'scriptAddController',

            scriptTypes: [{
                label: 'Ansible Playbook',
                value: 'ansible'
            }, {
                label: 'Executable',
                value: 'executable'
            }],

            scriptSources: [{
                label: 'Github',
                value: 'github'
            }, {
                label: 'URL',
                value: 'url',
            }, {
                label: 'Inline',
                value: 'inline'
            }],

            //
            //  Computed Properties
            //

            isReady: function () {
                var script = Mist.scriptAddController.get('newScript');
                var name = script.get('name');
                var type = script.get('type');
                var source = script.get('source');
                if (!type || !source || !name)
                    return false;
                if (source.value == 'inline')
                    return script.get('script');
                return script.get('url');
            }.property(
                'Mist.scriptAddController.newScript.name',
                'Mist.scriptAddController.newScript.source',
                'Mist.scriptAddController.newScript.type',
                'Mist.scriptAddController.newScript.url',
                'Mist.scriptAddController.newScript.script'
            ),

            isInline: function(){
                return Mist.scriptAddController.newScript.source.value == 'inline';
            }.property('Mist.scriptAddController.newScript.source'),

            isURL: function(){
                return Mist.scriptAddController.newScript.source.value == 'url';
            }.property('Mist.scriptAddController.newScript.source'),

            isGitHub: function(){
                return Mist.scriptAddController.newScript.source.value == 'github';
            }.property('Mist.scriptAddController.newScript.source'),

            load: function () {
               Ember.run.next(function(){
                   $( "#add-script" ).collapsible({
                       expand: function(event, ui) {
                           Mist.scriptAddController.open();

                           var id = $(this).attr('id'),
                           overlay = id ? $('#' + id+'-overlay') : false;
                           if (overlay) {
                               overlay.removeClass('ui-screen-hidden').addClass('in');
                           }
                           $(this).children().next().hide();
                           $(this).children().next().slideDown(250);
                       }
                   });
               });
            }.on('didInsertElement'),

            unload: function () {
               Ember.run.next(function(){
                   $( "#add-script" ).collapsible({
                       collapse: function(event, ui) {
                           Mist.scriptAddController.close();

                           $(this).children().next().slideUp(250);
                           var id = $(this).attr('id'),
                           overlay = id ? $('#' + id+'-overlay') : false;
                           if (overlay) {
                               overlay.removeClass('in').addClass('ui-screen-hidden');
                           }
                       }
                   });
               });
            }.on('willDestroyElement'),

            //
            //  Methods
            //

            clear: function () {
                this.closeTypeSelect();
                this.closeSourceSelect();
            },

            selectType: function (type) {
                this.closeTypeSelect();
                Mist.scriptAddController.get('newScript').set('type', type);
                this.setScript();
            },

            setScript: function () {
                var newScript = Mist.scriptAddController.get('newScript');
                var type = newScript.get('type');
                if (type.value == 'ansible')
                    newScript.set('script', DEFAULT_ANSIBLE_SCRIPT);
                if (type.value == 'executable')
                    newScript.set('script', DEFAULT_SCRIPT);
            },

            selectSource: function (source) {
                this.closeSourceSelect();
                this.showSourceBundle(source);
                var newScript = Mist.scriptAddController.get('newScript');
                newScript.set('source', source);
                if (source.value == 'url')
                    newScript.set('url', DEFAULT_URL);
                if (source.value == 'github')
                    newScript.set('url', DEFAULT_GITHUB_URL);
                if (source.value == 'inline')
                    this.setScript();

                Ember.run.next(function(){
                    $('body').enhanceWithin();
                });
            },

            closeTypeSelect: function () {
                this.$('#script-add-type .mist-select').collapsible('collapse');
            },

            closeSourceSelect: function () {
                this.$('#script-add-source .mist-select').collapsible('collapse');
            },

            showSourceBundle: function (source) {
                this.$('.'+source.value).slideDown();
                this.$('#script-add-description').slideDown();
            },

            //
            //  Actions
            //

            actions: {
                clickOverlay: function() {
                    $('#add-script').collapsible('collapse');
                },

                selectType: function (type) {
                    this.selectType(type);
                },

                selectSource: function (source) {
                    this.selectSource(source);
                },

                backClicked: function () {
                    Mist.scriptAddController.close();
                },

                addClicked: function () {
                    Mist.scriptAddController.add();
                }
            },
        });
    }
);
<commit_msg>minor fix in the format of the example ansible script<commit_after>define('app/views/script_add', ['app/views/controlled'],
    //
    //  Script Add View
    //
    //  @returns Class
    //
    function (ControlledComponent) {

        'use strict';

        var DEFAULT_URL = 'http://';
        var DEFAULT_GITHUB_URL = 'https://github.com/owner/repo';
        var DEFAULT_SCRIPT = '#!/bin/bash\necho "hello world"';
        var DEFAULT_ANSIBLE_SCRIPT = '- name: Dummy ansible playbook\n' +
            '  hosts: localhost\n' +
            '  tasks:\n' +
            '    - name: Dummy task\n' +
            '      debug:\n' +
            '        msg: "Hello World"\n';

        return App.ScriptAddComponent = ControlledComponent.extend({

            //
            //  Properties
            //

            layoutName: 'script_add',
            controllerName: 'scriptAddController',

            scriptTypes: [{
                label: 'Ansible Playbook',
                value: 'ansible'
            }, {
                label: 'Executable',
                value: 'executable'
            }],

            scriptSources: [{
                label: 'Github',
                value: 'github'
            }, {
                label: 'URL',
                value: 'url',
            }, {
                label: 'Inline',
                value: 'inline'
            }],

            //
            //  Computed Properties
            //

            isReady: function () {
                var script = Mist.scriptAddController.get('newScript');
                var name = script.get('name');
                var type = script.get('type');
                var source = script.get('source');
                if (!type || !source || !name)
                    return false;
                if (source.value == 'inline')
                    return script.get('script');
                return script.get('url');
            }.property(
                'Mist.scriptAddController.newScript.name',
                'Mist.scriptAddController.newScript.source',
                'Mist.scriptAddController.newScript.type',
                'Mist.scriptAddController.newScript.url',
                'Mist.scriptAddController.newScript.script'
            ),

            isInline: function(){
                return Mist.scriptAddController.newScript.source.value == 'inline';
            }.property('Mist.scriptAddController.newScript.source'),

            isURL: function(){
                return Mist.scriptAddController.newScript.source.value == 'url';
            }.property('Mist.scriptAddController.newScript.source'),

            isGitHub: function(){
                return Mist.scriptAddController.newScript.source.value == 'github';
            }.property('Mist.scriptAddController.newScript.source'),

            load: function () {
               Ember.run.next(function(){
                   $( "#add-script" ).collapsible({
                       expand: function(event, ui) {
                           Mist.scriptAddController.open();

                           var id = $(this).attr('id'),
                           overlay = id ? $('#' + id+'-overlay') : false;
                           if (overlay) {
                               overlay.removeClass('ui-screen-hidden').addClass('in');
                           }
                           $(this).children().next().hide();
                           $(this).children().next().slideDown(250);
                       }
                   });
               });
            }.on('didInsertElement'),

            unload: function () {
               Ember.run.next(function(){
                   $( "#add-script" ).collapsible({
                       collapse: function(event, ui) {
                           Mist.scriptAddController.close();

                           $(this).children().next().slideUp(250);
                           var id = $(this).attr('id'),
                           overlay = id ? $('#' + id+'-overlay') : false;
                           if (overlay) {
                               overlay.removeClass('in').addClass('ui-screen-hidden');
                           }
                       }
                   });
               });
            }.on('willDestroyElement'),

            //
            //  Methods
            //

            clear: function () {
                this.closeTypeSelect();
                this.closeSourceSelect();
            },

            selectType: function (type) {
                this.closeTypeSelect();
                Mist.scriptAddController.get('newScript').set('type', type);
                this.setScript();
            },

            setScript: function () {
                var newScript = Mist.scriptAddController.get('newScript');
                var type = newScript.get('type');
                if (type.value == 'ansible')
                    newScript.set('script', DEFAULT_ANSIBLE_SCRIPT);
                if (type.value == 'executable')
                    newScript.set('script', DEFAULT_SCRIPT);
            },

            selectSource: function (source) {
                this.closeSourceSelect();
                this.showSourceBundle(source);
                var newScript = Mist.scriptAddController.get('newScript');
                newScript.set('source', source);
                if (source.value == 'url')
                    newScript.set('url', DEFAULT_URL);
                if (source.value == 'github')
                    newScript.set('url', DEFAULT_GITHUB_URL);
                if (source.value == 'inline')
                    this.setScript();

                Ember.run.next(function(){
                    $('body').enhanceWithin();
                });
            },

            closeTypeSelect: function () {
                this.$('#script-add-type .mist-select').collapsible('collapse');
            },

            closeSourceSelect: function () {
                this.$('#script-add-source .mist-select').collapsible('collapse');
            },

            showSourceBundle: function (source) {
                this.$('.'+source.value).slideDown();
                this.$('#script-add-description').slideDown();
            },

            //
            //  Actions
            //

            actions: {
                clickOverlay: function() {
                    $('#add-script').collapsible('collapse');
                },

                selectType: function (type) {
                    this.selectType(type);
                },

                selectSource: function (source) {
                    this.selectSource(source);
                },

                backClicked: function () {
                    Mist.scriptAddController.close();
                },

                addClicked: function () {
                    Mist.scriptAddController.add();
                }
            },
        });
    }
);
<|endoftext|>


<commit_before>/* global define: false, module: false */
(function (mod) {
  'use strict';
  if (typeof module === 'object' && module.exports) { // CommonJS
    module.exports = mod();
    return;
  }
  if (typeof define === 'function' && define.amd) { // AMD
    define(mod);
    return;
  }
  var global = Function('return this;')(); // eslint-disable-line no-new-func
  global.scopify = mod(); // Global
}(function () {

  'use strict';

  var isNumber = function (value) {
    // eslint-disable-next-line no-self-compare
    return typeof value === 'number' && value === value;
  };

  var isBoolean = function (value) {
    return typeof value === 'boolean';
  };

  var isObject = function (value) {
    return value && typeof value === 'object';
  };

  var flatten = function (array) {
    return Array.prototype.concat.apply([], array);
  };

  var contains = function (list, element) {
    return Array.prototype.indexOf.call(list, element) > -1;
  };

  var scopify = function (walk, ast, topScope, options) {
    options = isObject(options) ? options : {};

    var charOffset = isNumber(options.charOffset) ? options.charOffset : 0;
    var blockScope = isBoolean(options.blockScope) ? options.blockScope : false;

    var getLevel = function (scope) {
      if (scope.level === undefined) {
        if (scope.prev) {
          scope.level = getLevel(scope.prev);
          if (blockScope || !scope.isBlock) {
            scope.level += 1;
          }
        } else {
          scope.level = 0;
        }
      }
      return scope.level;
    };

    var getEnclosingScope = function (nodes) {
      var enclosingScope;
      for (var i = nodes.length - 1; i >= 0; i -= 1) {
        var node = nodes[i];
        if (node.scope) {
          enclosingScope = node.scope;
          break;
        }
      }
      if (!enclosingScope) {
        enclosingScope = topScope;
      }
      return enclosingScope;
    };

    var dynamicallyBound = [
      'arguments',
      'this',
      'super',
      'new'
    ];
    var dynamicallyBinding = [
      'FunctionDeclaration',
      'FunctionExpression',
      'MethodDefinition'
    ];
    var getDefiningScope = function (scope, name) {
      var definingScope;
      for (;;) {
        var type;
        if (scope.originNode) {
          type = scope.originNode.type;
        }
        if (contains(Object.keys(scope.props), name) ||
            (contains(dynamicallyBound, name) &&
             contains(dynamicallyBinding, type))) {
          definingScope = scope;
          break;
        }
        if (scope.name === '<top>') {
          break;
        }
        scope = scope.prev;
        if (!scope) {
          scope = topScope;
        }
      }
      return definingScope;
    };

    // Scopes and the things inside them are recorded separately, because it
    // will be faster to color all the scopes and then all of their things.
    var scopes = [];
    var identifiers = [];

    var scopeHandler = function (node) {
      scopes.push([
        node.start + charOffset,
        node.end + charOffset,
        node.scope ? getLevel(node.scope) : getLevel(topScope)
      ]);
    };

    var identifierHandler = function (node, ancestors) {
      var level = 0;
      var enclosingScope = getEnclosingScope(ancestors);
      if (enclosingScope) {
        var name;
        if (node.type === 'ThisExpression') {
          name = 'this';
        } else if (node.type === 'Super') {
          name = 'super';
        } else {
          name = node.name;
        }
        var definingScope = getDefiningScope(enclosingScope, name);
        if (definingScope) {
          level = getLevel(definingScope);
        }
      }
      identifiers.push(
        node.start + charOffset,
        node.end + charOffset,
        level
      );
    };

    var importSpecifierHandler = function (node, ancestors) {
      identifierHandler(node.local, ancestors);
    };

    var metaPropertyHandler = function (node, ancestors) {
      if (node.meta.name === 'new') {
        identifierHandler(node.meta, ancestors);
      }
    };

    walk.ancestor(ast, {
      ArrowFunctionExpression: scopeHandler,
      BlockStatement: scopeHandler,
      CatchClause: scopeHandler,
      FunctionDeclaration: scopeHandler,
      FunctionExpression: scopeHandler,
      Identifier: identifierHandler,
      ImportDefaultSpecifier: importSpecifierHandler,
      ImportNamespaceSpecifier: importSpecifierHandler,
      MetaProperty: metaPropertyHandler,
      Program: scopeHandler,
      Super: identifierHandler,
      ThisExpression: identifierHandler,
      VariablePattern: identifierHandler
    });

    // Sort the scopes by their levels, since the inner scopes will be colored
    // on top of the outer scopes.
    scopes.sort(function (a, b) {
      return a[2] - b[2];
    });

    return [].concat(
      flatten(scopes),
      identifiers
    );
  };

  return scopify;

}));
<commit_msg>Rename "contains" to "includes".<commit_after>/* global define: false, module: false */
(function (mod) {
  'use strict';
  if (typeof module === 'object' && module.exports) { // CommonJS
    module.exports = mod();
    return;
  }
  if (typeof define === 'function' && define.amd) { // AMD
    define(mod);
    return;
  }
  var global = Function('return this;')(); // eslint-disable-line no-new-func
  global.scopify = mod(); // Global
}(function () {

  'use strict';

  var isNumber = function (value) {
    // eslint-disable-next-line no-self-compare
    return typeof value === 'number' && value === value;
  };

  var isBoolean = function (value) {
    return typeof value === 'boolean';
  };

  var isObject = function (value) {
    return value && typeof value === 'object';
  };

  var flatten = function (array) {
    return Array.prototype.concat.apply([], array);
  };

  var includes = function (list, element) {
    return Array.prototype.indexOf.call(list, element) > -1;
  };

  var scopify = function (walk, ast, topScope, options) {
    options = isObject(options) ? options : {};

    var charOffset = isNumber(options.charOffset) ? options.charOffset : 0;
    var blockScope = isBoolean(options.blockScope) ? options.blockScope : false;

    var getLevel = function (scope) {
      if (scope.level === undefined) {
        if (scope.prev) {
          scope.level = getLevel(scope.prev);
          if (blockScope || !scope.isBlock) {
            scope.level += 1;
          }
        } else {
          scope.level = 0;
        }
      }
      return scope.level;
    };

    var getEnclosingScope = function (nodes) {
      var enclosingScope;
      for (var i = nodes.length - 1; i >= 0; i -= 1) {
        var node = nodes[i];
        if (node.scope) {
          enclosingScope = node.scope;
          break;
        }
      }
      if (!enclosingScope) {
        enclosingScope = topScope;
      }
      return enclosingScope;
    };

    var dynamicallyBound = [
      'arguments',
      'this',
      'super',
      'new'
    ];
    var dynamicallyBinding = [
      'FunctionDeclaration',
      'FunctionExpression',
      'MethodDefinition'
    ];
    var getDefiningScope = function (scope, name) {
      var definingScope;
      for (;;) {
        var type;
        if (scope.originNode) {
          type = scope.originNode.type;
        }
        if (includes(Object.keys(scope.props), name) ||
            (includes(dynamicallyBound, name) &&
             includes(dynamicallyBinding, type))) {
          definingScope = scope;
          break;
        }
        if (scope.name === '<top>') {
          break;
        }
        scope = scope.prev;
        if (!scope) {
          scope = topScope;
        }
      }
      return definingScope;
    };

    // Scopes and the things inside them are recorded separately, because it
    // will be faster to color all the scopes and then all of their things.
    var scopes = [];
    var identifiers = [];

    var scopeHandler = function (node) {
      scopes.push([
        node.start + charOffset,
        node.end + charOffset,
        node.scope ? getLevel(node.scope) : getLevel(topScope)
      ]);
    };

    var identifierHandler = function (node, ancestors) {
      var level = 0;
      var enclosingScope = getEnclosingScope(ancestors);
      if (enclosingScope) {
        var name;
        if (node.type === 'ThisExpression') {
          name = 'this';
        } else if (node.type === 'Super') {
          name = 'super';
        } else {
          name = node.name;
        }
        var definingScope = getDefiningScope(enclosingScope, name);
        if (definingScope) {
          level = getLevel(definingScope);
        }
      }
      identifiers.push(
        node.start + charOffset,
        node.end + charOffset,
        level
      );
    };

    var importSpecifierHandler = function (node, ancestors) {
      identifierHandler(node.local, ancestors);
    };

    var metaPropertyHandler = function (node, ancestors) {
      if (node.meta.name === 'new') {
        identifierHandler(node.meta, ancestors);
      }
    };

    walk.ancestor(ast, {
      ArrowFunctionExpression: scopeHandler,
      BlockStatement: scopeHandler,
      CatchClause: scopeHandler,
      FunctionDeclaration: scopeHandler,
      FunctionExpression: scopeHandler,
      Identifier: identifierHandler,
      ImportDefaultSpecifier: importSpecifierHandler,
      ImportNamespaceSpecifier: importSpecifierHandler,
      MetaProperty: metaPropertyHandler,
      Program: scopeHandler,
      Super: identifierHandler,
      ThisExpression: identifierHandler,
      VariablePattern: identifierHandler
    });

    // Sort the scopes by their levels, since the inner scopes will be colored
    // on top of the outer scopes.
    scopes.sort(function (a, b) {
      return a[2] - b[2];
    });

    return [].concat(
      flatten(scopes),
      identifiers
    );
  };

  return scopify;

}));
<|endoftext|>


<commit_before>// Webpack
import webpack from 'webpack';

// Path
import path from 'path';

// // HTML Webpack plugin
// import HtmlWebpackPlugin from 'html-webpack-plugin';
//
// // Copy Webpack plugin
// import CopyWebpackPlugin from 'copy-webpack-plugin';

export default {
  entry: "./es6/main.js",//入口文件
  output: {//打包输出的文件
    path: __dirname,
    filename: "bundle.js"
  },
  module: {
    loaders: [
      {
				test: /\.handlebars$/,
				loader: 'handlebars-loader',
      },
      {
        //test: path.join(__dirname, 'es6'),
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
        query: {
          presets: ['es2015']
        }
      }
    ]
  },
  resolve: {// 现在你require文件的时候可以直接使用require('file')，不用使用require('file.coffee')
    extensions: ['', '.js', '.json']
  },
  node: {
    fs: 'empty'
  }
};
<commit_msg>更新配置信息，测试兼容性<commit_after>// Webpack
import webpack from 'webpack';

// Path
import path from 'path';

// HTML Webpack plugin
import HtmlWebpackPlugin from 'html-webpack-plugin';

// // Copy Webpack plugin
// import CopyWebpackPlugin from 'copy-webpack-plugin';

export default {
    entry: "./es6/main.js", //入口文件
    output: { //打包输出的文件
        // path: __dirname,
        // filename: "bundle.js"
        path: path.join(__dirname, 'dist'), //输出目录的配置，模板、样式、脚本、图片等资源的路径配置都相对于它
        //  publicPath: 'dist/', //模板、样式、脚本、图片等资源对应的server上的路径
        filename: 'js/[name].js', //每个页面对应的主js的生成配置
        chunkFilename: 'js/[id].chunk.js' // chunk生成的配置
    },
    module: {
        loaders: [{
            test: /\.handlebars$/,
            loader: 'handlebars-loader',
        }, {
            //test: path.join(__dirname, 'es6'),
            test: /\.js$/,
            exclude: /node_modules/,
            loader: 'babel-loader',
            query: {
                presets: ['es2015'],
                plugins: ['transform-runtime']
            }
        }]
    },
    resolve: { // 现在你require文件的时候可以直接使用require('file')，不用使用require('file.coffee')
        extensions: ['', '.js', '.json']
    },
    node: {
        fs: 'empty'
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: './index.html',
            filename: './index.html',
            chunks: ['main', 'vendor'],
            hash: true,
            minify: { //压缩HTML文件
                removeComments: true, //移除HTML中的注释
                collapseWhitespace: false //删除空白符与换行符
            }
        }),
        new webpack.ProvidePlugin({
            $: "jquery",
            jQuery: "jquery"
        }),
        new webpack.HotModuleReplacementPlugin(), //开启热替换插件
        new webpack.NoErrorsPlugin(),
    //    new webpack.optimize.CommonsChunkPlugin('vendor', 'vendor.bundle.js'), //这是妮第三方库打包生成的文件
        new webpack.optimize.UglifyJsPlugin({
            sourceMap: false,
            mangle: false,
            compress: {
                warnings: false
            }
        })
    ]
};
<|endoftext|>


<commit_before>/*
 * Simple jQuery Dialog
 * https://github.com/filamentgroup/dialog
 *
 * Copyright (c) 2013 Filament Group, Inc.
 * Author: @scottjehl
 * Licensed under the MIT, GPL licenses.
 */

(function( w, $ ){
	$.fn.dialog = function( transbg ){

		var pluginName = "dialog",
			cl = {
				open: pluginName + "-open",
				opened: pluginName + "-opened",
				content: pluginName + "-content",
				close: pluginName + "-close",
				closed: pluginName + "-closed",
				bkgd: pluginName + "-background",
				bkgdOpen: pluginName + "-background-open",
				bkgdTrans: pluginName + "-background-trans"
			},
			ev = {
				open: pluginName + "-open",
				close: pluginName + "-close"
			},
			nullHash = "dialog",
			doc = w.document,
			docElem = doc.documentElement,
			body = doc.body,
			$html = $( docElem ),
			$background = $( doc.createElement( 'div' ) ).addClass( cl.bkgd );

		w.Dialog = function( element ){
			this.$el = $( element );

			this.isOpen = false;
			this.positionMedia = this.$el.attr( 'data-set-position-media' );
		};

		w.Dialog.prototype.isSetScrollPosition = function() {
			return !this.positionMedia ||
				( w.matchMedia && w.matchMedia( this.positionMedia ).matches );
		};

		w.Dialog.prototype.open = function( e ) {
			$background[ 0 ].style.height = Math.max( docElem.scrollHeight, docElem.clientHeight ) + "px";
			this.$el.addClass( cl.open );
			$background.addClass( cl.bkgdOpen );

			if( this.isSetScrollPosition() ) {
				this.scroll = "pageYOffset" in w ? w.pageYOffset : ( docElem.scrollY || docElem.scrollTop || ( body && body.scrollY ) || 0 );
				this.$el[ 0 ].style.top = this.scroll + "px";
			} else {
				this.$el[ 0 ].style.top = '';
			}

			$html.addClass( cl.open );
			this.isOpen = true;

			location.hash = nullHash;

			if( doc.activeElement ){
				this.focused = doc.activeElement;
			}
			this.$el[ 0 ].focus();

			this.$el.trigger( cl.opened );
		};

		w.Dialog.prototype.close = function(){
			this.$el.removeClass( cl.open );

			$background.removeClass( cl.bkgdOpen );
			$html.removeClass( cl.open );

			if( this.focused ){
				this.focused.focus();
			}

			if( this.isSetScrollPosition() ) {
				w.scrollTo( 0, this.scroll );
			}

			this.isOpen = false;

			this.$el.trigger( cl.closed );
		};

		return this.each(function(){

			var $el = $( this ),
				positionMedia = $el.attr( 'data-set-position-media' ),
				scroll = 0,
				focused = null,
				isOpen = false,
				dialog = new w.Dialog( this );

			if( !transbg ){
				transbg = $el.is( '[data-transbg]' );
			}

			if( transbg ){
				$background.addClass( cl.bkgdTrans );
			}

			$background.appendTo( body );

			function isSetScrollPosition() {
				return dialog.isSetScrollPosition();
			}

			function open( e ){
				dialog.open( e );
			}

			function close(){
				dialog.close();
			}

			$el
				.addClass( cl.content )
				.attr( "role", "dialog" )
				.attr( "tabindex", 0 )
				.bind( ev.open, open )
				.bind( ev.close, close )
				.bind( "click", function( e ){
					if( $( e.target ).is( "." + cl.close ) ){
						w.history.back();
						e.preventDefault();
					}
				});

			$background.bind( "click", function( e ) {
				w.history.back();
			});

			// close on hashchange if open (supports back button closure)
			$( w ).bind( "hashchange", function( e ){
				var hash = w.location.hash.replace( "#", "" );

				if( hash !== nullHash && dialog.isOpen ){
					$el.trigger( ev.close );
				}
			});

			// open on matching a[href=#id] click
			$( doc ).bind( "click", function( e ){
				var $a = $( e.target ).closest( "a" );

				if( !dialog.isOpen && $a.length && $a.attr( "href" ) ){
					var $matchingDialog = $( $a.attr( "href" ) );
					if( $matchingDialog.length && $matchingDialog.is( $el ) ){
						$matchingDialog.trigger( ev.open );
						e.preventDefault();
					}
				}
			});

			// close on escape key
			$( doc )..bind( "keyup", function( e ){
				if( dialog.isOpen && e.which === 27 ){
					$el.trigger( ev.close );
				}
			});
		});
	};

	// auto-init
	$(function(){
		$( ".dialog" ).dialog();
	});
}( this, jQuery ));
<commit_msg>centralize open check for close<commit_after>/*
 * Simple jQuery Dialog
 * https://github.com/filamentgroup/dialog
 *
 * Copyright (c) 2013 Filament Group, Inc.
 * Author: @scottjehl
 * Licensed under the MIT, GPL licenses.
 */

(function( w, $ ){
	$.fn.dialog = function( transbg ){

		var pluginName = "dialog",
			cl = {
				open: pluginName + "-open",
				opened: pluginName + "-opened",
				content: pluginName + "-content",
				close: pluginName + "-close",
				closed: pluginName + "-closed",
				bkgd: pluginName + "-background",
				bkgdOpen: pluginName + "-background-open",
				bkgdTrans: pluginName + "-background-trans"
			},
			ev = {
				open: pluginName + "-open",
				close: pluginName + "-close"
			},
			nullHash = "dialog",
			doc = w.document,
			docElem = doc.documentElement,
			body = doc.body,
			$html = $( docElem ),
			$background = $( doc.createElement( 'div' ) ).addClass( cl.bkgd );

		w.Dialog = function( element ){
			this.$el = $( element );

			this.isOpen = false;
			this.positionMedia = this.$el.attr( 'data-set-position-media' );
		};

		w.Dialog.prototype.isSetScrollPosition = function() {
			return !this.positionMedia ||
				( w.matchMedia && w.matchMedia( this.positionMedia ).matches );
		};

		w.Dialog.prototype.open = function( e ) {
			$background[ 0 ].style.height = Math.max( docElem.scrollHeight, docElem.clientHeight ) + "px";
			this.$el.addClass( cl.open );
			$background.addClass( cl.bkgdOpen );

			if( this.isSetScrollPosition() ) {
				this.scroll = "pageYOffset" in w ? w.pageYOffset : ( docElem.scrollY || docElem.scrollTop || ( body && body.scrollY ) || 0 );
				this.$el[ 0 ].style.top = this.scroll + "px";
			} else {
				this.$el[ 0 ].style.top = '';
			}

			$html.addClass( cl.open );
			this.isOpen = true;

			location.hash = nullHash;

			if( doc.activeElement ){
				this.focused = doc.activeElement;
			}
			this.$el[ 0 ].focus();

			this.$el.trigger( cl.opened );
		};

		w.Dialog.prototype.close = function(){
			if( !this.isOpen ){
				return;
			}

			this.$el.removeClass( cl.open );

			$background.removeClass( cl.bkgdOpen );
			$html.removeClass( cl.open );

			if( this.focused ){
				this.focused.focus();
			}

			if( this.isSetScrollPosition() ) {
				w.scrollTo( 0, this.scroll );
			}

			this.isOpen = false;

			this.$el.trigger( cl.closed );
		};

		return this.each(function(){

			var $el = $( this ),
				positionMedia = $el.attr( 'data-set-position-media' ),
				scroll = 0,
				focused = null,
				isOpen = false,
				dialog = new w.Dialog( this );

			if( !transbg ){
				transbg = $el.is( '[data-transbg]' );
			}

			if( transbg ){
				$background.addClass( cl.bkgdTrans );
			}

			$background.appendTo( body );

			function isSetScrollPosition() {
				return dialog.isSetScrollPosition();
			}

			function open( e ){
				dialog.open( e );
			}

			function close(){
				dialog.close();
			}

			$el
				.addClass( cl.content )
				.attr( "role", "dialog" )
				.attr( "tabindex", 0 )
				.bind( ev.open, open )
				.bind( ev.close, close )
				.bind( "click", function( e ){
					if( $( e.target ).is( "." + cl.close ) ){
						w.history.back();
						e.preventDefault();
					}
				});

			$background.bind( "click", function( e ) {
				w.history.back();
			});

			// close on hashchange if open (supports back button closure)
			$( w ).bind( "hashchange", function( e ){
				var hash = w.location.hash.replace( "#", "" );

				if( hash !== nullHash ){
					$el.trigger( ev.close );
				}
			});

			// open on matching a[href=#id] click
			$( doc ).bind( "click", function( e ){
				var $a = $( e.target ).closest( "a" );

				if( !dialog.isOpen && $a.length && $a.attr( "href" ) ){
					var $matchingDialog = $( $a.attr( "href" ) );
					if( $matchingDialog.length && $matchingDialog.is( $el ) ){
						$matchingDialog.trigger( ev.open );
						e.preventDefault();
					}
				}
			});

			// close on escape key
			$( doc ).bind( "keyup", function( e ){
				if( e.which === 27 ){
					$el.trigger( ev.close );
				}
			});
		});
	};

	// auto-init
	$(function(){
		$( ".dialog" ).dialog();
	});
}( this, jQuery ));
<|endoftext|>


<commit_before>import * as path from 'path';

import webpack from 'webpack';
import HtmlWebpackPlugin from 'html-webpack-plugin';
import ExtractTextPlugin from 'extract-text-webpack-plugin';
import SystemBellPlugin from 'system-bell-webpack-plugin';
import CleanWebpackPlugin from 'clean-webpack-plugin';
import merge from 'webpack-merge';

import pkg from './package.json';

const TARGET = process.env.npm_lifecycle_event || '';
const ROOT_PATH = __dirname;
const config = {
  paths: {
    dist: path.join(ROOT_PATH, 'dist'),
    src: path.join(ROOT_PATH, 'src'),
    demo: path.join(ROOT_PATH, 'demo'),
  },
  filename: 'AdminLTE',
  library: 'React-AdminLTE',
};
const extractCSS = new ExtractTextPlugin('bundle.css');

process.env.BABEL_ENV = TARGET;

const common = {
  resolve: {
    extensions: ['', '.js', '.jsx', '.css', '.png', '.jpg'],
  },
  module: {
    preLoaders: [
      {
        test: /\.jsx?$/,
        loaders: ['eslint'],
        include: [
          config.paths.demo,
          config.paths.src,
        ],
      },
    ],
    loaders: [
      {
        test: /\.(jpg|png)$/,
        loader: 'file',
      },
      {
        test: /\.json$/,
        loader: 'json',
      },
      {
        test: /\.(ttf|eot|svg|gif)(\?[\s\S]+)?$/,
        loader: 'file',
      },
      {
        test: /\.woff2?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
        loader: 'url-loader?limit=10000&mimetype=application/font-woff',
      },
      {
        test: /\.md$/,
        loader: 'raw',
      },
    ],
  },
  plugins: [
    new SystemBellPlugin(),
  ],
};

const siteCommon = {
  plugins: [
    new webpack.DefinePlugin({
      NAME: JSON.stringify(pkg.name),
      USER: JSON.stringify(pkg.user),
      VERSION: JSON.stringify(pkg.version),
    }),
  ],
};

if (TARGET === 'start') {
  module.exports = merge(common, siteCommon, {
    devtool: 'eval-source-map',
    entry: {
      demo: config.paths.demo,
    },
    plugins: [
      new HtmlWebpackPlugin({
        template: require('html-webpack-template'), // eslint-disable-line global-require
        inject: false,
        mobile: true,
        title: pkg.name,
        appMountId: 'app',
      }),
      new webpack.DefinePlugin({
        GH_PAGES: false,
        'process.env.NODE_ENV': '"development"',
      }),
      new webpack.HotModuleReplacementPlugin(),
    ],
    module: {
      loaders: [
        {
          test: /\.css$/,
          loaders: ['style', 'css'],
        },
        {
          test: /\.jsx?$/,
          loaders: ['babel?cacheDirectory'],
          include: [
            config.paths.demo,
            config.paths.src,
          ],
        },
      ],
    },
    devServer: {
      historyApiFallback: true,
      hot: true,
      inline: true,
      progress: true,
      host: process.env.HOST,
      port: process.env.PORT,
      stats: 'errors-only',
    },
  });
}

if (TARGET === 'gh-pages' || TARGET === 'gh-pages:stats') {
  module.exports = merge(common, siteCommon, {
    entry: {
      app: config.paths.demo,
      vendors: [
        'react',
        'react-dom',
      ],
    },
    output: {
      path: './gh-pages',
      filename: 'bundle.js',
    },
    plugins: [
      new CleanWebpackPlugin(['gh-pages'], {
        verbose: false,
      }),
      extractCSS,
      new HtmlWebpackPlugin({
        template: 'lib/index_template.ejs',
        filename: 'index.html',

        // Context for the template
        title: pkg.name,
        description: pkg.description,
      }),
      new HtmlWebpackPlugin({
        template: 'lib/404_template.ejs',
        filename: '404.html',
        inject: false,

        // Context for the template
        title: pkg.name,
        remote: true,
      }),
      new webpack.DefinePlugin({
        GH_PAGES: true,
        // This affects the react lib size
        'process.env.NODE_ENV': '"production"',
      }),
      new webpack.optimize.DedupePlugin(),
      new webpack.optimize.UglifyJsPlugin({
        compress: {
          warnings: false,
        },
      }),
      new webpack.optimize.CommonsChunkPlugin({
        names: ['app', 'vendors'],
        filename: '[name].bundle.js',
      }),
    ],
    module: {
      loaders: [
        {
          test: /\.css$/,
          loader: extractCSS.extract('style', 'css?sourceMap'),
        },
        {
          test: /\.jsx?$/,
          loaders: ['babel'],
          include: [
            config.paths.demo,
            config.paths.src,
          ],
        },
      ],
    },
  });
}

const distCommon = {
  devtool: 'source-map',
  resolve: {
    extensions: ['', '.js', '.jsx'],
  },
  output: {
    path: config.paths.dist,
    libraryTarget: 'umd',
    library: config.library,
  },
  entry: {
    app: config.paths.src,
    vendors: [
      'react',
    ],
  },
  externals: {
    react: {
      commonjs: 'react',
      commonjs2: 'react',
      amd: 'React',
      root: 'React',
    },
  },
  module: {
    loaders: [
      {
        test: /\.jsx?$/,
        loaders: ['babel'],
        include: config.paths.src,
      },
    ],
  },
  plugins: [
    new SystemBellPlugin(),
  ],
};

if (TARGET === 'dist') {
  module.exports = merge(distCommon, {
    output: {
      filename: `${config.filename}.js`,
    },
  });
}

if (TARGET === 'dist:min') {
  module.exports = merge(distCommon, {
    output: {
      filename: `${config.filename}.min.js`,
    },
    plugins: [
      new webpack.optimize.UglifyJsPlugin({
        compress: {
          warnings: false,
        },
      }),
    ],
  });
}

if (!TARGET) {
  module.exports = common;
}
<commit_msg>Update webpack to build css in dist<commit_after>import * as path from 'path';

import webpack from 'webpack';
import HtmlWebpackPlugin from 'html-webpack-plugin';
import ExtractTextPlugin from 'extract-text-webpack-plugin';
import SystemBellPlugin from 'system-bell-webpack-plugin';
import CleanWebpackPlugin from 'clean-webpack-plugin';
import merge from 'webpack-merge';

import pkg from './package.json';

const TARGET = process.env.npm_lifecycle_event || '';
const ROOT_PATH = __dirname;
const config = {
  paths: {
    dist: path.join(ROOT_PATH, 'dist'),
    src: path.join(ROOT_PATH, 'src'),
    demo: path.join(ROOT_PATH, 'demo'),
  },
  filename: 'AdminLTE',
  library: 'React-AdminLTE',
};
const extractCSS = new ExtractTextPlugin('bundle.css');

process.env.BABEL_ENV = TARGET;

const common = {
  resolve: {
    extensions: ['', '.js', '.jsx', '.css', '.png', '.jpg'],
  },
  module: {
    preLoaders: [
      {
        test: /\.jsx?$/,
        loaders: ['eslint'],
        include: [
          config.paths.src,
        ],
      },
    ],
    loaders: [
      {
        test: /\.(jpg|png)$/,
        loader: 'file',
      },
      {
        test: /\.json$/,
        loader: 'json',
      },
      {
        test: /\.(ttf|eot|svg|gif)(\?[\s\S]+)?$/,
        loader: 'file',
      },
      {
        test: /\.woff2?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
        loader: 'url-loader?limit=10000&mimetype=application/font-woff',
      },
      {
        test: /\.md$/,
        loader: 'raw',
      },
    ],
  },
  plugins: [
    new SystemBellPlugin(),
  ],
};

const siteCommon = {
  module: {
    preLoaders: [
      {
        test: /\.jsx?$/,
        loaders: ['eslint'],
        include: [
          config.paths.demo,
        ],
      },
    ],
  },
  plugins: [
    new webpack.DefinePlugin({
      NAME: JSON.stringify(pkg.name),
      USER: JSON.stringify(pkg.user),
      VERSION: JSON.stringify(pkg.version),
    }),
  ],
};

if (TARGET === 'start') {
  module.exports = merge(common, siteCommon, {
    devtool: 'eval-source-map',
    entry: {
      demo: config.paths.demo,
    },
    plugins: [
      new HtmlWebpackPlugin({
        template: require('html-webpack-template'), // eslint-disable-line global-require
        inject: false,
        mobile: true,
        title: pkg.name,
        appMountId: 'app',
      }),
      new webpack.DefinePlugin({
        GH_PAGES: false,
        'process.env.NODE_ENV': '"development"',
      }),
      new webpack.HotModuleReplacementPlugin(),
    ],
    module: {
      loaders: [
        {
          test: /\.css$/,
          loaders: ['style', 'css'],
        },
        {
          test: /\.jsx?$/,
          loaders: ['babel?cacheDirectory'],
          include: [
            config.paths.demo,
            config.paths.src,
          ],
        },
      ],
    },
    devServer: {
      historyApiFallback: true,
      hot: true,
      inline: true,
      progress: true,
      host: process.env.HOST,
      port: process.env.PORT,
      stats: 'errors-only',
    },
  });
}

if (TARGET === 'gh-pages' || TARGET === 'gh-pages:stats') {
  module.exports = merge(common, siteCommon, {
    entry: {
      app: config.paths.demo,
      vendors: [
        'react',
        'react-dom',
      ],
    },
    output: {
      path: './gh-pages',
      filename: 'bundle.js',
    },
    plugins: [
      new CleanWebpackPlugin(['gh-pages'], {
        verbose: false,
      }),
      extractCSS,
      new HtmlWebpackPlugin({
        template: 'lib/index_template.ejs',
        filename: 'index.html',

        // Context for the template
        title: pkg.name,
        description: pkg.description,
      }),
      new HtmlWebpackPlugin({
        template: 'lib/404_template.ejs',
        filename: '404.html',
        inject: false,

        // Context for the template
        title: pkg.name,
        remote: true,
      }),
      new webpack.DefinePlugin({
        GH_PAGES: true,
        // This affects the react lib size
        'process.env.NODE_ENV': '"production"',
      }),
      new webpack.optimize.DedupePlugin(),
      new webpack.optimize.UglifyJsPlugin({
        compress: {
          warnings: false,
        },
      }),
      new webpack.optimize.CommonsChunkPlugin({
        names: ['app', 'vendors'],
        filename: '[name].bundle.js',
      }),
    ],
    module: {
      loaders: [
        {
          test: /\.css$/,
          loader: extractCSS.extract('style', 'css?sourceMap'),
        },
        {
          test: /\.jsx?$/,
          loaders: ['babel'],
          include: [
            config.paths.demo,
            config.paths.src,
          ],
        },
      ],
    },
  });
}

const distCommon = {
  devtool: 'source-map',
  output: {
    path: config.paths.dist,
    libraryTarget: 'umd',
    library: config.library,
  },
  entry: {
    app: config.paths.src,
    vendors: [
      'react',
    ],
  },
  externals: {
    react: {
      commonjs: 'react',
      commonjs2: 'react',
      amd: 'React',
      root: 'React',
    },
  },
};

if (TARGET === 'dist') {
  module.exports = merge(common, distCommon, {
    output: {
      filename: `${config.filename}.js`,
    },
  });
}

if (TARGET === 'dist:min') {
  module.exports = merge(common, distCommon, {
    output: {
      filename: `${config.filename}.min.js`,
    },
    plugins: [
      new webpack.optimize.UglifyJsPlugin({
        compress: {
          warnings: false,
        },
      }),
    ],
  });
}

if (!TARGET) {
  module.exports = common;
}
<|endoftext|>