<commit_before>var fs      = require("fs");
var cheerio = require("cheerio");
var _       = require('underscore');
var moment  = require('moment');
var argv    = require('argv');
var net     = require('net');
var path    = require('path');
var repl    = require('repl');

// Args
argv.option({
  name: 'input',
  short: 'i',
  type: 'string',
  description: 'Defines schema file to open',
  example: "'beardo.js --schema=value' or 'beardo.js -s data/hours.json"
});

argv.option({
  name: 'format',
  short: 'f',
  type: 'csv,string',
  description: 'Defines output formats with html,cli',
  example: "'beardo.js --format=value' or 'beardo.js -f value1,value2'"
});

argv.option({
  name: 'output',
  short: 'o',
  type: 'string',
  description: 'Defines name to save output files as',
  example: "'beardo.js --save=value' or 'beardo.js -s January Invoice'"
});

argv.option({
  name: 'date',
  short: 'd',
  type: 'string',
  description: 'Returns only by current date (currently month only)',
  example: "'beardo.js --date=value' or 'beardo.js -d January or Jan or 01'"
});

argv.option({
  name: 'trim',
  short: 't',
  type: 'list,string',
  description: 'Trims output by a given string value declared in schema',
  example: "'beardo.js --trim=value' or 'beardo.js -t Client'"
});

var args = argv.run();

// File Manipulation
var SaveFile = require('./lib/save_file');

// Beardo
var Beardo = {};

Beardo.Date = {};

Beardo.Date.full = function(date) {

  var this_date = date.replace(/-/g,'');
  var filter_date = args.options.date.replace(/-/g, '');

  if (this_date >= filter_date) {
    //console.log('this date: 'this_date + ' is greater than filter date: ' + filter_date);
    return true;
  } else {
    return false;
  }
};

Beardo.Date.year_month = function(date) {

  if (date.indexOf(args.options.date) > -1) {
    //console.log('date filter by year_month ' + date);
    return true;
  } else {
    return false;
  }
};

Beardo.Date.month_day = function(date) {

  if (date.indexOf(args.options.date) > -1) {
    //console.log('date filter by month_day ' + date);
    return true;
  } else {
    return false;
  }
};

Beardo.Date.year = function(date) {

  if (date.indexOf(args.options.date) > -1) {
    //console.log('date filter by year ' + date);
    return true;
  } else {
    return false;
  }
};

Beardo.Date.month = function(date) {

  var date_trim = args.options.date.toLowerCase();
  var date_full = moment(date).format('MMMM').toLowerCase();
  var date_abbr = moment(date).format('MMM').toLowerCase();
  var date_numb = moment(date).format('MM').toLowerCase();

  if (_.indexOf([date_full, date_abbr, date_numb], date_trim) > -1) {
    //console.log('date matches filter: ' + date_trim)
    return true;
  } else {
    return false;
  }
};

Beardo.Date.none = function(parts) {
  console.log('no date filtering performed');
};

Beardo.Trim = function(parts) {
  if (args.options.trim !== undefined) {

    var part = parts[3].trim();

    if (_.indexOf(args.options.trim, part) > -1) {
      //console.log('client: ' + part + ' matches: ' + args.options.trim);
      return true;
    } else {
      return false;
    }
  } else {
    return true;
  }
};

// Load Data & Parse
Beardo.Twirl = function(path, resource) {

  var resource_file = path + '/' + resource.path;

  fs.exists(resource_file, function(exists) {
  	if (exists) {

  		console.log('Beardo is twirling some data');

      fs.stat(resource_file, function(error, stats) {
        fs.open(resource_file, "r", function(error, fd) {

          var buffer = new Buffer(stats.size);

          fs.read(fd, buffer, 0, buffer.length, null, function(error, bytesRead, buffer) {
            fs.close(fd);

            var data = buffer.toString("utf8", 0, buffer.length);
            var lines = data.split("\n");
            delete lines[0];

            var hours = 0;

            // Totals (for tallying)
            // console.log(resource.schema.fields);
            var outputs = {
              totals: {
                hours: 0,
                money: 0.00,
              },
              cli: '',
              html: ''
            };

            // Make Totals
            var increment_output = function(item) {

              outputs.totals.hours += item.time;
              outputs.totals.money += (item.time * item.rate);

              // CLI format
              outputs.cli += item.date + ' ' + item.time + ' \t' + item.client + ' \t' + item.description + '\n';

              // HTML format
              if (_.indexOf(args.options.format, 'html') > -1) {
                outputs.html += '
\n';
                outputs.html += '   ' + item.date + '	\n';
                outputs.html += '   ' + item.time + '	\n';
                outputs.html += '    hrs	\n';
                outputs.html += '   ' + item.description + '	\n';
                outputs.html += '
\n';
              }
            };

            var mapLineToSchema = function(line, schema, fields){
              // line is the line being processed,
              // schema is the schema provided in the resource,
              // fields is the fields required in the output, if blank it
              // defaults to everything in the schema.
              var parts = line.split(',');
              var lineItem = {};

              _.each(schema.fields, function(field, index){
                if (fields === undefined || fields.indexOf(field.name) !== -1){
                  var parsed;

                  if (field.type === 'date') {
                    parsed = moment(parts[index]).format('D MMM');
                  }
                  if (field.type === 'number'){
                    parsed = parseFloat(parts[index]);
                  }
                  if (field.type === 'string'){
                    parsed = parts[index].trim();
                  }
                  lineItem[field.name] = parsed;

                }
              });
              return lineItem;
            };

            // Filter by Date / Type
            var date_filter = 'none';

            if (args.options.date !== undefined) {

              var is_date_full        = /[0-9]{4}-[0-9]{2}-[0-9]{2}/;
              var is_date_year_month  = /[0-9]{4}-[0-9]{2}/;
              var is_date_month_day   = /[0-9]{2}-[0-9]{2}/;
              var is_date_year        = /[0-9]{4}/;

              if (is_date_full.exec(args.options.date)) {
                date_filter = 'full';
              } else if (is_date_year_month.exec(args.options.date)) {
                date_filter = 'year_month';
              } else if (is_date_month_day.exec(args.options.date)) {
                date_filter = 'month_day';
              } else if (is_date_year.exec(args.options.date)) {
                date_filter = 'year';
              } else {
                date_filter = 'month';
              }

              console.log('filter date by: ' + date_filter);
            }

            // Loop Through Items
            _.each(lines, function(line, key) {

              // FIXME: ADD MUCH BETTER CHECKING OF EMPTY LINES
              if (line && line !== undefined) {

                var parts = line.split(',');

                // Filter Date & Trim
                var check_date = Beardo.Date[date_filter](parts[0]);
                var check_trim = Beardo.Trim(parts);

                if (_.indexOf([check_date, check_trim], false) === -1) {

                  var item_output = mapLineToSchema(line, resource.schema);

                  increment_output(item_output);
                }
              }
            });

            // FIXME: OUTPUT STUFF (Refactor out)
            console.log('-----------------------------------------------------------------------------');
            console.log('Output Formats: ' + args.options.format);
            console.log('-----------------------------------------------------------------------------');
            console.log(outputs.cli);
            console.log('-----------------------------------------------------------------------------');
            console.log('Total hours worked: ' + outputs.totals.hours);
            console.log('Total monies earned: $' + outputs.totals.money);

            // Output HTML
            if (_.indexOf(args.options.format, 'html') > -1) {

              // Get HTML Template
              var template_path = './templates/invoice.html';

              // Open
              fs.exists(template_path, function(exists) {
              	if (exists) {

              		console.log('Beardo loaded template');
                  fs.stat(template_path, function(error, stats) {
                    fs.open(template_path, "r", function(error, fd) {
                      var buffer = new Buffer(stats.size);
                      fs.read(fd, buffer, 0, buffer.length, null, function(error, bytesRead, buffer) {
                        fs.close(fd);

                        // Invoice Name
                        var output_name = 'Beardo - ' + moment().format('D MMMM YYYY');
                        if (args.options.output) {
                          output_name = args.options.output;
                        }

                        var template_file = buffer.toString("utf8", 0, buffer.length);
                        var template_html = _.template(template_file);
                        var output_html   = template_html({
                          generated_name: output_name,
                          generated_date: moment().format('Do MMMM, YYYY'),
                          hours_rows: outputs.html,
                          hours_total: outputs.totals.hours,
                          money_total: outputs.totals.money
                        });

                        var saveFile = new SaveFile(fs, 'output/' + output_name + '.html', output_html);

                      });
                    });
                  });
                }
              });
            }
          });
        });
      });
  	}
  	else {
      console.log('awwww no data');
  	}

  });

};

// Load Schema
Beardo.Grow = function(schema_file) {

  fs.exists(schema_file, function(exists) {
  	if (exists) {

  		console.log('Splendid schema exists open it up');

      var path = require('path').dirname(schema_file);

      fs.stat(schema_file, function(error, stats) {
        fs.open(schema_file, "r", function(error, fd) {

          var buffer = new Buffer(stats.size);

          fs.read(fd, buffer, 0, buffer.length, null, function(error, bytesRead, buffer) {
            fs.close(fd);

            var json = buffer.toString("utf8", 0, buffer.length);
            var schema = JSON.parse(json);

            console.log('Get item from schema: ' + schema[0].name);

            // If Schema Contains Multiple
            _.each(schema[0].resources, function(resource, key) {

              console.log('Twirl resource: ' + resource.path);

              // Open Data
              Beardo.Twirl(path, resource);

            });

          });

        });
      });

    }
    else {
      console.log('awwww no schema');
    }

  });
};

// Start It Up
if (args.options.input !== undefined) {
  Beardo.Grow(args.options.input);
} else {
  console.log('404 No beard found \nAre you sure you specified an --input -i value');
}

<commit_msg>added boolean type to mapLineToSchema<commit_after>var fs      = require("fs");
var cheerio = require("cheerio");
var _       = require('underscore');
var moment  = require('moment');
var argv    = require('argv');
var net     = require('net');
var path    = require('path');
var repl    = require('repl');

// Args
argv.option({
  name: 'input',
  short: 'i',
  type: 'string',
  description: 'Defines schema file to open',
  example: "'beardo.js --schema=value' or 'beardo.js -s data/hours.json"
});

argv.option({
  name: 'format',
  short: 'f',
  type: 'csv,string',
  description: 'Defines output formats with html,cli',
  example: "'beardo.js --format=value' or 'beardo.js -f value1,value2'"
});

argv.option({
  name: 'output',
  short: 'o',
  type: 'string',
  description: 'Defines name to save output files as',
  example: "'beardo.js --save=value' or 'beardo.js -s January Invoice'"
});

