<commit_before>import React, {Component} from 'react';

import {StyleSheet, Text, TouchableOpacity, View, ScrollView, Alert} from 'react-native';
import Sound from 'react-native-sound';

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  scrollContainer: {},
  title: {
    fontSize: 20,
    fontWeight: 'bold',
    paddingTop: 30,
    padding: 20,
    textAlign: 'center',
    backgroundColor: 'rgba(240,240,240,1)',
  },
  button: {
    fontSize: 20,
    backgroundColor: 'rgba(220,220,220,1)',
    borderRadius: 4,
    borderWidth: 1,
    borderColor: 'rgba(80,80,80,0.5)',
    overflow: 'hidden',
    padding: 7,
  },
  header: {
    textAlign: 'left',
  },
  feature: {
    flexDirection: 'row',
    padding: 10,
    alignSelf: 'stretch',
    alignItems: 'center',
    borderTopWidth: 1,
    borderTopColor: 'rgb(180,180,180)',
    borderBottomWidth: 1,
    borderBottomColor: 'rgb(230,230,230)',
  },
});

const Button = ({title, onPress}) => (
  <TouchableOpacity onPress={onPress}>
    <Text style={styles.button}>{title}</Text>
  </TouchableOpacity>
);

const Header = ({children, style}) => <Text style={[styles.header, style]}>{children}</Text>;

const Feature = ({title, onPress, description, buttonLabel = 'PLAY', status}) => (
  <View style={styles.feature}>
    {title}
    {status ? <Text style={{padding: 5}}>{resultIcons[status] || ''}</Text> : null}
    <Button title={buttonLabel} onPress={onPress} />
  </View>
);

const resultIcons = {
  '': '',
  pending: '?',
  playing: '\u25B6',
  win: '\u2713',
  fail: '\u274C',
};

const audioTests = [
  {
    title: 'mp3 in bundle',
    url: 'advertising.mp3',
    basePath: Sound.MAIN_BUNDLE,
  },
  {
    title: 'mp3 in bundle (looped)',
    url: 'advertising.mp3',
    basePath: Sound.MAIN_BUNDLE,
    onPrepared: (sound, component) => {
      sound.setNumberOfLoops(-1);
      component.setState({loopingSound: sound});
    },
  },
  {
    title: 'mp3 via require()',
    isRequire: true,
    url: require('./advertising.mp3'),
  },
  {
    title: 'mp3 remote download',
    url: 'https://raw.githubusercontent.com/zmxv/react-native-sound-demo/master/advertising.mp3',
  },
  {
    title: 'mp3 remote - file doesn\'t exist',
    url: 'https://raw.githubusercontent.com/zmxv/react-native-sound-demo/master/file-not-here.mp3',
  },
  {
    title: 'aac remote download',
    url: 'https://raw.githubusercontent.com/zmxv/react-native-sound-demo/master/pew2.aac',
  },
  {
    title: 'wav remote download',
    url: 'https://raw.githubusercontent.com/zmxv/react-native-sound-demo/master/frog.wav',
  },
  {
    title: 'aac via require()',
    isRequire: true,
    url: require('./pew2.aac'),
  },
  {
    title: 'wav via require()',
    isRequire: true,
    url: require('./frog.wav'),
  },
];

function setTestState(testInfo, component, status) {
  component.setState({tests: {...component.state.tests, [testInfo.title]: status}});
}

/**
 * Generic play function for majority of tests
 */
function playSound(testInfo, component) {
  setTestState(testInfo, component, 'pending');

  const callback = (error, sound) => {
    if (error) {
      Alert.alert('error', error.message);
      setTestState(testInfo, component, 'fail');
      return;
    }
    setTestState(testInfo, component, 'playing');
    // Run optional pre-play callback
    testInfo.onPrepared && testInfo.onPrepared(sound, component);
    sound.play(() => {
      // Success counts as getting to the end
      setTestState(testInfo, component, 'win');
      // Release when it's done so we're not using up resources
      sound.release();
    });
  };

  // If the audio is a 'require' then the second parameter must be the callback.
  if (testInfo.isRequire) {
    const sound = new Sound(testInfo.url, error => callback(error, sound));
  } else {
    const sound = new Sound(testInfo.url, testInfo.basePath, error => callback(error, sound));
  }
}

class MainView extends Component {
  constructor(props) {
    super(props);

    Sound.setCategory('Playback', true); // true = mixWithOthers

    // Special case for stopping
    this.stopSoundLooped = () => {
      if (!this.state.loopingSound) {
        return;
      }

      this.state.loopingSound.stop().release();
      this.setState({loopingSound: null, tests: {...this.state.tests, ['mp3 in bundle (looped)']: 'win'}});
    };

    this.state = {
      loopingSound: undefined,
      tests: {},
    };
  }

  render() {
    return (
      <View style={styles.container}>
        react-native-sound-demo
        <ScrollView style={styles.container} contentContainerStyle={styles.scrollContainer}>
          {audioTests.map(testInfo => {
            return (
              <Feature
                status={this.state.tests[testInfo.title]}
                key={testInfo.title}
                title={testInfo.title}
                onPress={() => {
                  return playSound(testInfo, this);
                }}
              />
            );
          })}
          <Feature title="mp3 in bundle (looped)" buttonLabel={'STOP'} onPress={this.stopSoundLooped} />
        </ScrollView>
      </View>
    );
  }
}

export default MainView;
<commit_msg>Removed unused variable inside Feature component (#21)<commit_after>import React, {Component} from 'react';

import {StyleSheet, Text, TouchableOpacity, View, ScrollView, Alert} from 'react-native';
import Sound from 'react-native-sound';

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  scrollContainer: {},
  title: {
    fontSize: 20,
    fontWeight: 'bold',
    paddingTop: 30,
    padding: 20,
    textAlign: 'center',
    backgroundColor: 'rgba(240,240,240,1)',
  },
  button: {
    fontSize: 20,
    backgroundColor: 'rgba(220,220,220,1)',
    borderRadius: 4,
    borderWidth: 1,
    borderColor: 'rgba(80,80,80,0.5)',
    overflow: 'hidden',
    padding: 7,
  },
  header: {
    textAlign: 'left',
  },
  feature: {
    flexDirection: 'row',
    padding: 10,
    alignSelf: 'stretch',
    alignItems: 'center',
    borderTopWidth: 1,
    borderTopColor: 'rgb(180,180,180)',
    borderBottomWidth: 1,
    borderBottomColor: 'rgb(230,230,230)',
  },
});

const Button = ({title, onPress}) => (
  <TouchableOpacity onPress={onPress}>
    <Text style={styles.button}>{title}</Text>
  </TouchableOpacity>
);

const Header = ({children, style}) => <Text style={[styles.header, style]}>{children}</Text>;

const Feature = ({title, onPress, buttonLabel = 'PLAY', status}) => (
  <View style={styles.feature}>
    {title}
    {status ? <Text style={{padding: 5}}>{resultIcons[status] || ''}</Text> : null}
    <Button title={buttonLabel} onPress={onPress} />
  </View>
);

const resultIcons = {
  '': '',
  pending: '?',
  playing: '\u25B6',
  win: '\u2713',
  fail: '\u274C',
};

const audioTests = [
  {
    title: 'mp3 in bundle',
    url: 'advertising.mp3',
    basePath: Sound.MAIN_BUNDLE,
  },
  {
    title: 'mp3 in bundle (looped)',
    url: 'advertising.mp3',
    basePath: Sound.MAIN_BUNDLE,
    onPrepared: (sound, component) => {
      sound.setNumberOfLoops(-1);
      component.setState({loopingSound: sound});
    },
  },
  {
    title: 'mp3 via require()',
    isRequire: true,
    url: require('./advertising.mp3'),
  },
  {
    title: 'mp3 remote download',
    url: 'https://raw.githubusercontent.com/zmxv/react-native-sound-demo/master/advertising.mp3',
  },
  {
    title: 'mp3 remote - file doesn\'t exist',
    url: 'https://raw.githubusercontent.com/zmxv/react-native-sound-demo/master/file-not-here.mp3',
  },
  {
    title: 'aac remote download',
    url: 'https://raw.githubusercontent.com/zmxv/react-native-sound-demo/master/pew2.aac',
  },
  {
    title: 'wav remote download',
    url: 'https://raw.githubusercontent.com/zmxv/react-native-sound-demo/master/frog.wav',
  },
  {
    title: 'aac via require()',
    isRequire: true,
    url: require('./pew2.aac'),
  },
  {
    title: 'wav via require()',
    isRequire: true,
    url: require('./frog.wav'),
  },
];

function setTestState(testInfo, component, status) {
  component.setState({tests: {...component.state.tests, [testInfo.title]: status}});
}

/**
 * Generic play function for majority of tests
 */
function playSound(testInfo, component) {
  setTestState(testInfo, component, 'pending');

  const callback = (error, sound) => {
    if (error) {
      Alert.alert('error', error.message);
      setTestState(testInfo, component, 'fail');
      return;
    }
    setTestState(testInfo, component, 'playing');
    // Run optional pre-play callback
    testInfo.onPrepared && testInfo.onPrepared(sound, component);
    sound.play(() => {
      // Success counts as getting to the end
      setTestState(testInfo, component, 'win');
      // Release when it's done so we're not using up resources
      sound.release();
    });
  };

  // If the audio is a 'require' then the second parameter must be the callback.
  if (testInfo.isRequire) {
    const sound = new Sound(testInfo.url, error => callback(error, sound));
  } else {
    const sound = new Sound(testInfo.url, testInfo.basePath, error => callback(error, sound));
  }
}

class MainView extends Component {
  constructor(props) {
    super(props);

    Sound.setCategory('Playback', true); // true = mixWithOthers

    // Special case for stopping
    this.stopSoundLooped = () => {
      if (!this.state.loopingSound) {
        return;
      }

      this.state.loopingSound.stop().release();
      this.setState({loopingSound: null, tests: {...this.state.tests, ['mp3 in bundle (looped)']: 'win'}});
    };

    this.state = {
      loopingSound: undefined,
      tests: {},
    };
  }

  render() {
    return (
      <View style={styles.container}>
        react-native-sound-demo
        <ScrollView style={styles.container} contentContainerStyle={styles.scrollContainer}>
          {audioTests.map(testInfo => {
            return (
              <Feature
                status={this.state.tests[testInfo.title]}
                key={testInfo.title}
                title={testInfo.title}
                onPress={() => {
                  return playSound(testInfo, this);
                }}
              />
            );
          })}
          <Feature title="mp3 in bundle (looped)" buttonLabel={'STOP'} onPress={this.stopSoundLooped} />
        </ScrollView>
      </View>
    );
  }
}

