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

// Components
import Button from "./components/button";

// Functions
import Addition from "./functions/addition";
import Subtract from "./functions/subtract";
import Multiply from "./functions/multiply";
import Divide from "./functions/divide";
import Rotation from 'react-rotation'

import './App.css';
import './Color.css';

class App extends Component {

  state = {
      input: "0",
      math: null,
      sum: null,
      resetNext: false,
      firstEntry: true,
      theme: "red",
    };

    buttons = ["C", "(-)", "<", "/", 1, 2, 3, "*", 4, 5, 6, "-", 7 ,8, 9, "+", 0, ".", "="];

  // Run when app is loaded
  componentWillMount() {
    // this.getLocalStorage();
  }

  handleInputClick(input) {
        this.setState({whatevz:false});

    if (typeof input === "number") {

      if (this.state.resetNext) {
        // reset input if resetNext = true
        this.setState({input: input.toString(), resetNext: false});
      } else {

        // Concatenate input string
        this.setState({input : this.state.input + input.toString()});
      }

    } else if (input === "(-)") {
      // If user input negative (-)
      this.handelNegative();

    } else if (input === ".") {
      // If user input negative (-)
      this.handelComma();

    } else if (input === "C" || input.toUpperCase() === "C") {
      // If user input C
      this.handelClear();

    } else if (input === "=") {
      // If user input =
      this.handelEqual();

    } else if (input === "<") {
      // If user input < (backspace)
      this.handelBackspace();

    } else {
      // If user input +, -, *, /...
      this.setState({resetNext: true});

      if (input !== this.state.math && this.state.math && this.state.math !== "=") {
        // If the user switch between +, -, *, /
        this.handelMathSwitch(input);

      } else {
        this.handelMath(input);
      }

    }
  }

  // ---------------------
  // Handle negative input, only allow one minus key
  // ---------------------
  handelNegative() {
    if (this.state.resetNext) {
      // reset input if resetNext = true
      this.setState({input: "-", resetNext: false});
    } else if (this.state.input.includes("-")) {
      return;
    } else {
        this.setState({input: "-" + this.state.input});
    }
  }

  // ---------------------
  // Handel comma input, only allow one comma key
  // ---------------------
  handelComma() {
    if (this.state.resetNext || this.state.input === "") {
      // reset input if resetNext = true
      this.setState({input: "0.", resetNext: false});
    } else {
      var reg = new RegExp("[.]");
      reg= reg.test(this.state.input);
      this.setState({input: (reg) ? this.state.input.toString() : this.state.input + "."});
    }
  }

  // ---------------------
  // Reset state to original
  // ---------------------
  handelClear() {
    this.setState({
      input: "",
      math: null,
      sum: null,
      resetNext: false,
      firstEntry: true,
    });
  }

  // ---------------------
  // Delete the last number in string, backspace
  // ---------------------
  handelBackspace() {
    this.setState({input: this.state.input.slice(0, -1)});
  }

  // ---------------------
  // Handel equal: handel math, set new state
  // ---------------------
  handelEqual() {
    this.handelMath(this.state.math);
    this.setState({
      firstEntry: true,
      math: "=",
      resetNext: true,
      sum: null,
      whatevz: true
    });
  }

  // ---------------------
  // Handel math switch: handel math and set new state
  // ---------------------
  handelMathSwitch(input) {
    this.handelMath(this.state.math);
    this.setState({
      firstEntry: false,
      math: input,
      resetNext: true
    });
  }

  // ---------------------
  // Save state to localStorage
  // ---------------------
  postLocalStorage() {
    const jsonString = JSON.stringify(this.state);
    localStorage.setItem('calc', jsonString);
  }

  // ---------------------
  // Load state from localStorage
  // ---------------------
  getLocalStorage() {
    const savedState = JSON.parse(localStorage.getItem('calc'));
    this.setState(savedState);
  }

  // ---------------------
  // Handle all math, set new state
  // ---------------------
  handelMath(input) {
    if (this.state.firstEntry) {
      // This only moves the input to state.sum
      this.setState({
        sum: this.state.input,
        math: input,
        firstEntry: false,
      });
    } else {
      switch(input) {
        case "+":
          this.setState({
            input: Addition(this.state.sum, this.state.input).toString(),
            sum: Addition(this.state.sum, this.state.input),
            math: "+",
          });
          break;
        case "-":
          this.setState({
            input: Subtract(this.state.sum, this.state.input).toString(),
            sum: Subtract(this.state.sum, this.state.input),
            math: "-"
          });
          break;
        case "*":
          this.setState({
            input: Multiply(this.state.sum, this.state.input).toString(),
            sum: Multiply(this.state.sum, this.state.input),
            math: "*"
          });
          break;
        case "/":
          this.setState({
            input: Divide(this.state.sum, this.state.input).toString(),
            sum: Divide(this.state.sum, this.state.input),
            math: "/"
          });
          break;
        default:
          break;
      }
    }
  }

  handelChangeTheme() {
    const newTheme = this.state.theme === "red" ? "blue" : "red";
    this.setState({theme: newTheme});
  }

  // React, render to DOM
  render() {
    // this.postLocalStorage();
    return (

        <div className={`calculator ${this.state.theme}`}>

            <button className="themes" onClick={() => this.handelChangeTheme()}>∞</button>

calc

          <div className={`input ${this.state.whatevz ? "animationz" : ""}`}>
            {this.state.input ? this.state.input : 0}

          {/*

            {this.handelHistory()}

 */}

            {this.buttons.map((int) => <Button key={int} onClick={this.handleInputClick.bind(this)} math={this.state.math}>{int}</Button>)}

    );
  }
}
export default App;
<commit_msg>fixed comma<commit_after>
import React, { Component } from 'react';

// Components
import Button from "./components/button";

// Functions
import Addition from "./functions/addition";
import Subtract from "./functions/subtract";
import Multiply from "./functions/multiply";
import Divide from "./functions/divide";
import Rotation from 'react-rotation'

import './App.css';
import './Color.css';

class App extends Component {

  state = {
      input: "0",
      math: null,
      sum: null,
      resetNext: false,
      firstEntry: true,
      theme: "red",
    };

    buttons = ["C", "(-)", "<", "/", 1, 2, 3, "*", 4, 5, 6, "-", 7 ,8, 9, "+", 0, ".", "="];

  // Run when app is loaded
  componentWillMount() {
    // this.getLocalStorage();
  }

  handleInputClick(input) {
        this.setState({whatevz:false});

    if (typeof input === "number") {

      if (this.state.resetNext) {
        // reset input if resetNext = true
        this.setState({input: input.toString(), resetNext: false});
      } else {

        // Concatenate input string
        this.setState({input : this.state.input === "" ?  input.toString() : this.state.input + input.toString()});
      }

    } else if (input === "(-)") {
      // If user input negative (-)
      this.handelNegative();

    } else if (input === ".") {
      // If user input negative (-)
      this.handelComma();

    } else if (input === "C" || input.toUpperCase() === "C") {
      // If user input C
      this.handelClear();

    } else if (input === "=") {
      // If user input =
      this.handelEqual();

    } else if (input === "<") {
      // If user input < (backspace)
      this.handelBackspace();

    } else {
      // If user input +, -, *, /...
      this.setState({resetNext: true});

      if (input !== this.state.math && this.state.math && this.state.math !== "=") {
        // If the user switch between +, -, *, /
        this.handelMathSwitch(input);

      } else {
        this.handelMath(input);
      }

    }
  }

  // ---------------------
  // Handle negative input, only allow one minus key
  // ---------------------
  handelNegative() {
    if (this.state.resetNext) {
      // reset input if resetNext = true
      this.setState({input: "-", resetNext: false});
    } else if (this.state.input.includes("-")) {
      return;
    } else {
        this.setState({input: "-" + this.state.input});
    }
  }

  // ---------------------
  // Handel comma input, only allow one comma key
  // ---------------------
  handelComma() {
    if (this.state.resetNext || this.state.input === "") {
      // reset input if resetNext = true
      this.setState({input: "0.", resetNext: false});
    } else {
      var reg = new RegExp("[.]");
      reg= reg.test(this.state.input);
      this.setState({input: (reg) ? this.state.input.toString() : this.state.input + "."});
    }
  }

  // ---------------------
  // Reset state to original
  // ---------------------
  handelClear() {
    this.setState({
      input: "",
      math: null,
      sum: null,
      resetNext: false,
      firstEntry: true,
    });
  }

  // ---------------------
  // Delete the last number in string, backspace
  // ---------------------
  handelBackspace() {
    this.setState({input: this.state.input.slice(0, -1)});
  }

  // ---------------------
  // Handel equal: handel math, set new state
  // ---------------------
  handelEqual() {
    this.handelMath(this.state.math);
    this.setState({
      firstEntry: true,
      math: "=",
      resetNext: true,
      sum: null,
      whatevz: true
    });
  }

  // ---------------------
  // Handel math switch: handel math and set new state
  // ---------------------
  handelMathSwitch(input) {
    this.handelMath(this.state.math);
    this.setState({
      firstEntry: false,
      math: input,
      resetNext: true
    });
  }

  // ---------------------
  // Save state to localStorage
  // ---------------------
  postLocalStorage() {
    const jsonString = JSON.stringify(this.state);
    localStorage.setItem('calc', jsonString);
  }

  // ---------------------
  // Load state from localStorage
  // ---------------------
  getLocalStorage() {
    const savedState = JSON.parse(localStorage.getItem('calc'));
    this.setState(savedState);
  }

  // ---------------------
  // Handle all math, set new state
  // ---------------------
  handelMath(input) {
    if (this.state.firstEntry) {
      // This only moves the input to state.sum
      this.setState({
        sum: this.state.input,
        math: input,
        firstEntry: false,
      });
    } else {
      switch(input) {
        case "+":
          this.setState({
            input: Addition(this.state.sum, this.state.input).toString(),
            sum: Addition(this.state.sum, this.state.input),
            math: "+",
          });
          break;
        case "-":
          this.setState({
            input: Subtract(this.state.sum, this.state.input).toString(),
            sum: Subtract(this.state.sum, this.state.input),
            math: "-"
          });
          break;
        case "*":
          this.setState({
            input: Multiply(this.state.sum, this.state.input).toString(),
            sum: Multiply(this.state.sum, this.state.input),
            math: "*"
          });
          break;
        case "/":
          this.setState({
            input: Divide(this.state.sum, this.state.input).toString(),
            sum: Divide(this.state.sum, this.state.input),
            math: "/"
          });
          break;
        default:
          break;
      }
    }
  }

  handelChangeTheme() {
    const newTheme = this.state.theme === "red" ? "blue" : "red";
    this.setState({theme: newTheme});
  }

  // React, render to DOM
  render() {
    // this.postLocalStorage();
    return (

        <div className={`calculator ${this.state.theme}`}>

            <button className="themes" onClick={() => this.handelChangeTheme()}>∞</button>

calc

          <div className={`input ${this.state.whatevz ? "animationz" : ""}`}>
            {this.state.input ? this.state.input : 0}

          {/*

            {this.handelHistory()}

 */}

            {this.buttons.map((int) => <Button key={int} onClick={this.handleInputClick.bind(this)} math={this.state.math}>{int}</Button>)}

    );
  }
}
export default App;
<|endoftext|>


<commit_before>import TyphonEvents  from 'backbone-common/src/TyphonEvents.js';
import Queue         from './Queue.js';
import Socket        from './Socket.js';

const DDP_VERSION = '1';

const RECONNECT_INTERVAL = 10000;

