<commit_before>function WeaponInventory(world, camera) {
    var slots = [
        'pistol',
    ];

    var models = [
        Models.pistol(),
    ];

    var actions = [
        function () {
            var intersect = world.findPlayerIntersection(camera);
            if (intersect) {
                console.log("Hit!!", intersect, intersect.item);
                world.addSmallCube(intersect.point);
            } else {
                console.log("miss!!");
            }
        }
    ];

    var elm = document.getElementById('weapon-inventory');

    return new Inventory(world, camera, slots, models, actions, elm, 0.05);
}

function BlockInventory(world, camera) {
    var slots = [
        'shovel',
        'block',
    ];

    var models = [
        Models.shovel(),
        Models.block(),
    ];

    var actions = [
        function () {
            world.removeLookedAtBlock(camera);
        },
        function () {
            world.addLookedAtBlock(camera);
        },
    ];

    var elm = document.getElementById('block-inventory');

    return new Inventory(world, camera, slots, models, actions, elm, -0.05);
}

function Inventory(world, camera, slots, models, actions, elm, leftwardOffset) {
    var self = this;

    var currentSlot = -1;

    self.doAction = function () {
        var action = actions[currentSlot];
        if (action) {
            action();
        } else {
            throw "Not sure what to do with the currently selected item: '" + selectedItem + "'";
        }
    }

    function selectSlot(n) {
        if (slots.length <= n) return;
        var html = generateInventoryHTML(slots, n);
        elm.innerHTML = html;
        if (currentSlot > -1) {
            world.removeFromScene(models[currentSlot]);
        }
        world.addToScene(models[n]);
        currentSlot = n;
    }

    function pointItem(item, c) {
        var p = item.position;
        var target = new THREE.Vector3();
        target.x = p.x + sin(c.lat) * cos(c.lon);
        target.y = p.y + cos(c.lat);
        target.z = p.z + sin(c.lat) * sin(c.lon);
        item.lookAt(target);
    }

    function positionItem(item, playerPos, c) {
        var pp = playerPos;
        var ip = item.position;
        // http://www.vias.org/comp_geometry/math_coord_convert_3d.htm
        ip.x = pp.x + 0.15 * sin(c.lat) * cos(c.lon)
        ip.y = pp.y + 0.15 * cos(c.lat);
        ip.z = pp.z + 0.15 * sin(c.lat) * sin(c.lon);
    }

    function postitionPerspective(item, leftward) {
        var p = item.position;
        var r = new THREE.Matrix4();
        r.setRotationFromEuler(item.rotation, item.eulerOrder);

        // Mov left / right
        var mov = new THREE.Vector3(leftward, 0, 0);
        mov.applyMatrix3(r);

        p.x += mov.x;
        p.y += mov.y;
        p.z += mov.z;
    }

    self.update = function (playerPosition, controlState) {
        var p = playerPosition;
        var c = controlState;
        var item = models[currentSlot];
        positionItem(item, p, c);
        pointItem(item, c);
        postitionPerspective(item, leftwardOffset);

        if (c.selectSlot1) {
            selectSlot(0);
        } else if (c.selectSlot2) {
            selectSlot(1);
        } else if (c.selectSlot3) {
            selectSlot(2);
        }
    }

    selectSlot(0);
}

function generateInventoryHTML(slots, selectedIndex) {
    var html = "";
    for (var i = 0; i < selectedIndex; i++) {
        html += "
" + slots[i] + "
";
    }
    html += "
" + slots[selectedIndex] + "
";
    for (var i = selectedIndex+1; i < slots.length; i++) {
        html += "
" + slots[i] + "
";
    }
    return html;
}
<commit_msg>Clean up inventory.<commit_after>function WeaponInventory(world, camera) {
    var slots = [
        {
            name: 'pistol',
            model: Models.pistol(),
            action: pistolAction,
        }
    ];

    function pistolAction() {
        var intersect = world.findPlayerIntersection(camera);
        if (intersect) {
            console.log("Hit!!", intersect, intersect.item);
            world.addSmallCube(intersect.point);
        } else {
            console.log("miss!!");
        }
    }

    var elm = document.getElementById('weapon-inventory');

    return new Inventory(world, camera, slots, elm, 0.05);
}

function BlockInventory(world, camera) {
    var slots = [
        {
            name: 'shovel',
            model: Models.shovel(),
            action: shovelAction,
        },
        {
            name: 'block',
            model: Models.block(),
            action: blockAction,
        }
    ];

    function shovelAction() {
        world.removeLookedAtBlock(camera);
    }

    function blockAction() {
        world.addLookedAtBlock(camera);
    }

    var elm = document.getElementById('block-inventory');

    return new Inventory(world, camera, slots, elm, -0.05);
}

function Inventory(world, camera, slots, elm, leftwardOffset) {
    var self = this;

    var currentSlot = -1;

    self.doAction = function () {
        var action = slots[currentSlot].action;
        if (action) {
            action();
        } else {
            throw "Not sure what to do with the currently selected item: '" + selectedItem + "'";
        }
    }

    function selectSlot(n) {
        if (slots.length <= n) return;
        var html = generateInventoryHTML(slots, n);
        elm.innerHTML = html;
        if (currentSlot > -1) {
            world.removeFromScene(slots[currentSlot].model);
        }
        world.addToScene(slots[n].model);
        currentSlot = n;
    }

    function pointItem(item, c) {
        var p = item.position;
        var target = new THREE.Vector3();
        target.x = p.x + sin(c.lat) * cos(c.lon);
        target.y = p.y + cos(c.lat);
        target.z = p.z + sin(c.lat) * sin(c.lon);
        item.lookAt(target);
    }

    function positionItem(item, playerPos, c) {
        var pp = playerPos;
        var ip = item.position;
        // http://www.vias.org/comp_geometry/math_coord_convert_3d.htm
        ip.x = pp.x + 0.15 * sin(c.lat) * cos(c.lon)
        ip.y = pp.y + 0.15 * cos(c.lat);
        ip.z = pp.z + 0.15 * sin(c.lat) * sin(c.lon);
    }

    function postitionPerspective(item, leftward) {
        var p = item.position;
        var r = new THREE.Matrix4();
        r.setRotationFromEuler(item.rotation, item.eulerOrder);

        // Mov left / right
        var mov = new THREE.Vector3(leftward, 0, 0);
        mov.applyMatrix3(r);

        p.x += mov.x;
        p.y += mov.y;
        p.z += mov.z;
    }

    self.update = function (playerPosition, controlState) {
        var p = playerPosition;
        var c = controlState;
        var item = slots[currentSlot].model;
        positionItem(item, p, c);
        pointItem(item, c);
        postitionPerspective(item, leftwardOffset);

        if (c.selectSlot1) {
            selectSlot(0);
        } else if (c.selectSlot2) {
            selectSlot(1);
        } else if (c.selectSlot3) {
            selectSlot(2);
        }
    }

    selectSlot(0);
}

function generateInventoryHTML(slots, selectedIndex) {
    var html = "";
    for (var i = 0; i < selectedIndex; i++) {
        html += "
" + slots[i].name + "
";
    }
    html += "
" + slots[selectedIndex].name + "
";
    for (var i = selectedIndex+1; i < slots.length; i++) {
        html += "
" + slots[i].name + "
";
    }
    return html;
}
<|endoftext|>


<commit_before>import chalk from 'chalk';
import title from 'title';
import bytes from 'bytes';
import { isReady, isFailed } from '../build-state';

const prepareState = state => title(state.replace('_', ' '));

// That's how long the word "Initializing" is
const longestState = 12;

// That's the spacing between the source, state and time
const padding = 8;

const styleBuild = (build, times, longestSource) => {
  const { entrypoint, readyState, id, hasOutput } = build;
  const state = prepareState(readyState).padEnd(longestState + padding);
  const time = typeof times[id] === 'string' ? times[id] : '';

  let stateColor = chalk.grey;
  let pathColor = chalk.cyan;

  if (isReady({ readyState })) {
    stateColor = item => item;
  } else if (isFailed({ readyState })) {
    stateColor = chalk.red;
    pathColor = chalk.red;
  }

  const entry = entrypoint.padEnd(longestSource + padding);
  const prefix = hasOutput ? '┌' : '╶';

  return `${chalk.grey(prefix)} ${pathColor(
    entry
  )}${stateColor(state)}${time}`;
};

const styleOutput = (output) => {
  const { type, path, readyState, size, isLast, lambda } = output;
  const prefix = type === 'lambda' ? 'λ ' : '';
  const finalSize = size ? ` ${chalk.grey(`(${bytes(size)})`)}` : '';

  let color = chalk.grey;
  let finalRegion = '';

  if (isReady({ readyState })) {
    color = item => item;
  } else if (isFailed({ readyState })) {
    color = chalk.red;
  }

  if (lambda) {
    const { deployedTo } = lambda;

    if (deployedTo && deployedTo.length > 0) {
      finalRegion = ` ${chalk.grey(`[${deployedTo.join(', ')}]`)}`;
    }
  }

  const corner = isLast ? '└──' : '├──';
  const main = prefix + path + finalSize + finalRegion;

  return `${chalk.grey(corner)} ${color(main)}`;
};

