<commit_before>
var CAMERA_MOVE_LENGTH = 2;

function onDocumentMouseMove( event ) {
    event.preventDefault();

    mouse2D.x = ( event.clientX / window.innerWidth ) * 2 - 1;
    mouse2D.y = - ( event.clientY / window.innerHeight ) * 2 + 1;

}

function onDocumentKeyDown( event ) {
    if (!gameInProgress) {
        return;
    }

    var toMove = new THREE.Vector3(0, 0, 0);
    var moved = false;
    var newPos;
    var rotated = false;

    switch( event.keyCode ) {
        case 49: // NUMBER 1
            rotate( "yaw" );
            rotated = true;
            break;
        case 50: // NUMBER 2
            rotate( "pitch" );
            rotated = true;
            break;
        case 51: // NUMBER 3
            rotate( "roll" );
            rotated = true;
            break;
        case 16:
            isShiftDown = true;
            if (boundingBox) {
                boundingBox.visible = !boundingBox.visible;
            }
            break;
        case 17: isCtrlDown = true; break;
        case 187: isEqualsDown = true; break;
        case 189: isDashDown = true; break;
        case 76: change_to_level(); break;//the "l" key
        case 65:
            aDown = true;
            moveLeft(gameBoardOrientation, toMove);
            moved = true;
            break;
        case 87:
            wDown = true;
            moveForward(gameBoardOrientation, toMove);
            moved = true;
            break;
        case 83:
            sDown = true;
            moveBackward(gameBoardOrientation, toMove);
            moved = true;
            break;
        case 68:
            dDown = true;
            moveRight(gameBoardOrientation, toMove);
            moved = true;
            break;
        case 81:
            qDown = true;
            toMove.y += STEP_SIZE;
            moved = true;
            break;
        case 69:
            eDown = true;
            toMove.y -= STEP_SIZE;
            moved = true;
            break;
        case 37:
            isLeftDown = true;
            break;
        case 32:
            isSpaceDown = true;
            add_voxel();
            break;
    }

    if ( rotated ) {
        newPos = rollOverMesh.position.clone();

        while (!BlockGenerator.isPosLegal(newPos)) {
            if (pos_illegal_code == 2) {
                moveIntoBounds(newPos);
                rollOverMesh.position = newPos;
            } else {
                console.log("wahh");
                newPos.y += STEP_SIZE;
            }
        }
        rollOverMesh.position = newPos;
    }

    // check if move is legal
    if (moved) {
        newPos = rollOverMesh.position.clone();
        newPos.add(toMove);
        newPos.y = STEP_SIZE / 2;

        while ( !BlockGenerator.isPosLegal(newPos) ) {
            // if it's the boundary, just don't let the player move it
            if (pos_illegal_code == 2) {
                collisionNoise.load();
                collisionNoise.play();
                return;
            }
            newPos.y += STEP_SIZE;
        }
        rollOverMesh.position = newPos;
    }
}

function onDocumentKeyUp( event ) {
    switch ( event.keyCode ) {
        case 16: isShiftDown = false; break;
        case 17: isCtrlDown = false; break;
        case 187: isEqualsDown = false; break;
        case 189: isDashDown = false; break;
        case 65: aDown = false; break;
        case 87: wDown = false; break;
        case 83: sDown = false; break;
        case 68: dDown = false; break;
        case 32: isSpaceDown = false; break;
    }
}

function moveLeft( axis, position ) {
    switch ( axis ) {
        case 1: position.x -= STEP_SIZE; break;
        case 2: position.z -= STEP_SIZE; break;
        case 3: position.z += STEP_SIZE; break;
        case 4: position.x += STEP_SIZE; break;
    }
}

function moveRight( axis, position ) {
    switch ( axis ) {
        case 1: position.x += STEP_SIZE; break;
        case 2: position.z += STEP_SIZE; break;
        case 3: position.z -= STEP_SIZE; break;
        case 4: position.x -= STEP_SIZE; break;
    }
}

function moveForward( axis, position ) {
    switch ( axis ) {
        case 1: position.z -= STEP_SIZE; break;
        case 2: position.x += STEP_SIZE; break;
        case 3: position.x -= STEP_SIZE; break;
        case 4: position.z += STEP_SIZE; break;
    }
}

function moveBackward( axis, position ) {
    switch ( axis ) {
        case 1: position.z += STEP_SIZE; break;
        case 2: position.x -= STEP_SIZE; break;
        case 3: position.x += STEP_SIZE; break;
        case 4: position.z -= STEP_SIZE; break;
    }
}

// directions: "pitch", "yaw", "roll"
function rotate( direction ) {
    if ( direction == "yaw" ) {
        BlockGenerator.rotate( 0, 90, 0 );
    }
    if ( direction == "pitch" ) {
        BlockGenerator.rotate( 90, 0, 0 );
    }
    if ( direction == "roll" ) {
        BlockGenerator.rotate( 0, 0, 90 );
    }
}

function change_to_level(){
    if(level_mode==true)
        return;
    game_mode.innerHTML = "Level 1";

    change_rollOver(level_1[0]);

    level_mode = true;
    //populates the selection button
    for(var i =0; i<level_1.length;i++){
        var option = document.createElement("option");
        option.text = level_1[i];
        avail_blocks.add(option);
    }
    nextPiece_doc.innerHTML = '';
}

function change_rollOver(shape){
    block = BlockGenerator.generate(shape);
    var oldPos = rollOverMesh.position.clone();
    scene.remove(rollOverMesh);
    rollOverMesh = block.mesh;

    moveBackward(gameBoardOrientation, oldPos);
    while (!BlockGenerator.isPosLegal(oldPos)) {
        if (pos_illegal_code == 1) {
            moveBackward(gameBoardOrientation, oldPos);
        } else if (pos_illegal_code == 2) {
            break;
        }
    }

    // on the edge already. first move back until we're okay then move up until we're okay
    if (pos_illegal_code == 2) {
        moveForward(gameBoardOrientation, oldPos);
        while (!BlockGenerator.isPosLegal(oldPos)) {
            if (pos_illegal_code == 1) {
                oldPos.y += STEP_SIZE;
            } else if (pos_illegal_code == 2) {
                moveForward(gameBoardOrientation, oldPos);
            }
        }
    }

    rollOverMesh.position.x = oldPos.x;
    rollOverMesh.position.y = oldPos.y;
    rollOverMesh.position.z = oldPos.z;
    scene.add(rollOverMesh);

}

function add_voxel( ) {
    var voxel = rollOverMesh;
    var oldPos = voxel.position.clone();
    oldPos.y = STEP_SIZE / 2;

    // places rollover block down and make it static
    voxel.material.opacity = 1.0;
    voxel.material.transparent = false;
    voxel.matrixAutoUpdate = false;
    voxel.geometry.verticesNeedUpdate = true;
    voxel.castShadow = false;
    voxel.updateMatrix();

    // update all blocks
    BlockGenerator.addToExisting(voxel.position);
    volume_doc.innerHTML = BlockGenerator.totalVolume;

    blockNoise.load();
    blockNoise.play();

    // add new block to block_list
    block_list.push(voxel);

    // calculate new bounding box
    getBoundingBox();

    //check to see if level mode
    if(level_mode){
        avail_blocks.remove(avail_blocks.selectedIndex);
        if(avail_blocks.length==0){
            endLevel();
            return;
        }
        nextPiece = avail_blocks[avail_blocks.selectedIndex].innerHTML;
    }

    // create new block and use that new block as rollover
    block = BlockGenerator.generate(nextPiece);
    rollOverMesh = block.mesh;

    if(!level_mode){
        nextPiece = getRandomMember(BlockGenerator.allShapes);
        nextPiece_doc.innerHTML = nextPiece;
    }

    // placement of the new block - first move towards user's perspective until we can't move anymore
    moveBackward(gameBoardOrientation, oldPos);
    while (!BlockGenerator.isPosLegal(oldPos)) {
        if (pos_illegal_code == 1) {
            moveBackward(gameBoardOrientation, oldPos);
        } else if (pos_illegal_code == 2) {
            break;
        }
    }

    // on the edge already. first move back until we're okay then move up until we're okay
    if (pos_illegal_code == 2) {
        moveForward(gameBoardOrientation, oldPos);
        while (!BlockGenerator.isPosLegal(oldPos)) {
            if (pos_illegal_code == 1) {
                oldPos.y += STEP_SIZE;
            } else if (pos_illegal_code == 2) {
                moveForward(gameBoardOrientation, oldPos);
            }
        }
    }

    rollOverMesh.position.x = oldPos.x;
    rollOverMesh.position.y = oldPos.y;
    rollOverMesh.position.z = oldPos.z;
    scene.add( rollOverMesh );
}

function onWindowResize() {
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();

    console.log(window.innerWidth / window.innerHeight);
    backgroundCamera.aspect = window.innerWidth / window.innerHeight;
    backgroundCamera.updateProjectionMatrix();

    renderer.setSize( window.innerWidth, window.innerHeight );
}<commit_msg>Made controls smoother.  Disabled faulty rotation controls (pitch,roll), will re-add when they work correctly.<commit_after>
var CAMERA_MOVE_LENGTH = 2;

function onDocumentMouseMove( event ) {
    event.preventDefault();

    mouse2D.x = ( event.clientX / window.innerWidth ) * 2 - 1;
    mouse2D.y = - ( event.clientY / window.innerHeight ) * 2 + 1;

}

function onDocumentKeyDown( event ) {
    if (!gameInProgress) {
        return;
    }

    var toMove = new THREE.Vector3(0, 0, 0);
    var moved = false;
    var newPos;
    var rotated = false;

    switch( event.keyCode ) {
        case 49: // NUMBER 1
            rotate( "yaw" );
            rotated = true;
            break;
        case 50: // NUMBER 2
            rotate( "pitch" );
            rotated = true;
            break;
        case 51: // NUMBER 3
            rotate( "roll" );
            rotated = true;
            break;
        case 16:
            isShiftDown = true;
            if (boundingBox) {
                boundingBox.visible = !boundingBox.visible;
            }
            break;
        case 17: isCtrlDown = true; break;
        case 187: isEqualsDown = true; break;
        case 189: isDashDown = true; break;
        case 76: change_to_level(); break;//the "l" key
        case 65:
            aDown = true;
            moveLeft(gameBoardOrientation, toMove);
            moved = true;
            break;
        case 87:
            wDown = true;
            moveForward(gameBoardOrientation, toMove);
            moved = true;
            break;
        case 83:
            sDown = true;
            moveBackward(gameBoardOrientation, toMove);
            moved = true;
            break;
        case 68:
            dDown = true;
            moveRight(gameBoardOrientation, toMove);
            moved = true;
            break;
        case 81:
            qDown = true;
            toMove.y += STEP_SIZE;
            moved = true;
            break;
        case 69:
            eDown = true;
            toMove.y -= STEP_SIZE;
            moved = true;
            break;
        case 37:
            isLeftDown = true;
            break;
        case 32:
            isSpaceDown = true;
            add_voxel();
            break;
    }

    if ( rotated ) {
        newPos = rollOverMesh.position.clone();

        while (!BlockGenerator.isPosLegal(newPos)) {
            if (pos_illegal_code == 2) {
                moveIntoBounds(newPos);
                rollOverMesh.position = newPos;
            } else {
                console.log("wahh");
                newPos.y += STEP_SIZE;
            }
        }
        rollOverMesh.position = newPos;
    }

    // check if move is legal
    if (moved) {
        newPos = rollOverMesh.position.clone();
        newPos.add(toMove);
        var isClimbing = false;
        //try to move in direction specified
        if ( !BlockGenerator.isPosLegal(newPos) ) {
            // ran into a wall, play error noise
            if (pos_illegal_code == 2) {
                collisionNoise.load();
                collisionNoise.play();
                return;
            }
            // ran into a block, move up instead of over
            if (pos_illegal_code == 1) {
                newPos.y += STEP_SIZE;
                newPos.sub(toMove);
                rollOverMesh.position = newPos;
                isClimbing = true;
                return;
            }
        }

        // Didn't run into a block or a wall, try to lower the piece as much as possible.
        while (true) {
            newPos.y -= STEP_SIZE;
            if (!BlockGenerator.isPosLegal(newPos)) {
                newPos.y += STEP_SIZE;
                break;
            }
        }
        // if( !isClimbing ) {
            // newPos.y = 25;
            // if (BlockGenerator.isPosLegal(newPos)) {
            //     rollOverMesh.position = newPos;
            // } else {
            //     return;
            // }
            // while( BlockGenerator.isPosLegal(newPos) && newPos.y >= 75)  {
            //     newPos.y -= STEP_SIZE;
            // }
        // }

        rollOverMesh.position = newPos;
    }
}

