<commit_before>    build: function () {
      var _this = this;
      var options = _this.options;
      var element = _this.element;
      var template;
      var parent;
      var viewer;
      var button;
      var toolbar;
      var navbar;
      var title;
      var rotate;

      if (_this.isBuilt) {
        return;
      }

      template = document.createElement('div');
      template.innerHTML = Viewer.TEMPLATE;

      _this.parent = parent = element.parentNode;
      _this.viewer = viewer = getByClass(template, 'viewer-container')[0];
      _this.canvas = getByClass(viewer, 'viewer-canvas')[0];
      _this.footer = getByClass(viewer, 'viewer-footer')[0];
      _this.title = title = getByClass(viewer, 'viewer-title')[0];
      _this.toolbar = toolbar = getByClass(viewer, 'viewer-toolbar')[0];
      _this.navbar = navbar = getByClass(viewer, 'viewer-navbar')[0];
      _this.button = button = getByClass(viewer, 'viewer-button')[0];
      _this.tooltipBox = getByClass(viewer, 'viewer-tooltip')[0];
      _this.player = getByClass(viewer, 'viewer-player')[0];
      _this.list = getByClass(viewer, 'viewer-list')[0];

      addClass(title, !options.title ? CLASS_HIDE : getResponsiveClass(options.title));
      addClass(toolbar, !options.toolbar ? CLASS_HIDE : getResponsiveClass(options.toolbar));
      addClass(navbar, !options.navbar ? CLASS_HIDE : getResponsiveClass(options.navbar));
      toggleClass(button, CLASS_HIDE, !options.button);

      toggleClass(toolbar.querySelectorAll('li[class*=zoom]'), CLASS_INVISIBLE, !options.zoomable);
      toggleClass(toolbar.querySelectorAll('li[class*=flip]'), CLASS_INVISIBLE, !options.scalable);

      if (!options.rotatable) {
        rotate = toolbar.querySelectorAll('li[class*=rotate]');
        addClass(rotate, CLASS_INVISIBLE);
        appendChild(toolbar, rotate);
      }

      if (options.inline) {
        addClass(button, CLASS_FULLSCREEN);
        setStyle(viewer, {
          zIndex: options.zIndexInline
        });

        if (getStyle(parent).position === 'static') {
          setStyle(parent, {
            position: 'relative'
          });
        }
      } else {
        addClass(button, CLASS_CLOSE);
        addClass(viewer, CLASS_FIXED);
        addClass(viewer, CLASS_FADE);
        addClass(viewer, CLASS_HIDE);

        setStyle(viewer, {
          zIndex: options.zIndex
        });
      }

      // Inserts the viewer after to the current element
      parent.insertBefore(viewer, element.nextSibling);

      if (options.inline) {
        _this.render();
        _this.bind();
        _this.isShown = true;
      }

      _this.isBuilt = true;

      if (isFunction(options.built)) {
        addListener(element, EVENT_BUILT, options.built, true);
      }

      dispatchEvent(element, EVENT_BUILT);
    },

    unbuild: function () {
      var _this = this;
      var options = _this.options;

      if (!_this.isBuilt) {
        return;
      }

      if (options.inline) {
        removeClass(_this.element, CLASS_HIDE);
      }

      removeChild(_this.viewer);
    },
<commit_msg>Remove useless code<commit_after>    build: function () {
      var _this = this;
      var options = _this.options;
      var element = _this.element;
      var template;
      var parent;
      var viewer;
      var button;
      var toolbar;
      var navbar;
      var title;
      var rotate;

      if (_this.isBuilt) {
        return;
      }

      template = document.createElement('div');
      template.innerHTML = Viewer.TEMPLATE;

      _this.parent = parent = element.parentNode;
      _this.viewer = viewer = getByClass(template, 'viewer-container')[0];
      _this.canvas = getByClass(viewer, 'viewer-canvas')[0];
      _this.footer = getByClass(viewer, 'viewer-footer')[0];
      _this.title = title = getByClass(viewer, 'viewer-title')[0];
      _this.toolbar = toolbar = getByClass(viewer, 'viewer-toolbar')[0];
      _this.navbar = navbar = getByClass(viewer, 'viewer-navbar')[0];
      _this.button = button = getByClass(viewer, 'viewer-button')[0];
      _this.tooltipBox = getByClass(viewer, 'viewer-tooltip')[0];
      _this.player = getByClass(viewer, 'viewer-player')[0];
      _this.list = getByClass(viewer, 'viewer-list')[0];

      addClass(title, !options.title ? CLASS_HIDE : getResponsiveClass(options.title));
      addClass(toolbar, !options.toolbar ? CLASS_HIDE : getResponsiveClass(options.toolbar));
      addClass(navbar, !options.navbar ? CLASS_HIDE : getResponsiveClass(options.navbar));
      toggleClass(button, CLASS_HIDE, !options.button);

      toggleClass(toolbar.querySelectorAll('li[class*=zoom]'), CLASS_INVISIBLE, !options.zoomable);
      toggleClass(toolbar.querySelectorAll('li[class*=flip]'), CLASS_INVISIBLE, !options.scalable);

      if (!options.rotatable) {
        rotate = toolbar.querySelectorAll('li[class*=rotate]');
        addClass(rotate, CLASS_INVISIBLE);
        appendChild(toolbar, rotate);
      }

      if (options.inline) {
        addClass(button, CLASS_FULLSCREEN);
        setStyle(viewer, {
          zIndex: options.zIndexInline
        });

        if (getStyle(parent).position === 'static') {
          setStyle(parent, {
            position: 'relative'
          });
        }
      } else {
        addClass(button, CLASS_CLOSE);
        addClass(viewer, CLASS_FIXED);
        addClass(viewer, CLASS_FADE);
        addClass(viewer, CLASS_HIDE);

        setStyle(viewer, {
          zIndex: options.zIndex
        });
      }

      // Inserts the viewer after to the current element
      parent.insertBefore(viewer, element.nextSibling);

      if (options.inline) {
        _this.render();
        _this.bind();
        _this.isShown = true;
      }

      _this.isBuilt = true;

      if (isFunction(options.built)) {
        addListener(element, EVENT_BUILT, options.built, true);
      }

      dispatchEvent(element, EVENT_BUILT);
    },

    unbuild: function () {
      var _this = this;

      if (!_this.isBuilt) {
        return;
      }

      _this.isBuilt = false;
      removeChild(_this.viewer);
    },
<|endoftext|>