export default (builds, times) => {
  const buildsAndOutput = [];

  for (const build of builds) {
    buildsAndOutput.push(build);
    const { output, copiedFrom } = build;

    if (!copiedFrom && output && output.length > 0) {
      build.hasOutput = true;

      for (const item of output) {
        item.isOutput = true;
        item.readyState = build.readyState;

        if (output.indexOf(item) === output.length - 1) {
          item.isLast = true;
        }

        buildsAndOutput.push(item);
      }
    }
  }

  const longestSource = builds.reduce((final, current) => {
    const { length } = current.entrypoint;
    return length > final ? length : final;
  }, 0);

  const final = buildsAndOutput.map((item, index) => {
    let log = null;

    if (item.isOutput) {
      log = styleOutput(item);
    } else {
      log = styleBuild(item, times, longestSource);
    }

    const newline = index === buildsAndOutput.length - 1 ? '' : '\n';
    return log + newline;
  });

  return {
    lines: final.length + 1,
    toPrint: `${final.join('')}\n`
  };
};
<commit_msg>Group builds with similar paths together to reduce the output (#2015)<commit_after>import chalk from 'chalk';
import title from 'title';
import bytes from 'bytes';
import { isReady, isFailed } from '../build-state';

// That's how long the word "Initializing" is
const longestState = 12;

// That's the spacing between the source, state and time
const padding = 8;

// That's the max numbers of builds and outputs that will be displayed
const MAX_BUILD_GROUPS = 5;
const MAX_OUTPUTS_PER_GROUP = 5;

const prepareState = state => title(state.replace('_', ' '));

// Get the common path out of multiple builds
const getCommonPath = (buildGroup) => {
  const commonPath = [];
  const splits = buildGroup.map((build) => getDirPath(build.entrypoint).split('/'));
  const shortest = splits.reduce((prevValue, currentValue) =>
    prevValue.length < currentValue.length
      ? prevValue.length
      : currentValue.length
  );

  for (let i = 0; i <= shortest; i++) {
    const first = splits[0][i];
    if (splits.every((pathParts) => pathParts[i] === first)) {
      commonPath.push(first);
      continue;
    }

    break;
  }

  return commonPath.join('/') || '/';
};

const styleBuild = (build, times, longestSource) => {
  const { entrypoint, readyState, id, hasOutput } = build;
  const state = prepareState(readyState).padEnd(longestState + padding);
  const time = typeof times[id] === 'string' ? times[id] : '';

  let stateColor = chalk.grey;
  let pathColor = chalk.cyan;

  if (isReady({ readyState })) {
    stateColor = item => item;
  } else if (isFailed({ readyState })) {
    stateColor = chalk.red;
    pathColor = chalk.red;
  }

  const entry = entrypoint.padEnd(longestSource + padding);
  const prefix = hasOutput ? '┌' : '╶';

  return `${chalk.grey(prefix)} ${pathColor(entry)}${stateColor(state)}${time}`;
};

const styleHiddenBuilds =  (commonPath, buildGroup, times, longestSource, isHidden = false) => {
  const { id } = buildGroup[0];
  const entry = commonPath.padEnd(longestSource + padding);
  const time = typeof times[id] === 'string' ? times[id] : '';
  const prefix = isHidden === false && buildGroup.some((build) => build.hasOutput) ? '┌' : '╶';

  // Set the defaults so that they will be sorted
  const stateMap = {
    READY: 0,
    ERROR: 0,
    BUILDING: 0
  };

  buildGroup.map(({ readyState }) => {
    stateMap[readyState] = stateMap[readyState]
      ? stateMap[readyState] + 1
      : 1;

    return readyState;
  });

  let state = Object.keys(stateMap).map((readyState) => {
    const counter = stateMap[readyState];
    const name = prepareState(readyState);

    if (!counter) {
      return null;
    }

    return `${counter > 9 ? '9+' : counter} ${name}`;
  }).filter(s => s).join(', ')

  // Since the longestState might still be shorter
  // than multiple states we still want to ensure
  // a space between the states and the time
  state = `${state} `.padEnd(longestState + padding);

  let pathColor = chalk.cyan;
  let stateColor = chalk.grey;

  if (buildGroup.every(isReady)) {
    stateColor = item => item;
  } else if (buildGroup.every(isFailed)) {
    stateColor = chalk.red;
    pathColor = chalk.red;
  }

  if (isHidden) {
    pathColor = chalk.grey;
  }

  return `${chalk.grey(prefix)} ${pathColor(entry)}${stateColor(state)}${time}`;
};

const styleOutput = (output) => {
  const { type, path, readyState, size, isLast, lambda } = output;
  const prefix = type === 'lambda' ? 'λ ' : '';
  const finalSize = size ? ` ${chalk.grey(`(${bytes(size)})`)}` : '';

  let color = chalk.grey;
  let finalRegion = '';

  if (isReady({ readyState })) {
    color = item => item;
  } else if (isFailed({ readyState })) {
    color = chalk.red;
  }

  if (lambda) {
    const { deployedTo } = lambda;

    if (deployedTo && deployedTo.length > 0) {
      finalRegion = ` ${chalk.grey(`[${deployedTo.join(', ')}]`)}`;
    }
  }

  const corner = isLast ? '└──' : '├──';
  const main = prefix + path + finalSize + finalRegion;

  return `${chalk.grey(corner)} ${color(main)}`;
};

const getDirPath = (path, level = 0, highestLevel = null) => {
  const parts = path.split('/').slice(0, -1);

  if (highestLevel === null || level === 0) {
    return parts.join('/');
  }

  const reverseLevel = highestLevel - level;
  return parts.slice(0, reverseLevel).join('/');
};

const sortByEntrypoint = (a, b) => {
  const aPath = getDirPath(a.entrypoint);
  const bPath = getDirPath(b.entrypoint);

  if (aPath === '') {
    return 1;
  }

  if (bPath === '') {
    return -1;
  }

  if (aPath > bPath) {
    return 1;
  }

  if (bPath > aPath) {
    return -1;
  }

  return 0;
};

const groupBuilds = (buildList, highestLevel, counter) => {
  const currentIndex = counter % (buildList.length);
  const __level = Math.ceil(counter / buildList.length);
  const _level = (__level === 0 ? 1 : __level) - 1;
  const level = _level > highestLevel ? highestLevel : _level;
  const currentPath = getDirPath(buildList[currentIndex][0].entrypoint, level, highestLevel);

  const nextList = [];
  let currentGroup = [];

  for (let i = 0; i < buildList.length; i++) {
    const group = buildList[i];
    const path = getDirPath(group[0].entrypoint, level, highestLevel);

    if (path === currentPath) {
      currentGroup = currentGroup.concat(group);
    } else {
      nextList.push(group);
    }
  }

  if (currentIndex === 0) {
    nextList.unshift(currentGroup);
  } else {
    nextList.splice(currentIndex, 0, currentGroup);
  }

  return nextList;
};

const prepareBuild = (build) => {
   build.hasOutput = Array.isArray(build.output) && build.output.length > 0;

   if (build.hasOutput) {
     build.output = build.output.map((item) => {
       item.readyState = build.readyState;
       return item;
     });
   }

   return build;
};

export default (builds, times) => {
  // Sort the builds by path
  // so that the grouping will be easier
  let path = builds
    .map(prepareBuild)
    .sort(sortByEntrypoint)
    .map(build => [build]);

  const highestLevel = builds.reduce((prev, curr) => {
    const partCounter = curr.entrypoint.split('/').length - 1;
    return partCounter > prev ? partCounter : prev;
  }, 0);

  // Group builds together
  let counter = 0;

  while (path.length > MAX_BUILD_GROUPS) {
    path = groupBuilds(path, highestLevel, counter);
    counter++;
  }

  // Reverse the paths so that the larger chunks come last
  // including the / directory
  path = path.reverse();

  const longestSource = builds.reduce((final, current) => {
    const { length } = current.entrypoint;
    return length > final ? length : final;
  }, 0);

  const final = [];
  let finalBuildsLength = path.length;
  let lengthWithoutRootPaths = path.length;
  let hiddenBuildGroup = [];

  // Ungroup the root files
  path = (() => {
    const nextList = [];
    const rootList = [];

    for (const group of path) {
      if (getCommonPath(group) === '/') {
        group.map((item) => rootList.push([item]));
      } else {
        nextList.push(group);
      }
    }

    lengthWithoutRootPaths = nextList.length;
    rootList.map((group) => nextList.push(group));

    return nextList;
  })();

  path.map((buildGroup) => {
    const commonPath = getCommonPath(buildGroup);

    // All items with the common path / are a single group
    if (commonPath === '/') {
      if (
        lengthWithoutRootPaths <= MAX_BUILD_GROUPS &&
        finalBuildsLength <= MAX_BUILD_GROUPS
      ) {
        const item = buildGroup[0];
        final.push(`${styleBuild(item, times, longestSource)}\n`);
        finalBuildsLength++;
      } else {
        hiddenBuildGroup.push(buildGroup[0]);
        return buildGroup;
      }
    } else if (buildGroup.length === 1) {
      const item = buildGroup[0];
      final.push(`${styleBuild(item, times, longestSource)}\n`);
      finalBuildsLength++;
    } else {
      final.push(`${styleHiddenBuilds(`${commonPath}/*`, buildGroup, times, longestSource)}\n`);
      finalBuildsLength++;
    }

    // Get the first five outputs when the deployment is ready
    const outputs = buildGroup.reduce((prevValue, currentValue) => (
      prevValue.concat(Array.isArray(currentValue.output)
        ? currentValue.output
        : []
      )
    ), []);

    outputs.slice(0, MAX_OUTPUTS_PER_GROUP).map((output, index) => (
      final.push(`${styleOutput({
        ...output,
        isLast: outputs.length === (index + 1)
      })}\n`)
    ));

    if (outputs.length > MAX_OUTPUTS_PER_GROUP) {
      final.push(chalk.grey(`└── ${outputs.length - MAX_OUTPUTS_PER_GROUP} output items hidden\n`));
    }

    return buildGroup;
  });

  if (hiddenBuildGroup.length) {
    final.push(`${styleHiddenBuilds(
      `${hiddenBuildGroup.length} builds hidden`,
      hiddenBuildGroup,
      times,
      longestSource,
      true
    )}\n`);
  }

  return {
    lines: final.length + 1,
    toPrint: `${final.join('')}`
  };
};
<|endoftext|>


<commit_before>/**
 * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH
 * under one or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information regarding copyright
 * ownership.
 *
 * Camunda licenses this file to you under the MIT; you may not use this file
 * except in compliance with the MIT License.
 */

var coverage = process.env.COVERAGE;

if (coverage) {

  // must set NODE_ENV to coverage to activate
  // babel-plugin-istanbul (cf. babel config)
  process.env.NODE_ENV = 'coverage';
}

var path = require('path');
var os = require('os');

var platform = os.platform();
var windows = /^win/.test(platform);

var { DefinePlugin } = require('webpack');

var absoluteBasePath = path.resolve(__dirname);
var resourcePath = path.resolve(__dirname + '/resources');

/* global process */

// configures browsers to run test against
// any of [ 'ChromeHeadless', 'Chrome', 'Firefox', 'IE', 'PhantomJS' ]
var browsers =
  (process.env.TEST_BROWSERS || 'ChromeHeadless')
    .replace(/^\s+|\s+$/, '')
    .split(/\s*,\s*/g)
    .map(function(browser) {
      if (browser === 'ChromeHeadless') {
        process.env.CHROME_BIN = require('puppeteer').executablePath();

        // workaround https://github.com/GoogleChrome/puppeteer/issues/290
        if (process.platform === 'linux') {
          return 'ChromeHeadless_Linux';
        }
      }

      return browser;
    });

var suite = coverage ? 'test/all.js' : 'test/suite.js';

module.exports = function(karma) {
  karma.set({

    frameworks: [
      'mocha',
      'sinon-chai'
    ],

    files: [
      suite
    ],

    preprocessors: {
      [suite]: [ 'webpack', 'env' ]
    },

    reporters: [ 'spec' ].concat(coverage ? 'coverage' : []),

    customLaunchers: {
      ChromeHeadless_Linux: {
        base: 'ChromeHeadless',
        flags: [
          '--no-sandbox',
          '--disable-setuid-sandbox'
        ],
        debug: true
      }
    },

    coverageReporter: {
      reporters: [
        { type: 'lcov', subdir: '.' }
      ]
    },

    browsers: browsers,

    browserNoActivityTimeout: 30000,

    singleRun: true,
    autoWatch: false,

    webpack: {
      mode: 'development',
      module: {
        rules: [
          {
            test: /\.js$/,
            exclude: /node_modules/,
            use: 'babel-loader'
          },
          {
            oneOf: [
              {
                test: /\/[A-Z][^/]+\.svg$/,
                use: 'react-svg-loader'
              },
              {
                test: /\.(css|bpmn|cmmn|dmn|less|xml|png|svg)$/,
                use: 'raw-loader'
              }
            ]
          }
        ]
      },
      plugins: [
        new DefinePlugin({
          'process.env': {
            NODE_ENV: JSON.stringify('test'),
            WINDOWS: JSON.stringify(windows)
          }
        })
      ],
      resolve: {
        mainFields: [
          'dev:module',
          'browser',
          'module',
          'main'
        ],
        modules: [
          'node_modules',
          absoluteBasePath,
          resourcePath
        ],
        alias: {
          'bpmn-js/lib/Modeler': 'test/mocks/bpmn-js/Modeler',
          'cmmn-js/lib/Modeler': 'test/mocks/cmmn-js/Modeler',
          'dmn-js/lib/Modeler': 'test/mocks/dmn-js/Modeler',
          './DmnModeler': 'test/mocks/dmn-js/Modeler',
          './CodeMirror': 'test/mocks/code-mirror/CodeMirror',
          'sourcemapped-stacktrace': 'test/mocks/sourcemapped-stacktrace'
        }
      }
    }
  });
};
<commit_msg>fix(project): fix Windows™<commit_after>/**
 * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH
 * under one or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information regarding copyright
 * ownership.
 *
 * Camunda licenses this file to you under the MIT; you may not use this file
 * except in compliance with the MIT License.
 */

var coverage = process.env.COVERAGE;

if (coverage) {

  // must set NODE_ENV to coverage to activate
  // babel-plugin-istanbul (cf. babel config)
  process.env.NODE_ENV = 'coverage';
}

var path = require('path');
var os = require('os');

var platform = os.platform();
var windows = /^win/.test(platform);

var { DefinePlugin } = require('webpack');

var absoluteBasePath = path.resolve(__dirname);
var resourcePath = path.resolve(__dirname + '/resources');

/* global process */

// configures browsers to run test against
// any of [ 'ChromeHeadless', 'Chrome', 'Firefox', 'IE', 'PhantomJS' ]
var browsers =
  (process.env.TEST_BROWSERS || 'ChromeHeadless')
    .replace(/^\s+|\s+$/, '')
    .split(/\s*,\s*/g)
    .map(function(browser) {
      if (browser === 'ChromeHeadless') {
        process.env.CHROME_BIN = require('puppeteer').executablePath();

        // workaround https://github.com/GoogleChrome/puppeteer/issues/290
        if (process.platform === 'linux') {
          return 'ChromeHeadless_Linux';
        }
      }

      return browser;
    });

var suite = coverage ? 'test/all.js' : 'test/suite.js';

module.exports = function(karma) {
  karma.set({

    frameworks: [
      'mocha',
      'sinon-chai'
    ],

    files: [
      suite
    ],

    preprocessors: {
      [suite]: [ 'webpack', 'env' ]
    },

    reporters: [ 'spec' ].concat(coverage ? 'coverage' : []),

    customLaunchers: {
      ChromeHeadless_Linux: {
        base: 'ChromeHeadless',
        flags: [
          '--no-sandbox',
          '--disable-setuid-sandbox'
        ],
        debug: true
      }
    },

    coverageReporter: {
      reporters: [
        { type: 'lcov', subdir: '.' }
      ]
    },

    browsers: browsers,

    browserNoActivityTimeout: 30000,

    singleRun: true,
    autoWatch: false,

    webpack: {
      mode: 'development',
      module: {
        rules: [
          {
            test: /\.js$/,
            exclude: /node_modules/,
            use: 'babel-loader'
          },
          {
            oneOf: [
              {
                test: /[/\\][A-Z][^/]+\.svg$/,
                use: 'react-svg-loader'
              },
              {
                test: /\.(css|bpmn|cmmn|dmn|less|xml|png|svg)$/,
                use: 'raw-loader'
              }
            ]
          }
        ]
      },
      plugins: [
        new DefinePlugin({
          'process.env': {
            NODE_ENV: JSON.stringify('test'),
            WINDOWS: JSON.stringify(windows)
          }
        })
      ],
      resolve: {
        mainFields: [
          'dev:module',
          'browser',
          'module',
          'main'
        ],
        modules: [
          'node_modules',
          absoluteBasePath,
          resourcePath
        ],
        alias: {
          'bpmn-js/lib/Modeler': 'test/mocks/bpmn-js/Modeler',
          'cmmn-js/lib/Modeler': 'test/mocks/cmmn-js/Modeler',
          'dmn-js/lib/Modeler': 'test/mocks/dmn-js/Modeler',
          './DmnModeler': 'test/mocks/dmn-js/Modeler',
          './CodeMirror': 'test/mocks/code-mirror/CodeMirror',
          'sourcemapped-stacktrace': 'test/mocks/sourcemapped-stacktrace'
        }
      }
    }
  });
};
<|endoftext|>


<commit_before>import mergeWith from 'lodash/mergeWith'
import isFunction from 'lodash/isFunction'
import defaults from 'lodash/defaults'
import map from 'lodash/map'
import get from 'lodash/get'

function resolveConfig(configs) {
  return defaults(
    {
      theme: resolveFunctionKeys(mergeExtensions(defaults(...map(configs, 'theme')))),
      variants: defaults(...map(configs, 'variants')),
    },
    ...configs
  )
}

function mergeExtensions({ extend, ...theme }) {
  return mergeWith(theme, extend, (themeValue, extensions, key) => {
    if (!isFunction(themeValue) && !(isFunction(extensions))) {
      return {
        ...themeValue,
        ...extensions,
      }
    }

    return resolveThemePath => ({
      ...value(themeValue, resolveThemePath),
      ...value(extensions, resolveThemePath),
    })
  })
}

function resolveFunctionKeys(object) {
  const resolveObjectPath = (key, defaultValue) => get(object, key, defaultValue)

  return Object.keys(object).reduce((resolved, key) => {
    return {
      ...resolved,
      [key]: isFunction(object[key]) ? object[key](resolveObjectPath) : object[key],
    }
  }, {})
}

function value(valueToResolve, ...args) {
  return isFunction(valueToResolve) ? valueToResolve(...args) : valueToResolve
}

export default resolveConfig
<commit_msg>Fix code style<commit_after>import mergeWith from 'lodash/mergeWith'
import isFunction from 'lodash/isFunction'
import defaults from 'lodash/defaults'
import map from 'lodash/map'
import get from 'lodash/get'

function value(valueToResolve, ...args) {
  return isFunction(valueToResolve) ? valueToResolve(...args) : valueToResolve
}

function mergeExtensions({ extend, ...theme }) {
  return mergeWith(theme, extend, (themeValue, extensions) => {
    if (!isFunction(themeValue) && !isFunction(extensions)) {
      return {
        ...themeValue,
        ...extensions,
      }
    }

    return resolveThemePath => ({
      ...value(themeValue, resolveThemePath),
      ...value(extensions, resolveThemePath),
    })
  })
}

function resolveFunctionKeys(object) {
  const resolveObjectPath = (key, defaultValue) => get(object, key, defaultValue)

  return Object.keys(object).reduce((resolved, key) => {
    return {
      ...resolved,
      [key]: isFunction(object[key]) ? object[key](resolveObjectPath) : object[key],
    }
  }, {})
}

export default function resolveConfig(configs) {
  return defaults(
    {
      theme: resolveFunctionKeys(mergeExtensions(defaults(...map(configs, 'theme')))),
      variants: defaults(...map(configs, 'variants')),
    },
    ...configs
  )
}
<|endoftext|>


<commit_before>'use strict';

angular.module('oide.vnc', ['ngRoute','ui.bootstrap','noVNC'])

.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/vnc', {
    templateUrl: '/static/vnc/vnc.html',
    controller: 'VncCtrl',
    resolve: {
      vncConfig: function (VncService) {
        return VncService.getVncConfig();
      }
    }
  });
}])

.factory('VncService', ['$http', function ($http) {
  return {
    getVncConfig: function () {
      return $http
        .get('/vnc/a/config')
        .success(function (data, status, headers, config) {
          return data;
        });
    }
  };
}])
.controller('VncCtrl', ['$scope', 'vncConfig', '$log', function($scope,vncConfig,$log) {
  $scope.vncConfig = vncConfig.config;
}]);
<commit_msg>Fixed typo.<commit_after>'use strict';

angular.module('oide.vnc', ['ngRoute','ui.bootstrap','noVNC'])

.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/vnc', {
    templateUrl: '/static/vnc/vnc.html',
    controller: 'VncCtrl',
    resolve: {
      vncConfig: function (VncService) {
        return VncService.getVncConfig();
      }
    }
  });
}])

