<commit_before>import program from 'commander'
import { dirname, relative, basename as base, resolve } from 'path'
import { read as readPkg, find as resolvePkg } from './util/pkg'
import { find, slurp, put } from './util/file'
import stdio from './util/stdio'
import { default as jsc } from './builder/javascript'
import { default as cssc } from './builder/css'
import { default as copyFiles } from './builder/copy-files'
import { default as createPipeline } from './pipeline'
import { default as jso } from './postbuild/javascript'
import { default as csso } from './postbuild/css'
import { red, yellow } from 'ansicolors'
import { watch } from 'chokidar'
import { timed } from './util/performance'
import './util/cli'

const keys = Object.keys
const all = Promise.all.bind(Promise)

main()

async function main() {
  const pkgFile = resolvePkg(module, process.cwd())
      , pkgRoot = dirname(pkgFile)

  let pkg = await readPkg(pkgFile)

  pkg.root = pkgRoot
  pkg.resolve = (path) => relative(process.cwd(), resolve(pkgRoot, path))
  pkg.relative = (path) => relative(pkgRoot, resolve(pkgRoot, path))

  pkg.directories || (pkg.directories = {})

  let alwaysExclude =
    [ `node_modules`
    , `package.json`
    , `.*`
    , `*-min.js`
    , `*-min.js.map`
    , `*-min.css`
    , `*-min.css.map`
    , `*-debug.log`
    , `optimised-modules.json`
    , `dependencies.json`
    ]

  const defaults =
    { out: pkg.relative(`${pkg.name.split('/').pop()}-min`)
    , lib: pkg.relative(pkg.directories.lib || 'lib')
    , src: pkg.relative(pkg.directories.src || 'src')
    , optimize: 0
    , copy: true
    , debug: true
    , interactive: false
    , production: false
    , include: ['js:**/*.js', 'css:**/*.css']
    , exclude: [...alwaysExclude]
    , log: 'normal'
    , flags: ['add-module-exports:false']
    }

  const cli = program
    .version(pkg.version)
    .option('-i, --src <dir>', `the root directory from which all sources are relative [${defaults.src}]`, pkg.relative, defaults.src)
    .option('-o, --out <prefix>', `write optimized output to files with the specified prefix [${defaults.out}]`, pkg.relative, defaults.out)
    .option('-L, --lib <dir>', `write unoptimized files to the specified directory [${defaults.lib}]`, pkg.relative, defaults.lib)
    .option('-I, --include [js|css:]<path>', `include a path or glob (relative to source root) [${defaults.include}]`, concat, [])
    .option('-X, --exclude [js|css:]<path>', `exclude a path or glob (relative to source root) [${defaults.exclude}]`, concat, [])
    .option('-O, --optimize <level>', `optimization level (0 = none) [${defaults.optimize}]`, setOptimization, defaults.optimize)
    .option('--no-copy', `disable copying of non-code files to ${defaults.lib}`, Boolean, !defaults.copy)
    .option('--no-debug', 'disable source map generation', Boolean, !defaults.debug)
    .option('--log <normal|json>', `log output format [${defaults.log}]`, /^(json|normal)$/i, defaults.log)
    .option('--interactive', `watch for and recompile on changes (implies -O 0)`)
    .option('--production', `enable production options (implies -O 1)`)
    .option('--flags <flags>', `toggle flags [${defaults.flags}]`, concat, [])

  const opts = cli.parse(process.argv)
  const console = stdio({ debug: !!process.env.DEBUG, format: opts.log })

  const pipeline =
    { js: createPipeline(pkg, opts, jsc(pkg, opts))
    , css: createPipeline(pkg, opts, cssc(pkg, opts))
    }

  if (opts.copy) {
    pipeline['copy-files'] = createPipeline(pkg, opts, copyFiles(pkg, opts))
  }

  opts.include = conclude(keys(pipeline), defaults.include, opts.include)
  opts.exclude = conclude(keys(pipeline), defaults.exclude, opts.exclude)
  opts.flags = flag(keys(defaults.flags), defaults.flags, opts.flags)

  opts.include['copy-files'] = ['**/*']
  opts.exclude['copy-files'] = [...opts.include.js, ...opts.include.css, ...opts.exclude['*']]

  opts.optimize
    = opts.production?  1
    : opts.interactive? 0
    : opts.optimize

  opts.interactive = opts.production? false : opts.interactive

  console.debug('Options:')
  keys(defaults).forEach(name => console.debug(`- ${name}: ${JSON.stringify(opts[name])}`))

  const build = await timed(
    keys(pipeline).reduce(
      async (result, type) => {
        result = await result
        let input = await collect(opts.include[type], opts.exclude[type])
        result[type] = await execute(type, pipeline[type], ...input)
        return result
      }
    , {})
  )

  console.debug(`Build took ${build.duration.ms} ms`)

  if (opts.interactive) {
    keys(pipeline).forEach(type => {
      console.debug(`Watching ${type} pipeline:`)
      console.debug(`- included: ${opts.include[type]}`)
      console.debug(`- excluded: ${opts.exclude[type]}`)
      interactive(opts.include[type], opts.exclude[type])
        .on('add', async file => await execute(type, pipeline[type], file))
        .on('change', async file => await execute(type, pipeline[type], file))
    })
    console.info('Watching source files for changes...')
  } else if (opts.optimize) {
    console.debug('Writing optimised-modules.json')
    const extension = /^([^\.]+).*$/
    const winslash = /\\/g

    await put(pkg.resolve('optimised-modules.json'), JSON.stringify(
      new Set(
        keys(build.result).reduce((files, type) => {
          let pipe = build.result[type]
          return pipe.reduce((files, result) => {
            if (result.files) {
              return [...files, ...result.files.map(file => {
                const name = file.replace(extension, '$1').replace(winslash, '/')
                return `${pkg.name}/${name}`
              })]
            } else {
              return files
            }
          }, files)
        }, [])
      )
      , null, 2
    ))

    if (build.result.css.length) {
      console.debug(`Writing ${opts.out}.css`)
      let filename = pkg.resolve(`${opts.out}.css`)
      let contents = await csso(pkg, opts)(build.result.css)
      await put(filename, contents)
    }

    if (build.result.js.length) {
      console.debug(`Writing ${opts.out}.js`)
      let filename = pkg.resolve(`${opts.out}.js`)
      let contents = await jso(pkg, opts)(build.result.js)
      await put(filename, contents)
    }
  }

  async function collect(include, exclude) {
    let collection = []

    for (let pattern of include) {
      let files = await find(`${opts.src}/${pattern}`, { nodir: true, ignore: exclude, cwd: pkg.root })
      collection = [...collection, ...files]
    }

    return collection
  }

  function interactive(include, exclude) {
    let watcher = watch(include.reduce((files, pattern) => {
      return files.concat(`${opts.src}/${pattern}`)
    }, []), { ignored: exclude, cwd: pkg.root, ignoreInitial: true })

    return watcher
  }

  async function execute(type, pipeline, ...input) {
    let result = await all(pipeline(...input))
    await status(type, ...result)
    return result
  }

  async function status(type, ...results) {
    for (let result of results) {
      let { input, messages, files, error } = await result

      if (messages) {
        [...messages].forEach(message => {
          console.warn(yellow(`\n${type} – ${input}: ${message}`))
        })
      }

      if (error) {
        console.error(`\n${type} – ${red(error.message)}\n${error.codeFrame || error.stack}\n`)
      } else {
        console.log(`${type} – ${input} -> ${files}`)
      }
    }
  }
}

function setOptimization(level) {
  return Math.max(level | 0, 0)
}

function concat(val, list) {
  return list.concat(val.split(','))
}

function flag(flags, defaults, opts) {
  return Object.assign
    ( [... new Set(defaults)].reduce(parse, {})
    , [... new Set(opts)].reduce(parse, {})
    )

  function parse(flags, val) {
    let [flag, setting] = val.split(':')

    try {
      flags[flag] = JSON.parse(setting)
    } catch (e) {
      flags[flag] = setting
    }

    return flags
  }
}

function conclude(types, defaults, opts) {
  return Object.assign
    ( [... new Set(defaults)].reduce(parse, {})
    , [... new Set(opts)].reduce(parse, {})
    )

  function parse(pipe, val) {
    let [lines, pattern] = val.split(':')

    if (pattern) {
      lines = [lines]
    } else {
      pattern = lines
      lines = ['*', ...types]
    }

    lines.forEach(line => {
      pipe[line] = (pipe[line] || []).concat(pattern)
    })

    return pipe
  }
}
<commit_msg>Make sure --version returns ez-build version number<commit_after>import program from 'commander'
import { dirname, relative, basename as base, resolve } from 'path'
import { read as readPkg, find as resolvePkg } from './util/pkg'
import { find, slurp, put } from './util/file'
import stdio from './util/stdio'
import { default as jsc } from './builder/javascript'
import { default as cssc } from './builder/css'
import { default as copyFiles } from './builder/copy-files'
import { default as createPipeline } from './pipeline'
import { default as jso } from './postbuild/javascript'
import { default as csso } from './postbuild/css'
import { red, yellow } from 'ansicolors'
import { watch } from 'chokidar'
import { timed } from './util/performance'
import './util/cli'

const keys = Object.keys
const all = Promise.all.bind(Promise)

main()