export default MainView;
<|endoftext|>


<commit_before>/** Use the Tab key to jump out of groupings after closing characters ", ', ), ] and } like in Eclipse. */
define(function (require, exports, module) {
    'use strict';

    var CommandManager = brackets.getModule('command/CommandManager');
    var KeyBindingManager = brackets.getModule('command/KeyBindingManager');
    var EditorManager = brackets.getModule('editor/EditorManager');

    function tabOutIfPossible() {
        var editor = EditorManager.getFocusedEditor();
        if (! editor)
            return;

        var currentCursorPosition = editor.getCursorPos();
        var nextCursorPosition = {line: currentCursorPosition.line, ch: currentCursorPosition.ch + 1}

        if (editor.getSelectedText() !== '')
            return true;

        var nextCharacter = editor.document.getRange(currentCursorPosition, nextCursorPosition);
        var closingCharacters = ['"', "'", ')', ']', '}'];
        var nextCharacterIsNotClosingCharacter = closingCharacters.indexOf(nextCharacter) === -1;
        if (nextCharacterIsNotClosingCharacter)
            return true;

        var beginningOfLinePosition = {line: currentCursorPosition.line, ch: 0};
        var textInLineBeforeCursor = editor.document.getRange(beginningOfLinePosition, currentCursorPosition);
        var hasOnlyWhitespaceToTheLeft = textInLineBeforeCursor.trim() === '';
        if (hasOnlyWhitespaceToTheLeft)
            return true;

        editor.setCursorPos(nextCursorPosition);

        return false;
    }

    var MY_COMMAND_ID = 'dag0310.tab-out';

    CommandManager.registerInternal(MY_COMMAND_ID, tabOutIfPossible);

    KeyBindingManager.addBinding(MY_COMMAND_ID, 'Tab');
});
<commit_msg>Add option to change keybinding to Alt+Tab on Mac<commit_after>/** Use the Tab key to jump out of groupings after closing characters ", ', ), ] and } like in Eclipse. */
define(function (require, exports, module) {
    'use strict';

    var EXTENSION_NAME = 'dag0310.tab-out';
    var TAB_OUT_COMMAND = EXTENSION_NAME + '.tab-out';
    var TOGGLE_COMMAND = EXTENSION_NAME + '.toggle';
    var DEFAULT_KEY_BINDING = 'Tab';
    var ALT_KEY_BINDING = 'Alt-Tab';
    var ALT_KEY_BINDING_ENABLED_PREFERENCE = 'altKeyEnabled'

    var CommandManager = brackets.getModule('command/CommandManager');
    var KeyBindingManager = brackets.getModule('command/KeyBindingManager');
    var EditorManager = brackets.getModule('editor/EditorManager');
    var Menus = brackets.getModule('command/Menus');
    var PreferencesManager = brackets.getModule('preferences/PreferencesManager');

    var _prefs = PreferencesManager.getExtensionPrefs(EXTENSION_NAME);
    _prefs.definePreference(ALT_KEY_BINDING_ENABLED_PREFERENCE, 'boolean', false);

    function tabOutIfPossible() {
        var editor = EditorManager.getFocusedEditor();
        if (! editor)
            return;

        var currentCursorPosition = editor.getCursorPos();
        var nextCursorPosition = {line: currentCursorPosition.line, ch: currentCursorPosition.ch + 1}

        if (editor.getSelectedText() !== '')
            return true;

        var nextCharacter = editor.document.getRange(currentCursorPosition, nextCursorPosition);
        var closingCharacters = ['"', "'", ')', ']', '}'];
        var nextCharacterIsNotClosingCharacter = closingCharacters.indexOf(nextCharacter) === -1;
        if (nextCharacterIsNotClosingCharacter)
            return true;

        var beginningOfLinePosition = {line: currentCursorPosition.line, ch: 0};
        var textInLineBeforeCursor = editor.document.getRange(beginningOfLinePosition, currentCursorPosition);
        var hasOnlyWhitespaceToTheLeft = textInLineBeforeCursor.trim() === '';
        if (hasOnlyWhitespaceToTheLeft)
            return true;

        editor.setCursorPos(nextCursorPosition);

        return false;
    }

    function setKeyBinding(isAlternative) {
        if (isAlternative && brackets.platform === 'mac') {
            KeyBindingManager.removeBinding(DEFAULT_KEY_BINDING);
            KeyBindingManager.addBinding(TAB_OUT_COMMAND, ALT_KEY_BINDING, 'mac');
        } else {
            KeyBindingManager.removeBinding(ALT_KEY_BINDING);
            KeyBindingManager.addBinding(TAB_OUT_COMMAND, DEFAULT_KEY_BINDING);
        }
    }

    function toggleKeyBinding() {
        _prefs.set(ALT_KEY_BINDING_ENABLED_PREFERENCE, ! _prefs.get(ALT_KEY_BINDING_ENABLED_PREFERENCE));
        _prefs.save();

        CommandManager.get(TOGGLE_COMMAND).setChecked(_prefs.get(ALT_KEY_BINDING_ENABLED_PREFERENCE));

        setKeyBinding(_prefs.get(ALT_KEY_BINDING_ENABLED_PREFERENCE));

        brackets.getModule('utils/Dialogs').showModalDialog('', 'Please restart Brackets', "Tab Out's and other plugins' affected keyboard shortcuts fully functional after restart of Brackets!");
    }

    CommandManager.registerInternal(TAB_OUT_COMMAND, tabOutIfPossible);
    setKeyBinding(_prefs.get(ALT_KEY_BINDING_ENABLED_PREFERENCE));

    if (brackets.platform === 'mac') {
        CommandManager.register('Tab Out: Use ' + ALT_KEY_BINDING.replace('-', '+') + ' instead of ' + DEFAULT_KEY_BINDING + ' (Mac only)', TOGGLE_COMMAND, toggleKeyBinding);
        var menu = Menus.getMenu(Menus.AppMenuBar.NAVIGATE_MENU);
        menu.addMenuItem(TOGGLE_COMMAND);
        CommandManager.get(TOGGLE_COMMAND).setChecked(_prefs.get(ALT_KEY_BINDING_ENABLED_PREFERENCE));
    }
});
<|endoftext|>


<commit_before>var margin = {top: 10, right: 200, bottom: 10, left: 40},
    width  = (getParam("width") || 1400) - margin.left - margin.right,
    height = (getParam("height") || 800) - margin.top - margin.bottom;
    offset_right = 300;

var svg = d3.select("body")
            .append("svg")
            .attr("width", width + margin.left + margin.right)
            .attr("height", height + margin.top + margin.bottom + width/10);

var base = svg.append("g")
              .attr("transform", "translate(" + margin.left + ", " + margin.top + ")");

var tree = d3.layout.tree()
             .separation(function(a, b) { return (a.fname == b.fname) ? 1 : 0.8 })
             .children(function(a){
               var result_before_limit = a.children.filter(function(e){
                 var ex_pattern = getParam("exclude");
                 var in_pattern = getParam("include");

                 function match(pattern){
                   return (new RegExp(pattern, 'i')).test(e.fname);
                 }

                 return (!in_pattern || match(in_pattern)) && (!ex_pattern || !match(ex_pattern));
               })

               var remainders_num = _.max([result_before_limit.length - getParam("limit"), 0]);
               var remainders = (0 < remainders_num) ? [{
                 "name": "remainders", "label": ("rem:" + remainders_num), "children": []
               }] : [];

               return result_before_limit.slice(0, getParam("limit") || Infinity).concat(remainders);
             })
             .size([height, width + height/10 - offset_right]);

var x_scale = function(x){
  var threshold = 500;
  var scale = 5;

  if(x < threshold){
    return (x * 1.0)/scale;
  }else{
    return x - threshold + threshold/scale;
  }
}

var diagonal = d3.svg.diagonal()
                     .projection(function(d) { return [x_scale(d.y), d.x + d.y / 10]; });

var color = d3.scale.category20();
var rails_directory_hue = d3.scale.ordinal()
                                  .domain([null, "controller", "model", "view", "helper", "lib", "vendor", "config", "js", "stylesheet", "db"])
                                  .rangeBands([0, 360]);
// var gray_scale = d3.scale.linear().domain([0, 255]).range(["red", "blue"]);

function setupJSON(json){
  if(json.is_action){
    json.children = [];
  }

  if(json.children){
    _.each(json.children, function(json_){ setupJSON(json_) });
  }
}