<commit_before>$(function()
{
    if(typeof config != 'undefinded' && config.debugdisabled) return;
    $('body').append('

Phone
XS

Tablet
SM

Desktop
MD

Widescreen
LG

')
    displayScreenSize();
    $('#zuiDebug').fadeIn();
    $(window).resize(displayScreenSize);
    function displayScreenSize()
    {
        $('#zuiDebug .screen-size').text($(document).width() + ' x ' + $(document).height());
    }
});
<commit_msg> * removed useless code.<commit_after>$(function()
{
    $('body').append('

Phone
XS

Tablet
SM

Desktop
MD

Widescreen
LG

')
    displayScreenSize();
    $('#zuiDebug').fadeIn();
    $(window).resize(displayScreenSize);
    function displayScreenSize()
    {
        $('#zuiDebug .screen-size').text($(document).width() + ' x ' + $(document).height());
    }
});
<|endoftext|>


<commit_before>module.exports = {
  icons: {
    day: {
      '1000': 'wi-day-sunny',
      '1003': 'wi-day-cloudy',
      '1006': 'wi-cloudy',
      '1009': 'wi-cloud',
      '1030': '',
      '1063': 'wi-day-sleet-storm',
      '1066': '',
      '1069': '',
      '1072': '',
      '1087': 'wi-day-thunderstorm',
      '1114': '',
      '1117': '',
      '1135': 'wi-day-fog',
      '1147': '',
      '1150': '',
      '1153': '',
      '1168': '',
      '1171': '',
      '1180': '',
      '1183': '',
      '1186': '',
      '1189': 'wi-day-hail',
      '1192': '',
      '1195': 'wi-day-rain',
      '1198': '',
      '1201': '',
      '1204': '',
      '1207': '',
      '1210': '',
      '1213': '',
      '1216': '',
      '1219': '',
      '1222': '',
      '1225': 'wi-day-snow-wind',
      '1237': '',
      '1240': 'wi-day-showers',
      '1243': '',
      '1246': '',
      '1249': '',
      '1252': '',
      '1255': '',
      '1258': '',
      '1261': '',
      '1264': '',
      '1273': '',
      '1276': '',
      '1279': '',
      '1282': ''
    },
    night: {
      '1000': 'wi-night-clear',
      '1003': 'wi-night-alt-cloudy',
      '1006': 'wi-cloudy',
      '1009': 'wi-cloud',
      '1030': '',
      '1063': 'wi-night-alt-sleet-storm',
      '1066': '',
      '1069': '',
      '1072': '',
      '1087': 'wi-night-alt-thunderstorm',
      '1114': '',
      '1117': '',
      '1135': 'wi-night-fog',
      '1147': '',
      '1150': '',
      '1153': '',
      '1168': '',
      '1171': '',
      '1180': '',
      '1183': '',
      '1186': '',
      '1189': 'wi-night-alt-hail',
      '1192': '',
      '1195': 'wi-night-alt-rain-wind',
      '1198': '',
      '1201': '',
      '1204': '',
      '1207': '',
      '1210': '',
      '1213': '',
      '1216': '',
      '1219': '',
      '1222': '',
      '1225': 'wi-night-alt-snow',
      '1237': '',
      '1240': 'wi-night-alt-showers',
      '1243': '',
      '1246': '',
      '1249': '',
      '1252': '',
      '1255': '',
      '1258': '',
      '1261': '',
      '1264': '',
      '1273': '',
      '1276': '',
      '1279': '',
      '1282': ''
    }
  }
};

// code	day	night	icon
// 1000	Sunny	Clear	113
// 1003	Partly cloudy	Partly cloudy	116
// 1006	Cloudy	Cloudy	119
// 1009	Overcast	Overcast	122
// 1030	Mist	Mist	143
// 1063	Patchy rain possible	Patchy rain possible	176
// 1066	Patchy snow possible	Patchy snow possible	179
// 1069	Patchy sleet possible	Patchy sleet possible	182
// 1072	Patchy freezing drizzle possible	Patchy freezing drizzle possible	185
// 1087	Thundery outbreaks possible	Thundery outbreaks possible	200
// 1114	Blowing snow	Blowing snow	227
// 1117	Blizzard	Blizzard	230
// 1135	Fog	Fog	248
// 1147	Freezing fog	Freezing fog	260
// 1150	Patchy light drizzle	Patchy light drizzle	263
// 1153	Light drizzle	Light drizzle	266
// 1168	Freezing drizzle	Freezing drizzle	281
// 1171	Heavy freezing drizzle	Heavy freezing drizzle	284
// 1180	Patchy light rain	Patchy light rain	293
// 1183	Light rain	Light rain	296
// 1186	Moderate rain at times	Moderate rain at times	299
// 1189	Moderate rain	Moderate rain	302
// 1192	Heavy rain at times	Heavy rain at times	305
// 1195	Heavy rain	Heavy rain	308
// 1198	Light freezing rain	Light freezing rain	311
// 1201	Moderate or heavy freezing rain	Moderate or heavy freezing rain	314
// 1204	Light sleet	Light sleet	317
// 1207	Moderate or heavy sleet	Moderate or heavy sleet	320
// 1210	Patchy light snow	Patchy light snow	323
// 1213	Light snow	Light snow	326
// 1216	Patchy moderate snow	Patchy moderate snow	329
// 1219	Moderate snow	Moderate snow	332
// 1222	Patchy heavy snow	Patchy heavy snow	335
// 1225	Heavy snow	Heavy snow	338
// 1237	Ice pellets	Ice pellets	350
// 1240	Light rain shower	Light rain shower	353
// 1243	Moderate or heavy rain shower	Moderate or heavy rain shower	356
// 1246	Torrential rain shower	Torrential rain shower	359
// 1249	Light sleet showers	Light sleet showers	362
// 1252	Moderate or heavy sleet showers	Moderate or heavy sleet showers	365
// 1255	Light snow showers	Light snow showers	368
// 1258	Moderate or heavy snow showers	Moderate or heavy snow showers	371
// 1261	Light showers of ice pellets	Light showers of ice pellets	374
// 1264	Moderate or heavy showers of ice pellets	Moderate or heavy showers of ice pellets	377
// 1273	Patchy light rain with thunder	Patchy light rain with thunder	386
// 1276	Moderate or heavy rain with thunder	Moderate or heavy rain with thunder	389
// 1279	Patchy light snow with thunder	Patchy light snow with thunder	392
// 1282	Moderate or heavy snow with thunder	Moderate or heavy snow with thunder	395<commit_msg>Fix codeclimate, quit comments<commit_after>module.exports = {
  icons: {
    day: {
      '1000': 'wi-day-sunny',
      '1003': 'wi-day-cloudy',
      '1006': 'wi-cloudy',
      '1009': 'wi-cloud',
      '1030': '',
      '1063': 'wi-day-sleet-storm',
      '1066': '',
      '1069': '',
      '1072': '',
      '1087': 'wi-day-thunderstorm',
      '1114': '',
      '1117': '',
      '1135': 'wi-day-fog',
      '1147': '',
      '1150': '',
      '1153': '',
      '1168': '',
      '1171': '',
      '1180': '',
      '1183': '',
      '1186': '',
      '1189': 'wi-day-hail',
      '1192': '',
      '1195': 'wi-day-rain',
      '1198': '',
      '1201': '',
      '1204': '',
      '1207': '',
      '1210': '',
      '1213': '',
      '1216': '',
      '1219': '',
      '1222': '',
      '1225': 'wi-day-snow-wind',
      '1237': '',
      '1240': 'wi-day-showers',
      '1243': '',
      '1246': '',
      '1249': '',
      '1252': '',
      '1255': '',
      '1258': '',
      '1261': '',
      '1264': '',
      '1273': '',
      '1276': '',
      '1279': '',
      '1282': ''
    },
    night: {
      '1000': 'wi-night-clear',
      '1003': 'wi-night-alt-cloudy',
      '1006': 'wi-cloudy',
      '1009': 'wi-cloud',
      '1030': '',
      '1063': 'wi-night-alt-sleet-storm',
      '1066': '',
      '1069': '',
      '1072': '',
      '1087': 'wi-night-alt-thunderstorm',
      '1114': '',
      '1117': '',
      '1135': 'wi-night-fog',
      '1147': '',
      '1150': '',
      '1153': '',
      '1168': '',
      '1171': '',
      '1180': '',
      '1183': '',
      '1186': '',
      '1189': 'wi-night-alt-hail',
      '1192': '',
      '1195': 'wi-night-alt-rain-wind',
      '1198': '',
      '1201': '',
      '1204': '',
      '1207': '',
      '1210': '',
      '1213': '',
      '1216': '',
      '1219': '',
      '1222': '',
      '1225': 'wi-night-alt-snow',
      '1237': '',
      '1240': 'wi-night-alt-showers',
      '1243': '',
      '1246': '',
      '1249': '',
      '1252': '',
      '1255': '',
      '1258': '',
      '1261': '',
      '1264': '',
      '1273': '',
      '1276': '',
      '1279': '',
      '1282': ''
    }
  }
};
<|endoftext|>


<commit_before>/*!
 * Harrix HTML Template (https://github.com/Harrix/Harrix-HTML-Template)
 * Copyright 2018 Sergienko Anton
 * Licensed under MIT (https://github.com/Harrix/Harrix-HTML-Template/blob/master/LICENSE)
 */

import fontawesome from '@fortawesome/fontawesome'
import fontawesomeFreeSolid from '@fortawesome/fontawesome-free-solid'
import fontawesomeFreeRegular from '@fortawesome/fontawesome-free-regular'
import fontawesomeFreeBrands from '@fortawesome/fontawesome-free-brands'

import faCustomIcons from './_fah.js'

document.addEventListener('DOMContentLoaded', () => {
    initNavbar(50, 300);
    initSearchPanel();
});

function initNavbar(scrollTopLogoShrink, scrollTopNavbarHide) {
    const root = document.documentElement;
    const navbar = document.getElementById('h-navbar');
    const navbarBurger = document.getElementById('h-burger');
    const navbarBottom = document.getElementById('h-navbar-bottom');
    const logo = document.getElementById('h-logo');
    let lastY = 0;
    let currentY = 0;

    let hasClassHide = logo.classList.contains('h-is-hidden');

    navbarBottom.onmouseover = function(event) {
        navbar.classList.remove('h-is-hidden');
        hasClassHide = false;
    };

    navbarBurger.addEventListener('click', () => {
        root.classList.toggle('h-is-clipped-touch');
        const target = document.getElementById(navbarBurger.dataset.target);
        navbarBurger.classList.toggle('is-active');
        target.classList.toggle('is-active');
    });

    window.addEventListener('scroll', function() {
        lastY = currentY;
        currentY = window.scrollY;

        if ((currentY > scrollTopNavbarHide) && (currentY > lastY) && (!hasClassHide)) {
            navbar.classList.add('h-is-hidden');
            hasClassHide = true;
        }

        if ((currentY < lastY) && (hasClassHide)) {
            navbar.classList.remove('h-is-hidden');
            hasClassHide = false;
        }
    });
}

function initSearchPanel() {
    const navbarMenu = document.getElementById('h-navbar-menu');
    const navbarMenuEnd = document.getElementById('h-navbar-menu-end');
    const buttonSearchOpen = document.getElementById('h-button-search-panel-open');
    const buttonSearchClose = document.getElementById('h-button-search-panel-close');
    const hdivsearch = document.getElementById('h-div-search');
    const hinputsearch = document.getElementById('h-input-search');
    const hsearchpanel = document.getElementById('h-search-panel');
    buttonSearchOpen.addEventListener('click', () => {
        hsearchpanel.classList.toggle("h-is-hidden");
        hinputsearch.focus();

        navbarMenuEnd.classList.toggle('hideItems');
    });
    buttonSearchClose.addEventListener('click', () => {
        hsearchpanel.classList.toggle("h-is-hidden");
        hinputsearch.blur();

        navbarMenuEnd.classList.toggle('hideItems');
    });
}<commit_msg>Modify initNavbar()<commit_after>/*!
 * Harrix HTML Template (https://github.com/Harrix/Harrix-HTML-Template)
 * Copyright 2018 Sergienko Anton
 * Licensed under MIT (https://github.com/Harrix/Harrix-HTML-Template/blob/master/LICENSE)
 */

import fontawesome from '@fortawesome/fontawesome'
import fontawesomeFreeSolid from '@fortawesome/fontawesome-free-solid'
import fontawesomeFreeRegular from '@fortawesome/fontawesome-free-regular'
import fontawesomeFreeBrands from '@fortawesome/fontawesome-free-brands'

import faCustomIcons from './_fah.js'

document.addEventListener('DOMContentLoaded', () => {
    initNavbar(100);
    initSearchPanel();
});

function initNavbar(scrollTopNavbarHide) {
    const root = document.documentElement;
    const navbar = document.getElementById('h-navbar');
    const navbarBurger = document.getElementById('h-burger');
    const navbarBottom = document.getElementById('h-navbar-bottom');
    const logo = document.getElementById('h-logo');
    let lastY = 0;
    let currentY = 0;

    let hasClassHide = logo.classList.contains('h-is-hidden');

    navbarBottom.onmouseover = function(event) {
        navbar.classList.remove('h-is-hidden');
        hasClassHide = false;
    };

    navbarBurger.addEventListener('click', () => {
        root.classList.toggle('h-is-clipped-touch');
        const target = document.getElementById(navbarBurger.dataset.target);
        navbarBurger.classList.toggle('is-active');
        target.classList.toggle('is-active');
    });

    window.addEventListener('scroll', function() {
        lastY = currentY;
        currentY = window.scrollY;

        if ((currentY > scrollTopNavbarHide) && (currentY > lastY) && (!hasClassHide)) {
            navbar.classList.add('h-is-hidden');
            hasClassHide = true;
        }

        if ((currentY < lastY) && (hasClassHide)) {
            navbar.classList.remove('h-is-hidden');
            hasClassHide = false;
        }
    });
}

function initSearchPanel() {
    const navbarMenu = document.getElementById('h-navbar-menu');
    const navbarMenuEnd = document.getElementById('h-navbar-menu-end');
    const buttonSearchOpen = document.getElementById('h-button-search-panel-open');
    const buttonSearchClose = document.getElementById('h-button-search-panel-close');
    const hdivsearch = document.getElementById('h-div-search');
    const hinputsearch = document.getElementById('h-input-search');
    const hsearchpanel = document.getElementById('h-search-panel');
    buttonSearchOpen.addEventListener('click', () => {
        hsearchpanel.classList.toggle("h-is-hidden");
        hinputsearch.focus();

        navbarMenuEnd.classList.toggle('hideItems');
    });
    buttonSearchClose.addEventListener('click', () => {
        hsearchpanel.classList.toggle("h-is-hidden");
        hinputsearch.blur();

        navbarMenuEnd.classList.toggle('hideItems');
    });
}<|endoftext|>


<commit_before>import Component from 'ben-component';
import DataCanvas from 'ben-canvas';
import lineCursor from '../img/pen@1x.ico';
import rectCursor from '../img/rect.ico';
import DrawCanvas from './draw-canvas';

const LINE = 'line';
const RECT = 'rect';
const TEXT = 'text';
const EASE = 'ease';
const ELLIPSE = 'ellipse';
const ARROW = 'arrow';
const SLINE = 'sline';
const tools = [LINE, RECT, TEXT, EASE, ELLIPSE, ARROW, SLINE];
const EASE_WIDTH = 20;
const TEXT_SIZE = 14;
const TEXT_HEIGHT = 18;

const COLOR_RED = '#f00';
const COLOR_DEFAULT = COLOR_RED;

class Sketch extends Component {
  constructor(options) {
    options.textSize || (options.textSize = TEXT_SIZE);
    options.textLineHeight || (options.textLineHeight = TEXT_HEIGHT);
    options.width || (options.width = options.container.clientWidth);
    options.height || (options.height = options.container.clientHeight);
    options.toolType || (options.toolType = '');
    super(null, options);
    this.ctx = this.canvas.getContext('2d');
    this.initDrawCanvas();
    this.addChild(this.drawCanvas);
    this.container = this.options.container;
    this.container.appendChild(this.el);
    this.color = COLOR_DEFAULT;
    this.defaultPage = 0;
    this.pageNum = this.defaultPage;
    this.cache = {
      0: [],
    };
    this.textMeasure();
    this.text = false;

    this.on('toolchange', () => {
      tools.map(toolClass => {
        this.hasClass(toolClass) ? this.removeClass(toolClass) : null;
      });
      this.addClass(this.toolType);
    });

    this.on('contextmenu', (e) => {
      e.stopPropagation();
      e.preventDefault();
    })
  }

  createEl() {
    const el = super.createEl('div', {
      style: `display: block; width: 100%; height: 100%;`
    }, {
      className: `ben-sketch ${this.options.toolType}`
    });
    this.canvas = this.createCanvas();
    el.appendChild(this.canvas);
    return el;
  }

  createCanvas() {
    console.log(this.options);
    const canvas = super.createEl('canvas', {
      width: this.options.width,
      height: this.options.height,
      style: 'display: block;'
    }, {
      className: 'ben-sketch_canvas'
    });
    return canvas;
  }

  initDrawCanvas() {
    this.drawCanvas = new DrawCanvas(this, this.options);

    this.on('colorchange', () => {
      this.drawCanvas.color = this.color;
    });

    this.on('toolchange', () => {
      this.drawCanvas.tool = this.toolType;
    });

    tools.map(type => {
      this.drawCanvas.on(`${type}.submit`, (event, data) => {
        DataCanvas[type](this.ctx, data);
        this.cache[this.pageNum].push({
          type,
          options: data,
        });
        this.trigger(type, data);
      });
    });
  }

  textMeasure() {
    const measureEl = this.measureEl = super.createEl('pre', {
      'class': 'sketch-temp text-pre',
      style: `font-size: ${ this.options.textSize }px; line-height: ${ this.options.textLineHeight }px;`
    });
    this.el.appendChild(measureEl);
  }

  width(width) {
    if (typeof width !== 'undefined') {
      this.options.width = width;
      return width;
    }
    return this.options.width;
  }

  height(height) {
    if (typeof height !== 'undefined') {
      this.options.height = height;
      return height;
    }
    return this.options.height;
  }

  setTool(toolName) {
    if (toolName == this.toolType) {
      return;
    }
    this.toolType = toolName;
    this.trigger('toolchange');
  }

  setColor(color) {
    if (!color) {
      throw new Error('Sketch:setTool(toolColor): toolColor argument is needed!');
    }
    this.color = color;
    this.trigger('colorchange');
  }

  draw(type, options) {
    let pageNum = this.pageNum;
    if (!isNaN(options.page)) {
      pageNum = options.page;
    }
    if (!this[type]) {
      if (pageNum === this.pageNum) {
        DataCanvas[type](this.ctx, options);
      }
      if (!this.cache[pageNum]) {
        this.cache[pageNum] = [];
      }
      this.cache[pageNum].push({
        type,
        options
      });
    } else {
      this[type](options);
    }
  }

  clear(pageNum) {
    if (isNaN(pageNum)) {
      DataCanvas.clear(this.ctx);
    }
    pageNum = isNaN(pageNum) ? this.pageNum : pageNum;
    console.log(pageNum);
    this.cache[pageNum] = [];
  }

  changePage(pageNum) {
    if (isNaN(pageNum) || pageNum === this.pageNum) {
      return;
    }
    this.pageNum = pageNum;
    if (!this.cache[pageNum]) {
      this.cache[pageNum] = [];
    }
    this.repaint(pageNum);
  }

  repaint(pageNum) {
    DataCanvas.clear(this.ctx);
    console.log(this.cache);
    pageNum = isNaN(pageNum) ? this.pageNum : pageNum;
    this.cache[pageNum].map((item) => {
      DataCanvas[item.type](this.ctx, item.options);
    });
  }

  undo(options = { page: this.pageNum }) {
    const page = options.page;
    const pageNum = isNaN(page) ? this.pageNum : page;
    if (!this.cache[pageNum]) {
      this.cache[pageNum] = [];
    }
    this.cache[pageNum].pop();
    if (pageNum === this.pageNum) {
      this.repaint(pageNum);
    }
  }

  resize() {
    this.canvas.width = this.width(this.el.clientWidth);
    this.canvas.height = this.height(this.el.clientHeight);
    console.log(this.options === this.drawCanvas.options);
    this.drawCanvas.resize();
    this.repaint(this.pageNum);
  }
}

module.exports = Sketch;

<commit_msg>优化clear方法；增加empty方法，重置画板，清空cache<commit_after>import Component from 'ben-component';
import DataCanvas from 'ben-canvas';
import lineCursor from '../img/pen@1x.ico';
import rectCursor from '../img/rect.ico';
import DrawCanvas from './draw-canvas';

const LINE = 'line';
const RECT = 'rect';
const TEXT = 'text';
const EASE = 'ease';
const ELLIPSE = 'ellipse';
const ARROW = 'arrow';
const SLINE = 'sline';
const tools = [LINE, RECT, TEXT, EASE, ELLIPSE, ARROW, SLINE];
const EASE_WIDTH = 20;
const TEXT_SIZE = 14;
const TEXT_HEIGHT = 18;

const COLOR_RED = '#f00';
const COLOR_DEFAULT = COLOR_RED;

class Sketch extends Component {
  constructor(options) {
    options.textSize || (options.textSize = TEXT_SIZE);
    options.textLineHeight || (options.textLineHeight = TEXT_HEIGHT);
    options.width || (options.width = options.container.clientWidth);
    options.height || (options.height = options.container.clientHeight);
    options.toolType || (options.toolType = '');
    super(null, options);
    this.ctx = this.canvas.getContext('2d');
    this.initDrawCanvas();
    this.addChild(this.drawCanvas);
    this.container = this.options.container;
    this.container.appendChild(this.el);
    this.color = COLOR_DEFAULT;
    this.defaultPage = 0;
    this.pageNum = this.defaultPage;
    this.cache = {
      0: [],
    };
    this.textMeasure();
    this.text = false;

    this.on('toolchange', () => {
      tools.map(toolClass => {
        this.hasClass(toolClass) ? this.removeClass(toolClass) : null;
      });
      this.addClass(this.toolType);
    });

    this.on('contextmenu', (e) => {
      e.stopPropagation();
      e.preventDefault();
    })
  }

  createEl() {
    const el = super.createEl('div', {
      style: `display: block; width: 100%; height: 100%;`
    }, {
      className: `ben-sketch ${this.options.toolType}`
    });
    this.canvas = this.createCanvas();
    el.appendChild(this.canvas);
    return el;
  }

  createCanvas() {
    console.log(this.options);
    const canvas = super.createEl('canvas', {
      width: this.options.width,
      height: this.options.height,
      style: 'display: block;'
    }, {
      className: 'ben-sketch_canvas'
    });
    return canvas;
  }

  initDrawCanvas() {
    this.drawCanvas = new DrawCanvas(this, this.options);

    this.on('colorchange', () => {
      this.drawCanvas.color = this.color;
    });

    this.on('toolchange', () => {
      this.drawCanvas.tool = this.toolType;
    });

    tools.map(type => {
      this.drawCanvas.on(`${type}.submit`, (event, data) => {
        DataCanvas[type](this.ctx, data);
        this.cache[this.pageNum].push({
          type,
          options: data,
        });
        this.trigger(type, data);
      });
    });
  }

  textMeasure() {
    const measureEl = this.measureEl = super.createEl('pre', {
      'class': 'sketch-temp text-pre',
      style: `font-size: ${ this.options.textSize }px; line-height: ${ this.options.textLineHeight }px;`
    });
    this.el.appendChild(measureEl);
  }

  width(width) {
    if (typeof width !== 'undefined') {
      this.options.width = width;
      return width;
    }
    return this.options.width;
  }

  height(height) {
    if (typeof height !== 'undefined') {
      this.options.height = height;
      return height;
    }
    return this.options.height;
  }

  setTool(toolName) {
    if (toolName == this.toolType) {
      return;
    }
    this.toolType = toolName;
    this.trigger('toolchange');
  }

  setColor(color) {
    if (!color) {
      throw new Error('Sketch:setTool(toolColor): toolColor argument is needed!');
    }
    this.color = color;
    this.trigger('colorchange');
  }

  draw(type, options) {
    let pageNum = this.pageNum;
    if (!isNaN(options.page)) {
      pageNum = options.page;
    }
    if (!this[type]) {
      if (pageNum === this.pageNum) {
        DataCanvas[type](this.ctx, options);
      }
      if (!this.cache[pageNum]) {
        this.cache[pageNum] = [];
      }
      this.cache[pageNum].push({
        type,
        options
      });
    } else {
      this[type](options);
    }
  }

  empty() {
    if (isNaN(pageNum)) {
      DataCanvas.clear(this.ctx);
    }
    this.cache = {
      0: [],
    };
  }

  clear(options = { page: this.pageNum }) {
    const page = options.page;
    if (isNaN(page)) {
      DataCanvas.clear(this.ctx);
    }
    const pageNum = isNaN(page) ? this.pageNum : page;
    console.log(pageNum);
    this.cache[pageNum] = [];
  }

  changePage(pageNum) {
    if (isNaN(pageNum) || pageNum === this.pageNum) {
      return;
    }
    this.pageNum = pageNum;
    if (!this.cache[pageNum]) {
      this.cache[pageNum] = [];
    }
    this.repaint(pageNum);
  }

  repaint(pageNum) {
    DataCanvas.clear(this.ctx);
    console.log(this.cache);
    pageNum = isNaN(pageNum) ? this.pageNum : pageNum;
    this.cache[pageNum].map((item) => {
      DataCanvas[item.type](this.ctx, item.options);
    });
  }

  undo(options = { page: this.pageNum }) {
    const page = options.page;
    const pageNum = isNaN(page) ? this.pageNum : page;
    if (!this.cache[pageNum]) {
      this.cache[pageNum] = [];
    }
    this.cache[pageNum].pop();
    if (pageNum === this.pageNum) {
      this.repaint(pageNum);
    }
  }

  resize() {
    this.canvas.width = this.width(this.el.clientWidth);
    this.canvas.height = this.height(this.el.clientHeight);
    console.log(this.options === this.drawCanvas.options);
    this.drawCanvas.resize();
    this.repaint(this.pageNum);
  }
}

module.exports = Sketch;

<|endoftext|>


<commit_before>var $ = function (query) {
  var res = document.querySelectorAll(query);

  if (res.length === 1) {
    return res[0];
  }

  return res;
};

// Full list of orgs
var orgs;
var quizForm = $('.quiz-form');
var quizResults = $('.results');
var main = $('.main');
var nav = $('nav');

var httpGet = function(url, callback){
  var xmlHttp = new XMLHttpRequest();
  xmlHttp.onreadystatechange = function() {
  if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
    callback(xmlHttp.responseText);
  }
  xmlHttp.open("GET", url, true); // true for asynchronous
  xmlHttp.send(null);
};

var setDetails = function(org) {
  $('.selection-title').textContent = org.name;
  $('.grade').textContent = org.overall;
  $('.percent').textContent = org.program_percentage + '%';
  $('.selection-link').setAttribute('target', '_blank');
  $('.selection-link').setAttribute('href', org.url);
};

var setContent = function(orgs) {
  setDetails(orgs[0]);
  var ul = $('.results-list');
  orgs.forEach(function(org, i) {
    var li = document.createElement('li');
    li.classList.add('results-item');
    var button = document.createElement('button');
    button.classList.add('results-item-button');
    button.textContent = org.name;

    button.addEventListener('click', function() {
      setDetails(org);
    })
    button.addEventListener('focus', function() {
      setDetails(org);
    })

    li.appendChild(button);
    ul.appendChild(li);
  })
};

var progressView = function() {
  // make the quiz display none
  quizForm.classList.add('hidden');

  // make the results page display
  quizResults.classList.remove('hidden');

  // make the main section take up the whole page
  main.classList.add('full-grid');

  // make the nav appear
  nav.classList.remove('hidden');
};

var filterOrgs = function(pred) {
  return orgs.filter(function(org) {
    // If the values in the predicate ARE NOT in org, remove it
    var isLocal = function(add) {
      return add.toLowerCase().indexOf('houston') >= 0;
    };

    var found = false;
    for (var type in pred['types']) {
      if (org['types'].indexOf(type) < 0) {
        found = true;
      }
    }

    if (found == false) { return false; }

    if (pred['tags'].indexOf(org['tags'][0]) < 0) {
      return false;
    }

    if (pred['local']) {
      return isLocal(org.address);
    }

    return true;
  });
};

// Handles form submission
var submitHandler = function(e) {
  e.preventDefault();

  var showRelevantOrgs = function() {
    var getQuizParams = function() {
      // Thanks for the code
      // https://stackoverflow.com/questions/8563240/how-to-get-all-checked-checkboxes
      var getCheckedBoxes = function(cbs) {
        var checkboxesChecked = [];
        // loop over them all
        for (var i=0; i<cbs.length; i++) {
           // And stick the checked ones onto an array...
           if (cbs[i].checked) {
              checkboxesChecked.push(cbs[i]);
           }
        }
        // Return the array if it is non-empty, or null
        return checkboxesChecked.length > 0 ? checkboxesChecked : null;
      };

      var q1cbs = $('.q1 input');
      var q2cbs = $('.q2 input');

      var q1Params = getCheckedBoxes(q1cbs);
      var q2Params = getCheckedBoxes(q2cbs);

      if (q1Params == null && q2Params == null) {
        return {
          'types': ['Money', 'Goods', 'Time'],
          'tags': ['General Relief', 'Shelter', 'Medical', 'Animals', 'Food', 'Disabilities', 'Seniors', 'Kids'],
          'local': false
        }
      }

      var types = [];
      var tags = [];

      for (var i=0; i<q1Params.length; i++) { tags.push(q1Params[i].value); }
      for (var i=0; i<q2Params.length; i++) { types.push(q2Params[i].value); }

      return {
        'types': types,
        'tags': tags,
        'local': false
      };
    };

    // TODO Populate pred
    var pred = getQuizParams();

    var out = filterOrgs(pred);

    return out;
  };

  var relevantOrgs = showRelevantOrgs();
  setContent(relevantOrgs);
  progressView();
};

quizForm.addEventListener('submit', submitHandler);
$('.browse').addEventListener('click', function() {
  // progressView();
  // Tacky, I know
  submitHandler(new Event('click'));
});

nav.addEventListener('click', function(e) {
  var updateView = function(state) {
    var $wrapper = $('.results-list');
    while ($wrapper.firstChild) {
      $wrapper.removeChild($wrapper.firstChild);
    }
    setContent(state);
  };

	if (e.target && e.target.nodeName == 'BUTTON') {
    var dset = e.target.dataset;
    if (dset && dset.pred.localeCompare('Money Goods Time') === 0) {
      updateView(orgs);
    }

    else {
      var types = dset.pred;
      var pred = {
        'types': types
      };

      var filtered = orgs.filter(function(org) {
        return org.types.indexOf(pred.types) > -1;
      });

      updateView(filtered);
    }
	}
});

(function() {
  var apiCallback = function(data) {
    var parsed = JSON.parse(data);
    orgs = parsed.res;
  };

  httpGet('https://harvey-api.mybluemix.net/api/0.1/hh', function(d) { apiCallback(d); });
})();
<commit_msg>skipping hides results nav-item<commit_after>var $ = function (query) {
  var res = document.querySelectorAll(query);

  if (res.length === 1) {
    return res[0];
  }

  return res;
};

// Full list of orgs
var orgs;
var quizForm = $('.quiz-form');
var quizResults = $('.results');
var main = $('.main');
var nav = $('nav');

var httpGet = function(url, callback){
  var xmlHttp = new XMLHttpRequest();
  xmlHttp.onreadystatechange = function() {
  if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
    callback(xmlHttp.responseText);
  }
  xmlHttp.open("GET", url, true); // true for asynchronous
  xmlHttp.send(null);
};

var setDetails = function(org) {
  $('.selection-title').textContent = org.name;
  $('.grade').textContent = org.overall;
  $('.percent').textContent = org.program_percentage + '%';
  $('.selection-link').setAttribute('target', '_blank');
  $('.selection-link').setAttribute('href', org.url);
};

var setContent = function(orgs) {
  setDetails(orgs[0]);
  var ul = $('.results-list');
  orgs.forEach(function(org, i) {
    var li = document.createElement('li');
    li.classList.add('results-item');
    var button = document.createElement('button');
    button.classList.add('results-item-button');
    button.textContent = org.name;

    button.addEventListener('click', function() {
      setDetails(org);
    })
    button.addEventListener('focus', function() {
      setDetails(org);
    })

    li.appendChild(button);
    ul.appendChild(li);
  })
};

var progressView = function() {
  // make the quiz display none
  quizForm.classList.add('hidden');

  // make the results page display
  quizResults.classList.remove('hidden');

  // make the main section take up the whole page
  main.classList.add('full-grid');

  // make the nav appear
  nav.classList.remove('hidden');
};

var filterOrgs = function(pred) {
  return orgs.filter(function(org) {
    // If the values in the predicate ARE NOT in org, remove it
    var isLocal = function(add) {
      return add.toLowerCase().indexOf('houston') >= 0;
    };

    var found = false;
    for (var type in pred['types']) {
      if (org['types'].indexOf(type) < 0) {
        found = true;
      }
    }

    if (found == false) { return false; }

    if (pred['tags'].indexOf(org['tags'][0]) < 0) {
      return false;
    }

    if (pred['local']) {
      return isLocal(org.address);
    }

    return true;
  });
};

// Handles form submission
var submitHandler = function(e) {
  e.preventDefault();

  var showRelevantOrgs = function() {
    var getQuizParams = function() {
      // Thanks for the code
      // https://stackoverflow.com/questions/8563240/how-to-get-all-checked-checkboxes
      var getCheckedBoxes = function(cbs) {
        var checkboxesChecked = [];
        // loop over them all
        for (var i=0; i<cbs.length; i++) {
           // And stick the checked ones onto an array...
           if (cbs[i].checked) {
              checkboxesChecked.push(cbs[i]);
           }
        }
        // Return the array if it is non-empty, or null
        return checkboxesChecked.length > 0 ? checkboxesChecked : null;
      };

      var q1cbs = $('.q1 input');
      var q2cbs = $('.q2 input');

      var q1Params = getCheckedBoxes(q1cbs);
      var q2Params = getCheckedBoxes(q2cbs);

      if (q1Params == null && q2Params == null) {
        return {
          'types': ['Money', 'Goods', 'Time'],
          'tags': ['General Relief', 'Shelter', 'Medical', 'Animals', 'Food', 'Disabilities', 'Seniors', 'Kids'],
          'local': false
        }
      }

      var types = [];
      var tags = [];

      for (var i=0; i<q1Params.length; i++) { tags.push(q1Params[i].value); }
      for (var i=0; i<q2Params.length; i++) { types.push(q2Params[i].value); }

      return {
        'types': types,
        'tags': tags,
        'local': false
      };
    };

    // TODO Populate pred
    var pred = getQuizParams();

    var out = filterOrgs(pred);

    return out;
  };

  var relevantOrgs = showRelevantOrgs();
  setContent(relevantOrgs);
  progressView();
};

quizForm.addEventListener('submit', submitHandler);
$('.browse').addEventListener('click', function() {
  // progressView();
  // Tacky, I know
  $('#results').parentNode.classList.add('hidden');
  submitHandler(new Event('click'));
});

nav.addEventListener('click', function(e) {
  var updateView = function(state) {
    var $wrapper = $('.results-list');
    while ($wrapper.firstChild) {
      $wrapper.removeChild($wrapper.firstChild);
    }
    setContent(state);
  };

	if (e.target && e.target.nodeName == 'BUTTON') {
    var dset = e.target.dataset;
    if (dset && dset.pred.localeCompare('Money Goods Time') === 0) {
      updateView(orgs);
    }

    else {
      var types = dset.pred;
      var pred = {
        'types': types
      };

      var filtered = orgs.filter(function(org) {
        return org.types.indexOf(pred.types) > -1;
      });

      updateView(filtered);
    }
	}
});

(function() {
  var apiCallback = function(data) {
    var parsed = JSON.parse(data);
    orgs = parsed.res;
  };

  httpGet('https://harvey-api.mybluemix.net/api/0.1/hh', function(d) { apiCallback(d); });
})();
<|endoftext|>


<commit_before>import THREE from 'three.js';
import FlyControlsTouch from './touch';
import pointerLock from './pointer-lock';
import Ship from './ship';
import Bullet from './bullet';
import Drone from './drone';
import Radar from './radar';
import { TargetingComputer } from './reticle';
import Skybox from'./skybox';
import Trail, { ScreenSpaceTrail } from './trail';
import Debris from './debris';
import Explosion from './explosion';
import createClient from './client';
import update from './update';
import config from './config';
import createMap from './map';

const container = document.createElement( 'div' );
document.body.appendChild( container );

const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
container.appendChild( renderer.domElement );

const scene = new THREE.Scene();
createMap( scene, 'minimal' );

const client = new THREE.Group();
scene.add( client );

const server = new THREE.Group();
scene.add( server );

createClient( client, server );

const camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 0.1 );
scene.add( camera );