async function main() {
  const pkgFile = resolvePkg(module, process.cwd())
      , pkgRoot = dirname(pkgFile)

  let pkg = await readPkg(pkgFile)

  pkg.root = pkgRoot
  pkg.resolve = (path) => relative(process.cwd(), resolve(pkgRoot, path))
  pkg.relative = (path) => relative(pkgRoot, resolve(pkgRoot, path))

  pkg.directories || (pkg.directories = {})

  let alwaysExclude =
    [ `node_modules`
    , `package.json`
    , `.*`
    , `*-min.js`
    , `*-min.js.map`
    , `*-min.css`
    , `*-min.css.map`
    , `*-debug.log`
    , `optimised-modules.json`
    , `dependencies.json`
    ]

  const defaults =
    { out: pkg.relative(`${pkg.name.split('/').pop()}-min`)
    , lib: pkg.relative(pkg.directories.lib || 'lib')
    , src: pkg.relative(pkg.directories.src || 'src')
    , optimize: 0
    , copy: true
    , debug: true
    , interactive: false
    , production: false
    , include: ['js:**/*.js', 'css:**/*.css']
    , exclude: [...alwaysExclude]
    , log: 'normal'
    , flags: ['add-module-exports:false']
    }

  const ezbuild = await readPkg(require.resolve('../package.json'))

  const cli = program
    .version(ezbuild.version)
    .option('-i, --src <dir>', `the root directory from which all sources are relative [${defaults.src}]`, pkg.relative, defaults.src)
    .option('-o, --out <prefix>', `write optimized output to files with the specified prefix [${defaults.out}]`, pkg.relative, defaults.out)
    .option('-L, --lib <dir>', `write unoptimized files to the specified directory [${defaults.lib}]`, pkg.relative, defaults.lib)
    .option('-I, --include [js|css:]<path>', `include a path or glob (relative to source root) [${defaults.include}]`, concat, [])
    .option('-X, --exclude [js|css:]<path>', `exclude a path or glob (relative to source root) [${defaults.exclude}]`, concat, [])
    .option('-O, --optimize <level>', `optimization level (0 = none) [${defaults.optimize}]`, setOptimization, defaults.optimize)
    .option('--no-copy', `disable copying of non-code files to ${defaults.lib}`, Boolean, !defaults.copy)
    .option('--no-debug', 'disable source map generation', Boolean, !defaults.debug)
    .option('--log <normal|json>', `log output format [${defaults.log}]`, /^(json|normal)$/i, defaults.log)
    .option('--interactive', `watch for and recompile on changes (implies -O 0)`)
    .option('--production', `enable production options (implies -O 1)`)
    .option('--flags <flags>', `toggle flags [${defaults.flags}]`, concat, [])

  const opts = cli.parse(process.argv)
  const console = stdio({ debug: !!process.env.DEBUG, format: opts.log })

  const pipeline =
    { js: createPipeline(pkg, opts, jsc(pkg, opts))
    , css: createPipeline(pkg, opts, cssc(pkg, opts))
    }

  if (opts.copy) {
    pipeline['copy-files'] = createPipeline(pkg, opts, copyFiles(pkg, opts))
  }

  opts.include = conclude(keys(pipeline), defaults.include, opts.include)
  opts.exclude = conclude(keys(pipeline), defaults.exclude, opts.exclude)
  opts.flags = flag(keys(defaults.flags), defaults.flags, opts.flags)

  opts.include['copy-files'] = ['**/*']
  opts.exclude['copy-files'] = [...opts.include.js, ...opts.include.css, ...opts.exclude['*']]

  opts.optimize
    = opts.production?  1
    : opts.interactive? 0
    : opts.optimize

  opts.interactive = opts.production? false : opts.interactive

  console.debug('Options:')
  keys(defaults).forEach(name => console.debug(`- ${name}: ${JSON.stringify(opts[name])}`))

  const build = await timed(
    keys(pipeline).reduce(
      async (result, type) => {
        result = await result
        let input = await collect(opts.include[type], opts.exclude[type])
        result[type] = await execute(type, pipeline[type], ...input)
        return result
      }
    , {})
  )

  console.debug(`Build took ${build.duration.ms} ms`)

  if (opts.interactive) {
    keys(pipeline).forEach(type => {
      console.debug(`Watching ${type} pipeline:`)
      console.debug(`- included: ${opts.include[type]}`)
      console.debug(`- excluded: ${opts.exclude[type]}`)
      interactive(opts.include[type], opts.exclude[type])
        .on('add', async file => await execute(type, pipeline[type], file))
        .on('change', async file => await execute(type, pipeline[type], file))
    })
    console.info('Watching source files for changes...')
  } else if (opts.optimize) {
    console.debug('Writing optimised-modules.json')
    const extension = /^([^\.]+).*$/
    const winslash = /\\/g

    await put(pkg.resolve('optimised-modules.json'), JSON.stringify(
      new Set(
        keys(build.result).reduce((files, type) => {
          let pipe = build.result[type]
          return pipe.reduce((files, result) => {
            if (result.files) {
              return [...files, ...result.files.map(file => {
                const name = file.replace(extension, '$1').replace(winslash, '/')
                return `${pkg.name}/${name}`
              })]
            } else {
              return files
            }
          }, files)
        }, [])
      )
      , null, 2
    ))

    if (build.result.css.length) {
      console.debug(`Writing ${opts.out}.css`)
      let filename = pkg.resolve(`${opts.out}.css`)
      let contents = await csso(pkg, opts)(build.result.css)
      await put(filename, contents)
    }

    if (build.result.js.length) {
      console.debug(`Writing ${opts.out}.js`)
      let filename = pkg.resolve(`${opts.out}.js`)
      let contents = await jso(pkg, opts)(build.result.js)
      await put(filename, contents)
    }
  }

  async function collect(include, exclude) {
    let collection = []

    for (let pattern of include) {
      let files = await find(`${opts.src}/${pattern}`, { nodir: true, ignore: exclude, cwd: pkg.root })
      collection = [...collection, ...files]
    }

    return collection
  }

  function interactive(include, exclude) {
    let watcher = watch(include.reduce((files, pattern) => {
      return files.concat(`${opts.src}/${pattern}`)
    }, []), { ignored: exclude, cwd: pkg.root, ignoreInitial: true })

    return watcher
  }

  async function execute(type, pipeline, ...input) {
    let result = await all(pipeline(...input))
    await status(type, ...result)
    return result
  }

  async function status(type, ...results) {
    for (let result of results) {
      let { input, messages, files, error } = await result

      if (messages) {
        [...messages].forEach(message => {
          console.warn(yellow(`\n${type} – ${input}: ${message}`))
        })
      }

      if (error) {
        console.error(`\n${type} – ${red(error.message)}\n${error.codeFrame || error.stack}\n`)
      } else {
        console.log(`${type} – ${input} -> ${files}`)
      }
    }
  }
}

function setOptimization(level) {
  return Math.max(level | 0, 0)
}

function concat(val, list) {
  return list.concat(val.split(','))
}

function flag(flags, defaults, opts) {
  return Object.assign
    ( [... new Set(defaults)].reduce(parse, {})
    , [... new Set(opts)].reduce(parse, {})
    )

  function parse(flags, val) {
    let [flag, setting] = val.split(':')

    try {
      flags[flag] = JSON.parse(setting)
    } catch (e) {
      flags[flag] = setting
    }

    return flags
  }
}

function conclude(types, defaults, opts) {
  return Object.assign
    ( [... new Set(defaults)].reduce(parse, {})
    , [... new Set(opts)].reduce(parse, {})
    )

  function parse(pipe, val) {
    let [lines, pattern] = val.split(':')

    if (pattern) {
      lines = [lines]
    } else {
      pattern = lines
      lines = ['*', ...types]
    }

    lines.forEach(line => {
      pipe[line] = (pipe[line] || []).concat(pattern)
    })

    return pipe
  }
}
<|endoftext|>


<commit_before>'use strict';

/* eslint-disable no-process-exit */

const util = require('util');
const Cli = require('./Cli');
const CliError = require('./CliError');
const cli = new Cli(process.argv.slice(1), process.stdin, process.stdout, process.stderr);

cli.on('error', (err) => {
	const message = err.message || err.stack;

	if (cli.options.verbose) {
		process.stderr.write((err.stack || (err.name + ': ' + message)) + '\n');
	} else {
		process.stderr.write(err.name + ': ' + message + '\n');
	}

	process.exit(1);
});

cli.on('warning', (err) => {
	process.stderr.write(err.message + '\n');
});

try {
	cli.run();

} catch (err) {
	if (err instanceof CliError) {
		process.stderr.write(err.message);
		process.exit(err.code);
	} else {
		process.stderr.write(util.inspect(err));
		process.exit(254);
	}
}
<commit_msg>Fixed stacktrace<commit_after>'use strict';

/* eslint-disable no-process-exit */

const util = require('util');
const Cli = require('./Cli');
const CliError = require('./CliError');
var cli;

const errHandler = (err) => {
	const message = err.message || err.stack;

	if (cli && cli.options.verbose) {
		process.stderr.write((err.stack || (err.name + ': ' + message)) + '\n');
	} else {
		process.stderr.write(message + '\n');
	}

	process.exit(1);
};

try {
	cli = new Cli(process.argv.slice(1), process.stdin, process.stdout, process.stderr);
} catch (err) {
	errHandler(err);
}

cli.on('error', errHandler);

cli.on('warning', (err) => {
	process.stderr.write(err.message + '\n');
});

try {
	cli.run();

} catch (err) {
	if (err instanceof CliError) {
		process.stderr.write(err.message);
		process.exit(err.code);
	} else {
		process.stderr.write(util.inspect(err));
		process.exit(254);
	}
}
<|endoftext|>


<commit_before>var ds18b20 = require('ds18b20');
var crontab = require('node-crontab');
var config =  require('../config.json');
var logger =  require('./logger.js');

function recordTemperature(){
    ds18b20.sensors(function(err, ids) {
        for(index in ids){
            ds18b20.temperature(ids[index], function(err, value) {
                logger.log(value);
            });
        }
    });
}

var jobId = crontab.scheduleJob(config.schedule, recordTemperature);
console.log('CronJob scheduled: '+ jobId);
recordTemperature();<commit_msg>Method to set up sensors and store them in global variable<commit_after>var ds18b20 = require('ds18b20');
var crontab = require('node-crontab');
var config =  require('../config.json');
var logger =  require('./logger.js');

function recordTemperature(){
    ds18b20.sensors(function(err, ids) {
        for(index in ids){
            ds18b20.temperature(ids[index], function(err, value) {
var sensors = [];
                logger.log(value);
            });
        }
    });
}
function setupSensors() {
    var promise = new Promise(function (resolve, reject) {
        var tmpSensors;
        var response;

        tmpSensors = [];
        ds18b20.sensors(function(err, ids) {
            for(index in ids){
                tmpSensors.push(ids[index]);
                console.log(ids[index]);
            }
            console.log('Are all sensors accounted for? [y/n] ');
            prompt.start();
            prompt.get(['inputResponse'], function (err, result) {
                if (result.inputResponse.toLowerCase() == 'y') {
                    resolve(tmpSensors);
                } else {
                    reject('Please reconnect sensors and retry.');
                }
            });
        });
    });

    return promise;
};

var jobId = crontab.scheduleJob(config.schedule, recordTemperature);
console.log('CronJob scheduled: '+ jobId);
recordTemperature();<|endoftext|>


