<commit_before>(function(window, document, undefined) {
    window.onload = init;
    function init() {
        //get the canvas
        var canvas = document.getElementById("mapcanvas");
        var c = canvas.getContext("2d");
        var cwidth = 960;
        var cheight = 540;
        var moves = {
            u: [0,-1],
            d: [0,1],
            l: [-1,0],
            r: [1,0]
        };
        var nodemap = [];
        var origroomlist = [];
        var roomlist = [];
        var removelist = [];
        document.getElementById("paintbtn").onclick = paint;

        function removeRooms(){
            origroomlist = roomlist.slice(0);
            removelist = [];
            for(var i = 0; i< roomlist.length; i++){
                var remove = 1;
                var tempHeight = roomlist[i].height;
                var tempWidth = roomlist[i].width;
                for(var j = 0; j< tempWidth; j++){
                    for(var k = 0; k< tempHeight; k++){
                        if(nodemap[roomlist[i].x + j][roomlist[i].y + k].isVisited == 1){
                            remove = 0;
                            break;
                        }
                    }
                }
                if(remove == 0){
                    for(var j = 0; j< tempWidth; j++){
                        for(var k = 0; k< tempHeight; k++){
                            nodemap[roomlist[i].x + j][roomlist[i].y + k].isVisited = 1;
                        }
                    }
                }

                if(remove ==1 ){
                    roomlist[i].removed = 1;
                }
            }
        }

        function shuffle(array) {
          var currentIndex = array.length, temporaryValue, randomIndex ;

          // While there remain elements to shuffle...
          while (0 !== currentIndex) {

            // Pick a remaining element...
            randomIndex = Math.floor(Math.random() * currentIndex);
            currentIndex -= 1;

            // And swap it with the current element.
            temporaryValue = array[currentIndex];
            array[currentIndex] = array[randomIndex];
            array[randomIndex] = temporaryValue;
          }
          return array;
        }

        function reset(){
            c.clearRect ( 0 , 0 , canvas.width, canvas.height );
            c.beginPath();
            nodemap = [];
            roomlist = [];
        }

        function walk(start, stop, steps){
            var distX = stop.x - start.x;
            var distY = stop.y - start.y;

            var walkSteps = [];
            for(var i = 0; i< Math.abs(distX); i++){
                if(distX < 0){
                    walkSteps.push(moves.l);
                } else {
                    walkSteps.push(moves.r);
                }
            }
            for(var i = 0; i< Math.abs(distY); i++){
                if(distY < 0){
                    walkSteps.push(moves.u);
                } else {
                    walkSteps.push(moves.d);
                }
            }

            //add a number of random pairs based on how big our grid is
            for(var i = 0; i< steps; i++){
                var rand = Math.floor(Math.random() * 2);
                if(rand < 1){
                    walkSteps.push(moves.u);
                    walkSteps.push(moves.d);
                } else{
                    walkSteps.push(moves.l);
                    walkSteps.push(moves.r);
                }
            }
            return shuffle(walkSteps);
        }

        function createRoom(x, y, pw, ph){
            maxW = pw - x;
            maxH = ph - y;

            var randw;
            while(randw > maxW){
                randw = Math.floor((Math.random() * (pw/2) + 1) );
            }
            var randh;
            while(randh > maxH){
                randh = Math.floor((Math.random() * (ph/2) + 1) );
            }
            //randw = randw - Math.floor(pw/4);
            //randh = randh - Math.floor(ph/4);

            for(i = 0; i< randw; i++){
                for(j = 0; j< randh; j++){
                    nodemap[x+i][y+j].isRoom = 1;
                }
            }
            var room = {
              x:x,
              y:y,
              width: randw,
              height: randh,
              removed: 0
            };
            roomlist.push(room);
            return [randw, randh];
        }

        function paint(){
            reset();

            var widthSelect = document.getElementById("width");
            var pathWidth = parseInt(widthSelect.options[widthSelect.selectedIndex].value);

            var heightSelect = document.getElementById("height");
            var pathHeight = parseInt(heightSelect.options[heightSelect.selectedIndex].value);

            //create a start and endpoint based on the grid size
            var startpoint = {
               x: -1,
               y: -1
            }
           var endpoint = {
               x: -1,
               y: -1
            }
            startpoint.x = 0;
            startpoint.y = pathHeight - 1;
            endpoint.x = pathWidth - 1;
            endpoint.y = 0;

            //paint the base grid
            for(var i = 0; i< pathWidth; i++){
                nodemap.push([]);
                for(var j = 0; j< pathHeight; j++){
                    var node = {
                        isVisited: 0,
                        isRoom:0,
                        n:0,
                        s:0,
                        e:0,
                        w:0,
                        x:i,
                        y:j
                    };
                    nodemap[i].push(node);
               }
           }

           //create a random path that we will walk
           var randsteps = 2* Math.floor((pathWidth/4) * (pathHeight/4));
           var walkArray = walk(startpoint, endpoint, randsteps);

           //create two moving points representing where we are and where we were
           var movingpoint = {
               x: -1,
               y: -1
           };
           var movingpointold = {
               x: -1,
               y: -1
           };
           movingpoint.x = startpoint.x;
           movingpoint.y = startpoint.y;
           movingpointold.x = startpoint.x;
           movingpointold.y = startpoint.y;

           //set the start node as visited in the beginning
           nodemap[startpoint.x][startpoint.y].isVisited = 1;

           //loop through the walk
           for (var i = 0; i< walkArray.length; i++){
               movingpoint.x = movingpoint.x + walkArray[i][0];
               movingpoint.y = movingpoint.y + walkArray[i][1];
               var oppcurrMoveX = -1 * walkArray[i][0];
               var oppcurrMoveY = -1 * walkArray[i][1];
               var index = -1;
               for(var j = i; j< walkArray.length; j++){
                   if(walkArray[j][0] == oppcurrMoveX && walkArray[j][1] == oppcurrMoveY){
                       index = j;
                       break;
                   }
               }
               if(movingpoint.x > pathWidth -1){
                   movingpoint.x = movingpoint.x - 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }
               }
               if(movingpoint.x < 0){
                   movingpoint.x = movingpoint.x + 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }
               }
               if(movingpoint.y > pathHeight -1){
                   movingpoint.y = movingpoint.y - 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }
               }
               if( movingpoint.y < 0){
                   movingpoint.y = movingpoint.y + 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }
                }

               var movedirX = movingpoint.x - movingpointold.x;
               var movedirY = movingpoint.y - movingpointold.y;

               if(movedirX < 0){
                   nodemap[movingpointold.x][movingpointold.y].w = 1;
                   nodemap[movingpoint.x][movingpoint.y].e = 1;
               }else if(movedirX > 0){
                   nodemap[movingpointold.x][movingpointold.y].e = 1;
                   nodemap[movingpoint.x][movingpoint.y].w = 1;
               }
               if(movedirY < 0){
                   nodemap[movingpointold.x][movingpointold.y].n =1;
                   nodemap[movingpoint.x][movingpoint.y].s = 1;
               }else if(movedirY >0){
                   nodemap[movingpointold.x][movingpointold.y].s = 1;
                   nodemap[movingpoint.x][movingpoint.y].n = 1;
               }

               nodemap[movingpoint.x][movingpoint.y].isVisited = 1

               movingpointold.x = movingpoint.x;
               movingpointold.y = movingpoint.y;
           }

           //create random rooms
           for(var i = 0; i< pathWidth; i++){
                for(var j = 0; j< pathHeight; j++){
                    var randRoom = Math.floor((Math.random() * 3));
                    if(randRoom < 1){
                        roomDim = createRoom(i,j,pathWidth,pathHeight);
                        //c.beginPath();
                        //c.fillStyle = "#FFFFFF";
                        //c.fillRect(i*30 + 6, j*30 + 6, roomDim[0]*30 - 6*2, roomDim[1]*30 - 6*2);
                        //c.stroke();
                    }
                }
            }

            //get rid of rooms that aren't attached
            removeRooms();

            //create a branch point
            var branchpoints = [];
           for(var i = 0; i< nodemap.length; i++){
               for(var j = 0; j< nodemap[i].length; j++){
                   var neighboorcount = 0;
                   try{
                       if(nodemap[i][j-1].isVisited == 1){
                           neighboorcount++;
                       }
                   } catch(e){
                       neighboorcount++;
                   }
                   try{
                       if(nodemap[i][j+1].isVisited == 1){
                           neighboorcount++;
                       }
                   }catch(e){
                       neighboorcount++;
                   }
                   try{
                       if(nodemap[i-1][j].isVisited == 1){
                           neighboorcount++;
                       }
                   }catch(e){
                       neighboorcount++;
                   }
                   try{
                       if(nodemap[i +1][j].isVisited == 1){
                           neighboorcount++;
                       }
                   }catch(e){
                       neighboorcount++;
                   }

                   if(neighboorcount <=2 && neighboorcount > 0 && nodemap[i][j].isVisited == 1){
                       branchpoints.push(nodemap[i][j]);
                   }
               }
           }

           //paint the map data
           for(var i = 0; i< nodemap.length; i++){
               for(var j = 0; j < nodemap[i].length; j++){
                   c.fillStyle = "#000000";
                   c.fillRect(i*30, j*30, 30, 30);
                   if(nodemap[i][j].isVisited == 1){
                       c.fillStyle = "#FFFFFF";
                       c.fillRect(i*30 + 6, j*30 + 6, 18, 18);
                       if(nodemap[i][j].n){
                           c.fillStyle = "#FFFFFF";
                           c.fillRect(i*30 + 12, j*30, 6, 6);
                       }
                       if(nodemap[i][j].s){
                           c.fillStyle = "#FFFFFF";
                           c.fillRect(i*30 + 12, j*30 + 24, 6, 6);
                       }
                       if(nodemap[i][j].e){
                           c.fillStyle = "#FFFFFF";
                           c.fillRect(i*30 + 24, j*30 + 12, 6, 6);
                       }
                       if(nodemap[i][j].w){
                           c.fillStyle = "#FFFFFF";
                           c.fillRect(i*30, j*30 + 12, 6, 6);
                       }
                       if(nodemap[i][j].isRoom == 1){
                           c.fillStyle = "#FFFFFF";
                           c.fillRect(i*30, j*30, 30, 30);
                       }
                   }
                   if(nodemap[i][j].isRoom == 1){
                       //c.fillStyle = "#FFFFFF";
                       //c.fillRect(i*30, j*30, 30, 30);

                   }
               }
           }

           //paint the original rooms
           /*for(var i = 0; i< origroomlist.length; i++){
                c.beginPath();
                c.fillStyle = "#33CCFF";
                c.fillRect(origroomlist[i].x*30 + 6, origroomlist[i].y*30 + 6, origroomlist[i].width*30 - 6*2, origroomlist[i].height*30 - 6*2);
                c.stroke();
            }*/

           //paint the rooms so they look nice
           /*for(var i = 0; i< roomlist.length; i++){
               if(roomlist[i].removed == 0){
                   c.beginPath();
                   c.fillStyle = "#FFFFFF";
                   c.fillRect(roomlist[i].x*30 + 6, roomlist[i].y*30 + 6, roomlist[i].width*30 - 6*2, roomlist[i].height*30 - 6*2);
                   c.stroke();
               }
            }*/

            for(var i = 0; i< branchpoints.length; i++){
                c.fillStyle = "#CC66FF";
                c.fillRect(branchpoints[i].x*30 + 6, branchpoints[i].y*30 + 6, 18, 18);
            }

            //paint the start, branch, and end points.
            c.fillStyle = "#33CC33";
            c.fillRect(startpoint.x*30 + 6, startpoint.y*30 + 6, 18, 18);
            c.fillStyle = "#CC0000";
            c.fillRect(endpoint.x*30 + 6, endpoint.y*30 + 6, 18, 18);

        }
    }
})(window, document, undefined);
<commit_msg>Update script.js<commit_after>(function(window, document, undefined) {
    window.onload = init;
    function init() {
        //get the canvas
        var canvas = document.getElementById("mapcanvas");
        var c = canvas.getContext("2d");
        var cwidth = 960;
        var cheight = 540;
        var moves = {
            u: [0,-1],
            d: [0,1],
            l: [-1,0],
            r: [1,0]
        };
        var nodemap = [];
        var origroomlist = [];
        var roomlist = [];
        var removelist = [];
        document.getElementById("paintbtn").onclick = paint;

        function removeRooms(){
            origroomlist = roomlist.slice(0);
            removelist = [];
            for(var i = 0; i< roomlist.length; i++){
                var remove = 1;
                var tempHeight = roomlist[i].height;
                var tempWidth = roomlist[i].width;
                for(var j = 0; j< tempWidth; j++){
                    for(var k = 0; k< tempHeight; k++){
                        if(nodemap[roomlist[i].x + j][roomlist[i].y + k].isVisited == 1){
                            remove = 0;
                            break;
                        }
                    }
                }
                if(remove == 0){
                    for(var j = 0; j< tempWidth; j++){
                        for(var k = 0; k< tempHeight; k++){
                            nodemap[roomlist[i].x + j][roomlist[i].y + k].isVisited = 1;
                        }
                    }
                }

                if(remove ==1 ){
                    roomlist[i].removed = 1;
                }
            }
        }

        function shuffle(array) {
          var currentIndex = array.length, temporaryValue, randomIndex ;

          // While there remain elements to shuffle...
          while (0 !== currentIndex) {

            // Pick a remaining element...
            randomIndex = Math.floor(Math.random() * currentIndex);
            currentIndex -= 1;

            // And swap it with the current element.
            temporaryValue = array[currentIndex];
            array[currentIndex] = array[randomIndex];
            array[randomIndex] = temporaryValue;
          }
          return array;
        }

        function reset(){
            c.clearRect ( 0 , 0 , canvas.width, canvas.height );
            c.beginPath();
            nodemap = [];
            roomlist = [];
        }

        function walk(start, stop, steps){
            var distX = stop.x - start.x;
            var distY = stop.y - start.y;

            var walkSteps = [];
            for(var i = 0; i< Math.abs(distX); i++){
                if(distX < 0){
                    walkSteps.push(moves.l);
                } else {
                    walkSteps.push(moves.r);
                }
            }
            for(var i = 0; i< Math.abs(distY); i++){
                if(distY < 0){
                    walkSteps.push(moves.u);
                } else {
                    walkSteps.push(moves.d);
                }
            }

            //add a number of random pairs based on how big our grid is
            for(var i = 0; i< steps; i++){
                var rand = Math.floor(Math.random() * 2);
                if(rand < 1){
                    walkSteps.push(moves.u);
                    walkSteps.push(moves.d);
                } else{
                    walkSteps.push(moves.l);
                    walkSteps.push(moves.r);
                }
            }
            return shuffle(walkSteps);
        }

        function createRoom(x, y, pw, ph){
            maxW = pw - x;
            maxH = ph - y;

            var randw = maxW + 1;
            while(randw > maxW){
                randw = Math.floor((Math.random() * (pw/2) + 1) );
            }
            var randh = maxH + 1;
            while(randh > maxH){
                randh = Math.floor((Math.random() * (ph/2) + 1) );
            }
            //randw = randw - Math.floor(pw/4);
            //randh = randh - Math.floor(ph/4);

            for(i = 0; i< randw; i++){
                for(j = 0; j< randh; j++){
                    nodemap[x+i][y+j].isRoom = 1;
                }
            }
            var room = {
              x:x,
              y:y,
              width: randw,
              height: randh,
              removed: 0
            };
            roomlist.push(room);
            return [randw, randh];
        }

        function paint(){
            reset();

            var widthSelect = document.getElementById("width");
            var pathWidth = parseInt(widthSelect.options[widthSelect.selectedIndex].value);

            var heightSelect = document.getElementById("height");
            var pathHeight = parseInt(heightSelect.options[heightSelect.selectedIndex].value);

            //create a start and endpoint based on the grid size
            var startpoint = {
               x: -1,
               y: -1
            }
           var endpoint = {
               x: -1,
               y: -1
            }
            startpoint.x = 0;
            startpoint.y = pathHeight - 1;
            endpoint.x = pathWidth - 1;
            endpoint.y = 0;

            //paint the base grid
            for(var i = 0; i< pathWidth; i++){
                nodemap.push([]);
                for(var j = 0; j< pathHeight; j++){
                    var node = {
                        isVisited: 0,
                        isRoom:0,
                        n:0,
                        s:0,
                        e:0,
                        w:0,
                        x:i,
                        y:j
                    };
                    nodemap[i].push(node);
               }
           }

           //create a random path that we will walk
           var randsteps = 2* Math.floor((pathWidth/4) * (pathHeight/4));
           var walkArray = walk(startpoint, endpoint, randsteps);

           //create two moving points representing where we are and where we were
           var movingpoint = {
               x: -1,
               y: -1
           };
           var movingpointold = {
               x: -1,
               y: -1
           };
           movingpoint.x = startpoint.x;
           movingpoint.y = startpoint.y;
           movingpointold.x = startpoint.x;
           movingpointold.y = startpoint.y;

           //set the start node as visited in the beginning
           nodemap[startpoint.x][startpoint.y].isVisited = 1;

           //loop through the walk
           for (var i = 0; i< walkArray.length; i++){
               movingpoint.x = movingpoint.x + walkArray[i][0];
               movingpoint.y = movingpoint.y + walkArray[i][1];
               var oppcurrMoveX = -1 * walkArray[i][0];
               var oppcurrMoveY = -1 * walkArray[i][1];
               var index = -1;
               for(var j = i; j< walkArray.length; j++){
                   if(walkArray[j][0] == oppcurrMoveX && walkArray[j][1] == oppcurrMoveY){
                       index = j;
                       break;
                   }
               }
               if(movingpoint.x > pathWidth -1){
                   movingpoint.x = movingpoint.x - 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }
               }
               if(movingpoint.x < 0){
                   movingpoint.x = movingpoint.x + 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }
               }
               if(movingpoint.y > pathHeight -1){
                   movingpoint.y = movingpoint.y - 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }
               }
               if( movingpoint.y < 0){
                   movingpoint.y = movingpoint.y + 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }
                }

               var movedirX = movingpoint.x - movingpointold.x;
               var movedirY = movingpoint.y - movingpointold.y;

               if(movedirX < 0){
                   nodemap[movingpointold.x][movingpointold.y].w = 1;
                   nodemap[movingpoint.x][movingpoint.y].e = 1;
               }else if(movedirX > 0){
                   nodemap[movingpointold.x][movingpointold.y].e = 1;
                   nodemap[movingpoint.x][movingpoint.y].w = 1;
               }
               if(movedirY < 0){
                   nodemap[movingpointold.x][movingpointold.y].n =1;
                   nodemap[movingpoint.x][movingpoint.y].s = 1;
               }else if(movedirY >0){
                   nodemap[movingpointold.x][movingpointold.y].s = 1;
                   nodemap[movingpoint.x][movingpoint.y].n = 1;
               }

               nodemap[movingpoint.x][movingpoint.y].isVisited = 1

               movingpointold.x = movingpoint.x;
               movingpointold.y = movingpoint.y;
           }

           //create random rooms
           for(var i = 0; i< pathWidth; i++){
                for(var j = 0; j< pathHeight; j++){
                    var randRoom = Math.floor((Math.random() * 3));
                    if(randRoom < 1){
                        roomDim = createRoom(i,j,pathWidth,pathHeight);
                        //c.beginPath();
                        //c.fillStyle = "#FFFFFF";
                        //c.fillRect(i*30 + 6, j*30 + 6, roomDim[0]*30 - 6*2, roomDim[1]*30 - 6*2);
                        //c.stroke();
                    }
                }
            }

            //get rid of rooms that aren't attached
            removeRooms();

            //create a branch point
            var branchpoints = [];
           for(var i = 0; i< nodemap.length; i++){
               for(var j = 0; j< nodemap[i].length; j++){
                   var neighboorcount = 0;
                   try{
                       if(nodemap[i][j-1].isVisited == 1){
                           neighboorcount++;
                       }
                   } catch(e){
                       neighboorcount++;
                   }
                   try{
                       if(nodemap[i][j+1].isVisited == 1){
                           neighboorcount++;
                       }
                   }catch(e){
                       neighboorcount++;
                   }
                   try{
                       if(nodemap[i-1][j].isVisited == 1){
                           neighboorcount++;
                       }
                   }catch(e){
                       neighboorcount++;
                   }
                   try{
                       if(nodemap[i +1][j].isVisited == 1){
                           neighboorcount++;
                       }
                   }catch(e){
                       neighboorcount++;
                   }

                   if(neighboorcount <=2 && neighboorcount > 0 && nodemap[i][j].isVisited == 1){
                       branchpoints.push(nodemap[i][j]);
                   }
               }
           }

           //paint the map data
           for(var i = 0; i< nodemap.length; i++){
               for(var j = 0; j < nodemap[i].length; j++){
                   c.fillStyle = "#000000";
                   c.fillRect(i*30, j*30, 30, 30);
                   if(nodemap[i][j].isVisited == 1){
                       c.fillStyle = "#FFFFFF";
                       c.fillRect(i*30 + 6, j*30 + 6, 18, 18);
                       if(nodemap[i][j].n){
                           c.fillStyle = "#FFFFFF";
                           c.fillRect(i*30 + 12, j*30, 6, 6);
                       }
                       if(nodemap[i][j].s){
                           c.fillStyle = "#FFFFFF";
                           c.fillRect(i*30 + 12, j*30 + 24, 6, 6);
                       }
                       if(nodemap[i][j].e){
                           c.fillStyle = "#FFFFFF";
                           c.fillRect(i*30 + 24, j*30 + 12, 6, 6);
                       }
                       if(nodemap[i][j].w){
                           c.fillStyle = "#FFFFFF";
                           c.fillRect(i*30, j*30 + 12, 6, 6);
                       }
                       if(nodemap[i][j].isRoom == 1){
                           c.fillStyle = "#FFFFFF";
                           c.fillRect(i*30, j*30, 30, 30);
                       }
                   }
                   if(nodemap[i][j].isRoom == 1){
                       //c.fillStyle = "#FFFFFF";
                       //c.fillRect(i*30, j*30, 30, 30);

                   }
               }
           }

           //paint the original rooms
           /*for(var i = 0; i< origroomlist.length; i++){
                c.beginPath();
                c.fillStyle = "#33CCFF";
                c.fillRect(origroomlist[i].x*30 + 6, origroomlist[i].y*30 + 6, origroomlist[i].width*30 - 6*2, origroomlist[i].height*30 - 6*2);
                c.stroke();
            }*/

           //paint the rooms so they look nice
           /*for(var i = 0; i< roomlist.length; i++){
               if(roomlist[i].removed == 0){
                   c.beginPath();
                   c.fillStyle = "#FFFFFF";
                   c.fillRect(roomlist[i].x*30 + 6, roomlist[i].y*30 + 6, roomlist[i].width*30 - 6*2, roomlist[i].height*30 - 6*2);
                   c.stroke();
               }
            }*/

            for(var i = 0; i< branchpoints.length; i++){
                c.fillStyle = "#CC66FF";
                c.fillRect(branchpoints[i].x*30 + 6, branchpoints[i].y*30 + 6, 18, 18);
            }

            //paint the start, branch, and end points.
            c.fillStyle = "#33CC33";
            c.fillRect(startpoint.x*30 + 6, startpoint.y*30 + 6, 18, 18);
            c.fillStyle = "#CC0000";
            c.fillRect(endpoint.x*30 + 6, endpoint.y*30 + 6, 18, 18);

        }
    }
})(window, document, undefined);
<|endoftext|>