argv.option({
  name: 'date',
  short: 'd',
  type: 'string',
  description: 'Returns only by current date (currently month only)',
  example: "'beardo.js --date=value' or 'beardo.js -d January or Jan or 01'"
});

argv.option({
  name: 'trim',
  short: 't',
  type: 'list,string',
  description: 'Trims output by a given string value declared in schema',
  example: "'beardo.js --trim=value' or 'beardo.js -t Client'"
});

var args = argv.run();

// File Manipulation
var SaveFile = require('./lib/save_file');

// Beardo
var Beardo = {};

Beardo.Date = {};

Beardo.Date.full = function(date) {

  var this_date = date.replace(/-/g,'');
  var filter_date = args.options.date.replace(/-/g, '');

  if (this_date >= filter_date) {
    //console.log('this date: 'this_date + ' is greater than filter date: ' + filter_date);
    return true;
  } else {
    return false;
  }
};

Beardo.Date.year_month = function(date) {

  if (date.indexOf(args.options.date) > -1) {
    //console.log('date filter by year_month ' + date);
    return true;
  } else {
    return false;
  }
};

Beardo.Date.month_day = function(date) {

  if (date.indexOf(args.options.date) > -1) {
    //console.log('date filter by month_day ' + date);
    return true;
  } else {
    return false;
  }
};

Beardo.Date.year = function(date) {

  if (date.indexOf(args.options.date) > -1) {
    //console.log('date filter by year ' + date);
    return true;
  } else {
    return false;
  }
};

Beardo.Date.month = function(date) {

  var date_trim = args.options.date.toLowerCase();
  var date_full = moment(date).format('MMMM').toLowerCase();
  var date_abbr = moment(date).format('MMM').toLowerCase();
  var date_numb = moment(date).format('MM').toLowerCase();

  if (_.indexOf([date_full, date_abbr, date_numb], date_trim) > -1) {
    //console.log('date matches filter: ' + date_trim)
    return true;
  } else {
    return false;
  }
};

Beardo.Date.none = function(parts) {
  console.log('no date filtering performed');
};

Beardo.Trim = function(parts) {
  if (args.options.trim !== undefined) {

    var part = parts[3].trim();

    if (_.indexOf(args.options.trim, part) > -1) {
      //console.log('client: ' + part + ' matches: ' + args.options.trim);
      return true;
    } else {
      return false;
    }
  } else {
    return true;
  }
};

// Load Data & Parse
Beardo.Twirl = function(path, resource) {

  var resource_file = path + '/' + resource.path;

  fs.exists(resource_file, function(exists) {
  	if (exists) {

  		console.log('Beardo is twirling some data');

      fs.stat(resource_file, function(error, stats) {
        fs.open(resource_file, "r", function(error, fd) {

          var buffer = new Buffer(stats.size);

          fs.read(fd, buffer, 0, buffer.length, null, function(error, bytesRead, buffer) {
            fs.close(fd);

            var data = buffer.toString("utf8", 0, buffer.length);
            var lines = data.split("\n");
            delete lines[0];

            var hours = 0;

            // Totals (for tallying)
            // console.log(resource.schema.fields);
            var outputs = {
              totals: {
                hours: 0,
                money: 0.00,
              },
              cli: '',
              html: ''
            };

            // Make Totals
            var increment_output = function(item) {

              outputs.totals.hours += item.time;
              outputs.totals.money += (item.time * item.rate);

              // CLI format
              outputs.cli += item.date + ' ' + item.time + ' \t' + item.client + ' \t' + item.description + '\n';

              // HTML format
              if (_.indexOf(args.options.format, 'html') > -1) {
                outputs.html += '
\n';
                outputs.html += '   ' + item.date + '	\n';
                outputs.html += '   ' + item.time + '	\n';
                outputs.html += '    hrs	\n';
                outputs.html += '   ' + item.description + '	\n';
                outputs.html += '
\n';
              }
            };

            var mapLineToSchema = function(line, schema, fields){
              // line is the line being processed,
              // schema is the schema provided in the resource,
              // fields is the fields required in the output, if blank it
              // defaults to everything in the schema.
              var parts = line.split(',');
              var lineItem = {};

              _.each(schema.fields, function(field, index){
                if (fields === undefined || fields.indexOf(field.name) !== -1){
                  var parsed;

                  if (field.type === 'date') {
                    parsed = moment(parts[index]).format('D MMM');
                  }
                  if (field.type === 'number'){
                    parsed = parseFloat(parts[index]);
                  }
                  if (field.type === 'string'){
                    parsed = parts[index].trim();
                  }
                  if (field.type === 'boolean'){
                    parsed = parts[index];
                    if (parsed === 'yes') parsed = true;
                    else if (parsed === 'no') parse = false;
                  }

                  // For Output
                  lineItem[field.name] = parsed;

                }
              });
              return lineItem;
            };

            // Filter by Date / Type
            var date_filter = 'none';

            if (args.options.date !== undefined) {

              var is_date_full        = /[0-9]{4}-[0-9]{2}-[0-9]{2}/;
              var is_date_year_month  = /[0-9]{4}-[0-9]{2}/;
              var is_date_month_day   = /[0-9]{2}-[0-9]{2}/;
              var is_date_year        = /[0-9]{4}/;

              if (is_date_full.exec(args.options.date)) {
                date_filter = 'full';
              } else if (is_date_year_month.exec(args.options.date)) {
                date_filter = 'year_month';
              } else if (is_date_month_day.exec(args.options.date)) {
                date_filter = 'month_day';
              } else if (is_date_year.exec(args.options.date)) {
                date_filter = 'year';
              } else {
                date_filter = 'month';
              }

              console.log('filter date by: ' + date_filter);
            }

            // Loop Through Items
            _.each(lines, function(line, key) {

              // FIXME: ADD MUCH BETTER CHECKING OF EMPTY LINES
              if (line && line !== undefined) {

                var parts = line.split(',');

                // Filter Date & Trim
                var check_date = Beardo.Date[date_filter](parts[0]);
                var check_trim = Beardo.Trim(parts);

                if (_.indexOf([check_date, check_trim], false) === -1) {

                  var item_output = mapLineToSchema(line, resource.schema);

                  increment_output(item_output);
                }
              }
            });

            // FIXME: OUTPUT STUFF (Refactor out)
            console.log('-----------------------------------------------------------------------------');
            console.log('Output Formats: ' + args.options.format);
            console.log('-----------------------------------------------------------------------------');
            console.log(outputs.cli);
            console.log('-----------------------------------------------------------------------------');
            console.log('Total hours worked: ' + outputs.totals.hours);
            console.log('Total monies earned: $' + outputs.totals.money);

            // Output HTML
            if (_.indexOf(args.options.format, 'html') > -1) {

              // Get HTML Template
              var template_path = './templates/invoice.html';

              // Open
              fs.exists(template_path, function(exists) {
              	if (exists) {

              		console.log('Beardo loaded template');
                  fs.stat(template_path, function(error, stats) {
                    fs.open(template_path, "r", function(error, fd) {
                      var buffer = new Buffer(stats.size);
                      fs.read(fd, buffer, 0, buffer.length, null, function(error, bytesRead, buffer) {
                        fs.close(fd);

                        // Invoice Name
                        var output_name = 'Beardo - ' + moment().format('D MMMM YYYY');
                        if (args.options.output) {
                          output_name = args.options.output;
                        }

                        var template_file = buffer.toString("utf8", 0, buffer.length);
                        var template_html = _.template(template_file);
                        var output_html   = template_html({
                          generated_name: output_name,
                          generated_date: moment().format('Do MMMM, YYYY'),
                          hours_rows: outputs.html,
                          hours_total: outputs.totals.hours,
                          money_total: outputs.totals.money
                        });

                        var saveFile = new SaveFile(fs, 'output/' + output_name + '.html', output_html);

                      });
                    });
                  });
                }
              });
            }
          });
        });
      });
  	}
  	else {
      console.log('awwww no data');
  	}

  });

};

// Load Schema
Beardo.Grow = function(schema_file) {

  fs.exists(schema_file, function(exists) {
  	if (exists) {

  		console.log('Splendid schema exists open it up');

      var path = require('path').dirname(schema_file);

      fs.stat(schema_file, function(error, stats) {
        fs.open(schema_file, "r", function(error, fd) {

          var buffer = new Buffer(stats.size);

          fs.read(fd, buffer, 0, buffer.length, null, function(error, bytesRead, buffer) {
            fs.close(fd);

            var json = buffer.toString("utf8", 0, buffer.length);
            var schema = JSON.parse(json);

            console.log('Get item from schema: ' + schema[0].name);

            // If Schema Contains Multiple
            _.each(schema[0].resources, function(resource, key) {

              console.log('Twirl resource: ' + resource.path);

              // Open Data
              Beardo.Twirl(path, resource);

            });

          });

        });
      });

    }
    else {
      console.log('awwww no schema');
    }

  });
};

// Start It Up
if (args.options.input !== undefined) {
  Beardo.Grow(args.options.input);
} else {
  console.log('404 No beard found \nAre you sure you specified an --input -i value');
}

<|endoftext|>