<commit_before>var enableRender = true;
var matchesTabUrl = chrome.runtime.getManifest().content_scripts[0].matches;

chrome.contextMenus.create({
  "title":"Render selection",
  "contexts":["selection"], "onclick":function (info, tab) {
    var funcToInject = function () {
      var selection = window.getSelection();
      return (selection.rangeCount > 0) ? selection.toString() : '';
    };
    var jsCodeStr = ';(' + funcToInject + ')();';
    chrome.tabs.executeScript({
      code:jsCodeStr,
      allFrames:true
    }, function (selectedTextPerFrame) {
      if (chrome.runtime.lastError) {
        console.log('error:' + chrome.runtime.lastError.message);
      } else if ((selectedTextPerFrame.length > 0) && (typeof(selectedTextPerFrame[0]) === 'string')) {
        var selectedText = selectedTextPerFrame[0];
        chrome.tabs.create({
          'url':chrome.extension.getURL("html/inject.html"),
          'active':true
        }, function (tab) {
          var selfTabId = tab.id;
          chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
            if (changeInfo.status == "complete" && tabId == selfTabId) {
              var tabs = chrome.extension.getViews({type:"tab"});
              // Get the latest tab opened
              tabs[tabs.length - 1].inject(selectedText);
            }
          });
        });
      }
    });
  }
});

function refreshTab(tab) {
  var code = 'window.location.reload();';
  chrome.tabs.executeScript(tab.id, {code:code});
}

function enableDisableRender() {
  // Save the status of the extension
  chrome.storage.local.set({'ENABLE_RENDER':enableRender});

  // Update the extension icon
  var iconPath = enableRender ? "img/enabled.png" : "img/disabled.png";
  chrome.browserAction.setIcon({path:iconPath});

  // Switch enabled <> disabled
  enableRender = !enableRender;

  // Reload the active tab in the current windows that matches
  var tabFound = false;
  for (var i = 0; i < matchesTabUrl.length; i++) {
    var matchTabUrl = matchesTabUrl[i];
    chrome.tabs.query({active:true, currentWindow:true, url:matchTabUrl}, function (tabs) {
      if (!tabFound && tabs.length > 0) {
        refreshTab(tabs[0]);
        tabFound = true;
      }
    });
  }
}

function refreshOptions() {
  chrome.storage.local.set({
    'CUSTOM_ATTRIBUTES':localStorage['CUSTOM_ATTRIBUTES'],
    'SAFE_MODE':localStorage['SAFE_MODE'],
    'ALLOW_TXT_EXTENSION':localStorage['ALLOW_TXT_EXTENSION'],
    'THEME':localStorage['THEME'],
    'JS':localStorage['JS'],
    'JS_LOAD':localStorage['JS_LOAD']
  });
  var customThemeNames = JSON.parse(localStorage['CUSTOM_THEME_NAMES'] || '[]');
  if (customThemeNames.length > 0) {
    for (var i in customThemeNames) {
      var themeName = customThemeNames[i];
      var themeNameKey = 'CUSTOM_THEME_' + themeName;
      var themeObj = {};
      themeObj[themeNameKey] = localStorage[themeNameKey];
      chrome.storage.local.set(themeObj);
    }
  }
  var customJavaScriptNames = JSON.parse(localStorage['CUSTOM_JS_NAMES'] || '[]');
    if (customJavaScriptNames.length > 0) {
      for (var j in customJavaScriptNames) {
        var javaScriptName = customJavaScriptNames[j];
        var javaScriptNameKey = 'CUSTOM_JS_' + javaScriptName;
        var javaScriptObj = {};
        javaScriptObj[javaScriptNameKey] = localStorage[javaScriptNameKey];
        chrome.storage.local.set(javaScriptObj);
      }
    }
}

chrome.browserAction.onClicked.addListener(enableDisableRender);
enableDisableRender();
<commit_msg>Replace executeScript with reload<commit_after>var enableRender = true;
var matchesTabUrl = chrome.runtime.getManifest().content_scripts[0].matches;

chrome.contextMenus.create({
  "title":"Render selection",
  "contexts":["selection"], "onclick":function (info, tab) {
    var funcToInject = function () {
      var selection = window.getSelection();
      return (selection.rangeCount > 0) ? selection.toString() : '';
    };
    var jsCodeStr = ';(' + funcToInject + ')();';
    chrome.tabs.executeScript({
      code:jsCodeStr,
      allFrames:true
    }, function (selectedTextPerFrame) {
      if (chrome.runtime.lastError) {
        console.log('error:' + chrome.runtime.lastError.message);
      } else if ((selectedTextPerFrame.length > 0) && (typeof(selectedTextPerFrame[0]) === 'string')) {
        var selectedText = selectedTextPerFrame[0];
        chrome.tabs.create({
          'url':chrome.extension.getURL("html/inject.html"),
          'active':true
        }, function (tab) {
          var selfTabId = tab.id;
          chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
            if (changeInfo.status == "complete" && tabId == selfTabId) {
              var tabs = chrome.extension.getViews({type:"tab"});
              // Get the latest tab opened
              tabs[tabs.length - 1].inject(selectedText);
            }
          });
        });
      }
    });
  }
});

function refreshTab(tab) {
  chrome.tabs.reload(tab.id);
}

function reloadTab(tab) {
  chrome.tabs.reload(tab.id);
}

function findActiveTab(callback) {
  var tabFound = false;
  for (var i = 0; i < matchesTabUrl.length; i++) {
    var matchTabUrl = matchesTabUrl[i];
    chrome.tabs.query({active: true, currentWindow: true, url: matchTabUrl}, function (tabs) {
      if (!tabFound && tabs.length > 0) {
        callback(tabs[0]);
        tabFound = true;
      }
    });
  }
}

function enableDisableRender() {
  // Save the status of the extension
  chrome.storage.local.set({'ENABLE_RENDER': enableRender});

  // Update the extension icon
  var iconPath = enableRender ? "img/enabled.png" : "img/disabled.png";
  chrome.browserAction.setIcon({path: iconPath});

  // Reload the active tab in the current windows that matches
  if (enableRender) {
    findActiveTab(function (activeTab) {
      refreshTab(activeTab);
    });
  } else {
    findActiveTab(function (activeTab) {
      reloadTab(activeTab);
    });
  }

  // Switch the flag
  enableRender = !enableRender;
}

function refreshOptions() {
  chrome.storage.local.set({
    'CUSTOM_ATTRIBUTES':localStorage['CUSTOM_ATTRIBUTES'],
    'SAFE_MODE':localStorage['SAFE_MODE'],
    'ALLOW_TXT_EXTENSION':localStorage['ALLOW_TXT_EXTENSION'],
    'THEME':localStorage['THEME'],
    'JS':localStorage['JS'],
    'JS_LOAD':localStorage['JS_LOAD']
  });
  var customThemeNames = JSON.parse(localStorage['CUSTOM_THEME_NAMES'] || '[]');
  if (customThemeNames.length > 0) {
    for (var i in customThemeNames) {
      var themeName = customThemeNames[i];
      var themeNameKey = 'CUSTOM_THEME_' + themeName;
      var themeObj = {};
      themeObj[themeNameKey] = localStorage[themeNameKey];
      chrome.storage.local.set(themeObj);
    }
  }
  var customJavaScriptNames = JSON.parse(localStorage['CUSTOM_JS_NAMES'] || '[]');
    if (customJavaScriptNames.length > 0) {
      for (var j in customJavaScriptNames) {
        var javaScriptName = customJavaScriptNames[j];
        var javaScriptNameKey = 'CUSTOM_JS_' + javaScriptName;
        var javaScriptObj = {};
        javaScriptObj[javaScriptNameKey] = localStorage[javaScriptNameKey];
        chrome.storage.local.set(javaScriptObj);
      }
    }
}

chrome.browserAction.onClicked.addListener(enableDisableRender);
enableDisableRender();
<|endoftext|>


<commit_before>import program from 'commander'
import readPkg from 'read-package-json'
import { sync as find } from 'glob'
import { find as resolvePkg } from 'pkginfo'
import { dirname, relative, basename as base, resolve, normalize, delimiter, extname as ext, join } from 'path'
import { execSync as exec } from 'child_process'
import { optimize } from 'requirejs'
import { default as put } from 'output-file-sync'
import { readFileSync as slurp } from 'fs'
import stdio from './util/stdio'
import { parallel, apply } from 'async'
import { default as jsc } from './builder/javascript'
import { default as cssc } from './builder/css'
import { default as copyFiles } from './builder/copy-files'
import { default as createPipeline } from './pipeline'
import { red, yellow } from 'ansicolors'
import { watch } from 'chokidar'
import rebaseProdCss from './rebase-prod-css'

const keys = Object.keys

const pkgFile = resolvePkg(module, process.cwd())
    , pkgRoot = dirname(pkgFile)