.factory('VncService', ['$http', function ($http) {
  return {
    getVncConfig: function () {
      return $http
        .get('/vnc/a/config')
        .success(function (data, status, headers, config) {
          return data;
        });
    }
  };
}])
.controller('VncCtrl', ['$scope', 'vncConfig', '$log', function($scope,vncConfig,$log) {
  $scope.vncConfig = vncConfig.data;
}]);
<|endoftext|>


<commit_before>export { default as createApiKey } from './createApiKey.js'
export { default as createUniqueId } from './createUniqueId.js'
export { default as detectExecutable } from './detectExecutable.js'
export { default as formatToClfTime } from './formatToClfTime.js'
export { default as getHttpApiCorsConfig } from './getHttpApiCorsConfig.js'
export { default as jsonPath } from './jsonPath.js'
export { default as lowerCaseKeys } from './lowerCaseKeys.js'
export { default as parseHeaders } from './parseHeaders.js'
export { default as parseMultiValueHeaders } from './parseMultiValueHeaders.js'
export { default as parseMultiValueQueryStringParameters } from './parseMultiValueQueryStringParameters.js'
export { default as parseQueryStringParameters } from './parseQueryStringParameters.js'
export { default as splitHandlerPathAndName } from './splitHandlerPathAndName.js'
export { default as checkDockerDaemon } from './checkDockerDaemon.js'
export { default as checkGoVersion } from './checkGoVersion.js'
export { default as generateHapiPath } from './generateHapiPath.js'
// export { default as baseImage } from './baseImage.js'

const { isArray } = Array
const { keys } = Object

// Detect the toString encoding from the request headers content-type
// enhance if further content types need to be non utf8 encoded.
export function detectEncoding(request) {
  const contentType = request.headers['content-type']

  return typeof contentType === 'string' &&
    contentType.includes('multipart/form-data')
    ? 'binary'
    : 'utf8'
}

export function nullIfEmpty(obj) {
  return obj && (keys(obj).length > 0 ? obj : null)
}

export function isPlainObject(obj) {
  return typeof obj === 'object' && !isArray(obj) && obj != null
}

export function toPlainOrEmptyObject(obj) {
  return typeof obj === 'object' && !isArray(obj) ? obj : {}
}
<commit_msg>chore: import order nit<commit_after>export { default as checkDockerDaemon } from './checkDockerDaemon.js'
export { default as checkGoVersion } from './checkGoVersion.js'
export { default as createApiKey } from './createApiKey.js'
export { default as createUniqueId } from './createUniqueId.js'
export { default as detectExecutable } from './detectExecutable.js'
export { default as formatToClfTime } from './formatToClfTime.js'
export { default as generateHapiPath } from './generateHapiPath.js'
export { default as getHttpApiCorsConfig } from './getHttpApiCorsConfig.js'
export { default as jsonPath } from './jsonPath.js'
export { default as lowerCaseKeys } from './lowerCaseKeys.js'
export { default as parseHeaders } from './parseHeaders.js'
export { default as parseMultiValueHeaders } from './parseMultiValueHeaders.js'
export { default as parseMultiValueQueryStringParameters } from './parseMultiValueQueryStringParameters.js'
export { default as parseQueryStringParameters } from './parseQueryStringParameters.js'
export { default as splitHandlerPathAndName } from './splitHandlerPathAndName.js'

// export { default as baseImage } from './baseImage.js'

const { isArray } = Array
const { keys } = Object

// Detect the toString encoding from the request headers content-type
// enhance if further content types need to be non utf8 encoded.
export function detectEncoding(request) {
  const contentType = request.headers['content-type']

  return typeof contentType === 'string' &&
    contentType.includes('multipart/form-data')
    ? 'binary'
    : 'utf8'
}

export function nullIfEmpty(obj) {
  return obj && (keys(obj).length > 0 ? obj : null)
}

export function isPlainObject(obj) {
  return typeof obj === 'object' && !isArray(obj) && obj != null
}

export function toPlainOrEmptyObject(obj) {
  return typeof obj === 'object' && !isArray(obj) ? obj : {}
}
<|endoftext|>