<commit_before>(function (fluid) {
    fluid.defaults("speakText.panels.CollectivePanel", {
        gradeNames: ["fluid.uiOptions.panels", "speakText.panels.keyEcho", "speakText.panels.wordEcho", "speakText.panels.speakTutorialMessages", "speakText.panels.speakTutorialMessages", "speakText.panels.screenReaderTTSEnabled", "speakText.panels.announceCapitals", "speakText.panels.punctuationVerbosity", "speakText.panels.screenReaderBrailleOutput", "speakText.panels.auditoryOutLanguage", "speakText.panels.speechRate", "autoInit"],

        partiallyExpandedSlideSpeed: 600,
        fullyExpandedSlideSpeed: 700,

        model: {
            speakTextPresetButton: false,
            addOrRemovePreference: false,
            moreOptions: false
        },

        messageResources: "{messageLoader}.resources",

        listeners: {
            onCreate: {
                listener: "speakText.panels.CollectivePanel.addResourcesAndAnimation",
                args: "{that}"
            },
            afterRender: {
                listener: "speakText.panels.CollectivePanel.activateCombobox",
                args: ["{that}"]
            }
        },

        selectors: {
            speakTextPresetButton: ".gpii-speakTextPresetButton",
            speakTextPresetButtonLabel: ".gpii-speakTextPresetButton-label",

            speakTextTickIcon: ".white-tick-icon",

            addOrRemovePreference: ".gpii-addOrRemovePreference",
            addOrRemovePreferenceLabel: ".gpii-addOrRemovePreference-label",

            moreOptions: ".more-options-checkbox",
            moreOptionsLabel: ".more-options-label",
            moreOptionsDiv: ".more-options",

            speechRateSelector: ".speech-rate-class",

            fullyExpanded: ".fully-expanded"
        },

        selectorsToIgnore: ["moreOptionsDiv", "speechRateSelector", "fullyExpanded", "speakTextTickIcon"],

        protoTree: {
            screenReaderTTSEnabled: "${screenReaderTTSEnabled}",
            screenReaderTTSEnabledLabel: {messagekey: "screenReaderTTSEnabledLabel"},

            addOrRemovePreference: "${addOrRemovePreference}",
            addOrRemovePreferenceLabel: {messagekey: "addOrRemovePreferenceLabelOff"},

            speechRate: {
                decorators: {
                    type: "fluid",
                    func: "gpii.uiOptions.textfieldStepper",
                    options: {
                        range: "{that}.options.controlValues.speechRate",
                        path: "value"
                    }
                }
            },
            speechRateLabel: {messagekey: "speechRateLabel"},
            speechRateMinus: {messagekey: "speechRateMinus"},
            speechRatePlus: {messagekey: "speechRatePlus"},

            auditoryOutLanguage: {
                selection: "${auditoryOutLanguage}",
                optionlist: "{that}.options.controlValues.auditoryOutLanguage"
            },
            auditoryOutLanguageLabel: {messagekey: "auditoryOutLanguageLabel"},

            expander: {
                type: "fluid.renderer.selection.inputs",
                rowID: "punctuationVerbosityRow",
                labelID: "punctuationVerbosityOptionLabel",
                inputID: "punctuationVerbosityInput",
                selectID: "punctuationVerbosity-selection",
                tree: {
                    optionnames: "{that}.options.controlValues.punctuationVerbosity",
                    optionlist: "{that}.options.controlValues.punctuationVerbosity",
                    selection: "${punctuationVerbosity}"
                }
            },
            punctuationVerbosityLabel: {messagekey: "punctuationVerbosityLabel"},
            punctuationVerbosityDescription: {messagekey: "punctuationVerbosityDescription"},

            announceCapitals: "${announceCapitals}",
            announceCapitalsLabel: {messagekey: "announceCapitalsLabel"},

            speakTutorialMessages: "${speakTutorialMessages}",
            speakTutorialMessagesLabel: {messagekey: "speakTutorialMessagesLabel"},

            keyEcho: "${keyEcho}",
            keyEchoLabel: {messagekey: "keyEchoLabel"},

            wordEcho: "${wordEcho}",
            wordEchoLabel: {messagekey: "wordEchoLabel"},

            screenReaderBrailleOutput: "${screenReaderBrailleOutput}",
            screenReaderBrailleOutputLabel: {messagekey: "screenReaderBrailleOutputLabel"},
            screenReaderBrailleOutputDescription: {messagekey: "screenReaderBrailleOutputDescription"},

            speakTextPresetButton: "${speakTextPresetButton}",
            speakTextPresetButtonLabel: {messagekey: "speakTextPresetButtonLabel"},

            moreOptions: "${moreOptions}",
            moreOptionsLabel: {messagekey: "moreOptions"}
        }
    });

    speakText.panels.CollectivePanel.addResourcesAndAnimation = function (that) {
        fluid.fetchResources(that.options.messageResources, function () {
            var completeMessage;
            fluid.each(that.options.messageResources, function (oneResource) {
                var message = JSON.parse(oneResource.resourceText);
                completeMessage = $.extend({}, completeMessage, message);
            });
            that.msgBundle = fluid.messageResolver({messageBase: completeMessage});
        });

        that.applier.modelChanged.addListener("speakTextPresetButton", function (newModel, oldModel, changeRequest) {
            if (newModel.speakTextPresetButton) {
                hook_newModel = newModel;
                that.locate("speakTextTickIcon").show();
                that.locate("moreOptionsLabel").text(that.msgBundle.messageBase.moreText);
                that.locate("speechRateSelector").slideDown(that.options.partiallyExpandedSlideSpeed);
                that.locate("moreOptionsDiv").slideDown(that.options.partiallyExpandedSlideSpeed);
            } else {
                that.locate("speakTextTickIcon").hide();
                that.locate("speechRateSelector").slideUp(that.options.partiallyExpandedSlideSpeed);
                that.locate("moreOptionsDiv").slideUp(that.options.partiallyExpandedSlideSpeed);
                that.locate("fullyExpanded").slideUp(that.options.partiallyExpandedSlideSpeed);
                that.locate("moreOptions").attr('checked', false);
            }
        });

        that.applier.modelChanged.addListener("moreOptions", function (newModel, oldModel, changeRequest) {
            if (newModel.moreOptions) {
                that.locate("fullyExpanded").slideDown(that.options.fullyExpandedSlideSpeed);
                that.locate("moreOptionsLabel").text(that.msgBundle.messageBase.lessText);
            } else {
                that.locate("fullyExpanded").slideUp(that.options.fullyExpandedSlideSpeed);
                that.locate("moreOptionsLabel").text(that.msgBundle.messageBase.moreText);
            }
        });

        hook = that;
    };

    speakText.panels.CollectivePanel.activateCombobox = function (that) {
        that.locate("speakTextTickIcon").hide();

        $("#auditoryOutLanguage").combobox();
        $("#auditoryOutLanguage").change(function (event, newValue) {
            that.applier.requestChange("auditoryOutLanguage", newValue);
        });
    };

})(fluid);
<commit_msg>GPII-153: A few repetitions removed by using local variables.<commit_after>(function (fluid) {
    fluid.defaults("speakText.panels.CollectivePanel", {
        gradeNames: ["fluid.uiOptions.panels", "speakText.panels.keyEcho", "speakText.panels.wordEcho", "speakText.panels.speakTutorialMessages", "speakText.panels.speakTutorialMessages", "speakText.panels.screenReaderTTSEnabled", "speakText.panels.announceCapitals", "speakText.panels.punctuationVerbosity", "speakText.panels.screenReaderBrailleOutput", "speakText.panels.auditoryOutLanguage", "speakText.panels.speechRate", "autoInit"],

        partiallyExpandedSlideSpeed: 600,
        fullyExpandedSlideSpeed: 700,

        model: {
            speakTextPresetButton: false,
            addOrRemovePreference: false,
            moreOptions: false
        },

        messageResources: "{messageLoader}.resources",

        listeners: {
            onCreate: {
                listener: "speakText.panels.CollectivePanel.addResourcesAndAnimation",
                args: "{that}"
            },
            afterRender: {
                listener: "speakText.panels.CollectivePanel.activateCombobox",
                args: ["{that}"]
            }
        },

        selectors: {
            speakTextPresetButton: ".gpii-speakTextPresetButton",
            speakTextPresetButtonLabel: ".gpii-speakTextPresetButton-label",

            speakTextTickIcon: ".white-tick-icon",

            addOrRemovePreference: ".gpii-addOrRemovePreference",
            addOrRemovePreferenceLabel: ".gpii-addOrRemovePreference-label",

            moreOptions: ".more-options-checkbox",
            moreOptionsLabel: ".more-options-label",
            moreOptionsDiv: ".more-options",

            speechRateSelector: ".speech-rate-class",

            fullyExpanded: ".fully-expanded"
        },

        selectorsToIgnore: ["moreOptionsDiv", "speechRateSelector", "fullyExpanded", "speakTextTickIcon"],

        protoTree: {
            screenReaderTTSEnabled: "${screenReaderTTSEnabled}",
            screenReaderTTSEnabledLabel: {messagekey: "screenReaderTTSEnabledLabel"},

            addOrRemovePreference: "${addOrRemovePreference}",
            addOrRemovePreferenceLabel: {messagekey: "addOrRemovePreferenceLabelOff"},

            speechRate: {
                decorators: {
                    type: "fluid",
                    func: "gpii.uiOptions.textfieldStepper",
                    options: {
                        range: "{that}.options.controlValues.speechRate",
                        path: "value"
                    }
                }
            },
            speechRateLabel: {messagekey: "speechRateLabel"},
            speechRateMinus: {messagekey: "speechRateMinus"},
            speechRatePlus: {messagekey: "speechRatePlus"},

            auditoryOutLanguage: {
                selection: "${auditoryOutLanguage}",
                optionlist: "{that}.options.controlValues.auditoryOutLanguage"
            },
            auditoryOutLanguageLabel: {messagekey: "auditoryOutLanguageLabel"},

            expander: {
                type: "fluid.renderer.selection.inputs",
                rowID: "punctuationVerbosityRow",
                labelID: "punctuationVerbosityOptionLabel",
                inputID: "punctuationVerbosityInput",
                selectID: "punctuationVerbosity-selection",
                tree: {
                    optionnames: "{that}.options.controlValues.punctuationVerbosity",
                    optionlist: "{that}.options.controlValues.punctuationVerbosity",
                    selection: "${punctuationVerbosity}"
                }
            },
            punctuationVerbosityLabel: {messagekey: "punctuationVerbosityLabel"},
            punctuationVerbosityDescription: {messagekey: "punctuationVerbosityDescription"},

            announceCapitals: "${announceCapitals}",
            announceCapitalsLabel: {messagekey: "announceCapitalsLabel"},

            speakTutorialMessages: "${speakTutorialMessages}",
            speakTutorialMessagesLabel: {messagekey: "speakTutorialMessagesLabel"},

            keyEcho: "${keyEcho}",
            keyEchoLabel: {messagekey: "keyEchoLabel"},

            wordEcho: "${wordEcho}",
            wordEchoLabel: {messagekey: "wordEchoLabel"},

            screenReaderBrailleOutput: "${screenReaderBrailleOutput}",
            screenReaderBrailleOutputLabel: {messagekey: "screenReaderBrailleOutputLabel"},
            screenReaderBrailleOutputDescription: {messagekey: "screenReaderBrailleOutputDescription"},

            speakTextPresetButton: "${speakTextPresetButton}",
            speakTextPresetButtonLabel: {messagekey: "speakTextPresetButtonLabel"},

            moreOptions: "${moreOptions}",
            moreOptionsLabel: {messagekey: "moreOptions"}
        }
    });

    speakText.panels.CollectivePanel.addResourcesAndAnimation = function (that) {
        fluid.fetchResources(that.options.messageResources, function () {
            var completeMessage;
            fluid.each(that.options.messageResources, function (oneResource) {
                var message = JSON.parse(oneResource.resourceText);
                completeMessage = $.extend({}, completeMessage, message);
            });
            that.msgBundle = fluid.messageResolver({messageBase: completeMessage});
        });

        that.applier.modelChanged.addListener("speakTextPresetButton", function (newModel) {
            var speed = that.options.partiallyExpandedSlideSpeed;

            if (newModel.speakTextPresetButton) {
                hook_newModel = newModel;
                that.locate("speakTextTickIcon").show();
                that.locate("moreOptionsLabel").text(that.msgBundle.messageBase.moreText);
                that.locate("speechRateSelector").slideDown(speed);
                that.locate("moreOptionsDiv").slideDown(speed);
            } else {
                that.locate("speakTextTickIcon").hide();
                that.locate("speechRateSelector").slideUp(speed);
                that.locate("moreOptionsDiv").slideUp(speed);
                that.locate("fullyExpanded").slideUp(speed);
                that.locate("moreOptions").attr('checked', false);
            }
        });

        that.applier.modelChanged.addListener("moreOptions", function (newModel) {
            var speed = that.options.fullyExpandedSlideSpeed;

            if (newModel.moreOptions) {
                that.locate("fullyExpanded").slideDown(speed);
                that.locate("moreOptionsLabel").text(that.msgBundle.messageBase.lessText);
            } else {
                that.locate("fullyExpanded").slideUp(speed);
                that.locate("moreOptionsLabel").text(that.msgBundle.messageBase.moreText);
            }
        });

        hook = that;
    };

    speakText.panels.CollectivePanel.activateCombobox = function (that) {
        that.locate("speakTextTickIcon").hide();

        $("#auditoryOutLanguage").combobox();
        $("#auditoryOutLanguage").change(function (event, newValue) {
            that.applier.requestChange("auditoryOutLanguage", newValue);
        });
    };

})(fluid);
<|endoftext|>