export default class DDP extends TyphonEvents
{
   constructor(options)
   {
      super();

      this.status = 'disconnected';

      this.messageQueue = new Queue((message) =>
      {
         if (this.status === 'connected') { this.socket.send(message); return true; }
         else { return false; }
      });

      this.socket = new Socket(options.SocketConstructor, options.endpoint).connect();

      this._init();
   }

   _init()
   {
      // When the socket opens, send the `connect` message to establish the DDP connection.
      this.socket.on('open', () =>
      {
         this.socket.send({ msg: 'connect', version: DDP_VERSION, support: [DDP_VERSION] });
      });

      this.socket.on('close', () =>
      {
         this.status = 'disconnected';
         this.messageQueue.empty();
         super.triggerDefer('disconnected');

         // Schedule a reconnection
         setTimeout(this.socket.connect.bind(this.socket), RECONNECT_INTERVAL);
      });

      this.socket.on('message:in', (message) =>
      {
         switch (message.msg)
         {
            case 'connected':
               this.status = 'connected';
               this.messageQueue.process();
               super.triggerDefer('connected');
               break;

            // Reply with a `pong` message to prevent the server from closing the connection.
            case 'ping':
               this.socket.send({ msg: 'pong', id: message.id });
               break;

            case 'error':
            case 'result':
            case 'updated':
               super.triggerDefer(message.msg, message);
               break;

            // Subscriptions
            case 'ready':
               // Send specific `ready` events with the subscription `id`.
               if (Array.isArray(message.subs))
               {
                  message.subs.forEach((id) => { super.triggerDefer(`sub:${message.msg}:${id}`, message); });
               }
               break;
            case 'nosub':
            case 'added':
            case 'changed':
            case 'removed':
               super.triggerDefer(message.msg, message);
               break;
         }
      });
   }

   method(name, params)
   {
      const id = s_UNIQUE_ID();

      this.messageQueue.push({ msg: 'method', id, name, params });

      return id;
   }

   sub(name, params)
   {
      const id = s_UNIQUE_ID();

      this.messageQueue.push({ msg: 'sub', id, name, params });

      return id;
   }

   triggerDefer()
   {
      setTimeout(() => { super.trigger(this, ...arguments); }, 0);
   }

   unsub(id)
   {
      this.messageQueue.push({ msg: 'unsub', id });

      return id;
   }
}

// Private Utility Methods ------------------------------------------------------------------------------------------

let uniqueID = 0;

/**
 * Returns a unique ID.
 *
 * @returns {string}
 */
const s_UNIQUE_ID = () => { return (uniqueID++).toString(); };<commit_msg>Code formatting.<commit_after>import TyphonEvents  from 'backbone-common/src/TyphonEvents.js';
import Queue         from './Queue.js';
import Socket        from './Socket.js';

const DDP_VERSION = '1';

const RECONNECT_INTERVAL = 10000;

export default class DDP extends TyphonEvents
{
   constructor(options)
   {
      super();

      this.status = 'disconnected';

      this.messageQueue = new Queue((message) =>
      {
         if (this.status === 'connected') { this.socket.send(message); return true; }
         else { return false; }
      });

      this.socket = new Socket(options.SocketConstructor, options.endpoint).connect();

      this._init();
   }

   _init()
   {
      // When the socket opens, send the `connect` message to establish the DDP connection.
      this.socket.on('open', () =>
      {
         this.socket.send({ msg: 'connect', version: DDP_VERSION, support: [DDP_VERSION] });
      });

      this.socket.on('close', () =>
      {
         this.status = 'disconnected';
         this.messageQueue.empty();
         super.triggerDefer('disconnected');

         // Schedule a reconnection
         setTimeout(this.socket.connect.bind(this.socket), RECONNECT_INTERVAL);
      });

      this.socket.on('message:in', (message) =>
      {
         switch (message.msg)
         {
            case 'connected':
               this.status = 'connected';
               this.messageQueue.process();
               super.triggerDefer('connected');
               break;

            // Reply with a `pong` message to prevent the server from closing the connection.
            case 'ping':
               this.socket.send({ msg: 'pong', id: message.id });
               break;

            case 'error':
            case 'result':
            case 'updated':
               super.triggerDefer(message.msg, message);
               break;

            // Subscriptions
            case 'ready':
               // Send specific `ready` events with the subscription `id`.
               if (Array.isArray(message.subs))
               {
                  message.subs.forEach((id) => { super.triggerDefer(`sub:${message.msg}:${id}`, message); });
               }
               break;
            case 'nosub':
            case 'added':
            case 'changed':
            case 'removed':
               super.triggerDefer(message.msg, message);
               break;
         }
      });
   }

   method(name, params)
   {
      const id = s_UNIQUE_ID();

      this.messageQueue.push({ msg: 'method', id, name, params });

      return id;
   }

   sub(name, params)
   {
      const id = s_UNIQUE_ID();

      this.messageQueue.push({ msg: 'sub', id, name, params });

      return id;
   }

   unsub(id)
   {
      this.messageQueue.push({ msg: 'unsub', id });

      return id;
   }
}

// Private Utility Methods ------------------------------------------------------------------------------------------

let uniqueID = 0;

/**
 * Returns a unique ID.
 *
 * @returns {string}
 */
const s_UNIQUE_ID = () => { return (uniqueID++).toString(); };<|endoftext|>


<commit_before>//@flow
import cssRgba from "./utils/cssRgba";
import KenBurnsBase from "./Base";
import type {Bound, WidthHeight} from "./Base";

type Source = HTMLElement | Image;

/**
  * DOM Kenburns effect.
  *
  * **Supported source:** any HTML Element or an `Image`.
  *
  * NB: the container & source DOM element style are getting mutated by KenBurnsDOM. Make sure you don't alter them while performing the effect.
  *
  *
  * @example
  *
  * import KenBurnsDOM from "kenburns/lib/DOM";
  * var div = document.createElement("div");
  * div.style.width = "400px";
  * div.style.height = "400px";
  * const kenBurnsDOM = new KenBurnsDOM(div);
  * // kenBurnsDOM.animate(...).then(...);
  * // kenBurnsDOM.animateStep(...);
  */
export default class KenBurnsDOM extends KenBurnsBase<Source> {
  container: HTMLElement;
  source: HTMLElement;
  _currentBackgroundColorStyle: ?string;
  /**
   * Create a DOM KenBurns with a container element (block element recommended).
   */
  constructor (container: HTMLElement) {
    super();
    this.container = container;
    this._currentBackgroundColorStyle = container.style.backgroundColor;
    // At least we need relative
    if (container.style.position !== "absolute") {
      container.style.position = "relative";
    }
    container.style.overflow = "hidden";
  }
  getViewport () {
    return this.container.getBoundingClientRect();
  }
  getSourceSize (source: Source): WidthHeight {
    return source instanceof Image || source instanceof HTMLImageElement
    ? source
    : source.getBoundingClientRect();
  }
  draw (source: Source, rect: Bound) {
    if (source !== this.source) {
      this.container.innerHTML = "";
      this.container.appendChild(source);
      source.style.position = "absolute";

      source.style.willChange = "transform"; // already supported by some browsers, ensures GPU acceleration
      source.style.outline = "1px solid transparent";         // improves edges
      source.style.backfaceVisibility = 'hidden';             // "
      source.style['-webkit-backface-visibility'] = 'hidden'; // "
      source.style.boxShadow = '0 0 1px rgba(255,255,255,0)'; // "

      source.style.top = "0px";
      source.style.left = "0px";
      source.style.transformOrigin = "0% 0%";
      this.source = source;
    }
    const backgroundColor = cssRgba(this.background);
    if (backgroundColor !== this._currentBackgroundColorStyle) {
      this._currentBackgroundColorStyle = backgroundColor;
      this.container.style.backgroundColor = backgroundColor;
    }
    const viewport = this.getViewport();
    const scale = (viewport.width / rect[2]).toFixed(4); // no need to handle the height dimension because ratio is preserved
    const translate = (-rect[0]).toFixed(2)+"px,"+(-rect[1]).toFixed(2)+"px";
    this.source.style.transform = "scale("+scale+") translate("+translate+") translateZ(0)"; // translateZ triggers GPU acceleration
  }
}
<commit_msg>Update DOM.js<commit_after>//@flow
import cssRgba from "./utils/cssRgba";
import KenBurnsBase from "./Base";
import type {Bound, WidthHeight} from "./Base";

type Source = HTMLElement | Image;

/**
  * DOM Kenburns effect.
  *
  * **Supported source:** any HTML Element or an `Image`.
  *
  * NB: the container & source DOM element style are getting mutated by KenBurnsDOM. Make sure you don't alter them while performing the effect.
  *
  *
  * @example
  *
  * import KenBurnsDOM from "kenburns/lib/DOM";
  * var div = document.createElement("div");
  * div.style.width = "400px";
  * div.style.height = "400px";
  * const kenBurnsDOM = new KenBurnsDOM(div);
  * // kenBurnsDOM.animate(...).then(...);
  * // kenBurnsDOM.animateStep(...);
  */
export default class KenBurnsDOM extends KenBurnsBase<Source> {
  container: HTMLElement;
  source: HTMLElement;
  _currentBackgroundColorStyle: ?string;
  /**
   * Create a DOM KenBurns with a container element (block element recommended).
   */
  constructor (container: HTMLElement) {
    super();
    this.container = container;
    this._currentBackgroundColorStyle = container.style.backgroundColor;
    // At least we need relative
    if (container.style.position !== "absolute") {
      container.style.position = "relative";
    }
    container.style.overflow = "hidden";
  }
  getViewport () {
    return this.container.getBoundingClientRect();
  }
  getSourceSize (source: Source): WidthHeight {
    return source instanceof Image || source instanceof HTMLImageElement
    ? source
    : source.getBoundingClientRect();
  }
  draw (source: Source, rect: Bound) {
    if (source !== this.source) {
      this.container.innerHTML = "";
      this.container.appendChild(source);
      source.style.position = "absolute";

      source.style.willChange = "transform"; // already supported by some browsers, ensures GPU acceleration

      // improves edge rendering (http://stackoverflow.com/questions/6492027/css-transform-jagged-edges-in-chrome):
      source.style.outline = "1px solid transparent";
      source.style.backfaceVisibility = "hidden";
      source.style.WebkitBackfaceVisibility = "hidden";
      source.style.boxShadow = "0 0 1px rgba(255,255,255,0)";

      source.style.top = "0px";
      source.style.left = "0px";
      source.style.transformOrigin = "0% 0%";
      this.source = source;
    }
    const backgroundColor = cssRgba(this.background);
    if (backgroundColor !== this._currentBackgroundColorStyle) {
      this._currentBackgroundColorStyle = backgroundColor;
      this.container.style.backgroundColor = backgroundColor;
    }
    const viewport = this.getViewport();
    const scale = (viewport.width / rect[2]).toFixed(4); // no need to handle the height dimension because ratio is preserved
    const translate = (-rect[0]).toFixed(2)+"px,"+(-rect[1]).toFixed(2)+"px";
    this.source.style.transform = "scale("+scale+") translate("+translate+") translateZ(0)"; // translateZ triggers GPU acceleration
  }
}
<|endoftext|>


<commit_before>var isCursor = function (c) {
  return c && c._publishCursor;
};

var deepCopy = function(value) {
  return EJSON.clone(value);
}

function Dependency(callback) {
  this.callback = callback;
  this.id = Random.id();
}

function BaseCollection(name) {
  this.name = name;
  this.relations = {};
}