function onDocumentKeyUp( event ) {
    switch ( event.keyCode ) {
        case 16: isShiftDown = false; break;
        case 17: isCtrlDown = false; break;
        case 187: isEqualsDown = false; break;
        case 189: isDashDown = false; break;
        case 65: aDown = false; break;
        case 87: wDown = false; break;
        case 83: sDown = false; break;
        case 68: dDown = false; break;
        case 32: isSpaceDown = false; break;
    }
}

function moveLeft( axis, position ) {
    switch ( axis ) {
        case 1: position.x -= STEP_SIZE; break;
        case 2: position.z -= STEP_SIZE; break;
        case 3: position.z += STEP_SIZE; break;
        case 4: position.x += STEP_SIZE; break;
    }
}

function moveRight( axis, position ) {
    switch ( axis ) {
        case 1: position.x += STEP_SIZE; break;
        case 2: position.z += STEP_SIZE; break;
        case 3: position.z -= STEP_SIZE; break;
        case 4: position.x -= STEP_SIZE; break;
    }
}

function moveForward( axis, position ) {
    switch ( axis ) {
        case 1: position.z -= STEP_SIZE; break;
        case 2: position.x += STEP_SIZE; break;
        case 3: position.x -= STEP_SIZE; break;
        case 4: position.z += STEP_SIZE; break;
    }
}

function moveBackward( axis, position ) {
    switch ( axis ) {
        case 1: position.z += STEP_SIZE; break;
        case 2: position.x -= STEP_SIZE; break;
        case 3: position.x += STEP_SIZE; break;
        case 4: position.z -= STEP_SIZE; break;
    }
}

// directions: "pitch", "yaw", "roll"
function rotate( direction ) {
    if ( direction == "yaw" ) {
        BlockGenerator.rotate( 0, 90, 0 );
    }
    if ( direction == "pitch" ) {
        BlockGenerator.rotate( 90, 0, 0 );
    }
    if ( direction == "roll" ) {
        BlockGenerator.rotate( 0, 0, 90 );
    }
}

function change_to_level(){
    if(level_mode==true)
        return;
    game_mode.innerHTML = "Level 1";

    change_rollOver(level_1[0]);

    level_mode = true;
    //populates the selection button
    for(var i =0; i<level_1.length;i++){
        var option = document.createElement("option");
        option.text = level_1[i];
        avail_blocks.add(option);
    }
    nextPiece_doc.innerHTML = '';
}

function change_rollOver(shape){
    block = BlockGenerator.generate(shape);
    var oldPos = rollOverMesh.position.clone();
    scene.remove(rollOverMesh);
    rollOverMesh = block.mesh;

    moveBackward(gameBoardOrientation, oldPos);
    while (!BlockGenerator.isPosLegal(oldPos)) {
        if (pos_illegal_code == 1) {
            moveBackward(gameBoardOrientation, oldPos);
        } else if (pos_illegal_code == 2) {
            break;
        }
    }

    // on the edge already. first move back until we're okay then move up until we're okay
    if (pos_illegal_code == 2) {
        moveForward(gameBoardOrientation, oldPos);
        while (!BlockGenerator.isPosLegal(oldPos)) {
            if (pos_illegal_code == 1) {
                oldPos.y += STEP_SIZE;
            } else if (pos_illegal_code == 2) {
                moveForward(gameBoardOrientation, oldPos);
            }
        }
    }

    rollOverMesh.position.x = oldPos.x;
    rollOverMesh.position.y = oldPos.y;
    rollOverMesh.position.z = oldPos.z;
    scene.add(rollOverMesh);

}

function add_voxel( ) {
    var voxel = rollOverMesh;
    var oldPos = voxel.position.clone();
    oldPos.y = STEP_SIZE / 2;

    // places rollover block down and make it static
    voxel.material.opacity = 1.0;
    voxel.material.transparent = false;
    voxel.matrixAutoUpdate = false;
    voxel.geometry.verticesNeedUpdate = true;
    voxel.castShadow = false;
    voxel.updateMatrix();

    // update all blocks
    BlockGenerator.addToExisting(voxel.position);
    volume_doc.innerHTML = BlockGenerator.totalVolume;

    blockNoise.load();
    blockNoise.play();

    // add new block to block_list
    block_list.push(voxel);

    // calculate new bounding box
    getBoundingBox();

    //check to see if level mode
    if(level_mode){
        avail_blocks.remove(avail_blocks.selectedIndex);
        if(avail_blocks.length==0){
            endLevel();
            return;
        }
        nextPiece = avail_blocks[avail_blocks.selectedIndex].innerHTML;
    }

    // create new block and use that new block as rollover
    block = BlockGenerator.generate(nextPiece);
    rollOverMesh = block.mesh;

    if(!level_mode){
        nextPiece = getRandomMember(BlockGenerator.allShapes);
        nextPiece_doc.innerHTML = nextPiece;
    }

    // placement of the new block - first move towards user's perspective until we can't move anymore
    moveBackward(gameBoardOrientation, oldPos);
    while (!BlockGenerator.isPosLegal(oldPos)) {
        if (pos_illegal_code == 1) {
            moveBackward(gameBoardOrientation, oldPos);
        } else if (pos_illegal_code == 2) {
            break;
        }
    }

    // on the edge already. first move back until we're okay then move up until we're okay
    if (pos_illegal_code == 2) {
        moveForward(gameBoardOrientation, oldPos);
        while (!BlockGenerator.isPosLegal(oldPos)) {
            if (pos_illegal_code == 1) {
                oldPos.y += STEP_SIZE;
            } else if (pos_illegal_code == 2) {
                moveForward(gameBoardOrientation, oldPos);
            }
        }
    }

    rollOverMesh.position.x = oldPos.x;
    rollOverMesh.position.y = oldPos.y;
    rollOverMesh.position.z = oldPos.z;
    scene.add( rollOverMesh );
}

function onWindowResize() {
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();

    console.log(window.innerWidth / window.innerHeight);
    backgroundCamera.aspect = window.innerWidth / window.innerHeight;
    backgroundCamera.updateProjectionMatrix();

    renderer.setSize( window.innerWidth, window.innerHeight );
}<|endoftext|>


<commit_before>/* eslint-disable jest/expect-expect */
/* We use a method to generate our assertions */

import execa from 'execa'
import puppeteer from 'puppeteer'

const percySnapshot = require('@percy/puppeteer')

const OTP_RR_TEST_CONFIG_PATH = '../percy/har-mock-config.yml'
const OTP_RR_TEST_JS_CONFIG_PATH = './percy/har-mock-config.js'

const MOCK_SERVER_PORT = 5000

// Puppeteer can take a long time to load, espeically in some ci environments
jest.setTimeout(600000)

// How long to wait for each page to fully render before taking a screenshot
const PERCY_EXTRA_WAIT = 5000
const percySnapshotWithWait = async (page, name) => {
  await page.waitForTimeout(PERCY_EXTRA_WAIT)
  await percySnapshot(page, name)
}

let browser
const serveAbortController = new AbortController()
const harAbortController = new AbortController()

/**
 * Loads a path
 */
async function loadPath(otpPath) {
  const page = await browser.newPage()
  const filePath = `http://localhost:${MOCK_SERVER_PORT}/#${otpPath}`
  await Promise.all([
    page.goto(filePath),
    page.waitForNavigation({ waitUntil: 'networkidle2' })
  ])

  return page
}

beforeAll(async () => {
  try {
    // Build OTP-RR main.js using new config file
    await execa('env', [
      `YAML_CONFIG=${OTP_RR_TEST_CONFIG_PATH}`,
      `JS_CONFIG=${OTP_RR_TEST_JS_CONFIG_PATH}`,
      'yarn',
      'build'
    ])

    // grab ATL har file to tmp
    await execa('curl', [
      'https://otp-repo.s3.amazonaws.com/ATL-fix_03-09-2022-14-40-46_03-10-2022-09-08-49.har',
      '-s',
      '--output',
      'ATL.har'
    ])
  } catch (error) {
    console.log(error)
  }
  console.log('Built OTP-RR and downloaded HAR data')

  try {
    execa('yarn', ['percy-serve', 'dist', '-p', MOCK_SERVER_PORT], {
      signal: serveAbortController.signal
    }).stdout.pipe(process.stdout)

    // Launch mock OTP server
    execa('yarn', ['percy-har-express', '-p', '9999', 'ATL.har'], {
      signal: harAbortController.signal
    }).stdout.pipe(process.stdout)

    // Web security is disabled to allow requests to the mock OTP server
    browser = await puppeteer.launch({
      args: ['--disable-web-security']
      // headless: false
    })
  } catch (error) {
    console.log(error)
  }

  // Give servers time to start up
  await execa('sleep', ['5'])
})

afterAll(async () => {
  try {
    serveAbortController.abort()
    harAbortController.abort()
    await browser.close()
  } catch (error) {
    console.log(error)
  }
  console.log('Closed mock server and headless browser')
})

// Puppeteer can take a long time to load, espeically in some ci environments
jest.setTimeout(600000)

