<commit_before>var files = require('customize/helpers-io').files

module.exports = {
  // Initial configuration when registering the engine.
  defaultConfig: null,

  // Files/Dirs to-be-watched with the default configuration
  defaultWatched: [],

  // This function is called for any `.merge` input.
  // It converts the input into its mergable form
  preprocessConfig: function (config) {
    return files(config)
  },

  // This function is called to determine the files and directories
  // to watch in developmentMode
  watched: function (config) {
    return [
      // The config itself is the directory-path
      config
    ]
  },

  // Runs the engine with a resolved configuration.
  // The config contains no Promises anymore.
  run: function (config) {
    var result = ''
    for (var filename in config) {
      if (config.hasOwnProperty(filename)) {
        result += config[filename].contents + '\n'
      }
    }
    return result
  }
}
<commit_msg>Unified output scheme for customize-engines: Output object { filename: contents, ...} for each file to be written.<commit_after>var files = require('customize/helpers-io').files

module.exports = {
  // Initial configuration when registering the engine.
  defaultConfig: null,

  // Files/Dirs to-be-watched with the default configuration
  defaultWatched: [],

  // This function is called for any `.merge` input.
  // It converts the input into its mergable form
  preprocessConfig: function (config) {
    return files(config)
  },

  // This function is called to determine the files and directories
  // to watch in developmentMode
  watched: function (config) {
    return [
      // The config itself is the directory-path
      config
    ]
  },

  // Runs the engine with a resolved configuration.
  // The config contains no Promises anymore.
  run: function (config) {
    var result = ''
    for (var filename in config) {
      if (config.hasOwnProperty(filename)) {
        result += config[filename].contents + '\n'
      }
    }
    return {
      // Return a file called "concat.txt"
      'concat.txt': result
    }
  }
}
<|endoftext|>


<commit_before><commit_msg>Remove redundant file<commit_after><|endoftext|>


<commit_before><commit_msg>Moved sequence.main into the CharACTers constructor. Added reset() and makeSequence() methods.<commit_after><|endoftext|>


<commit_before>function printFunc(divName)
{
	var printContents = document.getElementById(divName).innerHTML;
    var originalContents = document.body.innerHTML;

    document.body.innerHTML = printContents;

    window.print();

    document.body.innerHTML = originalContents;

 	// window.print();

	// var doc = new jsPDF()
	// var input = document.getElementById("primaryHousing").value;
	// doc.text("My Demographics", 70,10)
	// doc.text("Primary Housing Type: " + input, 10, 20)
	// doc.save('test.pdf')
}

window.onload = function() {
    document.getElementById('issq1optional').style.display = 'none';
    document.getElementById('issq6optional').style.display = 'none';
    document.getElementById('engq1optional').style.display = 'none';
    document.getElementById('orgq3optional').style.display = 'none';
    document.getElementById('mydemographics').style.display = 'none';
    document.getElementById('myorganization').style.display = 'none';
    document.getElementById('myissue').style.display = 'none';
    document.getElementById('myengagement').style.display = 'none';

    var fbElements = document.getElementsByClassName('fb');
    for (var i = 0, len = fbElements.length; i < len; i++) {
        fbElements[i].style.display = 'none';
    }

    sectionCheck();
}

function yesnoCheckissue() {
    if (document.getElementById('issq1y').checked) {
        document.getElementById('issq1optional').style.display = 'block';
        document.getElementById('issq1fb').style.display = 'none';
    }
    else if(document.getElementById('issq1n').checked) {
        document.getElementById('issq1optional').style.display = 'none';
        document.getElementById('issq1fb').style.display = 'block';
    }

    if (document.getElementById('issq2y').checked) {
        document.getElementById('issq2optional').style.display = 'block';
        document.getElementById('issq2fb').style.display = 'none';
    }
    else if(document.getElementById('issq2n').checked) {
        document.getElementById('issq2optional').style.display = 'none';
        document.getElementById('issq2fb').style.display = 'block';
    }

    if (document.getElementById('issq3y').checked) {
        document.getElementById('issq3optional').style.display = 'block';
        document.getElementById('issq3fb').style.display = 'none';
        document.getElementById('issq4').style.display = 'block';
    }
    else if(document.getElementById('issq3n').checked) {
        document.getElementById('issq3optional').style.display = 'none';
        document.getElementById('issq3fb').style.display = 'block';
        document.getElementById('issq4').style.display = 'none';
    }

    if (document.getElementById('issq4y').checked) {
        document.getElementById('issq4optional').style.display = 'block';
        document.getElementById('issq4fb').style.display = 'none';
    }
    else if(document.getElementById('issq4n').checked) {
        document.getElementById('issq4optional').style.display = 'none';
        document.getElementById('issq4fb').style.display = 'block';
    }

    if (document.getElementById('issq5y').checked) {
        document.getElementById('issq5optional').style.display = 'block';
        document.getElementById('issq5fb').style.display = 'none';
    }
    else if(document.getElementById('issq5n').checked) {
        document.getElementById('issq5optional').style.display = 'none';
        document.getElementById('issq5fb').style.display = 'block';
    }

    if (document.getElementById('issq6y').checked) {
        document.getElementById('issq6optional').style.display = 'block';
        document.getElementById('issq6fb').style.display = 'none';
    }
    else if(document.getElementById('issq6n').checked) {
        document.getElementById('issq6optional').style.display = 'none';
        document.getElementById('issq6fb').style.display = 'block';
    }

    if (document.getElementById('issq7y').checked) {
        document.getElementById('issq7optional').style.display = 'block';
        document.getElementById('issq7fb').style.display = 'none';
    }
    else if(document.getElementById('issq7n').checked) {
        document.getElementById('issq7optional').style.display = 'none';
        document.getElementById('issq7fb').style.display = 'block';
    }

    if (document.getElementById('issq8y').checked) {
        document.getElementById('issq8optional').style.display = 'block';
        document.getElementById('issq8fb').style.display = 'none';
        document.getElementById('issq9').style.display = 'block';
    }
    else if(document.getElementById('issq8n').checked) {
        document.getElementById('issq8optional').style.display = 'none';
        document.getElementById('issq8fb').style.display = 'block';
        document.getElementById('issq9').style.display = 'none';
    }

    if (document.getElementById('issq9y').checked) {
        document.getElementById('issq9optional').style.display = 'block';
        document.getElementById('issq9fb').style.display = 'none';
    }
    else if(document.getElementById('issq9n').checked) {
        document.getElementById('issq9optional').style.display = 'none';
        document.getElementById('issq9fb').style.display = 'block';
    }

    if (document.getElementById('issq10y').checked) {
        document.getElementById('issq10optional').style.display = 'block';
        document.getElementById('issq10fb').style.display = 'none';
    }
    else if(document.getElementById('issq10n').checked) {
        document.getElementById('issq10optional').style.display = 'none';
        document.getElementById('issq10fb').style.display = 'block';
    }

    if (document.getElementById('issq11y').checked) {
        document.getElementById('issq11optional').style.display = 'block';
        document.getElementById('issq11fb').style.display = 'none';
    }
    else if(document.getElementById('issq11n').checked) {
        document.getElementById('issq11optional').style.display = 'none';
        document.getElementById('issq11fb').style.display = 'block';
    }

    if (document.getElementById('issq12y').checked) {
        document.getElementById('issq12optional').style.display = 'block';
        document.getElementById('issq12fb').style.display = 'none';
    }
    else if(document.getElementById('issq12n').checked) {
        document.getElementById('issq12optional').style.display = 'none';
        document.getElementById('issq12fb').style.display = 'block';
    }

    if (document.getElementById('issq13y').checked) {
        document.getElementById('issq13optional').style.display = 'block';
        document.getElementById('issq13fb').style.display = 'none';
    }
    else if(document.getElementById('issq13n').checked) {
        document.getElementById('issq13optional').style.display = 'none';
        document.getElementById('issq13fb').style.display = 'block';
    }

    if (document.getElementById('issq14y').checked) {
        document.getElementById('issq14optional').style.display = 'block';
        document.getElementById('issq14fb').style.display = 'none';
    }
    else if(document.getElementById('issq14n').checked) {
        document.getElementById('issq14optional').style.display = 'none';
        document.getElementById('issq14fb').style.display = 'block';
    }

    if (document.getElementById('issq15y').checked) {
        document.getElementById('issq15optional').style.display = 'block';
        document.getElementById('issq15fb').style.display = 'none';
    }
    else if(document.getElementById('issq15n').checked) {
        document.getElementById('issq15optional').style.display = 'none';
        document.getElementById('issq15fb').style.display = 'block';
    }

    if (document.getElementById('issq16y').checked) {
        document.getElementById('issq16optional').style.display = 'block';
        document.getElementById('issq16fb').style.display = 'none';
    }
    else if(document.getElementById('issq16n').checked) {
        document.getElementById('issq16optional').style.display = 'none';
        document.getElementById('issq16fb').style.display = 'block';
    }
}

function yesnoCheckorg() {
    if (document.getElementById('orgq1y').checked) {
        document.getElementById('orgq1optional').style.display = 'block';
        document.getElementById('orgq1fb').style.display = 'none';
    }
    else if(document.getElementById('orgq1n').checked) {
        document.getElementById('orgq1optional').style.display = 'none';
        document.getElementById('orgq1fb').style.display = 'block';
    }

    if (document.getElementById('orgq2y').checked) {
        document.getElementById('orgq2optional').style.display = 'block';
        document.getElementById('orgq2fb').style.display = 'none';
    }
    else if(document.getElementById('orgq2n').checked) {
        document.getElementById('orgq2optional').style.display = 'none';
        document.getElementById('orgq2fb').style.display = 'block';
    }

    if (document.getElementById('orgq3y').checked) {
        document.getElementById('orgq3optional').style.display = 'block';
        document.getElementById('orgq3fb').style.display = 'none';
    }
    else if(document.getElementById('orgq3n').checked) {
        document.getElementById('orgq3optional').style.display = 'none';
        document.getElementById('orgq3fb').style.display = 'block';
    }
}