function BaseCollectionItem(id, collection, fields, index) {
  this.id = id;
  this.collection = collection;
  this.count = 1;
  this.data = {};
  this.mergedData = deepCopy(fields);
  this.children = {};
  var self = this;
  _.each(fields, function(val, key) {
    self.data[key] = self.data[key] || {};
    self.data[key][index] = deepCopy(val);
  });
}
BaseCollectionItem.prototype.updateFromData = function(fields) {
  var res = {};
  var merged = this.mergedData;
  var self = this;
  _.each(fields, function(flag, key) {
    var cur = undefined;
    _.each(self.data[key], (function(value) {
      cur = _.extend(deepCopy(value), cur);
    }));
    res[key] = cur;
    if (_.isUndefined(cur)) {
      delete merged[key];
    } else {
      merged[key] = cur;
    }
  });
  this.publication.changed(this.collection.name, this.id, res);
}

Meteor.smartPublish = function(name, callback) {
  Meteor.publish(name, function() {
    var publication = this;
    var collections = {};
    function getCollectionByName(name) {
      return collections[name] = collections[name] || new Collection(name);
    }

    function Collection() {
      BaseCollection.apply(this, arguments);
    }
    Collection.prototype = Object.create(BaseCollection.prototype);
    Collection.prototype.publication = publication;

    function CollectionItem() {
      BaseCollectionItem.apply(this, arguments);
    }
    CollectionItem.prototype = Object.create(BaseCollectionItem.prototype);
    CollectionItem.prototype.publication = publication;

    publication.CollectionItem = CollectionItem;

    publication.updateChildren = function(itemm, fields, removeAll) {
      var update = {};
      _.each(fields, function(flag, key) {
        if (!itemm.collection.relations[key]) return;
        _.each(itemm.collection.relations[key], function(dep) {
          update[dep.id] = dep;
        });
      });
      _.each(update, function(dep) {
        var toRemove = [];
        if (dep.id in itemm.children) {
          itemm.children[dep.id].forEach(function(x, i) {
            _.each(x.activeItems, function(flag, subid) {
              toRemove.push([x.collection, x.index, subid]);
            });
            x.observer.stop();
          });
        }

        if (!removeAll) {
          var cursors = dep.callback(itemm.mergedData);
          if (isCursor(cursors)) cursors = [cursors];
          if (!_.isArray(cursors))
            throw new Meteor.Error("Dependency function can only return a Cursor or an array of Cursors");

          var observers = itemm.children[dep.id] = [];
          for (var i = 0; i < cursors.length; i++) {
            var c = cursors[i];
            if (!isCursor(c))
              throw new Meteor.Error("Dependency function returned an array of non-Cursors");

            if (!c._cursorDescription) throw new Meteor.Error("Unable to get cursor's collection name");
            var subname = c._cursorDescription.collectionName;
            if (!subname) throw new Meteor.Error("Unable to get cursor's collection name");

            observers.push(new CursorWrapper(c, getCollectionByName(subname)));
          }
        }
        toRemove.forEach(function(args) {
          Collection.prototype.smartRemoved.apply(args[0], args.slice(1));
        });
      });
    }
    Collection.prototype.smartAdded = function(index, id, fields) {
      var self = this;
      if (!self[id]) {
        self.publication.added(self.name, id, fields);
        self[id] = new publication.CollectionItem(id, self, fields, index);
        self.publication.updateChildren(self[id], self.relations);
      } else {
        _.each(fields, function(val, key) {
          self[id].data[key] = self[id].data[key] || {};
          self[id].data[key][index] = deepCopy(val);
        });
        self[id].count++;
        self[id].updateFromData(fields);
        self.publication.updateChildren(self[id], fields);
      }
    }
    Collection.prototype.smartChanged = function(index, id, fields) {
      var data = this[id].data;
      _.each(fields, function(val, key) {
        if (!data[key]) data[key] = {};
        if (val === undefined) {
          delete data[key][index];
        } else {
          data[key][index] = deepCopy(val);
        }
      });
      this[id].updateFromData(fields);
      this.publication.updateChildren(this[id], fields);
    }
    Collection.prototype.smartRemoved = function(index, id) {
      if (!this[id]) throw new Meteor.Error("Removing unexisting element '" + id + "' from collection '" + this.name + "'");

      if (!--this[id].count) { // If reference counter was decremented to zero
        this.publication.updateChildren(this[id], this.relations, true);
        delete this[id];
        this.publication.removed(this.name, id);
      } else {
        var fields = {};
        _.each(this[id].data, function(vals, key) {
          if (index in vals) {
            fields[key] = 1;
            delete vals[index];
          }
        });
        this[id].updateFromData(fields);
        this.publication.updateChildren(this[id], fields);
      }
    }

    publication.addDependency = function(name, fields, callback) {
      if (!_.isArray(fields)) fields = [fields];
      var relations = getCollectionByName(name).relations;
      var dep = new Dependency(callback);
      fields.forEach(function(field) {
        if (field.indexOf(".") != -1) { // See #8
          field = field.substr(0, field.indexOf("."));
        }
        relations[field] = relations[field] || [];
        relations[field].push(dep);
      });
    }

    var cursors = callback.apply(publication, arguments);
    if (isCursor(cursors)) cursors = [cursors];

    if (!cursors) return;
    if (!_.isArray(cursors))
      throw new Meteor.Error("Publish function can only return a Cursor or an array of Cursors");

    for (var i = 0; i < cursors.length; i++)
      if (!isCursor(cursors[i]))
        throw new Meteor.Error("Publish function returned an array of non-Cursors");

    var observers = [];
    for (var i = 0; i < cursors.length; i++) {
      var c = cursors[i];

      if (!c._cursorDescription) throw new Meteor.Error("Unable to get cursor's collection name");

      function CursorWrapper(cursor, collection) {
        this.activeItems = {};
        this.collection = collection;
        this.index = Random.id();
        var self = this;
        this.observer = cursor.observeChanges({
          added:   function(id, fields) {
            self.activeItems[id] = 1;
            fields['_id'] = id;
            collection.smartAdded  (self.index, id, fields);
          },
          changed: function(id, fields) {
            collection.smartChanged(self.index, id, fields);
          },
          removed: function(id) {
            delete self.activeItems[id];
            collection.smartRemoved(self.index, id);
          },
        })
      };

      var name = c._cursorDescription.collectionName;
      if (!name) throw new Meteor.Error("Unable to get cursor's collection name");
      observers.push(new CursorWrapper(c, getCollectionByName(name)).observer);
    }
    this.ready();
    this.onStop(function() {
      _.forEach(observers, function(x) { x.stop(); });
    });
  });
}
<commit_msg>smart{Added,Changed,Removed} were moved to BaseCollection'<commit_after>var isCursor = function (c) {
  return c && c._publishCursor;
};

var deepCopy = function(value) {
  return EJSON.clone(value);
}

function Dependency(callback) {
  this.callback = callback;
  this.id = Random.id();
}

function BaseCollection(name) {
  this.name = name;
  this.relations = {};
}
BaseCollection.prototype.smartAdded = function(index, id, fields) {
  var self = this;
  if (!self[id]) {
    self.publication.added(self.name, id, fields);
    self[id] = new self.publication.CollectionItem(id, self, fields, index);
    self.publication.updateChildren(self[id], self.relations);
  } else {
    _.each(fields, function(val, key) {
      self[id].data[key] = self[id].data[key] || {};
      self[id].data[key][index] = deepCopy(val);
    });
    self[id].count++;
    self[id].updateFromData(fields);
    self.publication.updateChildren(self[id], fields);
  }
}
BaseCollection.prototype.smartChanged = function(index, id, fields) {
  var data = this[id].data;
  _.each(fields, function(val, key) {
    if (!data[key]) data[key] = {};
    if (val === undefined) {
      delete data[key][index];
    } else {
      data[key][index] = deepCopy(val);
    }
  });
  this[id].updateFromData(fields);
  this.publication.updateChildren(this[id], fields);
}
BaseCollection.prototype.smartRemoved = function(index, id) {
  if (!this[id]) throw new Meteor.Error("Removing unexisting element '" + id + "' from collection '" + this.name + "'");

  if (!--this[id].count) { // If reference counter was decremented to zero
    this.publication.updateChildren(this[id], this.relations, true);
    delete this[id];
    this.publication.removed(this.name, id);
  } else {
    var fields = {};
    _.each(this[id].data, function(vals, key) {
      if (index in vals) {
        fields[key] = 1;
        delete vals[index];
      }
    });
    this[id].updateFromData(fields);
    this.publication.updateChildren(this[id], fields);
  }
}

function BaseCollectionItem(id, collection, fields, index) {
  this.id = id;
  this.collection = collection;
  this.count = 1;
  this.data = {};
  this.mergedData = deepCopy(fields);
  this.children = {};
  var self = this;
  _.each(fields, function(val, key) {
    self.data[key] = self.data[key] || {};
    self.data[key][index] = deepCopy(val);
  });
}
BaseCollectionItem.prototype.updateFromData = function(fields) {
  var res = {};
  var merged = this.mergedData;
  var self = this;
  _.each(fields, function(flag, key) {
    var cur = undefined;
    _.each(self.data[key], (function(value) {
      cur = _.extend(deepCopy(value), cur);
    }));
    res[key] = cur;
    if (_.isUndefined(cur)) {
      delete merged[key];
    } else {
      merged[key] = cur;
    }
  });
  this.publication.changed(this.collection.name, this.id, res);
}

Meteor.smartPublish = function(name, callback) {
  Meteor.publish(name, function() {
    var publication = this;
    var collections = {};
    function getCollectionByName(name) {
      return collections[name] = collections[name] || new Collection(name);
    }

    function Collection() {
      BaseCollection.apply(this, arguments);
    }
    Collection.prototype = Object.create(BaseCollection.prototype);
    Collection.prototype.publication = publication;

    function CollectionItem() {
      BaseCollectionItem.apply(this, arguments);
    }
    CollectionItem.prototype = Object.create(BaseCollectionItem.prototype);
    CollectionItem.prototype.publication = publication;

    publication.CollectionItem = CollectionItem;

    publication.updateChildren = function(itemm, fields, removeAll) {
      var update = {};
      _.each(fields, function(flag, key) {
        if (!itemm.collection.relations[key]) return;
        _.each(itemm.collection.relations[key], function(dep) {
          update[dep.id] = dep;
        });
      });
      _.each(update, function(dep) {
        var toRemove = [];
        if (dep.id in itemm.children) {
          itemm.children[dep.id].forEach(function(x, i) {
            _.each(x.activeItems, function(flag, subid) {
              toRemove.push([x.collection, x.index, subid]);
            });
            x.observer.stop();
          });
        }

        if (!removeAll) {
          var cursors = dep.callback(itemm.mergedData);
          if (isCursor(cursors)) cursors = [cursors];
          if (!_.isArray(cursors))
            throw new Meteor.Error("Dependency function can only return a Cursor or an array of Cursors");

          var observers = itemm.children[dep.id] = [];
          for (var i = 0; i < cursors.length; i++) {
            var c = cursors[i];
            if (!isCursor(c))
              throw new Meteor.Error("Dependency function returned an array of non-Cursors");

            if (!c._cursorDescription) throw new Meteor.Error("Unable to get cursor's collection name");
            var subname = c._cursorDescription.collectionName;
            if (!subname) throw new Meteor.Error("Unable to get cursor's collection name");

            observers.push(new CursorWrapper(c, getCollectionByName(subname)));
          }
        }
        toRemove.forEach(function(args) {
          Collection.prototype.smartRemoved.apply(args[0], args.slice(1));
        });
      });
    }

    publication.addDependency = function(name, fields, callback) {
      if (!_.isArray(fields)) fields = [fields];
      var relations = getCollectionByName(name).relations;
      var dep = new Dependency(callback);
      fields.forEach(function(field) {
        if (field.indexOf(".") != -1) { // See #8
          field = field.substr(0, field.indexOf("."));
        }
        relations[field] = relations[field] || [];
        relations[field].push(dep);
      });
    }

    var cursors = callback.apply(publication, arguments);
    if (isCursor(cursors)) cursors = [cursors];

    if (!cursors) return;
    if (!_.isArray(cursors))
      throw new Meteor.Error("Publish function can only return a Cursor or an array of Cursors");

    for (var i = 0; i < cursors.length; i++)
      if (!isCursor(cursors[i]))
        throw new Meteor.Error("Publish function returned an array of non-Cursors");

    var observers = [];
    for (var i = 0; i < cursors.length; i++) {
      var c = cursors[i];

      if (!c._cursorDescription) throw new Meteor.Error("Unable to get cursor's collection name");

      function CursorWrapper(cursor, collection) {
        this.activeItems = {};
        this.collection = collection;
        this.index = Random.id();
        var self = this;
        this.observer = cursor.observeChanges({
          added:   function(id, fields) {
            self.activeItems[id] = 1;
            fields['_id'] = id;
            collection.smartAdded  (self.index, id, fields);
          },
          changed: function(id, fields) {
            collection.smartChanged(self.index, id, fields);
          },
          removed: function(id) {
            delete self.activeItems[id];
            collection.smartRemoved(self.index, id);
          },
        })
      };

      var name = c._cursorDescription.collectionName;
      if (!name) throw new Meteor.Error("Unable to get cursor's collection name");
      observers.push(new CursorWrapper(c, getCollectionByName(name)).observer);
    }
    this.ready();
    this.onStop(function() {
      _.forEach(observers, function(x) { x.stop(); });
    });
  });
}
<|endoftext|>