<commit_before>import _ from 'lodash';

import { frontendPreferences as frontendPrefsConfig } from '../../config/app';

export function getCookie(name) {
  const begin = document.cookie.indexOf(name);
  if (begin === -1) {
    return '';
  }
  const fromBegin = document.cookie.substr(begin);
  const tokenWithName = fromBegin.split(';');
  const tokenWithNameSplit = tokenWithName[0].split('=');
  const token = tokenWithNameSplit[1];
  return token.trim();
}

export function setCookie(name, value = '', expiresDays, path, domain) {
  const expiresDate = Date.now() + expiresDays * 24 * 60 * 60 * 1000;
  const expiresTime = new Date(expiresDate).toUTCString();
  const cookie = `${name}=${value}` +
    `;expires=${expiresTime}` +
    `;path=${path}` +
    (domain && domain !== 'localhost' ? `;domain=${domain}` : '');
  return document.cookie = cookie;
}

import moment from 'moment';

export function fromNowOrNow(date) {
  var now = moment(date);

  if (Math.abs(moment().diff(now)) < 1000) { // 1000 milliseconds
    return 'just now';
  }

  return now.fromNow();
}

export function getFullDate(date) {
  return moment(date).format('YYYY-MM-DD HH:mm:ss [UTC]Z');
}

import defaultUserpic50Path from 'assets/images/default-userpic-50.png';
import defaultUserpic75Path from 'assets/images/default-userpic-75.png';

const userDefaults = {
  profilePictureMediumUrl: defaultUserpic50Path,
  profilePictureLargeUrl: defaultUserpic75Path,
  frontendPreferences: frontendPrefsConfig.defaultValues
};

export function userParser(user) {
  const newUser = { ...user };

  // Missing display name
  if (!user.screenName) {
    newUser.screenName = user.username;
  }

  // Profile pictures
  newUser.profilePictureMediumUrl = user.profilePictureMediumUrl || userDefaults.profilePictureMediumUrl;
  newUser.profilePictureLargeUrl = user.profilePictureLargeUrl || userDefaults.profilePictureLargeUrl;

  // Frontend preferences (only use this client's subtree)
  const prefSubTree = user.frontendPreferences && user.frontendPreferences[frontendPrefsConfig.clientId];
  newUser.frontendPreferences = _.merge({}, userDefaults.frontendPreferences, prefSubTree);

  return newUser;
}

export function postParser(post) {
  post.commentsDisabled = (post.commentsDisabled === '1');
  return { ...post };
}

export function preventDefault(realFunction) {
  return (event) => {
    // Check if it's a "click" (not "submit", "keydown" etc).
    // Also, check if it's a "fancy" one (made with middle button, or with Shift pressed etc).
    // Then, if it's a "fancy click", don't prevent default action.
    // Prevent custom action ("realFunction") instead.
    if (event.type === 'click' && (event.button !== 0 || event.shiftKey || event.ctrlKey || event.altKey || event.metaKey)) {
      return true;
    }

    event.preventDefault();
    return realFunction && realFunction(event);
  };
}

export function stopPropagation(event) {
  event.stopPropagation();
}

export function confirmFirst(realFunction) {
  return () => {
    if (confirm('Are you sure?')) {
      return realFunction && realFunction();
    }
  };
}

export function getCurrentRouteName(router) {
  return router && router.routes && router.routes[router.routes.length - 1].name;
}

export function pluralForm(n, singular, plural = null, format = 'n w') {
  let w;

  if (n == 1) {
    w = singular;
  } else if (plural) {
    w = plural;
  } else {
    w = singular + 's';
  }

  return format.replace('n', n).replace('w', w);
}

export function isMobile() {
  const viewportWidth = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
  return (viewportWidth <= 767);
}
<commit_msg>Update isMobile() threshold: 767px -> 991px<commit_after>import _ from 'lodash';

import { frontendPreferences as frontendPrefsConfig } from '../../config/app';

export function getCookie(name) {
  const begin = document.cookie.indexOf(name);
  if (begin === -1) {
    return '';
  }
  const fromBegin = document.cookie.substr(begin);
  const tokenWithName = fromBegin.split(';');
  const tokenWithNameSplit = tokenWithName[0].split('=');
  const token = tokenWithNameSplit[1];
  return token.trim();
}

export function setCookie(name, value = '', expiresDays, path, domain) {
  const expiresDate = Date.now() + expiresDays * 24 * 60 * 60 * 1000;
  const expiresTime = new Date(expiresDate).toUTCString();
  const cookie = `${name}=${value}` +
    `;expires=${expiresTime}` +
    `;path=${path}` +
    (domain && domain !== 'localhost' ? `;domain=${domain}` : '');
  return document.cookie = cookie;
}

import moment from 'moment';

export function fromNowOrNow(date) {
  var now = moment(date);

  if (Math.abs(moment().diff(now)) < 1000) { // 1000 milliseconds
    return 'just now';
  }

  return now.fromNow();
}

export function getFullDate(date) {
  return moment(date).format('YYYY-MM-DD HH:mm:ss [UTC]Z');
}

import defaultUserpic50Path from 'assets/images/default-userpic-50.png';
import defaultUserpic75Path from 'assets/images/default-userpic-75.png';

const userDefaults = {
  profilePictureMediumUrl: defaultUserpic50Path,
  profilePictureLargeUrl: defaultUserpic75Path,
  frontendPreferences: frontendPrefsConfig.defaultValues
};

export function userParser(user) {
  const newUser = { ...user };

  // Missing display name
  if (!user.screenName) {
    newUser.screenName = user.username;
  }

  // Profile pictures
  newUser.profilePictureMediumUrl = user.profilePictureMediumUrl || userDefaults.profilePictureMediumUrl;
  newUser.profilePictureLargeUrl = user.profilePictureLargeUrl || userDefaults.profilePictureLargeUrl;

  // Frontend preferences (only use this client's subtree)
  const prefSubTree = user.frontendPreferences && user.frontendPreferences[frontendPrefsConfig.clientId];
  newUser.frontendPreferences = _.merge({}, userDefaults.frontendPreferences, prefSubTree);

  return newUser;
}

export function postParser(post) {
  post.commentsDisabled = (post.commentsDisabled === '1');
  return { ...post };
}

export function preventDefault(realFunction) {
  return (event) => {
    // Check if it's a "click" (not "submit", "keydown" etc).
    // Also, check if it's a "fancy" one (made with middle button, or with Shift pressed etc).
    // Then, if it's a "fancy click", don't prevent default action.
    // Prevent custom action ("realFunction") instead.
    if (event.type === 'click' && (event.button !== 0 || event.shiftKey || event.ctrlKey || event.altKey || event.metaKey)) {
      return true;
    }

    event.preventDefault();
    return realFunction && realFunction(event);
  };
}

export function stopPropagation(event) {
  event.stopPropagation();
}

export function confirmFirst(realFunction) {
  return () => {
    if (confirm('Are you sure?')) {
      return realFunction && realFunction();
    }
  };
}

export function getCurrentRouteName(router) {
  return router && router.routes && router.routes[router.routes.length - 1].name;
}

export function pluralForm(n, singular, plural = null, format = 'n w') {
  let w;

  if (n == 1) {
    w = singular;
  } else if (plural) {
    w = plural;
  } else {
    w = singular + 's';
  }

  return format.replace('n', n).replace('w', w);
}

export function isMobile() {
  const viewportWidth = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
  return (viewportWidth <= 991);
}
<|endoftext|>


<commit_before>import store from 'store';
import uuid from 'node-uuid';
import later from 'later';

function initDeviceID() {
	let deviceID = store.get('device_id');
	if (!deviceID) {
		store.set('device_id', uuid.v4());
	}
}

function setupWorker() {
	// var sched = later.parse.cron('1/1 * * * *');
	var sched = later.parse.cron('0,30 * * * *');
	later.setInterval(runWorker, sched);
}

function runWorker() {
	var deviceID = store.get('device_id');
	let worker = new Worker('./js/worker.js');

	worker.onmessage = (e) => {
		// TODO: update update records
		const { unreadChapters, comicID } = e.data;
		// console.log(unreadChapters.length);

		switch(window.PLATFORM) {
		case 'electron':
			// TODO: create native notification
			// var { ipcRenderer } = require('electron');

			break;
		case 'chrome_extension':
			// TODO create chrome notification

			break;
		default:
			throw 'Unsupported Platform';
		}
	};

	// start worker
	worker.postMessage({deviceID});
}

export function initializeApp({callback}) {
	initDeviceID();
	setupWorker();

	callback();
}
<commit_msg>Terminate worker before every task start<commit_after>import store from 'store';
import uuid from 'node-uuid';
import later from 'later';

let worker;

function initDeviceID() {
	let deviceID = store.get('device_id');
	if (!deviceID) {
		store.set('device_id', uuid.v4());
	}
}

function setupWorker() {
	// var sched = later.parse.cron('1/1 * * * *');
	var sched = later.parse.cron('0,30 * * * *');
	later.setInterval(runWorker, sched);
}

function runWorker() {
	var deviceID = store.get('device_id');

	if (typeof worker !== 'undefined') { worker.terminate(); }
	worker = new Worker('./js/worker.js');

	worker.onmessage = (e) => {
		// TODO: update update records
		const { unreadChapters, comicID } = e.data;
		// console.log(unreadChapters.length);

		switch(window.PLATFORM) {
		case 'electron':
			// TODO: create native notification
			// var { ipcRenderer } = require('electron');

			break;
		case 'chrome_extension':
			// TODO create chrome notification

			break;
		default:
			throw 'Unsupported Platform';
		}
	};

	// start worker
	worker.postMessage({deviceID});
}

export function initializeApp({callback}) {
	initDeviceID();
	setupWorker();

	callback();
}
<|endoftext|>


<commit_before>import data from '../../data'

const SKINS = [
  '1F3FA', '1F3FB', '1F3FC',
  '1F3FD', '1F3FE', '1F3FF',
]

function unifiedToNative(unified) {
  var unicodes = unified.split('-'),
      codePoints = unicodes.map((u) => `0x${u}`)

  return String.fromCodePoint(...codePoints)
}

function sanitize(emoji) {
  var { name, short_names, skin_tone, skin_variations, emoticons, unified } = emoji,
      id = short_names[0],
      colons = `:${id}:`

  if (skin_tone) {
    colons += `:skin-tone-${skin_tone}:`
  }

  return {
    id,
    name,
    colons,
    emoticons,
    skin: skin_tone || skin_variations ? 1 : null,
    native: unifiedToNative(unified),
  }
}

function getSanitizedData() {
  return sanitize(getData(...arguments))
}

function getData(emoji, skin, sheetURL) {
  var emojiData = {},
      _emojiData, _emoji, _id

  if (typeof emoji == 'string') {
    if (_emoji = data.short_names[emoji]) {
      emoji = _emoji
    }

    if (_emojiData = data.emojis[emoji]) {
      emojiData = _emojiData
    }
  } else if (emoji.id) {
    if (_id = data.short_names[emoji.id]) {
      emoji.id = _id
    }

    if (_emojiData = data.emojis[emoji.id]) {
      emojiData = _emojiData
      skin || (skin = emoji.skin)
    }
  }

  if (emojiData.skin_variations && skin > 1 && sheetURL) {
    emojiData = JSON.parse(JSON.stringify(emojiData))

    var skinKey = SKINS[skin - 1],
        variationKey = `${emojiData.unified}-${skinKey}`,
        variationData = emojiData.skin_variations[variationKey],
        kitMatches = sheetURL.match(/(apple|google|twitter|emojione)/),
        kit = kitMatches[0]

    if (variationData[`has_img_${kit}`]) {
      emojiData.skin_tone = skin

      for (let k in variationData) {
        let v = variationData[k]
        emojiData[k] = v
      }
    }
  }

  return emojiData
}