<commit_before>//Entry point
import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, browserHistory, IndexRoute } from 'react-router';
import App from './components/App';
import Home from './components/Home';

ReactDOM.render((
  <Router history={browserHistory}>
    <Route path="/" component={App}>
      <Route path="home/:userid" component={Home}/>
    </Route>
  </Router>
  ), document.getElementById('app')
);
<commit_msg>adds dashboard route<commit_after>//Entry point
import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, browserHistory, IndexRoute } from 'react-router';
import App from './components/App';
import Home from './components/Home';
import Dashboard from './components/Dashboard';

ReactDOM.render((
  <Router history={browserHistory}>
    <Route path="/" component={App}>
      <Route path="/home/:userid" component={Home}/>
      <Route path="/dashboard" component={Dashboard}/>
    </Route>
  </Router>
  ), document.getElementById('app')
);
<|endoftext|>


<commit_before>'use strict';

//1) Copy package.json and Gruntfile.js to root folder
//2) Download and unzip latest Wordpress version in to root
//3) Download html5blank theme and move to themes folder using theme name entered
//4) Download Advanced Custom Fields and move to plugins folder
//5) Move wp-config file to root and update with DB details entered
//6) Move reset stylsheet to theme folder and update theme name (Using a separate reset file to the downloaded one so that we can update the theme name)