<commit_before>// ==UserScript==
// @name        Smart QR
// @namespace   http://tampermonkey.net/
// @description Detects phone numbers and locations and displays their value as a QR code on mouseover. Needs doubleclick somewhere on the page to get triggered.
// @copyright   2017, Georg Jähnig
// @include     http://*
// @include     https://*
// @version     0.1
// ==/UserScript==
//
// ==OpenUserJS==
// @author jorges
// ==/OpenUserJS==

(function () {

  "use strict";

  function addQR(value) {
    //console.log(value);
    if (value == '') {
      return;
    }
    img.src = 'https://chart.apis.google.com/chart?cht=qr&chs=100x100&chld=L|0&chl=' + encodeURIComponent(value);
    img.style.visibility = "visible";
  };

  function removeQR() {
    img.style.visibility = "hidden";
  };

  function addListeners(element, value) {
    element.addEventListener('mouseover', function() { addQR(value); } );
    //element.addEventListener('mouseout', function() { removeQR(); });
  }

  function handleTextSelect(event) {
    var selection = document.getSelection();
    var text = selection.toString();
    if (text == '') {
      removeQR();
    }
    // Geo coordinates.
    // Match selections like "12.34 , 56.789".
    var re = new RegExp('^\\s*([0-9]\+\.[0-9]\+)\\s*(,\|;)\\s*([0-9]\+\.[0-9]\+)\\s*$');
    var matches = text.match(re);
    if (matches) {
      var value = 'geo:' + matches[1] + ',' + matches[3];
      addQR(value);
      return;
    }
    // Phone number.
    var re = new RegExp('^[^a-zA-Z]*$');
    var matches = text.match(re);
    if (matches) {
      var number = matches[0].replace(/[^0-9\+]/g, '');
      if (number == '') {
        return;
      }
      number = 'tel:' + number;
      addQR(number);
      return;
    }
  }

  function parseAndAddListeners() {
    var elements = document.getElementsByTagName('a');
    for(var i=0, len=elements.length; i < len; i++){
      var element = elements[i];
      if (element.href) {
        // elements with href="tel:..."
        var re = new RegExp('^tel:(.*)$');
        var matches = element.href.match(re);
        if (matches) {
          addListeners(element, element.href);
        }
        // elements with href="maps.google.com/?.*q=12,34"
        var re = new RegExp('maps.google.com.*q=([0-9\.]*),([0-9\.]*)');
        var matches = element.href.match(re);
        if (matches) {
          var value = 'geo:' + matches[1] + ',' + matches[2];
          addListeners(element, value);
        }
        // elements with href="@12.34,56.78"
        var re = new RegExp('google.*@([0-9]\+\.[0-9]\+),([0-9]\+\.[0-9]\+)');
        var matches = element.href.match(re);
        if (matches) {
          var value = 'geo:' + matches[1] + ',' + matches[2];
          addListeners(element, value);
        }
        // Wikipedia location elements.
        if (currentURL.hostname.match(/wikipedia\.org/)) {
          var re = new RegExp('tools.wmflabs.org/geohack/geohack\.php.*params=([0-9\.]*)_._([0-9\.]*)');
          var matches = element.href.match(re);
          if (matches) {
            var value = 'geo:' + matches[1] + ',' + matches[2];
            addListeners(element, value);
          }
        }
        // Openstreetmap coordinate link.
        if (currentURL.hostname.match(/openstreetmap\.org/)) {
          var re = new RegExp('/#map=[0-9]+/([0-9\.]+)/([0-9\.]+)');
          var matches = element.href.match(re);
          if (matches) {
            var value = 'geo:' + matches[1] + ',' + matches[2];
            addListeners(element, value);
          }
        }
        // Any "geo:" link.
        var re = new RegExp('geo:([0-9\.]+),([0-9\.]+)');
        var matches = element.href.match(re);
        if (matches) {
          var value = 'geo:' + matches[1] + ',' + matches[2];
          addListeners(element, value);
        }
      }
      // elements with data-number.
      if (element.dataset) {
        if (element.dataset.number) {
          var value = 'tel:' + element.dataset.number;
          addListeners(element, value);
        }
      }
    }
    // Facebook events, location.
    if (currentURL.hostname.match(/facebook\.com/)) {
      var elements = document.getElementsByTagName('img');
      for(var i=0, len=elements.length; i < len; i++){
        var element = elements[i];
        if (element.src) {
          var re = new RegExp('markers=([0-9\.]+)%2C([0-9\.]+)');
          var matches = element.src.match(re);
          if (matches) {
            var value = 'geo:' + matches[1] + ',' + matches[2];
            addListeners(element, value);
          }
        }
      }
    }
    // Google maps, info sidebar, phone numbers
    if (currentURL.hostname.match(/google/)) {
      var elements = document.getElementsByTagName('button');
      for(var i=0, len=elements.length; i < len; i++){
        var element = elements[i];
        if (element.dataset) {
          if (element.dataset.href) {
            addListeners(element, element.dataset.href);
          }
        }
      }
    }
    // Text selections.
    document.addEventListener('mouseup', handleTextSelect);
  }

  function manualTriggerWithDblClick() {
    document.body.appendChild(img);
    window.addEventListener('dblclick', parseAndAddListeners, true);
  }

  function parseURL(url) {
    var parser = document.createElement('a');
    parser.href = url;
    return parser;
  }

  var currentURL = parseURL(window.location.href);

  // Create code and add to body.
  var img = document.createElement("img");
  img.style.width = "100px";
  img.style.height = "100px";
  img.style.position = "fixed";
  img.style.left = "10px";
  img.style.bottom = "30px";
  img.style.zIndex = "999";
  img.style.visibility = "hidden";
  img.alt = "QR Code";

  img.addEventListener('mouseover', removeQR, true);

  manualTriggerWithDblClick();

}());

<commit_msg>Show code for current page on triple click.<commit_after>// ==UserScript==
// @name        Smart QR
// @namespace   http://tampermonkey.net/
// @description Detects phone numbers and locations and displays their value as a QR code on mouseover. Needs doubleclick somewhere on the page to get triggered.
// @copyright   2017, Georg Jähnig
// @include     http://*
// @include     https://*
// @version     0.1
// ==/UserScript==
//
// ==OpenUserJS==
// @author jorges
// ==/OpenUserJS==

(function () {

  "use strict";

  function addQR(value) {
    //console.log(value);
    if (value == '') {
      return;
    }
    img.src = 'https://chart.apis.google.com/chart?cht=qr&chs=100x100&chld=L|0&chl=' + encodeURIComponent(value);
    img.style.visibility = "visible";
  };

  function removeQR() {
    img.style.visibility = "hidden";
  };

  function addListeners(element, value) {
    element.addEventListener('mouseover', function() { addQR(value); } );
    //element.addEventListener('mouseout', function() { removeQR(); });
  }

  function handleTextSelect(event) {
    var selection = document.getSelection();
    var text = selection.toString();
    if (text == '') {
      removeQR();
    }
    // Geo coordinates.
    // Match selections like "12.34 , 56.789".
    var re = new RegExp('^\\s*([0-9]\+\.[0-9]\+)\\s*(,\|;)\\s*([0-9]\+\.[0-9]\+)\\s*$');
    var matches = text.match(re);
    if (matches) {
      var value = 'geo:' + matches[1] + ',' + matches[3];
      addQR(value);
      return;
    }
    // Phone number.
    var re = new RegExp('^[^a-zA-Z]*$');
    var matches = text.match(re);
    if (matches) {
      var number = matches[0].replace(/[^0-9\+]/g, '');
      if (number == '') {
        return;
      }
      number = 'tel:' + number;
      addQR(number);
      return;
    }
  }

  function parseAndAddListeners() {
    var elements = document.getElementsByTagName('a');
    for(var i=0, len=elements.length; i < len; i++){
      var element = elements[i];
      if (element.href) {
        // elements with href="tel:..."
        var re = new RegExp('^tel:(.*)$');
        var matches = element.href.match(re);
        if (matches) {
          addListeners(element, element.href);
        }
        // elements with href="maps.google.com/?.*q=12,34"
        var re = new RegExp('maps.google.com.*q=([0-9\.]*),([0-9\.]*)');
        var matches = element.href.match(re);
        if (matches) {
          var value = 'geo:' + matches[1] + ',' + matches[2];
          addListeners(element, value);
        }
        // elements with href="@12.34,56.78"
        var re = new RegExp('google.*@([0-9]\+\.[0-9]\+),([0-9]\+\.[0-9]\+)');
        var matches = element.href.match(re);
        if (matches) {
          var value = 'geo:' + matches[1] + ',' + matches[2];
          addListeners(element, value);
        }
        // Wikipedia location elements.
        if (currentURL.hostname.match(/wikipedia\.org/)) {
          var re = new RegExp('tools.wmflabs.org/geohack/geohack\.php.*params=([0-9\.]*)_._([0-9\.]*)');
          var matches = element.href.match(re);
          if (matches) {
            var value = 'geo:' + matches[1] + ',' + matches[2];
            addListeners(element, value);
          }
        }
        // Openstreetmap coordinate link.
        if (currentURL.hostname.match(/openstreetmap\.org/)) {
          var re = new RegExp('/#map=[0-9]+/([0-9\.]+)/([0-9\.]+)');
          var matches = element.href.match(re);
          if (matches) {
            var value = 'geo:' + matches[1] + ',' + matches[2];
            addListeners(element, value);
          }
        }
        // Any "geo:" link.
        var re = new RegExp('geo:([0-9\.]+),([0-9\.]+)');
        var matches = element.href.match(re);
        if (matches) {
          var value = 'geo:' + matches[1] + ',' + matches[2];
          addListeners(element, value);
        }
      }
      // elements with data-number.
      if (element.dataset) {
        if (element.dataset.number) {
          var value = 'tel:' + element.dataset.number;
          addListeners(element, value);
        }
      }
    }
    // Facebook events, location.
    if (currentURL.hostname.match(/facebook\.com/)) {
      var elements = document.getElementsByTagName('img');
      for(var i=0, len=elements.length; i < len; i++){
        var element = elements[i];
        if (element.src) {
          var re = new RegExp('markers=([0-9\.]+)%2C([0-9\.]+)');
          var matches = element.src.match(re);
          if (matches) {
            var value = 'geo:' + matches[1] + ',' + matches[2];
            addListeners(element, value);
          }
        }
      }
    }
    // Google maps, info sidebar, phone numbers
    if (currentURL.hostname.match(/google/)) {
      var elements = document.getElementsByTagName('button');
      for(var i=0, len=elements.length; i < len; i++){
        var element = elements[i];
        if (element.dataset) {
          if (element.dataset.href) {
            addListeners(element, element.dataset.href);
          }
        }
      }
    }
    // Text selections.
    document.addEventListener('mouseup', handleTextSelect);
  }

  function manualTriggerWithDblClick() {
    document.body.appendChild(img);
    window.addEventListener('dblclick', parseAndAddListeners, true);
  }

  function codeForCurrentPage() {
    window.addEventListener('click', function (evt) {
      if (evt.detail === 3) {
        var value = window.location.href;
        addQR(value);
      }
    });
  }

  function parseURL(url) {
    var parser = document.createElement('a');
    parser.href = url;
    return parser;
  }

  var currentURL = parseURL(window.location.href);

  // Create code and add to body.
  var img = document.createElement("img");
  img.style.width = "100px";
  img.style.height = "100px";
  img.style.position = "fixed";
  img.style.left = "10px";
  img.style.bottom = "30px";
  img.style.zIndex = "999";
  img.style.visibility = "hidden";
  img.alt = "QR Code";

  img.addEventListener('mouseover', removeQR, true);

  manualTriggerWithDblClick();
	codeForCurrentPage();

}());