function intersect(a, b) {
  var aSet = new Set(a),
      bSet = new Set(b),
      intersection = null

  intersection = new Set(
    [...aSet].filter(x => bSet.has(x))
  )

  return Array.from(intersection)
}

export { getData, getSanitizedData, intersect }
<commit_msg>Use hasOwnProperty to detect if emoji exists Fixes a bug in Firefox where “watch” emoji would throw because apparently `_emojiData = data.emojis['watch']` returns a function instead of the value of the watch key<commit_after>import data from '../../data'

const SKINS = [
  '1F3FA', '1F3FB', '1F3FC',
  '1F3FD', '1F3FE', '1F3FF',
]

function unifiedToNative(unified) {
  var unicodes = unified.split('-'),
      codePoints = unicodes.map((u) => `0x${u}`)

  return String.fromCodePoint(...codePoints)
}

function sanitize(emoji) {
  var { name, short_names, skin_tone, skin_variations, emoticons, unified } = emoji,
      id = short_names[0],
      colons = `:${id}:`

  if (skin_tone) {
    colons += `:skin-tone-${skin_tone}:`
  }

  return {
    id,
    name,
    colons,
    emoticons,
    skin: skin_tone || skin_variations ? 1 : null,
    native: unifiedToNative(unified),
  }
}

function getSanitizedData() {
  return sanitize(getData(...arguments))
}

function getData(emoji, skin, sheetURL) {
  var emojiData = {}

  if (typeof emoji == 'string') {
    if (data.short_names.hasOwnProperty(emoji)) {
      emoji = data.short_names[emoji]
    }

    if (data.emojis.hasOwnProperty(emoji)) {
      emojiData = data.emojis[emoji]
    }
  } else if (emoji.id) {
    if (data.short_names.hasOwnProperty(emoji.id)) {
      emoji.id = data.short_names[emoji.id]
    }

    if (data.emojis.hasOwnProperty(emoji.id)) {
      emojiData = data.emojis[emoji.id]
      skin || (skin = emoji.skin)
    }
  }

  if (emojiData.skin_variations && skin > 1 && sheetURL) {
    emojiData = JSON.parse(JSON.stringify(emojiData))

    var skinKey = SKINS[skin - 1],
        variationKey = `${emojiData.unified}-${skinKey}`,
        variationData = emojiData.skin_variations[variationKey],
        kitMatches = sheetURL.match(/(apple|google|twitter|emojione)/),
        kit = kitMatches[0]

    if (variationData[`has_img_${kit}`]) {
      emojiData.skin_tone = skin

      for (let k in variationData) {
        let v = variationData[k]
        emojiData[k] = v
      }
    }
  }

  return emojiData
}

function intersect(a, b) {
  var aSet = new Set(a),
      bSet = new Set(b),
      intersection = null

  intersection = new Set(
    [...aSet].filter(x => bSet.has(x))
  )

  return Array.from(intersection)
}

export { getData, getSanitizedData, intersect }
<|endoftext|>


<commit_before>import React        from 'react';
import ReactDOM     from 'react-dom';
import { Provider } from 'react-redux';
import DevTools     from 'containers/DevToolsWindow';

export function createConstants (...constants) {
  return constants.reduce((acc, constant) => {
    acc[constant] = constant;
    return acc;
  }, {});
}

export function createReducer (initialState, reducerMap) {
  return (state = initialState, action) => {
    const reducer = reducerMap[action.type];

    return reducer ? reducer(state, action.payload) : state;
  };
}