function yesnoCheckeng() {
    if (document.getElementById('engq1y').checked) {
        document.getElementById('engq1optional').style.display = 'block';
        document.getElementById('engq1fb').style.display = 'none';
    }
    else if(document.getElementById('engq1n').checked) {
        document.getElementById('engq1optional').style.display = 'none';
        document.getElementById('engq1fb').style.display = 'block';
    }

    if (document.getElementById('engq2y').checked) {
        document.getElementById('engq2optional').style.display = 'block';
        document.getElementById('engq2fb').style.display = 'none';
    }
    else if(document.getElementById('engq2n').checked) {
        document.getElementById('engq2optional').style.display = 'none';
        document.getElementById('engq2fb').style.display = 'block';
    }

    if (document.getElementById('engq3y').checked) {
        document.getElementById('engq3optional').style.display = 'block';
        document.getElementById('engq3fb').style.display = 'none';
    }
    else if(document.getElementById('engq3n').checked) {
        document.getElementById('engq3optional').style.display = 'none';
        document.getElementById('engq3fb').style.display = 'block';
    }

    if (document.getElementById('engq4y').checked) {
        document.getElementById('engq4optional').style.display = 'block';
        document.getElementById('engq4fb').style.display = 'none';
    }
    else if(document.getElementById('engq4n').checked) {
        document.getElementById('engq4optional').style.display = 'none';
        document.getElementById('engq4fb').style.display = 'block';
    }
}

// function checkAllInput() {
//     document.getElementById('orgq3fbtext').innerHTML = document.getElementById('orgqe').value;
//     document.getElementById('issq1fbtext').innerHTML = document.getElementById('issq1input').value;
//     document.getElementById('engq1fbtext').innerHTML = document.getElementById('engq1input').value;
// }

function sectionCheck() {
	if (document.getElementById('demographicscheck').checked) {
        document.getElementById('mydemographics').style.display = 'block';
    } else if(!document.getElementById('demographicscheck').checked) {
        document.getElementById('mydemographics').style.display = 'none';
    }

    if(document.getElementById('organizationcheck').checked) {
        document.getElementById('myorganization').style.display = 'block';
    } else if(!document.getElementById('organizationcheck').checked) {
        document.getElementById('myorganization').style.display = 'none';
    }

    if(document.getElementById('issuecheck').checked) {
        document.getElementById('myissue').style.display = 'block';
    } else if(!document.getElementById('issuecheck').checked) {
        document.getElementById('myissue').style.display = 'none';
    }

    if(document.getElementById('engagementcheck').checked) {
        document.getElementById('myengagement').style.display = 'block';
    } else if(!document.getElementById('engagementcheck').checked) {
        document.getElementById('myengagement').style.display = 'none';
    }
    if ((document.getElementById('demographicscheck').checked) || (document.getElementById('organizationcheck').checked) || (document.getElementById('issuecheck').checked) || (document.getElementById('engagementcheck').checked)) {
    	document.getElementById('printbutton').style.display = 'block';
    	document.getElementById('orginfo').style.display = 'block';
    } else {
    	document.getElementById('printbutton').style.display = 'none';
    	document.getElementById('orginfo').style.display = 'none';
    }
}<commit_msg>commented code in myjs<commit_after>function printFunc(divName)
{
	var printContents = document.getElementById(divName).innerHTML;
    var originalContents = document.body.innerHTML;

    document.body.innerHTML = printContents;

    window.print();

    document.body.innerHTML = originalContents;

 	// document.getElementById(divName).print();

	// var doc = new jsPDF()
	// var input = document.getElementById("primaryHousing").value;
	// doc.text("My Demographics", 70,10)
	// doc.text("Primary Housing Type: " + input, 10, 20)
	// doc.save('test.pdf')
}

window.onload = function() {
    document.getElementById('issq1optional').style.display = 'none';
    document.getElementById('issq6optional').style.display = 'none';
    document.getElementById('engq1optional').style.display = 'none';
    document.getElementById('orgq3optional').style.display = 'none';
    document.getElementById('mydemographics').style.display = 'none';
    document.getElementById('myorganization').style.display = 'none';
    document.getElementById('myissue').style.display = 'none';
    document.getElementById('myengagement').style.display = 'none';

    var fbElements = document.getElementsByClassName('fb');
    for (var i = 0, len = fbElements.length; i < len; i++) {
        fbElements[i].style.display = 'none';
    }

    sectionCheck();
}

function yesnoCheckissue() {
    if (document.getElementById('issq1y').checked) {
        document.getElementById('issq1optional').style.display = 'block';
        document.getElementById('issq1fb').style.display = 'none';
    }
    else if(document.getElementById('issq1n').checked) {
        document.getElementById('issq1optional').style.display = 'none';
        document.getElementById('issq1fb').style.display = 'block';
    }

    if (document.getElementById('issq2y').checked) {
        document.getElementById('issq2optional').style.display = 'block';
        document.getElementById('issq2fb').style.display = 'none';
    }
    else if(document.getElementById('issq2n').checked) {
        document.getElementById('issq2optional').style.display = 'none';
        document.getElementById('issq2fb').style.display = 'block';
    }

    if (document.getElementById('issq3y').checked) {
        document.getElementById('issq3optional').style.display = 'block';
        document.getElementById('issq3fb').style.display = 'none';
        document.getElementById('issq4').style.display = 'block';
    }
    else if(document.getElementById('issq3n').checked) {
        document.getElementById('issq3optional').style.display = 'none';
        document.getElementById('issq3fb').style.display = 'block';
        document.getElementById('issq4').style.display = 'none';
    }

    if (document.getElementById('issq4y').checked) {
        document.getElementById('issq4optional').style.display = 'block';
        document.getElementById('issq4fb').style.display = 'none';
    }
    else if(document.getElementById('issq4n').checked) {
        document.getElementById('issq4optional').style.display = 'none';
        document.getElementById('issq4fb').style.display = 'block';
    }

    if (document.getElementById('issq5y').checked) {
        document.getElementById('issq5optional').style.display = 'block';
        document.getElementById('issq5fb').style.display = 'none';
    }
    else if(document.getElementById('issq5n').checked) {
        document.getElementById('issq5optional').style.display = 'none';
        document.getElementById('issq5fb').style.display = 'block';
    }

    if (document.getElementById('issq6y').checked) {
        document.getElementById('issq6optional').style.display = 'block';
        document.getElementById('issq6fb').style.display = 'none';
    }
    else if(document.getElementById('issq6n').checked) {
        document.getElementById('issq6optional').style.display = 'none';
        document.getElementById('issq6fb').style.display = 'block';
    }

    if (document.getElementById('issq7y').checked) {
        document.getElementById('issq7optional').style.display = 'block';
        document.getElementById('issq7fb').style.display = 'none';
    }
    else if(document.getElementById('issq7n').checked) {
        document.getElementById('issq7optional').style.display = 'none';
        document.getElementById('issq7fb').style.display = 'block';
    }

    if (document.getElementById('issq8y').checked) {
        document.getElementById('issq8optional').style.display = 'block';
        document.getElementById('issq8fb').style.display = 'none';
        document.getElementById('issq9').style.display = 'block';
    }
    else if(document.getElementById('issq8n').checked) {
        document.getElementById('issq8optional').style.display = 'none';
        document.getElementById('issq8fb').style.display = 'block';
        document.getElementById('issq9').style.display = 'none';
    }

    if (document.getElementById('issq9y').checked) {
        document.getElementById('issq9optional').style.display = 'block';
        document.getElementById('issq9fb').style.display = 'none';
    }
    else if(document.getElementById('issq9n').checked) {
        document.getElementById('issq9optional').style.display = 'none';
        document.getElementById('issq9fb').style.display = 'block';
    }

    if (document.getElementById('issq10y').checked) {
        document.getElementById('issq10optional').style.display = 'block';
        document.getElementById('issq10fb').style.display = 'none';
    }
    else if(document.getElementById('issq10n').checked) {
        document.getElementById('issq10optional').style.display = 'none';
        document.getElementById('issq10fb').style.display = 'block';
    }

    if (document.getElementById('issq11y').checked) {
        document.getElementById('issq11optional').style.display = 'block';
        document.getElementById('issq11fb').style.display = 'none';
    }
    else if(document.getElementById('issq11n').checked) {
        document.getElementById('issq11optional').style.display = 'none';
        document.getElementById('issq11fb').style.display = 'block';
    }

    if (document.getElementById('issq12y').checked) {
        document.getElementById('issq12optional').style.display = 'block';
        document.getElementById('issq12fb').style.display = 'none';
    }
    else if(document.getElementById('issq12n').checked) {
        document.getElementById('issq12optional').style.display = 'none';
        document.getElementById('issq12fb').style.display = 'block';
    }

    if (document.getElementById('issq13y').checked) {
        document.getElementById('issq13optional').style.display = 'block';
        document.getElementById('issq13fb').style.display = 'none';
    }
    else if(document.getElementById('issq13n').checked) {
        document.getElementById('issq13optional').style.display = 'none';
        document.getElementById('issq13fb').style.display = 'block';
    }

    if (document.getElementById('issq14y').checked) {
        document.getElementById('issq14optional').style.display = 'block';
        document.getElementById('issq14fb').style.display = 'none';
    }
    else if(document.getElementById('issq14n').checked) {
        document.getElementById('issq14optional').style.display = 'none';
        document.getElementById('issq14fb').style.display = 'block';
    }

    if (document.getElementById('issq15y').checked) {
        document.getElementById('issq15optional').style.display = 'block';
        document.getElementById('issq15fb').style.display = 'none';
    }
    else if(document.getElementById('issq15n').checked) {
        document.getElementById('issq15optional').style.display = 'none';
        document.getElementById('issq15fb').style.display = 'block';
    }

    if (document.getElementById('issq16y').checked) {
        document.getElementById('issq16optional').style.display = 'block';
        document.getElementById('issq16fb').style.display = 'none';
    }
    else if(document.getElementById('issq16n').checked) {
        document.getElementById('issq16optional').style.display = 'none';
        document.getElementById('issq16fb').style.display = 'block';
    }
}

function yesnoCheckorg() {
    if (document.getElementById('orgq1y').checked) {
        document.getElementById('orgq1optional').style.display = 'block';
        document.getElementById('orgq1fb').style.display = 'none';
    }
    else if(document.getElementById('orgq1n').checked) {
        document.getElementById('orgq1optional').style.display = 'none';
        document.getElementById('orgq1fb').style.display = 'block';
    }

    if (document.getElementById('orgq2y').checked) {
        document.getElementById('orgq2optional').style.display = 'block';
        document.getElementById('orgq2fb').style.display = 'none';
    }
    else if(document.getElementById('orgq2n').checked) {
        document.getElementById('orgq2optional').style.display = 'none';
        document.getElementById('orgq2fb').style.display = 'block';
    }

    if (document.getElementById('orgq3y').checked) {
        document.getElementById('orgq3optional').style.display = 'block';
        document.getElementById('orgq3fb').style.display = 'none';
    }
    else if(document.getElementById('orgq3n').checked) {
        document.getElementById('orgq3optional').style.display = 'none';
        document.getElementById('orgq3fb').style.display = 'block';
    }
}