<|endoftext|>


<commit_before>import React, { PropTypes } from 'react'
import { connect } from 'react-redux'
import { Row, Col } from 'react-flexbox-grid'
import setPropTypes from 'recompose/setPropTypes'
import compose from 'recompose/compose'

const Log = compose(
  connect((state) => ({ log: state.log })),
  setPropTypes({
    log: PropTypes.array.isRequired
  })
)(({ log }) => (
  <Row>
    <Col>
      {
        log.map((content, idx) => (
          <Row key={ idx }>
            <Col> { content } </Col>
          </Row>
        ))
      }
    </Col>
  </Row>
))

export default Log
<commit_msg>Update style<commit_after>import React, { PropTypes } from 'react'
import { connect } from 'react-redux'
import { Row, Col } from 'react-flexbox-grid'
import setPropTypes from 'recompose/setPropTypes'
import compose from 'recompose/compose'

const Log = compose(
  connect((state) => ({ log: state.log })),
  setPropTypes({
    log: PropTypes.array.isRequired
  })
)(({ log }) => (
  <Row>
    <Col style={ styles.scroll }>
      {
        log.map((content, idx) => (
          <Row key={ idx }>
            <Col> { content } </Col>
          </Row>
        ))
      }
    </Col>
  </Row>
))

const styles = {
  scroll: {
    width: '25%',
    height: '600px',
    overflow: 'auto',
    padding: '0 10px'
  }
}

export default Log
<|endoftext|>


<commit_before>function setStylesheet(selector,cssText)
{
    var previewText = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec in diam mauris. Integer in lorem sit amet dolor lacinia aliquet. Cras vehicula odio non enim euismod nec congue lorem varius. Sed eu libero arcu, eget tempus augue. Vivamus varius risus ac libero sagittis eu ultricies lectus consequat. Integer gravida accumsan fermentum. Morbi erat ligula, volutpat non accumsan sed, pellentesque quis purus. Vestibulum vestibulum tincidunt lectus non pellentesque. Quisque porttitor sollicitudin tellus, id porta velit interdum sit amet. Cras quis sem orci, vel convallis magna. Pellentesque congue, libero et iaculis volutpat, enim turpis sodales dui, lobortis pharetra lectus dolor at sem. Nullam aliquam, odio ac laoreet vulputate, ligula nunc euismod leo, vel bibendum magna leo ut orci. In tortor turpis, pellentesque nec cursus ut, consequat non ipsum. Praesent venenatis, leo in pulvinar pharetra, eros nisi convallis elit, vitae luctus magna velit ut lorem."

    var style = document.getElementById("style");
//    alert("js: setStyleSheet");
//    alert("style = "+style);
//    alert("selector = "+selector);
//    alert("cssText = "+cssText);

    while (style.firstChild != null)
        style.removeChild(style.firstChild);
    while (document.body.firstChild != null)
        document.body.removeChild(document.body.firstChild);

    style.appendChild(document.createTextNode(cssText));

    var element;
    if (selector.charAt(0) == ".") {
        element = document.createElement("DIV");
        element.setAttribute("class",selector.slice(1));
    }
    else {
        element = document.createElement(selector);
    }

    document.body.appendChild(element);
    element.appendChild(document.createTextNode(previewText));
}
<commit_msg>Small capitalisation fix (setStyleSheet instead of setStylesheet in preview.js), and removed some debugging output and obsolete, commented-out code.<commit_after>function setStyleSheet(selector,cssText)
{
    var previewText = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec in diam mauris. Integer in lorem sit amet dolor lacinia aliquet. Cras vehicula odio non enim euismod nec congue lorem varius. Sed eu libero arcu, eget tempus augue. Vivamus varius risus ac libero sagittis eu ultricies lectus consequat. Integer gravida accumsan fermentum. Morbi erat ligula, volutpat non accumsan sed, pellentesque quis purus. Vestibulum vestibulum tincidunt lectus non pellentesque. Quisque porttitor sollicitudin tellus, id porta velit interdum sit amet. Cras quis sem orci, vel convallis magna. Pellentesque congue, libero et iaculis volutpat, enim turpis sodales dui, lobortis pharetra lectus dolor at sem. Nullam aliquam, odio ac laoreet vulputate, ligula nunc euismod leo, vel bibendum magna leo ut orci. In tortor turpis, pellentesque nec cursus ut, consequat non ipsum. Praesent venenatis, leo in pulvinar pharetra, eros nisi convallis elit, vitae luctus magna velit ut lorem."

    var style = document.getElementById("style");
//    alert("js: setStyleSheet");
//    alert("style = "+style);
//    alert("selector = "+selector);
//    alert("cssText = "+cssText);

    while (style.firstChild != null)
        style.removeChild(style.firstChild);
    while (document.body.firstChild != null)
        document.body.removeChild(document.body.firstChild);

    style.appendChild(document.createTextNode(cssText));

    var element;
    if (selector.charAt(0) == ".") {
        element = document.createElement("DIV");
        element.setAttribute("class",selector.slice(1));
    }
    else {
        element = document.createElement(selector);
    }

    document.body.appendChild(element);
    element.appendChild(document.createTextNode(previewText));
}
<|endoftext|>


<commit_before>(function() {
let randint = m => Math.floor(Math.random() * m);
let pad = ((s, l) => new Array(l + 1 - s.length).join("0") + s);

function getRegNo(country) {
	if (country === "se") {
		let isValidRegNo = no => no.split("").filter(c => c !== "-").map(c => c - "0").map((c, i) => ((i + 1) % 2 + 1) * c).map(s => (s % 10) + Math.floor(s / 10)).reduce((a, b) => a + b) % 10 === 0;
		let reg;
		do {
			reg = pad(randint(1000000).toString(), 6) + "-" + pad(randint(1000).toString(), 4);
		} while (!isValidRegNo(reg));
		return reg;
	} else if (country === "no") {
		let ctrl = [3, 2, 7, 6, 5, 4, 3, 2, 1];
		let isValidRegNo = no => no.split("").filter(c => c !== "-").map(c => c - "0").map((c, i) => ctrl[i] * c).reduce((a, b) => a + b) % 11 === 0;
		let reg;
		do {
			reg = pad(randint(1000000000).toString(), 9);
		} while (!isValidRegNo(reg));
		return reg;
	}
}

function CheckoutSE() {
	document.getElementById("Customer_OrgNo").value = getRegNo("se");
	let mail = document.getElementById("CompanyContactEmail").innerText;
	document.getElementById("Customer_Name").value = mail.split("@")[0];
	document.getElementById("Customer_InvoicingAddress1").value = "A";
	document.getElementById("Customer_InvoicingPostalCode").value = "22222";
	document.getElementById("Customer_InvoicingCity").value = "Lund";
	document.getElementById("Customer_PhoneNumber").value = "070-5572927";
	document.getElementById("AcceptTermsOfService").checked = true;
}

function CheckoutNO() {
	document.getElementById("Customer_OrgNo").value = getRegNo("no");
	let mail = document.getElementById("CompanyContactEmail").innerText;
	document.getElementById("Customer_Name").value = mail.split("@")[0];
	document.getElementById("Customer_InvoicingAddress1").value = "A";
	document.getElementById("Customer_InvoicingPostalCode").value = "1234";
	document.getElementById("Customer_InvoicingCity").value = "Norge";
	document.getElementById("Customer_PhoneNumber").value = "12345678";
	document.getElementById("AcceptTermsOfService").checked = true;
}

function NewVONCustomer(country) {
	var customerNumber = document.getElementById("maincontentholder_CustomerNoTextBox").value;
	if(!customerNumber.match(/\d+/)) {
	  document.getElementById("maincontentholder_CustomerNoTextBox").value = customerNumber = randint(100000000);
	}
	document.getElementById("maincontentholder_CustomerNameTextBox").value = "s" + customerNumber;
	document.getElementById("maincontentholder_NewOrgNoTextBox").value = getRegNo(country);
	document.getElementById("maincontentholder_NewInvoiceAddress1TextBox").value = "A";
	document.getElementById("maincontentholder_NewInvoicePostalCodeTextBox").value = "22222";
	document.getElementById("maincontentholder_NewInvoiceCityTextBox").value = "Lund";
	document.getElementById("maincontentholder_EmailTextBox").value = "s" + customerNumber + "@vline.spcs.se";
	document.getElementById("maincontentholder_FirstNameTextBox").value = "Sam";
	document.getElementById("maincontentholder_LastNameTextBox").value = customerNumber;
}

let topDomain = location.host.split(".").pop();
let country = { "se":"se", "no":"no" }[topDomain] || "se";

if(window.location.href.match(/\/sv\-SE\/checkout\/buy\b/i)) {
  CheckoutSE();
} else if(window.location.href.match(/\/nb\-NO\/checkout\/buy\b/i)) {
  CheckoutNO();
} else if(window.location.href.match(/\/administration\/Internal\/AddNewCustomer\.aspx\b/i)) {
  NewVONCustomer(country);
}

})();
<commit_msg>Trim customerNumber<commit_after>(function() {
let randint = m => Math.floor(Math.random() * m);
let pad = ((s, l) => new Array(l + 1 - s.length).join("0") + s);

function getRegNo(country) {
	if (country === "se") {
		let isValidRegNo = no => no.split("").filter(c => c !== "-").map(c => c - "0").map((c, i) => ((i + 1) % 2 + 1) * c).map(s => (s % 10) + Math.floor(s / 10)).reduce((a, b) => a + b) % 10 === 0;
		let reg;
		do {
			reg = pad(randint(1000000).toString(), 6) + "-" + pad(randint(1000).toString(), 4);
		} while (!isValidRegNo(reg));
		return reg;
	} else if (country === "no") {
		let ctrl = [3, 2, 7, 6, 5, 4, 3, 2, 1];
		let isValidRegNo = no => no.split("").filter(c => c !== "-").map(c => c - "0").map((c, i) => ctrl[i] * c).reduce((a, b) => a + b) % 11 === 0;
		let reg;
		do {
			reg = pad(randint(1000000000).toString(), 9);
		} while (!isValidRegNo(reg));
		return reg;
	}
}

function CheckoutSE() {
	document.getElementById("Customer_OrgNo").value = getRegNo("se");
	let mail = document.getElementById("CompanyContactEmail").innerText;
	document.getElementById("Customer_Name").value = mail.split("@")[0];
	document.getElementById("Customer_InvoicingAddress1").value = "A";
	document.getElementById("Customer_InvoicingPostalCode").value = "22222";
	document.getElementById("Customer_InvoicingCity").value = "Lund";
	document.getElementById("Customer_PhoneNumber").value = "070-5572927";
	document.getElementById("AcceptTermsOfService").checked = true;
}

function CheckoutNO() {
	document.getElementById("Customer_OrgNo").value = getRegNo("no");
	let mail = document.getElementById("CompanyContactEmail").innerText;
	document.getElementById("Customer_Name").value = mail.split("@")[0];
	document.getElementById("Customer_InvoicingAddress1").value = "A";
	document.getElementById("Customer_InvoicingPostalCode").value = "1234";
	document.getElementById("Customer_InvoicingCity").value = "Norge";
	document.getElementById("Customer_PhoneNumber").value = "12345678";
	document.getElementById("AcceptTermsOfService").checked = true;
}

function NewVONCustomer(country) {
	var customerNumber = document.getElementById("maincontentholder_CustomerNoTextBox").value.trim();
	if(!customerNumber.match(/\d+/)) {
	  document.getElementById("maincontentholder_CustomerNoTextBox").value = customerNumber = randint(100000000);
	}
	document.getElementById("maincontentholder_CustomerNameTextBox").value = "s" + customerNumber;
	document.getElementById("maincontentholder_NewOrgNoTextBox").value = getRegNo(country);
	document.getElementById("maincontentholder_NewInvoiceAddress1TextBox").value = "A";
	document.getElementById("maincontentholder_NewInvoicePostalCodeTextBox").value = "22222";
	document.getElementById("maincontentholder_NewInvoiceCityTextBox").value = "Lund";
	document.getElementById("maincontentholder_EmailTextBox").value = "s" + customerNumber + "@vline.spcs.se";
	document.getElementById("maincontentholder_FirstNameTextBox").value = "Sam";
	document.getElementById("maincontentholder_LastNameTextBox").value = customerNumber;
}

let topDomain = location.host.split(".").pop();
let country = { "se":"se", "no":"no" }[topDomain] || "se";

if(window.location.href.match(/\/sv\-SE\/checkout\/buy\b/i)) {
  CheckoutSE();
} else if(window.location.href.match(/\/nb\-NO\/checkout\/buy\b/i)) {
  CheckoutNO();
} else if(window.location.href.match(/\/administration\/Internal\/AddNewCustomer\.aspx\b/i)) {
  NewVONCustomer(country);
}

})();
<|endoftext|>