test('OTP-RR', async () => {
  const page = await loadPath('/')
  await page.evaluate(() => {
    Date.now = () => {
      return 1636363636
    }
  })
  await page.setViewport({
    height: 1080,
    width: 1920
  })

  await percySnapshotWithWait(page, 'Main Page (without styling)')

  // Plan a trip
  await page.goto(
    `http://localhost:${MOCK_SERVER_PORT}/#/?ui_activeSearch=5rzujqghc&ui_activeItinerary=0&fromPlace=Opus Music Store%2C Decatur%2C GA%3A%3A33.77505%2C-84.300178&toPlace=Five Points Station (MARTA Stop ID 908981)%3A%3A33.753837%2C-84.391397&date=2022-03-09&time=09%3A58&arriveBy=false&mode=WALK%2CBUS%2CSUBWAY%2CTRAM%2CFLEX_EGRESS%2CFLEX_ACCESS%2CFLEX_DIRECT&showIntermediateStops=true&maxWalkDistance=1207&optimize=QUICK&walkSpeed=1.34&ignoreRealtimeUpdates=true&wheelchair=false&numItineraries=3&otherThanPreferredRoutesPenalty=900`
  )
  await page.waitForNavigation({ waitUntil: 'networkidle2' })
  await page.waitForSelector('.title')

  await percySnapshotWithWait(page, 'Batch Itinerary')

  // Select a trip
  await page.waitForSelector('.title:nth-of-type(1)')
  await page.click('.title:nth-of-type(1)')

  await percySnapshotWithWait(page, 'Batch Itinerary Selected')

  // Open Trip Viewer
  await page.waitForTimeout(2000)
  const [tripViewerButton] = await page.$x(
    "//button[contains(., 'Trip Viewer')]"
  )
  await tripViewerButton.click()
  await page.waitForSelector('div.trip-viewer-body')
  await page.waitForTimeout(1000)
  await percySnapshotWithWait(page, 'Trip Viewer')

  // Open stop viewer from trip viewer
  await page.click(
    'div.trip-viewer-body > div:nth-child(3) > div.stop-button-container > button'
  )
  await page.waitForSelector('.stop-viewer')

  await percySnapshotWithWait(page, 'Stop Viewer')

  // Open schedule view
  await page.waitForSelector('button.link-button.pull-right')
  await page.click('button.link-button.pull-right')
  await page.waitForTimeout(9000) // Slow animation
  await percySnapshotWithWait(page, 'Schedule Viewer')

  // Open route viewer
  const [routeViewerButton] = await page.$x(
    "//button[contains(., 'View Routes')]"
  )
  await routeViewerButton.click()
  await page.waitForSelector('.route-viewer')
  await page.waitForTimeout(5000)

  await percySnapshotWithWait(page, 'Route Viewer')

  // Open Specific Route`
  const [busRouteButton] = await page.$x(
    "//button[contains(., 'Sugarloaf Mills - Lindbergh Center')]"
  )
  await busRouteButton.click()
  await page.waitForSelector('#headsign-selector')

  await percySnapshotWithWait(page, 'Route Viewer Showing Route 410')

  // View multiple patterns
  await page.select('#headsign-selector', '6:410:1:01')
  await page.waitForSelector('#headsign-selector-label')
  await page.waitForTimeout(1000)
  await page.select('#headsign-selector', '6:410:0:01')
  await page.waitForTimeout(1000)

  await percySnapshotWithWait(page, 'Pattern Viewer Showing Route 410')

  // Stop viewer from pattern viewer
  const [patternStopButton] = await page.$x(
    "//a[contains(., 'Sugarloaf Mills GCT Park and Ride')]"
  )
  await patternStopButton.click()
  await page.waitForSelector('.stop-viewer')

  // Activate all layers
  await page.$$eval('.leaflet-control-layers-selector', (checks) =>
    checks.forEach((c) => c.click())
  )
  await page.waitForTimeout(1000)

  // Go back to trip planner
  const [tripPlannerButton] = await page.$x(
    "//button[contains(., 'Plan Trip')]"
  )
  await tripPlannerButton.click()
  await page.waitForSelector('.batch-routing-panel')
  await page.waitForTimeout(3000)
  const [viewAllOptionsButton] = await page.$x(
    "//button[contains(., 'View all options')]"
  )
  await viewAllOptionsButton.click()
  await page.waitForTimeout(1000)

  await percySnapshotWithWait(page, 'Batch Itinerary Showing Bikes')
})
<commit_msg>ci(percy): ensure screenshots are proper<commit_after>/* eslint-disable jest/expect-expect */
/* We use a method to generate our assertions */

import execa from 'execa'
import puppeteer from 'puppeteer'

const percySnapshot = require('@percy/puppeteer')

const OTP_RR_TEST_CONFIG_PATH = '../percy/har-mock-config.yml'
const OTP_RR_TEST_JS_CONFIG_PATH = './percy/har-mock-config.js'

const MOCK_SERVER_PORT = 5000

// Puppeteer can take a long time to load, espeically in some ci environments
jest.setTimeout(600000)

// How long to wait for each page to fully render before taking a screenshot
const PERCY_EXTRA_WAIT = 5000
const percySnapshotWithWait = async (page, name) => {
  await page.waitForTimeout(PERCY_EXTRA_WAIT)
  await percySnapshot(page, name, { enableJavascript: true })
}

let browser
const serveAbortController = new AbortController()
const harAbortController = new AbortController()

/**
 * Loads a path
 */
async function loadPath(otpPath) {
  const page = await browser.newPage()
  const filePath = `http://localhost:${MOCK_SERVER_PORT}/#${otpPath}`
  await Promise.all([
    page.goto(filePath),
    page.waitForNavigation({ waitUntil: 'networkidle2' })
  ])

  return page
}

beforeAll(async () => {
  try {
    // Build OTP-RR main.js using new config file
    await execa('env', [
      `YAML_CONFIG=${OTP_RR_TEST_CONFIG_PATH}`,
      `JS_CONFIG=${OTP_RR_TEST_JS_CONFIG_PATH}`,
      'yarn',
      'build'
    ])

    // grab ATL har file to tmp
    await execa('curl', [
      'https://otp-repo.s3.amazonaws.com/ATL-fix_03-09-2022-14-40-46_03-10-2022-09-08-49.har',
      '-s',
      '--output',
      'ATL.har'
    ])
  } catch (error) {
    console.log(error)
  }
  console.log('Built OTP-RR and downloaded HAR data')

  try {
    execa('yarn', ['percy-serve', 'dist', '-p', MOCK_SERVER_PORT], {
      signal: serveAbortController.signal
    }).stdout.pipe(process.stdout)

    // Launch mock OTP server
    execa('yarn', ['percy-har-express', '-p', '9999', 'ATL.har'], {
      signal: harAbortController.signal
    }).stdout.pipe(process.stdout)

    // Web security is disabled to allow requests to the mock OTP server
    browser = await puppeteer.launch({
      args: ['--disable-web-security']
      // headless: false
    })

    // Fix time
    browser.on('targetchanged', async (target) => {
      const targetPage = await target.page()
      const client = await targetPage.target().createCDPSession()
      await client.send('Runtime.evaluate', {
        expression: 'Date.now = function() { return 1646835742000; }'
      })
    })
  } catch (error) {
    console.log(error)
  }

  // Give servers time to start up
  await execa('sleep', ['5'])
})

afterAll(async () => {
  try {
    serveAbortController.abort()
    harAbortController.abort()
    await browser.close()
  } catch (error) {
    console.log(error)
  }
  console.log('Closed mock server and headless browser')
})

// Puppeteer can take a long time to load, espeically in some ci environments
jest.setTimeout(600000)

test('OTP-RR', async () => {
  const page = await loadPath('/')
  await page.setViewport({
    height: 1080,
    width: 1920
  })

  await percySnapshotWithWait(page, 'Main Page (without styling)')

  // Plan a trip
  await page.goto(
    `http://localhost:${MOCK_SERVER_PORT}/#/?ui_activeSearch=5rzujqghc&ui_activeItinerary=0&fromPlace=Opus Music Store%2C Decatur%2C GA%3A%3A33.77505%2C-84.300178&toPlace=Five Points Station (MARTA Stop ID 908981)%3A%3A33.753837%2C-84.391397&date=2022-03-09&time=09%3A58&arriveBy=false&mode=WALK%2CBUS%2CSUBWAY%2CTRAM%2CFLEX_EGRESS%2CFLEX_ACCESS%2CFLEX_DIRECT&showIntermediateStops=true&maxWalkDistance=1207&optimize=QUICK&walkSpeed=1.34&ignoreRealtimeUpdates=true&wheelchair=false&numItineraries=3&otherThanPreferredRoutesPenalty=900`
  )
  await page.waitForNavigation({ waitUntil: 'networkidle2' })
  await page.waitForSelector('.title')

  await percySnapshotWithWait(page, 'Batch Itinerary')

  // Select a trip
  await page.waitForSelector('.title:nth-of-type(1)')
  await page.click('.title:nth-of-type(1)')

  await percySnapshotWithWait(page, 'Batch Itinerary Selected')

  // Open Trip Viewer
  await page.waitForTimeout(2000)
  const [tripViewerButton] = await page.$x(
    "//button[contains(., 'Trip Viewer')]"
  )
  await tripViewerButton.click()
  await page.waitForSelector('div.trip-viewer-body')
  await page.waitForTimeout(1000)
  await percySnapshotWithWait(page, 'Trip Viewer')

  // Open stop viewer from trip viewer
  await page.click(
    'div.trip-viewer-body > div:nth-child(3) > div.stop-button-container > button'
  )
  await page.waitForSelector('.stop-viewer')

  await percySnapshotWithWait(page, 'Stop Viewer')

  // Open schedule view
  await page.waitForSelector('button.link-button.pull-right')
  await page.click('button.link-button.pull-right')
  await page.waitForTimeout(3000) // Slow animation
  await percySnapshotWithWait(page, 'Schedule Viewer')

  // Open route viewer
  const [routeViewerButton] = await page.$x(
    "//button[contains(., 'View Routes')]"
  )
  await routeViewerButton.click()
  await page.waitForSelector('.route-viewer')
  await page.waitForTimeout(5000)

  await percySnapshotWithWait(page, 'Route Viewer')

  // Open Specific Route`
  const [busRouteButton] = await page.$x(
    "//span[contains(., 'Sugarloaf Mills - Lindbergh Center')]"
  )
  await busRouteButton.click()
  await page.waitForSelector('#headsign-selector')

  await percySnapshotWithWait(page, 'Route Viewer Showing Route 410')

  // View multiple patterns
  await page.select('#headsign-selector', '6:410:1:01')
  await page.waitForSelector('#headsign-selector-label')
  await page.waitForTimeout(1000)
  await page.select('#headsign-selector', '6:410:0:01')
  await page.waitForTimeout(1000)

  await percySnapshotWithWait(page, 'Pattern Viewer Showing Route 410')

  // Stop viewer from pattern viewer
  const [patternStopButton] = await page.$x(
    "//a[contains(., 'Sugarloaf Mills GCT Park and Ride')]"
  )
  await patternStopButton.click()
  await page.waitForSelector('.stop-viewer')

  // Activate all layers
  await page.$$eval('.leaflet-control-layers-selector', (checks) =>
    checks.forEach((c) => c.click())
  )
  await page.waitForTimeout(1000)

  // Go back to trip planner
  const [tripPlannerButton] = await page.$x(
    "//button[contains(., 'Plan Trip')]"
  )
  await tripPlannerButton.click()
  await page.waitForSelector('.batch-routing-panel')
  await page.waitForTimeout(3000)
  const [viewAllOptionsButton] = await page.$x(
    "//button[contains(., 'View all options')]"
  )
  await viewAllOptionsButton.click()
  await page.waitForTimeout(1000)

  await percySnapshotWithWait(page, 'Batch Itinerary Showing Bikes')
})
<|endoftext|>


<commit_before>// ==UserScript==
// @name         phabricator hacks
// @namespace    http://bd808.com/userscripts/
// @description  Make phabricator look and work like I want it to
// @match        https://secure.phabricator.com/*
// @match        https://phabricator.wikimedia.org/*
// @match        https://bugzillapreview.wmflabs.org/*
// @version      0.15
// @author       Bryan Davis
// @license      MiT License; http://opensource.org/licenses/MIT
// @downloadURL  https://bd808.github.io/userscripts/phabricator.user.js
// @updateURL    https://bd808.github.io/userscripts/phabricator.user.js
// @grant        GM_addStyle
// @grant        GM_getResourceText
// @resource     css http://bd808.com/userscripts/phabricator.user.css
// ==/UserScript==

/* Load custom css */
GM_addStyle(GM_getResourceText('css'));