export function createDevToolsWindow (store) {
  const win = window.open(
    null,
    'redux-devtools', // give it a name so it reuses the same window
    `width=400,height=${window.outerHeight},menubar=no,location=no,resizable=yes,scrollbars=no,status=no`
  );

  // reload in case it's reusing the same window with the old content
  win.location.reload();

  // wait a little bit for it to reload, then render
  setTimeout(() => {
    // Wait for the reload to prevent:
    // "Uncaught Error: Invariant Violation: _registerComponent(...): Target container is not a DOM element."
    win.document.write('

');
    win.document.body.style.margin = '0';

    ReactDOM.render(
      <Provider store={store}>
        <DevTools />
      </Provider>
      , win.document.getElementById('react-devtools-root')
    );
  }, 10);
}
<commit_msg>refactor(createReducer): fix misnamed action handler (reducer -> handler), minor refactoring<commit_after>import React        from 'react';
import ReactDOM     from 'react-dom';
import { Provider } from 'react-redux';
import DevTools     from 'containers/DevToolsWindow';

export function createConstants (...constants) {
  return constants.reduce((acc, constant) => {
    acc[constant] = constant;
    return acc;
  }, {});
}

export function createReducer (initialState, fnMap) {
  return (state = initialState, { type, payload }) => {
    const handler = fnMap[type];

    return handler ? handler(state, payload) : state;
  };
}

export function createDevToolsWindow (store) {
  const win = window.open(
    null,
    'redux-devtools', // give it a name so it reuses the same window
    `width=400,height=${window.outerHeight},menubar=no,location=no,resizable=yes,scrollbars=no,status=no`
  );

  // reload in case it's reusing the same window with the old content
  win.location.reload();

  // wait a little bit for it to reload, then render
  setTimeout(() => {
    // Wait for the reload to prevent:
    // "Uncaught Error: Invariant Violation: _registerComponent(...): Target container is not a DOM element."
    win.document.write('

');
    win.document.body.style.margin = '0';

    ReactDOM.render(
      <Provider store={store}>
        <DevTools />
      </Provider>
      , win.document.getElementById('react-devtools-root')
    );
  }, 10);
}
<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at <http://mozilla.org/MPL/2.0/>. */

// @flow

import { PrefsHelper } from "devtools-modules";
import { isDevelopment } from "devtools-environment";
import Services from "devtools-services";
import { asyncStoreHelper } from "./asyncStoreHelper";

const prefsSchemaVersion = "1.0.6";

const pref = Services.pref;

if (isDevelopment()) {
  pref("devtools.debugger.logging", false);
  pref("devtools.debugger.alphabetize-outline", false);
  pref("devtools.debugger.auto-pretty-print", false);
  pref("devtools.source-map.client-service.enabled", true);
  pref("devtools.chrome.enabled", false);
  pref("devtools.debugger.pause-on-exceptions", false);
  pref("devtools.debugger.pause-on-caught-exceptions", false);
  pref("devtools.debugger.ignore-caught-exceptions", true);
  pref("devtools.debugger.call-stack-visible", true);
  pref("devtools.debugger.scopes-visible", true);
  pref("devtools.debugger.component-visible", true);
  pref("devtools.debugger.workers-visible", true);
  pref("devtools.debugger.expressions-visible", true);
  pref("devtools.debugger.xhr-breakpoints-visible", true);
  pref("devtools.debugger.breakpoints-visible", true);
  pref("devtools.debugger.event-listeners-visible", true);
  pref("devtools.debugger.start-panel-collapsed", false);
  pref("devtools.debugger.end-panel-collapsed", false);
  pref("devtools.debugger.start-panel-size", 300);
  pref("devtools.debugger.end-panel-size", 300);
  pref("devtools.debugger.tabs", "[]");
  pref("devtools.debugger.tabsBlackBoxed", "[]");
  pref("devtools.debugger.ui.framework-grouping-on", true);
  pref("devtools.debugger.pending-selected-location", "{}");
  pref("devtools.debugger.pending-breakpoints", "{}");
  pref("devtools.debugger.expressions", "[]");
  pref("devtools.debugger.file-search-case-sensitive", false);
  pref("devtools.debugger.file-search-whole-word", false);
  pref("devtools.debugger.file-search-regex-match", false);
  pref("devtools.debugger.project-directory-root", "");
  pref("devtools.debugger.prefs-schema-version", "1.0.1");
  pref("devtools.debugger.skip-pausing", false);
  pref("devtools.debugger.features.workers", true);
  pref("devtools.debugger.features.async-stepping", true);
  pref("devtools.debugger.features.wasm", true);
  pref("devtools.debugger.features.shortcuts", true);
  pref("devtools.debugger.features.root", true);
  pref("devtools.debugger.features.map-scopes", true);
  pref("devtools.debugger.features.remove-command-bar-options", true);
  pref("devtools.debugger.features.code-folding", false);
  pref("devtools.debugger.features.outline", true);
  pref("devtools.debugger.features.column-breakpoints", false);
  pref("devtools.debugger.features.pause-points", true);
  pref("devtools.debugger.features.skip-pausing", true);
  pref("devtools.debugger.features.component-pane", false);
  pref("devtools.debugger.features.autocomplete-expressions", false);
  pref("devtools.debugger.features.map-expression-bindings", true);
  pref("devtools.debugger.features.map-await-expression", true);
  pref("devtools.debugger.features.xhr-breakpoints", true);
  pref("devtools.debugger.features.original-blackbox", true);
  pref("devtools.debugger.features.windowless-workers", false);
  pref("devtools.debugger.features.event-listeners-breakpoints", true);
  pref("devtools.debugger.features.log-points", true);
}

export const prefs = new PrefsHelper("devtools", {
  logging: ["Bool", "debugger.alphabetize-outline"],
  alphabetizeOutline: ["Bool", "debugger.alphabetize-outline"],
  autoPrettyPrint: ["Bool", "debugger.auto-pretty-print"],
  clientSourceMapsEnabled: ["Bool", "source-map.client-service.enabled"],
  chromeAndExtenstionsEnabled: ["Bool", "chrome.enabled"],
  pauseOnExceptions: ["Bool", "debugger.pause-on-exceptions"],
  pauseOnCaughtExceptions: ["Bool", "debugger.pause-on-caught-exceptions"],
  ignoreCaughtExceptions: ["Bool", "debugger.ignore-caught-exceptions"],
  callStackVisible: ["Bool", "debugger.call-stack-visible"],
  scopesVisible: ["Bool", "debugger.scopes-visible"],
  componentVisible: ["Bool", "debugger.component-visible"],
  workersVisible: ["Bool", "debugger.workers-visible"],
  breakpointsVisible: ["Bool", "debugger.breakpoints-visible"],
  expressionsVisible: ["Bool", "debugger.expressions-visible"],
  xhrBreakpointsVisible: ["Bool", "debugger.xhr-breakpoints-visible"],
  eventListenersVisible: ["Bool", "debugger.event-listeners-visible"],
  startPanelCollapsed: ["Bool", "debugger.start-panel-collapsed"],
  endPanelCollapsed: ["Bool", "debugger.end-panel-collapsed"],
  startPanelSize: ["Int", "debugger.start-panel-size"],
  endPanelSize: ["Int", "debugger.end-panel-size"],
  frameworkGroupingOn: ["Bool", "debugger.ui.framework-grouping-on"],
  tabs: ["Json", "debugger.tabs", []],
  tabsBlackBoxed: ["Json", "debugger.tabsBlackBoxed", []],
  pendingSelectedLocation: ["Json", "debugger.pending-selected-location", {}],
  pendingBreakpoints: ["Json", "debugger.pending-breakpoints", {}],
  expressions: ["Json", "debugger.expressions", []],
  fileSearchCaseSensitive: ["Bool", "debugger.file-search-case-sensitive"],
  fileSearchWholeWord: ["Bool", "debugger.file-search-whole-word"],
  fileSearchRegexMatch: ["Bool", "debugger.file-search-regex-match"],
  debuggerPrefsSchemaVersion: ["Char", "debugger.prefs-schema-version"],
  projectDirectoryRoot: ["Char", "debugger.project-directory-root", ""],
  skipPausing: ["Bool", "debugger.skip-pausing"]
});

export const features = new PrefsHelper("devtools.debugger.features", {
  asyncStepping: ["Bool", "async-stepping"],
  wasm: ["Bool", "wasm"],
  shortcuts: ["Bool", "shortcuts"],
  root: ["Bool", "root"],
  columnBreakpoints: ["Bool", "column-breakpoints"],
  mapScopes: ["Bool", "map-scopes"],
  removeCommandBarOptions: ["Bool", "remove-command-bar-options"],
  workers: ["Bool", "workers"],
  windowlessWorkers: ["Bool", "windowless-workers"],
  outline: ["Bool", "outline"],
  codeFolding: ["Bool", "code-folding"],
  pausePoints: ["Bool", "pause-points"],
  skipPausing: ["Bool", "skip-pausing"],
  autocompleteExpression: ["Bool", "autocomplete-expressions"],
  mapExpressionBindings: ["Bool", "map-expression-bindings"],
  mapAwaitExpression: ["Bool", "map-await-expression"],
  componentPane: ["Bool", "component-pane"],
  xhrBreakpoints: ["Bool", "xhr-breakpoints"],
  originalBlackbox: ["Bool", "original-blackbox"],
  eventListenersBreakpoints: ["Bool", "event-listeners-breakpoints"],
  logPoints: ["Bool", "log-points"]
});

export const asyncStore = asyncStoreHelper("debugger", {
  pendingBreakpoints: ["pending-breakpoints", {}],
  tabs: ["tabs", []],
  xhrBreakpoints: ["xhr-breakpoints", []],
  eventListenerBreakpoints: ["event-listener-breakpoints", []]
});

if (prefs.debuggerPrefsSchemaVersion !== prefsSchemaVersion) {
  // clear pending Breakpoints
  prefs.pendingBreakpoints = {};
  prefs.tabs = [];
  prefs.xhrBreakpoints = [];
  prefs.debuggerPrefsSchemaVersion = prefsSchemaVersion;
}
<commit_msg>Fix logging pref (#7794)<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at <http://mozilla.org/MPL/2.0/>. */

// @flow

import { PrefsHelper } from "devtools-modules";
import { isDevelopment } from "devtools-environment";
import Services from "devtools-services";
import { asyncStoreHelper } from "./asyncStoreHelper";

const prefsSchemaVersion = "1.0.6";

const pref = Services.pref;

if (isDevelopment()) {
  pref("devtools.debugger.logging", false);
  pref("devtools.debugger.alphabetize-outline", false);
  pref("devtools.debugger.auto-pretty-print", false);
  pref("devtools.source-map.client-service.enabled", true);
  pref("devtools.chrome.enabled", false);
  pref("devtools.debugger.pause-on-exceptions", false);
  pref("devtools.debugger.pause-on-caught-exceptions", false);
  pref("devtools.debugger.ignore-caught-exceptions", true);
  pref("devtools.debugger.call-stack-visible", true);
  pref("devtools.debugger.scopes-visible", true);
  pref("devtools.debugger.component-visible", true);
  pref("devtools.debugger.workers-visible", true);
  pref("devtools.debugger.expressions-visible", true);
  pref("devtools.debugger.xhr-breakpoints-visible", true);
  pref("devtools.debugger.breakpoints-visible", true);
  pref("devtools.debugger.event-listeners-visible", true);
  pref("devtools.debugger.start-panel-collapsed", false);
  pref("devtools.debugger.end-panel-collapsed", false);
  pref("devtools.debugger.start-panel-size", 300);
  pref("devtools.debugger.end-panel-size", 300);
  pref("devtools.debugger.tabs", "[]");
  pref("devtools.debugger.tabsBlackBoxed", "[]");
  pref("devtools.debugger.ui.framework-grouping-on", true);
  pref("devtools.debugger.pending-selected-location", "{}");
  pref("devtools.debugger.pending-breakpoints", "{}");
  pref("devtools.debugger.expressions", "[]");
  pref("devtools.debugger.file-search-case-sensitive", false);
  pref("devtools.debugger.file-search-whole-word", false);
  pref("devtools.debugger.file-search-regex-match", false);
  pref("devtools.debugger.project-directory-root", "");
  pref("devtools.debugger.prefs-schema-version", "1.0.1");
  pref("devtools.debugger.skip-pausing", false);
  pref("devtools.debugger.features.workers", true);
  pref("devtools.debugger.features.async-stepping", true);
  pref("devtools.debugger.features.wasm", true);
  pref("devtools.debugger.features.shortcuts", true);
  pref("devtools.debugger.features.root", true);
  pref("devtools.debugger.features.map-scopes", true);
  pref("devtools.debugger.features.remove-command-bar-options", true);
  pref("devtools.debugger.features.code-folding", false);
  pref("devtools.debugger.features.outline", true);
  pref("devtools.debugger.features.column-breakpoints", false);
  pref("devtools.debugger.features.pause-points", true);
  pref("devtools.debugger.features.skip-pausing", true);
  pref("devtools.debugger.features.component-pane", false);
  pref("devtools.debugger.features.autocomplete-expressions", false);
  pref("devtools.debugger.features.map-expression-bindings", true);
  pref("devtools.debugger.features.map-await-expression", true);
  pref("devtools.debugger.features.xhr-breakpoints", true);
  pref("devtools.debugger.features.original-blackbox", true);
  pref("devtools.debugger.features.windowless-workers", false);
  pref("devtools.debugger.features.event-listeners-breakpoints", true);
  pref("devtools.debugger.features.log-points", true);
}

export const prefs = new PrefsHelper("devtools", {
  logging: ["Bool", "debugger.logging"],
  alphabetizeOutline: ["Bool", "debugger.alphabetize-outline"],
  autoPrettyPrint: ["Bool", "debugger.auto-pretty-print"],
  clientSourceMapsEnabled: ["Bool", "source-map.client-service.enabled"],
  chromeAndExtenstionsEnabled: ["Bool", "chrome.enabled"],
  pauseOnExceptions: ["Bool", "debugger.pause-on-exceptions"],
  pauseOnCaughtExceptions: ["Bool", "debugger.pause-on-caught-exceptions"],
  ignoreCaughtExceptions: ["Bool", "debugger.ignore-caught-exceptions"],
  callStackVisible: ["Bool", "debugger.call-stack-visible"],
  scopesVisible: ["Bool", "debugger.scopes-visible"],
  componentVisible: ["Bool", "debugger.component-visible"],
  workersVisible: ["Bool", "debugger.workers-visible"],
  breakpointsVisible: ["Bool", "debugger.breakpoints-visible"],
  expressionsVisible: ["Bool", "debugger.expressions-visible"],
  xhrBreakpointsVisible: ["Bool", "debugger.xhr-breakpoints-visible"],
  eventListenersVisible: ["Bool", "debugger.event-listeners-visible"],
  startPanelCollapsed: ["Bool", "debugger.start-panel-collapsed"],
  endPanelCollapsed: ["Bool", "debugger.end-panel-collapsed"],
  startPanelSize: ["Int", "debugger.start-panel-size"],
  endPanelSize: ["Int", "debugger.end-panel-size"],
  frameworkGroupingOn: ["Bool", "debugger.ui.framework-grouping-on"],
  tabs: ["Json", "debugger.tabs", []],
  tabsBlackBoxed: ["Json", "debugger.tabsBlackBoxed", []],
  pendingSelectedLocation: ["Json", "debugger.pending-selected-location", {}],
  pendingBreakpoints: ["Json", "debugger.pending-breakpoints", {}],
  expressions: ["Json", "debugger.expressions", []],
  fileSearchCaseSensitive: ["Bool", "debugger.file-search-case-sensitive"],
  fileSearchWholeWord: ["Bool", "debugger.file-search-whole-word"],
  fileSearchRegexMatch: ["Bool", "debugger.file-search-regex-match"],
  debuggerPrefsSchemaVersion: ["Char", "debugger.prefs-schema-version"],
  projectDirectoryRoot: ["Char", "debugger.project-directory-root", ""],
  skipPausing: ["Bool", "debugger.skip-pausing"]
});

export const features = new PrefsHelper("devtools.debugger.features", {
  asyncStepping: ["Bool", "async-stepping"],
  wasm: ["Bool", "wasm"],
  shortcuts: ["Bool", "shortcuts"],
  root: ["Bool", "root"],
  columnBreakpoints: ["Bool", "column-breakpoints"],
  mapScopes: ["Bool", "map-scopes"],
  removeCommandBarOptions: ["Bool", "remove-command-bar-options"],
  workers: ["Bool", "workers"],
  windowlessWorkers: ["Bool", "windowless-workers"],
  outline: ["Bool", "outline"],
  codeFolding: ["Bool", "code-folding"],
  pausePoints: ["Bool", "pause-points"],
  skipPausing: ["Bool", "skip-pausing"],
  autocompleteExpression: ["Bool", "autocomplete-expressions"],
  mapExpressionBindings: ["Bool", "map-expression-bindings"],
  mapAwaitExpression: ["Bool", "map-await-expression"],
  componentPane: ["Bool", "component-pane"],
  xhrBreakpoints: ["Bool", "xhr-breakpoints"],
  originalBlackbox: ["Bool", "original-blackbox"],
  eventListenersBreakpoints: ["Bool", "event-listeners-breakpoints"],
  logPoints: ["Bool", "log-points"]
});

export const asyncStore = asyncStoreHelper("debugger", {
  pendingBreakpoints: ["pending-breakpoints", {}],
  tabs: ["tabs", []],
  xhrBreakpoints: ["xhr-breakpoints", []],
  eventListenerBreakpoints: ["event-listener-breakpoints", []]
});

if (prefs.debuggerPrefsSchemaVersion !== prefsSchemaVersion) {
  // clear pending Breakpoints
  prefs.pendingBreakpoints = {};
  prefs.tabs = [];
  prefs.xhrBreakpoints = [];
  prefs.debuggerPrefsSchemaVersion = prefsSchemaVersion;
}
<|endoftext|>


<commit_before>/*
 This file is a part of libertysoil.org website
 Copyright (C) 2015  Loki Education (Social Enterprise)

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU Affero General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU Affero General Public License for more details.

 You should have received a copy of the GNU Affero General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
import kueLib from 'kue';

import config from '../../config';

let instance = null;

export default class Queue {

  constructor() {
    if (!instance) {
      instance = this;
      this.handler = kueLib.createQueue(config.kue);
    }

    return instance;
  }

  /**
   * Creates job in a queue
   */
  createJob = async (name, data) => {
    const promise = new Promise((resolve, reject) => {
      this.handler.create(name, data).save(function (error) {
        if (error) {
          reject(error);
        } else {
          resolve();
        }
      });
    });

    return await promise;
  };

}
<commit_msg>🚨Fix "padded-blocks" ESLint errors<commit_after>/*
 This file is a part of libertysoil.org website
 Copyright (C) 2015  Loki Education (Social Enterprise)

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU Affero General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU Affero General Public License for more details.

 You should have received a copy of the GNU Affero General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
import kueLib from 'kue';

import config from '../../config';

let instance = null;

export default class Queue {
  constructor() {
    if (!instance) {
      instance = this;
      this.handler = kueLib.createQueue(config.kue);
    }

    return instance;
  }

  /**
   * Creates job in a queue
   */
  createJob = async (name, data) => {
    const promise = new Promise((resolve, reject) => {
      this.handler.create(name, data).save(function (error) {
        if (error) {
          reject(error);
        } else {
          resolve();
        }
      });
    });

    return await promise;
  };
}
<|endoftext|>


<commit_before>var get = Ember.get, set = Ember.set,
    classify = Ember.String.classify,
    decamelize = Ember.String.decamelize;

Ember.Route = Ember.Object.extend({
  exit: function() {
    teardownView(this);
  },

  /**
    Transition into another route. Optionally supply a model for the
    route in question. The model will be serialized into the URL
    using the `serialize` hook.

    @method transitionTo
    @param {String} name the name of the route
    @param {...Object} models the
  */
  transitionTo: function() {
    this.transitioned = true;
    return this.router.transitionTo.apply(this.router, arguments);
  },

  send: function() {
    return this.router.send.apply(this.router, arguments);
  },

  /**
    @private

    This hook is the entry point for router.js

    @method setup
  */
  setup: function(context) {
    this.transitioned = false;
    this.redirect(context);

    if (this.transitioned) { return; }

    var controller = this.controllerFor(this.templateName, context);
    this.setupController(controller, context);
    this.renderTemplate(controller, context);
  },

  /**
    A hook you can implement to optionally redirect to another route.

    If you call `this.transitionTo` from inside of this hook, this route
    will not be entered in favor of the other hook.

    @method redirect
    @param {Object} model the model for this route
  */
  redirect: Ember.K,

  /**
    @private

    The hook called by `router.js` to convert parameters into the context
    for this handler. The public Ember hook is `model`.

    @method deserialize
  */
  deserialize: function(params) {
    var model = this.model(params);
    return this.currentModel = model;
  },

  /**
    A hook you can implement to convert the URL into the model for
    this route.

    ```js
    App.Route.map(function(match) {
      match("/posts/:post_id").to("post");
    });
    ```

    The model for the `post` route is `App.Post.find(params.post_id)`.

    By default, if your route has a dynamic segment ending in `_id`:

    * The model class is determined from the segment (`post_id`'s
      class is `App.Post`)
    * The find method is called on the model class with the value of
      the dynamic segment.

    @method model
    @param {Object} params the parameters extracted from the URL
  */
  model: function(params) {
    var match, name, value;

    for (var prop in params) {
      if (match = prop.match(/^(.*)_id$/)) {
        name = match[1];
        value = params[prop];
      }
    }

    if (!name) { return; }

    var className = classify(name),
        namespace = this.router.namespace,
        modelClass = namespace[className];

    Ember.assert("You used the dynamic segment " + name + "_id in your router, but " + namespace + "." + className + " did not exist and you did not override your state's `model` hook.", modelClass);
    return modelClass.find(value);
  },

  /**
    A hook you can implement to convert the route's model into parameters
    for the URL.

    ```js
    App.Route.map(function(match) {
      match("/posts/:post_id").to("post");
    });

    App.PostRoute = Ember.Route.extend({
      model: function(params) {
        // the server returns `{ id: 12 }`
        return jQuery.getJSON("/posts/" + params.post_id);
      },

      serialize: function(model) {
        // this will make the URL `/posts/12`
        return { post_id: model.id };
      }
    });
    ```

    The default `serialize` method inserts the model's `id` into the
    route's dynamic segment (in this case, `:post_id`).

    This method is called when `transitionTo` is called with a context
    in order to populate the URL.

    @method serialize
    @param {Object} model the route's model
    @param {Array} params an Array of parameter names for the current
      route (in the example, `['post_id']`.
    @return {Object} the serialized parameters
  */
  serialize: function(model, params) {
    if (params.length !== 1) { return; }

    var name = params[0], object = {};
    object[name] = get(model, 'id');

    return object;
  },

  /**
    A hook you can use to setup the controller for the current route.

    This method is called with the controller for the current route and the
    model supplied by the `model` hook.

    ```js
    App.Route.map(function(match) {
      match("/posts/:post_id").to("post");
    });
    ```

    For the `post` route, the controller is `App.PostController`.

    By default, the `setupController` hook sets the `content` property of
    the controller to the `model`.

    If no explicit controller is defined, the route will automatically create
    an appropriate controller for the model:

    * if the model is an `Ember.Array` (including record arrays from Ember
      Data), the controller is an `Ember.ArrayController`.
    * otherwise, the controller is an `Ember.ObjectController`.

    This means that your template will get a proxy for the model as its
    context, and you can act as though the model itself was the context.

    @method setupController
  */
  setupController: function(controller, model) {
    if (controller) {
      controller.set('content', model);
    }
  },

  /**
    Returns the controller for a particular route.

    ```js
    App.PostRoute = Ember.Route.extend({
      setupController: function(controller, post) {
        this._super(controller, post);
        this.controllerFor('posts').set('currentPost', post);
      }
    });
    ```

    By default, the controller for `post` is the shared instance of
    `App.PostController`.

    @method controllerFor
    @param {String} name the name of the route
    @param {Object} model the model associated with the route (optional)
    @return {Ember.Controller}
  */
  controllerFor: function(name, model) {
    var container = this.router.container,
        controller = container.lookup('controller:' + name);

    if (!controller) {
      model = model || this.modelFor(name);
      controller = Ember.generateController(container, name, model);
    }

    return controller;
  },

  /**
    Returns the current model for a given route.

    This is the object returned by the `model` hook of the route
    in question.

    @method modelFor
    @param {String} name the name of the route
    @return {Object} the model object
  */
  modelFor: function(name) {
    return this.container.lookup('route:' + name).currentModel;
  },

  /**
    A hook you can use to render the template for the current route.

    This method is called with the controller for the current route and the
    model supplied by the `model` hook. By default, it renders the route's
    template, configured with the controller for the route.

    This method can be overridden to set up and render additional or
    alternative templates.

    @method renderTemplate
    @param {Object} controller the route's controller
    @param {Object} model the route's model
  */
  renderTemplate: function(controller, model) {
    this.render();
  },

  /**
    Renders a template into an outlet.

    This method has a number of defaults, based on the name of the
    route specified in the router.

    For example:

    ```js
    App.Router.map(function(match) {
      match("/").to("index");
      match("/posts/:post_id").to("post");
    });

    App.PostRoute = App.Route.extend({
      renderTemplate: function() {
        this.render();
      }
    });
    ```

    The name of the `PostRoute`, as defined by the router, is `post`.

    By default, render will:

    * render the `post` template
    * with the `post` view (`PostView`) for event handling, if one exists
    * and the `post` controller (`PostController`), if one exists
    * into the `main` outlet of the `application` template

    You can override this behavior:

    ```js
    App.PostRoute = App.Route.extend({
      renderTemplate: function() {
        this.render('myPost', {   // the template to render
          into: 'index',          // the template to render into
          outlet: 'detail',       // the name of the outlet in that template
          controller: 'blogPost'  // the controller to use for the template
        });
      }
    });
    ```

    Remember that the controller's `content` will be the route's model. In
    this case, the default model will be `App.Post.find(params.post_id)`.

    @method render
    @param {String} name the name of the template to render
    @param {Object} options the options
  */
  render: function(name, options) {
    if (typeof name === 'object' && !options) {
      options = name;
      name = this.templateName;
    }

    name = name || this.templateName;

    var container = this.container,
        view = container.lookup('view:' + name),
        template = container.lookup('template:' + name);

    if (!view && !template) { return; }

    this.lastRenderedTemplate = name;

    options = normalizeOptions(this, name, template, options);
    view = setupView(view, container, options);

    appendView(this, view, options);
  }
});

function parentRoute(route) {
  var handlerInfos = route.router.router.currentHandlerInfos;

  var parent, current;

  for (var i=0, l=handlerInfos.length; i<l; i++) {
    current = handlerInfos[i].handler;
    if (current === route) { return parent; }
    parent = current;
  }
}

function parentTemplate(route) {
  var parent = parentRoute(route), template;

  if (!parent) { return; }

  if (template = parent.lastRenderedTemplate) {
    return template;
  } else {
    return parentTemplate(parent);
  }
}

function normalizeOptions(route, name, template, options) {
  options = options || {};
  options.into = options.into || parentTemplate(route);
  options.outlet = options.outlet || 'main';
  options.name = name;
  options.template = template;

  var controller = options.controller || route.templateName;

  if (typeof controller === 'string') {
    controller = route.container.lookup('controller:' + controller);
  }

  options.controller = controller;

  return options;
}

function setupView(view, container, options) {
  var defaultView = options.into ? 'view:default' : 'view:toplevel';

  view = view || container.lookup(defaultView);

  set(view, 'template', options.template);
  set(view, 'viewName', options.name);
  set(view, 'controller', options.controller);

  return view;
}

function appendView(route, view, options) {
  if (options.into) {
    var parentView = route.router._lookupActiveView(options.into);
    route.teardownView = teardownOutlet(parentView, options.outlet);
    parentView.connectOutlet(options.outlet, view);
  } else {
    var rootElement = get(route, 'router.namespace.rootElement');
    route.router._connectActiveView(options.name, view);
    route.teardownView = teardownTopLevel(view);
    view.appendTo(rootElement);
  }
}

function teardownTopLevel(view) {
  return function() { view.remove(); };
}

function teardownOutlet(parentView, outlet) {
  return function() { parentView.disconnectOutlet(outlet); };
}

function teardownView(route) {
  if (route.teardownView) { route.teardownView(); }

  delete route.teardownView;
  delete route.lastRenderedTemplate;
}
<commit_msg>properly deprecated Ember.Route.setupControllers() and Ember.Route.renderTemplates()<commit_after>var get = Ember.get, set = Ember.set,
    classify = Ember.String.classify,
    decamelize = Ember.String.decamelize;

Ember.Route = Ember.Object.extend({
  exit: function() {
    teardownView(this);
  },

  /**
    Transition into another route. Optionally supply a model for the
    route in question. The model will be serialized into the URL
    using the `serialize` hook.

    @method transitionTo
    @param {String} name the name of the route
    @param {...Object} models the
  */
  transitionTo: function() {
    this.transitioned = true;
    return this.router.transitionTo.apply(this.router, arguments);
  },

  send: function() {
    return this.router.send.apply(this.router, arguments);
  },

  /**
    @private

    This hook is the entry point for router.js

    @method setup
  */
  setup: function(context) {
    this.transitioned = false;
    this.redirect(context);

    if (this.transitioned) { return; }

    var controller = this.controllerFor(this.templateName, context);

    if (this.setupControllers) {
      Ember.deprecate("Ember.Route.setupControllers is deprecated. Please use Ember.Route.setupController(controller, model) instead.");
      this.setupControllers(controller, context);
    } else {
      this.setupController(controller, context);
    }

    if (this.renderTemplates) {
      Ember.deprecate("Ember.Route.renderTemplates is deprecated. Please use Ember.Route.renderTemplate(controller, model) instead.");
      this.renderTemplates(context);
    } else {
      this.renderTemplate(controller, context);
    }
  },

  /**
    A hook you can implement to optionally redirect to another route.

    If you call `this.transitionTo` from inside of this hook, this route
    will not be entered in favor of the other hook.

    @method redirect
    @param {Object} model the model for this route
  */
  redirect: Ember.K,

  /**
    @private

    The hook called by `router.js` to convert parameters into the context
    for this handler. The public Ember hook is `model`.

    @method deserialize
  */
  deserialize: function(params) {
    var model = this.model(params);
    return this.currentModel = model;
  },

  /**
    A hook you can implement to convert the URL into the model for
    this route.

    ```js
    App.Route.map(function(match) {
      match("/posts/:post_id").to("post");
    });
    ```

    The model for the `post` route is `App.Post.find(params.post_id)`.

    By default, if your route has a dynamic segment ending in `_id`:

    * The model class is determined from the segment (`post_id`'s
      class is `App.Post`)
    * The find method is called on the model class with the value of
      the dynamic segment.

    @method model
    @param {Object} params the parameters extracted from the URL
  */
  model: function(params) {
    var match, name, value;

    for (var prop in params) {
      if (match = prop.match(/^(.*)_id$/)) {
        name = match[1];
        value = params[prop];
      }
    }

    if (!name) { return; }

    var className = classify(name),
        namespace = this.router.namespace,
        modelClass = namespace[className];

    Ember.assert("You used the dynamic segment " + name + "_id in your router, but " + namespace + "." + className + " did not exist and you did not override your state's `model` hook.", modelClass);
    return modelClass.find(value);
  },

  /**
    A hook you can implement to convert the route's model into parameters
    for the URL.

    ```js
    App.Route.map(function(match) {
      match("/posts/:post_id").to("post");
    });

    App.PostRoute = Ember.Route.extend({
      model: function(params) {
        // the server returns `{ id: 12 }`
        return jQuery.getJSON("/posts/" + params.post_id);
      },

      serialize: function(model) {
        // this will make the URL `/posts/12`
        return { post_id: model.id };
      }
    });
    ```

    The default `serialize` method inserts the model's `id` into the
    route's dynamic segment (in this case, `:post_id`).

    This method is called when `transitionTo` is called with a context
    in order to populate the URL.

    @method serialize
    @param {Object} model the route's model
    @param {Array} params an Array of parameter names for the current
      route (in the example, `['post_id']`.
    @return {Object} the serialized parameters
  */
  serialize: function(model, params) {
    if (params.length !== 1) { return; }

    var name = params[0], object = {};
    object[name] = get(model, 'id');

    return object;
  },

  /**
    A hook you can use to setup the controller for the current route.

    This method is called with the controller for the current route and the
    model supplied by the `model` hook.

    ```js
    App.Route.map(function(match) {
      match("/posts/:post_id").to("post");
    });
    ```

    For the `post` route, the controller is `App.PostController`.

    By default, the `setupController` hook sets the `content` property of
    the controller to the `model`.

    If no explicit controller is defined, the route will automatically create
    an appropriate controller for the model:

    * if the model is an `Ember.Array` (including record arrays from Ember
      Data), the controller is an `Ember.ArrayController`.
    * otherwise, the controller is an `Ember.ObjectController`.

    This means that your template will get a proxy for the model as its
    context, and you can act as though the model itself was the context.

    @method setupController
  */
  setupController: function(controller, model) {
    if (controller) {
      controller.set('content', model);
    }
  },

  /**
    Returns the controller for a particular route.

    ```js
    App.PostRoute = Ember.Route.extend({
      setupController: function(controller, post) {
        this._super(controller, post);
        this.controllerFor('posts').set('currentPost', post);
      }
    });
    ```

    By default, the controller for `post` is the shared instance of
    `App.PostController`.

    @method controllerFor
    @param {String} name the name of the route
    @param {Object} model the model associated with the route (optional)
    @return {Ember.Controller}
  */
  controllerFor: function(name, model) {
    var container = this.router.container,
        controller = container.lookup('controller:' + name);

    if (!controller) {
      model = model || this.modelFor(name);
      controller = Ember.generateController(container, name, model);
    }

    return controller;
  },

  /**
    Returns the current model for a given route.

    This is the object returned by the `model` hook of the route
    in question.

    @method modelFor
    @param {String} name the name of the route
    @return {Object} the model object
  */
  modelFor: function(name) {
    return this.container.lookup('route:' + name).currentModel;
  },

  /**
    A hook you can use to render the template for the current route.

    This method is called with the controller for the current route and the
    model supplied by the `model` hook. By default, it renders the route's
    template, configured with the controller for the route.

    This method can be overridden to set up and render additional or
    alternative templates.

    @method renderTemplate
    @param {Object} controller the route's controller
    @param {Object} model the route's model
  */
  renderTemplate: function(controller, model) {
    this.render();
  },

  /**
    Renders a template into an outlet.

    This method has a number of defaults, based on the name of the
    route specified in the router.

    For example:

    ```js
    App.Router.map(function(match) {
      match("/").to("index");
      match("/posts/:post_id").to("post");
    });

    App.PostRoute = App.Route.extend({
      renderTemplate: function() {
        this.render();
      }
    });
    ```

    The name of the `PostRoute`, as defined by the router, is `post`.

    By default, render will:

    * render the `post` template
    * with the `post` view (`PostView`) for event handling, if one exists
    * and the `post` controller (`PostController`), if one exists
    * into the `main` outlet of the `application` template

    You can override this behavior:

    ```js
    App.PostRoute = App.Route.extend({
      renderTemplate: function() {
        this.render('myPost', {   // the template to render
          into: 'index',          // the template to render into
          outlet: 'detail',       // the name of the outlet in that template
          controller: 'blogPost'  // the controller to use for the template
        });
      }
    });
    ```

    Remember that the controller's `content` will be the route's model. In
    this case, the default model will be `App.Post.find(params.post_id)`.

    @method render
    @param {String} name the name of the template to render
    @param {Object} options the options
  */
  render: function(name, options) {
    if (typeof name === 'object' && !options) {
      options = name;
      name = this.templateName;
    }

    name = name || this.templateName;

    var container = this.container,
        view = container.lookup('view:' + name),
        template = container.lookup('template:' + name);

    if (!view && !template) { return; }

    this.lastRenderedTemplate = name;

    options = normalizeOptions(this, name, template, options);
    view = setupView(view, container, options);

    appendView(this, view, options);
  }
});

function parentRoute(route) {
  var handlerInfos = route.router.router.currentHandlerInfos;

  var parent, current;

  for (var i=0, l=handlerInfos.length; i<l; i++) {
    current = handlerInfos[i].handler;
    if (current === route) { return parent; }
    parent = current;
  }
}

function parentTemplate(route) {
  var parent = parentRoute(route), template;

  if (!parent) { return; }

  if (template = parent.lastRenderedTemplate) {
    return template;
  } else {
    return parentTemplate(parent);
  }
}

function normalizeOptions(route, name, template, options) {
  options = options || {};
  options.into = options.into || parentTemplate(route);
  options.outlet = options.outlet || 'main';
  options.name = name;
  options.template = template;

  var controller = options.controller || route.templateName;

  if (typeof controller === 'string') {
    controller = route.container.lookup('controller:' + controller);
  }

  options.controller = controller;

  return options;
}

function setupView(view, container, options) {
  var defaultView = options.into ? 'view:default' : 'view:toplevel';

  view = view || container.lookup(defaultView);

  set(view, 'template', options.template);
  set(view, 'viewName', options.name);
  set(view, 'controller', options.controller);

  return view;
}

function appendView(route, view, options) {
  if (options.into) {
    var parentView = route.router._lookupActiveView(options.into);
    route.teardownView = teardownOutlet(parentView, options.outlet);
    parentView.connectOutlet(options.outlet, view);
  } else {
    var rootElement = get(route, 'router.namespace.rootElement');
    route.router._connectActiveView(options.name, view);
    route.teardownView = teardownTopLevel(view);
    view.appendTo(rootElement);
  }
}

function teardownTopLevel(view) {
  return function() { view.remove(); };
}

function teardownOutlet(parentView, outlet) {
  return function() { parentView.disconnectOutlet(outlet); };
}

function teardownView(route) {
  if (route.teardownView) { route.teardownView(); }

  delete route.teardownView;
  delete route.lastRenderedTemplate;
}
<|endoftext|>


<commit_before>// @flow

/**
 *  cancelEvent - Cancel Events so we dont bubble up our events to the document
 *
 *  @param { Object } event
 *  @return { Void }
 **/
export const cancelEvent = (e: Event): void => {
  e.stopPropagation();
  e.preventDefault();
};

 /**
  * Returns the touches of an event relative to the container offset
  * @param event
  * @return array touches
  */
export const getTouches = (touche: TouchEvent, container) => {
  // const {left, top} = container.offset();
  return touches.map(touch => ({
    x: touch.pageX - 0, // left,
    y: touch.pageY - 0, // top
  }));
};

 /**
  * calcDist - Calculate the distance between our fingers
  *
  * @param { Array } touches touches passas an array from TouchList
  * @return { Number } the calcualted distance between the fingers
  **/
export const calcDist = (touches: Array<Object>): number => {
  const [first, second] = touches;
  return Math.sqrt(
    ((first.x - second.x) * (first.x - second.x)) +
    ((first.y - second.y) * (first.y - second.y))
  );
};
<commit_msg>fixes argument name error<commit_after>// @flow

/**
 *  cancelEvent - Cancel Events so we dont bubble up our events to the document
 *
 *  @param { Object } event
 *  @return { Void }
 **/
export const cancelEvent = (e: Event): void => {
  e.stopPropagation();
  e.preventDefault();
};

 /**
  * Returns the touches of an event relative to the container offset
  * @param event
  * @return array touches
  */
export const getTouches = (touches: TouchEvent, container) => {
  // const {left, top} = container.offset();
  return touches.map(touch => ({
    x: touch.pageX - 0, // left,
    y: touch.pageY - 0, // top
  }));
};

 /**
  * calcDist - Calculate the distance between our fingers
  *
  * @param { Array } touches touches passas an array from TouchList
  * @return { Number } the calcualted distance between the fingers
  **/
export const calcDist = (touches: Array<Object>): number => {
  const [first, second] = touches;
  return Math.sqrt(
    ((first.x - second.x) * (first.x - second.x)) +
    ((first.y - second.y) * (first.y - second.y))
  );
};
<|endoftext|>


<commit_before>import mapValues from 'lodash/mapValues'
import isArray from 'lodash/isArray'

/**
 *
 * Calls all reactcards Component tests for mocha/jasmine cli tests
 *
 * resolveTests calls all component tests instead of having to manually execute all of them
 *
 * Import all Component tests and resolveTests will run all functions.
 *
 *
 *     import resolveTests from '../../src/utils/resolveTests'
 *     import * as advanced from './advanced'
 *
 *     resolveTests([advanced])
 *
 *
 * @param {Array} testComponents
 * @returns {boolean}
 */
const resolveTests = testComponents => {
    if (!isArray(testComponents)) {
        return false
    }
    mapValues(testComponents, testComponent => mapValues(testComponent, fn => fn()))
}

export default resolveTests
<commit_msg>Minor change.<commit_after>import forEach from 'lodash/forEach'
import isArray from 'lodash/isArray'

/**
 *
 * Calls all reactcards Component tests for mocha/jasmine cli tests
 *
 * resolveTests calls all component tests instead of having to manually execute all of them
 *
 * Import all Component tests and resolveTests will run all functions.
 *
 *
 *     import resolveTests from '../../src/utils/resolveTests'
 *     import * as advanced from './advanced'
 *
 *     resolveTests([advanced])
 *
 *
 * @param {Array} testComponents
 * @returns {boolean}
 */
const resolveTests = testComponents => {
    if (!isArray(testComponents)) {
        return false
    }
    forEach(testComponents, testComponent => forEach(testComponent, fn => fn()))
}

export default resolveTests
<|endoftext|>