<commit_before>const SPACE = {};
const NEWLINE = {};
const INDENT = {};
const OUTDENT = {};

export class Printer {
  constructor() {
    this.indentWidth = 2;
    this.depth = 0;
    this.stringDelimiter = "'";
    this.output = '';
  }

  newline() {
    this.output += '\n';
    if (this.indentWidth > 0)
      this.output += ' '.repeat(this.indentWidth * this.depth);
  }

  write(...args) {
    for (let i = 0; i < args.length; ++i) {
      switch (args[i]) {
        case SPACE:
          this.output += ' ';
          break;
        case NEWLINE:
          this.newline();
          break;
        case INDENT:
          this.depth += 1;
          this.newline();
          break;
        case OUTDENT:
          this.depth -= 1;
          this.newline();
          break;
        default:
          if (typeof args[i] === 'string') this.output += args[i];
          else this.printNode(args[i]);
          break;
      }
    }
  }

  print(ast) {
    this.output = '';
    this.printNode(ast);
    return this.output;
  }

  printNode(node) {
    if (node !== null && node !== undefined)
      this[node.type](node);
  }

  printList(list, sep = ', ') {
    list.forEach((n, i) => {
      this.printNode(n);
      if (i < list.length - 1) this.write(sep);
    });
  }

  Identifier(node) {
    // TODO: escaping
    this.write(node.value);
  }

  NumberLiteral(node) {
    this.write(String(node.value), node.suffix);
  }

  StringLiteral(node) {
    // TODO: escape string
    this.write(
      this.stringDelimiter,
      node.value,
      this.stringDelimiter
    );
  }

  TemplatePart(node) {
    this.write(node.raw);
  }

  RegularExpression(node) {
    this.write('/', node.value, '/', node.flags);
  }

  BooleanLiteral(node) {
    this.write(node.value ? 'true' : 'false');
  }

  NullLiteral() {
    this.write('null');
  }

  Script(node) {
    this.printList(node.statements, NEWLINE);
  }

  Module(node) {
    this.printList(node.statements, NEWLINE);
  }

  ThisExpression() {
    this.write('this');
  }

  SuperKeyword() {
    this.write('super');
  }

  SequenceExpression(node) {
    this.printList(node.expressions);
  }

  AssignmentExpression(node) {
    this.write(
      node.left,
      SPACE,
      node.operator,
      SPACE,
      node.right
    );
  }

  SpreadExpression(node) {
    this.write('...', node.expression);
  }

  YieldExpression(node) {
    this.write('yield');
    if (node.delegate) this.write(SPACE, '*');
    this.write(SPACE, node.expresion);
  }

  ConditionalExpression(node) {
    this.write(
      node.test, SPACE,
      '?', node.consequent, SPACE,
      ':', node.alternate
    );
  }

  BinaryExpression(node) {
    this.write(node.left, SPACE, node.right);
  }

  UpdateExpression(node) {
    if (node.prefix) this.write(node.operator, node.expression);
    else this.write(node.expression, node.operator);
  }

  UnaryExpression(node) {
    // TODO: no space if operator char
    this.write(node.operator, ' ', node.expression);
  }

  MemberExpression(node) {
    this.write(node.object);
    if (node.computed) this.write('[', node.property, ']');
    else this.write('.', node.property);
  }

  MetaProperty(node) {
    this.write(node.left, '.', node.right);
  }

  CallExpression(node) {
    this.write(node.callee, '(');
    this.printList(node.arguments);
    this.write(')');
  }

  TemplateExpression(node) {
    this.write('`');
    node.parts.forEach(part => {
      part.type === 'TemplatePart' ?
        this.write(part) :
        this.write('${', part, '}');
    });
    this.write('`');
  }

  TaggedTemplateExpression(node) {
    this.write(node.tag, node.template);
  }

  NewExpression(node) {
    this.write('new ', node.callee, '(');
    this.printList(node.arguments);
    this.write(')');
  }

  ParenExpression(node) {
    this.write('(', node.expression, ')');
  }

  ObjectLiteral(node) {
    this.write('{', INDENT);
    this.printList(node.properties, NEWLINE);
    this.write(OUTDENT, '}');
  }

  ComputedPropertyName(node) {
    this.write('[', node.expression, ']');
  }

  PropertyDefinition(node) {
    this.write(node.name, ':', SPACE, node.expression);
  }

  ObjectPattern(node) {
    this.write('{', INDENT);
    this.printList(node.properties, NEWLINE);
    this.write(OUTDENT, '}');
  }

  PatternProperty(node) {
    this.write(node.name);
    if (node.pattern) this.write(':', SPACE, node.pattern);
    if (node.initializer) this.write(SPACE, '=', SPACE, node.initializer);
  }

  ArrayPattern(node) {
    this.write('[');
    this.printList(node.elements);
    this.write(']');
  }

  PatternElement(node) {
    this.write(node.pattern);
    if (node.initializer) this.write(SPACE, '=', SPACE, node.initializer);
  }

  PatternRestElement(node) {
    this.write('...', node.pattern);
  }

  MethodDefinition(node) {
    if (node.static) this.write('static ');

    switch (node.kind) {
      case 'generator': this.write('*'); break;
      case 'async': this.write('async '); break;
      case 'async-generator': this.write('async *'); break;
    }

    this.write(node.name, '(');
    this.printList(node.params);
    this.write(')', SPACE, '{', INDENT, node.body, OUTDENT, '}');
  }

  ArrayLiteral(node) {
    this.write('[');
    this.printList(node.elements);
    this.write(']');
  }

  Block(node) {
    this.write('{', INDENT);
    this.printList(node.statements, NEWLINE);
    this.write(OUTDENT, '}');
  }

  LabelledStatement(node) {
    this.write(node.label, ':', SPACE, node.statement);
  }

  ExpressionStatement(node) {
    this.write(node.expression, ';');
  }

  Directive(node) {
    this.write(node.expression, ';');
  }

  EmptyStatement() {
    this.write(';');
  }

  VariableDeclaration(node) {
    this.write(node.kind, ' ');
    this.printList(node.declarations);
    this.write(';');
  }

  VariableDeclarator(node) {
    this.write(node.pattern);
    if (node.initializer)
      this.write(SPACE, '=', SPACE, node.initializer);
  }

  ReturnStatement(node) {
    this.write('return ', node.argument, ';');
  }

  BreakStatement(node) {
    this.write('break');
    if (node.label) this.write(' ', node.label);
    this.write(';');
  }

  ContinueStatement(node) {
    this.write('continue');
    if (node.label) this.write(' ', node.label);
    this.write(';');
  }

  ThrowStatement(node) {
    this.write('throw ', node.expression, ';');
  }

  DebuggerStatement() {
    this.write('debugger;');
  }

  IfStatement(node) {
    this.write('if', SPACE, '(', node.test, ')', SPACE, node.consequent);
    if (node.alternate) this.write('else ', node.alternate);
  }

  DoWhileStatement(node) {
    this.write('do ', node.body, ' while (', node.test, ')');
  }

  WhileStatement(node) {
    this.write('while', SPACE, '(', node.test, ')', node.body);
  }

  ForStatement(node) {
    this.write(
      'for', SPACE, '(',
      node.initializer, ';', SPACE,
      node.test, ';', SPACE,
      node.update,
      ')', SPACE, node.body
    );
  }

  ForInStatement(node) {
    this.write(
      'for', SPACE,
      '(', node.left, ' in ', node.right, ')', SPACE,
      node.body
    );
  }

  ForOfStatement(node) {
    this.write(
      'for', SPACE,
      '(', node.left, ' of ', node.right, ')', SPACE,
      node.body
    );
  }

  WithStatement(node) {
    this.write(
      'with', SPACE, '(', node.object, ')', SPACE, node.body
    );
  }

  SwitchStatement(node) {
    this.write(
      'switch', SPACE,
      '(', node.descriminant, ')', SPACE,
      '{', INDENT
    );
    this.printList(node.cases, NEWLINE);
    this.write(OUTDENT, '}');
  }

  SwitchCase(node) {
    this.write('case ', node.test, ':', SPACE, node.consequent);
  }

  TryStatement(node) {
    this.write(
      'try', SPACE, node.block, SPACE, node.handler, SPACE,
      'finally', SPACE, node.finalizer
    );
  }

  CatchClause(node) {
    this.write(
      ' catch', SPACE, '(', node.param, ')', SPACE, node.body
    );
  }

  FunctionDeclaration(node) {
    this.FunctionExpression(node);
  }

  FunctionExpression(node) {
    if (node.kind === 'async' || node.kind === 'async-generator')
      this.write('async ');

    this.write('function');

    if (node.kind === 'generator' || node.kind === 'async-generator')
      this.write('*');

    if (node.identifier)
      this.write(' ', node.identifier);

    this.write('(');
    this.printList(node.params);
    this.write(')', SPACE, node.body);
  }