readPkg(pkgFile, (err, pkg) => {
  if (err) {
    console.error(err.message)
    process.exit(1)
  }

  pkg.root = pkgRoot
  pkg.resolve = (path) => relative(process.cwd(), resolve(pkgRoot, path))
  pkg.relative = (path) => relative(pkgRoot, resolve(pkgRoot, path))

  pkg.directories || (pkg.directories = {})

  const defaults =
    { out: pkg.relative(`${pkg.name}-min`)
    , lib: pkg.relative(pkg.directories.lib || 'lib')
    , src: pkg.relative(pkg.directories.src || 'src')
    , optimize: 0
    , copy: true
    , debug: true
    , interactive: false
    , production: false
    , include: ['js:**/*.js', 'css:**/*.css']
    , exclude: ['../node_modules/**/*']
    , log: 'normal'
    }

  const cli = program
    .version(require('../package.json').version)
    .option('-i, --src <dir>', `the root directory from which all sources are relative [${defaults.src}]`, pkg.relative, defaults.src)
    .option('-o, --out <prefix>', `write optimized output to files with the specified prefix [${defaults.out}]`, pkg.relative, defaults.out)
    .option('-L, --lib <dir>', `write unoptimized files to the specified directory [${defaults.lib}]`, pkg.relative, defaults.lib)
    .option('-I, --include [js|css:]<path>', `include a path or glob (relative to source root) [${defaults.include}]`, concat, [])
    .option('-X, --exclude [js|css:]<path>', `exclude a path or glob (relative to source root) [${defaults.exclude}]`, concat, [])
    .option('-O, --optimize <level>', `optimization level (0 = none) [${defaults.optimize}]`, setOptimization, defaults.optimize)
    .option('--no-copy', `disable copying of non-code files to ${defaults.lib}`, Boolean, !defaults.copy)
    .option('--no-debug', 'disable source map generation', Boolean, !defaults.debug)
    .option('--log <normal|json>', `log output format [${defaults.log}]`, /^(json|normal)$/i, defaults.log)
    .option('--interactive', `watch for and recompile on changes (implies -O 0)`)
    .option('--production', `enable production options (implies -O 1)`)

  const opts = cli.parse(process.argv)
  const console = stdio({ debug: !!process.env.DEBUG, format: opts.log })

  const pipeline =
    { js: createPipeline(pkg, opts, jsc(pkg, opts), logPipe('js'))
    , css: createPipeline(pkg, opts, cssc(pkg, opts), logPipe('css'))
    , 'copy-files': createPipeline(pkg, opts, copyFiles(pkg, opts), logPipe('copy files'))
    }

  opts.include = conclude(keys(pipeline), defaults.include, opts.include)
  opts.exclude = conclude(keys(pipeline), defaults.exclude, opts.exclude)

  opts.include['copy-files'] = ['**/*']
  opts.exclude['copy-files'] = [...opts.include.js, ...opts.include.css, ...opts.exclude['*']]

  opts.optimize
    = opts.production?  1
    : opts.interactive? 0
    : opts.optimize

  opts.interactive = opts.production? false : opts.interactive

  console.debug('Options:')
  keys(defaults).forEach(name => console.debug(`- ${name}: ${JSON.stringify(opts[name])}`))

  parallel(
    keys(pipeline).map(type => apply(pipeline[type], collect(opts.include[type], opts.exclude[type])))
    , (error, results) => {
      if (opts.interactive) {
        console.info('Starting interactive mode...')
        keys(pipeline).forEach(type => {
          console.debug(`Watching ${type} pipeline:`)
          console.debug(`- included: ${opts.include[type]}`)
          console.debug(`- excluded: ${opts.exclude[type]}`)
          interactive(opts.include[type], opts.exclude[type])
            .on('add', pipeline[type])
            .on('change', pipeline[type])
        })
      } else if (opts.optimize) {
        console.debug('Writing optimised-modules.json')
        put(pkg.resolve('optimised-modules.json'),
          JSON.stringify(
            find(`${opts.lib}/**/*.js`).map(file => {
              const name = base(relative(opts.lib, file), ext(file))
              return `${pkg.name}/${opts.lib}/${name}`
            })
          , null, 2)
        )

        console.debug(`Writing ${pkg.name}-min.css`)
        put(pkg.resolve(`${pkg.name}-min.css`),
          find(`${opts.lib}/**/*.css`)
            .map(file => slurp(file, 'utf8'))
            .join('\n')
        )

        rebaseProdCss(`${pkg.name}-min.css`)
          .then(result => { put(pkg.resolve(`${pkg.name}-min.css`), result.css)})
          .catch(result => { console.error(result) })

        console.debug(`Writing ${pkg.name}-min.js`)
        put(pkg.resolve(`${pkg.name}-min.js`),
          find(`${opts.lib}/**/*.js`)
            .map(file => slurp(file, 'utf8'))
            .join('\n')
        )
      }
    }
  )

  function collect(include, exclude) {
    let collection = include.reduce((files, pattern) => {
      return files.concat(
        find(`${opts.src}/${pattern}`, { nodir: true, ignore: exclude, cwd: pkg.root })
      )
    }, [])

    return collection
  }

  function interactive(include, exclude) {
    let watcher = watch(include.reduce((files, pattern) => {
      return files.concat(`${opts.src}/${pattern}`)
    }, []), { ignored: exclude, cwd: pkg.root, ignoreInitial: true })

    return watcher
  }

  function logPipe(pipeline) {
    return {
      onBuild({ input, messages, files }) {
        if (messages) {
          [].concat(messages).forEach(message => {
            console.warn({ pipeline, message }, yellow(`\n${pipeline} – ${input}: ${message}`))
          })
        }
        console.log({ pipeline, input, files }, `${pipeline} – ${input} -> ${files}`)
      },

      onError({ input, error }) {
        console.error({ pipeline, error }, `\n${pipeline} – ${red(error.message)}\n${error.codeFrame}\n`)
      }
    }
  }
})

function setOptimization(level) {
  return Math.max(level | 0, 0)
}

function concat(val, list) {
  return list.concat(val.split(','))
}

function conclude(types, defaults, opts) {
  return Object.assign
    ( defaults.reduce(parse, {})
    , opts.reduce(parse, {})
    )

  function parse(pipe, val) {
    let [lines, pattern] = val.split(':')

    if (pattern) {
      lines = [lines]
    } else {
      pattern = lines
      lines = ['*', ...types]
    }

    lines.forEach(line => {
      pipe[line] = (pipe[line] || []).concat(pattern)
    })

    return pipe
  }
}<commit_msg>Include *all* files in optimised-modules.json<commit_after>import program from 'commander'
import readPkg from 'read-package-json'
import { sync as find } from 'glob'
import { find as resolvePkg } from 'pkginfo'
import { dirname, relative, basename as base, resolve, normalize, delimiter, extname as ext, join } from 'path'
import { execSync as exec } from 'child_process'
import { optimize } from 'requirejs'
import { default as put } from 'output-file-sync'
import { readFileSync as slurp } from 'fs'
import stdio from './util/stdio'
import { parallel, apply } from 'async'
import { default as jsc } from './builder/javascript'
import { default as cssc } from './builder/css'
import { default as copyFiles } from './builder/copy-files'
import { default as createPipeline } from './pipeline'
import { red, yellow } from 'ansicolors'
import { watch } from 'chokidar'
import rebaseProdCss from './rebase-prod-css'

const keys = Object.keys

const pkgFile = resolvePkg(module, process.cwd())
    , pkgRoot = dirname(pkgFile)

readPkg(pkgFile, (err, pkg) => {
  if (err) {
    console.error(err.message)
    process.exit(1)
  }

  pkg.root = pkgRoot
  pkg.resolve = (path) => relative(process.cwd(), resolve(pkgRoot, path))
  pkg.relative = (path) => relative(pkgRoot, resolve(pkgRoot, path))

  pkg.directories || (pkg.directories = {})

  const defaults =
    { out: pkg.relative(`${pkg.name}-min`)
    , lib: pkg.relative(pkg.directories.lib || 'lib')
    , src: pkg.relative(pkg.directories.src || 'src')
    , optimize: 0
    , copy: true
    , debug: true
    , interactive: false
    , production: false
    , include: ['js:**/*.js', 'css:**/*.css']
    , exclude: ['../node_modules/**/*']
    , log: 'normal'
    }

  const cli = program
    .version(require('../package.json').version)
    .option('-i, --src <dir>', `the root directory from which all sources are relative [${defaults.src}]`, pkg.relative, defaults.src)
    .option('-o, --out <prefix>', `write optimized output to files with the specified prefix [${defaults.out}]`, pkg.relative, defaults.out)
    .option('-L, --lib <dir>', `write unoptimized files to the specified directory [${defaults.lib}]`, pkg.relative, defaults.lib)
    .option('-I, --include [js|css:]<path>', `include a path or glob (relative to source root) [${defaults.include}]`, concat, [])
    .option('-X, --exclude [js|css:]<path>', `exclude a path or glob (relative to source root) [${defaults.exclude}]`, concat, [])
    .option('-O, --optimize <level>', `optimization level (0 = none) [${defaults.optimize}]`, setOptimization, defaults.optimize)
    .option('--no-copy', `disable copying of non-code files to ${defaults.lib}`, Boolean, !defaults.copy)
    .option('--no-debug', 'disable source map generation', Boolean, !defaults.debug)
    .option('--log <normal|json>', `log output format [${defaults.log}]`, /^(json|normal)$/i, defaults.log)
    .option('--interactive', `watch for and recompile on changes (implies -O 0)`)
    .option('--production', `enable production options (implies -O 1)`)

  const opts = cli.parse(process.argv)
  const console = stdio({ debug: !!process.env.DEBUG, format: opts.log })

  const pipeline =
    { js: createPipeline(pkg, opts, jsc(pkg, opts), logPipe('js'))
    , css: createPipeline(pkg, opts, cssc(pkg, opts), logPipe('css'))
    , 'copy-files': createPipeline(pkg, opts, copyFiles(pkg, opts), logPipe('copy files'))
    }

  opts.include = conclude(keys(pipeline), defaults.include, opts.include)
  opts.exclude = conclude(keys(pipeline), defaults.exclude, opts.exclude)

  opts.include['copy-files'] = ['**/*']
  opts.exclude['copy-files'] = [...opts.include.js, ...opts.include.css, ...opts.exclude['*']]

  opts.optimize
    = opts.production?  1
    : opts.interactive? 0
    : opts.optimize

  opts.interactive = opts.production? false : opts.interactive

  console.debug('Options:')
  keys(defaults).forEach(name => console.debug(`- ${name}: ${JSON.stringify(opts[name])}`))

  parallel(
    keys(pipeline).map(type => apply(pipeline[type], collect(opts.include[type], opts.exclude[type])))
    , (error, results) => {
      if (opts.interactive) {
        console.info('Starting interactive mode...')
        keys(pipeline).forEach(type => {
          console.debug(`Watching ${type} pipeline:`)
          console.debug(`- included: ${opts.include[type]}`)
          console.debug(`- excluded: ${opts.exclude[type]}`)
          interactive(opts.include[type], opts.exclude[type])
            .on('add', pipeline[type])
            .on('change', pipeline[type])
        })
      } else if (opts.optimize) {
        console.debug('Writing optimised-modules.json')
        put(pkg.resolve('optimised-modules.json'),
          JSON.stringify(
            new Set(find(`${opts.lib}/**/*`).map(file => {
              const name = base(relative(opts.lib, file.slice(0, file.indexOf('.'))))
              return `${pkg.name}/${opts.lib}/${name}`
            }))
          , null, 2)
        )

        console.debug(`Writing ${pkg.name}-min.css`)
        put(pkg.resolve(`${pkg.name}-min.css`),
          find(`${opts.lib}/**/*.css`)
            .map(file => slurp(file, 'utf8'))
            .join('\n')
        )

        rebaseProdCss(`${pkg.name}-min.css`)
          .then(result => { put(pkg.resolve(`${pkg.name}-min.css`), result.css)})
          .catch(result => { console.error(result) })

        console.debug(`Writing ${pkg.name}-min.js`)
        put(pkg.resolve(`${pkg.name}-min.js`),
          find(`${opts.lib}/**/*.js`)
            .map(file => slurp(file, 'utf8'))
            .join('\n')
        )
      }
    }
  )

  function collect(include, exclude) {
    let collection = include.reduce((files, pattern) => {
      return files.concat(
        find(`${opts.src}/${pattern}`, { nodir: true, ignore: exclude, cwd: pkg.root })
      )
    }, [])

    return collection
  }

  function interactive(include, exclude) {
    let watcher = watch(include.reduce((files, pattern) => {
      return files.concat(`${opts.src}/${pattern}`)
    }, []), { ignored: exclude, cwd: pkg.root, ignoreInitial: true })

    return watcher
  }

  function logPipe(pipeline) {
    return {
      onBuild({ input, messages, files }) {
        if (messages) {
          [].concat(messages).forEach(message => {
            console.warn({ pipeline, message }, yellow(`\n${pipeline} – ${input}: ${message}`))
          })
        }
        console.log({ pipeline, input, files }, `${pipeline} – ${input} -> ${files}`)
      },

      onError({ input, error }) {
        console.error({ pipeline, error }, `\n${pipeline} – ${red(error.message)}\n${error.codeFrame}\n`)
      }
    }
  }
})

