<commit_before>'use strict';

const TelegramBot = require('node-telegram-bot-api');
const config = require('../config/config');
const messages = require('../config/messages');
const morningEvent = require('./morning-event');
const blogEvent = require('./blog-event');
const generateRandom = require('./time-utility').generateRandom;
const fetch = require('node-fetch');

const token = config.telegramToken;
const groupId = config.groupId;
const goodMorningRegExp = config.goodMorningRegExp;

let bot = new TelegramBot(token, {polling: true});
let goodMorningGivenToday = false;
let minuteToCheck = generateRandom(0, 59);

bot
  .on('new_chat_participant', newChatParticipant)
  .on('text', newText);

morningEvent
  .on('minuteMark', (vzlanHour, vzlanMinute, weekday) => {
    if (morningConditions(vzlanHour, vzlanMinute)) {
      goodMorningGivenToday = true;
      minuteToCheck = generateRandom(0, 59);
      bot.sendMessage(
        groupId,
        getMorningMsg(weekday)
      );
    }

    function morningConditions(vzlanHour, vzlanMinute) {
      return !goodMorningGivenToday && vzlanHour === config.morningHour
        && vzlanMinute === minuteToCheck;
    }

    function getMorningMsg(weekday) {
      let weekDays = {
        0: 'generic',
        1: 'mondays',
        2: 'generic',
        3: 'generic',
        4: 'generic',
        5: 'fridays',
        6: 'generic',
      };

      let randomIndex = generateRandom(0, messages.goodMornings[weekDays[weekday]].length - 1);
      return messages.goodMornings[weekDays[weekday]][randomIndex];
    }
  })
  .on('newDay', () => {
    goodMorningGivenToday = false;
  });

blogEvent
  .on('newArticles', (articles) => {
    articles.forEach((article) => {
      bot.sendMessage(
        groupId,
        messages.newBlogPost
          .replace('#{author}', article.author)
          .replace('#{link}', article.link)
          .replace('#{title}', article.title),
        {parse_mode: 'Markdown'}
      );
    });
  });

function newText(msg) {
  if (!goodMorningGivenToday && isGoodMorningGiven(msg.text)) {
    goodMorningGivenToday = true;
  }

  function isGoodMorningGiven(text) {
    return goodMorningRegExp.test(text);
  }
}

function newChatParticipant(msg) {
  bot.sendMessage(
    msg.chat.id,
    getFullWelcomeMsg(msg),
    {reply_to_message_id: msg.message_id, parse_mode: 'Markdown'}
  );

  function getFullWelcomeMsg(msg) {
    let nameToBeShown = msg.new_chat_member.first_name;

    if (msg.new_chat_member.username) {
      nameToBeShown = '@' + msg.new_chat_member.username;
    } else if (msg.new_chat_member.hasOwnProperty('last_name')) {
      nameToBeShown = nameToBeShown + ' ' + msg.new_chat_member.last_name;
    }

    return messages.welcomeMsg.replace('#{name}', nameToBeShown);
  }
}

bot.onText(/\/gist (.|\n)*/g, (msg, match) => {
  const chatId = msg.chat.id;

  const filename = `${new Date().toISOString()}.js`;
  const gist = match[0].split(' ')
                       .filter( word => word !== '/gist' )
                       .join(' ');

  console.log(gist);

  const body = {
    'description': 'gist anonimo',
    'public': true,
    'files': {
      [filename]: {
        'content': gist
      }
    }
  };

  fetch('https://api.github.com/gists', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify( body )
  })
  .then(response => response.json())
  .then(({html_url}) => {
    console.log(html_url);

    bot.sendMessage( chatId, html_url );

  }).catch(error => {
    console.warn(error);
  });
});
<commit_msg>(Modifica): Detecta backticks  con evento 'text'<commit_after>'use strict';

const TelegramBot = require('node-telegram-bot-api');
const config = require('../config/config');
const messages = require('../config/messages');
const morningEvent = require('./morning-event');
const blogEvent = require('./blog-event');
const generateRandom = require('./time-utility').generateRandom;
const fetch = require('node-fetch');

const token = config.telegramToken;
const groupId = config.groupId;
const goodMorningRegExp = config.goodMorningRegExp;

let bot = new TelegramBot(token, {polling: true});
let goodMorningGivenToday = false;
let minuteToCheck = generateRandom(0, 59);

bot
  .on('new_chat_participant', newChatParticipant)
  .on('text', newText);

morningEvent
  .on('minuteMark', (vzlanHour, vzlanMinute, weekday) => {
    if (morningConditions(vzlanHour, vzlanMinute)) {
      goodMorningGivenToday = true;
      minuteToCheck = generateRandom(0, 59);
      bot.sendMessage(
        groupId,
        getMorningMsg(weekday)
      );
    }

    function morningConditions(vzlanHour, vzlanMinute) {
      return !goodMorningGivenToday && vzlanHour === config.morningHour
        && vzlanMinute === minuteToCheck;
    }

    function getMorningMsg(weekday) {
      let weekDays = {
        0: 'generic',
        1: 'mondays',
        2: 'generic',
        3: 'generic',
        4: 'generic',
        5: 'fridays',
        6: 'generic',
      };

      let randomIndex = generateRandom(0, messages.goodMornings[weekDays[weekday]].length - 1);
      return messages.goodMornings[weekDays[weekday]][randomIndex];
    }
  })
  .on('newDay', () => {
    goodMorningGivenToday = false;
  });

blogEvent
  .on('newArticles', (articles) => {
    articles.forEach((article) => {
      bot.sendMessage(
        groupId,
        messages.newBlogPost
          .replace('#{author}', article.author)
          .replace('#{link}', article.link)
          .replace('#{title}', article.title),
        {parse_mode: 'Markdown'}
      );
    });
  });

function newText(msg) {
  if (!goodMorningGivenToday && isGoodMorningGiven(msg.text)) {
    goodMorningGivenToday = true;
  }

  function isGoodMorningGiven(text) {
    return goodMorningRegExp.test(text);
  }
}

function newChatParticipant(msg) {
  bot.sendMessage(
    msg.chat.id,
    getFullWelcomeMsg(msg),
    {reply_to_message_id: msg.message_id, parse_mode: 'Markdown'}
  );

  function getFullWelcomeMsg(msg) {
    let nameToBeShown = msg.new_chat_member.first_name;

    if (msg.new_chat_member.username) {
      nameToBeShown = '@' + msg.new_chat_member.username;
    } else if (msg.new_chat_member.hasOwnProperty('last_name')) {
      nameToBeShown = nameToBeShown + ' ' + msg.new_chat_member.last_name;
    }

    return messages.welcomeMsg.replace('#{name}', nameToBeShown);
  }
}

bot.on('text', (msg) => {
  const chatId = msg.chat.id;
  console.log(msg);

  if( msg.entities[0].type !== 'pre' ) {
    return;
  }

  const filename = `${new Date().toISOString()}.js`;
  const gist = msg.text;

  console.log(gist);

  const body = {
    'description': 'gist anonimo',
    'public': true,
    'files': {
      [filename]: {
        'content': gist
      }
    }
  };

  fetch('https://api.github.com/gists', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify( body )
  })
  .then(response => response.json())
  .then(({html_url}) => {
    console.log(html_url);

    bot.sendMessage( chatId, html_url );

  }).catch(error => {
    console.warn(error);
  });
});
<|endoftext|>


<commit_before>//jshint node:true
/*global describe, it*/
"use strict";

var expect = require('chai').expect;
var esformatter = require('../lib/esformatter');

describe('API', function() {

  describe('exposed API', function() {
    // plugins might need to access some internal methods from esformatter
    // so we check if these methods are really available
    var limit = require('../lib/limit');
    var options = require('../lib/options');

    it('shoud expose useful methods to plugin authors', function() {
      // we don't need to check implementation here since these methods are
      // used internally
      expect(limit.before).to.be.a('function');
      expect(limit.after).to.be.a('function');
      expect(limit.around).to.be.a('function');
      expect(options.set).to.be.a('function');
      expect(options.get).to.be.a('function');
      expect(options.getRc).to.be.a('function');
      expect(options.loadAndParseConfig).to.be.a('function');
      expect(esformatter.rc).to.be.a('function');
    });
  });

  describe('esformatter.rc', function() {
    // PS: CLI is already testing this method indirectly, we are only checking
    // for edge cases for now

    it('should return custom options if root == true', function() {
      expect(
        esformatter.rc(null, {root:true})
      ).to.be.eql({root:true});
    });

    it('should return custom options if preset', function() {
      expect(
        esformatter.rc(null, {preset:'default'})
      ).to.be.eql({preset:'default'});
    });

    it('should merge the custom option', function() {
      var customOpts = {
        whiteSpace: {
          before: {
            "ArrayExpressionClosing" : 1
          },
          after: {
            "ArrayExpressionOpening" : 1
          }
        }
      };
      var result = esformatter.rc('test/compare/rc/top-in.js', customOpts);
      expect(result.whiteSpace.before.FunctionDeclarationOpeningBrace).to.be.eql(0);
      expect(result.whiteSpace.before.ArrayExpressionClosing).to.be.eql(1);
      expect(result.whiteSpace.after.ArrayExpressionOpening).to.be.eql(1);
    });

    it('should merge rcs from parent folder', function() {
      var result = esformatter.rc('test/compare/rc/nested/nested-in.js');
      expect(result.indent.value).to.be.eql('\t');
      expect(result.whiteSpace.before.FunctionDeclarationOpeningBrace).to.be.eql(0);
    });

    it('should merge .esformatter and package.json files', function() {
      var result = esformatter.rc('test/compare/rc/package/nested/pkg_nested-in.js');
      expect(result.indent.value).to.be.eql('\t');
      expect(result.lineBreak.before.FunctionDeclarationOpeningBrace).to.be.eql(1);
      expect(result.lineBreak.before.FunctionDeclarationClosingBrace).to.be.eql(0);
    });
  });
});
<commit_msg>check more functions on the API test<commit_after>//jshint node:true
/*global describe, it*/
"use strict";

var expect = require('chai').expect;
var esformatter = require('../lib/esformatter');

describe('API', function() {

  describe('exposed API', function() {
    // plugins might need to access some internal methods from esformatter
    // so we check if these methods are really available
    var limit = require('../lib/limit');
    var options = require('../lib/options');

    it('shoud expose useful methods to plugin authors', function() {
      // we don't need to check implementation here since these methods are
      // used internally
      expect(limit.before).to.be.a('function');
      expect(limit.after).to.be.a('function');
      expect(limit.around).to.be.a('function');
      expect(options.set).to.be.a('function');
      expect(options.get).to.be.a('function');
      expect(options.getRc).to.be.a('function');
      expect(options.loadAndParseConfig).to.be.a('function');
      expect(esformatter.diff.chars).to.be.a('function');
      expect(esformatter.hooks.FunctionExpression.format).to.be.a('function');
      expect(esformatter.format).to.be.a('function');
      expect(esformatter.transform).to.be.a('function');
      expect(esformatter.rc).to.be.a('function');
      expect(esformatter.register).to.be.a('function');
      expect(esformatter.unregister).to.be.a('function');
      expect(esformatter.unregisterAll).to.be.a('function');
    });
  });

  describe('esformatter.rc', function() {
    // PS: CLI is already testing this method indirectly, we are only checking
    // for edge cases for now

    it('should return custom options if root == true', function() {
      expect(
        esformatter.rc(null, {root:true})
      ).to.be.eql({root:true});
    });

    it('should return custom options if preset', function() {
      expect(
        esformatter.rc(null, {preset:'default'})
      ).to.be.eql({preset:'default'});
    });

    it('should merge the custom option', function() {
      var customOpts = {
        whiteSpace: {
          before: {
            "ArrayExpressionClosing" : 1
          },
          after: {
            "ArrayExpressionOpening" : 1
          }
        }
      };
      var result = esformatter.rc('test/compare/rc/top-in.js', customOpts);
      expect(result.whiteSpace.before.FunctionDeclarationOpeningBrace).to.be.eql(0);
      expect(result.whiteSpace.before.ArrayExpressionClosing).to.be.eql(1);
      expect(result.whiteSpace.after.ArrayExpressionOpening).to.be.eql(1);
    });

    it('should merge rcs from parent folder', function() {
      var result = esformatter.rc('test/compare/rc/nested/nested-in.js');
      expect(result.indent.value).to.be.eql('\t');
      expect(result.whiteSpace.before.FunctionDeclarationOpeningBrace).to.be.eql(0);
    });

    it('should merge .esformatter and package.json files', function() {
      var result = esformatter.rc('test/compare/rc/package/nested/pkg_nested-in.js');
      expect(result.indent.value).to.be.eql('\t');
      expect(result.lineBreak.before.FunctionDeclarationOpeningBrace).to.be.eql(1);
      expect(result.lineBreak.before.FunctionDeclarationClosingBrace).to.be.eql(0);
    });
  });
});
<|endoftext|>