<commit_before>// ----------------------------------------------------------------------------
//
// connect-blog.js - Blog middleware you can add to your Connect/Express app.
//
// Copyright (c) 2013 Andrew Chilton. All rights resered.
//
// License: http://chilts.mit-license.org/2013/
//
// ----------------------------------------------------------------------------

// core
var fs = require('fs');

// npm
var moment = require('moment');
var marked = require('marked');
var xtend = require('xtend');
var data2xml = require('data2xml')({
    attrProp : '@',
    valProp  : '#',
});

// ----------------------------------------------------------------------------

var defaults = {
    title       : 'Blog',
    description : '',
    contentDir  : 'blog',
    latestCount : 10,
    basePath    : '',
};

var months = {
    '01' : 'January',
    '02' : 'February',
    '03' : 'March',
    '04' : 'April',
    '05' : 'May',
    '06' : 'June',
    '07' : 'July',
    '08' : 'August',
    '09' : 'September',
    '10' : 'October',
    '11' : 'November',
    '12' : 'December',
};

// ----------------------------------------------------------------------------

module.exports = function(args) {
    var opts = xtend({}, defaults, args);

    if ( !opts.domain ) {
        throw new Error("Provide a domain");
    }

    var post  = {};
    var posts = [];

    // read all the files from the content dir
    var files = fs.readdirSync(opts.contentDir);
    files.forEach(function(filename) {
        var parts = filename.split(/\./);
        var basename = parts[0];
        var ext = parts[1];

        // strip any initial numbers from the post name
        if ( basename.match(/^\d+-/) ) {
            basename = basename.replace(/^\d+-/, '');
        }

        post[basename] = post[basename] || {
            name : basename,
        };

        var contents = fs.readFileSync(opts.contentDir + '/' + filename, 'utf8');

        if ( ext === 'json' ) {
            try {
                post[basename].meta = JSON.parse(contents);
            }
            catch (e) {
                console.warn('Error parsing ' + filename + ' file : ' + e);
                process.exit(2);
            }

            // generate some fields
            var dt = post[basename].meta.datetime;
            post[basename].meta.year  = dt.substr(0, 4);
            post[basename].meta.month = dt.substr(5, 2);
            post[basename].meta.day   = dt.substr(8, 2);

            post[basename].meta.monthname = months[post[basename].meta.month];
            post[basename].meta.moment = moment(dt);
            post[basename].meta.datetime = new Date(dt);
        }
        if ( ext === 'md' ) {
            post[basename].content = contents;
            post[basename].html = marked(contents);
        }

    });

    // sort the posts by chronological order
    posts = Object.keys(post).map(function(name) {
        // get the post itself
        return post[name];
    }).sort(function(a, b) {
        // sort on datetime
        return a.meta.datetime > b.meta.datetime;
    });

    // set up an easy way to access the latest posts
    latest = posts.reverse().slice(0, opts.latestCount);

    // make the archive
    var archive = {};
    posts.forEach(function(post) {
        var year = post.meta.year;
        var month = post.meta.month;

        // setup blank year and/or month lists
        archive[year] = archive[year] || {};
        archive[year][month] = archive[year][month] || [];

        // add this post to this month's archive
        archive[year][month].push(post);
    });

    // keep a list of all the tagged
    var tagged = {};
    posts.forEach(function(post) {
        post.meta.tags.forEach(function(tag) {
            tagged[tag] = tagged[tag] || [];
            tagged[tag].push(post);
        });
    });

    var middleware = function(req, res, next) {
        // for every page (and a side-effect for the feeds), give them each access to these things
        res.locals.title   = opts.title;
        res.locals.posts   = posts;
        res.locals.latest  = latest;
        res.locals.archive = archive;
        res.locals.tagged  = tagged;

        var path = req.params.path;
        if ( !path ) {
            return res.render('blog-index');
        }

        // look for a page that looks like a blog
        if ( path === 'rss20.xml' ) {
            // firstly, make the RSS feed
            var rss = {
                '@' : { version : '2.0' },
                channel : {
                    title         : opts.title,
                    description   : opts.description,
                    link          : 'http://' + opts.domain + opts.base + '/rss.xml',
                    lastBuildDate : moment().format("ddd, DD MMM YYYY HH:MM:SS Z"),
                    pubDate       : moment().format("ddd, DD MMM YYYY HH:MM:SS Z"),
                    ttl           : 1800,
                    item          : [],
                }
            };

            rss.item = posts.map(function(post, i) {
                return {
                    title       : post.meta.title,
                    description : post.html,
                    link        : 'http://' + opts.domain + opts.base + '/' + post.name,
                    guid        : 'http://' + opts.domain + opts.base + '/' + post.name,
                    pubDate     : post.meta.moment.format("ddd, DD MMM YYYY HH:MM:SS Z"),
                };
            });

            res.set('Content-Type', 'application/xml');
            return res.send(data2xml('rss', rss));
        }

        if ( path === 'atom.xml' ) {

            var atom = {
                '@'     : { xmlns : 'http://www.w3.org/2005/Atom' },
                title   : opts.title,
                link    : {
                    '@' : {
                        href : 'http://' + opts.domain + opts.base + '/atom.xml',
                        rel  : 'self',
                    },
                },
                updated : moment().format(),
                id      : 'http://' + opts.domain + '/',
                author  : {
                    name  : 'Andrew Chilton',
                    email : 'andychilton@gmail.com',
                },
                entry   : [],
            };

            atom.entry = posts.map(function(post, i) {
                return {
                    title   : post.meta.title,
                    id      : 'http://' + opts.domain + opts.base + '/' + post.name,
                    link    : [
                        {
                            '@' : { href : 'http://' + opts.domain + opts.base + '/' + post.name }
                        },
                        {
                            '@' : {
                                href : 'http://' + opts.domain + opts.base + '/' + post.name,
                                rel : 'self'
                            }
                        }
                    ],
                    content : {
                        '@' : { type : 'html' },
                        '#' : post.html,
                    },
                    updated : post.meta.moment.format(),
                };
            });

            res.set('Content-Type', 'application/xml');
            return res.send(data2xml('feed', atom));
        }

        if ( path === 'archive' ) {
            return res.render('blog-archive', {
                title       : opts.title + ' : Archive',
                thisArchive : archive,
            });
        }

        // do we even need this 'archive' stuff anymore ... seriously?
        if ( path.indexOf('archive:') === 0 ) {
            var thisArchive = {};
            var parts = path.split(/:/)[1].split(/\-/);
            var thisYear = parts[0];
            var thisMonth = parts[1];
            if ( parts.length === 1 && archive[thisYear] ) {
                thisArchive[thisYear] = archive[thisYear];
            }
            else if ( parts.length === 2 && archive[thisYear] && archive[thisYear][thisMonth] ) {
                thisArchive[thisYear] = {};
                thisArchive[thisYear][thisMonth] = archive[thisYear][thisMonth];
            }
            else {
                // don't know this format
                return next();
            }

            return res.render('blog-archive', {
                title       : opts.title + ' : Archive : ' + thisYear + (thisMonth ? '-' + thisMonth : ''),
                thisArchive : thisArchive,
            });
        }

        if ( path === 'tag' ) {
            return res.render('blog-tagcloud', {
                title : opts.title + ' : TagCloud',
            });
        }

        if ( path.indexOf('tag:') === 0 ) {
            var parts = path.split(/:/);
            var tagName = parts[1];
            if ( !tagged[tagName] ) {
                // 404 - Not Found
                return next();
            }

            return res.render('blog-tag', {
                title       : opts.title + ' : Tag : ' + tagName,
                thesePosts  : tagged[tagName],
                thisTagName : tagName,
            });
        }

        // is this a post
        if ( post[path] ) {
            return res.render('blog-post', {
                title    : opts.title + ' : ' + post[path].meta.title,
                thisPost : post[path],
            });
        }

        // didn't find anything interesting, pass it on
        next();
    };

    // prior to returning, let's put these vars onto this middleware so
    // the user can get access to some interesting things
    middleware.posts   = posts;
    middleware.latest  = latest;
    middleware.archive = archive;
    middleware.tagged  = tagged;

    return middleware;
};

// ----------------------------------------------------------------------------
<commit_msg>Fix date in RSS v2.0 feed<commit_after>// ----------------------------------------------------------------------------
//
// connect-blog.js - Blog middleware you can add to your Connect/Express app.
//
// Copyright (c) 2013 Andrew Chilton. All rights resered.
//
// License: http://chilts.mit-license.org/2013/
//
// ----------------------------------------------------------------------------

// core
var fs = require('fs');

// npm
var moment = require('moment');
var marked = require('marked');
var xtend = require('xtend');
var data2xml = require('data2xml')({
    attrProp : '@',
    valProp  : '#',
});

// ----------------------------------------------------------------------------

var defaults = {
    title       : 'Blog',
    description : '',
    contentDir  : 'blog',
    latestCount : 10,
    basePath    : '',
};

var months = {
    '01' : 'January',
    '02' : 'February',
    '03' : 'March',
    '04' : 'April',
    '05' : 'May',
    '06' : 'June',
    '07' : 'July',
    '08' : 'August',
    '09' : 'September',
    '10' : 'October',
    '11' : 'November',
    '12' : 'December',
};