/* Hide spammy events */
(function() {
    "use strict";
    var nodes = document.querySelectorAll('.phui-timeline-minor-event'),
        nodesLen = nodes.length,
        spam = /(added|removed) (a )?(subscriber|project)|(changed|set) Security (from|to)|moved this task to|awarded a token|(raised|lowered) the priority of this task|triaged this task as|changed the title from/;
    for (var nodeIdx = 0; nodeIdx < nodesLen; nodeIdx++) {
        var kids = nodes[nodeIdx].querySelectorAll('.phui-timeline-title'),
            kidsLen = kids.length,
            firstVisible = kidsLen + 1;
        for (var kidIdx = 0; kidIdx < kidsLen; kidIdx++) {
            if (kids[kidIdx].innerHTML.match(spam)) {
                // console.log('Hiding : ' + kids[kidIdx].outerHTML);
                kids[kidIdx].style.display = 'none';
            } else {
                firstVisible = Math.min(firstVisible, kidIdx);
            }
        }
        if (firstVisible < kidsLen) {
            // Not all items hidden, so move the timestamp to the first
            // visible item in the list.
            var extra = kids[0].querySelector('.phui-timeline-extra');
            kids[firstVisible].appendChild(extra);
        } else {
            // All items ended up hidden, so hide the whole minor event
            nodes[nodeIdx].style.display = 'none';
        }
    }
})();

/* Link bugzilla references to original bug */
(function() {
    "use strict";
    var nodes = document.querySelectorAll('.phui-property-list-value'),
        nodesLen = nodes.length,
        bzIdRegex = /\b(bz(\d+))\b/,
        bzLink = '$1 <smaller>(bz)</smaller>';
    for (var nodeIdx = 0; nodeIdx < nodesLen; nodeIdx++) {
        if (bzIdRegex.test(nodes[nodeIdx].innerHTML)) {
            nodes[nodeIdx].innerHTML =
                nodes[nodeIdx].innerHTML.replace( bzIdRegex, bzLink );
        }
    }
})();

/* Hide tags for archived projects */
(function() {
    "use strict";
    var disabled = document.querySelectorAll('li a.phui-tag-shade-disabled'),
        disabledLen = disabled.length;
    for (var disabledIdx = 0; disabledIdx < disabledLen; disabledIdx++) {
        disabled[disabledIdx].parentNode.style.display = 'none';
    }
})();

/* Add a shortcut to unread notifications */
(function() {
    "use strict";
    var nodes = document.querySelectorAll('.phabricator-notification-header');
    if ( nodes.length > 0 ) {
        nodes[0].innerHTML = nodes[0].innerHTML +
            'Unread';
    }
})();

/* vim:sw=4:ts=4:sts=4:et: */
<commit_msg>Phabricator: add a short delay before looking for tags to hide<commit_after>// ==UserScript==
// @name         phabricator hacks
// @namespace    http://bd808.com/userscripts/
// @description  Make phabricator look and work like I want it to
// @match        https://secure.phabricator.com/*
// @match        https://phabricator.wikimedia.org/*
// @match        https://bugzillapreview.wmflabs.org/*
// @version      0.16
// @author       Bryan Davis
// @license      MiT License; http://opensource.org/licenses/MIT
// @downloadURL  https://bd808.github.io/userscripts/phabricator.user.js
// @updateURL    https://bd808.github.io/userscripts/phabricator.user.js
// @grant        GM_addStyle
// @grant        GM_getResourceText
// @resource     css http://bd808.com/userscripts/phabricator.user.css
// ==/UserScript==

/* Load custom css */
GM_addStyle(GM_getResourceText('css'));

/* Hide spammy events */
(function() {
    "use strict";
    var nodes = document.querySelectorAll('.phui-timeline-minor-event'),
        nodesLen = nodes.length,
        spam = /(added|removed) (a )?(subscriber|project)|(changed|set) Security (from|to)|moved this task to|awarded a token|(raised|lowered) the priority of this task|triaged this task as|changed the title from/;
    for (var nodeIdx = 0; nodeIdx < nodesLen; nodeIdx++) {
        var kids = nodes[nodeIdx].querySelectorAll('.phui-timeline-title'),
            kidsLen = kids.length,
            firstVisible = kidsLen + 1;
        for (var kidIdx = 0; kidIdx < kidsLen; kidIdx++) {
            if (kids[kidIdx].innerHTML.match(spam)) {
                // console.log('Hiding : ' + kids[kidIdx].outerHTML);
                kids[kidIdx].style.display = 'none';
            } else {
                firstVisible = Math.min(firstVisible, kidIdx);
            }
        }
        if (firstVisible < kidsLen) {
            // Not all items hidden, so move the timestamp to the first
            // visible item in the list.
            var extra = kids[0].querySelector('.phui-timeline-extra');
            kids[firstVisible].appendChild(extra);
        } else {
            // All items ended up hidden, so hide the whole minor event
            nodes[nodeIdx].style.display = 'none';
        }
    }
})();

/* Link bugzilla references to original bug */
(function() {
    "use strict";
    var nodes = document.querySelectorAll('.phui-property-list-value'),
        nodesLen = nodes.length,
        bzIdRegex = /\b(bz(\d+))\b/,
        bzLink = '$1 <smaller>(bz)</smaller>';
    for (var nodeIdx = 0; nodeIdx < nodesLen; nodeIdx++) {
        if (bzIdRegex.test(nodes[nodeIdx].innerHTML)) {
            nodes[nodeIdx].innerHTML =
                nodes[nodeIdx].innerHTML.replace( bzIdRegex, bzLink );
        }
    }
})();

/* Hide tags for archived projects */
(window.setTimeout(function() {
    "use strict";
    var disabled = document.querySelectorAll('li a.phui-tag-shade-disabled'),
        disabledLen = disabled.length;
    for (var disabledIdx = 0; disabledIdx < disabledLen; disabledIdx++) {
        disabled[disabledIdx].parentNode.style.display = 'none';
    }
},50))();

/* Add a shortcut to unread notifications */
/* FIXME: doesn't work. Needs to watch for the div being created. */
(function() {
    "use strict";
    var nodes = document.querySelectorAll('.phabricator-notification-header');
    if ( nodes.length > 0 ) {
        nodes[0].innerHTML = nodes[0].innerHTML +
            'Unread';
    }
})();

/* vim:sw=4:ts=4:sts=4:et: */
<|endoftext|>


<commit_before>var crypto = require('crypto')
var fs = require('fs')
var path = require('path')

var minimatch = require('minimatch')

var Resolve = null

function PackageTranspilationRegistry () {
  this.configByPackagePath = {}
  this.specByFilePath = {}
  this.transpilerPaths = {}
}

Object.assign(PackageTranspilationRegistry.prototype, {
  addTranspilerConfigForPath: function (packagePath, config) {
    packagePath = fs.realpathSync(packagePath)
    this.configByPackagePath[packagePath] = {
      specs: config,
      path: packagePath
    }
  },

  removeTranspilerConfigForPath: function (packagePath) {
    packagePath = fs.realpathSync(packagePath)
    delete this.configByPackagePath[packagePath]
  },

  // Wraps the transpiler in an object with the same interface
  // that falls back to the original transpiler implementation if and
  // only if a package hasn't registered its desire to transpile its own source.
  wrapTranspiler: function (transpiler) {
    var self = this
    return {
      getCachePath: function (sourceCode, filePath) {
        var spec = self.getPackageTranspilerSpecForFilePath(filePath)
        if (spec) {
          return self.getCachePath(sourceCode, filePath, spec)
        }

        return transpiler.getCachePath(sourceCode, filePath)
      },

      compile: function (sourceCode, filePath) {
        var spec = self.getPackageTranspilerSpecForFilePath(filePath)
        if (spec) {
          return self.transpileWithPackageTranspiler(sourceCode, filePath, spec)
        }

        return transpiler.compile(sourceCode, filePath)
      },

      shouldCompile: function (sourceCode, filePath) {
        if (self.transpilerPaths[filePath]) {
          return false
        }
        var spec = self.getPackageTranspilerSpecForFilePath(filePath)
        if (spec) {
          return true
        }

        return transpiler.shouldCompile(sourceCode, filePath)
      }
    }
  },

  getPackageTranspilerSpecForFilePath: function (filePath) {
    if (this.specByFilePath[filePath] !== undefined) return this.specByFilePath[filePath]

    var config = null
    var spec = null
    var thisPath = filePath
    var lastPath = null
    // Iterate parents from the file path to the root, checking at each level
    // to see if a package manages transpilation for that directory.
    // This means searching for a config for `/path/to/file/here.js` only
    // only iterates four times, even if there are hundreds of configs registered.
    while (thisPath !== lastPath) { // until we reach the root
      if (config = this.configByPackagePath[thisPath]) { // // eslint-disable-line no-cond-assign
        for (var i = 0; i < config.specs.length; i++) {
          spec = config.specs[i]
          if (minimatch(filePath, path.join(config.path, spec.glob))) {
            spec._config = config
            this.specByFilePath[filePath] = spec
            return spec
          }
        }
      }

      lastPath = thisPath
      thisPath = path.resolve(thisPath, '..')
    }

    this.specByFilePath[filePath] = null
    return null
  },

  getCachePath: function (sourceCode, filePath, spec) {
    var transpilerPath = path.join(spec._config.path, spec.transpiler)
    var transpilerSource = spec._transpilerSource || fs.readFileSync(transpilerPath, 'utf8')
    spec._transpilerSource = transpilerSource
    return path.join(
      'package-transpile',
      crypto
        .createHash('sha1')
        .update(JSON.stringify(spec.options || {}))
        .update(transpilerSource, 'utf8')
        .update(sourceCode, 'utf8')
        .digest('hex')
    )
  },

  transpileWithPackageTranspiler: function (sourceCode, filePath, spec) {
    Resolve = Resolve || require('resolve')
    var transpilerPath = Resolve.sync(spec.transpiler, {
      basedir: spec._config.path,
      extensions: Object.keys(require.extensions)
    })

    if (transpilerPath) {
      this.transpilerPaths[transpilerPath] = true
      var transpiler = require(transpilerPath)
      var result = transpiler.compile(sourceCode, filePath, spec.options || {})
      if (result === undefined) {
        return sourceCode
      } else {
        return result
      }
    } else {
      var err = new Error("Could not resolve transpiler '" + spec.transpiler + "' from '" + spec._config.path + "'")
      console.error(err)
    }
  }
})

module.exports = PackageTranspilationRegistry
<commit_msg>:fire: Extra // in eslint comment<commit_after>var crypto = require('crypto')
var fs = require('fs')
var path = require('path')

var minimatch = require('minimatch')

var Resolve = null

function PackageTranspilationRegistry () {
  this.configByPackagePath = {}
  this.specByFilePath = {}
  this.transpilerPaths = {}
}