<commit_before>import ConnectedRouter from './component'
import routerMiddleware from './middleware'
import routerReducer from './reducer'
import {
  locationChange,
  router,
  setLocation,
  LOCATION_CHANGE,
  ROUTER_ACTION
} from './actions'

export {
  ConnectedRouter,
  locationChange,
  router,
  setLocation,
  routerMiddleware,
  routerReducer,
  LOCATION_CHANGE,
  ROUTER_ACTION
}
<commit_msg>Optimize modules exporting<commit_after>export { default as ConnectedRouter } from './component'
export { default as routerMiddleware } from './middleware'
export { default as routerReducer } from './reducer'
export { locationChange, router, setLocation, LOCATION_CHANGE, ROUTER_ACTION } from './actions'
<|endoftext|>


<commit_before>/**
 * Created by obzerg on 16/1/5.
 */
var should = require('should');
var Yhsd = require('../index');

describe('test/api.test.js', function () {
    var api;
    before(function () {
        api = new Yhsd.Api('fbc7f83524f14e358a325a5066acd741');
    });

    it('get api instance should throw error', function () {
        (function () {
            new Yhsd.Api()
        }).should.throw('缺少参数');
    });

    it('http get should be throw error', function () {
        (function () {
            api.get()
        }).should.throw('缺少参数');
    });

    it('http get should be success', function (done) {
        api.get('products', {fields: 'id'}, function (err, body) {
            should.not.exist(err);
            should.exist(body);
            done();
            //13576
        })
    });

    it('http put should be throw error', function () {
        (function () {
            api.put()
        }).should.throw('缺少参数');
    });

    it('http put should be success', function (done) {
        api.put('themes/13576', {"theme": {"name": "测试主题"}}, function (err, body) {
            should.not.exist(err);
            should.exist(body);
            done();
            //13576
        })
    });

    it('http post should be throw error', function () {
        (function () {
            api.post()
        }).should.throw('缺少参数');
    });

    it('http post should be success', function (done) {
        var obj = {
            meta: {
                name: new Date().getTime() + '',
                owner_id: '0',
                owner_resource: 'shop',
                fields: {'test': 'test'},
                descriptions: 'test'
            }
        };
        api.post('metas', obj, function (err, body) {
            should.not.exist(err);
            should.exist(body);
            var id = body.meta.id;
            api.delete('metas/' + id, function (err) {
                should.not.exist(err);
                done();
            })
        })
    });

    it('http delete should be throw error', function () {
        (function () {
            api.delete()
        }).should.throw('缺少参数');
    });

    it('http delete should be success', function (done) {
        var obj = {
            meta: {
                name: new Date().getTime() + '',
                owner_id: '0',
                owner_resource: 'shop',
                fields: {'test': 'test'},
                descriptions: 'test'
            }
        };
        api.post('metas', obj, function (err, body) {
            should.not.exist(err);
            should.exist(body);
            var id = body.meta.id;
            api.delete('metas/' + id, function (err) {
                should.not.exist(err);
                done();
            })
        })
    });

    it('api should be return error code 404', function (done) {
        api.get('12345', function (err, body) {
            err.code.should.equal(404);
            done();
        })
    });

    it('api should be throw ENOTFOUND error', function (done) {
        Yhsd.config.apiHost = 'localhost:32876';
        Yhsd.config.appHost = 'localhost:32876';
        Yhsd.config.httpProtocol = 'http';
        api.get('products',function (err, token) {
          if (err){
            // console.log(err.message);
            var eResult = err.message.indexOf('ENOTFOUND');
            if (eResult > 0) {
              (eResult).should.be.ok();
              done();
              return;
            }
          }
          console.log(token);
          done(new Error('没有捕捉到错误!'));
        });
    });

    //it('api should be return error code 429', function (done) {
    //    var total = 0;
    //    function _request() {
    //        var index = 0;
    //        api.get('shop', function (err, body) {
    //            ++index;
    //            if(index == 3) round()
    //        });
    //        api.get('shop', function (err, body) {
    //            ++index;
    //            if(index == 3) round()
    //
    //        });
    //        api.get('shop', function (err, body) {
    //            ++index;
    //            if(index == 3) round()
    //        });
    //    }
    //    function round(){
    //        total++;
    //        if(total < 20){
    //            setTimeout(_request,1000);
    //        } else {
    //            done();
    //        }
    //    }
    //    _request();
    //});
});

<commit_msg>更新 api.test.js；<commit_after>/**
 * Created by obzerg on 16/1/5.
 */
var should = require('should');
var Yhsd = require('../index');

describe('test/api.test.js', function () {
  var api;
  before(function () {
    api = new Yhsd.Api('5e242b4b41d14a2d8f4d80a9c6b05bea');
  });

  it('get api instance should throw error', function () {
    (function () {
      new Yhsd.Api();
    }).should.throw('缺少参数');
  });

  it('http get should be throw error', function () {
    (function () {
      api.get();
    }).should.throw('缺少参数');
  });

  it('http get should be success', function (done) {
    api.get('products', { fields: 'id' }).then(function (body) {
      should.exist(body);
      done();
      //13576
    });
  });

  it('http put should be throw error', function () {
    (function () {
      api.put();
    }).should.throw('缺少参数');
  });

  it('http put should be success', function (done) {
    api.put('themes/13576', { "theme": { "name": "测试主题" } }).then(function (body) {
      should.exist(body);
      done();
      //13576
    });
  });

  it('http post should be throw error', function () {
    (function () {
      api.post();
    }).should.throw('缺少参数');
  });

  it('http post should be success', function (done) {
    var obj = {
      meta: {
        name: new Date().getTime() + '',
        owner_id: '0',
        owner_resource: 'shop',
        fields: { 'test': 'test' },
        descriptions: 'test'
      }
    };
    api.post('metas', obj).then(function (body) {
      should.exist(body);
      var id = body.meta.id;
      api.delete('metas/' + id).then(function (body) {
        should.exist(body);
        done();
      });
    });
  });

  it('http delete should be throw error', function () {
    (function () {
      api.delete();
    }).should.throw('缺少参数');
  });

  it('http delete should be success', function (done) {
    var obj = {
      meta: {
        name: new Date().getTime() + '',
        owner_id: '0',
        owner_resource: 'shop',
        fields: { 'test': 'test' },
        descriptions: 'test'
      }
    };
    api.post('metas', obj).then(function (body) {
      should.exist(body);
      var id = body.meta.id;
      api.delete('metas/' + id).then(function (body) {
        should.exist(body);
        done();
      });
    });
  });

  it('api should be return error code 404', function (done) {
    api.get('12345').then(function (body) {
      body.code.should.equal(404);
      done();
    });
  });

  it('api should be throw ENOTFOUND error', function (done) {
    Yhsd.config.apiHost = 'localhost:32876';
    Yhsd.config.appHost = 'localhost:32876';
    Yhsd.config.httpProtocol = 'http';
    api.get('products').then(function (body) {
      console.log(body);
      should.not.exist(body);
      done(new Error('没有捕捉到错误!'));
    }).catch(function (err) {
      // console.log(err.message);
      var eResult = err.message.indexOf('ENOTFOUND');
      if (eResult > 0) {
        (eResult).should.be.ok();
        done();
        return;
      }
    });
  });
});

<|endoftext|>


<commit_before>'use strict';

import createError from 'http-errors';

export default function (req, res, next) {
  const auth = req.get('authorization');

  if (!auth) {
    return res.status(401).set('WWW-Authenticate', 'Negotiate');
  }

  if (auth.lastIndexOf('Negotiate') !== 0) {
    return next(createError(400, `Malformed authentication token ${auth}`));
  }

  req.auth = req.auth || {};
  req.auth.token = auth.substring('Negotiate '.length);

  next();
}
<commit_msg>change api<commit_after>'use strict';

import createError from 'http-errors';

export default () => {
  return (req, res, next) => {
    const auth = req.get('authorization');

    if (!auth) {
      return res.status(401).set('WWW-Authenticate', 'Negotiate').end();
    }

    if (auth.lastIndexOf('Negotiate') !== 0) {
      return next(createError(400, `Malformed authentication token ${auth}`));
    }

    req.auth = req.auth || {};
    req.auth.token = auth.substring('Negotiate '.length);

    next();
  };
};
<|endoftext|>


<commit_before>/* ©Copyright Utrecht University (Department of Information and Computing Sciences) */

/*
    This file contains all functionality pertaining to the mini map shown in the upper right corner in the editor
*/

var MiniMap;