function yesnoCheckeng() {
    if (document.getElementById('engq1y').checked) {
        document.getElementById('engq1optional').style.display = 'block';
        document.getElementById('engq1fb').style.display = 'none';
    }
    else if(document.getElementById('engq1n').checked) {
        document.getElementById('engq1optional').style.display = 'none';
        document.getElementById('engq1fb').style.display = 'block';
    }

    if (document.getElementById('engq2y').checked) {
        document.getElementById('engq2optional').style.display = 'block';
        document.getElementById('engq2fb').style.display = 'none';
    }
    else if(document.getElementById('engq2n').checked) {
        document.getElementById('engq2optional').style.display = 'none';
        document.getElementById('engq2fb').style.display = 'block';
    }

    if (document.getElementById('engq3y').checked) {
        document.getElementById('engq3optional').style.display = 'block';
        document.getElementById('engq3fb').style.display = 'none';
    }
    else if(document.getElementById('engq3n').checked) {
        document.getElementById('engq3optional').style.display = 'none';
        document.getElementById('engq3fb').style.display = 'block';
    }

    if (document.getElementById('engq4y').checked) {
        document.getElementById('engq4optional').style.display = 'block';
        document.getElementById('engq4fb').style.display = 'none';
    }
    else if(document.getElementById('engq4n').checked) {
        document.getElementById('engq4optional').style.display = 'none';
        document.getElementById('engq4fb').style.display = 'block';
    }
}

// function checkAllInput() {
//     document.getElementById('orgq3fbtext').innerHTML = document.getElementById('orgqe').value;
//     document.getElementById('issq1fbtext').innerHTML = document.getElementById('issq1input').value;
//     document.getElementById('engq1fbtext').innerHTML = document.getElementById('engq1input').value;
// }

function sectionCheck() {
	if (document.getElementById('demographicscheck').checked) {
        document.getElementById('mydemographics').style.display = 'block';
    } else if(!document.getElementById('demographicscheck').checked) {
        document.getElementById('mydemographics').style.display = 'none';
    }

    if(document.getElementById('organizationcheck').checked) {
        document.getElementById('myorganization').style.display = 'block';
    } else if(!document.getElementById('organizationcheck').checked) {
        document.getElementById('myorganization').style.display = 'none';
    }

    if(document.getElementById('issuecheck').checked) {
        document.getElementById('myissue').style.display = 'block';
    } else if(!document.getElementById('issuecheck').checked) {
        document.getElementById('myissue').style.display = 'none';
    }

    if(document.getElementById('engagementcheck').checked) {
        document.getElementById('myengagement').style.display = 'block';
    } else if(!document.getElementById('engagementcheck').checked) {
        document.getElementById('myengagement').style.display = 'none';
    }
    if ((document.getElementById('demographicscheck').checked) || (document.getElementById('organizationcheck').checked) || (document.getElementById('issuecheck').checked) || (document.getElementById('engagementcheck').checked)) {
    	document.getElementById('printbutton').style.display = 'block';
    	document.getElementById('orginfo').style.display = 'block';
    } else {
    	document.getElementById('printbutton').style.display = 'none';
    	document.getElementById('orginfo').style.display = 'none';
    }
}<|endoftext|>


<commit_before>const browserify      = require('browserify');
const bundleProcessor = require('./bundleProcessor');

const config = {
  debug: true,
  entries: 'index.js',
  standalone: 'interact',

  transform: [[ 'babelify', {} ]],

  cache: {},
  packageCache: {},
};

const b = browserify(config);

const pwdRegex   = new RegExp(`^${process.env.PWD}.`);
const noMetadata = process.argv.includes('--no-metadata');
const watch      = process.argv.includes('--watch');
const docs       = process.argv.includes('--docs')? require('./docs') : null;

if (watch) {
  b.plugin(require('watchify'));
  b.plugin(require('errorify'));

  b.on('update', update);
  b.on('log', msg => console.log(msg));
}
else {
  process.on('beforeExit', () => {
    console.log(' done.');
  });
}

function update (ids) {
  if (docs) {
    docs({
      stdio: ['ignore', 'ignore', 'inherit'],
    });
  }

  if (watch) {
    console.log('Bundling...');
  }
  else {
    process.stdout.write('Bundling...');
  }

  if (ids) {
    console.log(ids.reduce((formatted, id) => {
      return `${formatted}\n    ${id.replace(pwdRegex, '')}`;
    }, ''));
  }

  bundleProcessor({
    noMetadata,
    bundleStream: b.bundle(),
    headerFile: 'src/header.js',
    minHeaderFile: 'src/minHeader.js',
  });
}

update();
<commit_msg>build: set babel option compact: false<commit_after>const browserify      = require('browserify');
const bundleProcessor = require('./bundleProcessor');

const config = {
  debug: true,
  entries: 'index.js',
  standalone: 'interact',

  transform: [[ 'babelify', { compact: false } ]],

  cache: {},
  packageCache: {},
};

const b = browserify(config);

const pwdRegex   = new RegExp(`^${process.env.PWD}.`);
const noMetadata = process.argv.includes('--no-metadata');
const watch      = process.argv.includes('--watch');
const docs       = process.argv.includes('--docs')? require('./docs') : null;

if (watch) {
  b.plugin(require('watchify'));
  b.plugin(require('errorify'));

  b.on('update', update);
  b.on('log', msg => console.log(msg));
}
else {
  process.on('beforeExit', () => {
    console.log(' done.');
  });
}

function update (ids) {
  if (docs) {
    docs({
      stdio: ['ignore', 'ignore', 'inherit'],
    });
  }

  if (watch) {
    console.log('Bundling...');
  }
  else {
    process.stdout.write('Bundling...');
  }

  if (ids) {
    console.log(ids.reduce((formatted, id) => {
      return `${formatted}\n    ${id.replace(pwdRegex, '')}`;
    }, ''));
  }

  bundleProcessor({
    noMetadata,
    bundleStream: b.bundle(),
    headerFile: 'src/header.js',
    minHeaderFile: 'src/minHeader.js',
  });
}

update();
<|endoftext|>


<commit_before>var cp = require('child_process');
var path = require('path');
var util = require('../../util');
var config = util.config;

cp.spawn('node', [path.join(__dirname, 'weinre.js'), '--boundHost', config.WEINRE_HOST, '--httpPort', config.weinreport], {
	stdio: [ 0, 1, 2 ]
});<commit_msg>add weinre<commit_after>var cp = require('child_process');
var path = require('path');
var util = require('../../util');
var config = util.config;

cp.spawn('node', [path.join(__dirname, 'weinre.js'), '--boundHost',
                  config.WEINRE_HOST, '--httpPort', config.weinreport], {
	stdio: [ 0, 1, 2 ]
});<|endoftext|>


<commit_before>import $ from "jquery";

import * as overlays from "./overlays";
import {page_params} from "./page_params";
import {realm_user_settings_defaults} from "./realm_user_settings_defaults";
import * as settings_display from "./settings_display";
import * as settings_notifications from "./settings_notifications";
import * as settings_org from "./settings_org";

export const realm_default_settings_panel = {};

export function maybe_disable_widgets() {
    if (!page_params.is_admin) {
        $(".organization-box [data-name='organization-level-user-defaults']")
            .find("input, select")
            .prop("disabled", true);

        $(".organization-box [data-name='organization-level-user-defaults']")
            .find(".play_notification_sound")
            .addClass("control-label-disabled");
    }
}

export function update_page(property) {
    if (!overlays.settings_open()) {
        return;
    }
    const container = $(realm_default_settings_panel.container);
    const value = realm_user_settings_defaults[property];

    if (property === "emojiset") {
        container.find(`input[value=${CSS.escape(value)}]`).prop("checked", true);
        return;
    }
    const input_elem = container.find(`[name=${CSS.escape(property)}]`);
    settings_org.set_input_element_value(input_elem, value);
}

export function set_up() {
    const container = $(realm_default_settings_panel.container);
    settings_display.set_up(realm_default_settings_panel);
    settings_notifications.set_up(realm_default_settings_panel);

    settings_org.register_save_discard_widget_handlers(
        container,
        "/json/realm/user_settings_defaults",
        true,
    );

    maybe_disable_widgets();
}

export function initialize() {
    realm_default_settings_panel.container = "#realm-user-default-settings";
    realm_default_settings_panel.settings_object = realm_user_settings_defaults;
    realm_default_settings_panel.notification_sound_elem =
        "#realm-default-notification-sound-audio";
    realm_default_settings_panel.for_realm_settings = true;
}
<commit_msg>settings: Fix live update code for twenty_four_hour_time setting.<commit_after>import $ from "jquery";

import * as overlays from "./overlays";
import {page_params} from "./page_params";
import {realm_user_settings_defaults} from "./realm_user_settings_defaults";
import * as settings_display from "./settings_display";
import * as settings_notifications from "./settings_notifications";
import * as settings_org from "./settings_org";

export const realm_default_settings_panel = {};

export function maybe_disable_widgets() {
    if (!page_params.is_admin) {
        $(".organization-box [data-name='organization-level-user-defaults']")
            .find("input, select")
            .prop("disabled", true);

        $(".organization-box [data-name='organization-level-user-defaults']")
            .find(".play_notification_sound")
            .addClass("control-label-disabled");
    }
}

export function update_page(property) {
    if (!overlays.settings_open()) {
        return;
    }
    const container = $(realm_default_settings_panel.container);
    let value = realm_user_settings_defaults[property];

    if (property === "emojiset") {
        container.find(`input[value=${CSS.escape(value)}]`).prop("checked", true);
        return;
    }
    if (property === "twenty_four_hour_time") {
        value = value.toString();
    }

    const input_elem = container.find(`[name=${CSS.escape(property)}]`);
    settings_org.set_input_element_value(input_elem, value);
}

export function set_up() {
    const container = $(realm_default_settings_panel.container);
    settings_display.set_up(realm_default_settings_panel);
    settings_notifications.set_up(realm_default_settings_panel);

    settings_org.register_save_discard_widget_handlers(
        container,
        "/json/realm/user_settings_defaults",
        true,
    );

    maybe_disable_widgets();
}