  FormalParameter(node) {
    this.write(node.pattern);
    if (node.initializer)
      this.write(SPACE, '=', SPACE, node.initializer);
  }

  RestParameter(node) {
    this.write('...', node.identifier);
  }

  FunctionBody(node) {
    this.write('{', INDENT);
    this.printList(node.statements, NEWLINE);
    this.write(OUTDENT, '}');
  }

  ArrowFunction(node) {
    if (node.kind === 'async')
      this.write('async ');

    this.write('(');
    this.printList(node.params);
    this.write(')', SPACE, '=>', SPACE, node.body);
  }

  ClassDeclaration(node) {
    this.ClassExpression(node);
  }

  ClassExpression(node) {
    this.write('class');
    if (node.identifier) this.write(' ', node.identifier);
    if (node.base) this.write(' extends ', node.base);
    this.write(SPACE, node.body);
  }

  ClassBody(node) {
    this.write('{', INDENT);
    this.printList(node.elements, NEWLINE);
    this.write(OUTDENT, '}');
  }

  EmptyClassElement() {
    this.write(';');
  }

  ClassField(node) {
    if (node.static) this.write('static ');
    this.write(node.name);
    if (node.initializer) this.write(SPACE, '=', SPACE, node.initializer);
    this.write(';');
  }

  ImportCall(node) {
    this.write('import', SPACE, '(', node.argument, ')');
  }

  ImportDeclaration(node) {
    this.write('import ');
    if (node.imports) this.write(node.imports, ' from ');
    this.write(node.from, ';');
  }

  NamespaceImport(node) {
    this.write('* as ', node.identifier);
  }

  NamedImports(node) {
    this.write('{', SPACE);
    this.printList(node.specifiers);
    this.write(SPACE, '}');
  }

  DefaultImport(node) {
    this.write(node.identifier);
    if (node.imports) this.write(',', SPACE, node.imports);
  }

  ImportSpecifier(node) {
    this.write(node.imported);
    if (node.local) this.write(' as ', node.local);
  }

  ExportDeclaration(node) {
    this.write('export ', node.declaration);
  }

  ExportDefault(node) {
    this.write('export default ', node.binding);
  }

  ExportNameList(node) {
    this.write('export', SPACE, '{', SPACE);
    this.printList(node.specifiers);
    this.write(SPACE, '}');
    if (node.from) this.write(SPACE, 'from', SPACE, node.from);
  }

  ExportNamespace(node) {
    this.write('export * as ', node.identifier, ' from ', node.from);
  }

  ExportDefaultFrom(node) {
    this.write('export ', node.identifier, ' from ', node.from);
  }

  ExportSpecifier(node) {
    this.write(node.local);
    if (node.exported) this.write(' as ', node.exported);
  }

}
<commit_msg>Fix binary operator printing<commit_after>const SPACE = {};
const NEWLINE = {};
const INDENT = {};
const OUTDENT = {};

export class Printer {
  constructor() {
    this.indentWidth = 2;
    this.depth = 0;
    this.stringDelimiter = "'";
    this.output = '';
  }

  newline() {
    this.output += '\n';
    if (this.indentWidth > 0)
      this.output += ' '.repeat(this.indentWidth * this.depth);
  }

  write(...args) {
    for (let i = 0; i < args.length; ++i) {
      switch (args[i]) {
        case SPACE:
          this.output += ' ';
          break;
        case NEWLINE:
          this.newline();
          break;
        case INDENT:
          this.depth += 1;
          this.newline();
          break;
        case OUTDENT:
          this.depth -= 1;
          this.newline();
          break;
        default:
          if (typeof args[i] === 'string') this.output += args[i];
          else this.printNode(args[i]);
          break;
      }
    }
  }

  print(ast) {
    this.output = '';
    this.printNode(ast);
    return this.output;
  }

  printNode(node) {
    if (node !== null && node !== undefined)
      this[node.type](node);
  }

  printList(list, sep = ', ') {
    list.forEach((n, i) => {
      this.printNode(n);
      if (i < list.length - 1) this.write(sep);
    });
  }

  Identifier(node) {
    // TODO: escaping
    this.write(node.value);
  }

  NumberLiteral(node) {
    this.write(String(node.value), node.suffix);
  }

  StringLiteral(node) {
    // TODO: escape string
    this.write(
      this.stringDelimiter,
      node.value,
      this.stringDelimiter
    );
  }

  TemplatePart(node) {
    this.write(node.raw);
  }

  RegularExpression(node) {
    this.write('/', node.value, '/', node.flags);
  }

  BooleanLiteral(node) {
    this.write(node.value ? 'true' : 'false');
  }

  NullLiteral() {
    this.write('null');
  }

  Script(node) {
    this.printList(node.statements, NEWLINE);
  }

  Module(node) {
    this.printList(node.statements, NEWLINE);
  }

  ThisExpression() {
    this.write('this');
  }

  SuperKeyword() {
    this.write('super');
  }

  SequenceExpression(node) {
    this.printList(node.expressions);
  }

  AssignmentExpression(node) {
    this.write(
      node.left,
      SPACE,
      node.operator,
      SPACE,
      node.right
    );
  }

  SpreadExpression(node) {
    this.write('...', node.expression);
  }

  YieldExpression(node) {
    this.write('yield');
    if (node.delegate) this.write(SPACE, '*');
    this.write(SPACE, node.expresion);
  }

  ConditionalExpression(node) {
    this.write(
      node.test, SPACE,
      '?', node.consequent, SPACE,
      ':', node.alternate
    );
  }

  BinaryExpression(node) {
    this.write(node.left, SPACE, node.operator, SPACE, node.right);
  }

  UpdateExpression(node) {
    if (node.prefix) this.write(node.operator, node.expression);
    else this.write(node.expression, node.operator);
  }

  UnaryExpression(node) {
    // TODO: no space if operator char
    this.write(node.operator, ' ', node.expression);
  }

  MemberExpression(node) {
    this.write(node.object);
    if (node.computed) this.write('[', node.property, ']');
    else this.write('.', node.property);
  }

  MetaProperty(node) {
    this.write(node.left, '.', node.right);
  }

  CallExpression(node) {
    this.write(node.callee, '(');
    this.printList(node.arguments);
    this.write(')');
  }

  TemplateExpression(node) {
    this.write('`');
    node.parts.forEach(part => {
      part.type === 'TemplatePart' ?
        this.write(part) :
        this.write('${', part, '}');
    });
    this.write('`');
  }

  TaggedTemplateExpression(node) {
    this.write(node.tag, node.template);
  }

  NewExpression(node) {
    this.write('new ', node.callee, '(');
    this.printList(node.arguments);
    this.write(')');
  }

  ParenExpression(node) {
    this.write('(', node.expression, ')');
  }

  ObjectLiteral(node) {
    this.write('{', INDENT);
    this.printList(node.properties, NEWLINE);
    this.write(OUTDENT, '}');
  }

  ComputedPropertyName(node) {
    this.write('[', node.expression, ']');
  }

  PropertyDefinition(node) {
    this.write(node.name, ':', SPACE, node.expression);
  }

  ObjectPattern(node) {
    this.write('{', INDENT);
    this.printList(node.properties, NEWLINE);
    this.write(OUTDENT, '}');
  }

  PatternProperty(node) {
    this.write(node.name);
    if (node.pattern) this.write(':', SPACE, node.pattern);
    if (node.initializer) this.write(SPACE, '=', SPACE, node.initializer);
  }

  ArrayPattern(node) {
    this.write('[');
    this.printList(node.elements);
    this.write(']');
  }

  PatternElement(node) {
    this.write(node.pattern);
    if (node.initializer) this.write(SPACE, '=', SPACE, node.initializer);
  }

  PatternRestElement(node) {
    this.write('...', node.pattern);
  }

  MethodDefinition(node) {
    if (node.static) this.write('static ');

    switch (node.kind) {
      case 'generator': this.write('*'); break;
      case 'async': this.write('async '); break;
      case 'async-generator': this.write('async *'); break;
    }

    this.write(node.name, '(');
    this.printList(node.params);
    this.write(')', SPACE, '{', INDENT, node.body, OUTDENT, '}');
  }

  ArrayLiteral(node) {
    this.write('[');
    this.printList(node.elements);
    this.write(']');
  }

  Block(node) {
    this.write('{', INDENT);
    this.printList(node.statements, NEWLINE);
    this.write(OUTDENT, '}');
  }

  LabelledStatement(node) {
    this.write(node.label, ':', SPACE, node.statement);
  }

  ExpressionStatement(node) {
    this.write(node.expression, ';');
  }

  Directive(node) {
    this.write(node.expression, ';');
  }

  EmptyStatement() {
    this.write(';');
  }

  VariableDeclaration(node) {
    this.write(node.kind, ' ');
    this.printList(node.declarations);
    this.write(';');
  }

  VariableDeclarator(node) {
    this.write(node.pattern);
    if (node.initializer)
      this.write(SPACE, '=', SPACE, node.initializer);
  }

  ReturnStatement(node) {
    this.write('return ', node.argument, ';');
  }

  BreakStatement(node) {
    this.write('break');
    if (node.label) this.write(' ', node.label);
    this.write(';');
  }

  ContinueStatement(node) {
    this.write('continue');
    if (node.label) this.write(' ', node.label);
    this.write(';');
  }

  ThrowStatement(node) {
    this.write('throw ', node.expression, ';');
  }

  DebuggerStatement() {
    this.write('debugger;');
  }

  IfStatement(node) {
    this.write('if', SPACE, '(', node.test, ')', SPACE, node.consequent);
    if (node.alternate) this.write('else ', node.alternate);
  }

  DoWhileStatement(node) {
    this.write('do ', node.body, ' while (', node.test, ')');
  }

  WhileStatement(node) {
    this.write('while', SPACE, '(', node.test, ')', node.body);
  }

  ForStatement(node) {
    this.write(
      'for', SPACE, '(',
      node.initializer, ';', SPACE,
      node.test, ';', SPACE,
      node.update,
      ')', SPACE, node.body
    );
  }

  ForInStatement(node) {
    this.write(
      'for', SPACE,
      '(', node.left, ' in ', node.right, ')', SPACE,
      node.body
    );
  }

  ForOfStatement(node) {
    this.write(
      'for', SPACE,
      '(', node.left, ' of ', node.right, ')', SPACE,
      node.body
    );
  }

  WithStatement(node) {
    this.write(
      'with', SPACE, '(', node.object, ')', SPACE, node.body
    );
  }

  SwitchStatement(node) {
    this.write(
      'switch', SPACE,
      '(', node.descriminant, ')', SPACE,
      '{', INDENT
    );
    this.printList(node.cases, NEWLINE);
    this.write(OUTDENT, '}');
  }

  SwitchCase(node) {
    this.write('case ', node.test, ':', SPACE, node.consequent);
  }

  TryStatement(node) {
    this.write(
      'try', SPACE, node.block, SPACE, node.handler, SPACE,
      'finally', SPACE, node.finalizer
    );
  }

  CatchClause(node) {
    this.write(
      ' catch', SPACE, '(', node.param, ')', SPACE, node.body
    );
  }

  FunctionDeclaration(node) {
    this.FunctionExpression(node);
  }

  FunctionExpression(node) {
    if (node.kind === 'async' || node.kind === 'async-generator')
      this.write('async ');

    this.write('function');

    if (node.kind === 'generator' || node.kind === 'async-generator')
      this.write('*');

    if (node.identifier)
      this.write(' ', node.identifier);

    this.write('(');
    this.printList(node.params);
    this.write(')', SPACE, node.body);
  }

  FormalParameter(node) {
    this.write(node.pattern);
    if (node.initializer)
      this.write(SPACE, '=', SPACE, node.initializer);
  }