Object.assign(PackageTranspilationRegistry.prototype, {
  addTranspilerConfigForPath: function (packagePath, config) {
    packagePath = fs.realpathSync(packagePath)
    this.configByPackagePath[packagePath] = {
      specs: config,
      path: packagePath
    }
  },

  removeTranspilerConfigForPath: function (packagePath) {
    packagePath = fs.realpathSync(packagePath)
    delete this.configByPackagePath[packagePath]
  },

  // Wraps the transpiler in an object with the same interface
  // that falls back to the original transpiler implementation if and
  // only if a package hasn't registered its desire to transpile its own source.
  wrapTranspiler: function (transpiler) {
    var self = this
    return {
      getCachePath: function (sourceCode, filePath) {
        var spec = self.getPackageTranspilerSpecForFilePath(filePath)
        if (spec) {
          return self.getCachePath(sourceCode, filePath, spec)
        }

        return transpiler.getCachePath(sourceCode, filePath)
      },

      compile: function (sourceCode, filePath) {
        var spec = self.getPackageTranspilerSpecForFilePath(filePath)
        if (spec) {
          return self.transpileWithPackageTranspiler(sourceCode, filePath, spec)
        }

        return transpiler.compile(sourceCode, filePath)
      },

      shouldCompile: function (sourceCode, filePath) {
        if (self.transpilerPaths[filePath]) {
          return false
        }
        var spec = self.getPackageTranspilerSpecForFilePath(filePath)
        if (spec) {
          return true
        }

        return transpiler.shouldCompile(sourceCode, filePath)
      }
    }
  },

  getPackageTranspilerSpecForFilePath: function (filePath) {
    if (this.specByFilePath[filePath] !== undefined) return this.specByFilePath[filePath]

    var config = null
    var spec = null
    var thisPath = filePath
    var lastPath = null
    // Iterate parents from the file path to the root, checking at each level
    // to see if a package manages transpilation for that directory.
    // This means searching for a config for `/path/to/file/here.js` only
    // only iterates four times, even if there are hundreds of configs registered.
    while (thisPath !== lastPath) { // until we reach the root
      if (config = this.configByPackagePath[thisPath]) { // eslint-disable-line no-cond-assign
        for (var i = 0; i < config.specs.length; i++) {
          spec = config.specs[i]
          if (minimatch(filePath, path.join(config.path, spec.glob))) {
            spec._config = config
            this.specByFilePath[filePath] = spec
            return spec
          }
        }
      }

      lastPath = thisPath
      thisPath = path.resolve(thisPath, '..')
    }

    this.specByFilePath[filePath] = null
    return null
  },

  getCachePath: function (sourceCode, filePath, spec) {
    var transpilerPath = path.join(spec._config.path, spec.transpiler)
    var transpilerSource = spec._transpilerSource || fs.readFileSync(transpilerPath, 'utf8')
    spec._transpilerSource = transpilerSource
    return path.join(
      'package-transpile',
      crypto
        .createHash('sha1')
        .update(JSON.stringify(spec.options || {}))
        .update(transpilerSource, 'utf8')
        .update(sourceCode, 'utf8')
        .digest('hex')
    )
  },

  transpileWithPackageTranspiler: function (sourceCode, filePath, spec) {
    Resolve = Resolve || require('resolve')
    var transpilerPath = Resolve.sync(spec.transpiler, {
      basedir: spec._config.path,
      extensions: Object.keys(require.extensions)
    })

    if (transpilerPath) {
      this.transpilerPaths[transpilerPath] = true
      var transpiler = require(transpilerPath)
      var result = transpiler.compile(sourceCode, filePath, spec.options || {})
      if (result === undefined) {
        return sourceCode
      } else {
        return result
      }
    } else {
      var err = new Error("Could not resolve transpiler '" + spec.transpiler + "' from '" + spec._config.path + "'")
      console.error(err)
    }
  }
})

module.exports = PackageTranspilationRegistry
<|endoftext|>


<commit_before>"use strict"
// This file is required by compile-cache, which is required directly from
// apm, so it can only use the subset of newer JavaScript features that apm's
// version of Node supports. Strict mode is required for block scoped declarations.

const crypto = require('crypto')
const fs = require('fs')
const path = require('path')

const minimatch = require('minimatch')

let Resolve = null

class PackageTranspilationRegistry {
  constructor () {
    this.configByPackagePath = {}
    this.specByFilePath = {}
    this.transpilerPaths = {}
  }

  addTranspilerConfigForPath (packagePath, packageName, config) {
    this.configByPackagePath[packagePath] = {
      name: packageName,
      path: packagePath,
      specs: config
    }
  }

  removeTranspilerConfigForPath (packagePath) {
    delete this.configByPackagePath[packagePath]
  }

  // Wraps the transpiler in an object with the same interface
  // that falls back to the original transpiler implementation if and
  // only if a package hasn't registered its desire to transpile its own source.
  wrapTranspiler (transpiler) {
    return {
      getCachePath: (sourceCode, filePath) => {
        const spec = this.getPackageTranspilerSpecForFilePath(filePath)
        if (spec) {
          return this.getCachePath(sourceCode, filePath, spec)
        }

        return transpiler.getCachePath(sourceCode, filePath)
      },

      compile: (sourceCode, filePath) => {
        const spec = this.getPackageTranspilerSpecForFilePath(filePath)
        if (spec) {
          return this.transpileWithPackageTranspiler(sourceCode, filePath, spec)
        }

        return transpiler.compile(sourceCode, filePath)
      },

      shouldCompile: (sourceCode, filePath) => {
        if (this.transpilerPaths[filePath]) {
          return false
        }
        const spec = this.getPackageTranspilerSpecForFilePath(filePath)
        if (spec) {
          return true
        }

        return transpiler.shouldCompile(sourceCode, filePath)
      }
    }
  }

  getPackageTranspilerSpecForFilePath (filePath) {
    if (this.specByFilePath[filePath] !== undefined) return this.specByFilePath[filePath]

    // ignore node_modules
    if (filePath.indexOf(path.sep + 'node_modules' + path.sep) > -1) {
      return false
    }

    let thisPath = filePath
    let lastPath = null
    // Iterate parents from the file path to the root, checking at each level
    // to see if a package manages transpilation for that directory.
    // This means searching for a config for `/path/to/file/here.js` only
    // only iterates four times, even if there are hundreds of configs registered.
    while (thisPath !== lastPath) { // until we reach the root
      let config = this.configByPackagePath[thisPath]
      if (config) {
        for (let i = 0; i < config.specs.length; i++) {
          const spec = config.specs[i]
          if (minimatch(filePath, path.join(config.path, spec.glob))) {
            spec._config = config
            this.specByFilePath[filePath] = spec
            return spec
          }
        }
      }

      lastPath = thisPath
      thisPath = path.resolve(thisPath, '..')
    }

    this.specByFilePath[filePath] = null
    return null
  }

  getCachePath (sourceCode, filePath, spec) {
    const transpilerPath = this.getTranspilerPath(spec)
    const transpilerSource = spec._transpilerSource || fs.readFileSync(transpilerPath, 'utf8')
    spec._transpilerSource = transpilerSource
    const transpiler = this.getTranspiler(spec)

    let hash = crypto
      .createHash('sha1')
      .update(JSON.stringify(spec.options || {}))
      .update(transpilerSource, 'utf8')
      .update(sourceCode, 'utf8')

    if (transpiler && transpiler.getCacheKeyData) {
      const additionalCacheData = transpiler.getCacheKeyData(sourceCode, filePath, spec.options)
      hash.update(additionalCacheData, 'utf8')
    }

    return path.join('package-transpile', spec._config.name, hash.digest('hex'))
  }

  transpileWithPackageTranspiler (sourceCode, filePath, spec) {
    const transpiler = this.getTranspiler(spec)

    if (transpiler) {
      const result = transpiler.transpile(sourceCode, filePath, spec.options || {})
      if (result === undefined || (result && result.code === undefined)) {
        return sourceCode
      } else if (result.code) {
        return result.code.toString()
      } else {
        throw new Error('Could not find a property `.code` on the transpilation results of ' + filePath)
      }
    } else {
      const err = new Error("Could not resolve transpiler '" + spec.transpiler + "' from '" + spec._config.path + "'")
      throw err
    }
  }

  getTranspilerPath (spec) {
    Resolve = Resolve || require('resolve')
    return Resolve.sync(spec.transpiler, {
      basedir: spec._config.path,
      extensions: Object.keys(require.extensions)
    })
  }

  getTranspiler (spec) {
    const transpilerPath = this.getTranspilerPath(spec)
    if (transpilerPath) {
      const transpiler = require(transpilerPath)
      this.transpilerPaths[transpilerPath] = true
      return transpiler
    }
  }
}

module.exports = PackageTranspilationRegistry
<commit_msg>:shirt:<commit_after>'use strict'
// This file is required by compile-cache, which is required directly from
// apm, so it can only use the subset of newer JavaScript features that apm's
// version of Node supports. Strict mode is required for block scoped declarations.

const crypto = require('crypto')
const fs = require('fs')
const path = require('path')

const minimatch = require('minimatch')

let Resolve = null

class PackageTranspilationRegistry {
  constructor () {
    this.configByPackagePath = {}
    this.specByFilePath = {}
    this.transpilerPaths = {}
  }

  addTranspilerConfigForPath (packagePath, packageName, config) {
    this.configByPackagePath[packagePath] = {
      name: packageName,
      path: packagePath,
      specs: config
    }
  }

  removeTranspilerConfigForPath (packagePath) {
    delete this.configByPackagePath[packagePath]
  }

  // Wraps the transpiler in an object with the same interface
  // that falls back to the original transpiler implementation if and
  // only if a package hasn't registered its desire to transpile its own source.
  wrapTranspiler (transpiler) {
    return {
      getCachePath: (sourceCode, filePath) => {
        const spec = this.getPackageTranspilerSpecForFilePath(filePath)
        if (spec) {
          return this.getCachePath(sourceCode, filePath, spec)
        }

        return transpiler.getCachePath(sourceCode, filePath)
      },

      compile: (sourceCode, filePath) => {
        const spec = this.getPackageTranspilerSpecForFilePath(filePath)
        if (spec) {
          return this.transpileWithPackageTranspiler(sourceCode, filePath, spec)
        }

        return transpiler.compile(sourceCode, filePath)
      },

      shouldCompile: (sourceCode, filePath) => {
        if (this.transpilerPaths[filePath]) {
          return false
        }
        const spec = this.getPackageTranspilerSpecForFilePath(filePath)
        if (spec) {
          return true
        }

        return transpiler.shouldCompile(sourceCode, filePath)
      }
    }
  }

  getPackageTranspilerSpecForFilePath (filePath) {
    if (this.specByFilePath[filePath] !== undefined) return this.specByFilePath[filePath]

    // ignore node_modules
    if (filePath.indexOf(path.sep + 'node_modules' + path.sep) > -1) {
      return false
    }

    let thisPath = filePath
    let lastPath = null
    // Iterate parents from the file path to the root, checking at each level
    // to see if a package manages transpilation for that directory.
    // This means searching for a config for `/path/to/file/here.js` only
    // only iterates four times, even if there are hundreds of configs registered.
    while (thisPath !== lastPath) { // until we reach the root
      let config = this.configByPackagePath[thisPath]
      if (config) {
        for (let i = 0; i < config.specs.length; i++) {
          const spec = config.specs[i]
          if (minimatch(filePath, path.join(config.path, spec.glob))) {
            spec._config = config
            this.specByFilePath[filePath] = spec
            return spec
          }
        }
      }

      lastPath = thisPath
      thisPath = path.resolve(thisPath, '..')
    }

    this.specByFilePath[filePath] = null
    return null
  }

  getCachePath (sourceCode, filePath, spec) {
    const transpilerPath = this.getTranspilerPath(spec)
    const transpilerSource = spec._transpilerSource || fs.readFileSync(transpilerPath, 'utf8')
    spec._transpilerSource = transpilerSource
    const transpiler = this.getTranspiler(spec)

    let hash = crypto
      .createHash('sha1')
      .update(JSON.stringify(spec.options || {}))
      .update(transpilerSource, 'utf8')
      .update(sourceCode, 'utf8')

    if (transpiler && transpiler.getCacheKeyData) {
      const additionalCacheData = transpiler.getCacheKeyData(sourceCode, filePath, spec.options)
      hash.update(additionalCacheData, 'utf8')
    }

    return path.join('package-transpile', spec._config.name, hash.digest('hex'))
  }

  transpileWithPackageTranspiler (sourceCode, filePath, spec) {
    const transpiler = this.getTranspiler(spec)

    if (transpiler) {
      const result = transpiler.transpile(sourceCode, filePath, spec.options || {})
      if (result === undefined || (result && result.code === undefined)) {
        return sourceCode
      } else if (result.code) {
        return result.code.toString()
      } else {
        throw new Error('Could not find a property `.code` on the transpilation results of ' + filePath)
      }
    } else {
      const err = new Error("Could not resolve transpiler '" + spec.transpiler + "' from '" + spec._config.path + "'")
      throw err
    }
  }