export function initialize() {
    realm_default_settings_panel.container = "#realm-user-default-settings";
    realm_default_settings_panel.settings_object = realm_user_settings_defaults;
    realm_default_settings_panel.notification_sound_elem =
        "#realm-default-notification-sound-audio";
    realm_default_settings_panel.for_realm_settings = true;
}
<|endoftext|>


<commit_before>/*--------------------------------------------------------------------------*/
/*           Copyright (c) 2015 by DiamondB Software, llc.                  */
/*                           All Rights Reserved.                           */
/*           THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE OF DiamondB.       */
/*           The copyright notice above does not evidence any               */
/*           actual or intended publication of such source code.            */
/*--------------------------------------------------------------------------*/
(function () {
	"use strict";

	var fieldData = {
		title: "Haylage Report",
		desc: (new Date().getFullYear()) + " 1st",
		hayLbs: 2000,
		dm: 0.88,

		hayTypes:[
		{
			title: "Premium Dairy Hay",
			protMin: 0.23,
			protMax: 0.24,
			deliver: 240.0
		},
		{
			title: "Avg Dairy Hay",
			protMin: 0.21,
			protMax: 0.23,
			deliver: 230.0
		},
		{
			title: "Dry Cow/Feeder Hay",
			protMin: 0.19,
			protMax: 0.21,
			deliver: 220.0
		}],
		lab: {
			lbs: 2000,
			dm:0.3,
			prot:0.2088
		},
		swathTons: 1053.5,
		swathAcre: 113,
		swatchCost: 20.0,
		chop: 17.00,
		mileage: 0.0,
		innoculant: 0.85,
		adfTest: 0.00,

		sharePct: 0.2
	};

	if (window.localStorage) {
		var str = localStorage.getItem("fieldData");
		if (str) {
			var data = JSON.parse(str);
			_.assign(fieldData,data);
		}
	}

	var app = angular.module('fieldApp', ['ngRoute']);

	app.config(function($routeProvider){
		$routeProvider
			.when('/', {
				controller:"editCtrl as field",
				templateUrl:"editView.html"
			})
			.when("/print", {
				controller:"printCtrl as field",
				templateUrl:"printView.html"
			})
			.otherwise({redirectTo:'/'});
	});

	app.controller('editCtrl', function(fieldService){
		var fieldVm = this;
		fieldVm.data = fieldData;
		fieldVm.calculate = function(){
			calculate(fieldData);
			// probably not the correct place for this
			localStorage.setItem("fieldData", JSON.stringify(fieldData));
		};

		calculate(fieldData);

		return fieldVm;
	});

	app.controller('printCtrl', function(fieldService){
		var fieldVm = this;
		fieldVm.data = fieldData;

		calculate(fieldData);

		var hay = findHayForLabProt(fieldData);
		fieldData.selectedHayType = [hay];

		return fieldVm;
	});

	app.service('fieldService', function($q){
		return function(){
			var deferrred = $q.defer();

			// currently data is static
			deferrred.resolve(fieldData);

			return deferrred.promise;
		}
	});

	app.filter('percentage', ['$filter', function ($filter) {
		return function (input, decimals) {
			return $filter('number')(input * 100, decimals) + '%';
		};
	}]);

	function calculate(fieldData){
		console.log("calculating values");
		calcHayTypes(fieldData);
		calcLab(fieldData);
		calcProcessing(fieldData);
		return fieldData;

		function calcHayTypes(fieldData){
			_.each(fieldData.hayTypes, function(h){
				var pmin = new BigNumber(h.protMin);
				var pmax = new BigNumber(h.protMax);
				var avgProt = pmin.add(pmax).dividedBy(2); // (h.protMin + h.protMax) / 2;
				console.log("" + pmin + ": avgProt="+ avgProt);

				var lbs = 2000; // fieldData.hayLbs
				var dm = 0.88; // fieldData.dm
				h.lbsPerProt = new BigNumber(lbs * dm * avgProt);
				h.basePrice = new BigNumber(h.deliver).dividedBy(h.lbsPerProt);

			});
		}

		function calcLab(fieldData){
			var lab = fieldData.lab;
			lab.protPerTon = lab.lbs * lab.dm * lab.prot;
		}

		function calcProcessing(fieldData){
			var d = fieldData;
			var basePrice = getHayBasePrice(d.prot);

			d.tonPerAcre = new BigNumber(d.swathTons).dividedBy(d.swathAcre);
			d.costPerAcre = new BigNumber(d.swatchCost).dividedBy(d.tonPerAcre);
			d.costPerTon = d.costPerAcre + d.chop + d. mileage + d.innoculant + d.adfTest;
			d.costPerProt = new BigNumber(d.costPerTon).dividedBy(d.lab.protPerTon);
			d.costLbProt = basePrice - d.costPerProt;

			d.costHayPerTon = d.costLbProt * d.lab.protPerTon;

			d.totalCost = d.costHayPerTon * d.swathTons;

			d.shareCost = d.totalCost * d.sharePct;
		}

		function getHayBasePrice(labProt){
			var hay = findHayForLabProt(fieldData);
			if (!hay){
				hay = _.first(fieldData.hayTypes);
			}
			return hay.basePrice;
		}
	}

	function findHayForLabProt(fieldData){
		var labProt = fieldData.lab.prot;
		var hay = _.find(fieldData.hayTypes, function(h){
			return h.protMin <= labProt && h.protMax > labProt;
		});
		return hay;

	}

}());<commit_msg>maths is hard in js<commit_after>/*--------------------------------------------------------------------------*/
/*           Copyright (c) 2015 by DiamondB Software, llc.                  */
/*                           All Rights Reserved.                           */
/*           THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE OF DiamondB.       */
/*           The copyright notice above does not evidence any               */
/*           actual or intended publication of such source code.            */
/*--------------------------------------------------------------------------*/
(function () {
	"use strict";

	var fieldData = {
		title: "Haylage Report",
		desc: (new Date().getFullYear()) + " 1st",
		hayLbs: 2000,
		dm: 0.88,

		hayTypes:[
		{
			title: "Premium Dairy Hay",
			protMin: 0.23,
			protMax: 0.24,
			deliver: 240.0
		},
		{
			title: "Avg Dairy Hay",
			protMin: 0.21,
			protMax: 0.23,
			deliver: 230.0
		},
		{
			title: "Dry Cow/Feeder Hay",
			protMin: 0.19,
			protMax: 0.21,
			deliver: 220.0
		}],
		lab: {
			lbs: 2000,
			dm:0.3,
			prot:0.2088
		},
		swathTons: 1053.5,
		swathAcre: 113,
		swatchCost: 20.0,
		chop: 17.00,
		mileage: 0.0,
		innoculant: 0.85,
		adfTest: 0.00,

		sharePct: 0.2
	};

	if (window.localStorage) {
		var str = localStorage.getItem("fieldData");
		if (str) {
			var data = JSON.parse(str);
			_.assign(fieldData,data);
		}
	}

	var app = angular.module('fieldApp', ['ngRoute']);

	app.config(function($routeProvider){
		$routeProvider
			.when('/', {
				controller:"editCtrl as field",
				templateUrl:"editView.html"
			})
			.when("/print", {
				controller:"printCtrl as field",
				templateUrl:"printView.html"
			})
			.otherwise({redirectTo:'/'});
	});

	app.controller('editCtrl', function(fieldService){
		var fieldVm = this;
		fieldVm.data = fieldData;
		fieldVm.calculate = function(){
			calculate(fieldData);
			// probably not the correct place for this
			localStorage.setItem("fieldData", JSON.stringify(fieldData));
		};

		calculate(fieldData);

		return fieldVm;
	});

	app.controller('printCtrl', function(fieldService){
		var fieldVm = this;
		fieldVm.data = fieldData;

		calculate(fieldData);

		var hay = findHayForLabProt(fieldData);
		fieldData.selectedHayType = [hay];

		return fieldVm;
	});

	app.service('fieldService', function($q){
		return function(){
			var deferrred = $q.defer();

			// currently data is static
			deferrred.resolve(fieldData);

			return deferrred.promise;
		}
	});

	app.filter('percentage', ['$filter', function ($filter) {
		return function (input, decimals) {
			return $filter('number')(input * 100, decimals) + '%';
		};
	}]);

	function calculate(fieldData){
		console.log("calculating values");
		calcHayTypes(fieldData);
		calcLab(fieldData);
		calcProcessing(fieldData);
		return fieldData;

		function calcHayTypes(fieldData){
			_.each(fieldData.hayTypes, function(h){
				var pmin = new BigNumber(h.protMin);
				var pmax = new BigNumber(h.protMax);
				var avgProt = pmin.add(pmax).dividedBy(2); // (h.protMin + h.protMax) / 2;
				console.log("" + pmin + ": avgProt="+ avgProt);

				var lbs = 2000; // fieldData.hayLbs
				var dm = 0.88; // fieldData.dm
				h.lbsPerProt = new BigNumber(lbs * dm * avgProt);
				h.basePrice = new BigNumber(h.deliver).dividedBy(h.lbsPerProt);

			});
		}

		function calcLab(fieldData){
			var lab = fieldData.lab;
			lab.protPerTon = lab.lbs * lab.dm * lab.prot;
		}

		function calcProcessing(fieldData){
			var d = fieldData;
			var basePrice = getHayBasePrice(d.prot);

			d.tonPerAcre = new BigNumber(d.swathTons).dividedBy(d.swathAcre);
			d.costPerAcre = new BigNumber(d.swatchCost).dividedBy(d.tonPerAcre);
			console.log('cost per acre '+ d.costPerAcre);

			d.costPerTon = d.costPerAcre + d.chop + d. mileage + d.innoculant + d.adfTest;
			d.costPerProt = new BigNumber(d.costPerTon).dividedBy(d.lab.protPerTon);
			d.costLbProt = basePrice - d.costPerProt;

			d.costHayPerTon = d.costLbProt * d.lab.protPerTon;

			d.totalCost = d.costHayPerTon * d.swathTons;

			d.shareCost = d.totalCost * d.sharePct;
		}

		function getHayBasePrice(labProt){
			var hay = findHayForLabProt(fieldData);
			if (!hay){
				hay = _.first(fieldData.hayTypes);
			}
			return hay.basePrice;
		}
	}

	function findHayForLabProt(fieldData){
		var labProt = fieldData.lab.prot;
		var hay = _.find(fieldData.hayTypes, function(h){
			return h.protMin <= labProt && h.protMax > labProt;
		});
		return hay;

	}

}());<|endoftext|>


<commit_before>var path = require('path')
var config = require('../config')
var ExtractTextPlugin = require('extract-text-webpack-plugin')