function setOptimization(level) {
  return Math.max(level | 0, 0)
}

function concat(val, list) {
  return list.concat(val.split(','))
}

function conclude(types, defaults, opts) {
  return Object.assign
    ( defaults.reduce(parse, {})
    , opts.reduce(parse, {})
    )

  function parse(pipe, val) {
    let [lines, pattern] = val.split(':')

    if (pattern) {
      lines = [lines]
    } else {
      pattern = lines
      lines = ['*', ...types]
    }

    lines.forEach(line => {
      pipe[line] = (pipe[line] || []).concat(pattern)
    })

    return pipe
  }
}<|endoftext|>


<commit_before>'use strict';

/* Directives */

angular.module('uiucEmailForm.directives', []).
  directive('appVersion', ['version', function(version) {
    return function(scope, elm, attrs) {
      elm.text(version);
    };
  }])
  .directive('formDefault',function(){
    return {
      restrict: "E",
      transclude: true,
      scope:true,
      templateUrl:"partials/form-default.html",
      controller: function($scope){
        // Create form data object
        $scope.form.data = {};

        // Returns whether the form is valid
        $scope.isValid = function(){
          var name = $scope.form.name;
          return $scope[name].$valid;
        };

        // Add default form reset functionality to the functionality
        // specified by $scope.form.resetForm option
        var _resetForm = $scope.form.resetForm;
        $scope.form.resetForm = function(){
          // Call optional user-defined resetForm
          if(typeof(_resetForm) == "function"){
            _resetForm();
          }

          $scope.form.data = {};

          var name = $scope.form.name;
          $scope[name].$setPristine();
        };
      }
    };
  })
  .directive('formEmail',function(){
    return {
      restrict: "E",
      scope: true,
      templateUrl:"partials/form-email.html"
    };
  })
  .directive('formName',function(){
    return {
      restrict: "E",
      scope: true,
      templateUrl:"partials/form-name.html"
    };
  })
  .directive('formPassword',function(){
    return {
      restrict: "E",
      scope: true,
      templateUrl:"partials/form-password.html"
    };
  })
  .directive('formLists',function(){
    return {
      restrict: "E",
      scope: true,
      templateUrl:"partials/form-lists.html",
      link: function($scope){

      },
      controller: function($scope){
        $scope.form.listsAvail = [];
        angular.forEach(function(list){
          $scope.form.listsOrig;
        });

        // Add code to reset list form to parent's resetForm
        var _resetForm = $scope.form.resetForm;
        $scope.form.resetForm = function(){
          _resetForm();

          for (var key in $scope.form.listsAvail){
            console.log($scope.form.listsOrig[key]["selected"]);
            $scope.form.listsAvail[key]["selected"] = $scope.form.listsOrig[key]["selected"];
          }
        };

        // helper method to get selected lists
        var selectedLists = function selectedLists() {
          return filterFilter($scope.form.listsAvail, { selected: true });
        };

        // watch lists for changes and add them to form.data.lists
console.log($scope.form.listsAvail);
        $scope.$watch('form.listsAvail|filter:{selected:true}', function (nv) {
          $scope.form.data.lists = nv.map(function (list) {
            return list.name;
          });
        }, true);
      }
    };
  });

<commit_msg>Remove unneeded link function<commit_after>'use strict';

/* Directives */

angular.module('uiucEmailForm.directives', []).
  directive('appVersion', ['version', function(version) {
    return function(scope, elm, attrs) {
      elm.text(version);
    };
  }])
  .directive('formDefault',function(){
    return {
      restrict: "E",
      transclude: true,
      scope:true,
      templateUrl:"partials/form-default.html",
      controller: function($scope){
        // Create form data object
        $scope.form.data = {};

        // Returns whether the form is valid
        $scope.isValid = function(){
          var name = $scope.form.name;
          return $scope[name].$valid;
        };

        // Add default form reset functionality to the functionality
        // specified by $scope.form.resetForm option
        var _resetForm = $scope.form.resetForm;
        $scope.form.resetForm = function(){
          // Call optional user-defined resetForm
          if(typeof(_resetForm) == "function"){
            _resetForm();
          }

          $scope.form.data = {};

          var name = $scope.form.name;
          $scope[name].$setPristine();
        };
      }
    };
  })
  .directive('formEmail',function(){
    return {
      restrict: "E",
      scope: true,
      templateUrl:"partials/form-email.html"
    };
  })
  .directive('formName',function(){
    return {
      restrict: "E",
      scope: true,
      templateUrl:"partials/form-name.html"
    };
  })
  .directive('formPassword',function(){
    return {
      restrict: "E",
      scope: true,
      templateUrl:"partials/form-password.html"
    };
  })
  .directive('formLists',function(){
    return {
      restrict: "E",
      scope: true,
      templateUrl:"partials/form-lists.html",
      controller: function($scope){
        $scope.form.listsAvail = [];
        angular.forEach($scope.form.listsOrig,function(list,key){
           $scope.form.listsAvail.push({
             selected: list["selected"],
             name: list["name"]
           });
        });

        // Add code to reset list form to parent's resetForm
        var _resetForm = $scope.form.resetForm;
        $scope.form.resetForm = function(){
          _resetForm();

          for (var key in $scope.form.listsAvail){
            $scope.form.listsAvail[key]["selected"] = $scope.form.listsOrig[key]["selected"];
          }
        };

        // helper method to get selected lists
        var selectedLists = function selectedLists() {
          return filterFilter($scope.form.listsAvail, { selected: true });
        };

        // watch lists for changes and add them to form.data.lists
        $scope.$watch('form.listsAvail|filter:{selected:true}', function (nv) {
          $scope.form.data.lists = nv.map(function (list) {
            return list.name;
          });
        }, true);
      }
    };
  });

<|endoftext|>


<commit_before>/**
 *  We're using Chai.JS as our BDD assertion library, and specifically,
 *  we want to write our specs using the expect assert style.
 **/
var chai = require('chai');

/**
 *  Enable http testing
 **/
var supertest = require('supertest');
chai.use(require('chai-http'));

/**
 *  For all our mocking needs as well as stubbing needs, we will
 *  want to make use of Sinon.JS as our framework of choice for these needs.
 **/
var sinon = require('sinon');

/**
 *  General-purpose library dependencies for tasks such as file I/O
 **/
var path = require('path');
var fs = require('fs-extra');
var tmp = require('tmp');

/**
 *  All the tests we want to run.
 **/
var tests = [];

/**
 *  Directories of interest
 **/
var cwdDir = process.cwd();
var testDir = path.join(cwdDir, 'test');
var srcDir = path.join(cwdDir, 'src');

/**
 *   Add a test to be run.
 **/
function addTest(name, exec) {
    tests.push({
        name: name,
        exec: exec
    });
}

/**
 *  Setup before each test
 **/
function beforeEach(test, context, done) {
    context.dir = tmp.dirSync().name;
    process.chdir(context.dir);
    done && done();
}

/**
 *  Clean up after each test
 **/
function afterEach(test, context) {
    fs.removeSync(context.dir);
}

/**
 *  Execute a single test
 **/
function runTest(test, done) {
    // Construct a test context
    var context = {
        expect: chai.expect,
        assert: chai.assert,
        stub: sinon.stub
    };

    beforeEach(test, context, function() {
        // Run the actual test and give the test all the tools it needs for optimal execution
        test.exec(context, function(error) {
            // Clean up the context
            afterEach(test, context);

            // Finish up the test
            done && done(error)
        });
    });
}

/**
 *  We look at all our tests and describe them here and set them
 *  up so as to pass the execution over to the test framework.
 **/
function runAllTests(name, allDone) {

    // We're going to create a single, flat list of scenarios
    describe(name, function() {

        after(function() {
            // Tell the caller when all tests have finished running
            allDone && allDone();
        });

        tests.forEach(function(test) {
            // Have a look at all tests and define each test,
            // and pass it all the required dependencies to enable it
            // to perform work without worrying about dependencies
            it(test.name, function(done) {
                // Increase the timeout so that we can handle slower CI cycles if necessary
                this.timeout(60000);

                // Execute the actual test
                runTest(test, done);
            });
        });

        // Clean up the test fixture
        tests = [];
    });
}

/**
 *  Look for a test asset, and if it exists, copy it to the
 *  test context at the given location.
 **/
function copyAssetToContext(src, dest, context) {
    var sourceAsset = path.join(testDir, src);
    var targetAsset = path.join(context.dir, dest);

    if (!fs.existsSync(sourceAsset)) {
        // The source asset requested is missing
        throw new Error("The test asset is missing");
    }

    // Attempt to copy the asset
    fs.copySync(sourceAsset, targetAsset);

    if (!fs.existsSync(targetAsset)) {
        // The target asset was not copied successfully
        throw new Error("The test asset could not be copied");
    }
}