  getTranspilerPath (spec) {
    Resolve = Resolve || require('resolve')
    return Resolve.sync(spec.transpiler, {
      basedir: spec._config.path,
      extensions: Object.keys(require.extensions)
    })
  }

  getTranspiler (spec) {
    const transpilerPath = this.getTranspilerPath(spec)
    if (transpilerPath) {
      const transpiler = require(transpilerPath)
      this.transpilerPaths[transpilerPath] = true
      return transpiler
    }
  }
}

module.exports = PackageTranspilationRegistry
<|endoftext|>


<commit_before>var cadence = require('cadence')

var stringify = require('prolific.stringify')

function Processor (configuration, next) {
    this._streamName = configuration.stderr ? 'stderr' : 'stdout'
    this._next = next
}

Processor.prototype.process = function (entry) {
    process[this._streamName].write(stringify(entry))
    this._next.process(entry)
}

module.exports = function (destructible, configuration, nextProcessor, callback) {
    callback(null, new Processor(configuration, nextProcessor))
}
<commit_msg>Add the prolific processor flag.<commit_after>var cadence = require('cadence')

var stringify = require('prolific.stringify')

function Processor (configuration, next) {
    this._streamName = configuration.stderr ? 'stderr' : 'stdout'
    this._next = next
}

Processor.prototype.process = function (entry) {
    process[this._streamName].write(stringify(entry))
    this._next.process(entry)
}

Processor.isProlificProcessor = true

module.exports = function (destructible, configuration, nextProcessor, callback) {
    callback(null, new Processor(configuration, nextProcessor))
}
<|endoftext|>


<commit_before>import gulp from 'gulp';
const runSequence = require('run-sequence').use(gulp);

gulp.task('setup-watchers', (callback) => {
  process.env.WEBPACK_WATCH = true;
  gulp.watch(['src/pivotal-ui/components/**/*.scss'], ['monolith-hologram', 'monolith-build-css-from-cache']);
  gulp.watch(['src/pivotal-ui/components/**/*.js'], ['monolith-build-js', 'monolith-styleguide-assets', 'monolith-hologram']);
  gulp.watch(['src/pivotal-ui-react/**/*.js'], ['monolith-hologram']);
  gulp.watch(['hologram/**/**'], ['monolith-hologram']);
  gulp.watch(['src/styleguide/*.scss'], ['monolith-styleguide-css']);
  gulp.watch(['src/styleguide/*.js'], ['monolith-styleguide-assets']);
  callback();
});

gulp.task('dev', (callback) => runSequence(
  'setup-watchers',
  'monolith-serve',
  callback
));
<commit_msg>chore(pui): make all styleguide js trigger rebuild on change<commit_after>import gulp from 'gulp';
const runSequence = require('run-sequence').use(gulp);

gulp.task('setup-watchers', (callback) => {
  process.env.WEBPACK_WATCH = true;
  gulp.watch(['src/pivotal-ui/components/**/*.scss'], ['monolith-hologram', 'monolith-build-css-from-cache']);
  gulp.watch(['src/pivotal-ui/components/**/*.js'], ['monolith-build-js', 'monolith-styleguide-assets', 'monolith-hologram']);
  gulp.watch(['src/pivotal-ui-react/**/*.js'], ['monolith-hologram']);
  gulp.watch(['hologram/**/**'], ['monolith-hologram']);
  gulp.watch(['src/styleguide/*.scss'], ['monolith-styleguide-css']);
  gulp.watch(['src/styleguide/**/*.js'], ['monolith-styleguide-assets']);
  callback();
});

gulp.task('dev', (callback) => runSequence(
  'setup-watchers',
  'monolith-serve',
  callback
));
<|endoftext|>


<commit_before>const Lang = imports.lang;
const Gio = imports.gi.Gio;
const Shell = imports.gi.Shell;
const GLib = imports.gi.GLib;
const Meta = imports.gi.Meta;
const Clutter = imports.gi.Clutter;
const St = imports.gi.St;

const WindowManager = imports.ui.windowManager.WindowManager;
const Main = imports.ui.main;
const AltTab = imports.ui.altTab;
const SwitcherPopup = imports.ui.switcherPopup;
const WorkspaceThumbnail = imports.ui.workspaceThumbnail

const AppIconMode = {
    THUMBNAIL_ONLY: 1,
    APP_ICON_ONLY: 2,
    BOTH: 3,
};

const WINDOW_PREVIEW_SIZE = 128;
const APP_ICON_SIZE = 96;
const APP_ICON_SIZE_SMALL = 48;

const SHELL_KEYBINDINGS_SCHEMA = 'org.gnome.shell.keybindings';

let popupList;

const PopupList = new Lang.Class({
    Name: 'PopupList',

    _init : function() {
	this._popupList = [];
	this.create();
    },

    create: function() {
        let activeWs = global.screen.get_active_workspace();
	this._popupList.push(activeWs.index())

        for (let i = 0; i < global.screen.n_workspaces; i++) {
	    if (i === activeWs.index())
		continue;
	    this._popupList.push(i);
	}
	this._popupList.reverse();
    },

    update: function() {
	if (this._popupList.length > global.screen.n_workspaces) {
		let index = this._popupList.indexOf(global.screen.n_workspaces);
		if (index > -1) {
		    this._popupList.splice(index, 1);
		}
	}

	if (this._popupList.length < global.screen.n_workspaces) {
		this._popupList.reverse();
		this._popupList.push(global.screen.n_workspaces - 1);
		this._popupList.reverse();
	}
    },

    moveToTop: function(workspaceIndex) {
	let index = this._popupList.indexOf(workspaceIndex);

	if (index > -1) {
	    this._popupList.splice(index, 1);
	}

	this._popupList.push(workspaceIndex);
    },
});

const WorkSpace= new Lang.Class({
    Name: 'WorkSpace',

    _init : function() {
        this._shellwm =  global.window_manager;
        this._workspaceSwitcherPopup = null;

        Main.wm.setCustomKeybindingHandler('switch-to-workspace-down',
                                        Shell.ActionMode.NORMAL,
                                        Lang.bind(this, this._switchWorkspace));
    },

    _switchWorkspace : function(shellwm, from, to, direction) {
	popupList.update();

        if (this._workspaceSwitcherPopup != null)
            this._workspaceSwitcherPopup.destroy();

        let tabPopup = new WorkSpacePopup();

        if (!tabPopup.show(false, 'switch-windows', 8)) {
            tabPopup.destroy();
	}
    },
});

const WorkSpacePopup = new Lang.Class({
    Name: 'WorkSpacePopup',
    Extends: SwitcherPopup.SwitcherPopup,

    _init: function() {
        this.parent();
        //this._settings = new Gio.Settings({ schema_id: 'org.gnome.shell.window-switcher' });

        //let mode = this._settings.get_enum('app-icon-mode');
        this._switcherList = new WorkSpaceList();
        this._items = this._switcherList.icons;
    },

    _keyPressHandler: function(keysym, action) {
        this._select(this._next());
        return Clutter.EVENT_STOP;

        if (action == Meta.KeyBindingAction.SWITCH_WINDOWS) {
            this._select(this._next());
        } else if (action == Meta.KeyBindingAction.SWITCH_WINDOWS_BACKWARD) {
            this._select(this._previous());
        } else {
            if (keysym == Clutter.Left)
                this._select(this._previous());
            else if (keysym == Clutter.Right)
                this._select(this._next());
            else
                return Clutter.EVENT_PROPAGATE;
        }

        return Clutter.EVENT_STOP;
    },

    _finish: function() {
        Main.wm.actionMoveWorkspace(this._switcherList.selectWorkspaces[this._selectedIndex]);

        let activeWs = global.screen.get_active_workspace();
	popupList.moveToTop(activeWs.index());
	//this._switcherList.selectWorkspaces[this._selectedIndex].index();

        this.parent();
    }
});

const WorkSpaceList = new Lang.Class({
    Name: 'WorkSpaceList',
    Extends: SwitcherPopup.SwitcherList,

    _init : function() {
        this.parent(true);

        this._label = new St.Label({ x_align: Clutter.ActorAlign.CENTER,
                                     y_align: Clutter.ActorAlign.CENTER });
        this.actor.add_actor(this._label);

        this.icons = [];

	this.workspaces = this.getWorkSpace();
	this.selectWorkspaces = [];

	let popup = popupList._popupList.slice();
        for (let i = 0; i < global.screen.n_workspaces; i++) {
            let ws_index = popup.pop();
	    this.selectWorkspaces[i] = this.workspaces[ws_index];

            let icon = new WindowIcon(ws_index);

            this.addItem(icon.actor, icon.label);
            this.icons.push(icon);
        }
    },

    getWorkSpace: function() {
        let activeWs = global.screen.get_active_workspace();
	let activeIndex = activeWs.index();
	let ws = [];

	ws[activeIndex] = activeWs;

	for (let i = activeIndex - 1; i >= 0; i--) {
            ws[i] = ws[i + 1].get_neighbor(Meta.MotionDirection.UP);
	}

	for (let i = activeIndex + 1; i < global.screen.n_workspaces; i++) {
            ws[i] = ws[i - 1].get_neighbor(Meta.MotionDirection.DOWN);
	}

	return ws;
    },

    _getPreferredHeight: function(actor, forWidth, alloc) {
        this.parent(actor, forWidth, alloc);

        let spacing = this.actor.get_theme_node().get_padding(St.Side.BOTTOM);
        let [labelMin, labelNat] = this._label.get_preferred_height(-1);
        alloc.min_size += labelMin + spacing;
        alloc.natural_size += labelNat + spacing;
    },

    _allocateTop: function(actor, box, flags) {
        let childBox = new Clutter.ActorBox();
        childBox.x1 = box.x1;
        childBox.x2 = box.x2;
        childBox.y2 = box.y2;
        childBox.y1 = childBox.y2 - this._label.height;
        this._label.allocate(childBox, flags);

        let spacing = this.actor.get_theme_node().get_padding(St.Side.BOTTOM);
        box.y2 -= this._label.height + spacing;
        this.parent(actor, box, flags);
    },

    highlight: function(index, justOutline) {
        this.parent(index, justOutline);

        this._label.set_text(index == -1 ? '' : this.icons[index].label.text);
    }
});

const WindowIcon = new Lang.Class({
    Name: 'WindowIcon',

    _init: function(workspace_index) {

        this.actor = new St.BoxLayout({ style_class: 'alt-tab-app',
                                        vertical: true });
        this._icon = new St.Widget({ layout_manager: new Clutter.BinLayout() });

        this.actor.add(this._icon, { x_fill: false, y_fill: false } );
        this.label = new St.Label({ text: "WorkSpace " + String(workspace_index + 1) });

        let tracker = Shell.WindowTracker.get_default();

        let size;

        this._icon.destroy_all_children();

        let scaleFactor = St.ThemeContext.get_for_stage(global.stage).scale_factor;

	size = WINDOW_PREVIEW_SIZE;

	let metaWorkspace = global.screen.get_workspace_by_index(workspace_index);
	let thumbnail = new WorkspaceThumbnail.WorkspaceThumbnail(metaWorkspace);
	print("wxg: scaleFactor: ", scaleFactor);
        thumbnail.actor.set_scale(0.125, 0.125);
	this._icon.add_actor(thumbnail.actor);

	//if (this.app)
	this._icon.add_actor(this._createAppIcon(null, APP_ICON_SIZE_SMALL));

	/*
        switch (mode) {
            case AppIconMode.THUMBNAIL_ONLY:
                size = WINDOW_PREVIEW_SIZE;
                this._icon.add_actor(_createWindowClone(mutterWindow, size * scaleFactor));
                break;

            case AppIconMode.BOTH:
                size = WINDOW_PREVIEW_SIZE;
                this._icon.add_actor(_createWindowClone(mutterWindow, size * scaleFactor));

                if (this.app)
                    this._icon.add_actor(this._createAppIcon(this.app,
                                                             APP_ICON_SIZE_SMALL));
                break;

            case AppIconMode.APP_ICON_ONLY:
                size = APP_ICON_SIZE;
                this._icon.add_actor(this._createAppIcon(this.app, size));
        }
	*/

        this._icon.set_size(size * scaleFactor, size * scaleFactor);
    },

    _createAppIcon: function(app, size) {
        //let appIcon = app ? app.create_icon_texture(size)
        let appIcon = new St.Icon({ icon_name: 'icon-missing',
                                    icon_size: size });
        appIcon.x_expand = appIcon.y_expand = true;
        appIcon.x_align = appIcon.y_align = Clutter.ActorAlign.END;

        return appIcon;
    }
});