exports.assetsPath = function (_path) {
  var assetsSubDirectory = process.env.NODE_ENV === 'production'
    ? config.build.assetsSubDirectory
    : config.dev.assetsSubDirectory
  return path.posix.join(assetsSubDirectory, _path)
}

exports.cssLoaders = function (options) {
  options = options || {}

  var cssLoader = {
    loader: 'css-loader',
    options: {
      minimize: process.env.NODE_ENV === 'production',
      sourceMap: options.sourceMap
    }
  }

  // generate loader string to be used with extract text plugin
  function generateLoaders (loader, loaderOptions) {
    var loaders = [cssLoader]
    if (loader) {
      loaders.push({
        loader: loader + '-loader',
        options: Object.assign({}, loaderOptions, {
          sourceMap: options.sourceMap
        })
      })
    }

    // Extract CSS when that option is specified
    // (which is the case during production build)
    if (options.extract) {
      return ExtractTextPlugin.extract({
        use: loaders,
        fallback: 'vue-style-loader'
      })
    } else {
      return ['vue-style-loader'].concat(loaders)
    }
  }

  // https://vue-loader.vuejs.org/en/configurations/extract-css.html
  return {
    css: generateLoaders(),
    postcss: generateLoaders(),
    less: generateLoaders('less'),
    sass: generateLoaders('sass', { indentedSyntax: true }),
    scss: generateLoaders('sass'),
    stylus: generateLoaders('stylus'),
    styl: generateLoaders('stylus')
  }
}

// Generate loaders for standalone style files (outside of .vue)
exports.styleLoaders = function (options) {
  var output = []
  var loaders = exports.cssLoaders(options)
  for (var extension in loaders) {
    var loader = loaders[extension]
    output.push({
      test: new RegExp('\\.' + extension + '$'),
      use: loader
    })
  }
  return output
}
<commit_msg>Lint and add resolve to exports<commit_after>let path = require('path');
let config = require('../config');
let ExtractTextPlugin = require('extract-text-webpack-plugin');

exports.assetsPath = function(_path) {
  let assetsSubDirectory = process.env.NODE_ENV === 'production'
    ? config.build.assetsSubDirectory
    : config.dev.assetsSubDirectory;
  return path.posix.join(assetsSubDirectory, _path);
};

exports.resolve = function(dir) {
  return path.join(__dirname, '..', dir);
};

exports.cssLoaders = function(options) {
  options = options || {};

  let cssLoader = {
    loader: 'css-loader',
    options: {
      minimize: process.env.NODE_ENV === 'production',
      sourceMap: options.sourceMap,
    },
  };

  // generate loader string to be used with extract text plugin
  function generateLoaders(loader, loaderOptions) {
    let loaders = [cssLoader];
    if (loader) {
      loaders.push({
        loader: loader + '-loader',
        options: Object.assign({}, loaderOptions, {
          sourceMap: options.sourceMap,
        }),
      });
    }

    // Extract CSS when that option is specified
    // (which is the case during production build)
    if (options.extract) {
      return ExtractTextPlugin.extract({
        use: loaders,
        fallback: 'vue-style-loader',
      });
    } else {
      return ['vue-style-loader'].concat(loaders);
    }
  }

  // https://vue-loader.vuejs.org/en/configurations/extract-css.html
  return {
    css: generateLoaders(),
    postcss: generateLoaders(),
    less: generateLoaders('less'),
    sass: generateLoaders('sass', {indentedSyntax: true}),
    scss: generateLoaders('sass'),
    stylus: generateLoaders('stylus'),
    styl: generateLoaders('stylus'),
  };
};

// Generate loaders for standalone style files (outside of .vue)
exports.styleLoaders = function(options) {
  let output = [];
  let loaders = exports.cssLoaders(options);
  for (let extension in loaders) {
    let loader = loaders[extension];
    output.push({
      test: new RegExp('\\.' + extension + '$'),
      use: loader,
    });
  }
  return output;
};
<|endoftext|>


<commit_before>var path = require('path')
var config = require('../config')
var ExtractTextPlugin = require('extract-text-webpack-plugin')

exports.assetsPath = function (_path) {
  var assetsSubDirectory = process.env.NODE_ENV === 'production'
    ? config.build.assetsSubDirectory
    : config.dev.assetsSubDirectory
  return path.posix.join(assetsSubDirectory, _path)
}

exports.cssLoaders = function (options) {
  options = options || {}

  var cssLoader = {
    loader: 'css-loader',
    options: {
      minimize: process.env.NODE_ENV === 'production',
      sourceMap: options.sourceMap
    }
  }

  // generate loader string to be used with extract text plugin
  function generateLoaders (loader, loaderOptions) {
    var loaders = [cssLoader]
    if (loader) {
      loaders.push({
        loader: loader + '-loader',
        options: Object.assign({}, loaderOptions, {
          sourceMap: options.sourceMap
        })
      })
    }

    // Extract CSS when that option is specified
    // (which is the case during production build)
    if (options.extract) {
      return ExtractTextPlugin.extract({
        use: loaders,
        fallback: 'vue-style-loader'
      })
    } else {
      return ['vue-style-loader'].concat(loaders)
    }
  }

  // https://vue-loader.vuejs.org/en/configurations/extract-css.html
  return {
    css: generateLoaders(),
    postcss: generateLoaders(),
    less: generateLoaders('less'),
    sass: generateLoaders('sass', { indentedSyntax: true }),
    scss: generateLoaders('sass'),
    stylus: generateLoaders('stylus'),
    styl: generateLoaders('stylus')
  }
}

// Generate loaders for standalone style files (outside of .vue)
exports.styleLoaders = function (options) {
  var output = []
  var loaders = exports.cssLoaders(options)
  for (var extension in loaders) {
    var loader = loaders[extension]
    output.push({
      test: new RegExp('\\.' + extension + '$'),
      use: loader
    })
  }
  return output
}
<commit_msg>fix：修改webpack中的cssloader和extratextplugin配置<commit_after>var path = require('path')
var config = require('../config')
var ExtractTextPlugin = require('extract-text-webpack-plugin')

exports.assetsPath = function (_path) {
  var assetsSubDirectory = process.env.NODE_ENV === 'production'
    ? config.build.assetsSubDirectory
    : config.dev.assetsSubDirectory
  return path.posix.join(assetsSubDirectory, _path)
}

exports.cssLoaders = function (options) {
  options = options || {}

  var cssLoader = {
    loader: 'css-loader',
    options: {
      minimize: process.env.NODE_ENV === 'production',
      sourceMap: options.sourceMap
    }
  }

  // generate loader string to be used with extract text plugin
  function generateLoaders (loader, loaderOptions) {
    var loaders = [cssLoader]
    if (loader) {
      loaders.push({
        loader: loader + '-loader',
        options: Object.assign({}, loaderOptions, {
          sourceMap: options.sourceMap
        })
      })
    }

    // Extract CSS when that option is specified
    // (which is the case during production build)
    if (options.extract) {
      return ExtractTextPlugin.extract({
        use: loaders,
        fallback: 'vue-style-loader',
        publicPath: '../../'
      })
    } else {
      return ['vue-style-loader'].concat(loaders)
    }
  }

  // https://vue-loader.vuejs.org/en/configurations/extract-css.html
  return {
    css: generateLoaders(),
    postcss: generateLoaders(),
    less: generateLoaders('less'),
    sass: generateLoaders('sass', { indentedSyntax: true }),
    scss: generateLoaders('sass'),
    stylus: generateLoaders('stylus'),
    styl: generateLoaders('stylus')
  }
}

// Generate loaders for standalone style files (outside of .vue)
exports.styleLoaders = function (options) {
  var output = []
  var loaders = exports.cssLoaders(options)
  for (var extension in loaders) {
    var loader = loaders[extension]
    output.push({
      test: new RegExp('\\.' + extension + '$'),
      use: loader
    })
  }
  return output
}
<|endoftext|>


<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

'use strict';

base.requireStylesheet('tracing.tracks.ruler_track');

base.require('tracing.constants');
base.require('tracing.tracks.track');
base.require('tracing.tracks.heading_track');
base.require('ui');