(function()
{
    "use strict";

    var zoom = 1,
        // Show details? Set to false to speed up editor processing in large scenarios
        detailed = true;

    MiniMap =
    {
        zoom: zoom,
        detailed: detailed,
        initialise: initialise,
        attachScrollListener: attachScrollListener,
        update: update,
        activate: activate,
        deactivate: deactivate
    };

    // Turned on for this session? (based on e.g. browser)
    var enabled = true,
    // Allowed by the context? If not, hidden completely, including controls
    active = true,
    // Turned on by the user? If not, hidden, but controls are still visible
    shown = false;

    function initialise()
    {
        recallShown();
        if (!shown)
        {
            $("#minimap").hide();
            $("#enableMinimap").prop("checked", false);
        }

        $("#miniwrap").css("display","block");
        $("#minimap").css("width", "300px");
        $("#minimap").css("height", "300px");
        $("#minimap").css("overflow", "hidden");

        $("#minimap").on("click", function(e)
        {
            updateScrollPosition(e);
        });
        $("#mainCell #main").on("scroll", function()
        {
            update(false);
        });

        // Zoomed in scroll event listeners for minimap are created by attachScrollListener,
        // called by createEmptyTree()!

        // Listeners for minimap checkboxes
        $("#enableMinimap").on("click", function()
        {
            if (this.checked)
            {
                setAndStoreShown(true);
                update(true);
                showAnimated($("#minimap"));
            }
            else
            {
                hideAnimated($("#minimap"));
                setAndStoreShown(false);
            }
        });
        $("#simpleMinimap").on("click", function()
        {
            if (this.checked)
            {
                detailed = false;
                $("#scaledDiv").empty();
                update(false);
            }
            else
            {
                detailed = true;
                update(true);
            }
        });
    }

    function attachScrollListener(treeDiv)
    {
        if (!enabled) return;

        treeDiv.on('scroll', function(e)
        {
            update(false);
        });
    }

    function updateScrollPosition(e)
    {
        var minimapSelectorX = e.pageX - $("#minimap").offset().left - $("#minimapSelector").width() / 2;
        var minimapSelectorY = e.pageY - $("#minimap").offset().top - $("#minimapSelector").height() / 2;

        // Limit the minimum/maximum positions of the selector
        var maxX = $("#minimap").width() - $("#minimapSelector").width();
        var maxY = $("#minimap").height() - $("#minimapSelector").height();
        if (minimapSelectorX < 0) minimapSelectorX = 0;
        if (minimapSelectorY < 0) minimapSelectorY = 0;
        if (minimapSelectorX > maxX) minimapSelectorX = maxX;
        if (minimapSelectorY > maxY) minimapSelectorY = maxY;

        $("#minimapSelector").css("top", minimapSelectorY+"px");
        $("#minimapSelector").css("left", minimapSelectorX+"px");

        minimapSelectorX /= zoom;
        minimapSelectorY /= zoom;

        if (!Zoom.isZoomed())   // Nothing is zoomed
        {
            $("#mainCell > #main").scrollLeft(minimapSelectorX);
            $("#mainCell > #main").scrollTop(minimapSelectorY);
        }
        else
        {
            $("#mainCell .treeContainer.zoom > .treeDiv").scrollLeft(minimapSelectorX);
            $("#mainCell .treeContainer.zoom > .treeDiv").scrollTop(minimapSelectorY);
        }

        update(false);
    }

    // Scale the minimap according to the main div dimensions
    // and optionally refresh the map by cloning the main div
    function update(refresh)
    {
        if (!(enabled && active && shown)) return;

        var realWidth, realHeight;
        var viewportWidth, viewportHeight, viewportX, viewportY, zoomFactor;

        var main = $("#mainCell > #main");

        if (!Zoom.isZoomed())   // Nothing is zoomed
        {
            realWidth = main[0].scrollWidth;
            realHeight = main[0].scrollHeight;
            viewportX = main.scrollLeft();
            viewportY = main.scrollTop();
            viewportWidth = main[0].clientWidth;
            viewportHeight = main[0].clientHeight;
        }
        else
        {
            var treeDiv = $("#mainCell .treeContainer.zoom .treeDiv");
            realWidth = treeDiv[0].scrollWidth;
            realHeight = treeDiv[0].scrollHeight + $("#mainCell .subjectDiv")[0].scrollHeight;
            viewportX = treeDiv.scrollLeft();
            viewportY = treeDiv.scrollTop() + $("#mainCell .subjectDiv")[0].scrollHeight;
            viewportWidth = treeDiv[0].clientWidth;
            viewportHeight = treeDiv[0].clientHeight;
        }

        $("#scaledDiv").css("width", realWidth+"px");
        $("#scaledDiv").css("height", realHeight+"px");

        // Show a cloned and scaled down version of the main div in the minimap
        if (detailed && refresh)
        {
            $("#scaledDiv").empty();
            var clonedMain = main.clone();
            // Remove inappropriate elements from the cloned main
            clonedMain.find("#gridIndicator").remove();
            if (Zoom.isZoomed()) clonedMain.find(".treeContainer").not(".zoom").remove();
            else clonedMain.find(".treeDiv").remove();
            // Remove all event handlers and IDs from the cloned main
            clonedMain.find("*").addBack().off().removeAttr("id");
            $("#scaledDiv").append(clonedMain);
        }

        // Standard width/height for minimap container
        var width = 300;
        var widthFactor = width / realWidth;

        zoomFactor = widthFactor;
        // minimap gets taller than the allowed screenheight
        if (zoomFactor * realHeight > $("#sidebar").height())
        {
            zoomFactor = $("#sidebar").height()/(realHeight+realHeight*0.1);
        }

        var minimapSize = {
            width: realWidth * zoomFactor + "px",
            height: realHeight * zoomFactor + "px"
        };
        $("#minimap").css(minimapSize);
        $("#minimap").data("savedSize", minimapSize);

        if (detailed && refresh)
        {
            $("#scaledDiv .treeContainer.zoom").css("left", 0 + "px");
            $("#scaledDiv .treeContainer.zoom").css("top", 0 + "px");
            $("#scaledDiv .treeContainer.zoom > .treeDiv").css("height", realHeight + "px");
            $("#scaledDiv .treeContainer.zoom > .treeDiv").css("width", realWidth + "px");
        }

        $("#scaledDiv").css({
            transform: "scale(" + zoomFactor + ")",
            transformOrigin: "top left"
        });

        // Scale and reposition the minimap selector
        $("#minimapSelector").css({
            width: viewportWidth * zoomFactor + "px",
            height: viewportHeight * zoomFactor + "px",
            top: viewportY * zoomFactor + "px",
            left: viewportX * zoomFactor + "px"
        });

        zoom = zoomFactor;
    }

    function recallShown()
    {
        var recalledShown = localStorage.getItem('MiniMap.shown');
        if (recalledShown !== null) shown = Boolean(JSON.parse(recalledShown));
    }

    function setAndStoreShown(newShown)
    {
        shown = Boolean(newShown);
        try
        {
            localStorage.setItem('MiniMap.shown', JSON.stringify(shown));
        }
        catch (e)
        {
            // storage is an enhancement, so ignore failure
        }
    }

    function showAnimated(element)
    {
        // slide Down with animation stopper
        var savedSize = element.data('savedSize');
        var finalHeight = savedSize ? savedSize.height : element.css('height', 'auto').height();
        element.height(0).show().stop(true,false).animate({height: finalHeight}, 400);
    }

    function hideAnimated(element)
    {
        // slide Up with animation stopper
        element.stop(true,false).animate({height: 0}, 400,
            'swing', function(){ element.hide(); });
    }

    function activate()
    {
        if (!enabled) return;

        if (!active) showAnimated($("#miniwrap"));
        active = true;
        update(true);
    }

    function deactivate()
    {
        if (!enabled) return;

        if (active) hideAnimated($("#miniwrap"));
        active = false;
    }
})();
<commit_msg>Fixed minimap click behaviour<commit_after>/* ©Copyright Utrecht University (Department of Information and Computing Sciences) */

/*
    This file contains all functionality pertaining to the mini map shown in the upper right corner in the editor
*/

var MiniMap;

(function()
{
    "use strict";

    var zoom = 1,
        // Show details? Set to false to speed up editor processing in large scenarios
        detailed = true;

    MiniMap =
    {
        zoom: zoom,
        detailed: detailed,
        initialise: initialise,
        attachScrollListener: attachScrollListener,
        update: update,
        activate: activate,
        deactivate: deactivate
    };

    // Turned on for this session? (based on e.g. browser)
    var enabled = true,
    // Allowed by the context? If not, hidden completely, including controls
    active = true,
    // Turned on by the user? If not, hidden, but controls are still visible
    shown = false;

    function initialise()
    {
        recallShown();
        if (!shown)
        {
            $("#minimap").hide();
            $("#enableMinimap").prop("checked", false);
        }

        $("#miniwrap").css("display","block");
        $("#minimap").css("width", "300px");
        $("#minimap").css("height", "300px");
        $("#minimap").css("overflow", "hidden");

        $("#minimap").on("click", function(e)
        {
            updateScrollPosition(e);
        });
        $("#mainCell #main").on("scroll", function()
        {
            update(false);
        });

        // Zoomed in scroll event listeners for minimap are created by attachScrollListener,
        // called by createEmptyTree()!

        // Listeners for minimap checkboxes
        $("#enableMinimap").on("click", function()
        {
            if (this.checked)
            {
                setAndStoreShown(true);
                update(true);
                showAnimated($("#minimap"));
            }
            else
            {
                hideAnimated($("#minimap"));
                setAndStoreShown(false);
            }
        });
        $("#simpleMinimap").on("click", function()
        {
            if (this.checked)
            {
                detailed = false;
                $("#scaledDiv").empty();
                update(false);
            }
            else
            {
                detailed = true;
                update(true);
            }
        });
    }

    function attachScrollListener(treeDiv)
    {
        if (!enabled) return;

        treeDiv.on('scroll', function(e)
        {
            update(false);
        });
    }

    function updateScrollPosition(e)
    {
        var minimapSelectorX = e.pageX - $("#minimap").offset().left - $("#minimapSelector").width() / 2;
        var minimapSelectorY = e.pageY - $("#minimap").offset().top - $("#minimapSelector").height() / 2;

        // Limit the minimum/maximum positions of the selector
        var maxX = $("#minimap").width() - $("#minimapSelector").width();
        var maxY = $("#minimap").height() - $("#minimapSelector").height();
        if (minimapSelectorX < 0) minimapSelectorX = 0;
        if (minimapSelectorY < 0) minimapSelectorY = 0;
        if (minimapSelectorX > maxX) minimapSelectorX = maxX;
        if (minimapSelectorY > maxY) minimapSelectorY = maxY;

        $("#minimapSelector").css("top", minimapSelectorY+"px");
        $("#minimapSelector").css("left", minimapSelectorX+"px");

        minimapSelectorX /= zoom;
        minimapSelectorY /= zoom;

        if (!Zoom.isZoomed())   // Nothing is zoomed
        {
            $("#mainCell > #main").scrollLeft(minimapSelectorX);
            $("#mainCell > #main").scrollTop(minimapSelectorY);
        }
        else
        {
            $("#mainCell .treeContainer.zoom .treeDiv").scrollLeft(minimapSelectorX);
            $("#mainCell .treeContainer.zoom .treeDiv").scrollTop(minimapSelectorY);
        }

        update(false);
    }

    // Scale the minimap according to the main div dimensions
    // and optionally refresh the map by cloning the main div
    function update(refresh)
    {
        if (!(enabled && active && shown)) return;

        var realWidth, realHeight;
        var viewportWidth, viewportHeight, viewportX, viewportY, zoomFactor;

        var main = $("#mainCell > #main");

        if (!Zoom.isZoomed())   // Nothing is zoomed
        {
            realWidth = main[0].scrollWidth;
            realHeight = main[0].scrollHeight;
            viewportX = main.scrollLeft();
            viewportY = main.scrollTop();
            viewportWidth = main[0].clientWidth;
            viewportHeight = main[0].clientHeight;
        }
        else
        {
            var treeDiv = $("#mainCell .treeContainer.zoom .treeDiv");
            realWidth = treeDiv[0].scrollWidth;
            realHeight = treeDiv[0].scrollHeight + $("#mainCell .subjectDiv")[0].scrollHeight;
            viewportX = treeDiv.scrollLeft();
            viewportY = treeDiv.scrollTop() + $("#mainCell .subjectDiv")[0].scrollHeight;
            viewportWidth = treeDiv[0].clientWidth;
            viewportHeight = treeDiv[0].clientHeight;
        }

        $("#scaledDiv").css("width", realWidth+"px");
        $("#scaledDiv").css("height", realHeight+"px");

        // Show a cloned and scaled down version of the main div in the minimap
        if (detailed && refresh)
        {
            $("#scaledDiv").empty();
            var clonedMain = main.clone();
            // Remove inappropriate elements from the cloned main
            clonedMain.find("#gridIndicator").remove();
            if (Zoom.isZoomed()) clonedMain.find(".treeContainer").not(".zoom").remove();
            else clonedMain.find(".treeDiv").remove();
            // Remove all event handlers and IDs from the cloned main
            clonedMain.find("*").addBack().off().removeAttr("id");
            $("#scaledDiv").append(clonedMain);
        }

        // Standard width/height for minimap container
        var width = 300;
        var widthFactor = width / realWidth;

        zoomFactor = widthFactor;
        // minimap gets taller than the allowed screenheight
        if (zoomFactor * realHeight > $("#sidebar").height())
        {
            zoomFactor = $("#sidebar").height()/(realHeight+realHeight*0.1);
        }

        var minimapSize = {
            width: realWidth * zoomFactor + "px",
            height: realHeight * zoomFactor + "px"
        };
        $("#minimap").css(minimapSize);
        $("#minimap").data("savedSize", minimapSize);

        if (detailed && refresh)
        {
            $("#scaledDiv .treeContainer.zoom").css("left", 0 + "px");
            $("#scaledDiv .treeContainer.zoom").css("top", 0 + "px");
            $("#scaledDiv .treeContainer.zoom .treeDiv").css("height", realHeight + "px");
            $("#scaledDiv .treeContainer.zoom .treeDiv").css("width", realWidth + "px");
        }

        $("#scaledDiv").css({
            transform: "scale(" + zoomFactor + ")",
            transformOrigin: "top left"
        });

        // Scale and reposition the minimap selector
        $("#minimapSelector").css({
            width: viewportWidth * zoomFactor + "px",
            height: viewportHeight * zoomFactor + "px",
            top: viewportY * zoomFactor + "px",
            left: viewportX * zoomFactor + "px"
        });

        zoom = zoomFactor;
    }

    function recallShown()
    {
        var recalledShown = localStorage.getItem('MiniMap.shown');
        if (recalledShown !== null) shown = Boolean(JSON.parse(recalledShown));
    }

    function setAndStoreShown(newShown)
    {
        shown = Boolean(newShown);
        try
        {
            localStorage.setItem('MiniMap.shown', JSON.stringify(shown));
        }
        catch (e)
        {
            // storage is an enhancement, so ignore failure
        }
    }

    function showAnimated(element)
    {
        // slide Down with animation stopper
        var savedSize = element.data('savedSize');
        var finalHeight = savedSize ? savedSize.height : element.css('height', 'auto').height();
        element.height(0).show().stop(true,false).animate({height: finalHeight}, 400);
    }

    function hideAnimated(element)
    {
        // slide Up with animation stopper
        element.stop(true,false).animate({height: 0}, 400,
            'swing', function(){ element.hide(); });
    }

    function activate()
    {
        if (!enabled) return;

        if (!active) showAnimated($("#miniwrap"));
        active = true;
        update(true);
    }

    function deactivate()
    {
        if (!enabled) return;

        if (active) hideAnimated($("#miniwrap"));
        active = false;
    }
})();
<|endoftext|>