var util = require('util'),
    path = require('path'),
    yeoman = require('yeoman-generator'),
    shell = require('shelljs');

var DevpressGenerator = module.exports = function DevpressGenerator(args, options, config) {
  yeoman.generators.Base.apply(this, arguments);

  this.on('end', function () {
    this.installDependencies({ skipInstall: options['skip-install'] });
  });

  this.pkg = JSON.parse(this.readFileAsString(path.join(__dirname, '../package.json')));
};

util.inherits(DevpressGenerator, yeoman.generators.Base);

DevpressGenerator.prototype.askFor = function askFor() {
  var cb = this.async();

  // have Yeoman greet the user.
  console.log(this.yeoman);

  var prompts = [
    {
        type: 'input',
        name: 'dbName',
        message: 'Database Name',
    },
    {
        type: 'input',
        name: 'dbUser',
        message: 'Database Username',
        default: 'root'
    },
    {
        type: 'input',
        name: 'dbPass',
        message: 'Database Password',
        default: 'root'
    },
      {
          type: 'input',
          name: 'themeName',
          message: 'Enter a name for your theme (The default twentyfourteen theme will be downloaded and renamed)',
          default: ''
      }
  ];

    this.prompt(prompts, function (props) {
        this.dbName = props.dbName;
        this.dbUser = props.dbUser;
        this.dbPass = props.dbPass;
        this.installTheme = props.installTheme;
        this.themeName = props.themeName;

        if(!this.themeName){
            this.themeName = 'twentyfourteen';
        }

    cb();
  }.bind(this));
};

DevpressGenerator.prototype.gruntFiles = function gruntFiles() {
    this.copy('_package.json', 'package.json');
    this.copy('_Gruntfile.js', 'Gruntfile.js');
};

DevpressGenerator.prototype.LatestWordpress = function LatestWordpress() {
    var cb   = this.async();

    this.log.writeln('Let\'s download the latest Wordpress Version.');
    this.tarball('http://wordpress.org/latest.zip', './', cb);
};

DevpressGenerator.prototype.removeThemes= function removeThemes() {

    this.log.writeln('Let\'s delete the default Wordpress themes.');

    shell.rm('-rf', './wp-content/themes/*');

};

DevpressGenerator.prototype.DevpressTheme = function DevpressTheme() {
    var cb   = this.async();

    this.log.writeln('Let\'s download the Devpress Wordpress theme and rename it.');
    this.tarball('https://github.com/marclloyd77/devpress-theme/archive/master.zip', 'wp-content/themes/' + this.themeName, cb);

};

DevpressGenerator.prototype.acfWordpress = function acfWordpress() {
    var cb   = this.async();

    this.log.writeln('Now we\'ll download the latest advanced custom fields and add it to the plugins folder.');
    this.tarball('https://github.com/elliotcondon/acf/archive/master.tar.gz', 'wp-content/plugins/advanced-custom-fields', cb);
};

DevpressGenerator.prototype.updateWpConfig = function updateWpConfig() {
    shell.rm('-rf', './wp-config.php');
    this.copy('wp-config.php.tmpl', 'wp-config.php');
};

//move css template and update theme name
DevpressGenerator.prototype.moveCss = function moveCss() {
    shell.rm('-rf', './wp-content/themes/' + this.themeName + '/style.css');
    this.copy('_style.css', 'wp-content/themes/' + this.themeName + '/style.css');
};<commit_msg>Updating comments in index.js<commit_after>'use strict';

//1) Copy package.json and Gruntfile.js to root folder
//2) Download and unzip latest Wordpress version in to root
//3) Delete preinstalled themes
//3) Download Devpress theme, move to themes folder using theme name entered at prompt
//4) Download Advanced Custom Fields and move to plugins folder
//5) Move wp-config file to root and update with DB details entered
//6) Move reset stylsheet to theme folder and update theme name (Using a separate reset file to the downloaded one so that we can update the theme name)

var util = require('util'),
    path = require('path'),
    yeoman = require('yeoman-generator'),
    shell = require('shelljs');

var DevpressGenerator = module.exports = function DevpressGenerator(args, options, config) {
  yeoman.generators.Base.apply(this, arguments);

  this.on('end', function () {
    this.installDependencies({ skipInstall: options['skip-install'] });
  });

  this.pkg = JSON.parse(this.readFileAsString(path.join(__dirname, '../package.json')));
};

util.inherits(DevpressGenerator, yeoman.generators.Base);

DevpressGenerator.prototype.askFor = function askFor() {
  var cb = this.async();

  // have Yeoman greet the user.
  console.log(this.yeoman);

  var prompts = [
    {
        type: 'input',
        name: 'dbName',
        message: 'Database Name',
    },
    {
        type: 'input',
        name: 'dbUser',
        message: 'Database Username',
        default: 'root'
    },
    {
        type: 'input',
        name: 'dbPass',
        message: 'Database Password',
        default: 'root'
    },
      {
          type: 'input',
          name: 'themeName',
          message: 'Enter a name for your theme (The default twentyfourteen theme will be downloaded and renamed)',
          default: ''
      }
  ];

    this.prompt(prompts, function (props) {
        this.dbName = props.dbName;
        this.dbUser = props.dbUser;
        this.dbPass = props.dbPass;
        this.installTheme = props.installTheme;
        this.themeName = props.themeName;

        if(!this.themeName){
            this.themeName = 'twentyfourteen';
        }

    cb();
  }.bind(this));
};

DevpressGenerator.prototype.gruntFiles = function gruntFiles() {
    this.copy('_package.json', 'package.json');
    this.copy('_Gruntfile.js', 'Gruntfile.js');
};

DevpressGenerator.prototype.LatestWordpress = function LatestWordpress() {
    var cb   = this.async();

    this.log.writeln('Let\'s download the latest Wordpress Version.');
    this.tarball('http://wordpress.org/latest.zip', './', cb);
};

DevpressGenerator.prototype.removeThemes= function removeThemes() {

    this.log.writeln('Let\'s delete the default Wordpress themes.');

    shell.rm('-rf', './wp-content/themes/*');

};

DevpressGenerator.prototype.DevpressTheme = function DevpressTheme() {
    var cb   = this.async();

    this.log.writeln('Let\'s download the Devpress Wordpress theme and rename it.');
    this.tarball('https://github.com/marclloyd77/devpress-theme/archive/master.zip', 'wp-content/themes/' + this.themeName, cb);

};

DevpressGenerator.prototype.acfWordpress = function acfWordpress() {
    var cb   = this.async();

    this.log.writeln('Now we\'ll download the latest advanced custom fields and add it to the plugins folder.');
    this.tarball('https://github.com/elliotcondon/acf/archive/master.tar.gz', 'wp-content/plugins/advanced-custom-fields', cb);
};

DevpressGenerator.prototype.updateWpConfig = function updateWpConfig() {
    shell.rm('-rf', './wp-config.php');
    this.copy('wp-config.php.tmpl', 'wp-config.php');
};

//move css template and update theme name
DevpressGenerator.prototype.moveCss = function moveCss() {
    shell.rm('-rf', './wp-content/themes/' + this.themeName + '/style.css');
    this.copy('_style.css', 'wp-content/themes/' + this.themeName + '/style.css');
};<|endoftext|>