var savor = {
    src: function(name) {
        return require(path.join(srcDir, name));
    },
    capture: function(stream) {
        var original = stream.write;
        var content = '';

        stream.write = function(string) {
            // Keep track of the stream's data
            content += string.toString();
            return true;
        }

        return {
            release: () => {
                stream.write = original;
                return content;
            }
        }
    },
    add: function(name, exec) {
        addTest(name, exec);
        return savor;
    },
    run: function(name, done) {
        runAllTests(name, done);
    },
    allTests: tests,
    reset: function() {
        tests = []
    },
    addAsset: function(src, dest, context) {
        copyAssetToContext(src, dest, context);
    }
}

module.exports = savor;
<commit_msg>enable chai promises<commit_after>/**
 *  We're using Chai.JS as our BDD assertion library, and specifically,
 *  we want to write our specs using the expect assert style.
 **/
var chai = require('chai');

/**
 *  Enable http testing
 **/
var supertest = require('supertest');
chai.use(require('chai-http'));

/**
 *  Enable smart promise assertions
 **/
var chaiAsPromised = require('chai-as-promised');
chai.use(chaiAsPromised);

/**
 *  For all our mocking needs as well as stubbing needs, we will
 *  want to make use of Sinon.JS as our framework of choice for these needs.
 **/
var sinon = require('sinon');

/**
 *  General-purpose library dependencies for tasks such as file I/O
 **/
var path = require('path');
var fs = require('fs-extra');
var tmp = require('tmp');

/**
 *  All the tests we want to run.
 **/
var tests = [];

/**
 *  Directories of interest
 **/
var cwdDir = process.cwd();
var testDir = path.join(cwdDir, 'test');
var srcDir = path.join(cwdDir, 'src');

/**
 *   Add a test to be run.
 **/
function addTest(name, exec) {
    tests.push({
        name: name,
        exec: exec
    });
}

/**
 *  Setup before each test
 **/
function beforeEach(test, context, done) {
    context.dir = tmp.dirSync().name;
    process.chdir(context.dir);
    done && done();
}

/**
 *  Clean up after each test
 **/
function afterEach(test, context) {
    fs.removeSync(context.dir);
}

/**
 *  Execute a single test
 **/
function runTest(test, done) {
    // Construct a test context
    var context = {
        expect: chai.expect,
        assert: chai.assert,
        stub: sinon.stub
    };

    beforeEach(test, context, function() {
        // Run the actual test and give the test all the tools it needs for optimal execution
        test.exec(context, function(error) {
            // Clean up the context
            afterEach(test, context);

            // Finish up the test
            done && done(error)
        });
    });
}

/**
 *  We look at all our tests and describe them here and set them
 *  up so as to pass the execution over to the test framework.
 **/
function runAllTests(name, allDone) {

    // We're going to create a single, flat list of scenarios
    describe(name, function() {

        after(function() {
            // Tell the caller when all tests have finished running
            allDone && allDone();
        });

        tests.forEach(function(test) {
            // Have a look at all tests and define each test,
            // and pass it all the required dependencies to enable it
            // to perform work without worrying about dependencies
            it(test.name, function(done) {
                // Increase the timeout so that we can handle slower CI cycles if necessary
                this.timeout(60000);

                // Execute the actual test
                runTest(test, done);
            });
        });

        // Clean up the test fixture
        tests = [];
    });
}

/**
 *  Look for a test asset, and if it exists, copy it to the
 *  test context at the given location.
 **/
function copyAssetToContext(src, dest, context) {
    var sourceAsset = path.join(testDir, src);
    var targetAsset = path.join(context.dir, dest);

    if (!fs.existsSync(sourceAsset)) {
        // The source asset requested is missing
        throw new Error("The test asset is missing");
    }

    // Attempt to copy the asset
    fs.copySync(sourceAsset, targetAsset);

    if (!fs.existsSync(targetAsset)) {
        // The target asset was not copied successfully
        throw new Error("The test asset could not be copied");
    }
}

var savor = {
    src: function(name) {
        return require(path.join(srcDir, name));
    },
    capture: function(stream) {
        var original = stream.write;
        var content = '';

        stream.write = function(string) {
            // Keep track of the stream's data
            content += string.toString();
            return true;
        }

        return {
            release: () => {
                stream.write = original;
                return content;
            }
        }
    },
    add: function(name, exec) {
        addTest(name, exec);
        return savor;
    },
    run: function(name, done) {
        runAllTests(name, done);
    },
    allTests: tests,
    reset: function() {
        tests = []
    },
    addAsset: function(src, dest, context) {
        copyAssetToContext(src, dest, context);
    }
}

module.exports = savor;
<|endoftext|>