const ship = new Ship();
client.add( ship );

const radar = new Radar( ship );
client.add( radar );

const trail = new Trail();
trail.offset.set( 0, 0, 0.3 );
client.add( trail );

const drone = new Drone();
client.add( drone );

const targetingComputer = new TargetingComputer( ship, drone );
scene.add( targetingComputer );

const debris = new Debris();
scene.add( debris );

const explosion = new Explosion();
explosion.position.set( 0, -1, -4 );
scene.add( explosion );

setInterval( () => explosion.reset(), 1000 );

const skybox = new Skybox( camera );
createMap( skybox.scene, 'minimalSkybox' );

const keys = [];
const controls = new FlyControlsTouch( ship, renderer.domElement );
controls.speed = config.ship.speed;
pointerLock( controls );

const clock = new THREE.Clock();
let running = true;

const dt = 1 / 60;
let accumulatedTime = 0;

const updateCamera = ( target => {
  const stiffness = 6;
  const offset = new THREE.Vector3( 0, 0.3, 1 );
  const vector = new THREE.Vector3();

  return dt => {
    // Ideal camera position.
    vector.copy( offset )
      .applyQuaternion( target.quaternion )
      .add( target.position );

    camera.position.lerp( vector, stiffness * dt );
    camera.quaternion.slerp( target.quaternion, stiffness * dt );
  };
})( ship );