<commit_before>/*!
 * OS.js - JavaScript Operating System
 *
 * Copyright (c) 2011-2014, Anders Evenrud <andersevenrud@gmail.com>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * @author  Anders Evenrud <andersevenrud@gmail.com>
 * @licence Simplified BSD License
 */
(function(Utils, API) {
  'use strict';

  // https://github.com/bcherry/dropbox-js
  // https://github.com/apily/dropbox/blob/master/index.js
  // https://www.dropbox.com/developers/core/start/python
  // https://www.dropbox.com/developers/reference/devguide

  window.OSjs       = window.OSjs       || {};
  OSjs.VFS          = OSjs.VFS          || {};
  OSjs.VFS.Modules  = OSjs.VFS.Modules  || {};

  var _cachedClient;
  var _isMounted = false;

  function _getConfig(cfg) {
    try {
      var handler = API.getHandlerInstance();
      if ( handler ) {
        return handler.getConfig('Core').VFS.Dropbox[cfg];
      }
    } catch ( e ) {
      console.warn('OSjs.VFS.Modules.Dropbox::enabled()', e, e.stack);
    }
    return null;
  }

  function destroyNotificationIcon() {
    var wm = API.getWMInstance();
    if ( wm ) {
      wm.removeNotificationIcon('GoogleAPIService');
    }
  }

  function createNotificationIcon() {
    var wm = API.getWMInstance();

    function displayMenu(ev) {
      var pos = {x: ev.clientX, y: ev.clientY};
      OSjs.GUI.createMenu([{
        title: API._('DROPBOX_SIGN_OUT'),
        onClick: function() {
          signoutDropbox();
        }
      }], pos);
    }

    if ( wm ) {
      wm.createNotificationIcon('DropboxVFSService', {
        onContextMenu: function(ev) {
          displayMenu(ev);
          return false;
        },
        onClick: function(ev) {
          displayMenu(ev);
          return false;
        },
        onInited: function(el) {
          if ( el.firstChild ) {
            var img = document.createElement('img');
            img.title = API._('DROPBOX_NOTIFICATION_TITLE');
            img.alt = img.title;
            img.src = API.getThemeResource('status/gtk-dialog-authentication.png', 'icon', '16x16');
            el.firstChild.appendChild(img);
          }
        }
      });
    }
  }

  /////////////////////////////////////////////////////////////////////////////
  // HELPERS
  /////////////////////////////////////////////////////////////////////////////

  function DropboxVFS() {
    var clientKey = _getConfig('ClientKey');
    this.client = new window.Dropbox.Client({ key: clientKey });
  }

  DropboxVFS.prototype.init = function(callback) {
    this.client.authenticate(function(error, client) {
      console.warn('DropboxVFS::construct()', error, client);
      callback(error);
    });
  };

  DropboxVFS.prototype.scandir = function(item, callback) {
    console.info('DropboxVFS::scandir()', item);

    var path = OSjs.VFS.getRelativeURL(item.path);

    function _finish(entries) {
      var result = [];
      entries.forEach(function(iter) {
        console.info(iter);
        result.push(new OSjs.VFS.File({
          filename: iter.name,
          path: OSjs.VFS.Modules.Dropbox.root.replace(/\/$/, '') + iter.path,
          size: iter.size,
          mime: iter.isFolder ? null : iter.mimeType,
          type: iter.isFolder ? 'dir' : 'file'
        }));
      });
      console.info('DropboxVFS::scandir()', item, '=>', result);

      var list = OSjs.VFS.filterScandir(result, item._opts);
      callback(false, list);
    }

    this.client.readdir(path, {}, function(error, entries, stat, entry_stats) {
      if ( error ) {
        error = API._('ERR_VFSMODULE_SCANDIR_FMT', error);
        callback(error);
        return;
      }
      _finish(entry_stats);
    });
  };

  DropboxVFS.prototype.write = function(item, data, callback) {
    console.info('DropboxVFS::write()', item);

    var path = OSjs.VFS.getRelativeURL(item.path);
    var bytes = data;
    /*
    if ( typeof data === 'string' ) {
      bytes = new Uint8Array(data.length);
      for (var i=0; i<data.length; i++) {
        bytes[i] = data.charCodeAt(i);
      }
    }
    */

    this.client.writeFile(path, bytes, function(error, stat) {
      if ( error ) {
        error = API._('ERR_VFSMODULE_WRITE_FMT', error);
      }
      callback(error, true);
    });
  };

  DropboxVFS.prototype.read = function(item, callback, options) {
    options = options || {};

    console.info('DropboxVFS::read()', item, options);
    var path = OSjs.VFS.getRelativeURL(item.path);
    this.client.readFile(path, options, function(error, entries) {
      if ( error ) {
        error = API._('ERR_VFSMODULE_READ_FMT', error);
      }
      callback(error, (error ? false : (entries instanceof Array ? entries.join('\n') : entries)));
    });
  };

  DropboxVFS.prototype.copy = function(src, dest, callback) {
    console.info('DropboxVFS::copy()', src, dest);
    var spath = OSjs.VFS.getRelativeURL(src.path);
    var dpath = OSjs.VFS.getRelativeURL(dest.path);
    this.client.copy(spath, dpath, function(error) {
      if ( error ) {
        error = API._('ERR_VFSMODULE_COPY_FMT', error);
      }
      callback(error, !error);
    });
  };

  DropboxVFS.prototype.move = function(src, dest, callback) {
    console.info('DropboxVFS::move()', src, dest);
    var spath = OSjs.VFS.getRelativeURL(src.path);
    var dpath = OSjs.VFS.getRelativeURL(dest.path);
    this.client.move(spath, dpath, function(error) {
      if ( error ) {
        error = API._('ERR_VFSMODULE_MOVE_FMT', error);
      }
      callback(error, !error);
    });
  };

  DropboxVFS.prototype.unlink = function(item, callback) {
    console.info('DropboxVFS::unlink()', item);
    var path = OSjs.VFS.getRelativeURL(item.path);
    this.client.unlink(path, function(error, stat) {
      if ( error ) {
        error = API._('ERR_VFSMODULE_UNLINK_FMT', error);
      }
      callback(error, !error);
    });
  };

  DropboxVFS.prototype.mkdir = function(item, callback) {
    console.info('DropboxVFS::mkdir()', item);
    var path = OSjs.VFS.getRelativeURL(item.path);
    this.client.mkdir(path, function(error, stat) {
      if ( error ) {
        error = API._('ERR_VFSMODULE_MKDIR_FMT', error);
      }
      callback(error, !error);
    });
  };

  // FIXME: Is there a better way to do this ?!
  DropboxVFS.prototype.exists = function(item, callback) {
    console.info('DropboxVFS::exists()', item);
    this.read(item, function(error, data) {
      callback(error, !error);
    });
  };

  DropboxVFS.prototype.fileinfo = function(item, callback) {
    console.info('DropboxVFS::fileinfo()', item);

    var path = OSjs.VFS.getRelativeURL(item.path);
    this.client.stat(path, path, function(error, response) {
      var fileinfo = null;
      if ( error ) {
        error = API._('ERR_VFSMODULE_FILEINFO_FMT', error);
      } else {
        if ( response ) {
          fileinfo = {};

          var useKeys = ['clientModifiedAt', 'humanSize', 'mimeType', 'modifiedAt', 'name', 'path', 'size', 'versionTag'];
          useKeys.forEach(function(k) {
            fileinfo[k] = response[k];
          });
        }
      }

      callback(error, fileinfo);
    });
  };

  DropboxVFS.prototype.url = function(item, callback) {
    console.info('DropboxVFS::url()', item);
    var path = (typeof item === 'string') ? OSjs.VFS.getRelativeURL(item) : OSjs.VFS.getRelativeURL(item.path);
    this.client.makeUrl(path, {downloadHack: true}, function(error, url) {
      callback(error, url ? url.url : false);
    });
  };

  DropboxVFS.prototype.upload = function(file, dest, callback) {
    var ndest = dest.replace(OSjs.VFS.Modules.Dropbox.match, '');
    if ( !ndest.match(/\/$/) ) {
      ndest += '/';
    }

    console.info('DropboxVFS::upload()', file, dest, ndest);

    var item = new OSjs.VFS.File({
      filename: file.name,
      path: ndest + file.name,
      mime: file.type,
      size: file.size
    });

    this.write(item, file, callback);
  };

  /////////////////////////////////////////////////////////////////////////////
  // WRAPPERS
  /////////////////////////////////////////////////////////////////////////////

  function getDropbox(callback) {
    if ( !_cachedClient ) {
      _cachedClient = new DropboxVFS();
      _cachedClient.init(function(error) {
        if ( error ) {
          console.error('Failed to initialize dropbox VFS', error);
          callback(null);
          return;
        }

        _isMounted = true;
        createNotificationIcon();
        API.message('vfs', {type: 'mount', module: 'Dropbox', source: null});

        callback(_cachedClient);
      });
      return;
    }
    callback(_cachedClient);
  }

  function signoutDropbox(cb, options) {
    cb = cb || function() {};
    options = options || null;

    getDropbox(function(client) {
      client = client ? client.client : null;
      if ( client ) {
        client.signOut(options, function() {
          _isMounted = false;
          _cachedClient = null;

          API.message('vfs', {type: 'unmount', module: 'Dropbox', source: null});

          destroyNotificationIcon();

          cb();
        });
      }
    });
  }

  function makeRequest(name, args, callback, options) {
    args = args || [];
    callback = callback || function() {};

    getDropbox(function(instance) {
      if ( !instance ) {
        callback('No Dropbox VFS API Instance was ever created. Possible intialization error');
        return;
      }
      var fargs = args;
      fargs.push(callback);
      fargs.push(options);
      instance[name].apply(instance, fargs);
    });
  }

  /////////////////////////////////////////////////////////////////////////////
  // EXPORTS
  /////////////////////////////////////////////////////////////////////////////

  OSjs.VFS.Modules.Dropbox = OSjs.VFS.Modules.Dropbox || {
    readOnly: false,
    description: 'Dropbox',
    visible: true,
    unmount: function() {
      return false; // TODO
    },
    mounted: function() {
      return _isMounted;
    },
    enabled: function() {
      if ( !window.Dropbox ) {
        return false;
      }
      return _getConfig('Enabled') || false;
    },
    root: 'dropbox:///',
    icon: 'places/dropbox.png',
    match: /^dropbox\:\/\//,
    request: makeRequest
  };

})(OSjs.Utils, OSjs.API);