function init() {
	print("wxg: switch workspace init");
}

function enable() {
	print("wxg: switch workspace enable");
	let ws = new WorkSpace();

	popupList = new PopupList();
}

function disable() {
}
<commit_msg>updating<commit_after>const Lang = imports.lang;
const Gio = imports.gi.Gio;
const Shell = imports.gi.Shell;
const GLib = imports.gi.GLib;
const Meta = imports.gi.Meta;
const Clutter = imports.gi.Clutter;
const St = imports.gi.St;

const WindowManager = imports.ui.windowManager.WindowManager;
const Main = imports.ui.main;
const AltTab = imports.ui.altTab;
const SwitcherPopup = imports.ui.switcherPopup;
const WorkspaceThumbnail = imports.ui.workspaceThumbnail

const WINDOW_PREVIEW_SIZE = 128;
const APP_ICON_SIZE_SMALL = 48;

let popupList;

const PopupList = new Lang.Class({
    Name: 'PopupList',

    _init : function() {
	this._popupList = [];
	this.create();
    },

    create: function() {
        let activeWs = global.screen.get_active_workspace();
	this._popupList.push(activeWs.index())

        for (let i = 0; i < global.screen.n_workspaces; i++) {
	    if (i === activeWs.index())
		continue;
	    this._popupList.push(i);
	}
	this._popupList.reverse();
    },

    update: function() {
        let activeWs = global.screen.get_active_workspace();
	let activeWsIndex = activeWs.index();
	if (activeWsIndex != this._popupList[this._popupList.length - 1]) {
	    this.moveToTop(activeWsIndex);
	}

	if (this._popupList.length > global.screen.n_workspaces) {
		let index = this._popupList.indexOf(global.screen.n_workspaces);
		if (index > -1) {
		    this._popupList.splice(index, 1);
		}
	}

	if (this._popupList.length < global.screen.n_workspaces) {
		this._popupList.reverse();
		this._popupList.push(global.screen.n_workspaces - 1);
		this._popupList.reverse();
	}
    },

    moveToTop: function(workspaceIndex) {
	let index = this._popupList.indexOf(workspaceIndex);

	if (index > -1) {
	    this._popupList.splice(index, 1);
	}

	this._popupList.push(workspaceIndex);
    },
});

const WorkSpace= new Lang.Class({
    Name: 'WorkSpace',

    _init : function() {
        this._shellwm =  global.window_manager;
        this._workspaceSwitcherPopup = null;

        Main.wm.setCustomKeybindingHandler('switch-to-workspace-down',
                                        Shell.ActionMode.NORMAL,
                                        Lang.bind(this, this._switchWorkspace));
    },

    _switchWorkspace : function(shellwm, from, to, direction) {
	popupList.update();

        if (this._workspaceSwitcherPopup != null)
            this._workspaceSwitcherPopup.destroy();

        let tabPopup = new WorkSpacePopup();

        if (!tabPopup.show(false, 'switch-windows', 8)) {
            tabPopup.destroy();
	}
    },
});

const WorkSpacePopup = new Lang.Class({
    Name: 'WorkSpacePopup',
    Extends: SwitcherPopup.SwitcherPopup,

    _init: function() {
        this.parent();
        //this._settings = new Gio.Settings({ schema_id: 'org.gnome.shell.window-switcher' });

        //let mode = this._settings.get_enum('app-icon-mode');
        this._switcherList = new WorkSpaceList();
        this._items = this._switcherList.icons;
    },

    _keyPressHandler: function(keysym, action) {
        this._select(this._next());
        return Clutter.EVENT_STOP;

        if (action == Meta.KeyBindingAction.SWITCH_WINDOWS) {
            this._select(this._next());
        } else if (action == Meta.KeyBindingAction.SWITCH_WINDOWS_BACKWARD) {
            this._select(this._previous());
        } else {
            if (keysym == Clutter.Left)
                this._select(this._previous());
            else if (keysym == Clutter.Right)
                this._select(this._next());
            else
                return Clutter.EVENT_PROPAGATE;
        }

        return Clutter.EVENT_STOP;
    },

    _finish: function() {
        Main.wm.actionMoveWorkspace(this._switcherList.selectWorkspaces[this._selectedIndex]);

        let activeWs = global.screen.get_active_workspace();
	popupList.moveToTop(activeWs.index());

        this.parent();
    }
});

const WorkSpaceList = new Lang.Class({
    Name: 'WorkSpaceList',
    Extends: SwitcherPopup.SwitcherList,

    _init : function() {
        this.parent(true);

        this._label = new St.Label({ x_align: Clutter.ActorAlign.CENTER,
                                     y_align: Clutter.ActorAlign.CENTER });
        this.actor.add_actor(this._label);

        this.icons = [];

	this.workspaces = this.getWorkSpace();
	this.selectWorkspaces = [];

	let popup = popupList._popupList.slice();
        for (let i = 0; i < global.screen.n_workspaces; i++) {
            let workspace_index = popup.pop();
	    this.selectWorkspaces[i] = this.workspaces[workspace_index];

            let icon = new WindowIcon(workspace_index);

            this.addItem(icon.actor, icon.label);
            this.icons.push(icon);
        }
    },

    getWorkSpace: function() {
        let activeWs = global.screen.get_active_workspace();
	let activeIndex = activeWs.index();
	let ws = [];

	ws[activeIndex] = activeWs;

	for (let i = activeIndex - 1; i >= 0; i--) {
            ws[i] = ws[i + 1].get_neighbor(Meta.MotionDirection.UP);
	}

	for (let i = activeIndex + 1; i < global.screen.n_workspaces; i++) {
            ws[i] = ws[i - 1].get_neighbor(Meta.MotionDirection.DOWN);
	}

	return ws;
    },

    _getPreferredHeight: function(actor, forWidth, alloc) {
        this.parent(actor, forWidth, alloc);

        let spacing = this.actor.get_theme_node().get_padding(St.Side.BOTTOM);
        //let [labelMin, labelNat] = this._label.get_preferred_height(-1);
        //alloc.min_size += labelMin + spacing;
        alloc.min_size += spacing;
        //alloc.natural_size += labelNat + spacing;
        alloc.natural_size += spacing;
    },

    _allocateTop: function(actor, box, flags) {
        let childBox = new Clutter.ActorBox();
        childBox.x1 = box.x1;
        childBox.x2 = box.x2;
        childBox.y2 = box.y2;
        childBox.y1 = childBox.y2 - this._label.height;
        this._label.allocate(childBox, flags);

        let spacing = this.actor.get_theme_node().get_padding(St.Side.BOTTOM);
        box.y2 -= this._label.height + spacing;
        this.parent(actor, box, flags);
    },

    highlight: function(index, justOutline) {
        this.parent(index, justOutline);

        this._label.set_text(index == -1 ? '' : this.icons[index].label.text);
    }
});

const WindowIcon = new Lang.Class({
    Name: 'WindowIcon',

    _init: function(workspace_index) {

        this.actor = new St.BoxLayout({ style_class: 'alt-tab-app',
                                        vertical: true });
        this._icon = new St.Widget({ layout_manager: new Clutter.BinLayout() });

        this.actor.add(this._icon, { x_fill: false, y_fill: false } );
        this.label = new St.Label({ text: "WorkSpace " + String(workspace_index + 1) });

        this._icon.destroy_all_children();

        this._porthole = Main.layoutManager.getWorkAreaForMonitor(Main.layoutManager.primaryIndex);

	let scale = Math.min(1.0, WINDOW_PREVIEW_SIZE / this._porthole.width,
				WINDOW_PREVIEW_SIZE / this._porthole.height);

	let metaWorkspace = global.screen.get_workspace_by_index(workspace_index);
	let thumbnail = new WorkspaceThumbnail.WorkspaceThumbnail(metaWorkspace);

        thumbnail.actor.set_scale(scale, scale);
	this._icon.add_actor(thumbnail.actor);

	//if (this.app)
	this._icon.add_actor(this._createAppIcon(null, APP_ICON_SIZE_SMALL));

        let scaleFactor = St.ThemeContext.get_for_stage(global.stage).scale_factor;
        this._icon.set_size(WINDOW_PREVIEW_SIZE * scaleFactor, WINDOW_PREVIEW_SIZE * scaleFactor);
    },

    _createAppIcon: function(app, size) {
        //let appIcon = app ? app.create_icon_texture(size)
        let appIcon = new St.Icon({ icon_name: 'icon-missing',
                                    icon_size: size });
        appIcon.x_expand = appIcon.y_expand = true;
        appIcon.x_align = appIcon.y_align = Clutter.ActorAlign.END;

        return appIcon;
    }
});

function init() {
	print("wxg: switch workspace init");
}

function enable() {
	print("wxg: switch workspace enable");
	let ws = new WorkSpace();

	popupList = new PopupList();
}

function disable() {
}
<|endoftext|>


<commit_before>// syntax
'use strict';