const canFire = (() => {
  const period = 1 / config.ship.fireRate;
  let previous = 0;

  return time => {
    if ( time - previous < period ) {
      return false;
    }

    previous = time;
    return true;
  };
})();

function fire() {
  const bullet = new Bullet();
  bullet.position.copy( ship.position );
  bullet.start = bullet.position.clone();

  // Fire in ship direction.
  bullet.velocity.set( 0, 0, -config.bullet.speed )
    .applyQuaternion( ship.quaternion )
    .add( ship.velocity );

  client.add( bullet );
}

function animate() {
  const delta = Math.min( clock.getDelta(), 0.1 );
  controls.update();

  accumulatedTime += delta;

  while ( accumulatedTime >= dt ) {
    if ( keys[ 32 ] && canFire( clock.getElapsedTime() ) ) {
      fire();
    }

    const removed = [];

    update( scene, dt, object => {
      if ( object.type === 'bullet' ) {
        object.lookAt( camera.position );
        if ( object.start &&
             object.start.distanceTo( object.position ) > config.bullet.range ) {
          removed.push( object );
        }
      }
    });

    removed.forEach( object => object.parent.remove( object ) );

    // Update camera after ship update.
    updateCamera( dt );

    accumulatedTime -= dt;
  }

  radar.position.set( -1, -1, -2 )
    .applyQuaternion( camera.quaternion )
    .add( camera.position );

  radar.reset();
  radar.track( client, camera );
  radar.track( server, camera );
  trail.track( ship );
  debris.track( ship );

  renderer.autoClear = false;
  skybox.render( renderer, camera );
  renderer.render( scene, camera );
  renderer.autoClear = true;

  if ( running ) {
    requestAnimationFrame( animate );
  }
}

animate();

// Space bar.
const startFiring = () => keys[ 32 ] = true;
const stopFiring = () => keys[ 32 ] = false;

document.addEventListener( 'mousedown', startFiring );
document.addEventListener( 'mouseup', stopFiring );
document.addEventListener( 'touchstart', startFiring );
document.addEventListener( 'touchend', stopFiring );
document.addEventListener( 'keydown', event => keys[ event.keyCode ] = true );
document.addEventListener( 'keyup', event => keys[ event.keyCode ] = false );

document.addEventListener( 'keydown', event => {
  // P. Pause/play.
  if ( event.keyCode === 80 ) {
    running = !running;
    if ( running ) {
      animate();
    }
  }

  // Shift key.
  if ( event.keyCode === 16 ) {
    controls.speed = 4 * config.ship.speed;
  }
});

document.addEventListener( 'keyup', event => {
  if ( event.keyCode === 16 ) {
    controls.speed = config.ship.speed;
  }
});

window.addEventListener( 'resize', () => {
  renderer.setPixelRatio( window.devicePixelRatio );
  renderer.setSize( window.innerWidth, window.innerHeight );

  camera.aspect = window.innerWidth / window.innerHeight;
  camera.updateProjectionMatrix();

  skybox.resize( window.innerWidth, window.innerHeight );
});

require( './webrtc-component' )( client, server );
<commit_msg>Replace Trail with Engine.<commit_after>import THREE from 'three.js';
import FlyControlsTouch from './touch';
import pointerLock from './pointer-lock';
import Ship from './ship';
import Bullet from './bullet';
import Drone from './drone';
import Radar from './radar';
import { TargetingComputer } from './reticle';
import Skybox from'./skybox';
import Engine from './engine';
import Debris from './debris';
import Explosion from './explosion';
import createClient from './client';
import update from './update';
import config from './config';
import createMap from './map';

const container = document.createElement( 'div' );
document.body.appendChild( container );

const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
container.appendChild( renderer.domElement );

const scene = new THREE.Scene();
createMap( scene, 'minimal' );

const client = new THREE.Group();
scene.add( client );

const server = new THREE.Group();
scene.add( server );

createClient( client, server );

const camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 0.1 );
scene.add( camera );

const ship = new Ship();
client.add( ship );

const radar = new Radar( ship );
client.add( radar );

const drone = new Drone();
client.add( drone );

const targetingComputer = new TargetingComputer( ship, drone );
scene.add( targetingComputer );

const engine = new Engine( ship );
engine.position.set( 0, 0, 0.3 );
ship.add( engine );

const debris = new Debris();
scene.add( debris );

const explosion = new Explosion();
explosion.position.set( 0, -1, -4 );
scene.add( explosion );

setInterval( () => explosion.reset(), 1000 );

const skybox = new Skybox( camera );
createMap( skybox.scene, 'minimalSkybox' );

const keys = [];
const controls = new FlyControlsTouch( ship, renderer.domElement );
controls.speed = config.ship.speed;
pointerLock( controls );

const clock = new THREE.Clock();
let running = true;

const dt = 1 / 60;
let accumulatedTime = 0;

const updateCamera = ( target => {
  const stiffness = 6;
  const offset = new THREE.Vector3( 0, 0.3, 1 );
  const vector = new THREE.Vector3();

  return dt => {
    // Ideal camera position.
    vector.copy( offset )
      .applyQuaternion( target.quaternion )
      .add( target.position );

    camera.position.lerp( vector, stiffness * dt );
    camera.quaternion.slerp( target.quaternion, stiffness * dt );
  };
})( ship );

const canFire = (() => {
  const period = 1 / config.ship.fireRate;
  let previous = 0;

  return time => {
    if ( time - previous < period ) {
      return false;
    }

    previous = time;
    return true;
  };
})();

function fire() {
  const bullet = new Bullet();
  bullet.position.copy( ship.position );
  bullet.start = bullet.position.clone();

  // Fire in ship direction.
  bullet.velocity.set( 0, 0, -config.bullet.speed )
    .applyQuaternion( ship.quaternion )
    .add( ship.velocity );

  client.add( bullet );
}

function animate() {
  const delta = Math.min( clock.getDelta(), 0.1 );
  controls.update();

  accumulatedTime += delta;

  while ( accumulatedTime >= dt ) {
    if ( keys[ 32 ] && canFire( clock.getElapsedTime() ) ) {
      fire();
    }

    const removed = [];

    update( scene, dt, object => {
      if ( object.type === 'bullet' ) {
        object.lookAt( camera.position );
        if ( object.start &&
             object.start.distanceTo( object.position ) > config.bullet.range ) {
          removed.push( object );
        }
      }
    });

    removed.forEach( object => object.parent.remove( object ) );

    // Update camera after ship update.
    updateCamera( dt );

    accumulatedTime -= dt;
  }

  radar.position.set( -1, -1, -2 )
    .applyQuaternion( camera.quaternion )
    .add( camera.position );

  radar.reset();
  radar.track( client, camera );
  radar.track( server, camera );
  debris.track( ship );

  renderer.autoClear = false;
  skybox.render( renderer, camera );
  renderer.render( scene, camera );
  renderer.autoClear = true;

  if ( running ) {
    requestAnimationFrame( animate );
  }
}

animate();

// Space bar.
const startFiring = () => keys[ 32 ] = true;
const stopFiring = () => keys[ 32 ] = false;