// ----------------------------------------------------------------------------

module.exports = function(args) {
    var opts = xtend({}, defaults, args);

    if ( !opts.domain ) {
        throw new Error("Provide a domain");
    }

    var post  = {};
    var posts = [];

    // read all the files from the content dir
    var files = fs.readdirSync(opts.contentDir);
    files.forEach(function(filename) {
        var parts = filename.split(/\./);
        var basename = parts[0];
        var ext = parts[1];

        // strip any initial numbers from the post name
        if ( basename.match(/^\d+-/) ) {
            basename = basename.replace(/^\d+-/, '');
        }

        post[basename] = post[basename] || {
            name : basename,
        };

        var contents = fs.readFileSync(opts.contentDir + '/' + filename, 'utf8');

        if ( ext === 'json' ) {
            try {
                post[basename].meta = JSON.parse(contents);
            }
            catch (e) {
                console.warn('Error parsing ' + filename + ' file : ' + e);
                process.exit(2);
            }

            // generate some fields
            var dt = post[basename].meta.datetime;
            post[basename].meta.year  = dt.substr(0, 4);
            post[basename].meta.month = dt.substr(5, 2);
            post[basename].meta.day   = dt.substr(8, 2);

            post[basename].meta.monthname = months[post[basename].meta.month];
            post[basename].meta.moment = moment(dt);
            post[basename].meta.datetime = new Date(dt);
        }
        if ( ext === 'md' ) {
            post[basename].content = contents;
            post[basename].html = marked(contents);
        }

    });

    // sort the posts by chronological order
    posts = Object.keys(post).map(function(name) {
        // get the post itself
        return post[name];
    }).sort(function(a, b) {
        // sort on datetime
        return a.meta.datetime > b.meta.datetime;
    });

    // set up an easy way to access the latest posts
    latest = posts.reverse().slice(0, opts.latestCount);

    // make the archive
    var archive = {};
    posts.forEach(function(post) {
        var year = post.meta.year;
        var month = post.meta.month;

        // setup blank year and/or month lists
        archive[year] = archive[year] || {};
        archive[year][month] = archive[year][month] || [];

        // add this post to this month's archive
        archive[year][month].push(post);
    });

    // keep a list of all the tagged
    var tagged = {};
    posts.forEach(function(post) {
        post.meta.tags.forEach(function(tag) {
            tagged[tag] = tagged[tag] || [];
            tagged[tag].push(post);
        });
    });

    var middleware = function(req, res, next) {
        // for every page (and a side-effect for the feeds), give them each access to these things
        res.locals.title   = opts.title;
        res.locals.posts   = posts;
        res.locals.latest  = latest;
        res.locals.archive = archive;
        res.locals.tagged  = tagged;

        var path = req.params.path;
        if ( !path ) {
            return res.render('blog-index');
        }

        // look for a page that looks like a blog
        if ( path === 'rss20.xml' ) {
            // firstly, make the RSS feed
            var rss = {
                '@' : { version : '2.0' },
                channel : {
                    title         : opts.title,
                    description   : opts.description,
                    link          : 'http://' + opts.domain + opts.base + '/rss.xml',
                    lastBuildDate : moment().format("ddd, DD MMM YYYY HH:MM:SS ZZ"),
                    pubDate       : moment().format("ddd, DD MMM YYYY HH:MM:SS ZZ"),
                    ttl           : 1800,
                    item          : [],
                }
            };

            rss.item = posts.map(function(post, i) {
                return {
                    title       : post.meta.title,
                    description : post.html,
                    link        : 'http://' + opts.domain + opts.base + '/' + post.name,
                    guid        : 'http://' + opts.domain + opts.base + '/' + post.name,
                    pubDate     : post.meta.moment.format("ddd, DD MMM YYYY HH:MM:SS ZZ"),
                };
            });

            res.set('Content-Type', 'application/xml');
            return res.send(data2xml('rss', rss));
        }

        if ( path === 'atom.xml' ) {

            var atom = {
                '@'     : { xmlns : 'http://www.w3.org/2005/Atom' },
                title   : opts.title,
                link    : {
                    '@' : {
                        href : 'http://' + opts.domain + opts.base + '/atom.xml',
                        rel  : 'self',
                    },
                },
                updated : moment().format(),
                id      : 'http://' + opts.domain + '/',
                author  : {
                    name  : 'Andrew Chilton',
                    email : 'andychilton@gmail.com',
                },
                entry   : [],
            };

            atom.entry = posts.map(function(post, i) {
                return {
                    title   : post.meta.title,
                    id      : 'http://' + opts.domain + opts.base + '/' + post.name,
                    link    : [
                        {
                            '@' : { href : 'http://' + opts.domain + opts.base + '/' + post.name }
                        },
                        {
                            '@' : {
                                href : 'http://' + opts.domain + opts.base + '/' + post.name,
                                rel : 'self'
                            }
                        }
                    ],
                    content : {
                        '@' : { type : 'html' },
                        '#' : post.html,
                    },
                    updated : post.meta.moment.format(),
                };
            });

            res.set('Content-Type', 'application/xml');
            return res.send(data2xml('feed', atom));
        }

        if ( path === 'archive' ) {
            return res.render('blog-archive', {
                title       : opts.title + ' : Archive',
                thisArchive : archive,
            });
        }

        // do we even need this 'archive' stuff anymore ... seriously?
        if ( path.indexOf('archive:') === 0 ) {
            var thisArchive = {};
            var parts = path.split(/:/)[1].split(/\-/);
            var thisYear = parts[0];
            var thisMonth = parts[1];
            if ( parts.length === 1 && archive[thisYear] ) {
                thisArchive[thisYear] = archive[thisYear];
            }
            else if ( parts.length === 2 && archive[thisYear] && archive[thisYear][thisMonth] ) {
                thisArchive[thisYear] = {};
                thisArchive[thisYear][thisMonth] = archive[thisYear][thisMonth];
            }
            else {
                // don't know this format
                return next();
            }

            return res.render('blog-archive', {
                title       : opts.title + ' : Archive : ' + thisYear + (thisMonth ? '-' + thisMonth : ''),
                thisArchive : thisArchive,
            });
        }

        if ( path === 'tag' ) {
            return res.render('blog-tagcloud', {
                title : opts.title + ' : TagCloud',
            });
        }

        if ( path.indexOf('tag:') === 0 ) {
            var parts = path.split(/:/);
            var tagName = parts[1];
            if ( !tagged[tagName] ) {
                // 404 - Not Found
                return next();
            }

            return res.render('blog-tag', {
                title       : opts.title + ' : Tag : ' + tagName,
                thesePosts  : tagged[tagName],
                thisTagName : tagName,
            });
        }

        // is this a post
        if ( post[path] ) {
            return res.render('blog-post', {
                title    : opts.title + ' : ' + post[path].meta.title,
                thisPost : post[path],
            });
        }

        // didn't find anything interesting, pass it on
        next();
    };

    // prior to returning, let's put these vars onto this middleware so
    // the user can get access to some interesting things
    middleware.posts   = posts;
    middleware.latest  = latest;
    middleware.archive = archive;
    middleware.tagged  = tagged;

    return middleware;
};

// ----------------------------------------------------------------------------
<|endoftext|>


<commit_before>import React from "react"
import { Modal } from "../../components/CommonElement"
import { connect } from "react-redux"
import { getTranslate } from 'react-localize-redux';

@connect((store, props) => {
  return {
    clickCheckbox: props.clickCheckbox,
    termAgree: props.termAgree,
    translate: getTranslate(store.locale)
  }
})

export default class TermAndServices extends React.Component {

  constructor() {
    super()
    this.state = {
      isOpen: false,
    }
  }

  showTerms = () => {
    this.setState({ isOpen: true })
  }

  onRequestClose = () => {
    this.setState({ isOpen: false })
  }

  changeCheckbox = (e) => {
    this.props.clickCheckbox(!this.props.termAgree)
  }

  content = () => {
    return (

{this.props.translate("terms.title") || "KyberWallet - Terms of Use"}

      ×

{this.contentBody()}

)
  }
  contentBody = () => {
    return (

              {this.props.translate("terms.content") || `Kyber testnet wallet provides a platform for experimenting and understanding
            our exchange and payment services. The current implementation is not
            secure in any way. Using it may cause loss of funds and could compromise
            user privacy. The user bears the sole responsibility for any outcome that
            is using Kyber testnet wallet.`}

              {this.props.translate("terms.use_testnet") || "USE ONLY TESTNET ACCOUNTS!!!"}

              {this.props.translate("terms.use_real") || "DO NOT USE REAL ETHEREUM ACCOUNTS!!!"}

    )
  }

  render() {
    var src = this.props.termAgree ? require("../../../assets/img/checkmark-selected.svg")
      : require("../../../assets/img/checkmark-unselected.svg")
    return (

           this.changeCheckbox(e)} src={src} width="14"/>

            Accept Terms and Conditions to get started

        <Modal className={{
          base: 'reveal medium',
          afterOpen: 'reveal medium'
        }}
          isOpen={this.state.isOpen}
          onRequestClose={this.onRequestClose}
          contentLabel="Terms and Services"
          content={this.content()}
        />

    )
  }
}
<commit_msg>update langdingpage css<commit_after>import React from "react"
import { Modal } from "../../components/CommonElement"
import { connect } from "react-redux"
import { getTranslate } from 'react-localize-redux';

@connect((store, props) => {
  return {
    clickCheckbox: props.clickCheckbox,
    termAgree: props.termAgree,
    translate: getTranslate(store.locale)
  }
})

export default class TermAndServices extends React.Component {

  constructor() {
    super()
    this.state = {
      isOpen: false,
    }
  }

  showTerms = () => {
    this.setState({ isOpen: true })
  }

  onRequestClose = () => {
    this.setState({ isOpen: false })
  }

  changeCheckbox = (e) => {
    this.props.clickCheckbox(!this.props.termAgree)
  }

  content = () => {
    return (

{this.props.translate("terms.title") || "KyberWallet - Terms of Use"}

      ×

{this.contentBody()}

)
  }
  contentBody = () => {
    return (

              {this.props.translate("terms.content") || `Kyber testnet wallet provides a platform for experimenting and understanding
            our exchange and payment services. The current implementation is not
            secure in any way. Using it may cause loss of funds and could compromise
            user privacy. The user bears the sole responsibility for any outcome that
            is using Kyber testnet wallet.`}

              {this.props.translate("terms.use_testnet") || "USE ONLY TESTNET ACCOUNTS!!!"}

              {this.props.translate("terms.use_real") || "DO NOT USE REAL ETHEREUM ACCOUNTS!!!"}

    )
  }