base.exportTo('tracing.tracks', function() {

  /**
   * A track that displays the ruler.
   * @constructor
   * @extends {HeadingTrack}
   */

  var RulerTrack = ui.define('ruler-track', tracing.tracks.HeadingTrack);

  var logOf10 = Math.log(10);
  function log10(x) {
    return Math.log(x) / logOf10;
  }

  RulerTrack.prototype = {
    __proto__: tracing.tracks.HeadingTrack.prototype,

    decorate: function(viewport) {
      tracing.tracks.HeadingTrack.prototype.decorate.call(this, viewport);
      this.classList.add('ruler-track');
      this.strings_secs_ = [];
      this.strings_msecs_ = [];

      this.viewportMarkersChange_ = this.viewportMarkersChange_.bind(this);
      viewport.addEventListener('markersChange', this.viewportMarkersChange_);

    },

    detach: function() {
      tracing.tracks.HeadingTrack.prototype.detach.call(this);
      this.viewport.removeEventListener('markersChange',
                                        this.viewportMarkersChange_);
    },

    viewportMarkersChange_: function() {
      if (this.viewport.markers.length < 1)
        this.classList.remove('ruler-track-with-distance-measurements');
      else
        this.classList.add('ruler-track-with-distance-measurements');
    },

    drawLine_: function(ctx, x1, y1, x2, y2, color) {
      ctx.beginPath();
      ctx.moveTo(x1, y1);
      ctx.lineTo(x2, y2);
      ctx.closePath();
      ctx.strokeStyle = color;
      ctx.stroke();
    },

    drawArrow_: function(ctx, x1, y1, x2, y2, arrowWidth, color) {
      this.drawLine_(ctx, x1, y1, x2, y2, color);

      var dx = x2 - x1;
      var dy = y2 - y1;
      var len = Math.sqrt(dx * dx + dy * dy);
      var perc = (len - 10) / len;
      var bx = x1 + perc * dx;
      var by = y1 + perc * dy;
      var ux = dx / len;
      var uy = dy / len;
      var ax = uy * arrowWidth;
      var ay = -ux * arrowWidth;

      ctx.beginPath();
      ctx.fillStyle = color;
      ctx.moveTo(bx + ax, by + ay);
      ctx.lineTo(x2, y2);
      ctx.lineTo(bx - ax, by - ay);
      ctx.lineTo(bx + ax, by + ay);
      ctx.closePath();
      ctx.fill();
    },

    draw: function(type, viewLWorld, viewRWorld) {
      switch (type) {
        case tracing.tracks.DrawType.SLICE:
          this.drawSlices_(viewLWorld, viewRWorld);
          break;
      }
    },

    drawSlices_: function(viewLWorld, viewRWorld) {
      var ctx = this.context();
      var pixelRatio = window.devicePixelRatio || 1;

      var bounds = this.getBoundingClientRect();
      var width = bounds.width * pixelRatio;
      var height = bounds.height * pixelRatio;

      var measurements = this.classList.contains(
          'ruler-track-with-distance-measurements');

      var rulerHeight = measurements ? height * 2 / 5 : height;

      var vp = this.viewport;
      vp.drawMarkerArrows(ctx, viewLWorld, viewRWorld, rulerHeight);

      var idealMajorMarkDistancePix = 150 * pixelRatio;
      var idealMajorMarkDistanceWorld =
          vp.xViewVectorToWorld(idealMajorMarkDistancePix);

      var majorMarkDistanceWorld;
      var unit;
      var unitDivisor;
      var tickLabels;

      // The conservative guess is the nearest enclosing 0.1, 1, 10, 100, etc.
      var conservativeGuess =
          Math.pow(10, Math.ceil(log10(idealMajorMarkDistanceWorld)));

      // Once we have a conservative guess, consider things that evenly add up
      // to the conservative guess, e.g. 0.5, 0.2, 0.1 Pick the one that still
      // exceeds the ideal mark distance.
      var divisors = [10, 5, 2, 1];
      for (var i = 0; i < divisors.length; ++i) {
        var tightenedGuess = conservativeGuess / divisors[i];
        if (vp.xWorldVectorToView(tightenedGuess) < idealMajorMarkDistancePix)
          continue;
        majorMarkDistanceWorld = conservativeGuess / divisors[i - 1];
        break;
      }

      var tickLabels = undefined;
      if (majorMarkDistanceWorld < 100) {
        unit = 'ms';
        unitDivisor = 1;
        tickLabels = this.strings_msecs_;
      } else {
        unit = 's';
        unitDivisor = 1000;
        tickLabels = this.strings_secs_;
      }

      var numTicksPerMajor = 5;
      var minorMarkDistanceWorld = majorMarkDistanceWorld / numTicksPerMajor;
      var minorMarkDistancePx = vp.xWorldVectorToView(minorMarkDistanceWorld);

      var firstMajorMark =
          Math.floor(viewLWorld / majorMarkDistanceWorld) *
              majorMarkDistanceWorld;

      var minorTickH = Math.floor(height * 0.25);

      ctx.fillStyle = 'rgb(0, 0, 0)';
      ctx.strokeStyle = 'rgb(0, 0, 0)';
      ctx.textAlign = 'left';
      ctx.textBaseline = 'top';

      var pixelRatio = window.devicePixelRatio || 1;
      ctx.font = (9 * pixelRatio) + 'px sans-serif';

      vp.majorMarkPositions = [];

      // Each iteration of this loop draws one major mark
      // and numTicksPerMajor minor ticks.
      //
      // Rendering can't be done in world space because canvas transforms
      // affect line width. So, do the conversions manually.
      for (var curX = firstMajorMark;
           curX < viewRWorld;
           curX += majorMarkDistanceWorld) {

        var curXView = Math.floor(vp.xWorldToView(curX));

        var unitValue = curX / unitDivisor;
        var roundedUnitValue = Math.floor(unitValue * 100000) / 100000;

        if (!tickLabels[roundedUnitValue])
          tickLabels[roundedUnitValue] = roundedUnitValue + ' ' + unit;
        ctx.fillText(tickLabels[roundedUnitValue],
                     curXView + 2 * pixelRatio, 0);
        ctx.beginPath();

        vp.majorMarkPositions.push(curXView);

        // Major mark
        ctx.moveTo(curXView, 0);
        ctx.lineTo(curXView, rulerHeight);

        // Minor marks
        for (var i = 1; i < numTicksPerMajor; ++i) {
          var xView = Math.floor(curXView + minorMarkDistancePx * i);
          ctx.moveTo(xView, rulerHeight - minorTickH);
          ctx.lineTo(xView, rulerHeight);
        }

        ctx.stroke();
      }
      // Draw bottom bar.
      ctx.moveTo(0, rulerHeight);
      ctx.lineTo(width, rulerHeight);
      ctx.stroke();

      // Give distance between directly adjacent markers.
      if (measurements) {
        // Obtain a sorted array of markers
        var sortedMarkers = vp.markers.slice();
        sortedMarkers.sort(function(a, b) {
          return a.positionWorld_ - b.positionWorld_;
        });

        // Distance Variables.
        var displayDistance;
        var displayTextColor = 'rgb(0,0,0)';

        // Arrow Variables.
        var arrowSpacing = 10;
        var arrowColor = 'rgb(128,121,121)';
        var arrowPosY = rulerHeight * 1.75;
        var arrowWidthView = 3;
        var spaceForArrowsView = 2 * (arrowWidthView + arrowSpacing);

        ctx.textBaseline = 'middle';
        ctx.font = (14 * pixelRatio) + 'px sans-serif';
        var textPosY = arrowPosY;

        // If there is only one marker, draw it's timestamp next to the line.
        if (sortedMarkers.length === 1) {
          var markerWorld = sortedMarkers[0].positionWorld;
          var textLeftView =
              vp.xWorldToView(markerWorld) + 4 * pixelRatio;

          var displayValue = markerWorld / unitDivisor;
          displayValue = Math.abs((Math.floor(displayValue * 1000) / 1000));
          var textToDraw = displayValue + ' ' + unit;

          ctx.fillStyle = displayTextColor;
          ctx.fillText(textToDraw, textLeftView, textPosY);
        }

        for (i = 0; i < sortedMarkers.length - 1; i++) {
          var leftMarker = sortedMarkers[i];
          var rightMarker = sortedMarkers[i + 1];
          var leftMarkerView = vp.xWorldToView(leftMarker.positionWorld);
          var rightMarkerView = vp.xWorldToView(rightMarker.positionWorld);

          var distanceBetweenMarkers =
              rightMarker.positionWorld - leftMarker.positionWorld;
          var distanceBetweenMarkersView =
              vp.xWorldVectorToView(distanceBetweenMarkers);
          var positionInMiddleOfMarkersView =
              leftMarkerView + distanceBetweenMarkersView / 2;

          // Determine units.
          if (distanceBetweenMarkers < 100) {
            unit = 'ms';
            unitDivisor = 1;
          } else {
            unit = 's';
            unitDivisor = 1000;
          }
          // Calculate display value to print.
          displayDistance = distanceBetweenMarkers / unitDivisor;
          var roundedDisplayDistance =
              Math.abs((Math.floor(displayDistance * 1000) / 1000));
          var textToDraw = roundedDisplayDistance + ' ' + unit;
          var textWidthView = ctx.measureText(textToDraw).width;
          var spaceForArrowsAndTextView = textWidthView +
                                          spaceForArrowsView + arrowSpacing;

          // Set text positions.
          var textLeftView = positionInMiddleOfMarkersView - textWidthView / 2;
          var textRightView = textLeftView + textWidthView;

          if (sortedMarkers.length === 2 &&
              spaceForArrowsAndTextView > distanceBetweenMarkersView) {
            // Print the display distance text right of the 2 markers.
            textLeftView = rightMarkerView + 2 * arrowSpacing;
            ctx.fillStyle = displayTextColor;
            ctx.fillText(textToDraw, textLeftView, textPosY);

            // Draw the arrows pointing from outside in and a line in between.
            this.drawLine_(ctx, leftMarkerView, arrowPosY,
                rightMarkerView, arrowPosY, arrowColor);
            this.drawArrow_(ctx, leftMarkerView - 1.5 * arrowSpacing, arrowPosY,
                leftMarkerView, arrowPosY, arrowWidthView, arrowColor);
            this.drawArrow_(ctx, rightMarkerView + 1.5 * arrowSpacing,
                arrowPosY, rightMarkerView, arrowPosY, arrowWidthView,
                arrowColor);
          } else if (spaceForArrowsView <= distanceBetweenMarkersView) {
            var leftArrowStart;
            var rightArrowStart;
            if (spaceForArrowsAndTextView <= distanceBetweenMarkersView) {
              // Print the display distance text.
              ctx.fillStyle = displayTextColor;
              ctx.fillText(textToDraw, textLeftView, textPosY);

              leftArrowStart = textLeftView - arrowSpacing;
              rightArrowStart = textRightView + arrowSpacing;
            } else {
              leftArrowStart = positionInMiddleOfMarkersView;
              rightArrowStart = positionInMiddleOfMarkersView;
            }

            // Draw the arrows pointing inside out.
            this.drawArrow_(ctx, leftArrowStart, arrowPosY,
                leftMarkerView, arrowPosY, arrowWidthView, arrowColor);
            this.drawArrow_(ctx, rightArrowStart, arrowPosY,
                rightMarkerView, arrowPosY, arrowWidthView, arrowColor);
          }
        }
        // Draw bottom bar.
        ctx.moveTo(0, rulerHeight * 2.5);
        ctx.lineTo(width, rulerHeight * 2.5);
        ctx.stroke();
      }
    },

    /**
     * Adds items intersecting the given range to a selection.
     * @param {number} loVX Lower X bound of the interval to search, in
     *     viewspace.
     * @param {number} hiVX Upper X bound of the interval to search, in
     *     viewspace.
     * @param {number} loVY Lower Y bound of the interval to search, in
     *     viewspace.
     * @param {number} hiVY Upper Y bound of the interval to search, in
     *     viewspace.
     * @param {Selection} selection Selection to which to add hits.
     */
    addIntersectingItemsInRangeToSelection: function(
        loVX, hiVX, loY, hiY, selection) {
      // Does nothing. There's nothing interesting to pick on the ruler
      // track.
    },

    addAllObjectsMatchingFilterToSelection: function(filter, selection) {
    }
  };

  return {
    RulerTrack: RulerTrack
  };
});
<commit_msg>Fix line drawing issues in ruler track<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

'use strict';

base.requireStylesheet('tracing.tracks.ruler_track');

base.require('tracing.constants');
base.require('tracing.tracks.track');
base.require('tracing.tracks.heading_track');
base.require('ui');