  RestParameter(node) {
    this.write('...', node.identifier);
  }

  FunctionBody(node) {
    this.write('{', INDENT);
    this.printList(node.statements, NEWLINE);
    this.write(OUTDENT, '}');
  }

  ArrowFunction(node) {
    if (node.kind === 'async')
      this.write('async ');

    this.write('(');
    this.printList(node.params);
    this.write(')', SPACE, '=>', SPACE, node.body);
  }

  ClassDeclaration(node) {
    this.ClassExpression(node);
  }

  ClassExpression(node) {
    this.write('class');
    if (node.identifier) this.write(' ', node.identifier);
    if (node.base) this.write(' extends ', node.base);
    this.write(SPACE, node.body);
  }

  ClassBody(node) {
    this.write('{', INDENT);
    this.printList(node.elements, NEWLINE);
    this.write(OUTDENT, '}');
  }

  EmptyClassElement() {
    this.write(';');
  }

  ClassField(node) {
    if (node.static) this.write('static ');
    this.write(node.name);
    if (node.initializer) this.write(SPACE, '=', SPACE, node.initializer);
    this.write(';');
  }

  ImportCall(node) {
    this.write('import', SPACE, '(', node.argument, ')');
  }

  ImportDeclaration(node) {
    this.write('import ');
    if (node.imports) this.write(node.imports, ' from ');
    this.write(node.from, ';');
  }

  NamespaceImport(node) {
    this.write('* as ', node.identifier);
  }

  NamedImports(node) {
    this.write('{', SPACE);
    this.printList(node.specifiers);
    this.write(SPACE, '}');
  }

  DefaultImport(node) {
    this.write(node.identifier);
    if (node.imports) this.write(',', SPACE, node.imports);
  }

  ImportSpecifier(node) {
    this.write(node.imported);
    if (node.local) this.write(' as ', node.local);
  }

  ExportDeclaration(node) {
    this.write('export ', node.declaration);
  }

  ExportDefault(node) {
    this.write('export default ', node.binding);
  }

  ExportNameList(node) {
    this.write('export', SPACE, '{', SPACE);
    this.printList(node.specifiers);
    this.write(SPACE, '}');
    if (node.from) this.write(SPACE, 'from', SPACE, node.from);
  }

  ExportNamespace(node) {
    this.write('export * as ', node.identifier, ' from ', node.from);
  }

  ExportDefaultFrom(node) {
    this.write('export ', node.identifier, ' from ', node.from);
  }

  ExportSpecifier(node) {
    this.write(node.local);
    if (node.exported) this.write(' as ', node.exported);
  }

}
<|endoftext|>


<commit_before>let path = require('path');
let paths = require('./Paths');
let File = require('./File');
let lodash = require('lodash');
let Manifest = require('./Manifest');
let Versioning = require('./Versioning');
let concatenate = require('concatenate');

class Mix {
    /**
     * Create a new Laravel Mix instance.
     */
    constructor() {
        this.File = File;
        this.paths = paths;
        this.hmr = false;
        this.sourcemaps = false;
        this.notifications = true;
        this.cssPreprocessor = false;
        this.inProduction = process.env.NODE_ENV === 'production';

        this.publicPath = this.isUsingLaravel() ? 'public' : './';
        this.cachePath = this.isUsingLaravel() ? 'storage/framework/cache' : './';

        this.manifest = new Manifest(this.cachePath + '/Mix.json');
        this.versioning = new Versioning(this.manifest);
    }

    /**
     * Initialize the user's webpack.mix.js configuration file.
     */
    initialize() {
        // We'll first load the user's webpack.mix.js file.
        require(this.paths.mix());

        // Since the user might wish to override the default cache
        // path, we'll update these here with the latest values.
        this.manifest.path = this.cachePath + '/Mix.json';
        this.versioning.manifest = this.manifest;

        this.detectHotReloading();
    }

    /**
     * Finalize the Webpack configuration.
     *
     * @param {object} webpackConfig
     */
    finalize(webpackConfig) {
        if (this.webpackConfig) {
            lodash.mergeWith(webpackConfig, this.webpackConfig, (objValue, srcValue) => {
                if (Array.isArray(objValue)) {
                    return objValue.concat(srcValue);
                }
            });
        }
    }

    /**
     * Determine the Webpack entry file(s).
     */
    entry() {
        // We'll build up an entry object that the webpack.config.js
        // file will want to see. It'll include all mix.js() calls.
        let entry = this.js.reduce((result, paths) => {
            result[paths.output.name] = paths.entry.map(src => src.path);

            return result;
        }, {});

        // If the user has requested CSS preprocessing, then
        // we'll extract it into the very first entry point.
        if (this.cssPreprocessor) {
            entry[Object.keys(entry)[0]].push(
                this[this.cssPreprocessor].src.path
            );
        }

        return entry;
    }

    /**
     * Determine the Webpack output path.
     */
    output() {
        let filename = this.versioning.enabled ? '[name].[hash].js' : '[name].js';

        return {
            path: this.hmr ? '/' : this.publicPath,
            filename: path.join(this.js[0].output.base, filename).replace(this.publicPath, ''),
            publicPath: this.hmr ? 'http://localhost:8080/' : './'
        };
    }

    /**
     * Determine the appropriate CSS output path.
     */
    cssOutput() {
        let regex = new RegExp('^(\.\/)?' + this.publicPath);

        return this[this.cssPreprocessor].output[
            this.versioning.enabled ? 'hashedPath' : 'path'
        ].replace(regex, '');
    }

    /**
     * Minify the given files, or those from Mix.minify().
     *
     * @param {array|null} files
     */
    minifyAll(files = null) {
        if (! this.inProduction) return;

        files = files || this.minify || [];

        files.forEach(file => new File(file).minify());

        return this;
    }

    /**
     * Combine the given files, or those from Mix.combine().
     *
     * @param {array|null} files
     */
    concatenateAll(files = null) {
        files = files || this.combine || [];

        files.forEach(file => {
            concatenate.sync(file.src, file.output);

            if (! this.inProduction) return;

            new this.File(file.output).minify();
        });

        return this;
    }

    /**
     * Detect if the user desires hot reloading.
     */
    detectHotReloading() {
        let file = new this.File(this.cachePath + '/hot');

        file.delete();

        // If the user wants hot module replacement, we'll create
        // a temporary file, so that Laravel can detect it, and
        // reference the proper base URL for any assets.
        if (process.argv.includes('--hot')) {
            this.hmr = true;

            file.write('hot reloading enabled');
        }
    }

    /**
     * Fetch the appropriate Babel config for babel-loader.
     */
    babelConfig() {
        let file = this.paths.root('.babelrc');

        // If the user has defined their own .babelrc file,
        // the babel-loader will automatically fetch it.
        // Otherwise, we'll use these defaults.
        return this.File.exists(file) ? '' : '?' + JSON.stringify({
            'cacheDirectory': true,
            'presets': [
                ['es2015', { 'modules': false }]
            ]
        });
    }

    /**
     * Determine if we are working with a Laravel project.
     */
    isUsingLaravel() {
        return this.File.exists('./artisan');
    }
};

module.exports = new Mix;
<commit_msg>Clean up method<commit_after>let path = require('path');
let paths = require('./Paths');
let File = require('./File');
let lodash = require('lodash');
let Manifest = require('./Manifest');
let Versioning = require('./Versioning');
let concatenate = require('concatenate');

class Mix {
    /**
     * Create a new Laravel Mix instance.
     */
    constructor() {
        this.File = File;
        this.paths = paths;
        this.hmr = false;
        this.sourcemaps = false;
        this.notifications = true;
        this.cssPreprocessor = false;
        this.inProduction = process.env.NODE_ENV === 'production';

        this.publicPath = this.isUsingLaravel() ? 'public' : './';
        this.cachePath = this.isUsingLaravel() ? 'storage/framework/cache' : './';

        this.manifest = new Manifest(this.cachePath + '/Mix.json');
        this.versioning = new Versioning(this.manifest);
    }

    /**
     * Initialize the user's webpack.mix.js configuration file.
     */
    initialize() {
        // We'll first load the user's webpack.mix.js file.
        require(this.paths.mix());

        // Since the user might wish to override the default cache
        // path, we'll update these here with the latest values.
        this.manifest.path = this.cachePath + '/Mix.json';
        this.versioning.manifest = this.manifest;

        this.detectHotReloading();
    }

    /**
     * Finalize the Webpack configuration.
     *
     * @param {object} webpackConfig
     */
    finalize(webpackConfig) {
        if (! this.webpackConfig) return;

        lodash.mergeWith(webpackConfig, this.webpackConfig,
            (objValue, srcValue) => {
                if (Array.isArray(objValue)) {
                    return objValue.concat(srcValue);
                }
            }
        );
    }

    /**
     * Determine the Webpack entry file(s).
     */
    entry() {
        // We'll build up an entry object that the webpack.config.js
        // file will want to see. It'll include all mix.js() calls.
        let entry = this.js.reduce((result, paths) => {
            result[paths.output.name] = paths.entry.map(src => src.path);

            return result;
        }, {});

        // If the user has requested CSS preprocessing, then
        // we'll extract it into the very first entry point.
        if (this.cssPreprocessor) {
            entry[Object.keys(entry)[0]].push(
                this[this.cssPreprocessor].src.path
            );
        }

        return entry;
    }

    /**
     * Determine the Webpack output path.
     */
    output() {
        let filename = this.versioning.enabled ? '[name].[hash].js' : '[name].js';

        return {
            path: this.hmr ? '/' : this.publicPath,
            filename: path.join(this.js[0].output.base, filename).replace(this.publicPath, ''),
            publicPath: this.hmr ? 'http://localhost:8080/' : './'
        };
    }

    /**
     * Determine the appropriate CSS output path.
     */
    cssOutput() {
        let regex = new RegExp('^(\.\/)?' + this.publicPath);

        return this[this.cssPreprocessor].output[
            this.versioning.enabled ? 'hashedPath' : 'path'
        ].replace(regex, '');
    }

    /**
     * Minify the given files, or those from Mix.minify().
     *
     * @param {array|null} files
     */
    minifyAll(files = null) {
        if (! this.inProduction) return;

        files = files || this.minify || [];

        files.forEach(file => new File(file).minify());

        return this;
    }

    /**
     * Combine the given files, or those from Mix.combine().
     *
     * @param {array|null} files
     */
    concatenateAll(files = null) {
        files = files || this.combine || [];

        files.forEach(file => {
            concatenate.sync(file.src, file.output);

            if (! this.inProduction) return;

            new this.File(file.output).minify();
        });

        return this;
    }

    /**
     * Detect if the user desires hot reloading.
     */
    detectHotReloading() {
        let file = new this.File(this.cachePath + '/hot');

        file.delete();

        // If the user wants hot module replacement, we'll create
        // a temporary file, so that Laravel can detect it, and
        // reference the proper base URL for any assets.
        if (process.argv.includes('--hot')) {
            this.hmr = true;

            file.write('hot reloading enabled');
        }
    }

    /**
     * Fetch the appropriate Babel config for babel-loader.
     */
    babelConfig() {
        let file = this.paths.root('.babelrc');

        // If the user has defined their own .babelrc file,
        // the babel-loader will automatically fetch it.
        // Otherwise, we'll use these defaults.
        return this.File.exists(file) ? '' : '?' + JSON.stringify({
            'cacheDirectory': true,
            'presets': [
                ['es2015', { 'modules': false }]
            ]
        });
    }

    /**
     * Determine if we are working with a Laravel project.
     */
    isUsingLaravel() {
        return this.File.exists('./artisan');
    }
};

module.exports = new Mix;
<|endoftext|>