  render() {
    var src = this.props.termAgree ? require("../../../assets/img/checkmark-selected.svg")
      : require("../../../assets/img/checkmark-unselected.svg")
    return (

           this.changeCheckbox(e)} src={src} width="14"/>

             this.changeCheckbox(e)}>Accept Terms and Conditions to get started

        <Modal className={{
          base: 'reveal medium',
          afterOpen: 'reveal medium'
        }}
          isOpen={this.state.isOpen}
          onRequestClose={this.onRequestClose}
          contentLabel="Terms and Services"
          content={this.content()}
        />

    )
  }
}
<|endoftext|>


<commit_before><commit_msg>fix language.update bug<commit_after><|endoftext|>


<commit_before>/**
 * @fileoverview OAuth client.
 *
 */

goog.provide('ydn.client.OAuthClient');
goog.provide('ydn.client.OAuthProvider');
goog.require('goog.async.Deferred');
goog.require('ydn.client.Client');

/**
 * @interface
 */
ydn.client.OAuthProvider = function() {};

/**
 * @return {goog.async.Deferred}
 */
ydn.client.OAuthProvider.prototype.getOAuthToken = goog.abstractMethod;

/**
 * OAuth client.
 * @param {ydn.client.OAuthProvider} provider
 * @param {goog.net.XhrManager} xm xhr manager.
 * @constructor
 * @implements {ydn.client.Client}
 * @const
 */
ydn.client.OAuthClient = function(provider, xm) {
  /**
   * @protected
   * @type {ydn.client.OAuthProvider}
   */
  this.provider = provider;
  /**
   * @protected
   * @type {goog.net.XhrManager}
   */
  this.xm = xm;
  /**
   * @protected
   * @type {YdnApiToken}
   */
  this.token = null;
};

/**
 * @inheritDoc
 */
ydn.client.OAuthClient.prototype.request = function(req) {
  return new ydn.client.OAuthClient.Request(req, this);
};

/**
 * Request data.
 * @param {ydn.client.HttpRequestData} args
 * @param {ydn.client.OAuthClient} parent xhr manager.
 * @constructor
 * @extends {ydn.client.SimpleHttpRequest}
 */
ydn.client.OAuthClient.Request = function(args, parent) {
  goog.base(this, args, parent.xm);
  /**
   * @final
   * @type {ydn.client.OAuthClient}
   */
  this.parent = parent;
};
goog.inherits(ydn.client.OAuthClient.Request, ydn.client.SimpleHttpRequest);

/**
 * @const
 * @type {boolean}
 */
ydn.client.OAuthClient.USE_AUTHORIZATION_HEADER = true;

/**
 * @inheritDoc
 */
ydn.client.OAuthClient.Request.prototype.execute = function(cb, opt_scope, opt_no_retry) {
  var token = this.parent.token;
  if (token && token.expires < goog.now()) {
    if (ydn.client.OAuthClient.USE_AUTHORIZATION_HEADER) {
      this.req_data.headers['Authorization'] = 'Bearer ' + token.access_token;
    } else {
      this.req_data.params['access_token'] = token.access_token;
    }
    goog.base(this, 'execute', cb, opt_scope);
    return;
  } else if (opt_no_retry) {
    cb.call(opt_scope, null, new ydn.client.HttpRespondData(0));
    return;
  }
  this.parent.provider.getOAuthToken().addCallbacks(function(x) {
    this.parent.token = /** @type {YdnApiToken} */ (x);
    this.execute(cb, opt_scope, true);
  }, function(e) {
    this.parent.token = null;
    cb.call(opt_scope, null, new ydn.client.HttpRespondData(0));
  }, this);
};

<commit_msg>new login system.<commit_after>/**
 * @fileoverview OAuth client.
 *
 */

goog.provide('ydn.client.OAuthClient');
goog.provide('ydn.client.OAuthProvider');
goog.require('goog.async.Deferred');
goog.require('ydn.client.Client');
goog.require('ydn.client.SimpleHttpRequest');

/**
 * @interface
 */
ydn.client.OAuthProvider = function() {};

/**
 * @return {goog.async.Deferred}
 */
ydn.client.OAuthProvider.prototype.getOAuthToken = goog.abstractMethod;

/**
 * OAuth client.
 * @param {ydn.client.OAuthProvider} provider
 * @param {goog.net.XhrManager} xm xhr manager.
 * @constructor
 * @implements {ydn.client.Client}
 * @const
 */
ydn.client.OAuthClient = function(provider, xm) {
  /**
   * @protected
   * @type {ydn.client.OAuthProvider}
   */
  this.provider = provider;
  /**
   * @protected
   * @type {goog.net.XhrManager}
   */
  this.xm = xm;
  /**
   * @protected
   * @type {YdnApiToken}
   */
  this.token = null;
};

/**
 * @inheritDoc
 */
ydn.client.OAuthClient.prototype.request = function(req) {
  return new ydn.client.OAuthClient.Request(req, this);
};

/**
 * Request data.
 * @param {ydn.client.HttpRequestData} args
 * @param {ydn.client.OAuthClient} parent xhr manager.
 * @constructor
 * @extends {ydn.client.SimpleHttpRequest}
 */
ydn.client.OAuthClient.Request = function(args, parent) {
  goog.base(this, args, parent.xm);
  /**
   * @final
   * @type {ydn.client.OAuthClient}
   */
  this.parent = parent;
  this.no_retry_ = false;
};
goog.inherits(ydn.client.OAuthClient.Request, ydn.client.SimpleHttpRequest);

/**
 * @const
 * @type {boolean}
 */
ydn.client.OAuthClient.USE_AUTHORIZATION_HEADER = false;

/**
 * Execute the request.
 * @param {function(this: T, Object, ydn.client.HttpRespondData)?} cb
 * @param {T=} opt_scope scope.
 * @template T
 */
ydn.client.OAuthClient.Request.prototype.execute = function(cb, opt_scope) {
  var token = this.parent.token;
  if (!token || token.expires > goog.now()) {
    if (this.no_retry_) {
      if (cb) {
        cb.call(opt_scope, null, new ydn.client.HttpRespondData(0));
      }
    } else {
      this.no_retry_ = true;
      this.parent.provider.getOAuthToken().addCallbacks(function(x) {
        this.parent.token = /** @type {YdnApiToken} */ (x);
        this.execute(cb, opt_scope);
      }, function(e) {
        this.parent.token = null;
        if (cb) {
          cb.call(opt_scope, null, new ydn.client.HttpRespondData(0));
        }
      }, this);
    }

  } else {
    if (ydn.client.OAuthClient.USE_AUTHORIZATION_HEADER) {
      this.req_data.headers['Authorization'] = 'Bearer ' + token.access_token;
    } else {
      this.req_data.params['access_token'] = token.access_token;
    }
    goog.base(this, 'execute', cb, opt_scope);
  }

};

<|endoftext|>


<commit_before>/**
 * @license
 * Visual Blocks Editor
 *
 * Copyright 2012 Google Inc.
 * https://developers.google.com/blockly/
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @fileoverview Variable input field.
 * @author fraser@google.com (Neil Fraser)
 */
'use strict';

goog.provide('Blockly.FieldVariable');

goog.require('Blockly.FieldDropdown');
goog.require('Blockly.Msg');
goog.require('Blockly.VariableModel');
goog.require('Blockly.Variables');
goog.require('goog.asserts');
goog.require('goog.string');

/**
 * Class for a variable's dropdown field.
 * @param {?string} varname The default name for the variable.  If null,
 *     a unique variable name will be generated.
 * @param {Function=} opt_validator A function that is executed when a new
 *     option is selected.  Its sole argument is the new option value.
 * @param {Array.<string>=} opt_variableTypes A list of the types of variables
 *     to include in the dropdown.
 * @param {string=} opt_defaultType The type of variable to create if this
 *     field's value is not explicitly set.  Defaults to ''.
 * @extends {Blockly.FieldDropdown}
 * @constructor
 */
Blockly.FieldVariable = function(varname, opt_validator, opt_variableTypes,
    opt_defaultType) {
  // The FieldDropdown constructor would call setValue, which might create a
  // spurious variable.  Just do the relevant parts of the constructor.
  this.menuGenerator_ = Blockly.FieldVariable.dropdownCreate;
  this.size_ = new goog.math.Size(0, Blockly.BlockSvg.MIN_BLOCK_Y);
  this.setValidator(opt_validator);
  this.defaultVariableName = (varname || '');

  this.setTypes_(opt_variableTypes, opt_defaultType);
  this.value_ = null;
};
goog.inherits(Blockly.FieldVariable, Blockly.FieldDropdown);

/**
 * Initialize everything needed to render this field.  This includes making sure
 * that the field's value is valid.
 * @public
 */
Blockly.FieldVariable.prototype.init = function() {
  if (this.fieldGroup_) {
    // Dropdown has already been initialized once.
    return;
  }
  Blockly.FieldVariable.superClass_.init.call(this);

  // TODO (1010): Change from init/initModel to initView/initModel
  this.initModel();
};

/**
 * Initialize the model for this field if it has not already been initialized.
 * If the value has not been set to a variable by the first render, we make up a
 * variable rather than let the value be invalid.
 * @package
 */
Blockly.FieldVariable.prototype.initModel = function() {
  if (this.variable_) {
    return; // Initialization already happened.
  }
  this.workspace_ = this.sourceBlock_.workspace;
  var variable = Blockly.Variables.getOrCreateVariablePackage(
      this.workspace_, null, this.defaultVariableName, this.defaultType_);

  // Don't fire a change event for this setValue.  It would have null as the
  // old value, which is not valid.
  Blockly.Events.disable();
  try {
    this.setValue(variable.getId());
  } finally {
    Blockly.Events.enable();
  }
};

/**
 * Dispose of this field.
 * @public
 */
Blockly.FieldVariable.dispose = function() {
  Blockly.FieldVariable.superClass_.dispose.call(this);
  this.workspace_ = null;
  this.variableMap_ = null;
};

/**
 * Attach this field to a block.
 * @param {!Blockly.Block} block The block containing this field.
 */
Blockly.FieldVariable.prototype.setSourceBlock = function(block) {
  goog.asserts.assert(!block.isShadow(),
      'Variable fields are not allowed to exist on shadow blocks.');
  Blockly.FieldVariable.superClass_.setSourceBlock.call(this, block);
};

/**
 * Get the variable's ID.
 * @return {string} Current variable's ID.
 */
Blockly.FieldVariable.prototype.getValue = function() {
  return this.variable_ ? this.variable_.getId() : null;
};

/**
 * Get the text from this field, which is the selected variable's name.
 * @return {string} The selected variable's name, or the empty string if no
 *     variable is selected.
 */