<commit_before>/* global beforeEach, describe, it, expect */

const { app, html } = require("../hx")

function fireDOMLoaded() {
  const event = document.createEvent("Event")
  event.initEvent("DOMContentLoaded", true, true)
  window.document.dispatchEvent(event)
}

function firePopState() {
  const event = document.createEvent("Event")
  event.initEvent("popstate", true, true)
  window.document.dispatchEvent(event)
}

beforeEach(() => {
  document.body.innerHTML = ''
})

describe("App", () => {

  it("boots with no bugs", () => {
    app({ model: {}, view: () => (html`<div>Hi</div>`) })
  })

  it("renders a model", () => {
    const model = {
      world: "world"
    }

    const view = (model) => html`<div id="test-me">${model.world}</div>`

    app({ model, view })

    expect(document.getElementById("test-me").innerHTML).toEqual(model.world)
  })

  it("renders a model with a loop", () => {
    const model = {
      loop: [
        "string1",
        "string2"
      ]
    }

    const view = model =>
      html`<div>${model.loop.map(value => html`
${value}
`)}</div>`

    app({ model, view })

    expect(document.getElementsByTagName("p").length).toEqual(model.loop.length)
  })

  it("renders svg", () => {
    const model = {
      text: "zelda"
    }

    const view = model =>
      html`<svg><text>${model.text}</text></svg>`

    app({ model, view })

    expect(document.getElementsByTagName("svg").length).toEqual(1)
    expect(document.getElementsByTagName("svg")[0].namespaceURI).toEqual("http://www.w3.org/2000/svg")
    expect(document.getElementsByTagName("text")[0].innerHTML).toEqual(model.text)
  })

  it("exec's a render when the update changes", () => {
    const firstValue = 'first-value'
    const secondValue = 'second-value'

    const model = firstValue

    const view = (model, update) => html`<div><input oninput=${e => update.fire(e.target.value)} value=${model}/><p>${model}</p></div>`

    const update = { fire: (_, value) => value }

    app({ model, view, update })

    const input = document.getElementsByTagName('input')[0];

    expect(input.value).toEqual(firstValue)

    const evnt = new Event('input', {bubbles:true});
    input.value = secondValue;
    input.dispatchEvent(evnt);

    expect(input.value).toEqual(secondValue)
    expect(document.getElementsByTagName('p')[0].innerHTML).toEqual(secondValue)
  });
})

describe("Subscriptions", () => {

  it("fires all subscriptions when DOM is ready", () => {
    const check = {}

    app({
      view: () => html`<div>View</div>`,
      subs: [
        () => { check["one"] = true },
        () => { check["two"] = true }
      ]
    })

    fireDOMLoaded()

    expect(check["one"]).toBe(true)
    expect(check["two"]).toBe(true)
  })
})

describe("Hooks", () => {
  const model = 0

  const view = (model) => html`<div>${model}</div>`

  const update = { add: (model, data) => model + data }

  const subs = [(_, msg) => msg.add(2)]

  it("fires onUpdate when the model is updated", () => {
    const guard = null

    const hooks = {
      onUpdate: (prev, model) => { guard = { prev, model } }
    }

    app({ model, view, update, subs, hooks })

    fireDOMLoaded()

    expect(guard).toEqual({ model: 2, prev: 0 })
  })

  it("fires onAction when a reducer is dispatched", () => {
    const guard = null

    const hooks = {
      onAction: (name, data) => { guard = { name, data } }
    }

    app({ model, view, update, subs, hooks })

    fireDOMLoaded()

    expect(guard).toEqual({ name: "add", data: 2 })
  })

  it("fires onAction when an effect is dispatched", () => {
    const guard = null

    const effectDone = false

    const hooks = {
      onAction: (name, data) => { guard = { name, data } }
    }

    const effects = {
      add: () => { effectDone = true }
    }

    app({ model, view, effects, subs, hooks })

    fireDOMLoaded()

    expect(effectDone).toBe(true)
    expect(guard).toEqual({ name: "add", data: 2 })
  })

  it("fires onError when a effect fails", () => {
    const guard = null

    const hooks = {
      onError: (err) => { guard = err }
    }

    const effects = {
      add: (model, msg, data, error) => { error("effect error") }
    }

    app({ model, view, effects, subs, hooks })

    fireDOMLoaded()

    expect(guard).toEqual("effect error")
  })

})

describe("Lifecycle events", () => {
  const model = {}

  const update = { add: (model, data) => model + data }

  const subs = [(_, msg) => msg.add(2)]

  it("accepts oncreate property", done => {
    const target = null

    const handleCreate = (e) => { target = e }

    app({
      model: {},
      view: () => (html`<div oncreate=${handleCreate}>Hi</div>`)
    })

    setTimeout(() => {
      expect(target).not.toEqual(null)
      done()
    }, 1)
  })

  // FIXME: currently it fails... is it a bug?
  // TODO: need help on this
  it.skip("fires onupdate when view changed", done => {
    const guard = null

    const handleUpdate = (e) => { guard = e }

    const view = (model) => html`<div onupdate=${handleUpdate}>${model}</div>`

    app({ model, update, subs, view })

    fireDOMLoaded()

    setTimeout(() => {
      expect(guard).not.toEqual(null)
      done()
    }, 1)

  })

})