<commit_msg>VFS: dropbox - Added parent directory (#28)<commit_after>/*!
 * OS.js - JavaScript Operating System
 *
 * Copyright (c) 2011-2014, Anders Evenrud <andersevenrud@gmail.com>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * @author  Anders Evenrud <andersevenrud@gmail.com>
 * @licence Simplified BSD License
 */
(function(Utils, API) {
  'use strict';

  // https://github.com/bcherry/dropbox-js
  // https://github.com/apily/dropbox/blob/master/index.js
  // https://www.dropbox.com/developers/core/start/python
  // https://www.dropbox.com/developers/reference/devguide

  window.OSjs       = window.OSjs       || {};
  OSjs.VFS          = OSjs.VFS          || {};
  OSjs.VFS.Modules  = OSjs.VFS.Modules  || {};

  var _cachedClient;
  var _isMounted = false;

  function _getConfig(cfg) {
    try {
      var handler = API.getHandlerInstance();
      if ( handler ) {
        return handler.getConfig('Core').VFS.Dropbox[cfg];
      }
    } catch ( e ) {
      console.warn('OSjs.VFS.Modules.Dropbox::enabled()', e, e.stack);
    }
    return null;
  }

  function destroyNotificationIcon() {
    var wm = API.getWMInstance();
    if ( wm ) {
      wm.removeNotificationIcon('GoogleAPIService');
    }
  }

  function createNotificationIcon() {
    var wm = API.getWMInstance();

    function displayMenu(ev) {
      var pos = {x: ev.clientX, y: ev.clientY};
      OSjs.GUI.createMenu([{
        title: API._('DROPBOX_SIGN_OUT'),
        onClick: function() {
          signoutDropbox();
        }
      }], pos);
    }

    if ( wm ) {
      wm.createNotificationIcon('DropboxVFSService', {
        onContextMenu: function(ev) {
          displayMenu(ev);
          return false;
        },
        onClick: function(ev) {
          displayMenu(ev);
          return false;
        },
        onInited: function(el) {
          if ( el.firstChild ) {
            var img = document.createElement('img');
            img.title = API._('DROPBOX_NOTIFICATION_TITLE');
            img.alt = img.title;
            img.src = API.getThemeResource('status/gtk-dialog-authentication.png', 'icon', '16x16');
            el.firstChild.appendChild(img);
          }
        }
      });
    }
  }

  /////////////////////////////////////////////////////////////////////////////
  // HELPERS
  /////////////////////////////////////////////////////////////////////////////

  function DropboxVFS() {
    var clientKey = _getConfig('ClientKey');
    this.client = new window.Dropbox.Client({ key: clientKey });
  }

  DropboxVFS.prototype.init = function(callback) {
    this.client.authenticate(function(error, client) {
      console.warn('DropboxVFS::construct()', error, client);
      callback(error);
    });
  };

  DropboxVFS.prototype.scandir = function(item, callback) {
    console.info('DropboxVFS::scandir()', item);

    var path = OSjs.VFS.getRelativeURL(item.path);
    var isOnRoot = path === '/';

    function _finish(entries) {
      var result = [];
      if ( !isOnRoot ) {
        result.push(new OSjs.VFS.File({
          filename: '..',
          path: Utils.dirname(item.path),
          mime: null,
          type: 'dir'
        }));
      }
      entries.forEach(function(iter) {
        console.info(iter);
        result.push(new OSjs.VFS.File({
          filename: iter.name,
          path: OSjs.VFS.Modules.Dropbox.root.replace(/\/$/, '') + iter.path,
          size: iter.size,
          mime: iter.isFolder ? null : iter.mimeType,
          type: iter.isFolder ? 'dir' : 'file'
        }));
      });
      console.info('DropboxVFS::scandir()', item, '=>', result);

      var list = OSjs.VFS.filterScandir(result, item._opts);
      callback(false, list);
    }

    this.client.readdir(path, {}, function(error, entries, stat, entry_stats) {
      if ( error ) {
        error = API._('ERR_VFSMODULE_SCANDIR_FMT', error);
        callback(error);
        return;
      }
      _finish(entry_stats);
    });
  };

  DropboxVFS.prototype.write = function(item, data, callback) {
    console.info('DropboxVFS::write()', item);

    var path = OSjs.VFS.getRelativeURL(item.path);
    var bytes = data;
    /*
    if ( typeof data === 'string' ) {
      bytes = new Uint8Array(data.length);
      for (var i=0; i<data.length; i++) {
        bytes[i] = data.charCodeAt(i);
      }
    }
    */

    this.client.writeFile(path, bytes, function(error, stat) {
      if ( error ) {
        error = API._('ERR_VFSMODULE_WRITE_FMT', error);
      }
      callback(error, true);
    });
  };

  DropboxVFS.prototype.read = function(item, callback, options) {
    options = options || {};

    console.info('DropboxVFS::read()', item, options);
    var path = OSjs.VFS.getRelativeURL(item.path);
    this.client.readFile(path, options, function(error, entries) {
      if ( error ) {
        error = API._('ERR_VFSMODULE_READ_FMT', error);
      }
      callback(error, (error ? false : (entries instanceof Array ? entries.join('\n') : entries)));
    });
  };

  DropboxVFS.prototype.copy = function(src, dest, callback) {
    console.info('DropboxVFS::copy()', src, dest);
    var spath = OSjs.VFS.getRelativeURL(src.path);
    var dpath = OSjs.VFS.getRelativeURL(dest.path);
    this.client.copy(spath, dpath, function(error) {
      if ( error ) {
        error = API._('ERR_VFSMODULE_COPY_FMT', error);
      }
      callback(error, !error);
    });
  };

  DropboxVFS.prototype.move = function(src, dest, callback) {
    console.info('DropboxVFS::move()', src, dest);
    var spath = OSjs.VFS.getRelativeURL(src.path);
    var dpath = OSjs.VFS.getRelativeURL(dest.path);
    this.client.move(spath, dpath, function(error) {
      if ( error ) {
        error = API._('ERR_VFSMODULE_MOVE_FMT', error);
      }
      callback(error, !error);
    });
  };

  DropboxVFS.prototype.unlink = function(item, callback) {
    console.info('DropboxVFS::unlink()', item);
    var path = OSjs.VFS.getRelativeURL(item.path);
    this.client.unlink(path, function(error, stat) {
      if ( error ) {
        error = API._('ERR_VFSMODULE_UNLINK_FMT', error);
      }
      callback(error, !error);
    });
  };

  DropboxVFS.prototype.mkdir = function(item, callback) {
    console.info('DropboxVFS::mkdir()', item);
    var path = OSjs.VFS.getRelativeURL(item.path);
    this.client.mkdir(path, function(error, stat) {
      if ( error ) {
        error = API._('ERR_VFSMODULE_MKDIR_FMT', error);
      }
      callback(error, !error);
    });
  };

  // FIXME: Is there a better way to do this ?!
  DropboxVFS.prototype.exists = function(item, callback) {
    console.info('DropboxVFS::exists()', item);
    this.read(item, function(error, data) {
      callback(error, !error);
    });
  };

  DropboxVFS.prototype.fileinfo = function(item, callback) {
    console.info('DropboxVFS::fileinfo()', item);

    var path = OSjs.VFS.getRelativeURL(item.path);
    this.client.stat(path, path, function(error, response) {
      var fileinfo = null;
      if ( error ) {
        error = API._('ERR_VFSMODULE_FILEINFO_FMT', error);
      } else {
        if ( response ) {
          fileinfo = {};

          var useKeys = ['clientModifiedAt', 'humanSize', 'mimeType', 'modifiedAt', 'name', 'path', 'size', 'versionTag'];
          useKeys.forEach(function(k) {
            fileinfo[k] = response[k];
          });
        }
      }

      callback(error, fileinfo);
    });
  };

  DropboxVFS.prototype.url = function(item, callback) {
    console.info('DropboxVFS::url()', item);
    var path = (typeof item === 'string') ? OSjs.VFS.getRelativeURL(item) : OSjs.VFS.getRelativeURL(item.path);
    this.client.makeUrl(path, {downloadHack: true}, function(error, url) {
      callback(error, url ? url.url : false);
    });
  };

  DropboxVFS.prototype.upload = function(file, dest, callback) {
    var ndest = dest.replace(OSjs.VFS.Modules.Dropbox.match, '');
    if ( !ndest.match(/\/$/) ) {
      ndest += '/';
    }

    console.info('DropboxVFS::upload()', file, dest, ndest);

    var item = new OSjs.VFS.File({
      filename: file.name,
      path: ndest + file.name,
      mime: file.type,
      size: file.size
    });

    this.write(item, file, callback);
  };

  /////////////////////////////////////////////////////////////////////////////
  // WRAPPERS
  /////////////////////////////////////////////////////////////////////////////

  function getDropbox(callback) {
    if ( !_cachedClient ) {
      _cachedClient = new DropboxVFS();
      _cachedClient.init(function(error) {
        if ( error ) {
          console.error('Failed to initialize dropbox VFS', error);
          callback(null);
          return;
        }

        _isMounted = true;
        createNotificationIcon();
        API.message('vfs', {type: 'mount', module: 'Dropbox', source: null});

        callback(_cachedClient);
      });
      return;
    }
    callback(_cachedClient);
  }

  function signoutDropbox(cb, options) {
    cb = cb || function() {};
    options = options || null;

    getDropbox(function(client) {
      client = client ? client.client : null;
      if ( client ) {
        client.signOut(options, function() {
          _isMounted = false;
          _cachedClient = null;

          API.message('vfs', {type: 'unmount', module: 'Dropbox', source: null});

          destroyNotificationIcon();

          cb();
        });
      }
    });
  }

  function makeRequest(name, args, callback, options) {
    args = args || [];
    callback = callback || function() {};

    getDropbox(function(instance) {
      if ( !instance ) {
        callback('No Dropbox VFS API Instance was ever created. Possible intialization error');
        return;
      }
      var fargs = args;
      fargs.push(callback);
      fargs.push(options);
      instance[name].apply(instance, fargs);
    });
  }

  /////////////////////////////////////////////////////////////////////////////
  // EXPORTS
  /////////////////////////////////////////////////////////////////////////////

  OSjs.VFS.Modules.Dropbox = OSjs.VFS.Modules.Dropbox || {
    readOnly: false,
    description: 'Dropbox',
    visible: true,
    unmount: function() {
      return false; // TODO
    },
    mounted: function() {
      return _isMounted;
    },
    enabled: function() {
      if ( !window.Dropbox ) {
        return false;
      }
      return _getConfig('Enabled') || false;
    },
    root: 'dropbox:///',
    icon: 'places/dropbox.png',
    match: /^dropbox\:\/\//,
    request: makeRequest
  };

})(OSjs.Utils, OSjs.API);

<|endoftext|>


<commit_before>"use strict";

var Task = require("../lib/Task.js");
var AsyncTask = require("../lib/AsyncTask.js");
var tool = require("../lib/tool.js");
var common = require("../lib/common.js");

var signals = common.signals;
var EXECUTION_DELAYED = signals.EXECUTION_DELAYED;
var ID_UNRESOLVED = signals.ID_UNRESOLVED;

// basic testing
describe("Task(),", function() {
  var fn = function story() {
    var plot = "";
    [].slice.call(arguments).forEach(function(part) {
      plot += " " + part;
    }, null);
    return plot;
  };

  var tsk = new Task(fn, ["invisible", "man"]);
  // spies`
  beforeEach(function() {
    spyOn(tsk, "addDep").and.callThrough();
    spyOn(tsk, "execute").and.callThrough();
  });

  it("makes function instances", function() {
    expect(typeof tsk).toBe("function");
    expect(tsk.name).toBe("task");
    expect(tsk.fn.name).toBe("story");
    expect(typeof tsk.fn).toBe("function");
  });

  it("can include dependencies via `addDep()`", function() {
    function d1(s) {return s || "am"}
    tsk.addDep(d1, 1, "final");
    expect(tsk.sets.dep.length).toBe(0);
    expect(tsk.sets.final[0].executable).toEqual(true);
    expect(tsk.sets.final[0].index).toEqual(1);

    function d2(s) {return s || "an"};
    tsk.addDep(d2, 2, "final");

    expect(tsk.addDep.calls.count()).toBe(2);
  });

  it("throws on bad function arg", function() {
    expect(tsk.addDep).toThrow();
  });

  it ("throws on bad index, i.e. too large or duplicate", function() {
    // ...FILL IN HEEERRRE
  });

  describe("runs via `execute()`", function() {
    it("without async dependencies", function() {
      var res;
      res = tsk.execute("I");
      expect(res).toBe(" I am an invisible man")
    });

    it("with async dependencies", function() {
      // coming soon
    });
  });

  describe("removeDep()", function() {
    it("removes dep and returns them", function() {
      var dep = function d3(){void 0}, set = "final", index = 3;
      var id = tsk.addDep(dep, index, set);

      expect(tsk.sets.final[2].actual).toBe(dep);
      expect(tsk.removeDep(id)).toBe(dep);
    });
  });
});

// sets and final args order, extensive tests
describe("Task()", function() {
  var t1, t2, tsk, expArgs;

  function d1f(){return "d1"}
  function d2f(){return "d2"}
  function i1f(){return "i1"}
  function f1f(){return "f1"}

  function setup() {
    tsk = new Task(function() {
      expect([].slice.call(arguments)).toEqual(expArgs);
    }, [t1 || "t1", t2 || "t2"]);

    tsk.addDep(d1f);
    tsk.addDep(d2f);
    tsk.addDep(i1f, "internal");
    tsk.addDep(f1f, "final");
  }

  beforeEach(setup);

  describe("arg order", function() {
    it("ordered args in natural set order", function() {
      var sets = tsk.sets;

      expect(sets.task.length).toEqual(2);
      expect(sets.dep.length).toEqual(2);
      expect(sets.internal.length).toEqual(1);
      expArgs = ["f1", "p1", "i1", "t1", "t2", "d1", "d2"];
      tsk.execute("p1");
    });

    it ("forced `index`on d1", function() {
      var id;

      function d3f(){return "d3"};
      id = tsk.addDep(d3f, 0);
      expect(tsk.sets.dep.length).toEqual(3);
      expArgs = ["f1", "p1", "i1", "t1", "t2", "d3", "d1", "d2"];
      tsk.execute("p1");
      expect(tsk.removeDep(id)).toBe(d3f);
    });

    it ("forced `index` on i1", function() {
      var id;

      expArgs = ["f1", "p1", "t1", "t2", "d1", "i1", "d2"];
      // HACK
      id = tsk.sets.internal[0].id;
      expect(tsk.removeDep(id)).toBe(i1f);
      tsk.addDep(i1f, 1, "dep");
      tsk.execute("p1");
    });
  });

  it ("moveDep()", function() {
    var id;
    function t1_5f (){return "t1.5"}
    expArgs = ["f1", "p1", "i1", "t1", "t1.5", "t2", "d1", "d2"];
    id = tsk.addDep(t1_5f, 1, "task");
    tsk.execute("p1");
    expArgs = ["f1", "p1", "i1", "t1", "t2", "t1.5", "d1", "d2"];
    expect(tsk.moveDep(id, 5, "final")).not.toEqual(id);
    tsk.execute("p1");
    expect(tsk.moveDep(-4, 5)).toEqual(jasmine.any(Object));
  });

  describe("_mayExecute()", function() {
    it ("with no asyncTsks via itself", function () {
      var res = tsk._mayExecute();
      expect(res).toBe(true);
    });

    it ("with asyncTsk's via itself", function() {
      var atsk = new AsyncTask(function(){return "atsk1"}, []);
      var cb = atsk.getCb();

      tsk.addDep(atsk);
      tsk.addDep(function(){return "blah"});
      expect(common.isAsyncTask(tsk._mayExecute())).toBe(true);
    });

    it ("with asyncTsks via execute()", function() {
          expArgs = ["f1", "p1", "i1", "t1", "t2", "d1", "d2"];
          var atsk = new AsyncTask(function(){return "atsk1"}, []);
          expect(tsk.execute("p1")).not.toBe(EXECUTION_DELAYED);
          tsk.addDep(atsk);
          expect(tsk.execute()).toBe(EXECUTION_DELAYED);
    });

    it ("depends on deps' _mayExecute()", function () {
      var atsk1 = new AsyncTask(noop, []);
      var atsk2 = new AsyncTask(noop, []);
      var atsk3 = new AsyncTask(noop, []);
      var atsk4 = new AsyncTask(noop, []);
      var tsk = new Task(noop, []);
      var tsk1 = new Task(noop, []);
      var tsk2 = new Task(noop, []);

      tsk2.addDep(atsk2);
      atsk3.addDep(atsk4);

      tsk.addDep(tsk1);
      tsk.addDep(atsk1);
      tsk.addDep(noop);
      tsk.addDep(tsk2);
      tsk.addDep(atsk3);

      expect(tsk._mayExecute()).toBe(atsk1);
      atsk1.getCb()();
      // next to block execution: atsk2 of tsk2
      expect(tsk._mayExecute()).toBe(atsk2);
      atsk2.getCb()();
      // next to block: atsk3
      expect(tsk._mayExecute()).toBe(atsk3)
      // does not exec bc of non exec dep: atsk4
      atsk3.getCb()();
      expect(atsk3._mayExecute()).toBe(atsk4)
      // so next is still: atsk3
      expect(tsk._mayExecute()).toBe(atsk3);
      // not exec the last dep atsk4
      atsk4.getCb()();
      // should be no more blocks
      expect(tsk._mayExecute()).toBe(true);

      function noop(){};
    });
  });

  describe("execute()", function() {
    it("gathers args, and passes to fn", function() {
      var task = new Task(fn, [" blue", " moon"]);
      task.addDep(function(){return " in"}, 0, "task");
      task.addDep(function() {return " a"}, 1, "task");
      expect(task.execute("Once")).toEqual("Once in a blue moon");

      function fn(once, inn, a, blue, moon) {
        return once + inn + a + blue + moon;
      }
    });

    describe("aEC", function() {
      it ("catches an asynchronous return", function() {
        var task;
        var atask = new AsyncTask(afn, []);
        var mocks = {};
        var expThing;

        mocks.fn = fn;
        spyOn(mocks, "fn").and.callThrough();
        task = new Task(mocks.fn, []);

        task.addDep(atask);
        expect(task.execute(expThing = "petty")).toBe(EXECUTION_DELAYED);
        expect(mocks.fn.calls.count()).toBe(0);
        atask.getCb()();
        expect(mocks.fn.calls.count()).toBe(1);

        function afn() {
          //...
        }

        function fn(thing) {
          expect(thing).toBe(expThing);
        }
      });
    });
  });
});
<commit_msg>added opts:autoRetry suite<commit_after>"use strict";

var Task = require("../lib/Task.js");
var AsyncTask = require("../lib/AsyncTask.js");
var tool = require("../lib/tool.js");
var common = require("../lib/common.js");

var signals = common.signals;
var EXECUTION_DELAYED = signals.EXECUTION_DELAYED;
var ID_UNRESOLVED = signals.ID_UNRESOLVED;

// basic testing
describe("Task(),", function() {
  var fn = function story() {
    var plot = "";
    [].slice.call(arguments).forEach(function(part) {
      plot += " " + part;
    }, null);
    return plot;
  };

  var tsk = new Task(fn, ["invisible", "man"]);
  // spies`
  beforeEach(function() {
    spyOn(tsk, "addDep").and.callThrough();
    spyOn(tsk, "execute").and.callThrough();
  });

  it("makes function instances", function() {
    expect(typeof tsk).toBe("function");
    expect(tsk.name).toBe("task");
    expect(tsk.fn.name).toBe("story");
    expect(typeof tsk.fn).toBe("function");
  });

  it("can include dependencies via `addDep()`", function() {
    function d1(s) {return s || "am"}
    tsk.addDep(d1, 1, "final");
    expect(tsk.sets.dep.length).toBe(0);
    expect(tsk.sets.final[0].executable).toEqual(true);
    expect(tsk.sets.final[0].index).toEqual(1);

    function d2(s) {return s || "an"};
    tsk.addDep(d2, 2, "final");

    expect(tsk.addDep.calls.count()).toBe(2);
  });

  it("throws on bad function arg", function() {
    expect(tsk.addDep).toThrow();
  });

  it ("throws on bad index, i.e. too large or duplicate", function() {
    // ...FILL IN HEEERRRE
  });

  describe("runs via `execute()`", function() {
    it("without async dependencies", function() {
      var res;
      res = tsk.execute("I");
      expect(res).toBe(" I am an invisible man")
    });

    it("with async dependencies", function() {
      // coming soon
    });
  });

  describe("removeDep()", function() {
    it("removes dep and returns them", function() {
      var dep = function d3(){void 0}, set = "final", index = 3;
      var id = tsk.addDep(dep, index, set);

      expect(tsk.sets.final[2].actual).toBe(dep);
      expect(tsk.removeDep(id)).toBe(dep);
    });
  });
});

// sets and final args order, extensive tests
describe("Task()", function() {
  var t1, t2, tsk, expArgs;

  function d1f(){return "d1"}
  function d2f(){return "d2"}
  function i1f(){return "i1"}
  function f1f(){return "f1"}

  function setup() {
    tsk = new Task(function() {
      expect([].slice.call(arguments)).toEqual(expArgs);
    }, [t1 || "t1", t2 || "t2"]);

    tsk.addDep(d1f);
    tsk.addDep(d2f);
    tsk.addDep(i1f, "internal");
    tsk.addDep(f1f, "final");
  }

  beforeEach(setup);

  describe("arg order", function() {
    it("ordered args in natural set order", function() {
      var sets = tsk.sets;

      expect(sets.task.length).toEqual(2);
      expect(sets.dep.length).toEqual(2);
      expect(sets.internal.length).toEqual(1);
      expArgs = ["f1", "p1", "i1", "t1", "t2", "d1", "d2"];
      tsk.execute("p1");
    });

    it ("forced `index`on d1", function() {
      var id;

      function d3f(){return "d3"};
      id = tsk.addDep(d3f, 0);
      expect(tsk.sets.dep.length).toEqual(3);
      expArgs = ["f1", "p1", "i1", "t1", "t2", "d3", "d1", "d2"];
      tsk.execute("p1");
      expect(tsk.removeDep(id)).toBe(d3f);
    });

    it ("forced `index` on i1", function() {
      var id;

      expArgs = ["f1", "p1", "t1", "t2", "d1", "i1", "d2"];
      // HACK
      id = tsk.sets.internal[0].id;
      expect(tsk.removeDep(id)).toBe(i1f);
      tsk.addDep(i1f, 1, "dep");
      tsk.execute("p1");
    });
  });

  it ("moveDep()", function() {
    var id;
    function t1_5f (){return "t1.5"}
    expArgs = ["f1", "p1", "i1", "t1", "t1.5", "t2", "d1", "d2"];
    id = tsk.addDep(t1_5f, 1, "task");
    tsk.execute("p1");
    expArgs = ["f1", "p1", "i1", "t1", "t2", "t1.5", "d1", "d2"];
    expect(tsk.moveDep(id, 5, "final")).not.toEqual(id);
    tsk.execute("p1");
    expect(tsk.moveDep(-4, 5)).toEqual(jasmine.any(Object));
  });

  describe("_mayExecute()", function() {
    it ("with no asyncTsks via itself", function () {
      var res = tsk._mayExecute();
      expect(res).toBe(true);
    });

    it ("with asyncTsk's via itself", function() {
      var atsk = new AsyncTask(function(){return "atsk1"}, []);
      var cb = atsk.getCb();

      tsk.addDep(atsk);
      tsk.addDep(function(){return "blah"});
      expect(common.isAsyncTask(tsk._mayExecute())).toBe(true);
    });

    it ("with asyncTsks via execute()", function() {
          expArgs = ["f1", "p1", "i1", "t1", "t2", "d1", "d2"];
          var atsk = new AsyncTask(function(){return "atsk1"}, []);
          expect(tsk.execute("p1")).not.toBe(EXECUTION_DELAYED);
          tsk.addDep(atsk);
          expect(tsk.execute()).toBe(EXECUTION_DELAYED);
    });

    it ("depends on deps' _mayExecute()", function () {
      var atsk1 = new AsyncTask(noop, []);
      var atsk2 = new AsyncTask(noop, []);
      var atsk3 = new AsyncTask(noop, []);
      var atsk4 = new AsyncTask(noop, []);
      var tsk = new Task(noop, []);
      var tsk1 = new Task(noop, []);
      var tsk2 = new Task(noop, []);

      tsk2.addDep(atsk2);
      atsk3.addDep(atsk4);

      tsk.addDep(tsk1);
      tsk.addDep(atsk1);
      tsk.addDep(noop);
      tsk.addDep(tsk2);
      tsk.addDep(atsk3);

      expect(tsk._mayExecute()).toBe(atsk1);
      atsk1.getCb()();
      // next to block execution: atsk2 of tsk2
      expect(tsk._mayExecute()).toBe(atsk2);
      atsk2.getCb()();
      // next to block: atsk3
      expect(tsk._mayExecute()).toBe(atsk3)
      // does not exec bc of non exec dep: atsk4
      atsk3.getCb()();
      expect(atsk3._mayExecute()).toBe(atsk4)
      // so next is still: atsk3
      expect(tsk._mayExecute()).toBe(atsk3);
      // not exec the last dep atsk4
      atsk4.getCb()();
      // should be no more blocks
      expect(tsk._mayExecute()).toBe(true);

      function noop(){};
    });
  });

  describe("execute()", function() {
    it("gathers args, and passes to fn", function() {
      var task = new Task(fn, [" blue", " moon"]);
      task.addDep(function(){return " in"}, 0, "task");
      task.addDep(function() {return " a"}, 1, "task");
      expect(task.execute("Once")).toEqual("Once in a blue moon");

      function fn(once, inn, a, blue, moon) {
        return once + inn + a + blue + moon;
      }
    });

    describe("opts:autoRetry", function() {
      it ("auto retry's when async is completed", function () {
        var assertMe = 0;
        var tsk = new Task(function(){assertMe++}, [], {autoRetry: true});
        var atsk = new AsyncTask(function NOP(){}, []);
        tsk.addDep(atsk);
        expect(tsk.execute()).toBe(EXECUTION_DELAYED);
        expect(assertMe).toBe(0)
        atsk.getCb()();
        expect(assertMe).toBe(1);
      });
      it ("has autRetry set to default true", function() {
        var assertMe = 0;
        var tsk = new Task(function(){assertMe++}, []);
        var atsk = new AsyncTask(function NOP(){}, []);
        tsk.addDep(atsk);
        expect(tsk.execute()).toBe(EXECUTION_DELAYED);
        expect(assertMe).toBe(0)
        atsk.getCb()();
        expect(assertMe).toBe(1);
      });

      it ("does not reTry when opts:autoRetry is off", function() {
        var assertMe = 0;
        var tsk = new Task(function(){assertMe++}, [], {autoRetry: false});
        var atsk = new AsyncTask(function NOP(){}, []);
        tsk.addDep(atsk);
        expect(tsk.execute()).toBe(EXECUTION_DELAYED);
        expect(assertMe).toBe(0)
        atsk.getCb()();
        expect(assertMe).toBe(0);
        tsk.execute();
        expect(assertMe).toBe(1);
      });
    });

    describe("aEC", function() {
      it ("catches an asynchronous return", function() {
        var task;
        var atask = new AsyncTask(afn, []);
        var mocks = {};
        var expThing;

        mocks.fn = fn;
        spyOn(mocks, "fn").and.callThrough();
        task = new Task(mocks.fn, []);

        task.addDep(atask);
        expect(task.execute(expThing = "petty")).toBe(EXECUTION_DELAYED);
        expect(mocks.fn.calls.count()).toBe(0);
        atask.getCb()();
        expect(mocks.fn.calls.count()).toBe(1);

        function afn() {
          //...
        }

        function fn(thing) {
          expect(thing).toBe(expThing);
        }
      });
    });
  });
});
<|endoftext|>


<commit_before>/**
 * mSupply Mobile
 * Sustainable Solutions (NZ) Ltd. 2019
 */

/**
 * Method using a factory pattern variant to get a reducer
 * for a particular page or page style.
 *
 * For a new page - create a constant object with the
 * methods from reducerMethods which are composed to create
 * a reducer. Add to PAGE_REDUCERS.
 *
 * Each key value pair in a reducer object should be in the form
 * action type: reducer function, returning a new state object
 *
 */

import {
  filterData,
  editTotalQuantity,
  focusNextCell,
  selectRow,
  deselectRow,
  deselectAll,
  focusCell,
  sortData,
  openBasicModal,
  closeBasicModal,
  addMasterListItems,
  addItem,
  editTheirRef,
  editComment,
  deleteRecordsById,
  refreshData,
  editBatchExpiry,
} from './reducerMethods';

/**
 * Used for actions that should be in all pages using a data table.
 */
const BASE_TABLE_PAGE_REDUCER = {
  focusNextCell,
  focusCell,
  sortData,
};

const customerInvoice = {
  ...BASE_TABLE_PAGE_REDUCER,
  filterData,
  editTotalQuantity,
  selectRow,
  deselectRow,
  deselectAll,
  openBasicModal,
  closeBasicModal,
  addMasterListItems,
  addItem,
  editTheirRef,
  editComment,
  deleteRecordsById,
  refreshData,
};

const customerInvoices = {
  ...BASE_TABLE_PAGE_REDUCER,
  filterData,
  selectRow,
  deselectRow,
  deselectAll,
  openBasicModal,
  closeBasicModal,
  deleteRecordsById,
};

const supplierInvoice = {
  ...BASE_TABLE_PAGE_REDUCER,
  filterData,
  selectRow,
  deselectRow,
  deselectAll,
  closeBasicModal,
  openBasicModal,
  editTheirRef,
  editComment,
  refreshData,
  addItem,
  editTotalQuantity,
  deleteRecordsById,
  editBatchExpiry,
};

const supplierRequisitions = {
  sortData,
  filterData,
  selectRow,
  deselectRow,
  deselectAll,
  openBasicModal,
  closeBasicModal,
  refreshData,
  deleteRecordsById,
};

const supplierRequisitions = {
  sortData,
  filterData,
  selectRow,
  deselectRow,
  openBasicModal,
  closeBasicModal,
};

const PAGE_REDUCERS = {
  customerInvoice,
  customerInvoices,
  supplierInvoice,
  supplierRequisitions,
};

const getReducer = page => {
  const reducer = PAGE_REDUCERS[page];
  return (state, action) => {
    const { type } = action;
    if (!reducer[type]) return state;
    return reducer[type](state, action);
  };
};

export default getReducer;
<commit_msg>Add basic SupplierRequisitionPage reducer<commit_after>/**
 * mSupply Mobile
 * Sustainable Solutions (NZ) Ltd. 2019
 */

/**
 * Method using a factory pattern variant to get a reducer
 * for a particular page or page style.
 *
 * For a new page - create a constant object with the
 * methods from reducerMethods which are composed to create
 * a reducer. Add to PAGE_REDUCERS.
 *
 * Each key value pair in a reducer object should be in the form
 * action type: reducer function, returning a new state object
 *
 */

import {
  filterData,
  editTotalQuantity,
  focusNextCell,
  selectRow,
  deselectRow,
  deselectAll,
  focusCell,
  sortData,
  openBasicModal,
  closeBasicModal,
  addMasterListItems,
  addItem,
  editTheirRef,
  editComment,
  deleteRecordsById,
  refreshData,
  editBatchExpiry,
} from './reducerMethods';

/**
 * Used for actions that should be in all pages using a data table.
 */
const BASE_TABLE_PAGE_REDUCER = {
  focusNextCell,
  focusCell,
  sortData,
};

const customerInvoice = {
  ...BASE_TABLE_PAGE_REDUCER,
  filterData,
  editTotalQuantity,
  selectRow,
  deselectRow,
  deselectAll,
  openBasicModal,
  closeBasicModal,
  addMasterListItems,
  addItem,
  editTheirRef,
  editComment,
  deleteRecordsById,
  refreshData,
};

const customerInvoices = {
  ...BASE_TABLE_PAGE_REDUCER,
  filterData,
  selectRow,
  deselectRow,
  deselectAll,
  openBasicModal,
  closeBasicModal,
  deleteRecordsById,
};

const supplierInvoice = {
  ...BASE_TABLE_PAGE_REDUCER,
  filterData,
  selectRow,
  deselectRow,
  deselectAll,
  closeBasicModal,
  openBasicModal,
  editTheirRef,
  editComment,
  refreshData,
  addItem,
  editTotalQuantity,
  deleteRecordsById,
  editBatchExpiry,
};

const supplierRequisitions = {
  sortData,
  filterData,
  selectRow,
  deselectRow,
  deselectAll,
  openBasicModal,
  closeBasicModal,
  refreshData,
  deleteRecordsById,
};

const supplierRequisitions = {
  sortData,
  filterData,
  selectRow,
  deselectRow,
  openBasicModal,
  closeBasicModal,
};

const supplierRequisition = {
  ...BASE_TABLE_PAGE_REDUCER,
  filterData,
  selectRow,
  deselectRow,
  deselectAll,
  openBasicModal,
  closeBasicModal,
  editTheirRef,
  editComment,
};

const PAGE_REDUCERS = {
  customerInvoice,
  customerInvoices,
  supplierInvoice,
  supplierRequisitions,
  supplierRequisition,
};

const getReducer = page => {
  const reducer = PAGE_REDUCERS[page];
  return (state, action) => {
    const { type } = action;
    if (!reducer[type]) return state;
    return reducer[type](state, action);
  };
};

export default getReducer;
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2016
 *
 * This file is licensed under the Affero General Public License version 3
 * or later.
 *
 * See the COPYING-README file.
 *
 */

(function () {
	SidebarPreviewManager = function (fileList) {
		this._fileList = fileList;
		this._previewHandlers = {};
		OC.Plugins.attach('OCA.Files.SidebarPreviewManager', this);
	};

	SidebarPreviewManager.prototype = {
		addPreviewHandler: function (mime, handler) {
			this._previewHandlers[mime] = handler;
		},

		getPreviewHandler: function (mime) {
			var mimePart = mime.split('/').shift();
			if (this._previewHandlers[mime]) {
				return this._previewHandlers[mime];
			} else if(this._previewHandlers[mimePart]) {
				return this._previewHandlers[mimePart];
			} else {
				return this.fallbackPreview.bind(this);
			}
		},

		loadPreview: function (model, $thumbnailDiv, $thumbnailContainer) {
			if (model.get('hasPreview') === false) {
				var mimeIcon = OC.MimeType.getIconUrl(model.get('mimetype'));
				$thumbnailDiv.removeClass('icon-loading icon-32');
				$thumbnailContainer.removeClass('image'); //fall back to regular view
				$thumbnailDiv.css({
					'background-image': 'url("' + mimeIcon + '")'
				});
			} else {
				var handler = this.getPreviewHandler(model.get('mimetype'));
				var fallback = this.fallbackPreview.bind(this, model, $thumbnailDiv, $thumbnailContainer);
				handler(model, $thumbnailDiv, $thumbnailContainer, fallback);
			}
		},

		// previews for images and mimetype icons
		fallbackPreview: function (model, $thumbnailDiv, $thumbnailContainer) {
			var isImage = model.isImage();
			var maxImageWidth = $thumbnailContainer.parent().width() + 50;  // 50px for negative margins
			var maxImageHeight = maxImageWidth / (16 / 9);
			var smallPreviewSize = 75;

			var isLandscape = function (img) {
				return img.width > (img.height * 1.2);
			};

			var isSmall = function (img) {
				return (img.width * 1.1) < (maxImageWidth * window.devicePixelRatio);
			};

			var getTargetHeight = function (img) {
				if (isImage) {
					var targetHeight = img.height / window.devicePixelRatio;
					if (targetHeight <= smallPreviewSize) {
						targetHeight = smallPreviewSize;
					}
					return targetHeight;
				} else {
					return smallPreviewSize;
				}
			};

			var getTargetRatio = function (img) {
				var ratio = img.width / img.height;
				if (ratio > 16 / 9) {
					return ratio;
				} else {
					return 16 / 9;
				}
			};

			this._fileList.lazyLoadPreview({
				path: model.getFullPath(),
				mime: model.get('mimetype'),
				etag: model.get('etag'),
				y: isImage ? maxImageHeight : smallPreviewSize,
				x: isImage ? maxImageWidth : smallPreviewSize,
				a: isImage ? 1 : null,
				mode: isImage ? 'cover' : null,
				callback: function (previewUrl, img) {
					$thumbnailDiv.previewImg = previewUrl;

					// as long as we only have the mimetype icon, we only save it in case there is no preview
					if (!img) {
						return;
					}
					$thumbnailDiv.removeClass('icon-loading icon-32');
					var targetHeight = getTargetHeight(img);
					if (isImage && targetHeight > smallPreviewSize) {
						$thumbnailContainer.addClass((isLandscape(img) && !isSmall(img)) ? 'landscape' : 'portrait');
						$thumbnailContainer.addClass('large');
					}

					// only set background when we have an actual preview
					// when we don't have a preview we show the mime icon in the error handler
					$thumbnailDiv.css({
						'background-image': 'url("' + previewUrl + '")',
						height: (targetHeight > smallPreviewSize) ? 'auto' : targetHeight,
						'max-height': isSmall(img) ? targetHeight : null
					});

					var targetRatio = getTargetRatio(img);
					$thumbnailDiv.find('.stretcher').css({
						'padding-bottom': (100 / targetRatio) + '%'
					});
				},
				error: function () {
					$thumbnailDiv.removeClass('icon-loading icon-32');
					$thumbnailContainer.removeClass('image'); //fall back to regular view
					$thumbnailDiv.css({
						'background-image': 'url("' + $thumbnailDiv.previewImg + '")'
					});
				}
			});
		}
	};

	OCA.Files.SidebarPreviewManager = SidebarPreviewManager;
})();
<commit_msg>allow registering sidebar preview handlers for mimetypes that dont come with server side previews<commit_after>/*
 * Copyright (c) 2016
 *
 * This file is licensed under the Affero General Public License version 3
 * or later.
 *
 * See the COPYING-README file.
 *
 */

(function () {
	SidebarPreviewManager = function (fileList) {
		this._fileList = fileList;
		this._previewHandlers = {};
		OC.Plugins.attach('OCA.Files.SidebarPreviewManager', this);
	};

	SidebarPreviewManager.prototype = {
		addPreviewHandler: function (mime, handler) {
			this._previewHandlers[mime] = handler;
		},

		getMimeTypePreviewHandler: function(mime) {
			var mimePart = mime.split('/').shift();
			if (this._previewHandlers[mime]) {
				return this._previewHandlers[mime];
			} else if (this._previewHandlers[mimePart]) {
				return this._previewHandlers[mimePart];
			} else {
				return null;
			}
		},

		getPreviewHandler: function (mime) {
			var mimetypeHandler = this.getMimeTypePreviewHandler(mime);
			if (mimetypeHandler) {
				return mimetypeHandler;
			} else {
				return this.fallbackPreview.bind(this);
			}
		},

		loadPreview: function (model, $thumbnailDiv, $thumbnailContainer) {
			if (model.get('hasPreview') === false && this.getMimeTypePreviewHandler(model.get('mimetype')) === null) {
				var mimeIcon = OC.MimeType.getIconUrl(model.get('mimetype'));
				$thumbnailDiv.removeClass('icon-loading icon-32');
				$thumbnailContainer.removeClass('image'); //fall back to regular view
				$thumbnailDiv.css({
					'background-image': 'url("' + mimeIcon + '")'
				});
			} else {
				var handler = this.getPreviewHandler(model.get('mimetype'));
				var fallback = this.fallbackPreview.bind(this, model, $thumbnailDiv, $thumbnailContainer);
				handler(model, $thumbnailDiv, $thumbnailContainer, fallback);
			}
		},

		// previews for images and mimetype icons
		fallbackPreview: function (model, $thumbnailDiv, $thumbnailContainer) {
			var isImage = model.isImage();
			var maxImageWidth = $thumbnailContainer.parent().width() + 50;  // 50px for negative margins
			var maxImageHeight = maxImageWidth / (16 / 9);
			var smallPreviewSize = 75;

			var isLandscape = function (img) {
				return img.width > (img.height * 1.2);
			};

			var isSmall = function (img) {
				return (img.width * 1.1) < (maxImageWidth * window.devicePixelRatio);
			};

			var getTargetHeight = function (img) {
				if (isImage) {
					var targetHeight = img.height / window.devicePixelRatio;
					if (targetHeight <= smallPreviewSize) {
						targetHeight = smallPreviewSize;
					}
					return targetHeight;
				} else {
					return smallPreviewSize;
				}
			};

			var getTargetRatio = function (img) {
				var ratio = img.width / img.height;
				if (ratio > 16 / 9) {
					return ratio;
				} else {
					return 16 / 9;
				}
			};

			this._fileList.lazyLoadPreview({
				path: model.getFullPath(),
				mime: model.get('mimetype'),
				etag: model.get('etag'),
				y: isImage ? maxImageHeight : smallPreviewSize,
				x: isImage ? maxImageWidth : smallPreviewSize,
				a: isImage ? 1 : null,
				mode: isImage ? 'cover' : null,
				callback: function (previewUrl, img) {
					$thumbnailDiv.previewImg = previewUrl;

					// as long as we only have the mimetype icon, we only save it in case there is no preview
					if (!img) {
						return;
					}
					$thumbnailDiv.removeClass('icon-loading icon-32');
					var targetHeight = getTargetHeight(img);
					if (isImage && targetHeight > smallPreviewSize) {
						$thumbnailContainer.addClass((isLandscape(img) && !isSmall(img)) ? 'landscape' : 'portrait');
						$thumbnailContainer.addClass('large');
					}

					// only set background when we have an actual preview
					// when we don't have a preview we show the mime icon in the error handler
					$thumbnailDiv.css({
						'background-image': 'url("' + previewUrl + '")',
						height: (targetHeight > smallPreviewSize) ? 'auto' : targetHeight,
						'max-height': isSmall(img) ? targetHeight : null
					});

					var targetRatio = getTargetRatio(img);
					$thumbnailDiv.find('.stretcher').css({
						'padding-bottom': (100 / targetRatio) + '%'
					});
				},
				error: function () {
					$thumbnailDiv.removeClass('icon-loading icon-32');
					$thumbnailContainer.removeClass('image'); //fall back to regular view
					$thumbnailDiv.css({
						'background-image': 'url("' + $thumbnailDiv.previewImg + '")'
					});
				}
			});
		}
	};

	OCA.Files.SidebarPreviewManager = SidebarPreviewManager;
})();
<|endoftext|>