document.addEventListener( 'mousedown', startFiring );
document.addEventListener( 'mouseup', stopFiring );
document.addEventListener( 'touchstart', startFiring );
document.addEventListener( 'touchend', stopFiring );
document.addEventListener( 'keydown', event => keys[ event.keyCode ] = true );
document.addEventListener( 'keyup', event => keys[ event.keyCode ] = false );

document.addEventListener( 'keydown', event => {
  // P. Pause/play.
  if ( event.keyCode === 80 ) {
    running = !running;
    if ( running ) {
      animate();
    }
  }

  // Shift key.
  if ( event.keyCode === 16 ) {
    controls.speed = 4 * config.ship.speed;
  }
});

document.addEventListener( 'keyup', event => {
  if ( event.keyCode === 16 ) {
    controls.speed = config.ship.speed;
  }
});

window.addEventListener( 'resize', () => {
  renderer.setPixelRatio( window.devicePixelRatio );
  renderer.setSize( window.innerWidth, window.innerHeight );

  camera.aspect = window.innerWidth / window.innerHeight;
  camera.updateProjectionMatrix();

  skybox.resize( window.innerWidth, window.innerHeight );
});

require( './webrtc-component' )( client, server );
<|endoftext|>


<commit_before>import 'whatwg-fetch';
import codemirror from 'codemirror';
import 'codemirror/mode/javascript/javascript';
import analytics from './analytics';
import redirectTraffic from './redirect-traffic';
import layoutFunctions from './layoutFunctions';
import clickEvents from './clickEvents';
import drag from './drag';
import examples from './add-examples';
import libraries from './add-libraries';
import $ from './helpers';
import share from './share';
import snackbar from './snackbar';
import frameBridge from './frameBridge';
import MESSAGES from './sandbox/keys';

const codeWrapper = $.getElement('.code-wrapper'),
  fiddleWrapper = $.getElement('.fiddle-wrapper'),
  themeChanger = $.getElement('.change-theme'),
  savedTheme = localStorage.getItem('theme'),
  pathAr = location.pathname.split('/'),
  fiddleId = pathAr[pathAr.length - 2],
  embedded = pathAr[1] === 'embed',
  startFiddle = $.getElement('.star');

analytics.start();
redirectTraffic.register();
window.embedded = embedded;
window.exampleSelector = $.getElement('.examples');
examples.addExamples();

window.librariesSelector = $.getElement('.libraries');
libraries.addLibraries();

// check to see if the share button should be shown
if (fiddleId && !embedded) {
  const shareEl = $.getElement('.share');
  $.addStyleTo(startFiddle, 'display', 'block');
  if (shareEl) { share.shareFiddle(fiddleId); }
} else {
  $.addStyleTo(startFiddle, 'display', 'none');
}

// handle the embedded buttons
if (embedded) {
  const es6Btn = $.getElement('.es6-click-btn');
  const consoleBtn = $.getElement('.console-click-btn');
  $.getElement('.edit-at-es6').href = document.location.href.replace('/embed', '');

  es6Btn.onclick = () => {
    $.getElement('.fiddle').addStyle('display', 'block');
    $.getElement('.result-wrapper').addStyle('display', 'none');
    $.addClass(es6Btn, 'selected');
    $.removeClass(consoleBtn, 'selected');
  };

  consoleBtn.onclick = () => {
    $.getElement('.fiddle').addStyle('display', 'none');
    $.getElement('.result-wrapper').addStyle('display', 'block');
    $.removeClass(es6Btn, 'selected');
    $.addClass(consoleBtn, 'selected');
  };
}

// Change the layout of the page based on the type clicked.
// Save this layout choice in localStorage
// By default this will be vertical
$.getElement('.vertical').onclick = () => {
  layoutFunctions.setVerticalStyle(codeWrapper);
  layoutFunctions.saveLayoutOption('vertical');
};

// Onclick of the horizontal button then make the page visually horizontal
// And save the layout option clicked (in this case horizontal) to localstorage
$.getElement('.horizontal').onclick = () => {
  layoutFunctions.setHorizontalStyle(codeWrapper);
  layoutFunctions.saveLayoutOption('horizontal');
};

// add the fiddle area
const fiddle = codemirror($.getElement('.fiddle'), {
  lineNumbers: !embedded,
  readOnly: embedded ? 'nocursor' : false,
  theme: savedTheme || 'default',
});
fiddle.focus();

// If the user has previously selected to use the horizontal layout then load that
if (localStorage.getItem('es6fiddleLayout') === 'horizontal') {
  layoutFunctions.setHorizontalStyle(codeWrapper);
  // Otherwise make the page the default vertical style
} else {
  layoutFunctions.setVerticalStyle(codeWrapper);
}

// If the user has previously enabled dark mode then open in dark mode
if (localStorage.getItem('es6fiddleDarkMode') === 'true') {
  clickEvents.enableDarkMode();
} else {
  clickEvents.disableDarkMode();
}

// When the dark mode button is clicked, toggle the dark mode setting
$.getElement('.dark-mode').onclick = () => {
  clickEvents.darkModeClick(clickEvents.disableDarkMode, clickEvents.enableDarkMode, fiddle);
};

// Set the saved theme in the theme changer dropdown
if (savedTheme) {
  themeChanger.value = savedTheme;
}