// module
module.exports = grunt => {
  // modules
  const async = require('async');
  const path = require('path');
  const util = require('util');
  const merge = require('deepmerge');
  const needle = require('needle');
  const fs = require('fs');
  // const promise = require('promise');

  // load browserSync
  const browserSync = require('browser-sync').create();

  // maps
  const file = grunt.file;
  const log = grunt.log;

  // intermediary .json
  const hack = '.nightwatch.json';

  // consts
  const runner = path.resolve(path.dirname(require.resolve('nightwatch')), '../bin/runner.js');
  const args = ['-c', hack];
  const presets = [].concat( require('../lib/ios'), require('../lib/phantom') );

  // defaults
  const settings = {
    // testing source
    // folders define groups of tests
    'src_folders': [],
    // global parameters
    // usage: browser.globals.$variable
    // defaults of selenium;
    // yet not starting process
    'selenium': {
      'start_process': true,
      // is automatically set
      'server_path': require('selenium-standalone-jar')(),
      // log
      'log_path': '',
      // hostname
      // perhaps change to use sellenium grid
      'host': '127.0.0.1',
      // port
      'port': 4444,
      // client settings
      'cli_args': {
        // chromedriver; default is firefox
        // is used when browserName: Chrome
        'webdriver.chrome.driver': require('chromedriver').path,
        'webdriver.ie.driver': ''
      },
      // this is for multi-threading
      'test_workers' : {
        'enabled' : true,
        'workers' : 'auto'
      }
    },
    'test_settings': {
      'default': ''
    }
  };

  // default live variables
  const live = {
    port : 8080,
    logLevel : 'debug',
    open : false,
    server : [ 'src' ]
  };

  // run the tests
  function run (tasks, done) {
    // going parallel
    async.parallel(tasks, error => {
      if (error) {
        grunt.fail.fatal(`Error-> Running the tests`);
      }
      // nothing else to do, finish task
      done(true);
    });
  }

  // spawning task
  function task (e) {
    return callback => {
      // spawning a process
      grunt.util.spawn({
        cmd: 'node',
        args: [].concat(runner, [].concat(args, '--env', e)),
        opts: {
          stdio: 'inherit'
        },
        env: util._extend( {}, process.env )
      }, (error, result, code) => {
        callback(code !== 0 ? `Running test failed with ${code}` : null, `Success -> Running ${e}`);

        // delete intermediare configs
        file.delete( hack );
      } );
    };
  }

  // register as multi task to have multiple targets running
  grunt.registerMultiTask('e2e', 'Run e2e test for your Cordova project', function () {
    // async
    let done = this.async(),
      tasks = [],
      options = this.options(settings, this.data.settings),
      env = grunt.option('env'),
      argv = this.data.argv || {},
      sync = argv.live ? merge( live, argv.live || {} ) : '',
      saucelabs = grunt.option('saucelabs');

    // helpers
    let runTests = () => {
      // writing intermediary config
      grunt.file.write( path.resolve( process.cwd(), hack ), JSON.stringify( options, null, 2 ), null);

      // this is wrapper code; we could do something amazing perhaps later on
      tasks.push( task( env.join( ',' ) ) );

      // env.forEach( e => {
      //   tasks.push(task(e));
      // });
      // check if there is something in the queue
      if (tasks.length > 0) {
        // run the task queue
        run(tasks, done);
      } else {
        // delete intermediare configs
        file.delete(hack);
        // end, if there is nothing in the queue
        done();
      }
    };

    // uploading an artifact to saucelabs
    let uploadSaucelabs = config => {
      // files
      config.storage.files.forEach( ( file, index, files ) => {
        // file
        const buffer = fs.readFileSync(file);
        // request
        const http = {
          headers : {
            'Authorization' : `Basic ${ new Buffer( `${ config.username }:${ config.token }` ).toString('base64') }`,
            'Content-Type' : 'application/octet-stream',
            'Content-Length' : buffer.length,
          },
          timeout: 5000 * 1000
        };
        // debug
        log.ok( `Uploading ${ file } ...` );
        // do the request
        needle
          .post(`${ config.storage.url }/${ config.username }/${ file }?${ config.storage.params }`, buffer, http, function ( error, response ) {
            if ( ! error && response.statusCode === 200) {
              log.ok( `Success` );
            } else {
              log.fail( `Error ${ error }` );
            }
            // check for end
            if ( index === files.length - 1 ) {
              done();
            }
          } );
      } );
    };

    // parsing the
    env = !! env || typeof env === 'string' ?
      env.split(',') : [].concat(argv.env || 'default');

    // deepmerge presets on the settings
    presets.forEach( preset => {
      // this will yell at you, but is better then dot notation
      options['test_settings'] = merge(preset, options['test_settings']);
    } );

    if ( saucelabs && !! argv.saucelabs ) {
      uploadSaucelabs(argv.saucelabs);
      // done();
    } else {
      if ( sync ) {
        browserSync.init(sync, runTests);
      } else {
          runTests();
      }
    }

  });

};
<commit_msg>[Fix] filename<commit_after>// syntax
'use strict';

// module
module.exports = grunt => {
  // modules
  const async = require('async');
  const path = require('path');
  const util = require('util');
  const merge = require('deepmerge');
  const needle = require('needle');
  const fs = require('fs');
  // const promise = require('promise');

  // load browserSync
  const browserSync = require('browser-sync').create();

  // maps
  const file = grunt.file;
  const log = grunt.log;

  // intermediary .json
  const hack = '.nightwatch.json';

  // consts
  const runner = path.resolve(path.dirname(require.resolve('nightwatch')), '../bin/runner.js');
  const args = ['-c', hack];
  const presets = [].concat( require('../lib/ios'), require('../lib/phantom') );

  // defaults
  const settings = {
    // testing source
    // folders define groups of tests
    'src_folders': [],
    // global parameters
    // usage: browser.globals.$variable
    // defaults of selenium;
    // yet not starting process
    'selenium': {
      'start_process': true,
      // is automatically set
      'server_path': require('selenium-standalone-jar')(),
      // log
      'log_path': '',
      // hostname
      // perhaps change to use sellenium grid
      'host': '127.0.0.1',
      // port
      'port': 4444,
      // client settings
      'cli_args': {
        // chromedriver; default is firefox
        // is used when browserName: Chrome
        'webdriver.chrome.driver': require('chromedriver').path,
        'webdriver.ie.driver': ''
      },
      // this is for multi-threading
      'test_workers' : {
        'enabled' : true,
        'workers' : 'auto'
      }
    },
    'test_settings': {
      'default': ''
    }
  };

  // default live variables
  const live = {
    port : 8080,
    logLevel : 'debug',
    open : false,
    server : [ 'src' ]
  };

  // run the tests
  function run (tasks, done) {
    // going parallel
    async.parallel(tasks, error => {
      if (error) {
        grunt.fail.fatal(`Error-> Running the tests`);
      }
      // nothing else to do, finish task
      done(true);
    });
  }

  // spawning task
  function task (e) {
    return callback => {
      // spawning a process
      grunt.util.spawn({
        cmd: 'node',
        args: [].concat(runner, [].concat(args, '--env', e)),
        opts: {
          stdio: 'inherit'
        },
        env: util._extend( {}, process.env )
      }, (error, result, code) => {
        callback(code !== 0 ? `Running test failed with ${code}` : null, `Success -> Running ${e}`);

        // delete intermediare configs
        file.delete( hack );
      } );
    };
  }

  // register as multi task to have multiple targets running
  grunt.registerMultiTask('e2e', 'Run e2e test for your Cordova project', function () {
    // async
    let done = this.async(),
      tasks = [],
      options = this.options(settings, this.data.settings),
      env = grunt.option('env'),
      argv = this.data.argv || {},
      sync = argv.live ? merge( live, argv.live || {} ) : '',
      saucelabs = grunt.option('saucelabs');

    // helpers
    let runTests = () => {
      // writing intermediary config
      grunt.file.write( path.resolve( process.cwd(), hack ), JSON.stringify( options, null, 2 ), null);

      // this is wrapper code; we could do something amazing perhaps later on
      tasks.push( task( env.join( ',' ) ) );

      // env.forEach( e => {
      //   tasks.push(task(e));
      // });
      // check if there is something in the queue
      if (tasks.length > 0) {
        // run the task queue
        run(tasks, done);
      } else {
        // delete intermediare configs
        file.delete(hack);
        // end, if there is nothing in the queue
        done();
      }
    };

    // uploading an artifact to saucelabs
    let uploadSaucelabs = config => {
      // files
      config.storage.files.forEach( ( file, index, files ) => {
        // file
        const buffer = fs.readFileSync(file);
        // request
        const http = {
          headers : {
            'Authorization' : `Basic ${ new Buffer( `${ config.username }:${ config.token }` ).toString('base64') }`,
            'Content-Type' : 'application/octet-stream',
            'Content-Length' : buffer.length,
          },
          timeout: 5000 * 1000
        };
        // debug
        log.ok( `Uploading ${ file } ...` );
        // do the request
        needle
          .post(`${ config.storage.url }/${ config.username }/${ file.replace(/^.*[\\\/]/, '') }?${ config.storage.params }`, buffer, http, function ( error, response ) {
            if ( ! error && response.statusCode === 200) {
              log.ok( `Success` );
            } else {
              log.fail( `Error ${ error }` );
            }
            // check for end
            if ( index === files.length - 1 ) {
              done();
            }
          } );
      } );
    };

    // parsing the
    env = !! env || typeof env === 'string' ?
      env.split(',') : [].concat(argv.env || 'default');

    // deepmerge presets on the settings
    presets.forEach( preset => {
      // this will yell at you, but is better then dot notation
      options['test_settings'] = merge(preset, options['test_settings']);
    } );

    if ( saucelabs && !! argv.saucelabs ) {
      uploadSaucelabs(argv.saucelabs);
      // done();
    } else {
      if ( sync ) {
        browserSync.init(sync, runTests);
      } else {
          runTests();
      }
    }

  });

};
<|endoftext|>


<commit_before>module.exports = function(grunt) {

  var exec = require('child_process').exec;

  /**
   * Show content of the package to double check before publishing
   */
  grunt.registerTask('npm-show', 'Show files that would be published to npm.', function() {
    var done = this.async();

    exec('npm pack', function(err, pkgFile) {
      exec('tar -tf ' + pkgFile, function(err, pkgContent) {
        console.log(pkgContent);
        exec('rm ' + pkgFile, done);
      });
    });
  });

  /**
   * Publish to NPM
   */
  grunt.registerTask('npm-publish', 'Publish to NPM.', function() {
    this.requires('build');
    // TODO(vojta): cancel if not clean work space (to avoid pushing uncommitted changes to npm)

    var done = this.async();
    var pkg = grunt.config('pkg');
    var minor = parseInt(pkg.version.split('.')[1], 10);
    var tag = (minor % 2) ? 'canary' : 'latest';

    exec('npm publish --tag ' + tag, function(err, output, error) {
      if (err) return grunt.fail.fatal(err.message.replace(/\n$/, '.'));
      grunt.log.ok('Published to NPM @' + tag);
      done();
    });
  });
};
<commit_msg>Grunt release - do not publish if dirty working space<commit_after>module.exports = function(grunt) {

  var exec = require('child_process').exec;

  /**
   * Show content of the package to double check before publishing
   */
  grunt.registerTask('npm-show', 'Show files that would be published to npm.', function() {
    var done = this.async();

    exec('npm pack', function(err, pkgFile) {
      exec('tar -tf ' + pkgFile, function(err, pkgContent) {
        console.log(pkgContent);
        exec('rm ' + pkgFile, done);
      });
    });
  });

  /**
   * Publish to NPM
   */
  grunt.registerTask('npm-publish', 'Publish to NPM.', function() {
    this.requires('build');

    var done = this.async();
    var pkg = grunt.config('pkg');
    var minor = parseInt(pkg.version.split('.')[1], 10);
    var tag = (minor % 2) ? 'canary' : 'latest';

    exec('git status -s', function(err, stdout, stderr) {
      if (stdout) {
        return grunt.fail.warn('Dirty workspace, cannot push to NPM.\n' + stdout + '\n');
      }

      exec('npm publish --tag ' + tag, function(err, output, error) {
        if (err) return grunt.fail.fatal(err.message.replace(/\n$/, '.'));
        grunt.log.ok('Published to NPM @' + tag);
        done();
      });
    });
  });
};
<|endoftext|>


<commit_before>'use strict';

app.controller('RecipesCtrl',
    function ($scope, $routeParams, recipesData, identity) {

        $scope.isLogged = identity.isAuthenticated();

        $scope.recipeId = $routeParams.id;

        $scope.test = 'HERE!';

        recipesData.getAllRecipes(
            function (data) {
                $scope.recipes = data;
            });

        recipesData.getRecipeById($scope.recipeId,
            function (data) {
                $scope.recipe = data;
            })
    });<commit_msg>Issue with Recipe controller looking for Id that doesn't needs fixed moved to other controller recipeDetailsCtrl. Last minute before sleep....<commit_after>'use strict';

app.controller('RecipesCtrl',
    function ($scope, $routeParams, recipesData, identity) {

        $scope.isLogged = identity.isAuthenticated();

        $scope.test = 'HERE!';

        recipesData.getAllRecipes(
            function (data) {
                $scope.recipes = data;
            });
    });<|endoftext|>