d3.json("input.json", function(json) {
  setupJSON(json);

  var nodes = tree.nodes(json);
  var links = tree.links(nodes);

  var font_size = 9;

  base.selectAll("path.link")
     .data(links)
     .enter()
     .append("path")
     .attr("class", "link")
     .attr("d", function(d){
         return diagonal(d);
      });

  base.selectAll("g.textnode")
      .data(nodes)
      .enter()
      .append("g")
      .each(function(d){
           var texts = [d.label || (d.corners + " " + ((d.fname && d.lnum) ? (d.fname + ":" + d.lnum) : ''))];
           var offset_x = 0; //(-1) * d3.max(texts, function(t){ return font_size * (t || "").length }) / 4;
           var offset_y = (-1) * (font_size * texts.length) / 2;

           var text = d3.select(this).selectAll("text.label")
                        .data(texts)
                        .enter()
                        .append("text")
                        .attr("class", "label")
                        .attr("x", function(d){ return offset_x; })
                        .attr("y", function(d, i){ return offset_y + font_size*(i+1); })
                        .attr("fill", "#000")
                        .attr("font-family", "trebuchet ms, helvetica, sans-serif")
                        .attr("text-anchor", "start")
                        .attr("font-size", font_size)
                        .text(function(t){ return t })
                        .on("mouseover", function(){
                            return tooltip.style("visibility", "visible");
                        })
                        .on("mousemove", function(){
                            var inner = ""
                            _.each(d.around_text || [], function(arr){ inner += "
" + arr[0] + ": " + arr[1] + "
"});
                            return tooltip.style("top", (d3.event.pageY + 10) + "px")
                                          .style("left",(d3.event.pageX - 100) + "px")
                                          .html(inner);
                        })
                        .on("mouseout", function(){
                            return tooltip.style("visibility", "hidden");
                        });

           var real_box_width  = d3.max(text[0].map(function(e){ return e.getBBox().width; }));
           var real_box_height = d3.sum(text[0].map(function(e){ return e.getBBox().height; }));

           d3.select(this)
             .insert("rect", "text")
             .attr("width", function(e){  return real_box_width })
             .attr("height", function(e){ return real_box_height })
             .attr("rx", 3)
             .attr("ry", 3)
             //.style("fill", function(e){ return gray_scale(strToCode(d.search_word || "", 255)) })
             .style("fill", function(e){ return d3.hsl(rails_directory_hue(d.rails_directory), 1, 0.5) })
             .attr("x", function(e){ return offset_x })
             .attr("y", function(e){ return offset_y })
             .attr("fill-opacity", function(e){ return 0.3 })
             .style("stroke-width", "0");
      })
      .attr("transform",  function(d){ return "translate(" + x_scale(d.y) + ",  " + (d.x + d.y / 10) + ")"; });

    var tooltip = d3.select("body")
                    .append('div')
                    .attr('class', 'tooltip');
});
<commit_msg>Arrange svg offset<commit_after>var margin = {top: 10, right: 200, bottom: 10, left: 40},
    width  = (getParam("width") || 1400) - margin.left - margin.right,
    height = (getParam("height") || 800) - margin.top - margin.bottom;
    offset_right = 800;
    offset_buttom = 300;

var svg = d3.select("body")
            .append("svg")
            .attr("width", width + margin.left + margin.right + offset_right)
            .attr("height", height + margin.top + margin.bottom + width/10 + offset_buttom);

var base = svg.append("g")
              .attr("transform", "translate(" + margin.left + ", " + margin.top + ")");

var tree = d3.layout.tree()
             .separation(function(a, b) { return (a.fname == b.fname) ? 1 : 0.8 })
             .children(function(a){
               var result_before_limit = a.children.filter(function(e){
                 var ex_pattern = getParam("exclude");
                 var in_pattern = getParam("include");

                 function match(pattern){
                   return (new RegExp(pattern, 'i')).test(e.fname);
                 }

                 return (!in_pattern || match(in_pattern)) && (!ex_pattern || !match(ex_pattern));
               })

               var remainders_num = _.max([result_before_limit.length - getParam("limit"), 0]);
               var remainders = (0 < remainders_num) ? [{
                 "name": "remainders", "label": ("rem:" + remainders_num), "children": []
               }] : [];

               return result_before_limit.slice(0, getParam("limit") || Infinity).concat(remainders);
             })
             .size([height, width + height/10]);

var x_scale = function(x){
  var threshold = 500;
  var scale = 5;

  if(x < threshold){
    return (x * 1.0)/scale;
  }else{
    return x - threshold + threshold/scale;
  }
}

var diagonal = d3.svg.diagonal()
                     .projection(function(d) { return [x_scale(d.y), d.x + d.y / 10]; });

var color = d3.scale.category20();
var rails_directory_hue = d3.scale.ordinal()
                                  .domain([null, "controller", "model", "view", "helper", "lib", "vendor", "config", "js", "stylesheet", "db"])
                                  .rangeBands([0, 360]);
// var gray_scale = d3.scale.linear().domain([0, 255]).range(["red", "blue"]);

function setupJSON(json){
  if(json.is_action){
    json.children = [];
  }

  if(json.children){
    _.each(json.children, function(json_){ setupJSON(json_) });
  }
}

d3.json("input.json", function(json) {
  setupJSON(json);

  var nodes = tree.nodes(json);
  var links = tree.links(nodes);

  var font_size = 9;

  base.selectAll("path.link")
     .data(links)
     .enter()
     .append("path")
     .attr("class", "link")
     .attr("d", function(d){
         return diagonal(d);
      });

  base.selectAll("g.textnode")
      .data(nodes)
      .enter()
      .append("g")
      .each(function(d){
           var texts = [d.label || (d.corners + " " + ((d.fname && d.lnum) ? (d.fname + ":" + d.lnum) : ''))];
           var offset_x = 0; //(-1) * d3.max(texts, function(t){ return font_size * (t || "").length }) / 4;
           var offset_y = (-1) * (font_size * texts.length) / 2;

           var text = d3.select(this).selectAll("text.label")
                        .data(texts)
                        .enter()
                        .append("text")
                        .attr("class", "label")
                        .attr("x", function(d){ return offset_x; })
                        .attr("y", function(d, i){ return offset_y + font_size*(i+1); })
                        .attr("fill", "#000")
                        .attr("font-family", "trebuchet ms, helvetica, sans-serif")
                        .attr("text-anchor", "start")
                        .attr("font-size", font_size)
                        .text(function(t){ return t })
                        .on("mouseover", function(){
                            return tooltip.style("visibility", "visible");
                        })
                        .on("mousemove", function(){
                            var inner = ""
                            _.each(d.around_text || [], function(arr){ inner += "
" + arr[0] + ": " + arr[1] + "
"});
                            return tooltip.style("top", (d3.event.pageY + 10) + "px")
                                          .style("left",(d3.event.pageX - 100) + "px")
                                          .html(inner);
                        })
                        .on("mouseout", function(){
                            return tooltip.style("visibility", "hidden");
                        });

           var real_box_width  = d3.max(text[0].map(function(e){ return e.getBBox().width; }));
           var real_box_height = d3.sum(text[0].map(function(e){ return e.getBBox().height; }));

           d3.select(this)
             .insert("rect", "text")
             .attr("width", function(e){  return real_box_width })
             .attr("height", function(e){ return real_box_height })
             .attr("rx", 3)
             .attr("ry", 3)
             //.style("fill", function(e){ return gray_scale(strToCode(d.search_word || "", 255)) })
             .style("fill", function(e){ return d3.hsl(rails_directory_hue(d.rails_directory), 1, 0.5) })
             .attr("x", function(e){ return offset_x })
             .attr("y", function(e){ return offset_y })
             .attr("fill-opacity", function(e){ return 0.3 })
             .style("stroke-width", "0");
      })
      .attr("transform",  function(d){ return "translate(" + x_scale(d.y) + ",  " + (d.x + d.y / 10) + ")"; });

    var tooltip = d3.select("body")
                    .append('div')
                    .attr('class', 'tooltip');
});
<|endoftext|>


<commit_before>
//Declare global object tetris
var tetris = {};

//Draw the grid --------------------------------------------------
tetris.drawPlayField = function(){

  for(var row = 0; row < 22; row++){
    $('#playfield').append('

');

    for (var col=0;col<10;col++){
      $('tr.'+row).append('	');
    }
  }
}

//Variable to store current coordinates --------------------------
tetris.origin = {row:2,col:5};
tetris.currentShape = 'L';
tetris.currentCoor;

//Fill the cells -------------------------------------------------
tetris.fillCells = function(coordinates, fillcolor){

  for(var i=0; i < coordinates.length; i++){
    var row = coordinates[i].row;
    var col = coordinates[i].col;
    var $coor = $('.'+row).find('#'+col);
    $coor.attr('bgcolor', fillcolor);
  }
}

/* Funktionen tar en array av koordinater och loopar igenom,
för varje iteration lagras radnumret i den lokala variabeln "row",
samma gäller för colnumret i den lokala variabeln "col". JQuery selektoren lagras
i den lokala variabeln "$coor" - Sen kommer funktionen att byta ut koordinaternas
backgrundsfärg till den färg vi har angett längre ner "currentCoor", i detta fall "black". */

//Move current shape --------------------------------------------
tetris.move = function(direction){
	this.fillCells(this.currentCoor,'');

	//move origin
	if(direction === 'right'){
		this.origin.col++;
	} else if (direction === 'left'){
		this.origin.col--;
	}

	this.currentCoor = this.shapeToCoor(this.currentShape,this.origin);

	if(this.ifReverse()){
		if(direction === 'right'){
			this.origin.col--;
		} else if (direction === 'left'){
			this.origin.col++;
		}
	}

	this.currentCoor = this.shapeToCoor(this.currentShape,this.origin);

	this.fillCells(this.currentCoor,'black');
}

//Rotera nuvarande figur + efterföljande figurer -----------------------
tetris.rotate = function(){
	var lastShape = this.currentShape;
	this.fillCells(this.currentCoor,'');

	if(this.currentShape === 'L'){
		this.currentShape = 'L90';
	} else if(this.currentShape === 'L90'){
		this.currentShape = 'L180';
	} else if(this.currentShape === 'L180'){
		this.currentShape = 'L270';
	} else if(this.currentShape === 'L270'){
		this.currentShape = 'L';
	} else if(this.currentShape === 'J'){
		this.currentShape = 'J90';
	} else if(this.currentShape === 'J90'){
		this.currentShape = 'J180';
	} else if(this.currentShape === 'J180'){
		this.currentShape = 'J270';
	} else if(this.currentShape === 'J270'){
		this.currentShape = 'J';
	} else if(this.currentShape === 'I'){
		this.currentShape = 'I90';
	} else if(this.currentShape === 'I90'){
		this.currentShape = 'I';
	} else if(this.currentShape === 'S'){
		this.currentShape = 'S90';
	} else if(this.currentShape === 'S90'){
		this.currentShape = 'S';
	} else if(this.currentShape === 'Z'){
		this.currentShape = 'Z90';
	} else if(this.currentShape === 'Z90'){
		this.currentShape = 'Z';
	} else if(this.currentShape === 'T'){
		this.currentShape = 'T90';
	} else if(this.currentShape === 'T90'){
		this.currentShape = 'T180';
	} else if(this.currentShape === 'T180'){
		this.currentShape = 'T270';
	} else if(this.currentShape === 'T270'){
		this.currentShape = 'T';
	}

	this.currentCoor = this.shapeToCoor(this.currentShape,this.origin);

	for(var i=0;i<this.currentCoor.length;i++){
		if(this.ifReverse()){
			this.currentShape = lastShape;
		}
	}

	this.currentCoor = this.shapeToCoor(this.currentShape,this.origin);
	this.fillCells(this.currentCoor,'black');
}

// Definiera tetris-figurer ---------------------------------------------------------
tetris.shapeToCoor = function(shape,origin){
	if(shape === 'L'){
		return [{row:origin.row,col:origin.col},{row:origin.row-1,col:origin.col},{row:origin.row+1,col:origin.col},{row:origin.row+1,col:origin.col+1}]
	} else if(shape === 'J'){
		return [{row:origin.row,col:origin.col},{row:origin.row-1,col:origin.col},{row:origin.row+1,col:origin.col},{row:origin.row+1,col:origin.col-1}]
	} else if(shape === 'I'){
		return [{row:origin.row,col:origin.col},{row:origin.row-1,col:origin.col},{row:origin.row-2,col:origin.col},{row:origin.row+1,col:origin.col}]
	} else if(shape === 'O'){
		return [{row:origin.row,col:origin.col},{row:origin.row-1,col:origin.col},{row:origin.row-1,col:origin.col+1},{row:origin.row,col:origin.col+1}]
	} else if(shape === 'S'){
		return [{row:origin.row,col:origin.col},{row:origin.row-1,col:origin.col},{row:origin.row,col:origin.col-1},{row:origin.row-1,col:origin.col+1}]
	} else if(shape === 'T'){
		return [{row:origin.row,col:origin.col},{row:origin.row-1,col:origin.col},{row:origin.row,col:origin.col-1},{row:origin.row,col:origin.col+1}]
	} else if(shape === 'Z'){
		return [{row:origin.row,col:origin.col},{row:origin.row-1,col:origin.col},{row:origin.row-1,col:origin.col-1},{row:origin.row,col:origin.col+1}]
	} else if(shape === 'L90'){
  	return [{row:origin.row,col:origin.col},{row:origin.row,col:origin.col+1},{row:origin.row,col:origin.col-1},{row:origin.row+1,col:origin.col-1}];
  } else if(shape === 'L180'){
  	return [{row:origin.row,col:origin.col},{row:origin.row-1,col:origin.col},{row:origin.row+1,col:origin.col},{row:origin.row-1,col:origin.col-1}];
  } else if(shape === 'L270'){
  	return [{row:origin.row,col:origin.col},{row:origin.row,col:origin.col+1},{row:origin.row,col:origin.col-1},{row:origin.row-1,col:origin.col+1}];
  } else if(shape === 'J90'){
		return [{row:origin.row,col:origin.col},{row:origin.row,col:origin.col-1},{row:origin.row,col:origin.col+1},{row:origin.row-1,col:origin.col-1}]
	} else if(shape === 'J180'){
		return [{row:origin.row,col:origin.col},{row:origin.row-1,col:origin.col},{row:origin.row+1,col:origin.col},{row:origin.row-1,col:origin.col+1}]
	} else if(shape === 'J270'){
		return [{row:origin.row,col:origin.col},{row:origin.row,col:origin.col-1},{row:origin.row,col:origin.col+1},{row:origin.row+1,col:origin.col+1}]
	} else if(shape === 'I90'){
		return [{row:origin.row,col:origin.col},{row:origin.row,col:origin.col-1},{row:origin.row,col:origin.col+1},{row:origin.row,col:origin.col+2}]
	} else if(shape === 'S90'){
		return [{row:origin.row,col:origin.col},{row:origin.row-1,col:origin.col},{row:origin.row-1,col:origin.col-1},{row:origin.row-2,col:origin.col-1}]
	} else if(shape === 'Z90'){
		return [{row:origin.row,col:origin.col},{row:origin.row-1,col:origin.col},{row:origin.row-1,col:origin.col+1},{row:origin.row-2,col:origin.col+1}]
	} else if(shape === 'T90'){
		return [{row:origin.row,col:origin.col},{row:origin.row-1,col:origin.col},{row:origin.row+1,col:origin.col},{row:origin.row,col:origin.col+1}]
	} else if(shape === 'T180'){
		return [{row:origin.row,col:origin.col},{row:origin.row+1,col:origin.col},{row:origin.row,col:origin.col-1},{row:origin.row,col:origin.col+1}]
	} else if(shape === 'T270'){
		return [{row:origin.row,col:origin.col},{row:origin.row-1,col:origin.col},{row:origin.row+1,col:origin.col},{row:origin.row,col:origin.col-1}]
	}
}

/* Definera figurer OCH hur varje figur ska rotera när upp-tangenten trycks ner */

//Drop shape by one row -----------------------------------------------
tetris.drop = function(){
	var reverse = false;

	this.fillCells(this.currentCoor,'');
	this.origin.row++;
	for(var i=0;i<this.currentCoor.length;i++){
		this.currentCoor[i].row++;
		if(this.ifReverse()){
			reverse = true;
		}
	}

	if(reverse){
		for(var i=0;i<this.currentCoor.length;i++){
			this.currentCoor[i].row--;
		}
		this.origin.row--;
	}

	this.fillCells(this.currentCoor,'black');

	if(reverse){
		this.fillCells(this.currentCoor,'BLACK');
		this.emptyFullRow();
		this.spawn();
	}

}

//Spawn random shape -------------------------------------------------
tetris.spawn = function(){
	var random = Math.floor(Math.random()*7);
	var shapeArray = ['L','J','I','O','S','T','Z'];

	this.currentShape = shapeArray[random];
	this.origin = {row:2,col:5};
	this.currentCoor = this.shapeToCoor(this.currentShape,this.origin);
}

/* Slumpar fram nya tetris-figurer när den nuvarande har nått botten */

//If we need to reverse  -------------------------------------------------
tetris.ifReverse = function(){
	for(var i=0;i<this.currentCoor.length;i++){
		var row = this.currentCoor[i].row;
		var col = this.currentCoor[i].col;
		var $coor = $('.'+row).find('#'+col);
		if($coor.length === 0 || $coor.attr('bgcolor') === 'BLACK'){
			return true;
		}
	}
	return false;
}

//Empty full row -------------------------------------------------
tetris.emptyFullRow = function(){
	var drops = 0;
	for (var i=21; i>=0;i--){
		var rowIsFull = true;

		for (var j=0;j<10;j++){
			var $coor = $('.'+i).find('#'+j);
			if($coor.attr('bgcolor')!=='BLACK'){
				rowIsFull = false;
			}

			if(drops>0){
				var $newCoor = $('.'+(i+drops)).find('#'+j);
				$newCoor.attr('bgcolor',$coor.attr('bgcolor'));
			}
		}

		if(rowIsFull){
			drops++;
		}
	}
}

// document.ready function - ska alltid vara längst ner ----------------
$(document).ready(function(){

	tetris.drawPlayField();
	tetris.currentCoor = tetris.shapeToCoor(tetris.currentShape,tetris.origin);
	tetris.fillCells(tetris.currentCoor,'black');

	$(document).keydown(function(e){ // Känner av piltangenterna
		console.log(e.keyCode);
		if(e.keyCode === 39){
			tetris.move('right');
		} else if (e.keyCode === 37){
			tetris.move('left');
		} else if (e.keyCode === 38){
			tetris.rotate();
		} else if (e.keyCode === 40){ // tryck på ner-tangenten och hela figuren droppas!
			tetris.drop();
		}
	})

	8
	var gravity = setInterval(function(){
		tetris.drop();
	},500); // Ändra hastigheten här, i millisekunder

})
<commit_msg>senaste js fixad<commit_after>var name = "";
var points = 0;
var gravity;
//Declare global object tetris
var tetris = {};

//Draw the grid --------------------------------------------------
tetris.drawPlayField = function(){

  for(var row = 0; row < 22; row++){
    $('#playfield').append('

');

    for (var col=0;col<10;col++){
      $('tr.'+row).append('	');
    }
  }
}

//Variable to store current coordinates --------------------------

// vart första klossen börjar
tetris.origin = {row:2,col:5};
// vilket typ av kloss som man börjar med
tetris.currentShape = 'L'; // slumpa ist?

tetris.currentCoor;

//Fill the cells -------------------------------------------------
tetris.fillCells = function(coordinates, fillcolor){

  for(var i=0; i < coordinates.length; i++){
    var row = coordinates[i].row;
    var col = coordinates[i].col;
    var $coor = $('.'+row).find('#'+col);
    $coor.attr('bgcolor', fillcolor);
  }
}

/* Funktionen tar en array av koordinater och loopar igenom,
för varje iteration lagras radnumret i den lokala variabeln "row",
samma gäller för colnumret i den lokala variabeln "col". JQuery selektoren lagras
i den lokala variabeln "$coor" - Sen kommer funktionen att byta ut koordinaternas
backgrundsfärg till den färg vi har angett längre ner "currentCoor", i detta fall "black". */

//Move current shape --------------------------------------------
tetris.move = function(direction){
	this.fillCells(this.currentCoor,'');

	//move origin
	if(direction === 'right'){
		this.origin.col++;
	} else if (direction === 'left'){
		this.origin.col--;
	}

	this.currentCoor = this.shapeToCoor(this.currentShape,this.origin);

	if(this.ifReverse()){
		if(direction === 'right'){
			this.origin.col--;
		} else if (direction === 'left'){
			this.origin.col++;
		}
	}

	this.currentCoor = this.shapeToCoor(this.currentShape,this.origin);

	this.fillCells(this.currentCoor,'black');
}

//Rotera nuvarande figur + efterföljande figurer -----------------------
tetris.rotate = function(){
	var lastShape = this.currentShape;
	this.fillCells(this.currentCoor,'');

	if(this.currentShape === 'L'){
		this.currentShape = 'L90';
	} else if(this.currentShape === 'L90'){
		this.currentShape = 'L180';
	} else if(this.currentShape === 'L180'){
		this.currentShape = 'L270';
	} else if(this.currentShape === 'L270'){
		this.currentShape = 'L';
	} else if(this.currentShape === 'J'){
		this.currentShape = 'J90';
	} else if(this.currentShape === 'J90'){
		this.currentShape = 'J180';
	} else if(this.currentShape === 'J180'){
		this.currentShape = 'J270';
	} else if(this.currentShape === 'J270'){
		this.currentShape = 'J';
	} else if(this.currentShape === 'I'){
		this.currentShape = 'I90';
	} else if(this.currentShape === 'I90'){
		this.currentShape = 'I';
	} else if(this.currentShape === 'S'){
		this.currentShape = 'S90';
	} else if(this.currentShape === 'S90'){
		this.currentShape = 'S';
	} else if(this.currentShape === 'Z'){
		this.currentShape = 'Z90';
	} else if(this.currentShape === 'Z90'){
		this.currentShape = 'Z';
	} else if(this.currentShape === 'T'){
		this.currentShape = 'T90';
	} else if(this.currentShape === 'T90'){
		this.currentShape = 'T180';
	} else if(this.currentShape === 'T180'){
		this.currentShape = 'T270';
	} else if(this.currentShape === 'T270'){
		this.currentShape = 'T';
	}

	this.currentCoor = this.shapeToCoor(this.currentShape,this.origin);

	for(var i=0;i<this.currentCoor.length;i++){
		if(this.ifReverse()){
			this.currentShape = lastShape;
		}
	}

	this.currentCoor = this.shapeToCoor(this.currentShape,this.origin);
	this.fillCells(this.currentCoor,'black');
}

// Definiera tetris-figurer ---------------------------------------------------------
tetris.shapeToCoor = function(shape,origin){
	if (shape === 'L') {
		return [
            { row: origin.row, col: origin.col },
            { row: origin.row - 1, col: origin.col },
            { row: origin.row + 1, col: origin.col },
            { row: origin.row + 1, col: origin.col + 1 }
        ];
	} else if(shape === 'J'){
		return [{row:origin.row,col:origin.col},{row:origin.row-1,col:origin.col},{row:origin.row+1,col:origin.col},{row:origin.row+1,col:origin.col-1}]
	} else if(shape === 'I'){
		return [{row:origin.row,col:origin.col},{row:origin.row-1,col:origin.col},{row:origin.row-2,col:origin.col},{row:origin.row+1,col:origin.col}]
	} else if(shape === 'O'){
		return [{row:origin.row,col:origin.col},{row:origin.row-1,col:origin.col},{row:origin.row-1,col:origin.col+1},{row:origin.row,col:origin.col+1}]
	} else if(shape === 'S'){
		return [{row:origin.row,col:origin.col},{row:origin.row-1,col:origin.col},{row:origin.row,col:origin.col-1},{row:origin.row-1,col:origin.col+1}]
	} else if(shape === 'T'){
		return [{row:origin.row,col:origin.col},{row:origin.row-1,col:origin.col},{row:origin.row,col:origin.col-1},{row:origin.row,col:origin.col+1}]
	} else if(shape === 'Z'){
		return [{row:origin.row,col:origin.col},{row:origin.row-1,col:origin.col},{row:origin.row-1,col:origin.col-1},{row:origin.row,col:origin.col+1}]
	} else if(shape === 'L90'){
  	return [{row:origin.row,col:origin.col},{row:origin.row,col:origin.col+1},{row:origin.row,col:origin.col-1},{row:origin.row+1,col:origin.col-1}];
  } else if(shape === 'L180'){
  	return [{row:origin.row,col:origin.col},{row:origin.row-1,col:origin.col},{row:origin.row+1,col:origin.col},{row:origin.row-1,col:origin.col-1}];
  } else if(shape === 'L270'){
  	return [{row:origin.row,col:origin.col},{row:origin.row,col:origin.col+1},{row:origin.row,col:origin.col-1},{row:origin.row-1,col:origin.col+1}];
  } else if(shape === 'J90'){
		return [{row:origin.row,col:origin.col},{row:origin.row,col:origin.col-1},{row:origin.row,col:origin.col+1},{row:origin.row-1,col:origin.col-1}]
	} else if(shape === 'J180'){
		return [{row:origin.row,col:origin.col},{row:origin.row-1,col:origin.col},{row:origin.row+1,col:origin.col},{row:origin.row-1,col:origin.col+1}]
	} else if(shape === 'J270'){
		return [{row:origin.row,col:origin.col},{row:origin.row,col:origin.col-1},{row:origin.row,col:origin.col+1},{row:origin.row+1,col:origin.col+1}]
	} else if(shape === 'I90'){
		return [{row:origin.row,col:origin.col},{row:origin.row,col:origin.col-1},{row:origin.row,col:origin.col+1},{row:origin.row,col:origin.col+2}]
	} else if(shape === 'S90'){
		return [{row:origin.row,col:origin.col},{row:origin.row-1,col:origin.col},{row:origin.row-1,col:origin.col-1},{row:origin.row-2,col:origin.col-1}]
	} else if(shape === 'Z90'){
		return [{row:origin.row,col:origin.col},{row:origin.row-1,col:origin.col},{row:origin.row-1,col:origin.col+1},{row:origin.row-2,col:origin.col+1}]
	} else if(shape === 'T90'){
		return [{row:origin.row,col:origin.col},{row:origin.row-1,col:origin.col},{row:origin.row+1,col:origin.col},{row:origin.row,col:origin.col+1}]
	} else if(shape === 'T180'){
		return [{row:origin.row,col:origin.col},{row:origin.row+1,col:origin.col},{row:origin.row,col:origin.col-1},{row:origin.row,col:origin.col+1}]
	} else if(shape === 'T270'){
		return [{row:origin.row,col:origin.col},{row:origin.row-1,col:origin.col},{row:origin.row+1,col:origin.col},{row:origin.row,col:origin.col-1}]
	}
}

/* Definera figurer OCH hur varje figur ska rotera när upp-tangenten trycks ner */

//Drop shape by one row -----------------------------------------------
tetris.drop = function(){
	var reverse = false;

	this.fillCells(this.currentCoor,'');
	this.origin.row++;
	for(var i=0;i<this.currentCoor.length;i++){
		this.currentCoor[i].row++;
		if(this.ifReverse()){
			reverse = true;
		}
	}

	if(reverse){
		for(var i=0;i<this.currentCoor.length;i++){
			this.currentCoor[i].row--;
		}
		this.origin.row--;
	}

	this.fillCells(this.currentCoor,'black');

	if(reverse){
        // game over
        if (this.origin.row == 2) {
            console.log("game over?");
            clearInterval(gravity);

            console.log(name + " fick " + points);
            // spara poäng + spelarens namn i localStorage,
            // visa knapp för att starta om? eller visa highscore

        } else {
            console.log("game continues");
            this.fillCells(this.currentCoor,'BLACK');
            this.emptyFullRow();
            this.spawn();
        }
	}

}

//Spawn random shape -------------------------------------------------
tetris.spawn = function(){
	var random = Math.floor(Math.random()*7);
	var shapeArray = ['L','J','I','O','S','T','Z'];

	this.currentShape = shapeArray[random];
	this.origin = {row:2,col:5};
	this.currentCoor = this.shapeToCoor(this.currentShape,this.origin);
}

/* Slumpar fram nya tetris-figurer när den nuvarande har nått botten */

//If we need to reverse  -------------------------------------------------
tetris.ifReverse = function(){
	for(var i=0;i<this.currentCoor.length;i++){
		var row = this.currentCoor[i].row;
		var col = this.currentCoor[i].col;
		var $coor = $('.'+row).find('#'+col);
		if($coor.length === 0 || $coor.attr('bgcolor') === 'BLACK'){
			return true;
		}
	}
	return false;
}

//Empty full row -------------------------------------------------
tetris.emptyFullRow = function(){
	var drops = 0;
	for (var i=21; i>=0;i--){
		var rowIsFull = true;

		for (var j=0;j<10;j++){
			var $coor = $('.'+i).find('#'+j);
			if($coor.attr('bgcolor')!=='BLACK'){
				rowIsFull = false;
			}

			if(drops>0){
				var $newCoor = $('.'+(i+drops)).find('#'+j);
				$newCoor.attr('bgcolor',$coor.attr('bgcolor'));
			}
		}

		if(rowIsFull){
			drops++;
		}
	}
}

// document.ready function - ska alltid vara längst ner ----------------
$(document).ready(function(){
	tetris.drawPlayField();

})

// startar spelet
function startGame() {
	tetris.currentCoor = tetris.shapeToCoor(tetris.currentShape,tetris.origin);
	tetris.fillCells(tetris.currentCoor,'black');

	$(document).keydown(function(e){ // Känner av piltangenterna
		console.log(e.keyCode);
		if(e.keyCode === 39){
			tetris.move('right');
		} else if (e.keyCode === 37){
			tetris.move('left');
		} else if (e.keyCode === 38){
			tetris.rotate();
		} else if (e.keyCode === 40){ // tryck på ner-tangenten och hela figuren droppas!
			tetris.drop();
		}
	})

	// Global
	gravity = setInterval(function(){
		tetris.drop();
        // skriv ut den nuvarande klossens position (för färger) och positionen på spelplanen (origin)
        // console.log(tetris.currentCoor, tetris.origin);
	},500); // Ändra hastigheten här, i millisekunder
}

var startButton = document.getElementById("start-game");

startButton.addEventListener("click", function() {
    var username = prompt("Enter your username:");

    if (username !== null) {
        // spara det namn personen fyllde i, i den globala variabeln "name"
        name = username;
        startGame(); // starta spelet
    } else {
        console.log("empty name...");
    }

});<|endoftext|>


<commit_before>'use strict';

var currentUserIndex;
var userProfileIndex;
var users = [];
var wines = ['red','white'];
var wineList = ['cab','merlot','malbec'];
var wineries = ['st.michelles','whatever winery'];

try {
  users = JSON.parse(localStorage.users);

}
catch (error) {
  console.log('something went wrong', error);
}

try {
  currentUserIndex = JSON.parse(localStorage.currentUserIndex);
}
catch (error) {
  console.log('something went wrong', error);
}

function User (profilePic, first, last, userName) {
  this.first= first;
  this.last= last;
  this.userName = userName;
  this.wineColors = [];
  this.favWines =[];
  this.favWineries = [];
  this.bio = '';
  this.id = Math.random()+''+Math.random();
  this.profilePic = profilePic;
  this.reviews = [];
  this.comments = [];
}

function Comment(userName, comment, date) {
  this.userName = userName;
  this.comment = comment;
  this.date = date;
}

function checkBoxGenerator(list, listQuestion, questionName) {
  var form = document.getElementById('boolean-questions');
  var header = document.createElement('h3');
  header.textContent = listQuestion;
  form.appendChild(header);
  var ul = document.createElement('ul');
  ul.setAttribute('class', 'question');
  form.appendChild(ul);
  for (var i = 0; i < list.length; i++) {
    var li = document.createElement('li');
    var checkbox = document.createElement('input');
    checkbox.setAttribute('type', 'checkbox');
    checkbox.setAttribute('name', list[i]);
    checkbox.setAttribute('id', list[i]);
    var label = document.createElement('label');
    label.setAttribute('for', questionName);
    label.textContent = list[i];
    ul.appendChild(li);
    li.appendChild(checkbox);
    li.appendChild(label);
  }
}
<commit_msg>added json parse for userProfileIndex on to main js<commit_after>'use strict';

var currentUserIndex;
var userProfileIndex;
var users = [];
var wines = ['red','white'];
var wineList = ['cab','merlot','malbec'];
var wineries = ['st.michelles','whatever winery'];

try {
  users = JSON.parse(localStorage.users);

}
catch (error) {
  console.log('something went wrong', error);
}

try {
  currentUserIndex = JSON.parse(localStorage.currentUserIndex);
}
catch (error) {
  console.log('something went wrong', error);
}
try {
  userProfileIndex = JSON.parse(localStorage.userProfileIndex);
}
catch (error) {
  console.log('something is wrong with grabbing userProfileIndex', error);
}

function User (profilePic, first, last, userName) {
  this.first= first;
  this.last= last;
  this.userName = userName;
  this.wineColors = [];
  this.favWines =[];
  this.favWineries = [];
  this.bio = '';
  this.id = Math.random()+''+Math.random();
  this.profilePic = profilePic;
  this.reviews = [];
  this.comments = [];
}

function Comment(userName, comment, date) {
  this.userName = userName;
  this.comment = comment;
  this.date = date;
}

function checkBoxGenerator(list, listQuestion, questionName) {
  var form = document.getElementById('boolean-questions');
  var header = document.createElement('h3');
  header.textContent = listQuestion;
  form.appendChild(header);
  var ul = document.createElement('ul');
  ul.setAttribute('class', 'question');
  form.appendChild(ul);
  for (var i = 0; i < list.length; i++) {
    var li = document.createElement('li');
    var checkbox = document.createElement('input');
    checkbox.setAttribute('type', 'checkbox');
    checkbox.setAttribute('name', list[i]);
    checkbox.setAttribute('id', list[i]);
    var label = document.createElement('label');
    label.setAttribute('for', questionName);
    label.textContent = list[i];
    ul.appendChild(li);
    li.appendChild(checkbox);
    li.appendChild(label);
  }
}
<|endoftext|>


<commit_before>/**
 * Created by asher on 2/07/16.
 */
console.log("Starting up...");
var express = require('express'),
    http = require('http'),
    https = require('https'),
    app = express(),
    port = process.env.PORT || process.argv[2] || 8060,
    base = ".proxy.asherfoster.com",
    httpOnly = [];

function getPage(method, url, host, res){
    console.log(url);
    var body = "";
    method(url, function(resp){
        resp.on('data', function(chunk){
            body += chunk;
        });
        resp.on('end', function() {
            if(resp.statusCode > 300 && resp.statusCode < 400){
                if(resp.headers.location.substr(0, 5) === 'http:'){
                    console.log("Got an HTTP only page");
                    httpOnly.push(host);
                    getPage(http.get, url.slice(0, 4) + url.slice(5), host, res);
                }
            }else{
                res.status(resp.statusCode);
                res.set(resp.headers);
                res.send(body);
            }
        });
    });
}
app.use(function(req, res){
    var host = req.headers.host.split(base)[0],
        url = 'https://' + host + req.url;
    if(url !== "/"){
        var body = "";
        try{
            getPage((httpOnly.indexOf(host) > -1 ? http : https).get, url, host, res);
        }catch(e){
            console.error(e);
            res.sendStatus(500);
        }
    }else res.status(400).send("Have a host");
});
app.listen(port);
console.log("Ready on port "+port);
<commit_msg>More work<commit_after>/**
 * Created by asher on 2/07/16.
 */
console.log("Starting up...");
var express = require('express'),
    http = require('http'),
    https = require('https'),
    app = express(),
    port = process.env.PORT || process.argv[2] || 8060,
    base = ".proxy.asherfoster.com",
    httpOnly = [];

function getPage(method, url, host, res){
    console.log(url);
    var body = "";
    method(url, function(resp){
        resp.on('data', function(chunk){
            body += chunk;
        });
        resp.on('end', function() {
            if(resp.statusCode > 300 && resp.statusCode < 400){
                if(resp.headers.location.substr(0, 5) === 'http:'){
                    console.log("Got an HTTP only page");
                    httpOnly.push(host);
                    getPage(http.get, url.slice(0, 4) + url.slice(5), host, res);
                }
            }else{
                res.status(resp.statusCode);
                res.set(resp.headers);
                res.send(body);
            }
        });
    });
}
app.use(function(req, res){
    var host = req.headers.host.split(base)[0],
        url = (httpOnly.indexOf(host) > -1 ? 'http://' : 'https://') + host + req.url;
    if(url !== "/"){
        var body = "";
        try{
            getPage((url[4] === 's' ? http : https).get, url, host, res);
        }catch(e){
            console.error(e);
            res.sendStatus(500);
        }
    }else res.status(400).send("Have a host");
});
app.listen(port);
console.log("Ready on port "+port);
<|endoftext|>


<commit_before>define(function (require, exports, module) {

    var DocumentManager = brackets.getModule('document/DocumentManager'),
        babel           = require('babel-5.8.22.min');

    DocumentManager.on('documentSaved', function () {
        var doc = DocumentManager.getCurrentDocument();
        var file = {
            parentPath: doc.file._parentPath,
            name: doc.file._name.split('.')[0],
            ext: doc.file._name.split('.').pop(),
            contents: doc.file._contents
        };
        switch (file.ext) {
        case 'jsx':
            try {
                brackets.fs.writeFile(
                    file.parentPath + file.name + '.js',
                    babel.transform(file.contents, []).code,
                    'utf8'
                );
            } catch (e) {
                var DefaultDialogs = brackets.getModule('widgets/DefaultDialogs');
                var Dialogs = brackets.getModule('widgets/Dialogs');
                Dialogs.showModalDialog(DefaultDialogs.DIALOG_ID_ERROR, "", "Unable to transform ES6 and JSX files into ES5, see the debug logs for details.");
                brackets.fs.writeFile(
                    file.parentPath + file.name + '.js',
                    '',
                    'utf8'
                );
                throw e;
            }
            break;
        }
    });
});
<commit_msg>Update main.js<commit_after>define(function (require, exports, module) {

    var DocumentManager = brackets.getModule('document/DocumentManager'),
        babel           = require('babel-5.8.22.min');

    DocumentManager.on('documentSaved', function () {
        var doc = DocumentManager.getCurrentDocument();
        var file = {
            parentPath: doc.file._parentPath,
            name: doc.file._name.split('.')[0],
            ext: doc.file._name.split('.').pop(),
            contents: doc.file._contents
        };
        switch (file.ext) {
        case 'jsx':
            try {
                brackets.fs.writeFile(
                    file.parentPath + file.name + '.compiled.js',
                    babel.transform(file.contents, []).code,
                    'utf8'
                );
            } catch (e) {
                var DefaultDialogs = brackets.getModule('widgets/DefaultDialogs');
                var Dialogs = brackets.getModule('widgets/Dialogs');
                Dialogs.showModalDialog(DefaultDialogs.DIALOG_ID_ERROR, "", "Unable to transform ES6 and JSX files into ES5, see the debug logs for details.");
                brackets.fs.writeFile(
                    file.parentPath + file.name + '.js',
                    '',
                    'utf8'
                );
                throw e;
            }
            break;
        }
    });
});
<|endoftext|>


<commit_before>'use strict';

const { app, Tray, BrowserWindow } = require('electron');
const mycron = require('cron').CronJob;
const fetch = require('isomorphic-fetch');
const notifier = require('node-notifier');

const waterLevelURL = '';

// icon
const trayIcon1 = `${ __dirname }/icon/tray-icon1.png`;
const trayIcon2 = `${ __dirname }/icon/tray-icon2.png`;
const trayIcon3 = `${ __dirname }/icon/tray-icon3.png`;
const trayIcon4 = `${ __dirname }/icon/tray-icon4.png`;
const trayIcon5 = `${ __dirname }/icon/tray-icon5.png`;
const pushIcon = `${ __dirname }/icon/push-icon.png`;

let appIcon = null;
let win = null;

app.on('ready', function ready() {
  // hide icon on dock
  app.dock.hide();

  // Tray
  appIcon = new Tray(`${__dirname}/icon/icon1.png`);
  let trayBounds = appIcon.getBounds();

  // BrowserWindow
  win = new BrowserWindow({
    frame: false,
    width: 200,
    height: 200,
    x: trayBounds.x - 80,
    y: trayBounds.y,
  });
  win.loadURL(`file://${__dirname}/app/index.html`);

  win.on('blur', () =>{
    win.hide()
  });

  appIcon.on('click', () => {
    // win.setPosition(trayBounds.x - 80, trayBounds.y);
    win.isVisible() ? win.hide() : win.show()
  });

  polling(requestWaterLevel, '*/2 * * * * *');
  // String
  scheduledNotify(generateNotify, '*/10 * * * * *');
});

function polling(func, cronTime) {
  const job = new mycron({
    cronTime: cronTime,
    onTick: func,
    start: true,
  });
  job.start();
}

function generateNotify() {
  return notifier.notify({
    'title': '警告',
    'message': '水位が急上昇しています!',
    'icon': pushIcon,
  });
}

function scheduledNotify(func, cronTime) {
  const job = new mycron({
    cronTime: cronTime,
    onTick: func,
    start: true,
  });
  job.start();
}

function requestWaterLevel() {
  const min = 0 ;
  const max = 4 ;
  const randomNum = Math.floor( Math.random() * (max + 1 - min) ) + min;
  if (randomNum === 0) {
    appIcon.setImage(trayIcon1);
  } else if (randomNum === 1) {
    appIcon.setImage(trayIcon2);
  } else if (randomNum === 2) {
    appIcon.setImage(trayIcon3);
  } else if (randomNum === 3) {
    appIcon.setImage(trayIcon4);
  } else {
    appIcon.setImage(trayIcon5);
  }

  httpRequest(waterLevelURL, 'GET')
    .then((res) => console.log(res))
    .catch((err) => {
      console.error(err.stack);
    });
}

function httpRequest(path, method, body = undefined) {
  return fetch(path, {
    method,
    headers: {
      'Content-Type': 'application/json'
    },
    body
  })
    .then((res) => {
      if (res.status >= 400) {
        throw new Error("Bad response from server")
      }
      return res.json();
    });
}
<commit_msg>fix bug<commit_after>'use strict';

const { app, Tray, BrowserWindow } = require('electron');
const mycron = require('cron').CronJob;
const fetch = require('isomorphic-fetch');
const notifier = require('node-notifier');

const waterLevelURL = '';

// icon
const trayIcon1 = `${ __dirname }/icon/tray-icon1.png`;
const trayIcon2 = `${ __dirname }/icon/tray-icon2.png`;
const trayIcon3 = `${ __dirname }/icon/tray-icon3.png`;
const trayIcon4 = `${ __dirname }/icon/tray-icon4.png`;
const trayIcon5 = `${ __dirname }/icon/tray-icon5.png`;
const pushIcon = `${ __dirname }/icon/push-icon.png`;

let appIcon = null;
let win = null;

app.on('ready', function ready() {
  // hide icon on dock
  app.dock.hide();

  // Tray
  appIcon = new Tray(trayIcon1);
  let trayBounds = appIcon.getBounds();

  // BrowserWindow
  win = new BrowserWindow({
    frame: false,
    width: 200,
    height: 200,
    x: trayBounds.x - 80,
    y: trayBounds.y,
  });
  win.loadURL(`file://${__dirname}/app/index.html`);

  win.on('blur', () =>{
    win.hide()
  });

  appIcon.on('click', () => {
    // win.setPosition(trayBounds.x - 80, trayBounds.y);
    win.isVisible() ? win.hide() : win.show()
  });

  polling(requestWaterLevel, '*/2 * * * * *');
  // String
  scheduledNotify(generateNotify, '*/10 * * * * *');
});

function polling(func, cronTime) {
  const job = new mycron({
    cronTime: cronTime,
    onTick: func,
    start: true,
  });
  job.start();
}

function generateNotify() {
  return notifier.notify({
    'title': '警告',
    'message': '水位が急上昇しています!',
    'icon': pushIcon,
  });
}

function scheduledNotify(func, cronTime) {
  const job = new mycron({
    cronTime: cronTime,
    onTick: func,
    start: true,
  });
  job.start();
}

function requestWaterLevel() {
  const min = 0 ;
  const max = 4 ;
  const randomNum = Math.floor( Math.random() * (max + 1 - min) ) + min;
  if (randomNum === 0) {
    appIcon.setImage(trayIcon1);
  } else if (randomNum === 1) {
    appIcon.setImage(trayIcon2);
  } else if (randomNum === 2) {
    appIcon.setImage(trayIcon3);
  } else if (randomNum === 3) {
    appIcon.setImage(trayIcon4);
  } else {
    appIcon.setImage(trayIcon5);
  }

  httpRequest(waterLevelURL, 'GET')
    .then((res) => console.log(res))
    .catch((err) => {
      console.error(err.stack);
    });
}

function httpRequest(path, method, body = undefined) {
  return fetch(path, {
    method,
    headers: {
      'Content-Type': 'application/json'
    },
    body
  })
    .then((res) => {
      if (res.status >= 400) {
        throw new Error("Bad response from server")
      }
      return res.json();
    });
}
<|endoftext|>


<commit_before>// statsbot

var log = require('log-simple')()

var VERSION = '0.1.0'
log.info('statsbot v' + VERSION)

// configuration
var config = require('./config.json')
if (config && config.debug) {
  log.setDebug(config.debug)
}
log.debug('successfully loaded configuration')

// db setup
var jsop = require('jsop')
var db = jsop('stats.json')
if (!db.channels) db.channels = {}
if (!db.users) db.users = {}

// client setup
var client = require('coffea')()
var emoji = require('node-emoji').emoji

var network_config = {}
var id = 0
config.networks.forEach(function (network) {
  network.id = '' + id
  client.add(network)
  log.debug('connecting to network ' + id + ':', JSON.stringify(network))
  network_config[id] = network
  id++
})

// bot begins here
function name (data) {
  if (!data) return undefined
  // FIXME: coffea-telegram workaround, channel should be .name not .title
  return data.nick || data.name || data.title
}

// event handlers
function processEvent (event, type) {
  var c = name(event && event.channel)
  var u = name(event && event.user)

  log.debug('processing "' + type + '" event by "' + u + '" in "' + c + '"')

  if (c) {
    if (!db.channels[c]) db.channels[c] = { users: {} }
    if (!db.channels[c][type]) db.channels[c][type] = 0
    db.channels[c][type]++

    if (event.user) {
      if (!db.channels[c].users[u]) db.channels[c].users[u] = {}
      if (!db.channels[c].users[u][type]) db.channels[c].users[u][type] = 0
      db.channels[c].users[u][type]++
    }
  }

  if (u) {
    if (!db.users[u]) db.users[u] = {}
    if (!db.users[u][type]) db.users[u][type] = 0
    db.users[u][type]++
  }
}

function processEventFactory (type) {
  return function (event) {
    return processEvent(event, type)
  }
}

// display stats
function stats (type, emoji) {
  return function typedStats (data) {
    return (data && data[type] ? data[type] : 0) + ' ' + emoji
  }
}

function cmdStats (data) {
  // FIXME: (/2) is a dirty workaround for coffea-telegram bug that sends commands twice
  return (data && data.commands ? data.commands / 2 : 0) +
    ' ' + emoji.thought_balloon
}

var msgStats = stats('messages', emoji.speech_balloon)
var audioStats = stats('audio', emoji.sound)
var videoStats = stats('video', emoji.movie_camera)
var photoStats = stats('photo', emoji.mount_fuji)
var stickerStats = stats('sticker', emoji.paperclip)

function apply (arr, x) {
  return arr.map(function (f) {
    return f(x)
  })
}

function showStats (what, data) {
  return 'Stats for "' + what + '": ' +
    apply(
      [msgStats, cmdStats, stickerStats, photoStats, audioStats, videoStats]
    , data)
    .join(' | ')
}

// event listeners
client.on('message', processEventFactory('messages'))
client.on('audio', processEventFactory('audio'))
client.on('voice', processEventFactory('audio'))
client.on('video', processEventFactory('video'))
client.on('photo', processEventFactory('photo'))
client.on('sticker', processEventFactory('sticker'))

client.on('command', function (event) {
  processEvent(event, 'commands')

  var c = name(event && event.channel)
  var u = name(event && event.user)

  switch (event.cmd) {
    case 'stats':
      var repl
      if (event.channel) {
        repl = showStats(c, db.channels[c])
        if (event.args.length > 0) {
          var user = event.args[0]
          // FIXME: dat injection
          repl = showStats(user + '" in "' + c, db.channels[c].users[user])
        }
      } else repl = showStats(u, db.users[u])
      event.reply(repl)
      break
  }
})
<commit_msg>change sticker emoji from :paperclip: to :rainbow:<commit_after>// statsbot

var log = require('log-simple')()

var VERSION = '0.1.0'
log.info('statsbot v' + VERSION)

// configuration
var config = require('./config.json')
if (config && config.debug) {
  log.setDebug(config.debug)
}
log.debug('successfully loaded configuration')

// db setup
var jsop = require('jsop')
var db = jsop('stats.json')
if (!db.channels) db.channels = {}
if (!db.users) db.users = {}

// client setup
var client = require('coffea')()
var emoji = require('node-emoji').emoji

var network_config = {}
var id = 0
config.networks.forEach(function (network) {
  network.id = '' + id
  client.add(network)
  log.debug('connecting to network ' + id + ':', JSON.stringify(network))
  network_config[id] = network
  id++
})

// bot begins here
function name (data) {
  if (!data) return undefined
  // FIXME: coffea-telegram workaround, channel should be .name not .title
  return data.nick || data.name || data.title
}

// event handlers
function processEvent (event, type) {
  var c = name(event && event.channel)
  var u = name(event && event.user)

  log.debug('processing "' + type + '" event by "' + u + '" in "' + c + '"')

  if (c) {
    if (!db.channels[c]) db.channels[c] = { users: {} }
    if (!db.channels[c][type]) db.channels[c][type] = 0
    db.channels[c][type]++

    if (event.user) {
      if (!db.channels[c].users[u]) db.channels[c].users[u] = {}
      if (!db.channels[c].users[u][type]) db.channels[c].users[u][type] = 0
      db.channels[c].users[u][type]++
    }
  }

  if (u) {
    if (!db.users[u]) db.users[u] = {}
    if (!db.users[u][type]) db.users[u][type] = 0
    db.users[u][type]++
  }
}

function processEventFactory (type) {
  return function (event) {
    return processEvent(event, type)
  }
}

// display stats
function stats (type, emoji) {
  return function typedStats (data) {
    return (data && data[type] ? data[type] : 0) + ' ' + emoji
  }
}

function cmdStats (data) {
  // FIXME: (/2) is a dirty workaround for coffea-telegram bug that sends commands twice
  return (data && data.commands ? data.commands / 2 : 0) +
    ' ' + emoji.thought_balloon
}

var msgStats = stats('messages', emoji.speech_balloon)
var audioStats = stats('audio', emoji.sound)
var videoStats = stats('video', emoji.movie_camera)
var photoStats = stats('photo', emoji.mount_fuji)
var stickerStats = stats('sticker', emoji.rainbow)

function apply (arr, x) {
  return arr.map(function (f) {
    return f(x)
  })
}

function showStats (what, data) {
  return 'Stats for "' + what + '": ' +
    apply(
      [msgStats, cmdStats, stickerStats, photoStats, audioStats, videoStats]
    , data)
    .join(' | ')
}

// event listeners
client.on('message', processEventFactory('messages'))
client.on('audio', processEventFactory('audio'))
client.on('voice', processEventFactory('audio'))
client.on('video', processEventFactory('video'))
client.on('photo', processEventFactory('photo'))
client.on('sticker', processEventFactory('sticker'))

client.on('command', function (event) {
  processEvent(event, 'commands')

  var c = name(event && event.channel)
  var u = name(event && event.user)

  switch (event.cmd) {
    case 'stats':
      var repl
      if (event.channel) {
        repl = showStats(c, db.channels[c])
        if (event.args.length > 0) {
          var user = event.args[0]
          // FIXME: dat injection
          repl = showStats(user + '" in "' + c, db.channels[c].users[user])
        }
      } else repl = showStats(u, db.users[u])
      event.reply(repl)
      break
  }
})
<|endoftext|>


<commit_before>var electron = require('electron');
var app = electron.app;
var BrowserWindow = electron.BrowserWindow;
var Menu = electron.Menu;
var crashReporter = electron.crashReporter;
var menu, template;

crashReporter.start({
  productName: 'GraphiQL',
  companyName: 'n/a',
  submitURL: 'https://github.com/skevy/graphiql-app/issues',
  autoSubmit: true
});

var mainWindow = null;

app.on('window-all-closed', function() {
  if (process.platform !== 'darwin') app.quit();
});

app.on('ready', function() {

  mainWindow = new BrowserWindow({ width: 1024, height: 728 });

  electron.session.defaultSession.webRequest.onBeforeSendHeaders((details, callback) => {
    details.requestHeaders['Origin'] = 'electron://graphiql-app';
    callback({ cancel: false, requestHeaders: details.requestHeaders });
  });

  if (process.env.HOT) {
    mainWindow.loadURL('file://' + __dirname + '/app/hot-dev-app.html');
  } else {
    mainWindow.loadURL('file://' + __dirname + '/app/app.html');
  }

  mainWindow.on('closed', function() {
    mainWindow = null;
  });

  if (process.env.NODE_ENV === 'development') {
    mainWindow.openDevTools();
  }

  if (process.platform === 'darwin') {
    template = [{
      label: 'GraphiQL',
      submenu: [{
        label: 'About GraphiQL',
        selector: 'orderFrontStandardAboutPanel:'
      }, {
        type: 'separator'
      }, {
        label: 'Services',
        submenu: []
      }, {
        type: 'separator'
      }, {
        label: 'Hide GraphiQL',
        accelerator: 'Command+H',
        selector: 'hide:'
      }, {
        label: 'Hide Others',
        accelerator: 'Command+Shift+H',
        selector: 'hideOtherApplications:'
      }, {
        label: 'Show All',
        selector: 'unhideAllApplications:'
      }, {
        type: 'separator'
      }, {
        label: 'Quit',
        accelerator: 'Command+Q',
        click: function() {
          app.quit();
        }
      }]
    }, {
      label: 'File',
      submenu: [{
        label: 'New Query',
        accelerator: 'Command+T',
        click: function() {
          mainWindow.webContents.send('handleElectronMenuOption', 'NEW_TAB');
        }
      }, {
        label: 'Close Query',
        accelerator: 'Command+W',
        click: function() {
          mainWindow.webContents.send('handleElectronMenuOption', 'CLOSE_TAB');
        }
      }]
    }, {
      label: 'Edit',
      submenu: [{
        label: 'Undo',
        accelerator: 'Command+Z',
        selector: 'undo:'
      }, {
        label: 'Redo',
        accelerator: 'Shift+Command+Z',
        selector: 'redo:'
      }, {
        type: 'separator'
      }, {
        label: 'Cut',
        accelerator: 'Command+X',
        selector: 'cut:'
      }, {
        label: 'Copy',
        accelerator: 'Command+C',
        selector: 'copy:'
      }, {
        label: 'Paste',
        accelerator: 'Command+V',
        selector: 'paste:'
      }, {
        label: 'Select All',
        accelerator: 'Command+A',
        selector: 'selectAll:'
      }]
    }, {
      label: 'View',
      submenu: [{
        label: 'Reload',
        accelerator: 'Command+R',
        click: function() {
          mainWindow.reload();
        }
      }, {
        label: 'Toggle Full Screen',
        accelerator: 'Ctrl+Command+F',
        click: function() {
          mainWindow.setFullScreen(!mainWindow.isFullScreen());
        }
      }, {
        label: 'Toggle Developer Tools',
        accelerator: 'Alt+Command+I',
        click: function() {
          mainWindow.toggleDevTools();
        }
      }, {
        role: 'resetzoom'
      }, {
        role: 'zoomin'
      }, {
        role: 'zoomout'
      }]
    }, {
      label: 'Window',
      submenu: [{
        label: 'Minimize',
        accelerator: 'Command+M',
        selector: 'performMiniaturize:'
      }, {
        type: 'separator'
      }, {
        label: 'Bring All to Front',
        selector: 'arrangeInFront:'
      }]
    }, {
      label: 'Help',
      submenu: [{
        label: 'Learn More',
        click: function() {
          require('shell').openExternal('http://electron.atom.io');
        }
      }, {
        label: 'Documentation',
        click: function() {
          require('shell').openExternal('https://github.com/atom/electron/tree/master/docs#readme');
        }
      }, {
        label: 'Community Discussions',
        click: function() {
          require('shell').openExternal('https://discuss.atom.io/c/electron');
        }
      }, {
        label: 'Search Issues',
        click: function() {
          require('shell').openExternal('https://github.com/atom/electron/issues');
        }
      }]
    }];

    menu = Menu.buildFromTemplate(template);
    Menu.setApplicationMenu(menu);
  } else {
    template = [{
      label: '&File',
      submenu: [{
        label: 'New Query',
        accelerator: 'Ctrl+N',
        click: function() {
          mainWindow.webContents.send('handleElectronMenuOption', 'NEW_TAB');
        }
      }, {
        label: 'Close Query',
        accelerator: 'Ctrl+W',
        click: function() {
          mainWindow.webContents.send('handleElectronMenuOption', 'CLOSE_TAB');
        }
      }]
    }, {
      label: '&View',
      submenu: [{
        label: '&Reload',
        accelerator: 'Ctrl+R',
        click: function() {
          mainWindow.restart();
        }
      }, {
        label: 'Toggle &Full Screen',
        accelerator: 'F11',
        click: function() {
          mainWindow.setFullScreen(!mainWindow.isFullScreen());
        }
      }, {
        label: 'Toggle &Developer Tools',
        accelerator: 'Alt+Ctrl+I',
        click: function() {
          mainWindow.toggleDevTools();
        }
      }]
    }, {
      label: 'Help',
      submenu: [{
        label: 'Learn More',
        click: function() {
          require('shell').openExternal('http://electron.atom.io');
        }
      }, {
        label: 'Documentation',
        click: function() {
          require('shell').openExternal('https://github.com/atom/electron/tree/master/docs#readme');
        }
      }, {
        label: 'Community Discussions',
        click: function() {
          require('shell').openExternal('https://discuss.atom.io/c/electron');
        }
      }, {
        label: 'Search Issues',
        click: function() {
          require('shell').openExternal('https://github.com/atom/electron/issues');
        }
      }]
    }];
    menu = Menu.buildFromTemplate(template);
    mainWindow.setMenu(menu);
  }
});
<commit_msg>take shell straight of electron and updated button/links (#87)<commit_after>var electron = require('electron');
var app = electron.app;
var BrowserWindow = electron.BrowserWindow;
var Menu = electron.Menu;
var crashReporter = electron.crashReporter;
const shell = electron.shell;
var menu, template;

crashReporter.start({
  productName: 'GraphiQL',
  companyName: 'n/a',
  submitURL: 'https://github.com/skevy/graphiql-app/issues',
  autoSubmit: true
});

var mainWindow = null;

app.on('window-all-closed', function() {
  if (process.platform !== 'darwin') app.quit();
});

app.on('ready', function() {

  mainWindow = new BrowserWindow({ width: 1024, height: 728 });

  electron.session.defaultSession.webRequest.onBeforeSendHeaders((details, callback) => {
    details.requestHeaders['Origin'] = 'electron://graphiql-app';
    callback({ cancel: false, requestHeaders: details.requestHeaders });
  });

  if (process.env.HOT) {
    mainWindow.loadURL('file://' + __dirname + '/app/hot-dev-app.html');
  } else {
    mainWindow.loadURL('file://' + __dirname + '/app/app.html');
  }

  mainWindow.on('closed', function() {
    mainWindow = null;
  });

  if (process.env.NODE_ENV === 'development') {
    mainWindow.openDevTools();
  }

  if (process.platform === 'darwin') {
    template = [{
      label: 'GraphiQL',
      submenu: [{
        label: 'About GraphiQL',
        selector: 'orderFrontStandardAboutPanel:'
      }, {
        type: 'separator'
      }, {
        label: 'Services',
        submenu: []
      }, {
        type: 'separator'
      }, {
        label: 'Hide GraphiQL',
        accelerator: 'Command+H',
        selector: 'hide:'
      }, {
        label: 'Hide Others',
        accelerator: 'Command+Shift+H',
        selector: 'hideOtherApplications:'
      }, {
        label: 'Show All',
        selector: 'unhideAllApplications:'
      }, {
        type: 'separator'
      }, {
        label: 'Quit',
        accelerator: 'Command+Q',
        click: function() {
          app.quit();
        }
      }]
    }, {
      label: 'File',
      submenu: [{
        label: 'New Query',
        accelerator: 'Command+T',
        click: function() {
          mainWindow.webContents.send('handleElectronMenuOption', 'NEW_TAB');
        }
      }, {
        label: 'Close Query',
        accelerator: 'Command+W',
        click: function() {
          mainWindow.webContents.send('handleElectronMenuOption', 'CLOSE_TAB');
        }
      }]
    }, {
      label: 'Edit',
      submenu: [{
        label: 'Undo',
        accelerator: 'Command+Z',
        selector: 'undo:'
      }, {
        label: 'Redo',
        accelerator: 'Shift+Command+Z',
        selector: 'redo:'
      }, {
        type: 'separator'
      }, {
        label: 'Cut',
        accelerator: 'Command+X',
        selector: 'cut:'
      }, {
        label: 'Copy',
        accelerator: 'Command+C',
        selector: 'copy:'
      }, {
        label: 'Paste',
        accelerator: 'Command+V',
        selector: 'paste:'
      }, {
        label: 'Select All',
        accelerator: 'Command+A',
        selector: 'selectAll:'
      }]
    }, {
      label: 'View',
      submenu: [{
        label: 'Reload',
        accelerator: 'Command+R',
        click: function() {
          mainWindow.reload();
        }
      }, {
        label: 'Toggle Full Screen',
        accelerator: 'Ctrl+Command+F',
        click: function() {
          mainWindow.setFullScreen(!mainWindow.isFullScreen());
        }
      }, {
        label: 'Toggle Developer Tools',
        accelerator: 'Alt+Command+I',
        click: function() {
          mainWindow.toggleDevTools();
        }
      }, {
        role: 'resetzoom'
      }, {
        role: 'zoomin'
      }, {
        role: 'zoomout'
      }]
    }, {
      label: 'Window',
      submenu: [{
        label: 'Minimize',
        accelerator: 'Command+M',
        selector: 'performMiniaturize:'
      }, {
        type: 'separator'
      }, {
        label: 'Bring All to Front',
        selector: 'arrangeInFront:'
      }]
    }, {
      label: 'Help',
      submenu: [{
        label: 'Learn More',
        click: function() {
          shell.openExternal('http://electron.atom.io');
        }
      }, {
        label: 'Documentation',
        click: function() {
          shell.openExternal('https://github.com/atom/electron/tree/master/docs#readme');
        }
      }, {
        label: 'Community Discussions',
        click: function() {
          shell.openExternal('https://discuss.atom.io/c/electron');
        }
      }, {
        label: 'Search Issues',
        click: function() {
          shell.openExternal('https://github.com/atom/electron/issues');
        }
      }]
    }];

    menu = Menu.buildFromTemplate(template);
    Menu.setApplicationMenu(menu);
  } else {
    template = [{
      label: '&File',
      submenu: [{
        label: 'New Query',
        accelerator: 'Ctrl+N',
        click: function() {
          mainWindow.webContents.send('handleElectronMenuOption', 'NEW_TAB');
        }
      }, {
        label: 'Close Query',
        accelerator: 'Ctrl+W',
        click: function() {
          mainWindow.webContents.send('handleElectronMenuOption', 'CLOSE_TAB');
        }
      }]
    }, {
      label: '&View',
      submenu: [{
        label: '&Reload',
        accelerator: 'Ctrl+R',
        click: function() {
          mainWindow.restart();
        }
      }, {
        label: 'Toggle &Full Screen',
        accelerator: 'F11',
        click: function() {
          mainWindow.setFullScreen(!mainWindow.isFullScreen());
        }
      }, {
        label: 'Toggle &Developer Tools',
        accelerator: 'Alt+Ctrl+I',
        click: function() {
          mainWindow.toggleDevTools();
        }
      }]
    }, {
      label: 'Help',
      submenu: [{
        label: 'Learn More',
        click: function() {
          shell.openExternal('http://electron.atom.io');
        }
      }, {
        label: 'Documentation',
        click: function() {
          shell.openExternal('https://github.com/atom/electron/tree/master/docs#readme');
        }
      }, {
        label: 'Community Discussions',
        click: function() {
          shell.openExternal('https://discuss.atom.io/c/electron');
        }
      }, {
        label: 'Search Issues',
        click: function() {
          shell.openExternal('https://github.com/atom/electron/issues');
        }
      }]
    }];
    menu = Menu.buildFromTemplate(template);
    mainWindow.setMenu(menu);
  }
});
<|endoftext|>