Blockly.FieldVariable.prototype.getText = function() {
  return this.variable_ ? this.variable_.name : '';
};

/**
 * Get the variable model for the selected variable.
 * Not guaranteed to be in the variable map on the workspace (e.g. if accessed
 * after the variable has been deleted).
 * @return {?Blockly.VariableModel} the selected variable, or null if none was
 *     selected.
 * @package
 */
Blockly.FieldVariable.prototype.getVariable = function() {
  return this.variable_;
};

/**
 * Set the variable ID.
 * @param {string} id New variable ID, which must reference an existing
 *     variable.
 */
Blockly.FieldVariable.prototype.setValue = function(id) {
  var workspace = this.sourceBlock_.workspace;
  var variable = Blockly.Variables.getVariable(workspace, id);

  if (!variable) {
    throw new Error('Variable id doesn\'t point to a real variable!  ID was ' +
        id);
  }
  // Type checks!
  var type = variable.type;
  if (!this.typeIsAllowed_(type)) {
    throw new Error('Variable type doesn\'t match this field!  Type was ' +
        type);
  }
  if (this.sourceBlock_ && Blockly.Events.isEnabled()) {
    var oldValue = this.variable_ ? this.variable_.getId() : null;
    Blockly.Events.fire(new Blockly.Events.BlockChange(
        this.sourceBlock_, 'field', this.name, oldValue, id));
  }
  this.variable_ = variable;
  this.value_ = id;
  this.setText(variable.name);
};

/**
 * Check whether the given variable type is allowed on this field.
 * @param {string} type The type to check.
 * @return {boolean} True if the type is in the list of allowed types.
 * @private
 */
Blockly.FieldVariable.prototype.typeIsAllowed_ = function(type) {
  var typeList = this.getVariableTypes_();
  if (!typeList) {
    return true; // If it's null, all types are valid.
  }
  for (var i = 0; i < typeList.length; i++) {
    if (type == typeList[i]) {
      return true;
    }
  }
  return false;
};

/**
 * Return a list of variable types to include in the dropdown.
 * @return {!Array.<string>} Array of variable types.
 * @throws {Error} if variableTypes is an empty array.
 * @private
 */
Blockly.FieldVariable.prototype.getVariableTypes_ = function() {
  // TODO (#1513): Try to avoid calling this every time the field is edited.
  var variableTypes = this.variableTypes;
  if (variableTypes === null) {
    // If variableTypes is null, return all variable types.
    if (this.sourceBlock_) {
      var workspace = this.sourceBlock_.workspace;
      return workspace.getVariableTypes();
    }
  }
  variableTypes = variableTypes || [''];
  if (variableTypes.length == 0) {
    // Throw an error if variableTypes is an empty list.
    var name = this.getText();
    throw new Error('\'variableTypes\' of field variable ' +
      name + ' was an empty list');
  }
  return variableTypes;
};

/**
 * Parse the optional arguments representing the allowed variable types and the
 * default variable type.
 * @param {Array.<string>=} opt_variableTypes A list of the types of variables
 *     to include in the dropdown.  If null or undefined, variables of all types
 *     will be displayed in the dropdown.
 * @param {string=} opt_defaultType The type of the variable to create if this
 *     field's value is not explicitly set.  Defaults to ''.
 * @private
 */
Blockly.FieldVariable.prototype.setTypes_ = function(opt_variableTypes,
    opt_defaultType) {
  // If you expected that the default type would be the same as the only entry
  // in the variable types array, tell the Blockly team by commenting on #1499.
  this.defaultType_ = opt_defaultType || '';
  // Set the allowable variable types.  Null means all types on the workspace.
  if (opt_variableTypes == null || opt_variableTypes == undefined) {
    this.variableTypes = null;
  } else if (Array.isArray(opt_variableTypes)) {
    this.variableTypes = opt_variableTypes;
    // Make sure the default type is valid.
    var isInArray = false;
    for (var i = 0; i < this.variableTypes.length; i++) {
      if (this.variableTypes[i] == this.defaultType_) {
        isInArray = true;
      }
    }
    if (!isInArray) {
      throw new Error('Invalid default type \'' + this.defaultType_ + '\' in ' +
          'the definition of a FieldVariable');
    }
  } else {
    throw new Error('\'variableTypes\' was not an array in the definition of ' +
        'a FieldVariable');
  }
};

/**
 * Return a sorted list of variable names for variable dropdown menus.
 * Include a special option at the end for creating a new variable name.
 * @return {!Array.<string>} Array of variable names.
 * @this {Blockly.FieldVariable}
 */
Blockly.FieldVariable.dropdownCreate = function() {
  if (!this.variable_) {
    throw new Error('Tried to call dropdownCreate on a variable field with no' +
        ' variable selected.');
  }
  var variableModelList = [];
  var name = this.getText();
  var workspace = null;
  if (this.sourceBlock_) {
    workspace = this.sourceBlock_.workspace;
  }
  if (workspace) {
    var variableTypes = this.getVariableTypes_();
    var variableModelList = [];
    // Get a copy of the list, so that adding rename and new variable options
    // doesn't modify the workspace's list.
    for (var i = 0; i < variableTypes.length; i++) {
      var variableType = variableTypes[i];
      var variables = workspace.getVariablesOfType(variableType);
      variableModelList = variableModelList.concat(variables);
    }
  }
  variableModelList.sort(Blockly.VariableModel.compareByName);

  var options = [];
  for (var i = 0; i < variableModelList.length; i++) {
    // Set the UUID as the internal representation of the variable.
    options[i] = [variableModelList[i].name, variableModelList[i].getId()];
  }
  options.push([Blockly.Msg.RENAME_VARIABLE, Blockly.RENAME_VARIABLE_ID]);
  if (Blockly.Msg.DELETE_VARIABLE) {
    options.push([Blockly.Msg.DELETE_VARIABLE.replace('%1', name),
        Blockly.DELETE_VARIABLE_ID]);
  }

  return options;
};

/**
 * Handle the selection of an item in the variable dropdown menu.
 * Special case the 'Rename variable...' and 'Delete variable...' options.
 * In the rename case, prompt the user for a new name.
 * @param {!goog.ui.Menu} menu The Menu component clicked.
 * @param {!goog.ui.MenuItem} menuItem The MenuItem selected within menu.
 */
Blockly.FieldVariable.prototype.onItemSelected = function(menu, menuItem) {
  var id = menuItem.getValue();
  if (this.sourceBlock_ && this.sourceBlock_.workspace) {
    var workspace = this.sourceBlock_.workspace;
    if (id == Blockly.RENAME_VARIABLE_ID) {
      // Rename variable.
      Blockly.Variables.renameVariable(workspace, this.variable_);
      return;
    } else if (id == Blockly.DELETE_VARIABLE_ID) {
      // Delete variable.
      workspace.deleteVariableById(this.variable_.getId());
      return;
    }

    // TODO (#1529): Call any validation function, and allow it to override.
  }
  this.setValue(id);
};
<commit_msg>Don't update the field until all checks pass<commit_after>/**
 * @license
 * Visual Blocks Editor
 *
 * Copyright 2012 Google Inc.
 * https://developers.google.com/blockly/
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @fileoverview Variable input field.
 * @author fraser@google.com (Neil Fraser)
 */
'use strict';

goog.provide('Blockly.FieldVariable');

goog.require('Blockly.FieldDropdown');
goog.require('Blockly.Msg');
goog.require('Blockly.VariableModel');
goog.require('Blockly.Variables');
goog.require('goog.asserts');
goog.require('goog.string');

/**
 * Class for a variable's dropdown field.
 * @param {?string} varname The default name for the variable.  If null,
 *     a unique variable name will be generated.
 * @param {Function=} opt_validator A function that is executed when a new
 *     option is selected.  Its sole argument is the new option value.
 * @param {Array.<string>=} opt_variableTypes A list of the types of variables
 *     to include in the dropdown.
 * @param {string=} opt_defaultType The type of variable to create if this
 *     field's value is not explicitly set.  Defaults to ''.
 * @extends {Blockly.FieldDropdown}
 * @constructor
 */
Blockly.FieldVariable = function(varname, opt_validator, opt_variableTypes,
    opt_defaultType) {
  // The FieldDropdown constructor would call setValue, which might create a
  // spurious variable.  Just do the relevant parts of the constructor.
  this.menuGenerator_ = Blockly.FieldVariable.dropdownCreate;
  this.size_ = new goog.math.Size(0, Blockly.BlockSvg.MIN_BLOCK_Y);
  this.setValidator(opt_validator);
  this.defaultVariableName = (varname || '');

  this.setTypes_(opt_variableTypes, opt_defaultType);
  this.value_ = null;
};
goog.inherits(Blockly.FieldVariable, Blockly.FieldDropdown);

/**
 * Initialize everything needed to render this field.  This includes making sure
 * that the field's value is valid.
 * @public
 */
Blockly.FieldVariable.prototype.init = function() {
  if (this.fieldGroup_) {
    // Dropdown has already been initialized once.
    return;
  }
  Blockly.FieldVariable.superClass_.init.call(this);

  // TODO (1010): Change from init/initModel to initView/initModel
  this.initModel();
};

/**
 * Initialize the model for this field if it has not already been initialized.
 * If the value has not been set to a variable by the first render, we make up a
 * variable rather than let the value be invalid.
 * @package
 */
Blockly.FieldVariable.prototype.initModel = function() {
  if (this.variable_) {
    return; // Initialization already happened.
  }
  this.workspace_ = this.sourceBlock_.workspace;
  var variable = Blockly.Variables.getOrCreateVariablePackage(
      this.workspace_, null, this.defaultVariableName, this.defaultType_);

  // Don't fire a change event for this setValue.  It would have null as the
  // old value, which is not valid.
  Blockly.Events.disable();
  try {
    this.setValue(variable.getId());
  } finally {
    Blockly.Events.enable();
  }
};

/**
 * Dispose of this field.
 * @public
 */
Blockly.FieldVariable.dispose = function() {
  Blockly.FieldVariable.superClass_.dispose.call(this);
  this.workspace_ = null;
  this.variableMap_ = null;
};

/**
 * Attach this field to a block.
 * @param {!Blockly.Block} block The block containing this field.
 */
Blockly.FieldVariable.prototype.setSourceBlock = function(block) {
  goog.asserts.assert(!block.isShadow(),
      'Variable fields are not allowed to exist on shadow blocks.');
  Blockly.FieldVariable.superClass_.setSourceBlock.call(this, block);
};

/**
 * Get the variable's ID.
 * @return {string} Current variable's ID.
 */
Blockly.FieldVariable.prototype.getValue = function() {
  return this.variable_ ? this.variable_.getId() : null;
};