base.exportTo('tracing.tracks', function() {

  /**
   * A track that displays the ruler.
   * @constructor
   * @extends {HeadingTrack}
   */

  var RulerTrack = ui.define('ruler-track', tracing.tracks.HeadingTrack);

  var logOf10 = Math.log(10);
  function log10(x) {
    return Math.log(x) / logOf10;
  }

  RulerTrack.prototype = {
    __proto__: tracing.tracks.HeadingTrack.prototype,

    decorate: function(viewport) {
      tracing.tracks.HeadingTrack.prototype.decorate.call(this, viewport);
      this.classList.add('ruler-track');
      this.strings_secs_ = [];
      this.strings_msecs_ = [];

      this.viewportMarkersChange_ = this.viewportMarkersChange_.bind(this);
      viewport.addEventListener('markersChange', this.viewportMarkersChange_);

    },

    detach: function() {
      tracing.tracks.HeadingTrack.prototype.detach.call(this);
      this.viewport.removeEventListener('markersChange',
                                        this.viewportMarkersChange_);
    },

    viewportMarkersChange_: function() {
      if (this.viewport.markers.length < 1)
        this.classList.remove('ruler-track-with-distance-measurements');
      else
        this.classList.add('ruler-track-with-distance-measurements');
    },

    drawLine_: function(ctx, x1, y1, x2, y2) {
      ctx.beginPath();
      ctx.moveTo(x1, y1);
      ctx.lineTo(x2, y2);
      ctx.stroke();
    },

    drawArrow_: function(ctx, x1, y1, x2, y2, arrowWidth, color) {
      ctx.save();

      ctx.strokeStyle = color;
      this.drawLine_(ctx, x1, y1, x2, y2);

      var dx = x2 - x1;
      var dy = y2 - y1;
      var len = Math.sqrt(dx * dx + dy * dy);
      var perc = (len - 10) / len;
      var bx = x1 + perc * dx;
      var by = y1 + perc * dy;
      var ux = dx / len;
      var uy = dy / len;
      var ax = uy * arrowWidth;
      var ay = -ux * arrowWidth;

      ctx.beginPath();
      ctx.fillStyle = color;
      ctx.moveTo(bx + ax, by + ay);
      ctx.lineTo(x2, y2);
      ctx.lineTo(bx - ax, by - ay);
      ctx.lineTo(bx + ax, by + ay);
      ctx.closePath();
      ctx.fill();

      ctx.restore();
    },

    draw: function(type, viewLWorld, viewRWorld) {
      switch (type) {
        case tracing.tracks.DrawType.SLICE:
          this.drawSlices_(viewLWorld, viewRWorld);
          break;
      }
    },

    drawSlices_: function(viewLWorld, viewRWorld) {
      var ctx = this.context();
      var pixelRatio = window.devicePixelRatio || 1;

      var bounds = this.getBoundingClientRect();
      var width = bounds.width * pixelRatio;
      var height = bounds.height * pixelRatio;

      var measurements = this.classList.contains(
          'ruler-track-with-distance-measurements');

      var rulerHeight = measurements ? height * 2 / 5 : height;

      var vp = this.viewport;
      vp.drawMarkerArrows(ctx, viewLWorld, viewRWorld, rulerHeight);

      var idealMajorMarkDistancePix = 150 * pixelRatio;
      var idealMajorMarkDistanceWorld =
          vp.xViewVectorToWorld(idealMajorMarkDistancePix);

      var majorMarkDistanceWorld;
      var unit;
      var unitDivisor;
      var tickLabels;

      // The conservative guess is the nearest enclosing 0.1, 1, 10, 100, etc.
      var conservativeGuess =
          Math.pow(10, Math.ceil(log10(idealMajorMarkDistanceWorld)));

      // Once we have a conservative guess, consider things that evenly add up
      // to the conservative guess, e.g. 0.5, 0.2, 0.1 Pick the one that still
      // exceeds the ideal mark distance.
      var divisors = [10, 5, 2, 1];
      for (var i = 0; i < divisors.length; ++i) {
        var tightenedGuess = conservativeGuess / divisors[i];
        if (vp.xWorldVectorToView(tightenedGuess) < idealMajorMarkDistancePix)
          continue;
        majorMarkDistanceWorld = conservativeGuess / divisors[i - 1];
        break;
      }

      var tickLabels = undefined;
      if (majorMarkDistanceWorld < 100) {
        unit = 'ms';
        unitDivisor = 1;
        tickLabels = this.strings_msecs_;
      } else {
        unit = 's';
        unitDivisor = 1000;
        tickLabels = this.strings_secs_;
      }

      var numTicksPerMajor = 5;
      var minorMarkDistanceWorld = majorMarkDistanceWorld / numTicksPerMajor;
      var minorMarkDistancePx = vp.xWorldVectorToView(minorMarkDistanceWorld);

      var firstMajorMark =
          Math.floor(viewLWorld / majorMarkDistanceWorld) *
              majorMarkDistanceWorld;

      var minorTickH = Math.floor(rulerHeight * 0.25);

      ctx.fillStyle = 'rgb(0, 0, 0)';
      ctx.strokeStyle = 'rgb(0, 0, 0)';
      ctx.textAlign = 'left';
      ctx.textBaseline = 'top';

      var pixelRatio = window.devicePixelRatio || 1;
      ctx.font = (9 * pixelRatio) + 'px sans-serif';

      vp.majorMarkPositions = [];

      // Each iteration of this loop draws one major mark
      // and numTicksPerMajor minor ticks.
      //
      // Rendering can't be done in world space because canvas transforms
      // affect line width. So, do the conversions manually.
      for (var curX = firstMajorMark;
           curX < viewRWorld;
           curX += majorMarkDistanceWorld) {

        var curXView = Math.floor(vp.xWorldToView(curX));

        var unitValue = curX / unitDivisor;
        var roundedUnitValue = Math.floor(unitValue * 100000) / 100000;

        if (!tickLabels[roundedUnitValue])
          tickLabels[roundedUnitValue] = roundedUnitValue + ' ' + unit;
        ctx.fillText(tickLabels[roundedUnitValue],
                     curXView + 2 * pixelRatio, 0);
        ctx.beginPath();

        vp.majorMarkPositions.push(curXView);

        // Major mark
        ctx.moveTo(curXView, 0);
        ctx.lineTo(curXView, rulerHeight);

        // Minor marks
        for (var i = 1; i < numTicksPerMajor; ++i) {
          var xView = Math.floor(curXView + minorMarkDistancePx * i);
          ctx.moveTo(xView, rulerHeight - minorTickH);
          ctx.lineTo(xView, rulerHeight);
        }

        ctx.stroke();
      }
      // Draw bottom bar.
      this.drawLine_(ctx, 0, height, width, height);

      // Give distance between directly adjacent markers.
      if (measurements) {
        // Draw middle bar.
        this.drawLine_(ctx, 0, rulerHeight, width, rulerHeight);

        // Obtain a sorted array of markers
        var sortedMarkers = vp.markers.slice();
        sortedMarkers.sort(function(a, b) {
          return a.positionWorld_ - b.positionWorld_;
        });

        // Distance Variables.
        var displayDistance;
        var displayTextColor = 'rgb(0,0,0)';

        // Arrow Variables.
        var arrowSpacing = 10;
        var arrowColor = 'rgb(128,121,121)';
        var arrowPosY = rulerHeight * 1.75;
        var arrowWidthView = 3;
        var spaceForArrowsView = 2 * (arrowWidthView + arrowSpacing);

        ctx.textBaseline = 'middle';
        ctx.font = (14 * pixelRatio) + 'px sans-serif';
        var textPosY = arrowPosY;

        // If there is only one marker, draw it's timestamp next to the line.
        if (sortedMarkers.length === 1) {
          var markerWorld = sortedMarkers[0].positionWorld;
          var textLeftView =
              vp.xWorldToView(markerWorld) + 4 * pixelRatio;

          var displayValue = markerWorld / unitDivisor;
          displayValue = Math.abs((Math.floor(displayValue * 1000) / 1000));
          var textToDraw = displayValue + ' ' + unit;

          ctx.fillStyle = displayTextColor;
          ctx.fillText(textToDraw, textLeftView, textPosY);
        }

        for (i = 0; i < sortedMarkers.length - 1; i++) {
          var leftMarker = sortedMarkers[i];
          var rightMarker = sortedMarkers[i + 1];
          var leftMarkerView = vp.xWorldToView(leftMarker.positionWorld);
          var rightMarkerView = vp.xWorldToView(rightMarker.positionWorld);

          var distanceBetweenMarkers =
              rightMarker.positionWorld - leftMarker.positionWorld;
          var distanceBetweenMarkersView =
              vp.xWorldVectorToView(distanceBetweenMarkers);
          var positionInMiddleOfMarkersView =
              leftMarkerView + distanceBetweenMarkersView / 2;

          // Determine units.
          if (distanceBetweenMarkers < 100) {
            unit = 'ms';
            unitDivisor = 1;
          } else {
            unit = 's';
            unitDivisor = 1000;
          }
          // Calculate display value to print.
          displayDistance = distanceBetweenMarkers / unitDivisor;
          var roundedDisplayDistance =
              Math.abs((Math.floor(displayDistance * 1000) / 1000));
          var textToDraw = roundedDisplayDistance + ' ' + unit;
          var textWidthView = ctx.measureText(textToDraw).width;
          var spaceForArrowsAndTextView = textWidthView +
                                          spaceForArrowsView + arrowSpacing;

          // Set text positions.
          var textLeftView = positionInMiddleOfMarkersView - textWidthView / 2;
          var textRightView = textLeftView + textWidthView;

          if (sortedMarkers.length === 2 &&
              spaceForArrowsAndTextView > distanceBetweenMarkersView) {
            // Print the display distance text right of the 2 markers.
            textLeftView = rightMarkerView + 2 * arrowSpacing;
            ctx.fillStyle = displayTextColor;
            ctx.fillText(textToDraw, textLeftView, textPosY);

            // Draw the arrows pointing from outside in and a line in between.
            ctx.strokeStyle = arrowColor;
            this.drawLine_(ctx, leftMarkerView, arrowPosY, rightMarkerView,
                arrowPosY);
            this.drawArrow_(ctx, leftMarkerView - 1.5 * arrowSpacing, arrowPosY,
                leftMarkerView, arrowPosY, arrowWidthView, arrowColor);
            this.drawArrow_(ctx, rightMarkerView + 1.5 * arrowSpacing,
                arrowPosY, rightMarkerView, arrowPosY, arrowWidthView,
                arrowColor);
          } else if (spaceForArrowsView <= distanceBetweenMarkersView) {
            var leftArrowStart;
            var rightArrowStart;
            if (spaceForArrowsAndTextView <= distanceBetweenMarkersView) {
              // Print the display distance text.
              ctx.fillStyle = displayTextColor;
              ctx.fillText(textToDraw, textLeftView, textPosY);

              leftArrowStart = textLeftView - arrowSpacing;
              rightArrowStart = textRightView + arrowSpacing;
            } else {
              leftArrowStart = positionInMiddleOfMarkersView;
              rightArrowStart = positionInMiddleOfMarkersView;
            }

            // Draw the arrows pointing inside out.
            this.drawArrow_(ctx, leftArrowStart, arrowPosY,
                leftMarkerView, arrowPosY, arrowWidthView, arrowColor);
            this.drawArrow_(ctx, rightArrowStart, arrowPosY,
                rightMarkerView, arrowPosY, arrowWidthView, arrowColor);
          }
        }
      }
    },

    /**
     * Adds items intersecting the given range to a selection.
     * @param {number} loVX Lower X bound of the interval to search, in
     *     viewspace.
     * @param {number} hiVX Upper X bound of the interval to search, in
     *     viewspace.
     * @param {number} loVY Lower Y bound of the interval to search, in
     *     viewspace.
     * @param {number} hiVY Upper Y bound of the interval to search, in
     *     viewspace.
     * @param {Selection} selection Selection to which to add hits.
     */
    addIntersectingItemsInRangeToSelection: function(
        loVX, hiVX, loY, hiY, selection) {
      // Does nothing. There's nothing interesting to pick on the ruler
      // track.
    },

    addAllObjectsMatchingFilterToSelection: function(filter, selection) {
    }
  };

  return {
    RulerTrack: RulerTrack
  };
});
<|endoftext|>