<commit_before>define([
    'streamhub-sdk/jquery',
    'streamhub-sdk/views/list-view',
    'streamhub-sdk/content/views/content-view',
    'streamhub-sdk/util'
], function($, ListView, ContentView, util) {

    var MEDIA_WALL_STYLE_EL;
    var MEDIA_WALL_CSS = ".streamhub-media-wall-view { \
	    position:relative; \
	} \
    .streamhub-media-wall-view .content-container { \
        position: absolute; \
        box-sizing: border-box; \
        padding: 5px; \
	    -webkit-transition-duration: 1s; \
	       -moz-transition-duration: 1s; \
	        -ms-transition-duration: 1s; \
	         -o-transition-duration: 1s; \
	            transition-duration: 1s; \
	    -webkit-transition-property: -webkit-transform, opacity, top, left; \
	       -moz-transition-property:    -moz-transform, opacity, top, left; \
	        -ms-transition-property:     -ms-transform, opacity, top, left; \
	         -o-transition-property:      -o-transform, opacity, top, left; \
	            transition-property:         transform, opacity, top, left; } \
	.streamhub-media-wall-view article.content { \
        width: 100%; \
        border: 1px solid rgba(0,0,0,0.15); \
        border-radius: 3px; }\
    .streamhub-media-wall-view article.hub-wall-is-inserting { \
        opacity: 0 ; \
	    -webkit-transition-property: none; \
	       -moz-transition-property: none; \
	        -ms-transition-property: none; \
	         -o-transition-property: none; \
	            transition-property: none; \
	    -webkit-transition: opacity 0.3s; \
	       -moz-transition: opacity 0.3s; \
	        -ms-transition: opacity 0.3s; \
	         -o-transition: opacity 0.3s; \
	            transition: opacity 0.3s; }";

    /**
     * A view that displays Content in a media wall.
     * @param opts {Object} A set of options to config the view with
     * @param opts.el {HTMLElement} The element in which to render the streamed content
     * @param opts.relayoutWait {number} The number of milliseconds to wait when debouncing
     *        .relayout(). Defaults to 200ms.
     * @param opts.css {boolean} Whether to insert default media wall css. Default true.
     * @constructor
     */
    var MediaWallView = function(opts) {
        var self = this;
        opts = opts || {};

        this._id = new Date().getTime();
        this._autoFitColumns = true;
        this._contentWidth = opts.minContentWidth || 300;

        ListView.call(this, opts);

        this.debouncedRelayout = debounce(function () {
            self._relayout.apply(self, arguments);
        }, opts.debounceRelayout || 200);

        this.debouncedFitColumns = debounce(function () {
            self._fitColumns();
        }, opts.debounceRelayout || 200);

        $(window).resize(function() {
            self.relayout();
            if (self._autoFitColumns) {
                self.fitColumns();
            }
        });

        opts.css = (typeof opts.css === 'undefined') ? true : opts.css;
        if (!MEDIA_WALL_STYLE_EL && opts.css) {
            MEDIA_WALL_STYLE_EL = $('').text(MEDIA_WALL_CSS).prependTo('head');
        }
        if (opts.columns && typeof opts.columns === 'number') {
            this._columns = opts.columns;
            this._autoFitColumns = false;
            this.setColumns(opts.columns);
        }
        if (this._autoFitColumns) {
            this.fitColumns({ force: true });
        }
    };
    util.inherits(MediaWallView, ListView);

    MediaWallView.prototype.mediaWallClassName = 'streamhub-media-wall-view';
    MediaWallView.prototype.contentContainerClassName = 'content-container';

    MediaWallView.prototype.setElement = function (el) {
        ListView.prototype.setElement.call(this, el);
        $(this.el)
            .addClass(this.mediaWallClassName)
            .addClass('streamhub-media-wall-' + this._id);
    };

    MediaWallView.prototype._getWallStyleEl = function () {
        var $wallStyleEl = $('#wall-style-' + this._id);
        if ($wallStyleEl) {
            return $wallStyleEl;
        }
    };

    MediaWallView.prototype.setColumns = function (numColumns) {
        this._columns = numColumns;
        var $wallStyleEl = this._getWallStyleEl();
        if ($wallStyleEl) {
            $wallStyleEl.remove();
        }
        $wallStyleEl = $('</style');
        $wallStyleEl.html('.streamhub-media-wall-'+this._id+' .content-container { width: ' + width + '; }');
        $wallStyleEl.appendTo('head');
    };

    /**
     * Add a piece of Content to the MediaWallView
     * @param content {Content} A Content model to add to the MediaWallView
     * @return the newly created ContentView
     */
    MediaWallView.prototype.add = function(content) {
        var self = this,
            contentView = ListView.prototype.add.call(this, content);

        contentView.$el.addClass(this.insertingClassName);
        contentView.$el.on('imageLoaded.hub', function() {
            self.relayout();
        });

        this.relayout();
    };

    MediaWallView.prototype._insert = function (contentView) {
        var newContentViewIndex,
            $previousEl;

        newContentViewIndex = this.contentViews.indexOf(contentView);

        var $containerEl = $('

');
        contentView.$el.wrap($containerEl);
        var $wrappedEl = contentView.$el.parent();

        if (newContentViewIndex === 0) {
            // Beginning!
            $wrappedEl.prependTo(this.el);
        } else {
            // Find it's previous contentView and insert new contentView after
            $previousEl = this.contentViews[newContentViewIndex - 1].$el;
            $wrappedEl.insertAfter($previousEl.parent('.'+this.contentContainerClassName));
        }
    };

    MediaWallView.prototype.fitColumns = function (opts) {
        opts = opts || {};

        if (opts.force) {
            this._fitColumns.apply(this, arguments);
        } else {
            this.debouncedFitColumns.apply(this, arguments);
        }
    };

    MediaWallView.prototype._fitColumns = function (opts) {
        var containerWidth = $(this.el).innerWidth();
        var numColumns = parseInt(containerWidth / this._contentWidth) || 1;
        this.setColumns(numColumns);
    };

    MediaWallView.prototype.insertingClassName = 'hub-wall-is-inserting';

    MediaWallView.prototype.relayout = function (opts) {
        opts = opts || {};

        if (opts.force) {
            this._relayout.apply(this, arguments);
        } else {
            this.debouncedRelayout.apply(this, arguments);
        }
    };

    MediaWallView.prototype._relayout = function(opts) {
        opts = opts || {};
        var columnWidth = 0;
        var columnHeights = [];
        var cols = 0;
        var containerWidth = $(this.el).innerWidth();
        var maximumY;
        var self = this;

        var self = this;
        $.each(this.contentViews, function (index, contentView) {
            var $contentContainerEl = contentView.$el.parent('.'+self.contentContainerClassName);

            if (columnWidth === 0) {
                columnWidth = $contentContainerEl[0].getBoundingClientRect().width;
                if (columnWidth !== 0) {
                    cols = Math.floor(containerWidth / columnWidth);
                    for (var j = 0; j < cols; j++) {
                        columnHeights[j] = 0;
                    }
                }
            }
            // get the minimum Y value from the columns
            var minimumY = Math.min.apply( Math, columnHeights );
            maximumY = Math.max.apply( Math, columnHeights );
            var shortCol = 0;

            // Find index of short column, the first from the left
            for (var k = 0; k < columnHeights.length; k++) {
                if ( columnHeights[k] === minimumY ) {
                    shortCol = k;
                    break;
                }
            }
            // position the content
            var x = columnWidth * shortCol;
            var y = minimumY;

            $contentContainerEl.css({
                position: 'absolute',
                left: x+'px',
                top: y+'px'
            });

            // apply height to column
            columnHeights[shortCol] = minimumY + contentView.$el.outerHeight(true);

            if (columnHeights[shortCol] > maximumY) {
                maximumY = columnHeights[shortCol];
            }

            contentView.$el.removeClass(self.insertingClassName);
        });

        $(this.$listEl).css('height', maximumY + 'px');
    };

    /**
     * Returns a function, that, as long as it continues to be invoked, will not be triggered.
     * The function will be called after it stops being called for N milliseconds.
     * Copied from Underscore.js (MIT License) http://underscorejs.org/docs/underscore.html#section-65
     * @param func {function} The function to debounce
     * @param wait {number} The number of milliseconds to wait for execution of func
     * @param immediate {boolean} trigger the function on the leading edge, instead of the trailing.
     * @return {function} A debounced version of the passed `func`
     */
    function debounce(func, wait, immediate) {
        var timeout, result;
        return function() {
            var context = this,
                args = arguments;
            var later = function() {
                timeout = null;
                if (!immediate) {
                    result = func.apply(context, args);
                }
            };
            var callNow = immediate && !timeout;
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
            if (callNow) {
                result = func.apply(context, args);
            }
            return result;
        };
    }

    return MediaWallView;
});
<commit_msg>don't use util.inherits, since its no longer in sdk<commit_after>define([
    'streamhub-sdk/jquery',
    'streamhub-sdk/views/list-view',
    'streamhub-sdk/content/views/content-view',
    'inherits'
], function($, ListView, ContentView, inherits) {

    var MEDIA_WALL_STYLE_EL;
    var MEDIA_WALL_CSS = ".streamhub-media-wall-view { \
	    position:relative; \
	} \
    .streamhub-media-wall-view .content-container { \
        position: absolute; \
        box-sizing: border-box; \
        padding: 5px; \
	    -webkit-transition-duration: 1s; \
	       -moz-transition-duration: 1s; \
	        -ms-transition-duration: 1s; \
	         -o-transition-duration: 1s; \
	            transition-duration: 1s; \
	    -webkit-transition-property: -webkit-transform, opacity, top, left; \
	       -moz-transition-property:    -moz-transform, opacity, top, left; \
	        -ms-transition-property:     -ms-transform, opacity, top, left; \
	         -o-transition-property:      -o-transform, opacity, top, left; \
	            transition-property:         transform, opacity, top, left; } \
	.streamhub-media-wall-view article.content { \
        width: 100%; \
        border: 1px solid rgba(0,0,0,0.15); \
        border-radius: 3px; }\
    .streamhub-media-wall-view article.hub-wall-is-inserting { \
        opacity: 0 ; \
	    -webkit-transition-property: none; \
	       -moz-transition-property: none; \
	        -ms-transition-property: none; \
	         -o-transition-property: none; \
	            transition-property: none; \
	    -webkit-transition: opacity 0.3s; \
	       -moz-transition: opacity 0.3s; \
	        -ms-transition: opacity 0.3s; \
	         -o-transition: opacity 0.3s; \
	            transition: opacity 0.3s; }";

    /**
     * A view that displays Content in a media wall.
     * @param opts {Object} A set of options to config the view with
     * @param opts.el {HTMLElement} The element in which to render the streamed content
     * @param opts.relayoutWait {number} The number of milliseconds to wait when debouncing
     *        .relayout(). Defaults to 200ms.
     * @param opts.css {boolean} Whether to insert default media wall css. Default true.
     * @constructor
     */
    var MediaWallView = function(opts) {
        var self = this;
        opts = opts || {};

        this._id = new Date().getTime();
        this._autoFitColumns = true;
        this._contentWidth = opts.minContentWidth || 300;

        ListView.call(this, opts);

        this.debouncedRelayout = debounce(function () {
            self._relayout.apply(self, arguments);
        }, opts.debounceRelayout || 200);

        this.debouncedFitColumns = debounce(function () {
            self._fitColumns();
        }, opts.debounceRelayout || 200);

        $(window).resize(function() {
            self.relayout();
            if (self._autoFitColumns) {
                self.fitColumns();
            }
        });

        opts.css = (typeof opts.css === 'undefined') ? true : opts.css;
        if (!MEDIA_WALL_STYLE_EL && opts.css) {
            MEDIA_WALL_STYLE_EL = $('').text(MEDIA_WALL_CSS).prependTo('head');
        }
        if (opts.columns && typeof opts.columns === 'number') {
            this._columns = opts.columns;
            this._autoFitColumns = false;
            this.setColumns(opts.columns);
        }
        if (this._autoFitColumns) {
            this.fitColumns({ force: true });
        }
    };
    inherits(MediaWallView, ListView);

    MediaWallView.prototype.mediaWallClassName = 'streamhub-media-wall-view';
    MediaWallView.prototype.contentContainerClassName = 'content-container';

    MediaWallView.prototype.setElement = function (el) {
        ListView.prototype.setElement.call(this, el);
        $(this.el)
            .addClass(this.mediaWallClassName)
            .addClass('streamhub-media-wall-' + this._id);
    };

    MediaWallView.prototype._getWallStyleEl = function () {
        var $wallStyleEl = $('#wall-style-' + this._id);
        if ($wallStyleEl) {
            return $wallStyleEl;
        }
    };

    MediaWallView.prototype.setColumns = function (numColumns) {
        this._columns = numColumns;
        var $wallStyleEl = this._getWallStyleEl();
        if ($wallStyleEl) {
            $wallStyleEl.remove();
        }
        $wallStyleEl = $('</style');
        $wallStyleEl.html('.streamhub-media-wall-'+this._id+' .content-container { width: ' + width + '; }');
        $wallStyleEl.appendTo('head');
    };

    /**
     * Add a piece of Content to the MediaWallView
     * @param content {Content} A Content model to add to the MediaWallView
     * @return the newly created ContentView
     */
    MediaWallView.prototype.add = function(content) {
        var self = this,
            contentView = ListView.prototype.add.call(this, content);

        contentView.$el.addClass(this.insertingClassName);
        contentView.$el.on('imageLoaded.hub', function() {
            self.relayout();
        });

        this.relayout();
    };

    MediaWallView.prototype._insert = function (contentView) {
        var newContentViewIndex,
            $previousEl;

        newContentViewIndex = this.contentViews.indexOf(contentView);

        var $containerEl = $('

');
        contentView.$el.wrap($containerEl);
        var $wrappedEl = contentView.$el.parent();

        if (newContentViewIndex === 0) {
            // Beginning!
            $wrappedEl.prependTo(this.el);
        } else {
            // Find it's previous contentView and insert new contentView after
            $previousEl = this.contentViews[newContentViewIndex - 1].$el;
            $wrappedEl.insertAfter($previousEl.parent('.'+this.contentContainerClassName));
        }
    };

    MediaWallView.prototype.fitColumns = function (opts) {
        opts = opts || {};

        if (opts.force) {
            this._fitColumns.apply(this, arguments);
        } else {
            this.debouncedFitColumns.apply(this, arguments);
        }
    };

    MediaWallView.prototype._fitColumns = function (opts) {
        var containerWidth = $(this.el).innerWidth();
        var numColumns = parseInt(containerWidth / this._contentWidth) || 1;
        this.setColumns(numColumns);
    };

    MediaWallView.prototype.insertingClassName = 'hub-wall-is-inserting';

    MediaWallView.prototype.relayout = function (opts) {
        opts = opts || {};

        if (opts.force) {
            this._relayout.apply(this, arguments);
        } else {
            this.debouncedRelayout.apply(this, arguments);
        }
    };

    MediaWallView.prototype._relayout = function(opts) {
        opts = opts || {};
        var columnWidth = 0;
        var columnHeights = [];
        var cols = 0;
        var containerWidth = $(this.el).innerWidth();
        var maximumY;
        var self = this;

        var self = this;
        $.each(this.contentViews, function (index, contentView) {
            var $contentContainerEl = contentView.$el.parent('.'+self.contentContainerClassName);

            if (columnWidth === 0) {
                columnWidth = $contentContainerEl[0].getBoundingClientRect().width;
                if (columnWidth !== 0) {
                    cols = Math.floor(containerWidth / columnWidth);
                    for (var j = 0; j < cols; j++) {
                        columnHeights[j] = 0;
                    }
                }
            }
            // get the minimum Y value from the columns
            var minimumY = Math.min.apply( Math, columnHeights );
            maximumY = Math.max.apply( Math, columnHeights );
            var shortCol = 0;

            // Find index of short column, the first from the left
            for (var k = 0; k < columnHeights.length; k++) {
                if ( columnHeights[k] === minimumY ) {
                    shortCol = k;
                    break;
                }
            }
            // position the content
            var x = columnWidth * shortCol;
            var y = minimumY;

            $contentContainerEl.css({
                position: 'absolute',
                left: x+'px',
                top: y+'px'
            });

            // apply height to column
            columnHeights[shortCol] = minimumY + contentView.$el.outerHeight(true);

            if (columnHeights[shortCol] > maximumY) {
                maximumY = columnHeights[shortCol];
            }

            contentView.$el.removeClass(self.insertingClassName);
        });

        $(this.$listEl).css('height', maximumY + 'px');
    };

    /**
     * Returns a function, that, as long as it continues to be invoked, will not be triggered.
     * The function will be called after it stops being called for N milliseconds.
     * Copied from Underscore.js (MIT License) http://underscorejs.org/docs/underscore.html#section-65
     * @param func {function} The function to debounce
     * @param wait {number} The number of milliseconds to wait for execution of func
     * @param immediate {boolean} trigger the function on the leading edge, instead of the trailing.
     * @return {function} A debounced version of the passed `func`
     */
    function debounce(func, wait, immediate) {
        var timeout, result;
        return function() {
            var context = this,
                args = arguments;
            var later = function() {
                timeout = null;
                if (!immediate) {
                    result = func.apply(context, args);
                }
            };
            var callNow = immediate && !timeout;
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
            if (callNow) {
                result = func.apply(context, args);
            }
            return result;
        };
    }

    return MediaWallView;
});
<|endoftext|>