describe("Routing", () => {

  it("handles the / route", () => {

    const view = {
      "/": () => html`<div id="root">root path</div>`
    }

    app({ view })

    expect(document.getElementById("root").innerHTML).toEqual('root path')
  })

  // FIXME: it throws an exception
  it.skip("handles * route", () => {
    const view = {
      "*": () => html`<div id="root">any path</div>`
    }

    app({ view })

    expect(document.getElementById("root").innerHTML).toEqual('any path')
  })

  // FIXME: how to change the location
  it.skip("handles route params", () => {

    const view = {
      "/": () => html`<div id="root">root path</div>`,
      ":a/:b/:c": () => html`<div id="root">params</div>`
    }

    app({ view })

    window.history.pushState({}, 'one', 'about:one/two/three')

    firePopState()

    expect(document.getElementById("root").innerHTML).toEqual('params')
  })

})
<commit_msg>More tests and coverage (#52)<commit_after>/* global beforeEach, describe, it, expect */

const { app, html, h } = require("../hx")

function fireDOMLoaded() {
  const event = document.createEvent("Event")
  event.initEvent("DOMContentLoaded", true, true)
  window.document.dispatchEvent(event)
}

function firePopState() {
  const event = document.createEvent("Event")
  event.initEvent("popstate", true, true)
  window.document.dispatchEvent(event)
}

beforeEach(() => {
  document.body.innerHTML = ''
})

describe("App", () => {

  it("boots with no bugs", () => {
    app({ model: {}, view: () => (html`<div>Hi</div>`) })
  })

  // FIXME: if fails... this is not true
  it.skip("allow all params to be optional", () => {
    app()
  })

  it("renders a model", () => {
    const model = {
      world: "world"
    }

    const view = (model) => html`<div id="test-me">${model.world}</div>`

    app({ model, view })

    expect(document.getElementById("test-me").innerHTML).toEqual(model.world)
  })

  it("renders a model with a loop", () => {
    const model = {
      loop: [
        "string1",
        "string2"
      ]
    }

    const view = model =>
      html`<div>${model.loop.map(value => html`
${value}
`)}</div>`

    app({ model, view })

    expect(document.getElementsByTagName("p").length).toEqual(model.loop.length)
  })

  it("renders svg", () => {
    const model = {
      text: "zelda"
    }

    const view = model =>
      html`<svg><text>${model.text}</text></svg>`

    app({ model, view })

    expect(document.getElementsByTagName("svg").length).toEqual(1)
    expect(document.getElementsByTagName("svg")[0].namespaceURI).toEqual("http://www.w3.org/2000/svg")
    expect(document.getElementsByTagName("text")[0].innerHTML).toEqual(model.text)
  })

  it("exec's a render when the update changes", () => {
    const firstValue = 'first-value'
    const secondValue = 'second-value'

    const model = firstValue

    const view = (model, update) => html`<div><input oninput=${e => update.fire(e.target.value)} value=${model}/><p>${model}</p></div>`

    const update = { fire: (_, value) => value }

    app({ model, view, update })

    const input = document.getElementsByTagName('input')[0];

    expect(input.value).toEqual(firstValue)

    const evnt = new Event('input', {bubbles:true});
    input.value = secondValue;
    input.dispatchEvent(evnt);

    expect(input.value).toEqual(secondValue)
    expect(document.getElementsByTagName('p')[0].innerHTML).toEqual(secondValue)
  });
})

describe("Views", () => {
  it("allows inline styles as object with properties in camelCase", () => {
    const view = (model) => html`
I'm red
`

    app({ view })
    var el = document.getElementById("red")
    expect(el).not.toBe(null)
    expect(el.style["background-color"]).toEqual("red")
    expect(el.style["padding"]).toEqual("10px")
  })

  it("allows the views to be defined directly with h", () => {
    const view = (model) => h("div", { id: "test" }, "inside div")
    app({ view })
    var el = document.getElementById("test")
    expect(el).not.toBe(null)
    expect(el.innerHTML).toEqual("inside div")
  })
})

describe("Subscriptions", () => {

  it("fires all subscriptions when DOM is ready", () => {
    const check = {}

    app({
      view: () => html`<div>View</div>`,
      subs: [
        () => { check["one"] = true },
        () => { check["two"] = true }
      ]
    })

    fireDOMLoaded()

    expect(check["one"]).toBe(true)
    expect(check["two"]).toBe(true)
  })
})

describe("Hooks", () => {
  const model = 0

  const view = (model) => html`<div>${model}</div>`

  const update = { add: (model, data) => model + data }

  const subs = [(_, msg) => msg.add(2)]

  it("fires onUpdate when the model is updated", () => {
    let guard = null

    const hooks = {
      onUpdate: (prev, model) => { guard = { prev, model } }
    }

    app({ model, view, update, subs, hooks })

    fireDOMLoaded()

    expect(guard).toEqual({ model: 2, prev: 0 })
  })

  it("fires onAction when a reducer is dispatched", () => {
    let guard = null

    const hooks = {
      onAction: (name, data) => { guard = { name, data } }
    }

    app({ model, view, update, subs, hooks })

    fireDOMLoaded()

    expect(guard).toEqual({ name: "add", data: 2 })
  })

  it("fires onAction when an effect is dispatched", () => {
    let guard = null

    let effectDone = false

    const hooks = {
      onAction: (name, data) => { guard = { name, data } }
    }

    const effects = {
      add: () => { effectDone = true }
    }

    app({ model, view, effects, subs, hooks })

    fireDOMLoaded()

    expect(effectDone).toBe(true)
    expect(guard).toEqual({ name: "add", data: 2 })
  })

  it("fires onError when a effect fails", () => {
    let guard = null

    const hooks = {
      onError: (err) => { guard = err }
    }

    const effects = {
      add: (model, msg, data, error) => { error("effect error") }
    }

    app({ model, view, effects, subs, hooks })

    fireDOMLoaded()

    expect(guard).toEqual("effect error")
  })

})

describe("Lifecycle events", () => {
  const model = {}

  const update = { add: (model, data) => model + data }

  const subs = [(_, msg) => msg.add(2)]

  it("accepts oncreate property", done => {
    let target = null

    const handleCreate = (e) => { target = e }

    app({
      model: {},
      view: () => (html`<div oncreate=${handleCreate}>Hi</div>`)
    })

    setTimeout(() => {
      expect(target).not.toEqual(null)
      done()
    }, 1)
  })

  // FIXME: currently it fails... is it a bug?
  // TODO: need help on this
  it.skip("fires onupdate when view changed", done => {
    let guard = null

    const handleUpdate = (e) => { guard = e }

    const view = (model) => html`<div onupdate=${handleUpdate}>${model}</div>`

    app({ model, update, subs, view })

    fireDOMLoaded()

    setTimeout(() => {
      expect(guard).not.toEqual(null)
      done()
    }, 1)

  })

})

describe("Routing", () => {

  it("handles the / route", () => {

    const view = {
      "/": () => html`<div id="root">root path</div>`
    }

    app({ view })

    expect(document.getElementById("root").innerHTML).toEqual('root path')
  })

  // FIXME: it throws an exception
  it.skip("handles * route", () => {
    const view = {
      "*": () => html`<div id="root">any path</div>`
    }

    app({ view })

    expect(document.getElementById("root").innerHTML).toEqual('any path')
  })

  // FIXME: how to change the location
  it.skip("handles route params", () => {

    const view = {
      "/": () => html`<div id="root">root path</div>`,
      ":a/:b/:c": () => html`<div id="root">params</div>`
    }

    app({ view })

    window.history.pushState({}, 'one', 'about:one/two/three')

    firePopState()

    expect(document.getElementById("root").innerHTML).toEqual('params')
  })

})
<|endoftext|>


<commit_before>import EventEmitter from 'eventemitter3';
import UUID from 'node-uuid';

const SELECT_ACTION_EVENT = 'ACTIONIZER.ACTION.SELECT';
const PUT_ACTION_EVENT    = 'ACTIONIZER.ACTION.PUT';
const CALL_ACTION_EVENT   = 'ACTIONIZER.ACTION.CALL';
const FORK_ACTION_EVENT   = 'ACTIONIZER.ACTION.FORK';
const CANCEL_ACTION_EVENT = 'ACTIONIZER.ACTION.CANCEL';

export const select = () => {
  return {type: SELECT_ACTION_EVENT};
};

export const put = (nextState) => {
  return {type: PUT_ACTION_EVENT, nextState};
};

export const call = (fn, ...args) => {
  return {type: CALL_ACTION_EVENT, fn, args};
};

export const fork = (actionCreator, ...args) => {
  return {type: FORK_ACTION_EVENT, actionCreator, args};
};

export const cancel = (actionId) => {
  return {type: CANCEL_ACTION_EVENT, actionId};
};

const EMITTER_EVENT = 'ACTIONIZER.EMITTER.NOTIFY';

export const createStore = (initialState, notify = (emit) => { emit(); }) => {

  let state = initialState;
  const emitter = new EventEmitter();

  const subscribe = (listener) => {
    emitter.on(EMITTER_EVENT, listener);

    return () => {
      emitter.removeListener(EMITTER_EVENT, listener);
    };
  };

  const getState = () => {
    return state;
  };

  const setState = (nextState) => {
    if (state === nextState) { return; }

    state = nextState;

    notify(() => {
      emitter.emit(EMITTER_EVENT, state);
    });
  };

  const processes = {};

  const dispatch = (action) => {
    const uuid = UUID.v4();
    processes[uuid] = action;

    const step = (result) => {
      const { done, value } = result;

      if (done) {
        delete processes[uuid];
        return;
      }

      switch (value.type) {
        case SELECT_ACTION_EVENT:
          step(action.next(state));
          break;
        case PUT_ACTION_EVENT:
          setState(value.nextState);
          step(action.next(state));
          break;
        case CALL_ACTION_EVENT:
          value
            .fn(...value.args)
            .then((val) => { step(action.next(val)); })
            .catch((e) => { step(action.throw(e)); });
          break;
        case FORK_ACTION_EVENT:
          step(action.next(dispatch(value.actionCreator(...value.args))));
          break;
        case CANCEL_ACTION_EVENT:
          if (processes[value.actionId]) {
            processes[value.actionId].return();
            delete processes[value.actionId];
          }
          step(action.next());
          break;
        default:
          step(action.throw(new Error('Received unknown command.')));
          break;
      }
    };

    step(action.next());
    return uuid;
  };

  return {
    subscribe,
    getState,
    dispatch
  };

};
<commit_msg>Arrow passing selector to select<commit_after>import EventEmitter from 'eventemitter3';
import UUID from 'node-uuid';

const SELECT_ACTION_EVENT = 'ACTIONIZER.ACTION.SELECT';
const PUT_ACTION_EVENT    = 'ACTIONIZER.ACTION.PUT';
const CALL_ACTION_EVENT   = 'ACTIONIZER.ACTION.CALL';
const FORK_ACTION_EVENT   = 'ACTIONIZER.ACTION.FORK';
const CANCEL_ACTION_EVENT = 'ACTIONIZER.ACTION.CANCEL';

export const select = (selector = (state) => state) => {
  return {type: SELECT_ACTION_EVENT, selector};
};

export const put = (nextState) => {
  return {type: PUT_ACTION_EVENT, nextState};
};

export const call = (fn, ...args) => {
  return {type: CALL_ACTION_EVENT, fn, args};
};

export const fork = (actionCreator, ...args) => {
  return {type: FORK_ACTION_EVENT, actionCreator, args};
};

export const cancel = (actionId) => {
  return {type: CANCEL_ACTION_EVENT, actionId};
};

const EMITTER_EVENT = 'ACTIONIZER.EMITTER.NOTIFY';

export const createStore = (initialState, notify = (emit) => { emit(); }) => {

  let state = initialState;
  const emitter = new EventEmitter();

  const subscribe = (listener) => {
    emitter.on(EMITTER_EVENT, listener);

    return () => {
      emitter.removeListener(EMITTER_EVENT, listener);
    };
  };

  const getState = () => {
    return state;
  };

  const setState = (nextState) => {
    if (state === nextState) { return; }

    state = nextState;

    notify(() => {
      emitter.emit(EMITTER_EVENT, state);
    });
  };

  const processes = {};

  const dispatch = (action) => {
    const uuid = UUID.v4();
    processes[uuid] = action;

    const step = (result) => {
      const { done, value } = result;

      if (done) {
        delete processes[uuid];
        return;
      }

      switch (value.type) {
        case SELECT_ACTION_EVENT:
          step(action.next(value.selector(state)));
          break;
        case PUT_ACTION_EVENT:
          setState(value.nextState);
          step(action.next(state));
          break;
        case CALL_ACTION_EVENT:
          value
            .fn(...value.args)
            .then((val) => { step(action.next(val)); })
            .catch((e) => { step(action.throw(e)); });
          break;
        case FORK_ACTION_EVENT:
          step(action.next(dispatch(value.actionCreator(...value.args))));
          break;
        case CANCEL_ACTION_EVENT:
          if (processes[value.actionId]) {
            processes[value.actionId].return();
            delete processes[value.actionId];
          }
          step(action.next());
          break;
        default:
          step(action.throw(new Error('Received unknown command.')));
          break;
      }
    };

    step(action.next());
    return uuid;
  };

  return {
    subscribe,
    getState,
    dispatch
  };

};
<|endoftext|>


<commit_before>var titleinput = $(".doc-name");
var editregion = $("#document-editor");

function getAbstract(html) { //get a text string representative of the document
	var removed = $("" + html + "").remove("div").remove("iframe").remove("script"); //strip out the interactive stuff - we just want a text string
	removed = removed[0].textContent;
	var abstract = removed.substring(0, 175); //the length of the abstract to return
	if (abstract) {
		return abstract;
	} else {
		return "";
	}
}

function getPosterImage(html) {
	var content = $("" + html + "");
	var images = content.find("img");
	var posterImage = $(images[0]).attr("src");
	return posterImage;
};

var currentTime = (new Date).getTime();
var document_id = window.location.hash.replace("#", "");
var baseWindowTitle = document.title;

var client = new Dropbox.Client({
	key: config.dropbox
});

// Try to finish OAuth authorization.
client.authenticate({
	interactive: false
}, function (error) {
	if (error) {
		createError({
			error: 'Authentication error: ' + error,
			action: "please log in to Dropbox and try again"
		});
	}
});

if (client.isAuthenticated()) {
	client.readFile("/metadata/metadata.json", function (error, data) { //first, we need the metadata
		if (error) {
			return createError({
				error: 'Error loading metadata: ' + error,
				action: "please try again in a few minutes"
			});
		}

		window.metadata = JSON.parse(data);

		if (document_id && metadata[document_id]) { //this document already exists - load it
			client.readFile("/documents/" + document_id + ".html", function (error, data) {
				if (error) {
					return createError({
						error: 'Error loading document: ' + error,
						action: "please try again in a few minutes"
					});
				}
				titleinput.val(metadata[document_id].title);
				editregion.html(data);
				document.title = metadata[document_id].title + " | " + baseWindowTitle;

				window.cachedDocument = {
					title: metadata[document_id].title,
					content: editregion.html(),
				}
			});

		} else if (document_id) { //we have a hash, but it isn't in the metadata. Probably not owned by the user
			return createError({
				error: "Document does not exist.",
				action: "This document does not exist, or you do not have permission to view it."
			});

		} else { //there is no hash - create a document
			document_id = currentTime; //update this so we can save the document later
			metadata[document_id] = {
				title: "Untitled Document",
				abstract: "",
				posterImage: "default",
				created: (new Date).getTime(),
				modified: (new Date).getTime(),
			}

			window.cachedDocument = {
				title: "Untitled Document",
				content: "",
			}

			client.writeFile("/documents/" + document_id + ".html", "", function (error, stat) {}); //create a new file
			client.writeFile("/metadata/metadata.json", JSON.stringify(window.metadata), function (error, stat) {}); //and also update the metadata
			window.location.hash = document_id; //and also update the URL
		}

		//save the document periodically

		function saveDocument() {
			if (titleinput.val() != window.cachedDocument.title || editregion.html() != window.cachedDocument.content) { //to prevent conflicts, we only save the document when content is added in the current window
				client.readFile("/metadata/metadata.json", function (error, data) { //we can't cache this
					if (error) {
						return createToast("Document could not be saved. Please make sure you are connected to the internet and try again.");
					}
					window.metadata = JSON.parse(data);
					//update the metadata
					metadata[document_id].title = titleinput.val();
					metadata[document_id].abstract = getAbstract(editregion.html());
					metadata[document_id].posterImage = getPosterImage(editregion.html());
					metadata[document_id].modified = (new Date).getTime();

					if (!metadata[document_id].title) { //if the title is empty, use the default
						metadata[document_id].title = "Untitled Document";
						titleinput.val("Untitled Document");
					}

					window.cachedDocument = {
						title: metadata[document_id].title,
						content: editregion.html(),
					}

					document.title = metadata[document_id].title + " | " + baseWindowTitle;

					client.writeFile("/metadata/metadata.json", JSON.stringify(metadata), function (error, stat) {
						if (error) {
							return createToast("Document could not be saved. Please make sure you are connected to the internet and try again.");
						}
					}); //update the metadata
					client.writeFile("/documents/" + document_id + ".html", editregion.html(), function (error, stat) {
						if (error) {
							return createToast("Document could not be saved. Please make sure you are connected to the internet and try again.");
						}
					}); //write file contents
				});
				removeToasts(); //clear any previous offiline errors, since the document saved successfully
			} else {}
		}

		window.refreshIfNeeded = function () {
			client.readFile("/documents/" + document_id + ".html", function (error, data) {
				if (error) {
					return createToast("An error occured.");
				}
				if (window.cachedDocument.content != data) { //only refresh if the document has changed
					window.cachedDocument.content = data; //update cached
					editregion.html(data);
					client.readFile("/metadata/metadata.json", function (error, data) { //also update metadata
						if (error) { //we don't want to parse the metadata if an error occured
							return createToast("An error occured.");
						}
						window.metadata = JSON.parse(data);
						document.title = metadata[document_id].title + " | " + baseWindowTitle;
						titleinput.val(metadata[document_id].title);
					});
				}
			});
		}

		setInterval(refreshIfNeeded, 17500);

		setInterval(saveDocument, 5500);

		window.onbeforeunload = function () {
			if (saveDocument()) {
				return "Your changes have not been saved yet. Are you sure you want to leave?"
			}
		}
	});

} else {
	window.location = config.basepath;
}<commit_msg>bug fix: make newly created documents work correctly with grid view<commit_after>var titleinput = $(".doc-name");
var editregion = $("#document-editor");

function getAbstract(html) { //get a text string representative of the document
	var removed = $("" + html + "").remove("div").remove("iframe").remove("script"); //strip out the interactive stuff - we just want a text string
	removed = removed[0].textContent;
	var abstract = removed.substring(0, 175); //the length of the abstract to return
	if (abstract) {
		return abstract;
	} else {
		return "";
	}
}

function getPosterImage(html) {
	var content = $("" + html + "");
	var images = content.find("img");
	var posterImage = $(images[0]).attr("src");
	return posterImage;
};

var currentTime = (new Date).getTime();
var document_id = window.location.hash.replace("#", "");
var baseWindowTitle = document.title;

var client = new Dropbox.Client({
	key: config.dropbox
});

// Try to finish OAuth authorization.
client.authenticate({
	interactive: false
}, function (error) {
	if (error) {
		createError({
			error: 'Authentication error: ' + error,
			action: "please log in to Dropbox and try again"
		});
	}
});

if (client.isAuthenticated()) {
	client.readFile("/metadata/metadata.json", function (error, data) { //first, we need the metadata
		if (error) {
			return createError({
				error: 'Error loading metadata: ' + error,
				action: "please try again in a few minutes"
			});
		}

		window.metadata = JSON.parse(data);

		if (document_id && metadata[document_id]) { //this document already exists - load it
			client.readFile("/documents/" + document_id + ".html", function (error, data) {
				if (error) {
					return createError({
						error: 'Error loading document: ' + error,
						action: "please try again in a few minutes"
					});
				}
				titleinput.val(metadata[document_id].title);
				editregion.html(data);
				document.title = metadata[document_id].title + " | " + baseWindowTitle;

				window.cachedDocument = {
					title: metadata[document_id].title,
					content: editregion.html(),
				}
			});

		} else if (document_id) { //we have a hash, but it isn't in the metadata. Probably not owned by the user
			return createError({
				error: "Document does not exist.",
				action: "This document does not exist, or you do not have permission to view it."
			});

		} else { //there is no hash - create a document
			document_id = currentTime; //update this so we can save the document later
			metadata[document_id] = {
				title: "Untitled Document",
				abstract: "",
				posterImage: "",
				created: (new Date).getTime(),
				modified: (new Date).getTime(),
			}

			window.cachedDocument = {
				title: "Untitled Document",
				content: "",
			}

			client.writeFile("/documents/" + document_id + ".html", "", function (error, stat) {}); //create a new file
			client.writeFile("/metadata/metadata.json", JSON.stringify(window.metadata), function (error, stat) {}); //and also update the metadata
			window.location.hash = document_id; //and also update the URL
		}

		//save the document periodically

		function saveDocument() {
			if (titleinput.val() != window.cachedDocument.title || editregion.html() != window.cachedDocument.content) { //to prevent conflicts, we only save the document when content is added in the current window
				client.readFile("/metadata/metadata.json", function (error, data) { //we can't cache this
					if (error) {
						return createToast("Document could not be saved. Please make sure you are connected to the internet and try again.");
					}
					window.metadata = JSON.parse(data);
					//update the metadata
					metadata[document_id].title = titleinput.val();
					metadata[document_id].abstract = getAbstract(editregion.html());
					metadata[document_id].posterImage = getPosterImage(editregion.html());
					metadata[document_id].modified = (new Date).getTime();

					if (!metadata[document_id].title) { //if the title is empty, use the default
						metadata[document_id].title = "Untitled Document";
						titleinput.val("Untitled Document");
					}

					window.cachedDocument = {
						title: metadata[document_id].title,
						content: editregion.html(),
					}

					document.title = metadata[document_id].title + " | " + baseWindowTitle;

					client.writeFile("/metadata/metadata.json", JSON.stringify(metadata), function (error, stat) {
						if (error) {
							return createToast("Document could not be saved. Please make sure you are connected to the internet and try again.");
						}
					}); //update the metadata
					client.writeFile("/documents/" + document_id + ".html", editregion.html(), function (error, stat) {
						if (error) {
							return createToast("Document could not be saved. Please make sure you are connected to the internet and try again.");
						}
					}); //write file contents
				});
				removeToasts(); //clear any previous offiline errors, since the document saved successfully
			} else {}
		}

		window.refreshIfNeeded = function () {
			client.readFile("/documents/" + document_id + ".html", function (error, data) {
				if (error) {
					return createToast("An error occured.");
				}
				if (window.cachedDocument.content != data) { //only refresh if the document has changed
					window.cachedDocument.content = data; //update cached
					editregion.html(data);
					client.readFile("/metadata/metadata.json", function (error, data) { //also update metadata
						if (error) { //we don't want to parse the metadata if an error occured
							return createToast("An error occured.");
						}
						window.metadata = JSON.parse(data);
						document.title = metadata[document_id].title + " | " + baseWindowTitle;
						titleinput.val(metadata[document_id].title);
					});
				}
			});
		}

		setInterval(refreshIfNeeded, 17500);

		setInterval(saveDocument, 5500);

		window.onbeforeunload = function () {
			if (saveDocument()) {
				return "Your changes have not been saved yet. Are you sure you want to leave?"
			}
		}
	});

} else {
	window.location = config.basepath;
}<|endoftext|>


<commit_before>// cheap way of doing AA
//c.width = 3200, c.height = 1800; // 16:9 aspect ratio
c.width = 192, c.height = 108; // battery saving

f = new AudioContext;
a = f.createScriptProcessor(0x200, t = 1, K = 1);
a.connect(f.destination);

// sequencer thing
s=(notes,octave,rate,len) =>
  31 & t * Math.pow(2, notes[(t>>rate)%len] / 12 - octave)

// music debug
//t= 1744100
//t= 3744100
//t= 4744100

// music
X = a.onaudioprocess = audioEvent => {
  L = audioEvent.outputBuffer.getChannelData(i=0);

  for(;i++<0x200;t++) {
    // TODO: golf
    /*
    X = Math.max(0., Math.min(
      -Math.abs(++t/5e5 - 5) + 5,
    1e0)) // 5 = demo length
    */
    //X = t/1e5
    //if(!i) console.log(X);
    X = 1 // debug

    // kick drum with variation
    L[i] = (((K=1e4/(t&0x3fff*(
      (t>>15)%16 - 15 ? 1 : 0.75
    )))&1)*35)

    // bass
    + (s('7050',4,17,4)&0xff) / K;

    L[i] *= !(t>>22); // turn off above instruments after a while

    // LEFT CHANNEL
    // hihat TODO improve/golf envelope
    L[i] += ((t%150*t%130*t)&0x80)*Math.min(0.2, (1e1/((t>>3)%512))) * !!(t>>19)
    // arpeggio
    + (s((t>>17)%2 ? '027' : '037',1,13-(3*(t>>20)%12),4)) / K * !!(t>>20);

    L[i] *= X / 200;
    //if (L[i] > 1) console.log('clipping');

    // limit volume while testing
    //L[i] = Math.max(-0.5, Math.min(0.5, L[i]));
  }
}

// gfx
g=c.getContext`webgl`;
P = g.createProgram();

// NOTE: 2nd argument to drawArrays used to be 0, but undefined works
r = time => g.drawArrays(g.TRIANGLE_FAN,
  // Send resolution and time to shader
  g.uniform4f(g.getUniformLocation(P, 'a'), c.width, c.height, time / 1e3, X),
  3,
  g.uniform4f(g.getUniformLocation(P, 'b'), 1, 0, .2/K, requestAnimationFrame(r))
);

// vertex shader
g.shaderSource(S=g.createShader(g.VERTEX_SHADER), require('./vertex.glsl'));
g.compileShader(S);g.attachShader(P,S);

// fragment shader
g.shaderSource(S=g.createShader(g.FRAGMENT_SHADER), require('./fragment.glsl'));
g.compileShader(S);g.attachShader(P,S);

// Log compilation errors
// if (!getShaderParameter(S, 35713)) { // COMPILE_STATUS = 35713
//   throw getShaderInfoLog(S);
// }

g.bindBuffer(g.ARRAY_BUFFER, g.createBuffer(c.parentElement.style.margin = 0));
// 1st argument to enableVertexAttribArray used to be 0, but undefined works
// 1st argument to vertexAttribPointer used to be 0, but undefined works
g.vertexAttribPointer(
  g.enableVertexAttribArray(
    g.bufferData(g.ARRAY_BUFFER, Int8Array.of(-3, 1, 1, -3, 1, 1), g.STATIC_DRAW)
  ),
2, g.BYTE, r(c.style.height = '100vh'), g.linkProgram(P), g.useProgram(P));
<commit_msg>output closer to uglifyjs<commit_after>// cheap way of doing AA
c.width = 3200, c.height = 1800; // 16:9 aspect ratio
//c.width = 192, c.height = 108; // battery saving

f = new AudioContext;
a = f.createScriptProcessor(512, t = 1, K = 1);
a.connect(f.destination);

// sequencer thing
s=(notes,octave,rate,len) =>
  31 & t * Math.pow(2, notes[(t>>rate)%len] / 12 - octave)

// music debug
//t= 1744100
//t= 3744100
//t= 4744100

// music
X = a.onaudioprocess = e => {
  L = e.outputBuffer.getChannelData(i=0);

  for(;i++<512;t++) {
    // TODO: golf
    /*
    X = Math.max(0., Math.min(
      -Math.abs(++t/5e5 - 5) + 5,
    1e0)) // 5 = demo length
    */
    //X = t/1e5
    //if(!i) console.log(X);
    X = 1 // debug

    // kick drum with variation
    L[i] = (((K=1e4/(t&16383*(
      (t>>15)%16 - 15 ? 1 : 0.75
    )))&1)*35)

    // bass
    + (s('7050',4,17,4)&255) / K;

    L[i] *= !(t>>22); // turn off above instruments after a while

    // LEFT CHANNEL
    // hihat TODO improve/golf envelope
    L[i] += ((t%150*t%130*t)&128)*Math.min(0.2, (1e1/((t>>3)%512))) * !!(t>>19)
    // arpeggio
    + (s((t>>17)%2 ? '027' : '037',1,13-(3*(t>>20)%12),4)) / K * !!(t>>20);

    L[i] *= X / 200;
    //if (L[i] > 1) console.log('clipping');

    // limit volume while testing
    //L[i] = Math.max(-0.5, Math.min(0.5, L[i]));
  }
}

// gfx
g=c.getContext`webgl`;
P = g.createProgram();

// NOTE: 2nd argument to drawArrays used to be 0, but undefined works
r = time => g.drawArrays(g.TRIANGLE_FAN,
  // Send resolution and time to shader
  g.uniform4f(g.getUniformLocation(P, 'a'), c.width, c.height, time / 1e3, X),
  3,
  g.uniform4f(g.getUniformLocation(P, 'b'), 1, 0, .2/K, requestAnimationFrame(r))
);

// vertex shader
g.shaderSource(S=g.createShader(g.VERTEX_SHADER), require('./vertex.glsl'));
g.compileShader(S);g.attachShader(P,S);

// fragment shader
g.shaderSource(S=g.createShader(g.FRAGMENT_SHADER), require('./fragment.glsl'));
g.compileShader(S);g.attachShader(P,S);

// Log compilation errors
// if (!getShaderParameter(S, 35713)) { // COMPILE_STATUS = 35713
//   throw getShaderInfoLog(S);
// }

g.bindBuffer(g.ARRAY_BUFFER, g.createBuffer(c.parentElement.style.margin = 0));
// 1st argument to enableVertexAttribArray used to be 0, but undefined works
// 1st argument to vertexAttribPointer used to be 0, but undefined works
g.vertexAttribPointer(
  g.enableVertexAttribArray(
    g.bufferData(g.ARRAY_BUFFER, Int8Array.of(-3, 1, 1, -3, 1, 1), g.STATIC_DRAW)
  ),
2, g.BYTE, r(c.style.height = '100vh'), g.linkProgram(P), g.useProgram(P));
<|endoftext|>


<commit_before>'use strict'
import jsTypes from 'js-types'

const lowerCaseTypes = jsTypes.map(type => type.toLowerCase())

/**
 * Determine if a type is JS type
 * @param {Stirng} type - type to verify
 * @return {Boolean} - type is a JS type
 */
module.exports = function isJsType(type) {
  if (typeof type !== 'string') {
    throw new TypeError('Expected type to be a string')
  }

  return lowerCaseTypes.indexOf(type.toLowerCase()) > -1
}
<commit_msg>docs(src): fix typo in JSDoc<commit_after>'use strict'
import jsTypes from 'js-types'

const lowerCaseTypes = jsTypes.map(type => type.toLowerCase())

/**
 * Determine if a type is JS type
 * @param {String} type - type to verify
 * @return {Boolean} - type is a JS type
 */
module.exports = function isJsType(type) {
  if (typeof type !== 'string') {
    throw new TypeError('Expected type to be a string')
  }

  return lowerCaseTypes.indexOf(type.toLowerCase()) > -1
}
<|endoftext|>


<commit_before>/* index.jsx */
import React, { Component } from 'react';
import { render } from 'react-dom';
import WebFontLoader from 'webfontloader';

import './scss/index.scss';
import { Card, CardTitle, CardText, CardActions } from 'react-md/lib/Cards';
import Button from 'react-md/lib/Buttons';

WebFontLoader.load({
  google: {
    families: ['Roboto:300,400,500,700', 'Material Icons']
  }
});

class App extends Component {
  render() {
    return (

        <Card className="md-cell">
          <CardTitle title="Hello, World!"  />
          <CardText>
            Lorem ipsum... pretend more ...
          </CardText>
          <CardActions>
            <Button flat label="Action 1" />
            <Button flat label="Action 2" />
          </CardActions>
        </Card>

    );
  }
}

render(<App />, document.getElementById('application'));
<commit_msg>skeleton is pretty spoopy<commit_after>/* index.jsx */
import React, { Component } from 'react';
import { render } from 'react-dom';
import WebFontLoader from 'webfontloader';

import './scss/index.scss';
import { Card, CardTitle, CardText, CardActions, Drawer } from 'react-md/lib/Cards';
import Button from 'react-md/lib/Buttons';

WebFontLoader.load({
  google: {
    families: ['Roboto:300,400,500,700', 'Material Icons']
  }
});

class App extends Component {
  render() {
    return (

        <Card className="md-cell">
          <CardTitle title="Hello, World!"  />
          <CardText>
            Lorem ipsum... pretend more ...
          </CardText>
          <CardActions>
            <Button flat label="Action 1" />
            <Button flat label="Action 2" />
          </CardActions>
        </Card>

    );
  }
}

render(<App />, document.getElementById('application'));
<|endoftext|>


<commit_before>// cheap way of doing AA
c.width = 192, c.height = 108; // 16:9 aspect ratio

f = new AudioContext;
a = f.createScriptProcessor(0x200, t = 1, K = 1);
a.connect(f.destination);

// music
X = a.onaudioprocess = audioEvent => {
  L = audioEvent.outputBuffer.getChannelData(i=0);
  //R = audioEvent.outputBuffer.getChannelData(1);

  //L.map((sample, i) => {
  for(;i++<0x200;) {
  //for(;i++<L.length;) {
    // TODO: golf
    // debug: set Math.max(x <- to 0 when done
    /*
    X = Math.max(0., Math.min(
      -Math.abs(++t/5e5 - 5) + 5,
    1e0)) // 5 = demo length
    */
    //X = t/1e5
    //if(!i) console.log(X);
    ++t;
    X = 1 // debug

    // sequencer thing
    S=(notes,octave,rate,len) =>
      31 & t * Math.pow(2, notes[(t>>rate)%len] / 12 - octave)
    // version which supports whitespace for silence
      // notes.charCodeAt((t>>rate)%len) - 32 // Is the note a whitespace?
      //   ? 31 & t * Math.pow(2, notes.charCodeAt((t>>rate)%len) / 12 - octave)
      //   : 0

    // kick drum with variation
    L[i] = (((K=1e4/(t&0x3fff*(
      (t>>15)%16 - 15 ? 1 : 0.75
    )))&1)*35)

    // bass
    + (S('7050',4,17,4)&0xff) / K;

    L[i] *= !(t>>22);
    //R[i] = L[i];

    // hihat envelope TODO: golf
    E=Math.min(1, (1e1/((t>>5)%0x80))) * 0.2;
    //if (i<2) console.log(t>>1);

    // LEFT CHANNEL
    // hihat
    L[i] += (((t%100)*(t%100)*(t>>5))&0x80)*E * !!(t>>19)
    // sierpinski thing
    + ((t*(t>>11))&0x80)*E * !!(t>>20)
    //+ ((t*(t>>11))&128)*E * !!(t>>20)
    // arpeggio
    + (!!(t/4&0x1000)*S((t>>17)%2 ? '027' : '037',1,11,3)*(0x1000-(t&0xfff))>>11) / K * !!(t>>21);
    //+ (t/4&4096?S((t>>17)%2 ? '027' : '037',5,11,3)*(4096-(t&4095))>>11 : 0) / K * !!(t>>21);

    // RIGHT CHANNEL
    // hihat
    /*
    R[i] += (((t%100)*(t%100)*(t>>4))&128)*E * !!(t>>19)
    // sierpinski thing
    + ((t*(t>>12))&128)*E * !!(t>>20)
    // arpeggio
    + (!!(t/4&4096)*S((t>>17)%2 ? '072' : '073',1,11,3)*(4096-(t&4095))>>11) / K * !!(t>>21);
    //+ (t/4&4096?S((t>>17)%2 ? '072' : '073',5,11,3)*(4096-(t&4095))>>11 : 0) / K * !!(t>>21);
    */

    L[i] *= X / 200;
    //R[i] *= X / 200;
    //if (L[i] > 1 || R[i] > 1) console.log('clipping');

    //i; // *something* in the prod build removes i without this line: WTF TODO

    // limit volume while testing
    //L[i] = Math.max(-0.5, Math.min(0.5, L[i]));
    //R[i] = Math.max(-0.5, Math.min(0.5, R[i]));
  }
}

// gfx
g=c.getContext`webgl`;
P = g.createProgram();

// NOTE: 2nd argument to drawArrays used to be 0, but undefined works
r = time => g.drawArrays(g.TRIANGLE_FAN,
  // Send resolution and time to shader
  g.uniform4f(g.getUniformLocation(P, 'a'), c.width, c.height, time / 1e3, X),
  3,
  g.uniform4f(g.getUniformLocation(P, 'b'), 1, 0, .2/K, requestAnimationFrame(r))
);

// vertex shader
g.shaderSource(S=g.createShader(g.VERTEX_SHADER), require('./vertex.glsl'));
g.compileShader(S);g.attachShader(P,S);

// fragment shader
g.shaderSource(S=g.createShader(g.FRAGMENT_SHADER), require('./fragment.glsl'));
g.compileShader(S);g.attachShader(P,S);

// Log compilation errors
// if (!getShaderParameter(S, 35713)) { // COMPILE_STATUS = 35713
//   throw getShaderInfoLog(S);
// }

g.bindBuffer(g.ARRAY_BUFFER, g.createBuffer(c.parentElement.style.margin = 0));
// 1st argument to enableVertexAttribArray used to be 0, but undefined works
// 1st argument to vertexAttribPointer used to be 0, but undefined works
g.vertexAttribPointer(
  g.enableVertexAttribArray(
    g.bufferData(g.ARRAY_BUFFER, Int8Array.of(-3, 1, 1, -3, 1, 1), g.STATIC_DRAW)
  ),
2, g.BYTE, r(c.style.height = '100vh'), g.linkProgram(P), g.useProgram(P));
<commit_msg>golf (+230)<commit_after>// cheap way of doing AA
c.width = 192, c.height = 108; // 16:9 aspect ratio

f = new AudioContext;
a = f.createScriptProcessor(0x200, t = 1, K = 1);
a.connect(f.destination);

// music
X = a.onaudioprocess = audioEvent => {
  L = audioEvent.outputBuffer.getChannelData(i=0);
  //R = audioEvent.outputBuffer.getChannelData(1);

  //L.map((sample, i) => {
  for(;i++<0x200;) {
  //for(;i++<L.length;) {
    // TODO: golf
    // debug: set Math.max(x <- to 0 when done
    /*
    X = Math.max(0., Math.min(
      -Math.abs(++t/5e5 - 5) + 5,
    1e0)) // 5 = demo length
    */
    //X = t/1e5
    //if(!i) console.log(X);
    ++t;
    X = 1 // debug

    // sequencer thing
    S=(notes,octave,rate,len) =>
      31 & t * Math.pow(2, notes[(t>>rate)%len] / 12 - octave)
    // version which supports whitespace for silence
      // notes.charCodeAt((t>>rate)%len) - 32 // Is the note a whitespace?
      //   ? 31 & t * Math.pow(2, notes.charCodeAt((t>>rate)%len) / 12 - octave)
      //   : 0

    // kick drum with variation
    L[i] = (((K=1e4/(t&0x3fff*(
      (t>>15)%16 - 15 ? 1 : 0.75
    )))&1)*35)

    // bass
    + (S('7050',4,17,4)&0xff) / K;

    L[i] *= !(t>>22);
    //R[i] = L[i];

    // hihat envelope TODO: golf
    //E=Math.min(1, (1e1/((t>>5)%0x80))) * 0.2;
    E=Math.min(0.2, (1e1/((t>>3)%512)));
    //if (i<2) console.log(t>>1);

    // LEFT CHANNEL
    // hihat
    L[i] += (((t%100)*(t%100)*(t>>5))&0x80)*E * !!(t>>19)
    // sierpinski thing
    //+ ((t*(t>>11))&0x80)*E * !!(t>>20)
    //+ ((t*(t>>11))&128)*E * !!(t>>20)
    // arpeggio
    + (!!(t/4&0x1000)*S((t>>17)%2 ? '027' : '037',1,11,3)*(0x1000-(t&0xfff))>>11) / K * !!(t>>21);
    //+ (t/4&4096?S((t>>17)%2 ? '027' : '037',5,11,3)*(4096-(t&4095))>>11 : 0) / K * !!(t>>21);

    // RIGHT CHANNEL
    // hihat
    /*
    R[i] += (((t%100)*(t%100)*(t>>4))&128)*E * !!(t>>19)
    // sierpinski thing
    + ((t*(t>>12))&128)*E * !!(t>>20)
    // arpeggio
    + (!!(t/4&4096)*S((t>>17)%2 ? '072' : '073',1,11,3)*(4096-(t&4095))>>11) / K * !!(t>>21);
    //+ (t/4&4096?S((t>>17)%2 ? '072' : '073',5,11,3)*(4096-(t&4095))>>11 : 0) / K * !!(t>>21);
    */

    L[i] *= X / 200;
    //R[i] *= X / 200;
    //if (L[i] > 1 || R[i] > 1) console.log('clipping');

    //i; // *something* in the prod build removes i without this line: WTF TODO

    // limit volume while testing
    //L[i] = Math.max(-0.5, Math.min(0.5, L[i]));
    //R[i] = Math.max(-0.5, Math.min(0.5, R[i]));
  }
}

// gfx
g=c.getContext`webgl`;
P = g.createProgram();

// NOTE: 2nd argument to drawArrays used to be 0, but undefined works
r = time => g.drawArrays(g.TRIANGLE_FAN,
  // Send resolution and time to shader
  g.uniform4f(g.getUniformLocation(P, 'a'), c.width, c.height, time / 1e3, X),
  3,
  g.uniform4f(g.getUniformLocation(P, 'b'), 1, 0, .2/K, requestAnimationFrame(r))
);

// vertex shader
g.shaderSource(S=g.createShader(g.VERTEX_SHADER), require('./vertex.glsl'));
g.compileShader(S);g.attachShader(P,S);

// fragment shader
g.shaderSource(S=g.createShader(g.FRAGMENT_SHADER), require('./fragment.glsl'));
g.compileShader(S);g.attachShader(P,S);

// Log compilation errors
// if (!getShaderParameter(S, 35713)) { // COMPILE_STATUS = 35713
//   throw getShaderInfoLog(S);
// }

g.bindBuffer(g.ARRAY_BUFFER, g.createBuffer(c.parentElement.style.margin = 0));
// 1st argument to enableVertexAttribArray used to be 0, but undefined works
// 1st argument to vertexAttribPointer used to be 0, but undefined works
g.vertexAttribPointer(
  g.enableVertexAttribArray(
    g.bufferData(g.ARRAY_BUFFER, Int8Array.of(-3, 1, 1, -3, 1, 1), g.STATIC_DRAW)
  ),
2, g.BYTE, r(c.style.height = '100vh'), g.linkProgram(P), g.useProgram(P));
<|endoftext|>


<commit_before>describe('c6 - https', function(done) {

  require('benchmarket').start();
  after(require('benchmarket').store());

  this.timeout(20000);

  var Mesh = require('../')

  var spawn = require('child_process').spawn;
  var expect = require('expect.js');
  var sep = require('path').sep;
  var libFolder = __dirname + sep + 'lib' + sep;

  var test_id = Date.now() + '_' + require('shortid').generate();
  var should = require('chai').should();

  after(function(done){
     remote.kill();
     done();
  });

  var testClient;

  before(function(done){

     // spawn remote mesh in another process
    remote = spawn('node', [libFolder + 'c6-remote-mesh']);

    //NB - the remote mesh is configured to initialize the datalayer with https, by setting the transport option:
    //   dataLayer: {
    //   transport:{
    //     mode:'https'
    //   },
    //   port: 3111,
    // },

    remote.stdout.on('data', function(data) {

      console.log(data.toString());

      if (data.toString().match(/READY/)){
        testClient = new Mesh.MeshClient({port:3111, protocol:'https', allowSelfSignedCerts:true});
        testClient.login().then(function(e){
          done(e);
        });
      }

    });

  });

  it('fails to connect, wrong transport on client', function(done) {

     var nodeProc = Number(process.version.match(/^v(\d+\.\d+)/)[1]);
     var timeout;

     if (nodeProc == '0.10') {
      timeout = setTimeout(function(){
        done();
      }, 3000);
     }

     var badClient = new Mesh.MeshClient({port:3111});
      badClient.login().then(function(e){
       done(new Error('this was not meant to happen'));
      }).catch(function(e){
        expect(e.toString()).to.equal('Error: socket hang up');
        if (nodeProc != '0.10') done();
      });

  });

  it('does a set on the datalayer component', function(done) {

     testClient.exchange.test_c6.data.set('/c6-https/set', {"val":"set"}, function(e, result){

      if (e) return done(e);

      expect(result.val).to.be("set");

      done();

     });

  });

  it('does a get on the datalayer component', function(done) {

    testClient.exchange.test_c6.data.set('/c6-https/get', {"val":"get"}, function(e, result){

      if (e) return done(e);

      expect(result.val).to.be("get");

      testClient.exchange.test_c6.data.get('/c6-https/get', {}, function(e, getresult){

        if (e) return done(e);

        // console.log('get happened:::', getresult);

        expect(getresult.val).to.be("get");
        done();

      });

     });

  });

  it('does a delete on the datalayer component', function(done) {

     testClient.exchange.test_c6.data.set('/c6-https/delete', {"val":"delete"}, function(e, result){

      if (e) return done(e);

      expect(result.val).to.be("delete");

      testClient.exchange.test_c6.data.get('/c6-https/delete', {}, function(e, getresult){

        if (e) return done(e);

        expect(getresult.val).to.be("delete");

        testClient.exchange.test_c6.data.remove('/c6-https/delete', {}, function(e, removeresult){

          if (e) return done(e);

          // console.log('delete happened:::', removeresult);

          testClient.exchange.test_c6.data.get('/c6-https/delete', {}, function(e, getremovedresult){

            if (e) return done(e);

            expect(getremovedresult).to.be(null);
            done();

          });

        });

      });

     });

  });

  xit('does an on, on the datalayer component', function(done) {

  });

  xit('runs a method on a component', function(done) {

  });

  xit('runs attaches to an event on a component', function(done) {

  });

  require('benchmarket').stop();

});

<commit_msg>investigate env vars in travis<commit_after>describe('c6 - https', function(done) {

  require('benchmarket').start();
  after(require('benchmarket').store());

  this.timeout(20000);

  var Mesh = require('../')

  var spawn = require('child_process').spawn;
  var expect = require('expect.js');
  var sep = require('path').sep;
  var libFolder = __dirname + sep + 'lib' + sep;

  var test_id = Date.now() + '_' + require('shortid').generate();
  var should = require('chai').should();

  after(function(done){
     remote.kill();
     done();
  });

  var testClient;

  before(function(done){

     // spawn remote mesh in another process
    remote = spawn('node', [libFolder + 'c6-remote-mesh']);

    //NB - the remote mesh is configured to initialize the datalayer with https, by setting the transport option:
    //   dataLayer: {
    //   transport:{
    //     mode:'https'
    //   },
    //   port: 3111,
    // },

    remote.stdout.on('data', function(data) {

      console.log(data.toString());

      if (data.toString().match(/READY/)){
        testClient = new Mesh.MeshClient({port:3111, protocol:'https', allowSelfSignedCerts:true});
        testClient.login().then(function(e){
          done(e);
        });
      }

    });

  });

  it.only('fails to connect, wrong transport on client', function(done) {

    console.log(process.env.BENCHMARKET_API_URI);

     var nodeProc = Number(process.version.match(/^v(\d+\.\d+)/)[1]);
     var timeout;

     if (nodeProc == '0.10') {
      timeout = setTimeout(function(){
        done();
      }, 3000);
     }

     var badClient = new Mesh.MeshClient({port:3111});
      badClient.login().then(function(e){
       done(new Error('this was not meant to happen'));
      }).catch(function(e){
        expect(e.toString()).to.equal('Error: socket hang up');
        if (nodeProc != '0.10') done();
      });

  });

  it('does a set on the datalayer component', function(done) {

     testClient.exchange.test_c6.data.set('/c6-https/set', {"val":"set"}, function(e, result){

      if (e) return done(e);

      expect(result.val).to.be("set");

      done();

     });

  });

  it('does a get on the datalayer component', function(done) {

    testClient.exchange.test_c6.data.set('/c6-https/get', {"val":"get"}, function(e, result){

      if (e) return done(e);

      expect(result.val).to.be("get");

      testClient.exchange.test_c6.data.get('/c6-https/get', {}, function(e, getresult){

        if (e) return done(e);

        // console.log('get happened:::', getresult);

        expect(getresult.val).to.be("get");
        done();

      });

     });

  });

  it('does a delete on the datalayer component', function(done) {

     testClient.exchange.test_c6.data.set('/c6-https/delete', {"val":"delete"}, function(e, result){

      if (e) return done(e);

      expect(result.val).to.be("delete");

      testClient.exchange.test_c6.data.get('/c6-https/delete', {}, function(e, getresult){

        if (e) return done(e);

        expect(getresult.val).to.be("delete");

        testClient.exchange.test_c6.data.remove('/c6-https/delete', {}, function(e, removeresult){

          if (e) return done(e);

          // console.log('delete happened:::', removeresult);

          testClient.exchange.test_c6.data.get('/c6-https/delete', {}, function(e, getremovedresult){

            if (e) return done(e);

            expect(getremovedresult).to.be(null);
            done();

          });

        });

      });

     });

  });

  xit('does an on, on the datalayer component', function(done) {

  });

  xit('runs a method on a component', function(done) {

  });

  xit('runs attaches to an event on a component', function(done) {

  });

  require('benchmarket').stop();

});

<|endoftext|>


<commit_before>import program from "commander";
import fs from "fs";
import hasYarn from "has-yarn";
import createTasks from "./tasks";

const defaultOptions = {
  hook: "build",
  directory: "dist",
  remote: "origin",
  branch: "gh-pages",
  yarn: hasYarn (),
  anyBranch: false,
  commit: true,
  publish: true
};

program
  .option ("--any-branch", "Allow pushing from any branch")
  .option ("--no-yarn", "Don't use Yarn")
  .option ("-C, --commit <commit>", "Optional commit message")
  .option ("--no-commit", "Don't commit")
  .option ("--no-push", "Don't push to branch")
  .option (
    "-H, --hook <hook>",
    "NPM hook that builds your static website (defaults to `build`)"
  )
  .option (
    "-D, --directory <path>",
    "Directory that will be pushed to separate branch"
  )
  .option ("-B, --branch <branch>", "Branch that will be used as subtree")
  .option ("-R, --remote <remote>", "Repository that will be pushed to")
  .parse (process.argv);

const options = Object.assign ({}, defaultOptions, program);
const tasks = createTasks (options);

tasks.run ().catch (error => console.error (error));
<commit_msg>refactor: Updated wording on --hook description<commit_after>import program from "commander";
import hasYarn from "has-yarn";
import createTasks from "./tasks";

const defaultOptions = {
  hook: "build",
  directory: "dist",
  remote: "origin",
  branch: "gh-pages",
  yarn: hasYarn (),
  anyBranch: false,
  commit: true,
  publish: true
};

program
  .option ("--any-branch", "Allow pushing from any branch")
  .option ("--no-yarn", "Don't use Yarn")
  .option ("-C, --commit <commit>", "Optional commit message")
  .option ("--no-commit", "Don't commit")
  .option ("--no-push", "Don't push to branch")
  .option ("-H, --hook <hook>", "NPM hook that builds your static website")
  .option (
    "-D, --directory <path>",
    "Directory that will be pushed to separate branch"
  )
  .option ("-B, --branch <branch>", "Branch that will be used as subtree")
  .option ("-R, --remote <remote>", "Repository that will be pushed to")
  .parse (process.argv);

const options = Object.assign ({}, defaultOptions, program);
const tasks = createTasks (options);

tasks.run ().catch (error => console.error (error));
<|endoftext|>