<commit_before>import React from 'react';
import Downshift from 'downshift';
import PropTypes from 'prop-types';
import uniqueId from 'lodash/uniqueId';
import TetherComponent from 'react-tether';
import injectIntl from '@folio/stripes-components/lib/InjectIntl';
import TextField from '@folio/stripes-components/lib/TextField';
import reduxFormField from '@folio/stripes-components/lib/ReduxFormField';
import css from './AutoSuggest.css';

const defaultProps = {
  validationEnabled: true,
  tether: {
    attachment: 'top left',
    renderElementTo: null,
    targetAttachment: 'bottom left',
    optimizations: {
      gpu: false,
    },
    constraints: [
      {
        to: 'scrollParent',
      },
    ],
  },
};

const propTypes = {
  error: PropTypes.string,
  id: PropTypes.string,
  items: PropTypes.arrayOf(PropTypes.object).isRequired,
  label: PropTypes.string,
  meta: PropTypes.object,
  onBlur: PropTypes.func,
  onChange: PropTypes.func,
  required: PropTypes.bool,
  screenReaderMessage: PropTypes.string,
  tether: PropTypes.object,
  validationEnabled: PropTypes.bool,
  value: PropTypes.string,
};

class AutoSuggest extends React.Component {
  static propTypes = propTypes;
  static defaultProps = defaultProps;

  constructor(props) {
    super(props);
    this.container = React.createRef();
    this.textfield = React.createRef();
    this.testId = this.props.id || uniqueId('detailname-');
    this.autoSuggestId = `list-dropdown-${this.testId}`;
  }

  getInputWidth() {
    if (this.textfield.current) {
      const { input : { current : { offsetWidth }}} = this.textfield.current;
      return offsetWidth;
    }
  }

  render() {
    const { tether,
      items,
      label,
      value,
      required,
      validationEnabled, onBlur, error, onChange } = this.props;

    const textfieldRef = this.textfield;
    const mergedTetherProps = { ...AutoSuggest.defaultProps.tether, ...tether };
    const testId = this.testId;
    const autoSuggestId = this.autoSuggestId;
    const listWidth = this.getInputWidth();
    const inputProps = {
      autoComplete: 'off',
      required,
      label,
      validationEnabled,
      ref: textfieldRef,
      id: testId,
      error,
    };

    return (
        <Downshift
          style={{ display: 'inline-block', position: 'relative' }}
          itemToString={item => (item ? item.value : '')}
          onChange={selectedItem => onChange(selectedItem.value)}
          onStateChange={({ inputValue }) => onChange(inputValue)}
          selectedItem={value}
          inputValue={value}
        >
          {({
              getInputProps,
              getItemProps,
              getMenuProps,
              selectedItem,
              highlightedIndex,
              isOpen,
              inputValue,
            }) => (

                <TetherComponent {...mergedTetherProps}>

 { this.container = ref; }}
                    aria-live="assertive"
                    aria-relevant="additions"
                  >
                    <TextField {...getInputProps(
                        { ...inputProps,
                          onBlur: onBlur,
                        }
                      )}
                    />

                  <ul className={css.AutoSuggest} style={{ width: `${listWidth}px` }} {...getMenuProps({ id: autoSuggestId })} >
                    {isOpen
                      ? items
                        .filter(item => !inputValue || item.value.includes(inputValue))
                        .map((item, index) => (
                          <li
                            {...getItemProps({
                              key: item.value,
                              index,
                              item,
                              style: {
                                padding: '5px',
                                cursor: 'default',
                                display: 'flex',
                                justifyContent: 'space-between',
                                backgroundColor:
                                  highlightedIndex === index ? 'lightgray' : 'white',
                                  fontWeight: selectedItem === item ? 'bold' : 'normal',
                              },
                            })}
                          >
                            {item.value}

                        ))
                    : null}

                </TetherComponent>

              )
            }
        </Downshift>
    );
  }
}

export default reduxFormField(
  injectIntl(
    AutoSuggest, { withRef: true }
  ), ({ input, meta }) => ({
    dirty: meta.dirty,
    error: (meta.touched && meta.error ? meta.error : ''),
    loading: meta.asyncValidating,
    name: input.name,
    onBlur: input.onBlur,
    onChange: input.onChange,
    onFocus: input.onFocus,
    touched: meta.touched,
    valid: meta.valid,
    value: input.value,
    warning: (meta.touched && meta.warning ? meta.warning : ''),
  })
);
<commit_msg>pass style property to getmenuprops, refs UIORG-87 (#103)<commit_after>import React from 'react';
import Downshift from 'downshift';
import PropTypes from 'prop-types';
import uniqueId from 'lodash/uniqueId';
import TetherComponent from 'react-tether';
import injectIntl from '@folio/stripes-components/lib/InjectIntl';
import TextField from '@folio/stripes-components/lib/TextField';
import reduxFormField from '@folio/stripes-components/lib/ReduxFormField';
import css from './AutoSuggest.css';

const defaultProps = {
  validationEnabled: true,
  tether: {
    attachment: 'top left',
    renderElementTo: null,
    targetAttachment: 'bottom left',
    optimizations: {
      gpu: false,
    },
    constraints: [
      {
        to: 'scrollParent',
      },
    ],
  },
};

const propTypes = {
  error: PropTypes.string,
  id: PropTypes.string,
  items: PropTypes.arrayOf(PropTypes.object).isRequired,
  label: PropTypes.string,
  meta: PropTypes.object,
  onBlur: PropTypes.func,
  onChange: PropTypes.func,
  required: PropTypes.bool,
  screenReaderMessage: PropTypes.string,
  tether: PropTypes.object,
  validationEnabled: PropTypes.bool,
  value: PropTypes.string,
};

class AutoSuggest extends React.Component {
  static propTypes = propTypes;
  static defaultProps = defaultProps;

  constructor(props) {
    super(props);
    this.container = React.createRef();
    this.textfield = React.createRef();
    this.testId = this.props.id || uniqueId('detailname-');
    this.autoSuggestId = `list-dropdown-${this.testId}`;
  }

  getInputWidth() {
    if (this.textfield.current) {
      const { input : { current : { offsetWidth }}} = this.textfield.current;
      return offsetWidth;
    }
  }

  render() {
    const { tether,
      items,
      label,
      value,
      required,
      validationEnabled, onBlur, error, onChange } = this.props;

    const textfieldRef = this.textfield;
    const mergedTetherProps = { ...AutoSuggest.defaultProps.tether, ...tether };
    const testId = this.testId;
    const autoSuggestId = this.autoSuggestId;
    const listWidth = this.getInputWidth();
    const inputProps = {
      autoComplete: 'off',
      required,
      label,
      validationEnabled,
      ref: textfieldRef,
      id: testId,
      error,
    };

    return (
        <Downshift
          style={{ display: 'inline-block', position: 'relative' }}
          itemToString={item => (item ? item.value : '')}
          onChange={selectedItem => onChange(selectedItem.value)}
          onStateChange={({ inputValue }) => onChange(inputValue)}
          selectedItem={value}
          inputValue={value}
        >
          {({
              getInputProps,
              getItemProps,
              getMenuProps,
              selectedItem,
              highlightedIndex,
              isOpen,
              inputValue,
            }) => (

                <TetherComponent {...mergedTetherProps}>

 { this.container = ref; }}
                    aria-live="assertive"
                    aria-relevant="additions"
                  >
                    <TextField {...getInputProps(
                        { ...inputProps,
                          onBlur: onBlur,
                        }
                      )}
                    />

                  <ul className={css.AutoSuggest} {...getMenuProps({
                        id: autoSuggestId,
                        style: { width: `${listWidth}px` }
                      })}
                  >
                    {isOpen
                      ? items
                        .filter(item => !inputValue || item.value.includes(inputValue))
                        .map((item, index) => (
                          <li
                            {...getItemProps({
                              key: item.value,
                              index,
                              item,
                              style: {
                                padding: '5px',
                                cursor: 'default',
                                display: 'flex',
                                justifyContent: 'space-between',
                                backgroundColor:
                                  highlightedIndex === index ? 'lightgray' : 'white',
                                  fontWeight: selectedItem === item ? 'bold' : 'normal',
                              },
                            })}
                          >
                            {item.value}

                        ))
                    : null}

                </TetherComponent>

              )
            }
        </Downshift>
    );
  }
}

export default reduxFormField(
  injectIntl(
    AutoSuggest, { withRef: true }
  ), ({ input, meta }) => ({
    dirty: meta.dirty,
    error: (meta.touched && meta.error ? meta.error : ''),
    loading: meta.asyncValidating,
    name: input.name,
    onBlur: input.onBlur,
    onChange: input.onChange,
    onFocus: input.onFocus,
    touched: meta.touched,
    valid: meta.valid,
    value: input.value,
    warning: (meta.touched && meta.warning ? meta.warning : ''),
  })
);
<|endoftext|>