// Add line number to all console.log() statements
function calculateLineNumber(fiddleValue) {
  const lines = fiddleValue.split(/\n/);
  let newLines = '';
  newLines = lines.map((line, index) => {
    const consReg = /(console\.log\()(.*)/;
    //  separate console.log from original string and split it in to
    // "console.log(" and ")"
    const clgLines = line.match(consReg);
    if (clgLines) {
      // Add line no: to console.log and join it with rest of the original line.
      // return line.slice(0, clgLines.index) + clgLines[1] + `'${index+1}: ' , ` +clgLines[2];
      return `${line.slice(0, clgLines.index) + clgLines[1]}'${index + 1}: ' , ${clgLines[2]}`;
    }
    return line;
  });
  return newLines.join('\n');
}

/* eslint-disable */
const runFiddle = () => {
  frameBridge.send(MESSAGES.RUN_SCRIPT, calculateLineNumber(fiddle.getValue()));
};

/* eslint-enable */

const getFiddle = (data) => {
  if (data.fiddle) {
    if (data.value) {
      fiddle.setValue(data.value);
    } else {
      fiddle.setValue('* Sorry, but I could not load your code right now. *');
    }
    if (data.isPrivate) {
      const privateIcon = $.getElement('.fa-globe');
      privateIcon.classList.remove('fa-globe');
      privateIcon.classList.add('fa-lock');
      privateIcon.parentElement.setAttribute('data-balloon', 'Private Fiddle');
    }
  } else {
    $.addStyleTo(startFiddle, 'display', 'none');
    fiddle.setValue(data.message);
  }

  if (embedded) { // go ahead and run the code
    runFiddle();
  }
};

// if fiddleId is define then load up the saved code
if (fiddleId) {
  fetch(`/fiddles/${fiddleId}`, {
    credentials: 'same-origin',
  }).then(resp => resp.json()).then(data => getFiddle(data));
}

// if this is not an embedded fiddle than add extra elements to this
if (!embedded) {
  // run the input
  $.getElement('.run').onclick = runFiddle;

  // lint the result
  $.getElement('.lint').onclick = () => {
    const lint = JSHINT(fiddle.getValue(), {
      esnext: true,
      devel: true,
      browser: true,
    });

    // remove the line error class from all lines
    fiddle.eachLine((line) => {
      fiddle.removeLineClass(line, 'background', 'line-error');
    });

    const lints = [];
    if (!lint) {
      JSHINT.errors.forEach((err) => {
        fiddle.addLineClass(err.line - 1, 'background', 'line-error');
        lints.push(`console.log('Line ' + ${err.line} + ':', '${err.reason.replace(/'/g, '\\\'')}')\n`);
      });
    } else {
      lints.push('console.log(\'Awesome! Your code is lint free!\');');
    }

    frameBridge.send(MESSAGES.RUN_SCRIPT, lints.join('\n'));
  };

  // save the code
  document.querySelector('.save').onclick = () => clickEvents.saveBtn(fiddle);

  // star the code
  $.getElement('.star').onclick = () => {
    const pathArr = window.location.pathname.split('/'),
      fiddleID = pathArr[1].length > 1 ? pathArr[1] : -1;

    if (fiddleID !== -1) {
      fetch(`/star/${fiddleID}`, {
        method: 'POST',
        credentials: 'same-origin',
        headers: new Headers({
          'Content-Type': 'application/json',
        }),
      })
        .then(resp => resp.json())
        .then(data => clickEvents.starFiddle(data));
    }
  };

  // Make fiddle private
  $.getElement('.private').onclick = () => {
    const pathArr = window.location.pathname.split('/'),
      fiddleID = pathArr[1].length > 1 ? pathArr[1] : -1;

    if (fiddleID !== -1) {
      fetch(`/private/${fiddleID}`, {
        method: 'POST',
        credentials: 'same-origin',
        headers: new Headers({
          'Content-Type': 'application/json',
        }),
      })
          .then(resp => resp.json())
          .then(data => clickEvents.privateFiddle(data));
    } else {
      snackbar.showSnackbar('You don\'t appear to have any code or its not saved.');
    }
  };

  themeChanger.onchange = () => {
    const theme = themeChanger.options[themeChanger.selectedIndex].textContent;
    fiddle.setOption('theme', theme);
    localStorage.setItem('theme', theme);
  };

  // load the selected code
  window.exampleSelector.onchange = () => {
    if (window.exampleSelector.value) {
      let code = 'Example Can Not Be Found';

      if (window.es6Example[window.exampleSelector.value]) {
        ({ code } = window.es6Example[window.exampleSelector.value]);
      } else if (window.es7Example[window.exampleSelector.value]) {
        ({ code } = window.es7Example[window.exampleSelector.value]);
      }

      fiddle.setValue(code);
    }
  };

  // load the selected javascript library
  window.librariesSelector.onchange = () => {
    if (window.librariesSelector.value) {
      const script = $.createElement('script');
      script.onload = function onScriptLoad() {
        console.log(`${window.librariesSelector.selectedOptions[0].text} Script loaded`);
      };
      script.src = window.librariesSelector.value;

      document.head.appendChild(script);
    }
  };
} // end not embedded

// Add dragging funcionality
fiddleWrapper.addEventListener('click', function init() {
  fiddleWrapper.removeEventListener('click', init, false);
  $.getElement('.resizer').addEventListener('mousedown', drag.initDrag, false);
}, false);
<commit_msg>Add extra line<commit_after>import 'whatwg-fetch';
import codemirror from 'codemirror';
import 'codemirror/mode/javascript/javascript';
import analytics from './analytics';
import redirectTraffic from './redirect-traffic';
import layoutFunctions from './layoutFunctions';
import clickEvents from './clickEvents';
import drag from './drag';
import examples from './add-examples';
import libraries from './add-libraries';
import $ from './helpers';
import share from './share';
import snackbar from './snackbar';
import frameBridge from './frameBridge';
import MESSAGES from './sandbox/keys';

const codeWrapper = $.getElement('.code-wrapper'),
  fiddleWrapper = $.getElement('.fiddle-wrapper'),
  themeChanger = $.getElement('.change-theme'),
  savedTheme = localStorage.getItem('theme'),
  pathAr = location.pathname.split('/'),
  fiddleId = pathAr[pathAr.length - 2],
  embedded = pathAr[1] === 'embed',
  startFiddle = $.getElement('.star');

analytics.start();
redirectTraffic.register();

window.embedded = embedded;
window.exampleSelector = $.getElement('.examples');
examples.addExamples();

window.librariesSelector = $.getElement('.libraries');
libraries.addLibraries();

// check to see if the share button should be shown
if (fiddleId && !embedded) {
  const shareEl = $.getElement('.share');
  $.addStyleTo(startFiddle, 'display', 'block');
  if (shareEl) { share.shareFiddle(fiddleId); }
} else {
  $.addStyleTo(startFiddle, 'display', 'none');
}

// handle the embedded buttons
if (embedded) {
  const es6Btn = $.getElement('.es6-click-btn');
  const consoleBtn = $.getElement('.console-click-btn');
  $.getElement('.edit-at-es6').href = document.location.href.replace('/embed', '');

  es6Btn.onclick = () => {
    $.getElement('.fiddle').addStyle('display', 'block');
    $.getElement('.result-wrapper').addStyle('display', 'none');
    $.addClass(es6Btn, 'selected');
    $.removeClass(consoleBtn, 'selected');
  };

  consoleBtn.onclick = () => {
    $.getElement('.fiddle').addStyle('display', 'none');
    $.getElement('.result-wrapper').addStyle('display', 'block');
    $.removeClass(es6Btn, 'selected');
    $.addClass(consoleBtn, 'selected');
  };
}

// Change the layout of the page based on the type clicked.
// Save this layout choice in localStorage
// By default this will be vertical
$.getElement('.vertical').onclick = () => {
  layoutFunctions.setVerticalStyle(codeWrapper);
  layoutFunctions.saveLayoutOption('vertical');
};

// Onclick of the horizontal button then make the page visually horizontal
// And save the layout option clicked (in this case horizontal) to localstorage
$.getElement('.horizontal').onclick = () => {
  layoutFunctions.setHorizontalStyle(codeWrapper);
  layoutFunctions.saveLayoutOption('horizontal');
};

// add the fiddle area
const fiddle = codemirror($.getElement('.fiddle'), {
  lineNumbers: !embedded,
  readOnly: embedded ? 'nocursor' : false,
  theme: savedTheme || 'default',
});
fiddle.focus();

// If the user has previously selected to use the horizontal layout then load that
if (localStorage.getItem('es6fiddleLayout') === 'horizontal') {
  layoutFunctions.setHorizontalStyle(codeWrapper);
  // Otherwise make the page the default vertical style
} else {
  layoutFunctions.setVerticalStyle(codeWrapper);
}

// If the user has previously enabled dark mode then open in dark mode
if (localStorage.getItem('es6fiddleDarkMode') === 'true') {
  clickEvents.enableDarkMode();
} else {
  clickEvents.disableDarkMode();
}

// When the dark mode button is clicked, toggle the dark mode setting
$.getElement('.dark-mode').onclick = () => {
  clickEvents.darkModeClick(clickEvents.disableDarkMode, clickEvents.enableDarkMode, fiddle);
};

// Set the saved theme in the theme changer dropdown
if (savedTheme) {
  themeChanger.value = savedTheme;
}

// Add line number to all console.log() statements
function calculateLineNumber(fiddleValue) {
  const lines = fiddleValue.split(/\n/);
  let newLines = '';
  newLines = lines.map((line, index) => {
    const consReg = /(console\.log\()(.*)/;
    //  separate console.log from original string and split it in to
    // "console.log(" and ")"
    const clgLines = line.match(consReg);
    if (clgLines) {
      // Add line no: to console.log and join it with rest of the original line.
      // return line.slice(0, clgLines.index) + clgLines[1] + `'${index+1}: ' , ` +clgLines[2];
      return `${line.slice(0, clgLines.index) + clgLines[1]}'${index + 1}: ' , ${clgLines[2]}`;
    }
    return line;
  });
  return newLines.join('\n');
}

/* eslint-disable */
const runFiddle = () => {
  frameBridge.send(MESSAGES.RUN_SCRIPT, calculateLineNumber(fiddle.getValue()));
};

/* eslint-enable */

const getFiddle = (data) => {
  if (data.fiddle) {
    if (data.value) {
      fiddle.setValue(data.value);
    } else {
      fiddle.setValue('* Sorry, but I could not load your code right now. *');
    }
    if (data.isPrivate) {
      const privateIcon = $.getElement('.fa-globe');
      privateIcon.classList.remove('fa-globe');
      privateIcon.classList.add('fa-lock');
      privateIcon.parentElement.setAttribute('data-balloon', 'Private Fiddle');
    }
  } else {
    $.addStyleTo(startFiddle, 'display', 'none');
    fiddle.setValue(data.message);
  }

  if (embedded) { // go ahead and run the code
    runFiddle();
  }
};

// if fiddleId is define then load up the saved code
if (fiddleId) {
  fetch(`/fiddles/${fiddleId}`, {
    credentials: 'same-origin',
  }).then(resp => resp.json()).then(data => getFiddle(data));
}

// if this is not an embedded fiddle than add extra elements to this
if (!embedded) {
  // run the input
  $.getElement('.run').onclick = runFiddle;

  // lint the result
  $.getElement('.lint').onclick = () => {
    const lint = JSHINT(fiddle.getValue(), {
      esnext: true,
      devel: true,
      browser: true,
    });

    // remove the line error class from all lines
    fiddle.eachLine((line) => {
      fiddle.removeLineClass(line, 'background', 'line-error');
    });

    const lints = [];
    if (!lint) {
      JSHINT.errors.forEach((err) => {
        fiddle.addLineClass(err.line - 1, 'background', 'line-error');
        lints.push(`console.log('Line ' + ${err.line} + ':', '${err.reason.replace(/'/g, '\\\'')}')\n`);
      });
    } else {
      lints.push('console.log(\'Awesome! Your code is lint free!\');');
    }

    frameBridge.send(MESSAGES.RUN_SCRIPT, lints.join('\n'));
  };

  // save the code
  document.querySelector('.save').onclick = () => clickEvents.saveBtn(fiddle);

  // star the code
  $.getElement('.star').onclick = () => {
    const pathArr = window.location.pathname.split('/'),
      fiddleID = pathArr[1].length > 1 ? pathArr[1] : -1;

    if (fiddleID !== -1) {
      fetch(`/star/${fiddleID}`, {
        method: 'POST',
        credentials: 'same-origin',
        headers: new Headers({
          'Content-Type': 'application/json',
        }),
      })
        .then(resp => resp.json())
        .then(data => clickEvents.starFiddle(data));
    }
  };

  // Make fiddle private
  $.getElement('.private').onclick = () => {
    const pathArr = window.location.pathname.split('/'),
      fiddleID = pathArr[1].length > 1 ? pathArr[1] : -1;

    if (fiddleID !== -1) {
      fetch(`/private/${fiddleID}`, {
        method: 'POST',
        credentials: 'same-origin',
        headers: new Headers({
          'Content-Type': 'application/json',
        }),
      })
          .then(resp => resp.json())
          .then(data => clickEvents.privateFiddle(data));
    } else {
      snackbar.showSnackbar('You don\'t appear to have any code or its not saved.');
    }
  };

  themeChanger.onchange = () => {
    const theme = themeChanger.options[themeChanger.selectedIndex].textContent;
    fiddle.setOption('theme', theme);
    localStorage.setItem('theme', theme);
  };

  // load the selected code
  window.exampleSelector.onchange = () => {
    if (window.exampleSelector.value) {
      let code = 'Example Can Not Be Found';

      if (window.es6Example[window.exampleSelector.value]) {
        ({ code } = window.es6Example[window.exampleSelector.value]);
      } else if (window.es7Example[window.exampleSelector.value]) {
        ({ code } = window.es7Example[window.exampleSelector.value]);
      }

      fiddle.setValue(code);
    }
  };

  // load the selected javascript library
  window.librariesSelector.onchange = () => {
    if (window.librariesSelector.value) {
      const script = $.createElement('script');
      script.onload = function onScriptLoad() {
        console.log(`${window.librariesSelector.selectedOptions[0].text} Script loaded`);
      };
      script.src = window.librariesSelector.value;

      document.head.appendChild(script);
    }
  };
} // end not embedded

// Add dragging funcionality
fiddleWrapper.addEventListener('click', function init() {
  fiddleWrapper.removeEventListener('click', init, false);
  $.getElement('.resizer').addEventListener('mousedown', drag.initDrag, false);
}, false);
<|endoftext|>


<commit_before>/**
 * Contains variables and functions used to retrieve images, GIFs, and music
 * for the GIF Dance Party
 */
gdpMedia =  {
    /* List of GIF Dance Party song titles */
    gdpPlaylist: [
        'no music', 'bazz', 'bubblebutt', 'fatboy', 'grounded',
        'halffull', 'hotline', 'nahnahnah', 'sandstorm', 'shake it off', 'singalong', 'trololo',
        'twist', 'walkmen', 'wegotyou', 'whats going on'
    ],
    gdpSongMap:{
        'no music': 'nomusic',
        'bazz': 'http://gifdanceparty.giphy.com/music/bazz.ogg',
        'bubblebutt': 'http://gifdanceparty.giphy.com/music/bubblebutt.ogg',
        'fatboy': 'http://gifdanceparty.giphy.com/music/fatboy.ogg',
        'grounded': 'http://gifdanceparty.giphy.com/music/grounded.ogg',
        'halffull': 'http://gifdanceparty.giphy.com/music/halffull.ogg',
        'nahnahnah': 'http://gifdanceparty.giphy.com/music/nahnahnah.ogg',
        'singalong': 'http://gifdanceparty.giphy.com/music/singalong.ogg',
        'trololo': 'http://gifdanceparty.giphy.com/music/trololo.ogg',
        'twist': 'http://gifdanceparty.giphy.com/music/twist.ogg',
        'walkmen': 'http://gifdanceparty.giphy.com/music/walkmen.ogg',
        'wegotyou': 'http://gifdanceparty.giphy.com/music/wegotyou.ogg',
        'hotline': 'http://jlyneu.github.io/GIF-Dance-Party-Extension/hotlineloop.wav',
        'sandstorm': 'http://jlyneu.github.io/GIF-Dance-Party-Extension/sandstorm.wav',
        'whats going on': 'http://jlyneu.github.io/GIF-Dance-Party-Extension/heman.wav',
        'shake it off': 'http://jlyneu.github.io/GIF-Dance-Party-Extension/Taylor_shake_it_off.wav',
    },
    /* Mapping from dancer names to Imgur thumbnail and Giphy dancer ids */
    mediaIds: {
        '8bitcarlton': {
            imgur: 'ifuoPqn',
            giphy: '3oEduOy5DYLEzDoxb2'
        },
        apple: {
            imgur: 'wbv3RCd',
            giphy: 'l41lQrLqxsH1EIuIw'
        },
        arnold: {
            imgur: 'Sh6WPJs',
            giphy: '3oEduW2sRvdCJjomZi'
        },
        babe: {
            imgur: 'hDWrKI7',
            giphy: 'l41lUxdQ1uRoQfC5G'
        },
        banana: {
            imgur: 'Li3pOWH',
            giphy: '3oEduNh73pM45xDSNi'
        },
        bear: {
            imgur: '7KW1zWk',
            giphy: '3oEduP15LEqQfXJCNy'
        },
        yoshi: {
            imgur: 'ENUYNWU',
            giphy: '9OIXjveDvpGRW'
        },
        blob: {
            imgur: 'P7meKeB',
            giphy: 'l41lOD9cTj6YbmcX6'
        },
        bb: {
            imgur: 'zhtTJNv',
            giphy: 'eEbiAqk9YUT5e'
        },
        bmo: {
            imgur: 'Q6Jyks5',
            giphy: '3oEduYm2dxZpkCCkOA'
        },
        bonebreak: {
            imgur: 'otdi7m9',
            giphy: '3oEduIiEL5hcetXqAE'
        },
        brian: {
            imgur: 'mcVtWQT',
            giphy: 'l41lFG8HaIVcPt9QY'
        },
        bunnyspank: {
            imgur: 'G9Bs0N9',
            giphy: 'l41lNvJ5gkGf0y4Xm'
        },
        cact: {
            imgur: 'fn0xLOv',
            giphy: 'l41lYdZg4lDWCYKjK'
        },
        pooh: {
            imgur: '1DXTA1I',
            giphy: 'wjIDrGKbvuGxW'
        },
        carlton: {
            imgur: 'uF179oM',
            giphy: '3oEduT6H7fftjTic2k'
        },
        charlie: {
            imgur: 'aXXDfwI',
            giphy: '3oEduQkZZDBupCoXU4'
        },
        cowboy: {
            imgur: 'sCxQ7om',
            giphy: '3oEduYRB2uyvHWEdJC'
        },
        discoball: {
            imgur: 'FqqZgIZ',
            giphy: 'l41lGAas7QuzXT9UQ'
        },
        doggy: {
            imgur: 'Q6r1gYp',
            giphy: 'l41lIG49uUKFm1sR2'
        },
        nyan: {
            imgur: 'nxCxp6u',
            giphy: 'WC0DCFkLq4faU'
        },
        drakeHotline: {
            imgur: 'wTATJ1T',
            giphy: '3oEduGBEzAuZHR9jwc'
        },
        drakePush: {
            imgur: '8zy3MQA',
            giphy: '3oEduLLkRxHa9LrwTS'
        },
        drakeWrist: {
            imgur: 'jZUSVbA',
            giphy: 'xTiTnLOTgCWEu3akr6'
        },
        fabio: {
            imgur: '320x7kR',
            giphy: '3oEdvcgt5kA260mpva'
        },
        fatspidey: {
            imgur: '5GZYEmt',
            giphy: '3oEduV5zJRtZA20V32'
        },
        kenny: {
            imgur: 'LKzQ7KE',
            giphy: '14nrpQCJ5iagdG'
        },
        foreveralone: {
            imgur: 'jgOvt9T',
            giphy: 'l41lWaQCC5Y65ErUQ'
        },
        fred: {
            imgur: 'FSvV7is',
            giphy: 'l41lPqa3dpN6ete3m'
        },
        gene: {
            imgur: 'nfO1s5a',
            giphy: '3oEdv6b7ul6xu0qkx2'
        },
        ghosty: {
            imgur: 'VcNCtEa',
            giphy: 'l41lUNDlC1ka19oU8'
        },
        greenlady: {
            imgur: 't8qX9Q2',
            giphy: 'l41lFr6nvWK6foKXe'
        },
        greenlady2: {
            imgur: '0v0rcxb',
            giphy: '3oEduPQBm9ugmXOupq'
        },
        victorydance: {
            imgur: 'rbOosYj',
            giphy: 'xTk9ZSHoVA1uODUyoU'
        },
        heman: {
            imgur: 'LxPW2rQ',
            giphy: '3o85xEQknNotn5dXfG'
        },
        hipdog: {
            imgur: 'eMs7spK',
            giphy: '3oEdvaWNO2CrIE4fh6'
        },
        hotdogs: {
            imgur: 'g9wUmtR',
            giphy: '3oEduOwP0y4eYwQBNK'
        },
        hula: {
            imgur: 'LoWDE67',
            giphy: '3oEdv8tYhAP5obLpUk'
        },
        humpery: {
            imgur: 'PXplXOH',
            giphy: 'l41lFnwluQ94HmMuY'
        },
        llama: {
            imgur: 'Nj46dlb',
            giphy: 'mGWj9gZG7eFCE'
        },
        jason: {
            imgur: 'YTLTpTk',
            giphy: 'l41lZ65JSCJPni7FS'
        },
        kirby: {
            imgur: 'fOit8Na',
            giphy: 'l41lVDy4QPJJApSPS'
        },
        kitty: {
            imgur: 'IOO2VgN',
            giphy: '3oEduKQuAlKRfgRAvS'
        },
        lilguy: {
            imgur: 'wETEb4l',
            giphy: 'l41lI6dIfDLLMsNjy'
        },
        lisa: {
            imgur: 'hf2s0Ej',
            giphy: 'NfeV16w5ZvaaQ'
        },
        maranda: {
            imgur: 'zZrLAyH',
            giphy: '26BkNCYFWc3YrUSFa'
        },
        mj: {
            imgur: 'U0TcBG6',
            giphy: '3oEdv8uVwchZIxkJDG'
        },
        nerd: {
            imgur: 'S5Wo2T1',
            giphy: 'l41lTnsFgDcDFtiPm'
        },
        obama: {
            imgur: 'lKpfbv1',
            giphy: 'l41lSXRKx8csZ1kic'
        },
        orangeguy: {
            imgur: 'rG0HL2S',
            giphy: '3oEduRSQNa8CTeA3iU'
        },
        pa: {
            imgur: 'wzTfl7Z',
            giphy: 'l41lXHizBwZJWoYLK'
        },
        patrick: {
            imgur: 'CgLMqm8',
            giphy: '3oEdv6ocnBsOlAUQfK'
        },
        pedopickle: {
            imgur: 'jRoMC6Y',
            giphy: 'l41m3WCro5TSN7Bp6'
        },
        pikachu: {
            imgur: '3nnb34A',
            giphy: 'zEBHffYMPaIwM'
        },
        pixelly: {
            imgur: 'Qw2O47x',
            giphy: '3oEduPmVVIex3w0Oys'
        },
        ponyshuffle: {
            imgur: '6frE5RS',
            giphy: '3oEduTi5ktbhXp3Rm0'
        },
        possum: {
            imgur: 'lFPmQrS',
            giphy: '3oEduKLDMtc7jleGgU'
        },
        pumpgirl: {
            imgur: 'GD8TggR',
            giphy: 'l41m4R1fgL5jZX1Qc'
        },
        ravecat: {
            imgur: 'KWBLGKg',
            giphy: '3oEduWBjP4utBdgGL6'
        },
        robothump: {
            imgur: 'VZNMx5i',
            giphy: '3oEdv53199cJ6nUhDq'
        },
        roger: {
            imgur: 'JSMQUnh',
            giphy: '3oEdv21WszrucZzBSw'
        },
        runningworm: {
            imgur: '4cDqUCe',
            giphy: '3oEdv2xy5QjqBiSxzO'
        },
        saxguy: {
            imgur: 'E3sRBkX',
            giphy: 'l41lWg4naO0TljUSQ'
        },
        scorpion: {
            imgur: 'dzScRdd',
            giphy: '3oEduNF2afOEDQ4kCY'
        },
        shawty: {
            imgur: 'stZZLVd',
            giphy: '3oEdv0F6sqE5XCWkCc'
        },
        smooch: {
            imgur: 'BeH7q4x',
            giphy: '3oEduTxikdl6659Tws'
        },
        snoop: {
            imgur: 'u82kPtm',
            giphy: 'O0Xo8Tpk5QxTW'
        },
        speakerhead: {
            imgur: '7Hy7lrN',
            giphy: 'l41lTFERkZe2H9FOo'
        },
        leftshark: {
            imgur: 'glPurdO',
            giphy: '3o85xBH1NjrRfa8kPm'
        },
        spongeybob: {
            imgur: '6AXEklV',
            giphy: '3oEduGmM5MJLjciFSU'
        },
        squidword: {
            imgur: 'v9pzZCM',
            giphy: '26BkMz3mtQqMl6Dw4'
        },
        shakeitoff: {
            imgur: '8xbnBRN',
            giphy: '26tP3JkdNpeU1k8Tu'
        },
        tej: {
            imgur: 'Q49aPYo',
            giphy: '3oEduF6VoHOTKkrplu'
        },
        thehop: {
            imgur: '5fmPHBc',
            giphy: '3oEduP8lE334O5KNJS'
        },
        thewizard: {
            imgur: 'FExyzq0',
            giphy: '3oEduP15u1e3duOSE8'
        },
        theworm: {
            imgur: 'Z62jSAr',
            giphy: 'l41m6R0OgDvej2Vag'
        },
        tim: {
            imgur: 'hGXXXDl',
            giphy: 'l41lT8zKKiIRjnM1G'
        },
        twerk: {
            imgur: 'EjL0GLT',
            giphy: 'l41lQZJYzSqGDWFz2'
        },
        whiteguy: {
            imgur: '6jYdEPO',
            giphy: '3oEduKmO22VEzbmpLq'
        },
        yeti: {
            imgur: '4LDzQq6',
            giphy: '3oEduYLrzljc1cGY5a'
        }
    },
    /* Retrieve the Imgur url for the given dancer's thumbnail image */
    getThumbnailUrl: function(dancerName) {
        return "https://imgur.com/" + gdpMedia.mediaIds[dancerName]["imgur"] + ".png";
    },
    /* Retrieve the Giphy url for the given dancer's GIF */
    getGifUrl: function(dancerName) {
        return "https://media.giphy.com/media/" + gdpMedia.mediaIds[dancerName]["giphy"] + "/giphy.gif";
    },
    /* Send a message to the background script to play the song with the
       given name */
    selectSong: function(name, url, isCustom) {
        console.log([name, url, isCustom]);
        chrome.runtime.sendMessage({
            type: "songUrl",
            songUrl: (!isCustom ? gdpMedia.gdpSongMap[name] : url)
        });
    },
    /* Send a message to the background script to stop playing audio */
    stopAudio: function() {
        chrome.runtime.sendMessage({
            type: "stopAudio"
        });
    },
    /* When leaving the current page, send a message to the background script
       to stop playing audio */
    unloadAudio: function() {
        // when leaving the page, be sure to stop the gdp audio
        $(window).unload(function() {
            gdpMedia.stopAudio();
        });
    }
}
<commit_msg>resized gifs<commit_after>/**
 * Contains variables and functions used to retrieve images, GIFs, and music
 * for the GIF Dance Party
 */
gdpMedia =  {
    /* List of GIF Dance Party song titles */
    gdpPlaylist: [
        'no music', 'bazz', 'bubblebutt', 'fatboy', 'grounded',
        'halffull', 'hotline', 'nahnahnah', 'sandstorm', 'shake it off', 'singalong', 'trololo',
        'twist', 'walkmen', 'wegotyou', 'whats going on'
    ],
    gdpSongMap:{
        'no music': 'nomusic',
        'bazz': 'http://gifdanceparty.giphy.com/music/bazz.ogg',
        'bubblebutt': 'http://gifdanceparty.giphy.com/music/bubblebutt.ogg',
        'fatboy': 'http://gifdanceparty.giphy.com/music/fatboy.ogg',
        'grounded': 'http://gifdanceparty.giphy.com/music/grounded.ogg',
        'halffull': 'http://gifdanceparty.giphy.com/music/halffull.ogg',
        'nahnahnah': 'http://gifdanceparty.giphy.com/music/nahnahnah.ogg',
        'singalong': 'http://gifdanceparty.giphy.com/music/singalong.ogg',
        'trololo': 'http://gifdanceparty.giphy.com/music/trololo.ogg',
        'twist': 'http://gifdanceparty.giphy.com/music/twist.ogg',
        'walkmen': 'http://gifdanceparty.giphy.com/music/walkmen.ogg',
        'wegotyou': 'http://gifdanceparty.giphy.com/music/wegotyou.ogg',
        'hotline': 'http://jlyneu.github.io/GIF-Dance-Party-Extension/hotlineloop.wav',
        'sandstorm': 'http://jlyneu.github.io/GIF-Dance-Party-Extension/sandstorm.wav',
        'whats going on': 'http://jlyneu.github.io/GIF-Dance-Party-Extension/heman.wav',
        'shake it off': 'http://jlyneu.github.io/GIF-Dance-Party-Extension/Taylor_shake_it_off.wav',
    },
    /* Mapping from dancer names to Imgur thumbnail and Giphy dancer ids */
    mediaIds: {
        '8bitcarlton': {
            imgur: 'ifuoPqn',
            giphy: '3oEduOy5DYLEzDoxb2'
        },
        apple: {
            imgur: 'wbv3RCd',
            giphy: 'l41lQrLqxsH1EIuIw'
        },
        arnold: {
            imgur: 'Sh6WPJs',
            giphy: '3oEduW2sRvdCJjomZi'
        },
        babe: {
            imgur: 'hDWrKI7',
            giphy: 'l41lUxdQ1uRoQfC5G'
        },
        banana: {
            imgur: 'Li3pOWH',
            giphy: '3oEduNh73pM45xDSNi'
        },
        bear: {
            imgur: '7KW1zWk',
            giphy: '3oEduP15LEqQfXJCNy'
        },
        yoshi: {
            imgur: 'ENUYNWU',
            giphy: '9OIXjveDvpGRW'
        },
        blob: {
            imgur: 'P7meKeB',
            giphy: 'l41lOD9cTj6YbmcX6'
        },
        bb: {
            imgur: 'zhtTJNv',
            giphy: 'xTk9ZJwB1Mg0Jq1KhO'
        },
        bmo: {
            imgur: 'Q6Jyks5',
            giphy: '3oEduYm2dxZpkCCkOA'
        },
        bonebreak: {
            imgur: 'otdi7m9',
            giphy: '3oEduIiEL5hcetXqAE'
        },
        brian: {
            imgur: 'mcVtWQT',
            giphy: 'l41lFG8HaIVcPt9QY'
        },
        bunnyspank: {
            imgur: 'G9Bs0N9',
            giphy: 'l41lNvJ5gkGf0y4Xm'
        },
        cact: {
            imgur: 'fn0xLOv',
            giphy: 'l41lYdZg4lDWCYKjK'
        },
        pooh: {
            imgur: '1DXTA1I',
            giphy: 'wjIDrGKbvuGxW'
        },
        carlton: {
            imgur: 'uF179oM',
            giphy: '3oEduT6H7fftjTic2k'
        },
        charlie: {
            imgur: 'aXXDfwI',
            giphy: '3oEduQkZZDBupCoXU4'
        },
        cowboy: {
            imgur: 'sCxQ7om',
            giphy: '3oEduYRB2uyvHWEdJC'
        },
        discoball: {
            imgur: 'FqqZgIZ',
            giphy: 'l41lGAas7QuzXT9UQ'
        },
        doggy: {
            imgur: 'Q6r1gYp',
            giphy: 'l41lIG49uUKFm1sR2'
        },
        nyan: {
            imgur: 'nxCxp6u',
            giphy: 'WC0DCFkLq4faU'
        },
        drakeHotline: {
            imgur: 'wTATJ1T',
            giphy: '3oEduGBEzAuZHR9jwc'
        },
        drakePush: {
            imgur: '8zy3MQA',
            giphy: '3oEduLLkRxHa9LrwTS'
        },
        drakeWrist: {
            imgur: 'jZUSVbA',
            giphy: 'xTiTnLOTgCWEu3akr6'
        },
        fabio: {
            imgur: '320x7kR',
            giphy: '3oEdvcgt5kA260mpva'
        },
        fatspidey: {
            imgur: '5GZYEmt',
            giphy: '3oEduV5zJRtZA20V32'
        },
        kenny: {
            imgur: 'LKzQ7KE',
            giphy: '3o8doQrgKZa6Ce7jOM'
        },
        foreveralone: {
            imgur: 'jgOvt9T',
            giphy: 'l41lWaQCC5Y65ErUQ'
        },
        fred: {
            imgur: 'FSvV7is',
            giphy: 'l41lPqa3dpN6ete3m'
        },
        gene: {
            imgur: 'nfO1s5a',
            giphy: '3oEdv6b7ul6xu0qkx2'
        },
        ghosty: {
            imgur: 'VcNCtEa',
            giphy: 'l41lUNDlC1ka19oU8'
        },
        greenlady: {
            imgur: 't8qX9Q2',
            giphy: 'l41lFr6nvWK6foKXe'
        },
        greenlady2: {
            imgur: '0v0rcxb',
            giphy: '3oEduPQBm9ugmXOupq'
        },
        victorydance: {
            imgur: 'rbOosYj',
            giphy: 'xTka04CfeXMX74iE3m'
        },
        heman: {
            imgur: 'LxPW2rQ',
            giphy: '3o85xEQknNotn5dXfG'
        },
        hipdog: {
            imgur: 'eMs7spK',
            giphy: '3oEdvaWNO2CrIE4fh6'
        },
        hotdogs: {
            imgur: 'g9wUmtR',
            giphy: '3oEduOwP0y4eYwQBNK'
        },
        hula: {
            imgur: 'LoWDE67',
            giphy: '3oEdv8tYhAP5obLpUk'
        },
        humpery: {
            imgur: 'PXplXOH',
            giphy: 'l41lFnwluQ94HmMuY'
        },
        llama: {
            imgur: 'Nj46dlb',
            giphy: 'mGWj9gZG7eFCE'
        },
        jason: {
            imgur: 'YTLTpTk',
            giphy: 'l41lZ65JSCJPni7FS'
        },
        kirby: {
            imgur: 'fOit8Na',
            giphy: 'l41lVDy4QPJJApSPS'
        },
        kitty: {
            imgur: 'IOO2VgN',
            giphy: '3oEduKQuAlKRfgRAvS'
        },
        lilguy: {
            imgur: 'wETEb4l',
            giphy: 'l41lI6dIfDLLMsNjy'
        },
        lisa: {
            imgur: 'hf2s0Ej',
            giphy: 'NfeV16w5ZvaaQ'
        },
        maranda: {
            imgur: 'zZrLAyH',
            giphy: '26BkNCYFWc3YrUSFa'
        },
        mj: {
            imgur: 'U0TcBG6',
            giphy: '3oEdv8uVwchZIxkJDG'
        },
        nerd: {
            imgur: 'S5Wo2T1',
            giphy: 'l41lTnsFgDcDFtiPm'
        },
        obama: {
            imgur: 'lKpfbv1',
            giphy: 'l41lSXRKx8csZ1kic'
        },
        orangeguy: {
            imgur: 'rG0HL2S',
            giphy: '3oEduRSQNa8CTeA3iU'
        },
        pa: {
            imgur: 'wzTfl7Z',
            giphy: 'l41lXHizBwZJWoYLK'
        },
        patrick: {
            imgur: 'CgLMqm8',
            giphy: '3oEdv6ocnBsOlAUQfK'
        },
        pedopickle: {
            imgur: 'jRoMC6Y',
            giphy: 'l41m3WCro5TSN7Bp6'
        },
        pikachu: {
            imgur: '3nnb34A',
            giphy: 'zEBHffYMPaIwM'
        },
        pixelly: {
            imgur: 'Qw2O47x',
            giphy: '3oEduPmVVIex3w0Oys'
        },
        ponyshuffle: {
            imgur: '6frE5RS',
            giphy: '3oEduTi5ktbhXp3Rm0'
        },
        possum: {
            imgur: 'lFPmQrS',
            giphy: '3oEduKLDMtc7jleGgU'
        },
        pumpgirl: {
            imgur: 'GD8TggR',
            giphy: 'l41m4R1fgL5jZX1Qc'
        },
        ravecat: {
            imgur: 'KWBLGKg',
            giphy: '3oEduWBjP4utBdgGL6'
        },
        robothump: {
            imgur: 'VZNMx5i',
            giphy: '3oEdv53199cJ6nUhDq'
        },
        roger: {
            imgur: 'JSMQUnh',
            giphy: '3oEdv21WszrucZzBSw'
        },
        runningworm: {
            imgur: '4cDqUCe',
            giphy: '3oEdv2xy5QjqBiSxzO'
        },
        saxguy: {
            imgur: 'E3sRBkX',
            giphy: 'l41lWg4naO0TljUSQ'
        },
        scorpion: {
            imgur: 'dzScRdd',
            giphy: '3oEduNF2afOEDQ4kCY'
        },
        shawty: {
            imgur: 'stZZLVd',
            giphy: '3oEdv0F6sqE5XCWkCc'
        },
        smooch: {
            imgur: 'BeH7q4x',
            giphy: '3oEduTxikdl6659Tws'
        },
        snoop: {
            imgur: 'u82kPtm',
            giphy: 'O0Xo8Tpk5QxTW'
        },
        speakerhead: {
            imgur: '7Hy7lrN',
            giphy: 'l41lTFERkZe2H9FOo'
        },
        leftshark: {
            imgur: 'glPurdO',
            giphy: '3o85xBH1NjrRfa8kPm'
        },
        spongeybob: {
            imgur: '6AXEklV',
            giphy: '3oEduGmM5MJLjciFSU'
        },
        squidword: {
            imgur: 'v9pzZCM',
            giphy: '26BkMz3mtQqMl6Dw4'
        },
        shakeitoff: {
            imgur: '8xbnBRN',
            giphy: '26tP3JkdNpeU1k8Tu'
        },
        tej: {
            imgur: 'Q49aPYo',
            giphy: '3oEduF6VoHOTKkrplu'
        },
        thehop: {
            imgur: '5fmPHBc',
            giphy: '3oEduP8lE334O5KNJS'
        },
        thewizard: {
            imgur: 'FExyzq0',
            giphy: '3oEduP15u1e3duOSE8'
        },
        theworm: {
            imgur: 'Z62jSAr',
            giphy: 'l41m6R0OgDvej2Vag'
        },
        tim: {
            imgur: 'hGXXXDl',
            giphy: 'l41lT8zKKiIRjnM1G'
        },
        twerk: {
            imgur: 'EjL0GLT',
            giphy: 'l41lQZJYzSqGDWFz2'
        },
        whiteguy: {
            imgur: '6jYdEPO',
            giphy: '3oEduKmO22VEzbmpLq'
        },
        yeti: {
            imgur: '4LDzQq6',
            giphy: '3oEduYLrzljc1cGY5a'
        }
    },
    /* Retrieve the Imgur url for the given dancer's thumbnail image */
    getThumbnailUrl: function(dancerName) {
        return "https://imgur.com/" + gdpMedia.mediaIds[dancerName]["imgur"] + ".png";
    },
    /* Retrieve the Giphy url for the given dancer's GIF */
    getGifUrl: function(dancerName) {
        return "https://media.giphy.com/media/" + gdpMedia.mediaIds[dancerName]["giphy"] + "/giphy.gif";
    },
    /* Send a message to the background script to play the song with the
       given name */
    selectSong: function(name, url, isCustom) {
        console.log([name, url, isCustom]);
        chrome.runtime.sendMessage({
            type: "songUrl",
            songUrl: (!isCustom ? gdpMedia.gdpSongMap[name] : url)
        });
    },
    /* Send a message to the background script to stop playing audio */
    stopAudio: function() {
        chrome.runtime.sendMessage({
            type: "stopAudio"
        });
    },
    /* When leaving the current page, send a message to the background script
       to stop playing audio */
    unloadAudio: function() {
        // when leaving the page, be sure to stop the gdp audio
        $(window).unload(function() {
            gdpMedia.stopAudio();
        });
    }
}
<|endoftext|>


<commit_before>var fs = require('fs'),
	path = require('path');

var storage = function(key, value) {
	if (value) {
		window.localStorage[key] = value;
	} else {
		return window.localStorage[key];
	}
};

var defaults = {
	port: {
		type: 'number',
		value: 8888,
		user: true
	},
	basicRule: {
		type: 'object',
		value: {
			beforeRequests: false,
			afterResponses: false
		},
		user: false
	},
	list: {
		type: 'string',
		value: '%50f
Host: %H',
		user: true
	},
	contentLength: {
		type: 'number',
		value: 1024,
		user: true
	},
	editors: {
		type: 'array',
		value: [
			{
				name: '既定',
				value: 'default' // 仮
			}
		],
		user: true
	}
};

var config = function(key, value) {
	if (value !== undefined) {
		saveConfig(key, value);
	} else {
		return getConfig(key);
	}
};

var saveConfig = function(key, value) {
	switch(defaults[key].type) {
	case 'number':
		value = '' + value;
		break;
	case 'boolean':
		value = value === true ? 'true' : 'false';
		break;
	case 'object':
		value = JSON.stringify(value);
		break;
	case 'string':
		value = value.toString();
		break;
	case 'array':
		value = JSON.stringify({
			array: value
		});
		break;
	default:
		break;
	}

	window.localStorage[key] = value;
};

var getConfig = function(key) {
	var val = window.localStorage[key];

	if (val) {
		switch(defaults[key].type) {
		case 'number':
			val = parseInt(val, 10);
			break;
		case 'boolean':
			val = val == 'true' ? true : false;
			break;
		case 'object':
			val = JSON.parse(val);
			break;
		case 'string':
			val = val.toString();
			break;
		case 'array':
			val = JSON.parse(val).array;
			break;
		default:
			break;
		}
	} else {
		val = defaults[key].value;
	}

	return val;
};

var getAllConfig = function() {
	var ret = { };

	for (var key in defaults) {
		ret[key] = defaults[key];
		ret[key].value = getConfig(key);
	}

	return ret;
};

var err = function(str) {
	return function(err) {
		if (err) {
			throw { message: err };
		}
	};
};

var rmdir = function(dirPath) {
	var list = fs.readdirSync(dirPath);

	for (var i=0; i<list.length; i++) {
		var filename = path.join(dirPath, list[i]);
		var stat = fs.statSync(filename);

		if (!(filename == '.' || filename == '..')) {
			fs.unlinkSync(filename);
		}
	}
	fs.rmdirSync(dirPath);
};

var noerr = function(next) {
	return function() {
		var args = Array.prototype.slice.call(arguments);
		args.unshift(null);
		next.apply(null, args);
	};
};

var apply = function(_this, _function) {
	return function() {
		var args = Array.prototype.slice.call(arguments);
		args.unshift(_this);
		_function.apply(null, args);
	};
};

module.exports = exports = {
	storage: storage,
	config: config,
	getAll: getAllConfig,
	err: err,
	rmdir: rmdir,
	noerr: noerr,
	apply: apply,
	empty: function() { }
};<commit_msg>直で表示する最大のサイズを緩和<commit_after>var fs = require('fs'),
	path = require('path');

var storage = function(key, value) {
	if (value) {
		window.localStorage[key] = value;
	} else {
		return window.localStorage[key];
	}
};

var defaults = {
	port: {
		type: 'number',
		value: 8888,
		user: true
	},
	basicRule: {
		type: 'object',
		value: {
			beforeRequests: false,
			afterResponses: false
		},
		user: false
	},
	list: {
		type: 'string',
		value: '%50f
Host: %H',
		user: true
	},
	contentLength: {
		type: 'number',
		value: 1024 * 1024,
		user: true
	},
	editors: {
		type: 'array',
		value: [
			{
				name: '既定',
				value: 'default' // 仮
			}
		],
		user: true
	}
};

var config = function(key, value) {
	if (value !== undefined) {
		saveConfig(key, value);
	} else {
		return getConfig(key);
	}
};

var saveConfig = function(key, value) {
	switch(defaults[key].type) {
	case 'number':
		value = '' + value;
		break;
	case 'boolean':
		value = value === true ? 'true' : 'false';
		break;
	case 'object':
		value = JSON.stringify(value);
		break;
	case 'string':
		value = value.toString();
		break;
	case 'array':
		value = JSON.stringify({
			array: value
		});
		break;
	default:
		break;
	}

	window.localStorage[key] = value;
};

var getConfig = function(key) {
	var val = window.localStorage[key];

	if (val) {
		switch(defaults[key].type) {
		case 'number':
			val = parseInt(val, 10);
			break;
		case 'boolean':
			val = val == 'true' ? true : false;
			break;
		case 'object':
			val = JSON.parse(val);
			break;
		case 'string':
			val = val.toString();
			break;
		case 'array':
			val = JSON.parse(val).array;
			break;
		default:
			break;
		}
	} else {
		val = defaults[key].value;
	}

	return val;
};

var getAllConfig = function() {
	var ret = { };

	for (var key in defaults) {
		ret[key] = defaults[key];
		ret[key].value = getConfig(key);
	}

	return ret;
};

var err = function(str) {
	return function(err) {
		if (err) {
			throw { message: err };
		}
	};
};

var rmdir = function(dirPath) {
	var list = fs.readdirSync(dirPath);

	for (var i=0; i<list.length; i++) {
		var filename = path.join(dirPath, list[i]);
		var stat = fs.statSync(filename);

		if (!(filename == '.' || filename == '..')) {
			fs.unlinkSync(filename);
		}
	}
	fs.rmdirSync(dirPath);
};

var noerr = function(next) {
	return function() {
		var args = Array.prototype.slice.call(arguments);
		args.unshift(null);
		next.apply(null, args);
	};
};

var apply = function(_this, _function) {
	return function() {
		var args = Array.prototype.slice.call(arguments);
		args.unshift(_this);
		_function.apply(null, args);
	};
};

module.exports = exports = {
	storage: storage,
	config: config,
	getAll: getAllConfig,
	err: err,
	rmdir: rmdir,
	noerr: noerr,
	apply: apply,
	empty: function() { }
};<|endoftext|>