/**
 * Get the text from this field, which is the selected variable's name.
 * @return {string} The selected variable's name, or the empty string if no
 *     variable is selected.
 */
Blockly.FieldVariable.prototype.getText = function() {
  return this.variable_ ? this.variable_.name : '';
};

/**
 * Get the variable model for the selected variable.
 * Not guaranteed to be in the variable map on the workspace (e.g. if accessed
 * after the variable has been deleted).
 * @return {?Blockly.VariableModel} the selected variable, or null if none was
 *     selected.
 * @package
 */
Blockly.FieldVariable.prototype.getVariable = function() {
  return this.variable_;
};

/**
 * Set the variable ID.
 * @param {string} id New variable ID, which must reference an existing
 *     variable.
 */
Blockly.FieldVariable.prototype.setValue = function(id) {
  var workspace = this.sourceBlock_.workspace;
  var variable = Blockly.Variables.getVariable(workspace, id);

  if (!variable) {
    throw new Error('Variable id doesn\'t point to a real variable!  ID was ' +
        id);
  }
  // Type checks!
  var type = variable.type;
  if (!this.typeIsAllowed_(type)) {
    throw new Error('Variable type doesn\'t match this field!  Type was ' +
        type);
  }
  if (this.sourceBlock_ && Blockly.Events.isEnabled()) {
    var oldValue = this.variable_ ? this.variable_.getId() : null;
    Blockly.Events.fire(new Blockly.Events.BlockChange(
        this.sourceBlock_, 'field', this.name, oldValue, id));
  }
  this.variable_ = variable;
  this.value_ = id;
  this.setText(variable.name);
};

/**
 * Check whether the given variable type is allowed on this field.
 * @param {string} type The type to check.
 * @return {boolean} True if the type is in the list of allowed types.
 * @private
 */
Blockly.FieldVariable.prototype.typeIsAllowed_ = function(type) {
  var typeList = this.getVariableTypes_();
  if (!typeList) {
    return true; // If it's null, all types are valid.
  }
  for (var i = 0; i < typeList.length; i++) {
    if (type == typeList[i]) {
      return true;
    }
  }
  return false;
};

/**
 * Return a list of variable types to include in the dropdown.
 * @return {!Array.<string>} Array of variable types.
 * @throws {Error} if variableTypes is an empty array.
 * @private
 */
Blockly.FieldVariable.prototype.getVariableTypes_ = function() {
  // TODO (#1513): Try to avoid calling this every time the field is edited.
  var variableTypes = this.variableTypes;
  if (variableTypes === null) {
    // If variableTypes is null, return all variable types.
    if (this.sourceBlock_) {
      var workspace = this.sourceBlock_.workspace;
      return workspace.getVariableTypes();
    }
  }
  variableTypes = variableTypes || [''];
  if (variableTypes.length == 0) {
    // Throw an error if variableTypes is an empty list.
    var name = this.getText();
    throw new Error('\'variableTypes\' of field variable ' +
      name + ' was an empty list');
  }
  return variableTypes;
};

/**
 * Parse the optional arguments representing the allowed variable types and the
 * default variable type.
 * @param {Array.<string>=} opt_variableTypes A list of the types of variables
 *     to include in the dropdown.  If null or undefined, variables of all types
 *     will be displayed in the dropdown.
 * @param {string=} opt_defaultType The type of the variable to create if this
 *     field's value is not explicitly set.  Defaults to ''.
 * @private
 */
Blockly.FieldVariable.prototype.setTypes_ = function(opt_variableTypes,
    opt_defaultType) {
  // If you expected that the default type would be the same as the only entry
  // in the variable types array, tell the Blockly team by commenting on #1499.
  var defaultType = opt_defaultType || '';
  // Set the allowable variable types.  Null means all types on the workspace.
  if (opt_variableTypes == null || opt_variableTypes == undefined) {
    var variableTypes = null;
  } else if (Array.isArray(opt_variableTypes)) {
    var variableTypes = opt_variableTypes;
    // Make sure the default type is valid.
    var isInArray = false;
    for (var i = 0; i < variableTypes.length; i++) {
      if (variableTypes[i] == defaultType) {
        isInArray = true;
      }
    }
    if (!isInArray) {
      throw new Error('Invalid default type \'' + defaultType + '\' in ' +
          'the definition of a FieldVariable');
    }
  } else {
    throw new Error('\'variableTypes\' was not an array in the definition of ' +
        'a FieldVariable');
  }
  // Only update the field once all checks pass.
  this.defaultType_ =  defaultType;
  this.variableTypes = variableTypes;
};

/**
 * Return a sorted list of variable names for variable dropdown menus.
 * Include a special option at the end for creating a new variable name.
 * @return {!Array.<string>} Array of variable names.
 * @this {Blockly.FieldVariable}
 */
Blockly.FieldVariable.dropdownCreate = function() {
  if (!this.variable_) {
    throw new Error('Tried to call dropdownCreate on a variable field with no' +
        ' variable selected.');
  }
  var variableModelList = [];
  var name = this.getText();
  var workspace = null;
  if (this.sourceBlock_) {
    workspace = this.sourceBlock_.workspace;
  }
  if (workspace) {
    var variableTypes = this.getVariableTypes_();
    var variableModelList = [];
    // Get a copy of the list, so that adding rename and new variable options
    // doesn't modify the workspace's list.
    for (var i = 0; i < variableTypes.length; i++) {
      var variableType = variableTypes[i];
      var variables = workspace.getVariablesOfType(variableType);
      variableModelList = variableModelList.concat(variables);
    }
  }
  variableModelList.sort(Blockly.VariableModel.compareByName);

  var options = [];
  for (var i = 0; i < variableModelList.length; i++) {
    // Set the UUID as the internal representation of the variable.
    options[i] = [variableModelList[i].name, variableModelList[i].getId()];
  }
  options.push([Blockly.Msg.RENAME_VARIABLE, Blockly.RENAME_VARIABLE_ID]);
  if (Blockly.Msg.DELETE_VARIABLE) {
    options.push([Blockly.Msg.DELETE_VARIABLE.replace('%1', name),
        Blockly.DELETE_VARIABLE_ID]);
  }

  return options;
};

/**
 * Handle the selection of an item in the variable dropdown menu.
 * Special case the 'Rename variable...' and 'Delete variable...' options.
 * In the rename case, prompt the user for a new name.
 * @param {!goog.ui.Menu} menu The Menu component clicked.
 * @param {!goog.ui.MenuItem} menuItem The MenuItem selected within menu.
 */
Blockly.FieldVariable.prototype.onItemSelected = function(menu, menuItem) {
  var id = menuItem.getValue();
  if (this.sourceBlock_ && this.sourceBlock_.workspace) {
    var workspace = this.sourceBlock_.workspace;
    if (id == Blockly.RENAME_VARIABLE_ID) {
      // Rename variable.
      Blockly.Variables.renameVariable(workspace, this.variable_);
      return;
    } else if (id == Blockly.DELETE_VARIABLE_ID) {
      // Delete variable.
      workspace.deleteVariableById(this.variable_.getId());
      return;
    }

    // TODO (#1529): Call any validation function, and allow it to override.
  }
  this.setValue(id);
};
<|endoftext|>


<commit_before>/*global  ChromeAudioEQ,
          chrome,
          icon,
          console
                          */
'use strict';

// console.log('background.js');
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
	//console.log(sender.tab ? "from a content script:" + sender.tab.url : "from the extension");
	//get setting from page
	if (request.action === 'get') {
		chrome.storage.local.get(function(items) {
			//console.log('background.js', 'chrome.storage.local.get', items);
			sendResponse({
				eq : items.eq,
				config : items.config,
				selected : items.selected,
				version : items.version
			});
		});

	}
	//set settings from popup
	if (request.action === 'set') {
		var items = {};
		items.config = request.config;
		items.eq = request.eq;
		items.selected = request.selected;
		items.version = request.version;

		chrome.storage.local.set(items);
		//console.log(request);
		chrome.tabs.query({
		}, function(tabs) {
      function onTabMsgResp(response) {
          //console.log('tab response', response);
        }
			for (var i = 0; i < tabs.length; i++) {
				chrome.tabs.sendMessage(tabs[i].id, request, onTabMsgResp);
			}
		});
		icon.generate(items.eq);
	}

	//error logger
	if (request.action === 'error') {
		//for now just forward do console
		console.error(request.source, request.error, request.page);
	}

	return true;
});

chrome.storage.local.get(function(storage) {
	//Default values
	//console.log('background.js init', 'chrome.storage.local.get', storage);
	if (storage.version !== CONST.VERSION) {
		storage.eq = CONST.EQ;
		storage.config = CONST.CONFIG;
		storage.version = CONST.VERSION;
	}

	chrome.storage.local.set(storage, function() {
		//console.log('background.js init', 'chrome.storage.local.set');
	});
	icon.generate(storage.eq);
});
<commit_msg>Add missing global CONST<commit_after>/*global  ChromeAudioEQ,
          chrome,
          icon,
          console,
					CONST
                          */
'use strict';

// console.log('background.js');
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
	//console.log(sender.tab ? "from a content script:" + sender.tab.url : "from the extension");
	//get setting from page
	if (request.action === 'get') {
		chrome.storage.local.get(function(items) {
			//console.log('background.js', 'chrome.storage.local.get', items);
			sendResponse({
				eq : items.eq,
				config : items.config,
				selected : items.selected,
				version : items.version
			});
		});

	}
	//set settings from popup
	if (request.action === 'set') {
		var items = {};
		items.config = request.config;
		items.eq = request.eq;
		items.selected = request.selected;
		items.version = request.version;

		chrome.storage.local.set(items);
		//console.log(request);
		chrome.tabs.query({
		}, function(tabs) {
      function onTabMsgResp(response) {
          //console.log('tab response', response);
        }
			for (var i = 0; i < tabs.length; i++) {
				chrome.tabs.sendMessage(tabs[i].id, request, onTabMsgResp);
			}
		});
		icon.generate(items.eq);
	}

	//error logger
	if (request.action === 'error') {
		//for now just forward do console
		console.error(request.source, request.error, request.page);
	}

	return true;
});

chrome.storage.local.get(function(storage) {
	//Default values
	//console.log('background.js init', 'chrome.storage.local.get', storage);
	if (storage.version !== CONST.VERSION) {
		storage.eq = CONST.EQ;
		storage.config = CONST.CONFIG;
		storage.version = CONST.VERSION;
	}

	chrome.storage.local.set(storage, function() {
		//console.log('background.js init', 'chrome.storage.local.set');
	});
	icon.generate(storage.eq);
});
<|endoftext|>