<commit_before>dbs_chartValue = function(pId) {
	var xChart = $(pId).closest(".dbs_chart");
	if (xChart.attr("type") == "line"){
		dbsfaces.chartValue.drawLines(pId);
	}

	setTimeout(function(){
		dbsfaces.chartValue.showLabel(pId);
	},0);

	$(pId).mouseenter(function (e){
		dbsfaces.tooltip.showTooltip(pId + '_tooltip');
		$(pId + '_tooltip').addClass("-selected");
		$(pId + " > .-xlabel").get(0).classList.add("-selected");
		$(pId + " > .-ylabel").get(0).classList.add("-selected");
		dbsfaces.chartValue.selectValue(pId, true);
	});
	$(pId).mouseleave(function (e){
		dbsfaces.tooltip.hideTooltip(pId + '_tooltip');
		$(pId + '_tooltip').removeClass("-selected");
		$(pId + " > .-xlabel").get(0).classList.remove("-selected");
		$(pId + " > .-ylabel").get(0).classList.remove("-selected");
		dbsfaces.chartValue.selectValue(pId, false);
	});
};

dbsfaces.chartValue = {
	drawLines: function(pId){
		var xValue = $(pId);
		if (xValue.length == 0){
			return;
		}
		var xLineGroup = $(pId).siblings(".-line");
		var xValueAnterior = xValue.prevAll(".dbs_chartValue").first();

		dbsfaces.chartValue.drawLine(xLineGroup, xValueAnterior);
		dbsfaces.chartValue.drawLine(xLineGroup, xValue);

		return;
	},

	drawLine: function(pLineGroup, pValue){
		if (pValue.length == 0){return;}
		var xValuePosterior = pValue.nextAll(".dbs_chartValue").first().children("ellipse");
		if (xValuePosterior.length == 0){return;}
		var xValue = pValue.children("ellipse");
		var xId = pValue.attr("id");
		var xX1 = xValue.attr("cx");
		var xY1 = xValue.attr("cy");
		var xX2 = xValuePosterior.attr("cx");
		var xY2 = xValuePosterior.attr("cy");
		var xLine = pLineGroup.children("line[index='" + xId + "']");
		if (xLine.length == 0){
			xLine = $(document.createElementNS('http://www.w3.org/2000/svg','line'));
		}
		xLine.attr("index", xId);
		xLine.attr("x1", xX1);
		xLine.attr("y1", xY1);
		xLine.attr("x2", xX2);
		xLine.attr("y2", xY2);
		pLineGroup.append(xLine);
	},

	showLabel: function(pId){
		var xValue = $(pId);
		if (xValue.length == 0){return;}

		var xLabelAtual = xValue.children(".-xlabel");
		if (xLabelAtual.length == 0){return;}

		//Procura valor anterior que contenha label sendo exibido
		var xLabelAnterior = xValue.prevAll(".dbs_chartValue").children(".-xlabel").not("[class ~= '-hide']").first();
		var xXAtual = 0;
		var xXAnterior = 0;
		//Calcula posição final da label anterior
		if (xLabelAnterior.length != 0){
			xXAnterior = Number(xLabelAnterior.attr("x")) + (xLabelAnterior.get(0).getComputedTextLength() / 2) + 4;
		}
		//Calcula posição inicial da label atual
		xXAtual = Number(xLabelAtual.attr("x")) - (xLabelAtual.get(0).getComputedTextLength() / 2);
		//Exclui sobreposição de texto
		if (xXAnterior > xXAtual){
			xLabelAtual.get(0).classList.add("-hide");
		}else{
			xLabelAtual.get(0).classList.remove("-hide");
		}

		//Centraliza o texto do extrainfo
//		var xXLabel = $(pId + " > .-extrainfo > .-x");
//		xXLabel.offset({left: xXAtual})
	},

	selectValue: function(pId, pSelect){
		var xValue = $(pId);
		if (xValue.length == 0){return;}

		var xXLabelAtual = xValue.children(".-xlabel");

		var xYLabels = xValue.closest(".dbs_charts").find(".-container > .-data > .-container > .-content > .-value > .-grid > .-label");
		var xXLabels = xValue.siblings(".dbs_chartValue").children(".-xlabel").not("[class ~= '-hide']").not(xXLabelAtual);
		if (pSelect){
			xXLabels.hide();
			xYLabels.hide();
		}else{
			xXLabels.show();
			xYLabels.show();
		}
	}

};

<commit_msg>Correção da exibição do label lateral<commit_after>dbs_chartValue = function(pId) {
	var xChart = $(pId).closest(".dbs_chart");
	if (xChart.attr("type") == "line"){
		dbsfaces.chartValue.drawLines(pId);
	}

	setTimeout(function(){
		dbsfaces.chartValue.showLabel(pId);
	},0);

	$(pId).mouseenter(function (e){
		dbsfaces.tooltip.showTooltip(pId + '_tooltip');
		$(pId + '_tooltip').addClass("-selected");
		if ($(pId + " > .-xlabel").length > 0){
			$(pId + " > .-xlabel").get(0).classList.add("-selected");
		}
		if ($(pId + " > .-ylabel").length > 0){
			$(pId + " > .-ylabel").get(0).classList.add("-selected");
		}
		dbsfaces.chartValue.selectValue(pId, true);
	});
	$(pId).mouseleave(function (e){
		dbsfaces.tooltip.hideTooltip(pId + '_tooltip');
		$(pId + '_tooltip').removeClass("-selected");
		if ($(pId + " > .-xlabel").length > 0){
			$(pId + " > .-xlabel").get(0).classList.remove("-selected");
		}
		if ($(pId + " > .-ylabel").length > 0){
			$(pId + " > .-ylabel").get(0).classList.remove("-selected");
		}
		dbsfaces.chartValue.selectValue(pId, false);
	});
};

dbsfaces.chartValue = {
	drawLines: function(pId){
		var xValue = $(pId);
		if (xValue.length == 0){
			return;
		}
		var xLineGroup = $(pId).siblings(".-line");
		var xValueAnterior = xValue.prevAll(".dbs_chartValue").first();

		dbsfaces.chartValue.drawLine(xLineGroup, xValueAnterior);
		dbsfaces.chartValue.drawLine(xLineGroup, xValue);

		return;
	},

	drawLine: function(pLineGroup, pValue){
		if (pValue.length == 0){return;}
		var xValuePosterior = pValue.nextAll(".dbs_chartValue").first().children("ellipse");
		if (xValuePosterior.length == 0){return;}
		var xValue = pValue.children("ellipse");
		var xId = pValue.attr("id");
		var xX1 = xValue.attr("cx");
		var xY1 = xValue.attr("cy");
		var xX2 = xValuePosterior.attr("cx");
		var xY2 = xValuePosterior.attr("cy");
		var xLine = pLineGroup.children("line[index='" + xId + "']");
		if (xLine.length == 0){
			xLine = $(document.createElementNS('http://www.w3.org/2000/svg','line'));
		}
		xLine.attr("index", xId);
		xLine.attr("x1", xX1);
		xLine.attr("y1", xY1);
		xLine.attr("x2", xX2);
		xLine.attr("y2", xY2);
		pLineGroup.append(xLine);
	},

	showLabel: function(pId){
		var xValue = $(pId);
		if (xValue.length == 0){return;}

		var xLabelAtual = xValue.children(".-xlabel");
		if (xLabelAtual.length == 0){return;}

		//Procura valor anterior que contenha label sendo exibido
		var xLabelAnterior = xValue.prevAll(".dbs_chartValue").children(".-xlabel").not("[class ~= '-hide']").first();
		var xXAtual = 0;
		var xXAnterior = 0;
		//Calcula posição final da label anterior
		if (xLabelAnterior.length != 0){
			xXAnterior = Number(xLabelAnterior.attr("x")) + (xLabelAnterior.get(0).getComputedTextLength() / 2) + 4;
		}
		//Calcula posição inicial da label atual
		xXAtual = Number(xLabelAtual.attr("x")) - (xLabelAtual.get(0).getComputedTextLength() / 2);
		//Exclui sobreposição de texto
		if (xXAnterior > xXAtual){
			xLabelAtual.get(0).classList.add("-hide");
		}else{
			xLabelAtual.get(0).classList.remove("-hide");
		}

		//Centraliza o texto do extrainfo
//		var xXLabel = $(pId + " > .-extrainfo > .-x");
//		xXLabel.offset({left: xXAtual})
	},

	selectValue: function(pId, pSelect){
		var xValue = $(pId);
		if (xValue.length == 0){return;}

		var xXLabelAtual = xValue.children(".-xlabel");

		var xYLabels = xValue.closest(".dbs_charts").find(".-container > .-data > .-container > .-content > .-value > .-grid > .-label");
		var xXLabels = xValue.siblings(".dbs_chartValue").children(".-xlabel").not("[class ~= '-hide']").not(xXLabelAtual);
		if (pSelect){
			xXLabels.hide();
			xYLabels.hide();
		}else{
			xXLabels.show();
			xYLabels.show();
		}
	}

};

<|endoftext|>