<commit_before>/* This file is part of Indico.
 * Copyright (C) 2002 - 2019 European Organization for Nuclear Research (CERN).
 *
 * Indico is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of the
 * License, or (at your option) any later version.
 *
 * Indico is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Indico; if not, see <http://www.gnu.org/licenses/>.
 */

import * as linkingActions from './actions';

const initialState = {
    type: null,
    id: null,
    title: null,
    eventURL: null,
    eventTitle: null,
};

export default (state = initialState, action) => {
    switch (action.type) {
        case linkingActions.SET_OBJECT:
            return {
                type: action.objectType,
                id: action.objectId,
                title: action.objectTitle,
                eventURL: action.eventURL,
                eventTitle: action.eventTitle,
            };
        case linkingActions.CLEAR_OBJECT:
            return initialState;
        default:
            return state;
    }
};
<commit_msg>Exit linking mode after creating a booking<commit_after>/* This file is part of Indico.
 * Copyright (C) 2002 - 2019 European Organization for Nuclear Research (CERN).
 *
 * Indico is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of the
 * License, or (at your option) any later version.
 *
 * Indico is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Indico; if not, see <http://www.gnu.org/licenses/>.
 */

import * as linkingActions from './actions';
import {actions as bookRoomActions} from '../../modules/bookRoom';

const initialState = {
    type: null,
    id: null,
    title: null,
    eventURL: null,
    eventTitle: null,
};

export default (state = initialState, action) => {
    switch (action.type) {
        case linkingActions.SET_OBJECT:
            return {
                type: action.objectType,
                id: action.objectId,
                title: action.objectTitle,
                eventURL: action.eventURL,
                eventTitle: action.eventTitle,
            };
        case linkingActions.CLEAR_OBJECT:
        case bookRoomActions.CREATE_BOOKING_SUCCESS:
            return initialState;
        default:
            return state;
    }
};
<|endoftext|>


<commit_before>const path = require('path');
const makeDir = require('mkdirp');
const fs = require('fs');

/**
 * Writes text to a .cache folder in the root of the `react-dev-config` module.
 * Creates the necessary path if needed.
 **/
module.exports = function writeToCache(filename, text) {
  const dir = path.join(__dirname, '../.cache');

  makeDir.sync(dir);

  const filepath = `${dir}/${filename}`;

  try {
    fs.unlinkSync(filepath);
  } finally {
    fs.writeFileSync(filepath, text);
  }

  return filepath;
};
<commit_msg>unlink catch error<commit_after>const path = require('path');
const makeDir = require('mkdirp');
const fs = require('fs');

/**
 * Writes text to a .cache folder in the root of the `react-dev-config` module.
 * Creates the necessary path if needed.
 **/
module.exports = function writeToCache(filename, text) {
  const dir = path.join(__dirname, '../.cache');
  const filepath = `${dir}/${filename}`;

  try {
    fs.unlinkSync(filepath);
  } catch (err) {
    makeDir.sync(dir);
  } finally {
    fs.writeFileSync(filepath, text);
  }

  return filepath;
};
<|endoftext|>


<commit_before>(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
var $ = require('tinix')

function Template(name) {

    this.name = name
    this.template = $('template[data-name=' + name + ']')
    if (!this.template) throw 'Invalid Template Name'
    this.clones = []
    this.isLoading = false

    // For Unsupported Browsers
    if (!this.template.content) {
        var tContent = document.createDocumentFragment(),
            children = this.template.childNodes
        while (children[0]) {
            tContent.appendChild(children[0])
        }
        this.template.content = tContent
    }

    // remove whitespace nodes
    this.template.content.childNodes.forEach(function(child) {
        if (child.nodeName == '#text') {
            this.template.content.removeChild(child)
        }
    }.bind(this))

    if (this.template.content.childNodes.length !== 1) {
        throw 'Invalid template ' + this.name
    }

}

/*
 * Clone template and append to template parent.
 * if data Object provided will replace data textContent fields in template with
 * corresponding data Object Keys.
 * if data value has '<' innerHTML is replaced.
 */

Template.prototype.append = function(data, to) {

    var clone = document.importNode(this.template.content, true)
    if (data) {
        Object.keys(data).forEach(function(key) {
            var dataField = $('[data-field=' + key + ']', clone)
            if (dataField.type === 'checkbox') {
                dataField.checked = data[key]
            } else if (dataField) {
                var value = data[key]
                if ($.isString(value) && value.match(/</)) {
                    dataField.innerHTML = value
                } else {
                    dataField.textContent = value
                }
            }
        })
    }
    if (this.willRenderCallback) {
        this.willRenderCallback(clone.firstChild)
    }
    to = to || this.template.parentElement
    var firstChild = clone.firstChild
    to.appendChild(firstChild)
    this.clones.push(firstChild)
    return firstChild
}

Template.prototype.remove = function(elem) {
    elem.parentNode.removeChild(elem)
    this.clones.splice(this.clones.indexOf(elem), 1)
}

/*
 * If callback will call callback with error and responseBody or
 * json object if Json response. error is called with response object
 */

Template.prototype.post = function(url, body, callback) {
    if (callback) {
        callback = callback.bind(this)
    }
    var localCallback = function(error, res) {
        this.isLoading = false
        if (callback) {
            callback(error, res)
        } else {
            this.append(res)
        }
    }.bind(this)
    if (!this.isLoading) {
        this.isLoading = true
        if ($.isObject(body) || $.isArray(body)) {
            $.postJSON(url, body, localCallback)
        } else {
            $.post(url, body, 'application/x-www-form-urlencoded', localCallback)
        }
    }
}

Template.prototype.willRender = function(callback) {
    this.willRenderCallback = callback
}

Template.prototype.getData = function(index) {
    index = index || 0
    var dataFields = $.all('[data-field]', this.clones[index])
    var data = {}
    dataFields.forEach(function(dataField) {
        var key = dataField.getAttribute('data-field'),
            value
        if (dataField.type && dataField.type === 'checkbox') {
            value = dataField.checked
        } else if (dataField.tagName === 'INPUT' || dataField.tagName == 'TEXTAREA') {
            value = dataField.value
        } else {
            value = dataField.textContent
        }
        data[key] = value
    })
    return data
}

Template.prototype.getDataAll = function() {
    return this.clones.map(function(item, i) {
        return this.getData(i)
    }.bind(this))
}

module.exports = Template

},{"tinix":2}],2:[function(require,module,exports){
// tinix.js
//
// Copyright 2013 - Santosh Rajan - santoshrajan.com

function tinix(selector, elem) {
    elem = elem || document
    return elem.querySelector(selector)
}

tinix.version = "0.2.2"

tinix.supported = !!document.addEventListener

if (tinix.supported && !Element.prototype.on) {
  Element.prototype.on = Element.prototype.addEventListener
}

if (tinix.supported && !NodeList.prototype.forEach) {
  NodeList.prototype.forEach = Array.prototype.forEach
}

tinix.all = function(selector, elem) {
    elem = elem || document
    return elem.querySelectorAll(selector)
}

tinix.style = function(selector, rootElem, key, val) {
  this.all(selector, rootElem).forEach(function(el){
    el.style[key] = val
  })
}

tinix.display = function(selector, rootElem, val) {
    this.style(selector, rootElem, "display", val)
}

tinix.ready = function(func) {
  document.addEventListener('DOMContentLoaded', function() {func()})
}

tinix.isString = function(str) {
  return typeof(str) === 'string'
}

tinix.isArray = Array.isArray

tinix.isObject = function(str) {
  return Object.prototype.toString.call(str) === '[object Object]'
}

tinix.getR = function(callback) {
    var request = new XMLHttpRequest()
    responseText.onload = function() {
        if (request.status == 200) {
            if (request.getResponseHeader("Content-Type") == "application/json") {
                callback(null, JSON.parse(request.responseText))
            } else {
                callback(null, request.responseText)
            }
        } else {
            callback(request)
        }
    }
    return request
}

// get(url, callback [,overrideMimeType])
tinix.get = function(url, callback, overrideMimeType) {
    var request = this.getR(callback)
    request.open("GET", url)
    if (overrideMimeType) {
      request.overrideMimeType(overrideMimeType)
    }
    request.send()
}

// post(url, body, contenttype, callback)
tinix.post = function(url, body, contenttype, callback) {
    var request = this.getR(callback)
    request.open("POST", url)
    request.setRequestHeader("Content-Type", contenttype)
    request.send(body)
}

// postJSON(url, body, callback)
tinix.postJSON = function(url, body, callback) {
    this.post(url, JSON.stringify(body), "application/json", callback)
}

module.exports = tinix

},{}],3:[function(require,module,exports){
var $ = require('tinix')
var Template = require('temperor')

function start() {

    var mainDiv = new Template('Resp1ColMax640').append()

    var TodoInput = new Template('todo-input')

    TodoInput.willRender(function(elem) {
        var todoInput = $('input', elem)
        todoInput.on('keypress', function(e) {
            if (e.which === 13) {
                todo.append({todo: todoInput.value}, mainDiv)
                storeTodos()
                todoInput.value = ''
            }
        })
    })

    TodoInput.append(null, mainDiv)

    var todo = new Template('todo')
    todo.willRender(function(elem) {
        var todoView = elem.childNodes[1]
        var todoEdit = elem.childNodes[3]

        $('.delete', elem).on('click', function(e) {
            todo.remove(elem)
            storeTodos()
        })

        $('.check', elem).on('click', function(e) {
            storeTodos()
        })

        elem.on('dblclick', function(e){
            todoView.style.display = 'none'
            todoEdit.style.display = 'inline'
            todoEdit.focus()
            todoEdit.value = todoView.childNodes[3].textContent;
            todoEdit.on('keypress', function(e){
                if (e.which === 13)
                updateTodo()
            })

            function updateTodo () {
                todoEdit.style.display = 'none'
                todoView.style.display = 'block'
                todoView.childNodes[3].textContent = todoEdit.value
                storeTodos()
            }
        })
    })

    function storeTodos () {
        localStorage.setItem('todos',JSON.stringify(todo.getDataAll()))
    }

    JSON.parse(localStorage.getItem('todos')).forEach(function(elem){
        todo.append(elem, mainDiv);
    })
}

$.ready(start)

},{"temperor":1,"tinix":2}]},{},[3]);
<commit_msg>update tinix<commit_after>(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
var $ = require('tinix')

function Template(name) {

    this.name = name
    this.template = $('template[data-name=' + name + ']')
    if (!this.template) throw 'Invalid Template Name'
    this.clones = []
    this.isLoading = false

    // For Unsupported Browsers
    if (!this.template.content) {
        var tContent = document.createDocumentFragment(),
            children = this.template.childNodes
        while (children[0]) {
            tContent.appendChild(children[0])
        }
        this.template.content = tContent
    }

    // remove whitespace nodes
    this.template.content.childNodes.forEach(function(child) {
        if (child.nodeName == '#text') {
            this.template.content.removeChild(child)
        }
    }.bind(this))

    if (this.template.content.childNodes.length !== 1) {
        throw 'Invalid template ' + this.name
    }

}

/*
 * Clone template and append to template parent.
 * if data Object provided will replace data textContent fields in template with
 * corresponding data Object Keys.
 * if data value has '<' innerHTML is replaced.
 */

Template.prototype.append = function(data, to) {

    var clone = document.importNode(this.template.content, true)
    if (data) {
        Object.keys(data).forEach(function(key) {
            var dataField = $('[data-field=' + key + ']', clone)
            if (dataField.type === 'checkbox') {
                dataField.checked = data[key]
            } else if (dataField) {
                var value = data[key]
                if ($.isString(value) && value.match(/</)) {
                    dataField.innerHTML = value
                } else {
                    dataField.textContent = value
                }
            }
        })
    }
    if (this.willRenderCallback) {
        this.willRenderCallback(clone.firstChild)
    }
    to = to || this.template.parentElement
    var firstChild = clone.firstChild
    to.appendChild(firstChild)
    this.clones.push(firstChild)
    return firstChild
}

Template.prototype.remove = function(elem) {
    elem.parentNode.removeChild(elem)
    this.clones.splice(this.clones.indexOf(elem), 1)
}

/*
 * If callback will call callback with error and responseBody or
 * json object if Json response. error is called with response object
 */

Template.prototype.post = function(url, body, callback) {
    if (callback) {
        callback = callback.bind(this)
    }
    var localCallback = function(error, res) {
        this.isLoading = false
        if (callback) {
            callback(error, res)
        } else {
            this.append(res)
        }
    }.bind(this)
    if (!this.isLoading) {
        this.isLoading = true
        if ($.isObject(body) || $.isArray(body)) {
            $.postJSON(url, body, localCallback)
        } else {
            $.post(url, body, 'application/x-www-form-urlencoded', localCallback)
        }
    }
}

Template.prototype.willRender = function(callback) {
    this.willRenderCallback = callback
}

Template.prototype.getData = function(index) {
    index = index || 0
    var dataFields = $.all('[data-field]', this.clones[index])
    var data = {}
    dataFields.forEach(function(dataField) {
        var key = dataField.getAttribute('data-field'),
            value
        if (dataField.type && dataField.type === 'checkbox') {
            value = dataField.checked
        } else if (dataField.tagName === 'INPUT' || dataField.tagName == 'TEXTAREA') {
            value = dataField.value
        } else {
            value = dataField.textContent
        }
        data[key] = value
    })
    return data
}

Template.prototype.getDataAll = function() {
    return this.clones.map(function(item, i) {
        return this.getData(i)
    }.bind(this))
}

module.exports = Template

},{"tinix":2}],2:[function(require,module,exports){
// tinix.js
//
// Copyright 2013 - Santosh Rajan - santoshrajan.com

function tinix(selector, elem) {
    elem = elem || document
    return elem.querySelector(selector)
}

tinix.version = "0.2.3"

tinix.supported = !!document.addEventListener

if (tinix.supported && !Element.prototype.on) {
  Element.prototype.on = Element.prototype.addEventListener
}

if (tinix.supported && !NodeList.prototype.forEach) {
  NodeList.prototype.forEach = Array.prototype.forEach
}

tinix.all = function(selector, elem) {
    elem = elem || document
    return elem.querySelectorAll(selector)
}

tinix.style = function(selector, rootElem, key, val) {
  this.all(selector, rootElem).forEach(function(el){
    el.style[key] = val
  })
}

tinix.display = function(selector, rootElem, val) {
    this.style(selector, rootElem, "display", val)
}

tinix.ready = function(func) {
  document.addEventListener('DOMContentLoaded', function() {func()})
}

tinix.isString = function(str) {
  return typeof(str) === 'string'
}

tinix.isArray = Array.isArray

tinix.isObject = function(str) {
  return Object.prototype.toString.call(str) === '[object Object]'
}

tinix.getR = function(callback) {
    var request = new XMLHttpRequest()
    request.onload = function() {
        if (request.status == 200) {
            if (request.getResponseHeader("Content-Type") == "application/json") {
                callback(null, JSON.parse(request.responseText))
            } else {
                callback(null, request.responseText)
            }
        } else {
            callback(request)
        }
    }
    return request
}

// get(url, callback [,overrideMimeType])
tinix.get = function(url, callback, overrideMimeType) {
    var request = this.getR(callback)
    request.open("GET", url)
    if (overrideMimeType) {
      request.overrideMimeType(overrideMimeType)
    }
    request.send()
}

// post(url, body, contenttype, callback)
tinix.post = function(url, body, contenttype, callback) {
    var request = this.getR(callback)
    request.open("POST", url)
    request.setRequestHeader("Content-Type", contenttype)
    request.send(body)
}

// postJSON(url, body, callback)
tinix.postJSON = function(url, body, callback) {
    this.post(url, JSON.stringify(body), "application/json", callback)
}

module.exports = tinix

},{}],3:[function(require,module,exports){
var $ = require('tinix')
var Template = require('temperor')

function start() {

    var mainDiv = new Template('Resp1ColMax640').append()

    var TodoInput = new Template('todo-input')

    TodoInput.willRender(function(elem) {
        var todoInput = $('input', elem)
        todoInput.on('keypress', function(e) {
            if (e.which === 13) {
                todo.append({todo: todoInput.value}, mainDiv)
                storeTodos()
                todoInput.value = ''
            }
        })
    })

    TodoInput.append(null, mainDiv)

    var todo = new Template('todo')
    todo.willRender(function(elem) {
        var todoView = elem.childNodes[1]
        var todoEdit = elem.childNodes[3]

        $('.delete', elem).on('click', function(e) {
            todo.remove(elem)
            storeTodos()
        })

        $('.check', elem).on('click', function(e) {
            storeTodos()
        })

        elem.on('dblclick', function(e){
            todoView.style.display = 'none'
            todoEdit.style.display = 'inline'
            todoEdit.focus()
            todoEdit.value = todoView.childNodes[3].textContent;
            todoEdit.on('keypress', function(e){
                if (e.which === 13)
                updateTodo()
            })

            function updateTodo () {
                todoEdit.style.display = 'none'
                todoView.style.display = 'block'
                todoView.childNodes[3].textContent = todoEdit.value
                storeTodos()
            }
        })
    })

    function storeTodos () {
        localStorage.setItem('todos',JSON.stringify(todo.getDataAll()))
    }

    JSON.parse(localStorage.getItem('todos')).forEach(function(elem){
        todo.append(elem, mainDiv);
    })
}

$.ready(start)

},{"temperor":1,"tinix":2}]},{},[3]);
<|endoftext|>


<commit_before>const merge = require('webpack-merge');
const webpack = require('webpack');

const baseConfig = require('./webpack.base.config');

const prodConfig = merge(baseConfig, {
	devtool: 'source-map',
	stats: {
		modules: false
	},
	externals: {
		'highlight.js': {
			root: 'hljs',
			commonjs: 'highlight.js',
			commonjs2: 'highlight.js',
			amd: 'highlight.js'
		}
	}
});

const prodMinConfig = merge(prodConfig, {
	plugins: [
		new webpack.LoaderOptionsPlugin({
			minimize: true
		}),
		new webpack.optimize.UglifyJsPlugin({
			sourceMap: true
		})
	]
});

module.exports = [
	// CommonJS
	merge(prodConfig, {
		output: {
			filename: 'vue-highlight.js',
			libraryExport: 'default'
		}
	}),
	merge(prodMinConfig, {
		output: {
			filename: 'vue-highlight.min.js',
			libraryExport: 'default'
		}
	}),

	// ES Module
	merge(prodConfig, {
		output: {
			filename: 'vue-highlight.esm.js'
		}
	}),
	merge(prodMinConfig, {
		output: {
			filename: 'vue-highlight.esm.min.js'
		}
	})
];
<commit_msg>:wrench: Remove unnecessary minified ES module<commit_after>const merge = require('webpack-merge');
const webpack = require('webpack');

const baseConfig = require('./webpack.base.config');

const prodConfig = merge(baseConfig, {
	devtool: 'source-map',
	stats: {
		modules: false
	},
	externals: {
		'highlight.js': {
			root: 'hljs',
			commonjs: 'highlight.js',
			commonjs2: 'highlight.js',
			amd: 'highlight.js'
		}
	}
});

const prodMinConfig = merge(prodConfig, {
	plugins: [
		new webpack.LoaderOptionsPlugin({
			minimize: true
		}),
		new webpack.optimize.UglifyJsPlugin({
			sourceMap: true
		})
	]
});

module.exports = [
	// CommonJS
	merge(prodConfig, {
		output: {
			filename: 'vue-highlight.js',
			libraryExport: 'default'
		}
	}),
	merge(prodMinConfig, {
		output: {
			filename: 'vue-highlight.min.js',
			libraryExport: 'default'
		}
	}),

	// ES Module
	merge(prodConfig, {
		output: {
			filename: 'vue-highlight.esm.js'
		}
	})
];
<|endoftext|>


<commit_before>(function() {

  function addParamToUrl(url, param) {
    return url + (/\?/.test(url) ? '&' : '?') + param;
  }

  var makeXHR = (function() {
    var factories = [
      function() { return new ActiveXObject('Microsoft.XMLHTTP'); },
      function() { return new ActiveXObject('Msxml2.XMLHTTP'); },
      function() { return new ActiveXObject('Msxml2.XMLHTTP.3.0'); },
      function() { return new XMLHttpRequest(); }
    ];
    for (var i = factories.length; i--; ) {
      try {
        var req = factories[i]();
        if (req) {
          return factories[i];
        }
      }
      catch (err) { }
    }
  })();

  function emptyFn() { }

  /**
   * Cross-browser abstraction for sending XMLHttpRequest
   * @memberOf fabric.util
   * @param {String} url URL to send XMLHttpRequest to
   * @param {Object} [options] Options object
   * @param {String} [options.method="GET"]
   * @param {Function} options.onComplete Callback to invoke when request is completed
   * @return {XMLHttpRequest} request
   */
  function request(url, options) {

    options || (options = { });

    var method = options.method ? options.method.toUpperCase() : 'GET',
        onComplete = options.onComplete || function() { },
        xhr = makeXHR(),
        body;

    /** @ignore */
    xhr.onreadystatechange = function() {
      if (xhr.readyState === 4) {
        onComplete(xhr);
        xhr.onreadystatechange = emptyFn;
      }
    };

    if (method === 'GET') {
      body = null;
      if (typeof options.parameters === 'string') {
        url = addParamToUrl(url, options.parameters);
      }
    }

    xhr.open(method, url, true);

    if (method === 'POST' || method === 'PUT') {
      xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    }

    xhr.send(body);
    return xhr;
  }

  fabric.util.request = request;
})();
<commit_msg>initialized body variable<commit_after>(function() {

  function addParamToUrl(url, param) {
    return url + (/\?/.test(url) ? '&' : '?') + param;
  }

  var makeXHR = (function() {
    var factories = [
      function() { return new ActiveXObject('Microsoft.XMLHTTP'); },
      function() { return new ActiveXObject('Msxml2.XMLHTTP'); },
      function() { return new ActiveXObject('Msxml2.XMLHTTP.3.0'); },
      function() { return new XMLHttpRequest(); }
    ];
    for (var i = factories.length; i--; ) {
      try {
        var req = factories[i]();
        if (req) {
          return factories[i];
        }
      }
      catch (err) { }
    }
  })();

  function emptyFn() { }

  /**
   * Cross-browser abstraction for sending XMLHttpRequest
   * @memberOf fabric.util
   * @param {String} url URL to send XMLHttpRequest to
   * @param {Object} [options] Options object
   * @param {String} [options.method="GET"]
   * @param {String} [options.parameters] parameters to append to url in GET or in body
   * @param {String} [options.body] body to send with POST or PUT request
   * @param {Function} options.onComplete Callback to invoke when request is completed
   * @return {XMLHttpRequest} request
   */
  function request(url, options) {

    options || (options = { });

    var method = options.method ? options.method.toUpperCase() : 'GET',
        onComplete = options.onComplete || function() { },
        xhr = makeXHR(),
        body = options.body || options.parameters;

    /** @ignore */
    xhr.onreadystatechange = function() {
      if (xhr.readyState === 4) {
        onComplete(xhr);
        xhr.onreadystatechange = emptyFn;
      }
    };

    if (method === 'GET') {
      body = null;
      if (typeof options.parameters === 'string') {
        url = addParamToUrl(url, options.parameters);
      }
    }

    xhr.open(method, url, true);

    if (method === 'POST' || method === 'PUT') {
      xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    }

    xhr.send(body);
    return xhr;
  }

  fabric.util.request = request;
})();
<|endoftext|>


<commit_before>'use strict';

const nameRegex   = /at (.+) \((.+):(\d+):(\d+)\)$/;
const noNameRegex = /at( )(.+):(\d+):(\d+)$/;
const nativeRegex = /at (.+) \(native\)$/;

function parseFrame(frame) {
  let name   = null;
  let line   = null;
  let column = null;
  let file   = null;
  let match  = nameRegex.exec(frame);

  // Is it a named function?
  if (match) {
    name = match[1];
  } else {
    // Perhaps it's an anonymous function
    match = noNameRegex.exec(frame);
  }

  if (match) {
    line   = parseInt(match[3]);
    column = parseInt(match[4]);
    file   = match[2];

  } else {
    // It must be a native function.
    match = nativeRegex.exec(frame);
    name  = match[1];
  }

  return {
    functionName: name,
    file:   file,
    line:   line,
    column: column,
  };
}

const msgRegex = /(\w+): (.+)$/;

function parseError(err) {
  let   name;
  let   msg   = null;
  const stack = err.stack.split('\n');
  const first = stack.shift();
  const match = msgRegex.exec(first);

  if (match) {
    name  = match[1];
    msg   = match[2];
  } else {
    name = first;
  }

  return {
    name:    name,
    message: msg,
    stack:   stack.map(parseFrame),
  };
}

module.exports = { parseError, parseFrame };
<commit_msg>Dig that ES6 noise, baby<commit_after>'use strict';

const nameRegex   = /at (.+) \((.+):(\d+):(\d+)\)$/;
const noNameRegex = /at( )(.+):(\d+):(\d+)$/;
const nativeRegex = /at (.+) \(native\)$/;

function parseFrame(frame) {
  let functionName = null;
  let line   = null;
  let column = null;
  let file   = null;
  let match  = nameRegex.exec(frame);

  // Is it a named function?
  if (match) {
    functionName = match[1];
  } else {
    // Perhaps it's an anonymous function
    match = noNameRegex.exec(frame);
  }

  if (match) {
    line   = parseInt(match[3]);
    column = parseInt(match[4]);
    file   = match[2];

  } else {
    // It must be a native function.
    match = nativeRegex.exec(frame);
    functionName = match[1];
  }

  return { functionName, file, line, column };
}

const msgRegex = /(\w+): (.+)$/;

function parseError(err) {
  let   name;
  let   msg   = null;
  const stack = err.stack.split('\n');
  const first = stack.shift();
  const match = msgRegex.exec(first);

  if (match) {
    name  = match[1];
    msg   = match[2];
  } else {
    name = first;
  }

  return {
    name:    name,
    message: msg,
    stack:   stack.map(parseFrame),
  };
}

module.exports = { parseError, parseFrame };
<|endoftext|>


<commit_before>// Ensure `application` module is loaded
// before overriding `global.__onLiveSyncCore`
import { run, on, launchEvent } from 'tns-core-modules/application'
import { warn } from 'core/util/index'
import { patch } from './patch'
import { mountComponent } from 'core/instance/lifecycle'
import { compileToFunctions } from '../compiler/index'
import { mustUseProp, isReservedTag, isUnknownElement } from '../util/index'
import { registerElement, getElementMap } from '../element-registry'

import Vue from 'core/index'
import DocumentNode from '../renderer/DocumentNode'
import platformDirectives from './directives/index'

Vue.config.mustUseProp = mustUseProp
Vue.config.isReservedTag = isReservedTag
Vue.config.isUnknownElement = isUnknownElement

Vue.$document = Vue.prototype.$document = new DocumentNode()

Vue.compile = compileToFunctions
Vue.registerElement = registerElement

Object.assign(Vue.options.directives, platformDirectives)

Vue.prototype.__patch__ = patch

Vue.prototype.$mount = function(el, hydrating) {
  const options = this.$options
  // resolve template/el and convert to render function
  if (!options.render) {
    let template = options.template
    if (template && typeof template !== 'string') {
      warn('invalid template option: ' + template, this)
      return this
    }

    if (template) {
      const { render, staticRenderFns } = compileToFunctions(
        template,
        {
          delimiters: options.delimiters,
          comments: options.comments
        },
        this
      )
      options.render = render
      options.staticRenderFns = staticRenderFns
    }
  }

  return mountComponent(this, el, hydrating)
}

Vue.prototype.$start = function() {
  let self = this
  const AppConstructor = Vue.extend(this.$options)

  // register NS components into Vue
  Object.values(getElementMap()).forEach(entry => {
    Vue.component(entry.meta.component.name, entry.meta.component)
  })

  on(launchEvent, args => {
    if (self.$el) {
      self.$destroy()
      self = new AppConstructor()
    }

    self.$mount()
    args.root = self.$el.nativeView
  })

  run()
}

// Define a `nativeView` getter in every NS vue instance
Object.defineProperty(Vue.prototype, 'nativeView', {
  get() {
    return this.$el.nativeView
  }
})

export default Vue
<commit_msg>fix: import `frame` module before __onLiveSyncCore override  (#517)<commit_after>// Ensure `application` and `frame` modules are loaded
// before overriding `global.__onLiveSyncCore`
import { run, on, launchEvent } from 'tns-core-modules/application'
import 'tns-core-modules/ui/frame'

import { warn } from 'core/util/index'
import { patch } from './patch'
import { mountComponent } from 'core/instance/lifecycle'
import { compileToFunctions } from '../compiler/index'
import { mustUseProp, isReservedTag, isUnknownElement } from '../util/index'
import { registerElement, getElementMap } from '../element-registry'

import Vue from 'core/index'
import DocumentNode from '../renderer/DocumentNode'
import platformDirectives from './directives/index'

Vue.config.mustUseProp = mustUseProp
Vue.config.isReservedTag = isReservedTag
Vue.config.isUnknownElement = isUnknownElement

Vue.$document = Vue.prototype.$document = new DocumentNode()

Vue.compile = compileToFunctions
Vue.registerElement = registerElement

Object.assign(Vue.options.directives, platformDirectives)

Vue.prototype.__patch__ = patch

Vue.prototype.$mount = function(el, hydrating) {
  const options = this.$options
  // resolve template/el and convert to render function
  if (!options.render) {
    let template = options.template
    if (template && typeof template !== 'string') {
      warn('invalid template option: ' + template, this)
      return this
    }

    if (template) {
      const { render, staticRenderFns } = compileToFunctions(
        template,
        {
          delimiters: options.delimiters,
          comments: options.comments
        },
        this
      )
      options.render = render
      options.staticRenderFns = staticRenderFns
    }
  }

  return mountComponent(this, el, hydrating)
}

Vue.prototype.$start = function() {
  let self = this
  const AppConstructor = Vue.extend(this.$options)

  // register NS components into Vue
  Object.values(getElementMap()).forEach(entry => {
    Vue.component(entry.meta.component.name, entry.meta.component)
  })

  on(launchEvent, args => {
    if (self.$el) {
      self.$destroy()
      self = new AppConstructor()
    }

    self.$mount()
    args.root = self.$el.nativeView
  })

  run()
}

// Define a `nativeView` getter in every NS vue instance
Object.defineProperty(Vue.prototype, 'nativeView', {
  get() {
    return this.$el.nativeView
  }
})

export default Vue
<|endoftext|>


<commit_before>var React = require('react')
var styleAttr = require('style-attr')
var camelCase = require('lodash.camelcase')
var mapValues = require('lodash.mapvalues')
var querySelectorAll = require('query-selector')

function styleCamelCase (name) {
  var camel = camelCase(name)

  if (name[0] === '-') {
    return camel[0].toUpperCase() + camel.slice(1)
  } else {
    return camel
  }
}

function isTruthy (value) {
  return !!value
}

function clone (value) {
  return Object.assign({}, value)
}

function Element (nodeName, parentNode) {
  this.nodeName = nodeName
  this.parentNode = parentNode
  this.childNodes = []
  this.eventListeners = {}
  this.text = ''
  var props = this.props = {
    style: {
      setProperty: function (name, value) {
        props.style[styleCamelCase(name)] = value
      },
      getProperty: function (name) {
        return props.style[styleCamelCase(name)]
      },
      removeProperty: function (name) {
        delete props.style[styleCamelCase(name)]
      }
    }
  }

  this.style = props.style
}

Element.prototype.nodeType = 1

// This was easy to do with Vim.
// Just saying.
Element.prototype.eventNameMappings = {
  'blur': 'onBlur',
  'change': 'onChange',
  'click': 'onClick',
  'contextmenu': 'onContextMenu',
  'copy': 'onCopy',
  'cut': 'onCut',
  'doubleclick': 'onDoubleClick',
  'drag': 'onDrag',
  'dragend': 'onDragEnd',
  'dragenter': 'onDragEnter',
  'dragexit': 'onDragExit',
  'dragleave': 'onDragLeave',
  'dragover': 'onDragOver',
  'dragstart': 'onDragStart',
  'drop': 'onDrop',
  'error': 'onError',
  'focus': 'onFocus',
  'input': 'onInput',
  'keydown': 'onKeyDown',
  'keypress': 'onKeyPress',
  'keyup': 'onKeyUp',
  'load': 'onLoad',
  'mousedown': 'onMouseDown',
  'mouseenter': 'onMouseEnter',
  'mouseleave': 'onMouseLeave',
  'mousemove': 'onMouseMove',
  'mouseout': 'onMouseOut',
  'mouseover': 'onMouseOver',
  'mouseup': 'onMouseUp',
  'paste': 'onPaste',
  'scroll': 'onScroll',
  'submit': 'onSubmit',
  'touchcancel': 'onTouchCancel',
  'touchend': 'onTouchEnd',
  'touchmove': 'onTouchMove',
  'touchstart': 'onTouchStart',
  'wheel': 'onWheel'
}

Element.prototype.skipNameTransformationExpressions = [
  /^data-/,
  /^aria-/
]

Element.prototype.attributeNameMappings = {
  'class': 'className'
}

Element.prototype.attributeToPropName = function (name) {
  var skipTransformMatches = this.skipNameTransformationExpressions.map(function (expr) {
    return expr.test(name)
  })

  if (skipTransformMatches.some(isTruthy)) {
    return name
  } else {
    return this.attributeNameMappings[name] || camelCase(name)
  }
}

Element.prototype.setAttribute = function (name, value) {
  if (name === 'style' && typeof value === 'string') {
    var styles = styleAttr.parse(value)

    for (var key in styles) {
      this.style.setProperty(key, styles[key])
    }
  } else {
    this.props[this.attributeToPropName(name)] = value
  }
}

Element.prototype.getAttribute = function (name) {
  return this.props[this.attributeToPropName(name)]
}

Element.prototype.getAttributeNode = function (name) {
  var value = this.getAttribute(name)

  if (typeof value !== 'undefined') {
    return {
      value: value,
      specified: true
    }
  }
}

Element.prototype.removeAttribute = function (name) {
  delete this.props[this.attributeToPropName(name)]
}

Element.prototype.eventToPropName = function (name) {
  return this.eventNameMappings[name] || name
}

Element.prototype.addEventListener = function (name, fn) {
  var prop = this.eventToPropName(name)
  this.eventListeners[prop] = this.eventListeners[prop] || []
  this.eventListeners[prop].push(fn)
}

Element.prototype.removeEventListener = function (name, fn) {
  var listeners = this.eventListeners[this.eventToPropName(name)]

  if (listeners) {
    var match = listeners.indexOf(fn)

    if (match !== -1) {
      listeners.splice(match, 1)
    }
  }
}

Element.prototype.appendChild = function (el) {
  el.parentNode = this
  this.childNodes.push(el)
  return el
}

Element.prototype.insertBefore = function (el, before) {
  var index = this.childNodes.indexOf(before)
  el.parentNode = this

  if (index !== -1) {
    this.childNodes.splice(index, 0, el)
  } else {
    this.childNodes.push(el)
  }

  return el
}

Element.prototype.removeChild = function (child) {
  var target = this.childNodes.indexOf(child)
  this.childNodes.splice(target, 1)
}

Element.prototype.querySelector = function () {
  return this.querySelectorAll.apply(this, arguments)[0]
}

Element.prototype.querySelectorAll = function (selector) {
  return querySelectorAll(selector, this)
}

Element.prototype.getElementsByTagName = function (nodeName) {
  var children = this.children

  if (children.length === 0) {
    return []
  } else {
    var matches

    if (nodeName !== '*') {
      matches = children.filter(function (el) {
        return el.nodeName === nodeName
      })
    } else {
      matches = children
    }

    var childMatches = children.map(function (el) {
      return el.getElementsByTagName(nodeName)
    })

    return matches.concat.apply(matches, childMatches)
  }
}

Element.prototype.getElementById = function (id) {
  var children = this.children

  if (children.length === 0) {
    return null
  } else {
    var match = children.filter(function (el) {
      return el.getAttribute('id') === id
    })[0]

    if (match) {
      return match
    } else {
      var childMatches = children.map(function (el) {
        return el.getElementById(id)
      })

      return childMatches.filter(function (match) {
        return match !== null
      })[0] || null
    }
  }
}

Element.prototype.toReact = function (index) {
  index = index || 0
  var props = clone(this.props)
  props.style = clone(props.style)

  var originalElement = this

  function uniqueKey () {
    return 'faux-dom-' + index
  }

  if (typeof props.key === 'undefined') {
    props.key = uniqueKey()
  }

  delete props.style.setProperty
  delete props.style.getProperty
  delete props.style.removeProperty

  Object.assign(props, mapValues(this.eventListeners, function (listeners) {
    return function (syntheticEvent) {
      var event

      if (syntheticEvent) {
        event = syntheticEvent.nativeEvent
        event.syntheticEvent = syntheticEvent
      }

      mapValues(listeners, function (listener) {
        listener.call(originalElement, event)
      })
    }
  }))

  return React.createElement(this.nodeName, props, this.text || this.children.map(function (el, i) {
    if (el instanceof Element) {
      return el.toReact(i)
    } else {
      return el
    }
  }))
}

Object.defineProperties(Element.prototype, {
  nextSibling: {
    get: function () {
      var siblings = this.parentNode.children
      var me = siblings.indexOf(this)
      return siblings[me + 1]
    }
  },
  previousSibling: {
    get: function () {
      var siblings = this.parentNode.children
      var me = siblings.indexOf(this)
      return siblings[me - 1]
    }
  },
  innerHTML: {
    get: function () {
      return this.text
    },
    set: function (text) {
      this.text = text
    }
  },
  textContent: {
    get: function () {
      return this.text
    },
    set: function (text) {
      this.text = text
    }
  },
  children: {
    get: function () {
      // So far nodes created by this library are all of nodeType 1 (elements),
      // but this could change in the future.
      return this.childNodes.filter(function (el) {
        if (!el.nodeType) {
          // It's a React element, we always add it
          return true
        }

        // It's a HTML node. We want to filter to have only nodes with type 1
        return el.nodeType === 1
      })
    }
  }
})

// These NS methods are called by things like D3 if it spots a namespace.
// Like xlink:href. I don't care about namespaces, so these functions have NS aliases created.
var namespaceMethods = [
  'setAttribute',
  'getAttribute',
  'getAttributeNode',
  'removeAttribute',
  'getElementsByTagName',
  'getElementById'
]

namespaceMethods.forEach(function (name) {
  var fn = Element.prototype[name]
  Element.prototype[name + 'NS'] = function () {
    return fn.apply(this, Array.prototype.slice.call(arguments, 1))
  }
})

module.exports = Element
<commit_msg>Replace typeof checks with functions<commit_after>var React = require('react')
var styleAttr = require('style-attr')
var camelCase = require('lodash.camelcase')
var mapValues = require('lodash.mapvalues')
var querySelectorAll = require('query-selector')

function styleCamelCase (name) {
  var camel = camelCase(name)

  if (name[0] === '-') {
    return camel[0].toUpperCase() + camel.slice(1)
  } else {
    return camel
  }
}

function isTruthy (value) {
  return !!value
}

function isString (value) {
  return typeof value === 'string'
}

function isUndefined (value) {
  return typeof value === 'undefined'
}

function clone (value) {
  return Object.assign({}, value)
}

function Element (nodeName, parentNode) {
  this.nodeName = nodeName
  this.parentNode = parentNode
  this.childNodes = []
  this.eventListeners = {}
  this.text = ''
  var props = this.props = {
    style: {
      setProperty: function (name, value) {
        props.style[styleCamelCase(name)] = value
      },
      getProperty: function (name) {
        return props.style[styleCamelCase(name)]
      },
      removeProperty: function (name) {
        delete props.style[styleCamelCase(name)]
      }
    }
  }

  this.style = props.style
}

Element.prototype.nodeType = 1

// This was easy to do with Vim.
// Just saying.
Element.prototype.eventNameMappings = {
  'blur': 'onBlur',
  'change': 'onChange',
  'click': 'onClick',
  'contextmenu': 'onContextMenu',
  'copy': 'onCopy',
  'cut': 'onCut',
  'doubleclick': 'onDoubleClick',
  'drag': 'onDrag',
  'dragend': 'onDragEnd',
  'dragenter': 'onDragEnter',
  'dragexit': 'onDragExit',
  'dragleave': 'onDragLeave',
  'dragover': 'onDragOver',
  'dragstart': 'onDragStart',
  'drop': 'onDrop',
  'error': 'onError',
  'focus': 'onFocus',
  'input': 'onInput',
  'keydown': 'onKeyDown',
  'keypress': 'onKeyPress',
  'keyup': 'onKeyUp',
  'load': 'onLoad',
  'mousedown': 'onMouseDown',
  'mouseenter': 'onMouseEnter',
  'mouseleave': 'onMouseLeave',
  'mousemove': 'onMouseMove',
  'mouseout': 'onMouseOut',
  'mouseover': 'onMouseOver',
  'mouseup': 'onMouseUp',
  'paste': 'onPaste',
  'scroll': 'onScroll',
  'submit': 'onSubmit',
  'touchcancel': 'onTouchCancel',
  'touchend': 'onTouchEnd',
  'touchmove': 'onTouchMove',
  'touchstart': 'onTouchStart',
  'wheel': 'onWheel'
}

Element.prototype.skipNameTransformationExpressions = [
  /^data-/,
  /^aria-/
]

Element.prototype.attributeNameMappings = {
  'class': 'className'
}

Element.prototype.attributeToPropName = function (name) {
  var skipTransformMatches = this.skipNameTransformationExpressions.map(function (expr) {
    return expr.test(name)
  })

  if (skipTransformMatches.some(isTruthy)) {
    return name
  } else {
    return this.attributeNameMappings[name] || camelCase(name)
  }
}

Element.prototype.setAttribute = function (name, value) {
  if (name === 'style' && isString(value)) {
    var styles = styleAttr.parse(value)

    for (var key in styles) {
      this.style.setProperty(key, styles[key])
    }
  } else {
    this.props[this.attributeToPropName(name)] = value
  }
}

Element.prototype.getAttribute = function (name) {
  return this.props[this.attributeToPropName(name)]
}

Element.prototype.getAttributeNode = function (name) {
  var value = this.getAttribute(name)

  if (!isUndefined(value)) {
    return {
      value: value,
      specified: true
    }
  }
}

Element.prototype.removeAttribute = function (name) {
  delete this.props[this.attributeToPropName(name)]
}

Element.prototype.eventToPropName = function (name) {
  return this.eventNameMappings[name] || name
}

Element.prototype.addEventListener = function (name, fn) {
  var prop = this.eventToPropName(name)
  this.eventListeners[prop] = this.eventListeners[prop] || []
  this.eventListeners[prop].push(fn)
}

Element.prototype.removeEventListener = function (name, fn) {
  var listeners = this.eventListeners[this.eventToPropName(name)]

  if (listeners) {
    var match = listeners.indexOf(fn)

    if (match !== -1) {
      listeners.splice(match, 1)
    }
  }
}

Element.prototype.appendChild = function (el) {
  el.parentNode = this
  this.childNodes.push(el)
  return el
}

Element.prototype.insertBefore = function (el, before) {
  var index = this.childNodes.indexOf(before)
  el.parentNode = this

  if (index !== -1) {
    this.childNodes.splice(index, 0, el)
  } else {
    this.childNodes.push(el)
  }

  return el
}

Element.prototype.removeChild = function (child) {
  var target = this.childNodes.indexOf(child)
  this.childNodes.splice(target, 1)
}

Element.prototype.querySelector = function () {
  return this.querySelectorAll.apply(this, arguments)[0]
}

Element.prototype.querySelectorAll = function (selector) {
  return querySelectorAll(selector, this)
}

Element.prototype.getElementsByTagName = function (nodeName) {
  var children = this.children

  if (children.length === 0) {
    return []
  } else {
    var matches

    if (nodeName !== '*') {
      matches = children.filter(function (el) {
        return el.nodeName === nodeName
      })
    } else {
      matches = children
    }

    var childMatches = children.map(function (el) {
      return el.getElementsByTagName(nodeName)
    })

    return matches.concat.apply(matches, childMatches)
  }
}

Element.prototype.getElementById = function (id) {
  var children = this.children

  if (children.length === 0) {
    return null
  } else {
    var match = children.filter(function (el) {
      return el.getAttribute('id') === id
    })[0]

    if (match) {
      return match
    } else {
      var childMatches = children.map(function (el) {
        return el.getElementById(id)
      })

      return childMatches.filter(function (match) {
        return match !== null
      })[0] || null
    }
  }
}

Element.prototype.toReact = function (index) {
  index = index || 0
  var props = clone(this.props)
  props.style = clone(props.style)

  var originalElement = this

  function uniqueKey () {
    return 'faux-dom-' + index
  }

  if (isUndefined(props.key)) {
    props.key = uniqueKey()
  }

  delete props.style.setProperty
  delete props.style.getProperty
  delete props.style.removeProperty

  Object.assign(props, mapValues(this.eventListeners, function (listeners) {
    return function (syntheticEvent) {
      var event

      if (syntheticEvent) {
        event = syntheticEvent.nativeEvent
        event.syntheticEvent = syntheticEvent
      }

      mapValues(listeners, function (listener) {
        listener.call(originalElement, event)
      })
    }
  }))

  return React.createElement(this.nodeName, props, this.text || this.children.map(function (el, i) {
    if (el instanceof Element) {
      return el.toReact(i)
    } else {
      return el
    }
  }))
}

Object.defineProperties(Element.prototype, {
  nextSibling: {
    get: function () {
      var siblings = this.parentNode.children
      var me = siblings.indexOf(this)
      return siblings[me + 1]
    }
  },
  previousSibling: {
    get: function () {
      var siblings = this.parentNode.children
      var me = siblings.indexOf(this)
      return siblings[me - 1]
    }
  },
  innerHTML: {
    get: function () {
      return this.text
    },
    set: function (text) {
      this.text = text
    }
  },
  textContent: {
    get: function () {
      return this.text
    },
    set: function (text) {
      this.text = text
    }
  },
  children: {
    get: function () {
      // So far nodes created by this library are all of nodeType 1 (elements),
      // but this could change in the future.
      return this.childNodes.filter(function (el) {
        if (!el.nodeType) {
          // It's a React element, we always add it
          return true
        }

        // It's a HTML node. We want to filter to have only nodes with type 1
        return el.nodeType === 1
      })
    }
  }
})

// These NS methods are called by things like D3 if it spots a namespace.
// Like xlink:href. I don't care about namespaces, so these functions have NS aliases created.
var namespaceMethods = [
  'setAttribute',
  'getAttribute',
  'getAttributeNode',
  'removeAttribute',
  'getElementsByTagName',
  'getElementById'
]

namespaceMethods.forEach(function (name) {
  var fn = Element.prototype[name]
  Element.prototype[name + 'NS'] = function () {
    return fn.apply(this, Array.prototype.slice.call(arguments, 1))
  }
})

module.exports = Element
<|endoftext|>


<commit_before>angular.module("dotyApp")
.factory('queryAPI', function($http, $timeout, $q, $rootScope) {
  var fac = {};

  fac.logout = function() {
    $http({
      method: 'GET',
      url: 'https://www.daysoftheyear.com/api/1.5/user/?logout'
    }).then(function() {
      fac.userRemoveData();
      fac.removeCredentials();
      fac.signinModalOpen();
    });
  };

  fac.getDayToday = function() {

    var deferred = $q.defer();

    var todayDate = new Date();
    var today = Date.UTC(todayDate.getFullYear(), todayDate.getMonth(), todayDate.getDate()) / 1000;
    var todayB = Date.UTC(todayDate.getFullYear(), todayDate.getMonth(), todayDate.getDate()) / 1000;

    console.log("Grabbing [day-by-date]: https://www.daysoftheyear.com/api/1.5/days/?date_start="
                + today +"&date_end=" + today + "&limit=100");

    $http({
      method: 'GET',
      url: "https://www.daysoftheyear.com/api/1.5/days/?date_start="
      + today +"&date_end=" + todayB + "&limit=100"
    })
    .success(function(data) {
      deferred.resolve(data);
    })
    .error(function () {
      deferred.reject('could not retrieve days (getDayToday)');
    });

    return deferred.promise;
  };

  fac.getDayByDate = function(startDate, endDate) {

    var deferred = $q.defer();

    endDate = endDate || startDate;

    console.log("Grabbing [day-by-date]: https://www.daysoftheyear.com/api/1.5/days/?date_start="
                + startDate +"&date_end=" + endDate + "&limit=100");

    $http({
      method: 'GET',
      url: "https://www.daysoftheyear.com/api/1.5/days/?date_start="
      + startDate +"&date_end=" + endDate + "&limit=100"
    })
    .success(function(data) {
      deferred.resolve(data);
    })
    .error(function () {
      deferred.reject('could not retrieve days (getDayToday)');
    });

    return deferred.promise;
  };

  fac.getDayById = function(idArray) {
    var deferred = $q.defer();

    var url = "https://www.daysoftheyear.com/api/1.5/days?";

    var idArrayLength = idArray.length;

    if (idArrayLength) {
      url = url + '&ids=' + idArray[0];
      for(var i = 1; i < idArrayLength; i++) {
        url = url + ',' + idArray[i];
      };

      console.log("grabbing [day-by-id]: " + url);

      $http({
        method: 'GET',
        url: url
      })
      .success(function (data) {
        deferred.resolve(data)
      })
      .error(function () {
        deferred.reject('could not retrieve day-id data');
      });
    } else {
      deferred.reject('no ids passed to getDayById!');
    }

    return deferred.promise;
  };

  fac.getDayByTag = function(options) {

    var tagArray = options.tagArray;
    var limit = options.limit || 10;
    var offset = options.offset || 0;

    var deferred = $q.defer();

    var url = "https://www.daysoftheyear.com/api/1.5/days?limit=" + limit;

    var tagArrayLength = tagArray.length;

    if (tagArrayLength) {
      url = url + '&tags=' + tagArray[0];
      for(var i = 1; i < tagArrayLength; i++) {
        url = url + ',' + tagArray[i];
      };

      console.log('Grabbing [day-by-tag]: ' + url);

      $http({
        method: 'GET',
        url: url
      })
      .success(function (data) {
        deferred.resolve(data)
      })
      .error(function () {
        deferred.reject('could not retrieve days by tag data');
      });
    }  else {
      deferred.reject('no tags passed to getDayByTag!');
    }

    return deferred.promise;
  };

  fac.getDayBySearch = function (query, offset) {
    var deferred = $q.defer();

    var limit = 10; // Temporary. This function should grab days in the near future. Need to figure out if the API returns date sorted content.
    var offset = offset || 0;
    var url = "https://www.daysoftheyear.com/api/1.5/days/?limit=" + limit + '&s=' + query + '&offset=' + offset;

    console.log('Grabbing [day-by-search]: ' + url);

    $http({
      method: 'GET',
      url: url
    })
    .success(function (data) {
      deferred.resolve(data);
    })
    .error(function () {
      deferred.reject('could not retrieve days by search query');
    });

    return deferred.promise;
  };

  fac.getTags = function() {
    var deferred = $q.defer();

    $http({
      method: 'GET',
      url: "https://www.daysoftheyear.com/api/1.5/tags"
    })
    .success(function (data) {
      deferred.resolve(data)
    })
    .error(function () {
      deferred.reject('could not retrieve tags');
    });

    return deferred.promise;
  };

  // Clean Title and Content
  fac.cleanDay = function(daysArray) {
    var deferred = $q.defer();

    $.each(daysArray, function (index, _dayObj) {
      //      _dayObj.title = _dayObj.title
      //      .replace("’","'")
      //      .replace("&","&")
      //      .replace("é","é");

      _dayObj.tag = {};
      _dayObj.tagArray = [];
      $.each(_dayObj.tags, function (_tagIndex, _tagValue) {
        _dayObj.tags[_tagIndex].name = _dayObj.tags[_tagIndex].name
        .replace("&","&");

        if (_dayObj.tags[_tagIndex].level === 0) {
          _dayObj.tag = {
            name: _dayObj.tags[_tagIndex].name,
            slug: _dayObj.tags[_tagIndex].slug
          };
        }

        _dayObj.tagArray.push(_dayObj.tags[_tagIndex].slug);
      });

      var currentTime = new Date().getTime() / 1000;
      var timeDiff = 0;
      var timeIndex = -1;

      $.each(_dayObj.dates, function (_dateIndex, _dateValue) {
        var dateDiff = Math.abs(parseInt(_dayObj.dates[_dateIndex]) - currentTime);
        if (dateDiff < timeDiff || timeIndex === -1) {
          timeDiff = dateDiff;
          timeIndex = _dateIndex;
        }
      });

      _dayObj.date = new Date(parseInt(_dayObj.dates[timeIndex]) * 1000);

      if ($rootScope.userData.pc_days.indexOf(_dayObj.id.toString()) !== -1) {
        _dayObj.bookmarked = true;
      } else {_dayObj.bookmarked = false;}

      _dayObj.content = "
" + _dayObj.content + "
"
      _dayObj.content = _dayObj.content
      .replace(/
/g, "
")
      .replace(/
/g, "
")
      .replace(/
/g, "
")
      .replace(/<\/h3>/gi, "
")
      .replace(/
/g, "
")
      .replace(/<\/h2>/gi, "
");
      //      .replace(//g, "")
      //      .replace(/<\/?a[^>]*>/g, "")
      //      .replace(/
/g, "
")
      //      .replace(/<\/p>/gi, "
");
      //      console.log(_dayObj.content);
    });

    console.log("cleaned up these days");
    console.log(daysArray);
    deferred.resolve(daysArray);

    return deferred.promise;
  };

  fac.cleanCategory = function(categoryArray) {
    $.each(categoryArray, function (index, catObj) {
      catObj.name = catObj.name.replace("&","&");
      console.log(catObj);
      if(catObj.children.length) {
        $.each(catObj.children, function (index, subObj) {
          subObj.name = subObj.name.replace("&","&");
        });
      }
    });
    return categoryArray;
  };

  fac.setDayColors = function () {
    var colors = ["#ea493b", "#7fccbd", "#81c256", "#f6d24c",
                  "#9765b8", "#73a6db", "#9e4f64", "#e6b294"];

    var lightercolors = ["#EE6D62", "#99D6CA", "#9ACE78", "#F8DB70",
                         "#AC84C6", "#8FB8E2", "#B17283", "#EBC1A9"];

    var darkercolors = ["#bf544b", "#549f90", "#649543", "#aa964d",
                        "#70478b", "#4b6e93", "#743a4a", "#9f7258"];

    $timeout(function () {
      $(".card-title").each(function(i) {
        this.style.background = colors[i % 8];
      });

      $(".card-wrapper").each(function(i) {
        this.style.borderColor = colors[i % 8];
        this.style['box-shadow'] = '0px 2px 0px 0px' + darkercolors[i % 8];
        //        rgba(175, 136, 114, 1)'
      });

      $(".dayimage-container").each(function(i) {
        this.style['background-color'] = lightercolors[i % 8];
      });
    }, 0, false);

  };

  fac.setCategoryColors = function () {
    var colors = ["#ea493b", "#7fccbd", "#81c256", "#f6d24c",
                  "#9765b8", "#73a6db", "#9e4f64", "#e6b294"];

    $timeout(function () {
      $(".explore-category").each(function(i) {
        this.style.background = colors[i % 8];
      });
    }, 1);

  };

  return fac;
});
<commit_msg>Arguments passed as argument-object properties now for various functions,  cleaned up debug logging, replaced a for loop with a valueOf<commit_after>angular.module("dotyApp")
.factory('queryAPI', function($http, $timeout, $q, $rootScope) {
  var fac = {};

  fac.logout = function() {
    $http({
      method: 'GET',
      url: 'https://www.daysoftheyear.com/api/1.5/user/?logout'
    }).then(function() {
      fac.userRemoveData();
      fac.removeCredentials();
      fac.signinModalOpen();
    });
  };

  fac.getDayToday = function() {

    var deferred = $q.defer();

    var todayDate = new Date();
    var today = Date.UTC(todayDate.getFullYear(), todayDate.getMonth(), todayDate.getDate()) / 1000;
    var todayB = Date.UTC(todayDate.getFullYear(), todayDate.getMonth(), todayDate.getDate()) / 1000;

    console.log("Grabbing [day-by-date]: https://www.daysoftheyear.com/api/1.5/days/?date_start="
                + today +"&date_end=" + today + "&limit=100");

    $http({
      method: 'GET',
      url: "https://www.daysoftheyear.com/api/1.5/days/?date_start="
      + today +"&date_end=" + todayB + "&limit=100"
    })
    .success(function(data) {
      deferred.resolve(data);
    })
    .error(function () {
      deferred.reject('could not retrieve days (getDayToday)');
    });

    return deferred.promise;
  };

  fac.getDayByDate = function(options) {

    var deferred = $q.defer();

    var startDate = options.startDate;
    var endDate = options.endDate || startDate;
    var tagArray = options.tagArray || -1;

    var url = "https://www.daysoftheyear.com/api/1.5/days/?date_start="
    + startDate +"&date_end=" + endDate + "&limit=100";

    if (tagArray !== -1) {
      url = url + '&tags=' + tagArray.valueOf();
    }

    console.log("Grabbing [day-by-date]: " + url);

    $http({
      method: 'GET',
      url: url
    })
    .success(function(data) {
      deferred.resolve(data);
    })
    .error(function () {
      deferred.reject('could not retrieve days (getDayToday)');
    });

    return deferred.promise;
  };

  fac.getDayById = function(options) {
    var deferred = $q.defer();

    var url = "https://www.daysoftheyear.com/api/1.5/days?limit=100",
        idArray = options.idArray,
        startDate = options.startDate || -1,
        endDate = options.startDate || -1,
        idArrayLength = idArray.length;

//    options {'startDate': startDate, 'endDate': endDate, 'idArray': idArray}

    if (idArrayLength) {

      //      url = url + '&ids=' + idArray[0];
      //      for(var i = 1; i < idArrayLength; i++) {
      //        url = url + ',' + idArray[i];
      //      };

      url = url + '&ids=' + idArray.valueOf();

      if (startDate !== -1) {
        url = url + "&date_start=" + startDate;
      }

      if (endDate !== -1) {
        url = url + "&date_end=" + endDate;
      }

      console.log("grabbing [day-by-id]: " + url);

      $http({
        method: 'GET',
        url: url
      })
      .success(function (data) {
        deferred.resolve(data)
      })
      .error(function () {
        deferred.reject('could not retrieve day-id data');
      });
    } else {
      deferred.reject('no ids passed to getDayById!');
    }

    return deferred.promise;
  };

  fac.getDayByTag = function(options) {

    var tagArray = options.tagArray;
    var limit = options.limit || 10;
    var offset = options.offset || 0;

    var deferred = $q.defer();

    var url = "https://www.daysoftheyear.com/api/1.5/days?limit=" + limit;

    var tagArrayLength = tagArray.length;

    if (tagArrayLength) {
      url = url + '&tags=' + tagArray[0];
      for(var i = 1; i < tagArrayLength; i++) {
        url = url + ',' + tagArray[i];
      };

      console.log('Grabbing [day-by-tag]: ' + url);

      $http({
        method: 'GET',
        url: url
      })
      .success(function (data) {
        deferred.resolve(data)
      })
      .error(function () {
        deferred.reject('could not retrieve days by tag data');
      });
    }  else {
      deferred.reject('no tags passed to getDayByTag!');
    }

    return deferred.promise;
  };

  fac.getDayBySearch = function (query, offset) {
    var deferred = $q.defer();

    var limit = 10; // Temporary. This function should grab days in the near future. Need to figure out if the API returns date sorted content.
    var offset = offset || 0;
    var url = "https://www.daysoftheyear.com/api/1.5/days/?limit=" + limit + '&s=' + query + '&offset=' + offset;

    console.log('Grabbing [day-by-search]: ' + url);

    $http({
      method: 'GET',
      url: url
    })
    .success(function (data) {
      deferred.resolve(data);
    })
    .error(function () {
      deferred.reject('could not retrieve days by search query');
    });

    return deferred.promise;
  };

  fac.getTags = function() {
    var deferred = $q.defer();

    $http({
      method: 'GET',
      url: "https://www.daysoftheyear.com/api/1.5/tags"
    })
    .success(function (data) {
      deferred.resolve(data)
    })
    .error(function () {
      deferred.reject('could not retrieve tags');
    });

    return deferred.promise;
  };

  // Clean Title and Content
  fac.cleanDay = function(daysArray) {
    var deferred = $q.defer();

    $.each(daysArray, function (index, _dayObj) {
      //      _dayObj.title = _dayObj.title
      //      .replace("’","'")
      //      .replace("&","&")
      //      .replace("é","é");

      _dayObj.tag = {};
      _dayObj.tagArray = [];
      $.each(_dayObj.tags, function (_tagIndex, _tagValue) {
        _dayObj.tags[_tagIndex].name = _dayObj.tags[_tagIndex].name
        .replace("&","&");

        if (_dayObj.tags[_tagIndex].level === 0) {
          _dayObj.tag = {
            name: _dayObj.tags[_tagIndex].name,
            slug: _dayObj.tags[_tagIndex].slug
          };
        }

        _dayObj.tagArray.push(_dayObj.tags[_tagIndex].slug);
      });

      var currentTime = new Date().getTime() / 1000;
      var timeDiff = 0;
      var timeIndex = -1;

      $.each(_dayObj.dates, function (_dateIndex, _dateValue) {
        var dateDiff = Math.abs(parseInt(_dayObj.dates[_dateIndex]) - currentTime);
        if (dateDiff < timeDiff || timeIndex === -1) {
          timeDiff = dateDiff;
          timeIndex = _dateIndex;
        }
      });

      _dayObj.date = new Date(parseInt(_dayObj.dates[timeIndex]) * 1000);

      if ($rootScope.userData.pc_days.indexOf(_dayObj.id.toString()) !== -1) {
        _dayObj.bookmarked = true;
      } else {_dayObj.bookmarked = false;}

      _dayObj.content = "
" + _dayObj.content + "
"
      _dayObj.content = _dayObj.content
      .replace(/
/g, "
")
      .replace(/
/g, "
")
      .replace(/
/g, "
")
      .replace(/<\/h3>/gi, "
")
      .replace(/
/g, "
")
      .replace(/<\/h2>/gi, "
");
      //      .replace(//g, "")
      //      .replace(/<\/?a[^>]*>/g, "")
      //      .replace(/
/g, "
")
      //      .replace(/<\/p>/gi, "
");
      //      console.log(_dayObj.content);
    });

    console.log("cleaned up these days", daysArray);
    deferred.resolve(daysArray);

    return deferred.promise;
  };

  fac.cleanCategory = function(categoryArray) {
    $.each(categoryArray, function (index, catObj) {
      catObj.name = catObj.name.replace("&","&");
      if(catObj.children.length) {
        $.each(catObj.children, function (index, subObj) {
          subObj.name = subObj.name.replace("&","&");
        });
      }
    });
    return categoryArray;
  };

  fac.setDayColors = function () {
    var colors = ["#ea493b", "#7fccbd", "#81c256", "#f6d24c",
                  "#9765b8", "#73a6db", "#9e4f64", "#e6b294"];

    var lightercolors = ["#EE6D62", "#99D6CA", "#9ACE78", "#F8DB70",
                         "#AC84C6", "#8FB8E2", "#B17283", "#EBC1A9"];

    var darkercolors = ["#bf544b", "#549f90", "#649543", "#aa964d",
                        "#70478b", "#4b6e93", "#743a4a", "#9f7258"];

    $timeout(function () {
      $(".card-title").each(function(i) {
        this.style.background = colors[i % 8];
      });

      $(".card-wrapper").each(function(i) {
        this.style.borderColor = colors[i % 8];
        this.style['box-shadow'] = '0px 2px 0px 0px' + darkercolors[i % 8];
        //        rgba(175, 136, 114, 1)'
      });

      $(".dayimage-container").each(function(i) {
        this.style['background-color'] = lightercolors[i % 8];
      });
    }, 0, false);

  };

  fac.setCategoryColors = function () {
    var colors = ["#ea493b", "#7fccbd", "#81c256", "#f6d24c",
                  "#9765b8", "#73a6db", "#9e4f64", "#e6b294"];

    $timeout(function () {
      $(".explore-category").each(function(i) {
        this.style.background = colors[i % 8];
      });
    }, 1);

  };

  return fac;
});
<|endoftext|>


<commit_before>var jsface = require("jsface"),
	color  = require("cli-color");

/**
 * @name Logger
 * @namespace
 * @classdef Logger class, used for all logging inside newman
 */
var Logger = jsface.Class({
	$singleton: true,
	/**
	 * Logger Method
	 * @param  {String} log Logs success.
	 * @memberOf Logger
	 */
	success: function(log) {
		process.stdout.write(color.green("✔ " + log));
	},
	/**
	 * Logger Method
	 * @param  {String} log Logs errors.
	 * @memberOf Logger
	 */
	error: function(log) {
		process.stdout.write(color.red("✗ " + log));
	},
	/**
	 * Logger Method
	 * @param  {String} log Logs notice messages.
	 * @memberOf Logger
	 */
	notice: function(log) {
		process.stdout.write(color.cyan(log));
	},
	/**
	 * Logger Method
	 * @param  {String} log Logs warning messages.
	 * @memberOf Logger
	 */
	warn: function(log) {
		process.stdout.write(color.yellow(log));
	},
	/**
	 * Logger Method
	 * @param  {String} log Logs normal messages.
	 * @memberOf Logger
	 */
	normal: function(log) {
		process.stdout.write(color.black(log));
	},
	/**
	 * Logger Method
	 * @param  {String} log Logs light grey messages.
	 * @memberOf Logger
	 */
	light: function(log) {
		process.stdout.write(color.xterm(245)(log));
	},
	/**
	 * Logger Method
	 * @param  {String} log Logs a node error in red
	 * @memberOf Logger
	 */
	throwError: function(msg) {
		var err = new Error(msg);
		process.stdout.write(color.red(err.message));
	}
});

module.exports = Logger;
<commit_msg>Super nab code :sad:<commit_after>var jsface = require("jsface"),
	color  = require("cli-color");

/**
 * @name Logger
 * @namespace
 * @classdef Logger class, used for all logging inside newman
 */
var Logger = jsface.Class({
	$singleton: true,
	/**
	 * Logger Method
	 * @param  {String} log Logs success.
	 * @memberOf Logger
	 */
	success: function(log) {
		process.stdout.write(color.green("✔ " + log));
	},
	/**
	 * Logger Method
	 * @param  {String} log Logs errors.
	 * @memberOf Logger
	 */
	error: function(log) {
		process.stdout.write(color.red("✗ " + log));
	},
	/**
	 * Logger Method
	 * @param  {String} log Logs notice messages.
	 * @memberOf Logger
	 */
	notice: function(log) {
		process.stdout.write(color.cyan(log));
	},
	/**
	 * Logger Method
	 * @param  {String} log Logs warning messages.
	 * @memberOf Logger
	 */
	warn: function(log) {
		process.stdout.write(color.yellow(log));
	},
	/**
	 * Logger Method
	 * @param  {String} log Logs normal messages.
	 * @memberOf Logger
	 */
	normal: function(log) {
		process.stdout.write(color.black(log));
	},
	/**
	 * Logger Method
	 * @param  {String} log Logs light grey messages.
	 * @memberOf Logger
	 */
	light: function(log) {
		process.stdout.write(color.xterm(245)(log));
	},
	/**
	 * Logger Method
	 * @param  {String} log Logs a node error in red
	 * @memberOf Logger
	 */
	throwError: function(msg) {
		var err = new Error(msg);
		process.stdout.write(color.red(err.message));
		throw err;
	}
});

module.exports = Logger;
<|endoftext|>


<commit_before>import { warn } from 'core/util/index'
import { patch } from './patch'
import { mountComponent } from 'core/instance/lifecycle'
import { compileToFunctions } from '../compiler/index'
import { mustUseProp, isReservedTag, isUnknownElement } from '../util/index'
import { registerElement, getElementMap } from '../element-registry'

import Vue from 'core/index'
import DocumentNode from '../renderer/DocumentNode'
import platformDirectives from './directives/index'

Vue.config.mustUseProp = mustUseProp
Vue.config.isReservedTag = isReservedTag
Vue.config.isUnknownElement = isUnknownElement

Vue.$document = Vue.prototype.$document = new DocumentNode()

Vue.compile = compileToFunctions
Vue.registerElement = registerElement

Object.assign(Vue.options.directives, platformDirectives)

Vue.prototype.__patch__ = patch

Vue.prototype.$mount = function(el, hydrating) {
  const options = this.$options
  // resolve template/el and convert to render function
  if (!options.render) {
    let template = options.template
    if (template && typeof template !== 'string') {
      warn('invalid template option: ' + template, this)
      return this
    }

    if (template) {
      const { render, staticRenderFns } = compileToFunctions(
        template,
        {
          delimiters: options.delimiters,
          comments: options.comments
        },
        this
      )
      options.render = render
      options.staticRenderFns = staticRenderFns
    }
  }

  return mountComponent(this, el, hydrating)
}

Vue.prototype.$start = function() {
  const application = require('tns-core-modules/application')
  let self = this
  const AppConstructor = Vue.extend(this.$options)

  // register NS components into Vue
  Object.values(getElementMap()).forEach(entry => {
    Vue.component(entry.meta.component.name, entry.meta.component)
  })

  application.on(application.launchEvent, args => {
    if (self.$el) {
      self.$destroy()
      self = new AppConstructor()
    }

    self.$mount()
    args.root = self.$el.nativeView
  })

  application.run()
}

// Define a `nativeView` getter in every NS vue instance
Object.defineProperty(Vue.prototype, 'nativeView', {
  get() {
    return this.$el.nativeView
  }
})

export default Vue
<commit_msg>fix: import `application` module (#512)<commit_after>// Ensure `application` module is loaded
// before overriding `global.__onLiveSyncCore`
import { run, on, launchEvent } from 'tns-core-modules/application'
import { warn } from 'core/util/index'
import { patch } from './patch'
import { mountComponent } from 'core/instance/lifecycle'
import { compileToFunctions } from '../compiler/index'
import { mustUseProp, isReservedTag, isUnknownElement } from '../util/index'
import { registerElement, getElementMap } from '../element-registry'

import Vue from 'core/index'
import DocumentNode from '../renderer/DocumentNode'
import platformDirectives from './directives/index'

Vue.config.mustUseProp = mustUseProp
Vue.config.isReservedTag = isReservedTag
Vue.config.isUnknownElement = isUnknownElement

Vue.$document = Vue.prototype.$document = new DocumentNode()

Vue.compile = compileToFunctions
Vue.registerElement = registerElement

Object.assign(Vue.options.directives, platformDirectives)

Vue.prototype.__patch__ = patch

Vue.prototype.$mount = function(el, hydrating) {
  const options = this.$options
  // resolve template/el and convert to render function
  if (!options.render) {
    let template = options.template
    if (template && typeof template !== 'string') {
      warn('invalid template option: ' + template, this)
      return this
    }

    if (template) {
      const { render, staticRenderFns } = compileToFunctions(
        template,
        {
          delimiters: options.delimiters,
          comments: options.comments
        },
        this
      )
      options.render = render
      options.staticRenderFns = staticRenderFns
    }
  }

  return mountComponent(this, el, hydrating)
}

Vue.prototype.$start = function() {
  let self = this
  const AppConstructor = Vue.extend(this.$options)

  // register NS components into Vue
  Object.values(getElementMap()).forEach(entry => {
    Vue.component(entry.meta.component.name, entry.meta.component)
  })

  on(launchEvent, args => {
    if (self.$el) {
      self.$destroy()
      self = new AppConstructor()
    }

    self.$mount()
    args.root = self.$el.nativeView
  })

  run()
}

// Define a `nativeView` getter in every NS vue instance
Object.defineProperty(Vue.prototype, 'nativeView', {
  get() {
    return this.$el.nativeView
  }
})

export default Vue
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule StatusBar
 * @flow
 */
'use strict';

const React = require('React');
const ColorPropType = require('ColorPropType');
const Platform = require('Platform');

const processColor = require('processColor');

const StatusBarManager = require('NativeModules').StatusBarManager;

export type StatusBarStyle = $Enum<{
  'default': string,
  'light-content': string,
}>;

export type StatusBarAnimation = $Enum<{
  'none': string,
  'fade': string,
  'slide': string,
}>;

type DefaultProps = {
  animated: boolean;
};

/**
 * Merges the prop stack with the default values.
 */
function mergePropsStack(propsStack: Array<Object>, defaultValues: Object): Object {
  return propsStack.reduce((prev, cur) => {
    for (let prop in cur) {
      if (cur[prop] != null) {
        prev[prop] = cur[prop];
      }
    }
    return prev;
  }, Object.assign({}, defaultValues));
}

/**
 * Returns an object to insert in the props stack from the props
 * and the transition/animation info.
 */
function createStackEntry(props: any): any {
  return {
    backgroundColor: props.backgroundColor != null ? {
      value: props.backgroundColor,
      animated: props.animated,
    } : null,
    barStyle: props.barStyle != null ? {
      value: props.barStyle,
      animated: props.animated,
    } : null,
    translucent: props.translucent,
    hidden: props.hidden != null ? {
      value: props.hidden,
      animated: props.animated,
      transition: props.showHideTransition,
    } : null,
    networkActivityIndicatorVisible: props.networkActivityIndicatorVisible,
  };
}

/**
 * Component to control the app status bar.
 *
 * ### Usage with Navigator
 *
 * It is possible to have multiple `StatusBar` components mounted at the same
 * time. The props will be merged in the order the `StatusBar` components were
 * mounted. One use case is to specify status bar styles per route using `Navigator`.
 *
 * ```
 *  <View>
 *    <StatusBar
 *      backgroundColor="blue"
 *      barStyle="light-content"
 *    />
 *    <Navigator
 *      initialRoute={{statusBarHidden: true}}
 *      renderScene={(route, navigator) =>
 *        <View>
 *          <StatusBar hidden={route.statusBarHidden} />
 *          ...
 *        </View>
 *      }
 *    />
 *  </View>
 * ```
 *
 * ### Imperative API
 *
 * For cases where using a component is not ideal, there is also an imperative
 * API exposed as static functions on the component. It is however not recommended
 * to use the static API and the compoment for the same prop because any value
 * set by the static API will get overriden by the one set by the component in
 * the next render.
 */
const StatusBar = React.createClass({
  statics: {
    _propsStack: [],
    _defaultProps: createStackEntry({
      animated: false,
      showHideTransition: 'fade',
      backgroundColor: 'black',
      barStyle: 'default',
      translucent: false,
      hidden: false,
      networkActivityIndicatorVisible: false,
    }),
    // Timer for updating the native module values at the end of the frame.
    _updateImmediate: null,
    // The current merged values from the props stack.
    _currentValues: null,

    // TODO(janic): Provide a real API to deal with status bar height. See the
    // discussion in #6195.
    /**
     * The current height of the status bar on the device.
     *
     * @platform android
     */
    currentHeight: StatusBarManager.HEIGHT,

    // Provide an imperative API as static functions of the component.
    // See the corresponding prop for more detail.
    setHidden(hidden: boolean, animation?: StatusBarAnimation) {
      animation = animation || 'none';
      StatusBar._defaultProps.hidden.value = hidden;
      if (Platform.OS === 'ios') {
        StatusBarManager.setHidden(hidden, animation);
      } else if (Platform.OS === 'android') {
        StatusBarManager.setHidden(hidden);
      }
    },

    setBarStyle(style: StatusBarStyle, animated?: boolean) {
      if (Platform.OS !== 'ios') {
        console.warn('`setBarStyle` is only available on iOS');
        return;
      }
      animated = animated || false;
      StatusBar._defaultProps.barStyle.value = style;
      StatusBarManager.setStyle(style, animated);
    },

    setNetworkActivityIndicatorVisible(visible: boolean) {
      if (Platform.OS !== 'ios') {
        console.warn('`setNetworkActivityIndicatorVisible` is only available on iOS');
        return;
      }
      StatusBar._defaultProps.networkActivityIndicatorVisible = visible;
      StatusBarManager.setNetworkActivityIndicatorVisible(visible);
    },

    setBackgroundColor(color, animated?: boolean) {
      if (Platform.OS !== 'android') {
        console.warn('`setBackgroundColor` is only available on Android');
        return;
      }
      animated = animated || false;
      StatusBar._defaultProps.backgroundColor.value = color;
      StatusBarManager.setColor(processColor(color), animated);
    },

    setTranslucent(translucent: boolean) {
      if (Platform.OS !== 'android') {
        console.warn('`setTranslucent` is only available on Android');
        return;
      }
      StatusBar._defaultProps.translucent = translucent;
      StatusBarManager.setTranslucent(translucent);
    },
  },

  propTypes: {
    /**
     * If the status bar is hidden.
     */
    hidden: React.PropTypes.bool,
    /**
     * If the transition between status bar property changes should be animated.
     * Supported for backgroundColor, barStyle and hidden.
     */
    animated: React.PropTypes.bool,
    /**
     * The background color of the status bar.
     * @platform android
     */
    backgroundColor: ColorPropType,
    /**
     * If the status bar is translucent.
     * When translucent is set to true, the app will draw under the status bar.
     * This is useful when using a semi transparent status bar color.
     *
     * @platform android
     */
    translucent: React.PropTypes.bool,
    /**
     * Sets the color of the status bar text.
     *
     * @platform ios
     */
    barStyle: React.PropTypes.oneOf([
      'default',
      'light-content',
    ]),
    /**
     * If the network activity indicator should be visible.
     *
     * @platform ios
     */
    networkActivityIndicatorVisible: React.PropTypes.bool,
    /**
     * The transition effect when showing and hiding the status bar using the `hidden`
     * prop. Defaults to 'fade'.
     *
     * @platform ios
     */
    showHideTransition: React.PropTypes.oneOf([
      'fade',
      'slide',
    ]),
  },

  getDefaultProps(): DefaultProps {
    return {
      animated: false,
      showHideTransition: 'fade',
    };
  },

  _stackEntry: null,

  componentDidMount() {
    // Every time a StatusBar component is mounted, we push it's prop to a stack
    // and always update the native status bar with the props from the top of then
    // stack. This allows having multiple StatusBar components and the one that is
    // added last or is deeper in the view hierachy will have priority.
    this._stackEntry = createStackEntry(this.props);
    StatusBar._propsStack.push(this._stackEntry);
    this._updatePropsStack();
  },

  componentWillUnmount() {
    // When a StatusBar is unmounted, remove itself from the stack and update
    // the native bar with the next props.
    const index = StatusBar._propsStack.indexOf(this._stackEntry);
    StatusBar._propsStack.splice(index, 1);

    this._updatePropsStack();
  },

  componentDidUpdate() {
    const index = StatusBar._propsStack.indexOf(this._stackEntry);
    this._stackEntry = createStackEntry(this.props);
    StatusBar._propsStack[index] = this._stackEntry;

    this._updatePropsStack();
  },

  /**
   * Updates the native status bar with the props from the stack.
   */
  _updatePropsStack() {
    // Send the update to the native module only once at the end of the frame.
    clearImmediate(StatusBar._updateImmediate);
    StatusBar._updateImmediate = setImmediate(() => {
      const oldProps = StatusBar._currentValues;
      const mergedProps = mergePropsStack(StatusBar._propsStack, StatusBar._defaultProps);

      // Update the props that have changed using the merged values from the props stack.
      if (Platform.OS === 'ios') {
        if (!oldProps || oldProps.barStyle.value !== mergedProps.barStyle.value) {
          StatusBarManager.setStyle(
            mergedProps.barStyle.value,
            mergedProps.barStyle.animated,
          );
        }
        if (!oldProps || oldProps.hidden.value !== mergedProps.hidden.value) {
          StatusBarManager.setHidden(
            mergedProps.hidden.value,
            mergedProps.hidden.animated ?
              mergedProps.hidden.transition :
              'none',
          );
        }

        if (!oldProps || oldProps.networkActivityIndicatorVisible !== mergedProps.networkActivityIndicatorVisible) {
          StatusBarManager.setNetworkActivityIndicatorVisible(
            mergedProps.networkActivityIndicatorVisible
          );
        }
      } else if (Platform.OS === 'android') {
        if (!oldProps || oldProps.backgroundColor.value !== mergedProps.backgroundColor.value) {
          StatusBarManager.setColor(
            processColor(mergedProps.backgroundColor.value),
            mergedProps.backgroundColor.animated,
          );
        }
        if (!oldProps || oldProps.hidden.value !== mergedProps.hidden.value) {
          StatusBarManager.setHidden(mergedProps.hidden.value);
        }
        if (!oldProps || oldProps.translucent !== mergedProps.translucent) {
          StatusBarManager.setTranslucent(mergedProps.translucent);
        }
      }
      // Update the current prop values.
      StatusBar._currentValues = mergedProps;
    });
  },

  render(): ?ReactElement {
    return null;
  },
});

module.exports = StatusBar;
<commit_msg>Fix minor typo in Imperative API notes<commit_after>/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule StatusBar
 * @flow
 */
'use strict';

const React = require('React');
const ColorPropType = require('ColorPropType');
const Platform = require('Platform');

const processColor = require('processColor');

const StatusBarManager = require('NativeModules').StatusBarManager;

export type StatusBarStyle = $Enum<{
  'default': string,
  'light-content': string,
}>;

export type StatusBarAnimation = $Enum<{
  'none': string,
  'fade': string,
  'slide': string,
}>;

type DefaultProps = {
  animated: boolean;
};

/**
 * Merges the prop stack with the default values.
 */
function mergePropsStack(propsStack: Array<Object>, defaultValues: Object): Object {
  return propsStack.reduce((prev, cur) => {
    for (let prop in cur) {
      if (cur[prop] != null) {
        prev[prop] = cur[prop];
      }
    }
    return prev;
  }, Object.assign({}, defaultValues));
}

/**
 * Returns an object to insert in the props stack from the props
 * and the transition/animation info.
 */
function createStackEntry(props: any): any {
  return {
    backgroundColor: props.backgroundColor != null ? {
      value: props.backgroundColor,
      animated: props.animated,
    } : null,
    barStyle: props.barStyle != null ? {
      value: props.barStyle,
      animated: props.animated,
    } : null,
    translucent: props.translucent,
    hidden: props.hidden != null ? {
      value: props.hidden,
      animated: props.animated,
      transition: props.showHideTransition,
    } : null,
    networkActivityIndicatorVisible: props.networkActivityIndicatorVisible,
  };
}

/**
 * Component to control the app status bar.
 *
 * ### Usage with Navigator
 *
 * It is possible to have multiple `StatusBar` components mounted at the same
 * time. The props will be merged in the order the `StatusBar` components were
 * mounted. One use case is to specify status bar styles per route using `Navigator`.
 *
 * ```
 *  <View>
 *    <StatusBar
 *      backgroundColor="blue"
 *      barStyle="light-content"
 *    />
 *    <Navigator
 *      initialRoute={{statusBarHidden: true}}
 *      renderScene={(route, navigator) =>
 *        <View>
 *          <StatusBar hidden={route.statusBarHidden} />
 *          ...
 *        </View>
 *      }
 *    />
 *  </View>
 * ```
 *
 * ### Imperative API
 *
 * For cases where using a component is not ideal, there is also an imperative
 * API exposed as static functions on the component. It is however not recommended
 * to use the static API and the component for the same prop because any value
 * set by the static API will get overriden by the one set by the component in
 * the next render.
 */
const StatusBar = React.createClass({
  statics: {
    _propsStack: [],
    _defaultProps: createStackEntry({
      animated: false,
      showHideTransition: 'fade',
      backgroundColor: 'black',
      barStyle: 'default',
      translucent: false,
      hidden: false,
      networkActivityIndicatorVisible: false,
    }),
    // Timer for updating the native module values at the end of the frame.
    _updateImmediate: null,
    // The current merged values from the props stack.
    _currentValues: null,

    // TODO(janic): Provide a real API to deal with status bar height. See the
    // discussion in #6195.
    /**
     * The current height of the status bar on the device.
     *
     * @platform android
     */
    currentHeight: StatusBarManager.HEIGHT,

    // Provide an imperative API as static functions of the component.
    // See the corresponding prop for more detail.
    setHidden(hidden: boolean, animation?: StatusBarAnimation) {
      animation = animation || 'none';
      StatusBar._defaultProps.hidden.value = hidden;
      if (Platform.OS === 'ios') {
        StatusBarManager.setHidden(hidden, animation);
      } else if (Platform.OS === 'android') {
        StatusBarManager.setHidden(hidden);
      }
    },

    setBarStyle(style: StatusBarStyle, animated?: boolean) {
      if (Platform.OS !== 'ios') {
        console.warn('`setBarStyle` is only available on iOS');
        return;
      }
      animated = animated || false;
      StatusBar._defaultProps.barStyle.value = style;
      StatusBarManager.setStyle(style, animated);
    },

    setNetworkActivityIndicatorVisible(visible: boolean) {
      if (Platform.OS !== 'ios') {
        console.warn('`setNetworkActivityIndicatorVisible` is only available on iOS');
        return;
      }
      StatusBar._defaultProps.networkActivityIndicatorVisible = visible;
      StatusBarManager.setNetworkActivityIndicatorVisible(visible);
    },

    setBackgroundColor(color, animated?: boolean) {
      if (Platform.OS !== 'android') {
        console.warn('`setBackgroundColor` is only available on Android');
        return;
      }
      animated = animated || false;
      StatusBar._defaultProps.backgroundColor.value = color;
      StatusBarManager.setColor(processColor(color), animated);
    },

    setTranslucent(translucent: boolean) {
      if (Platform.OS !== 'android') {
        console.warn('`setTranslucent` is only available on Android');
        return;
      }
      StatusBar._defaultProps.translucent = translucent;
      StatusBarManager.setTranslucent(translucent);
    },
  },

  propTypes: {
    /**
     * If the status bar is hidden.
     */
    hidden: React.PropTypes.bool,
    /**
     * If the transition between status bar property changes should be animated.
     * Supported for backgroundColor, barStyle and hidden.
     */
    animated: React.PropTypes.bool,
    /**
     * The background color of the status bar.
     * @platform android
     */
    backgroundColor: ColorPropType,
    /**
     * If the status bar is translucent.
     * When translucent is set to true, the app will draw under the status bar.
     * This is useful when using a semi transparent status bar color.
     *
     * @platform android
     */
    translucent: React.PropTypes.bool,
    /**
     * Sets the color of the status bar text.
     *
     * @platform ios
     */
    barStyle: React.PropTypes.oneOf([
      'default',
      'light-content',
    ]),
    /**
     * If the network activity indicator should be visible.
     *
     * @platform ios
     */
    networkActivityIndicatorVisible: React.PropTypes.bool,
    /**
     * The transition effect when showing and hiding the status bar using the `hidden`
     * prop. Defaults to 'fade'.
     *
     * @platform ios
     */
    showHideTransition: React.PropTypes.oneOf([
      'fade',
      'slide',
    ]),
  },

  getDefaultProps(): DefaultProps {
    return {
      animated: false,
      showHideTransition: 'fade',
    };
  },

  _stackEntry: null,

  componentDidMount() {
    // Every time a StatusBar component is mounted, we push it's prop to a stack
    // and always update the native status bar with the props from the top of then
    // stack. This allows having multiple StatusBar components and the one that is
    // added last or is deeper in the view hierachy will have priority.
    this._stackEntry = createStackEntry(this.props);
    StatusBar._propsStack.push(this._stackEntry);
    this._updatePropsStack();
  },

  componentWillUnmount() {
    // When a StatusBar is unmounted, remove itself from the stack and update
    // the native bar with the next props.
    const index = StatusBar._propsStack.indexOf(this._stackEntry);
    StatusBar._propsStack.splice(index, 1);

    this._updatePropsStack();
  },

  componentDidUpdate() {
    const index = StatusBar._propsStack.indexOf(this._stackEntry);
    this._stackEntry = createStackEntry(this.props);
    StatusBar._propsStack[index] = this._stackEntry;

    this._updatePropsStack();
  },

  /**
   * Updates the native status bar with the props from the stack.
   */
  _updatePropsStack() {
    // Send the update to the native module only once at the end of the frame.
    clearImmediate(StatusBar._updateImmediate);
    StatusBar._updateImmediate = setImmediate(() => {
      const oldProps = StatusBar._currentValues;
      const mergedProps = mergePropsStack(StatusBar._propsStack, StatusBar._defaultProps);

      // Update the props that have changed using the merged values from the props stack.
      if (Platform.OS === 'ios') {
        if (!oldProps || oldProps.barStyle.value !== mergedProps.barStyle.value) {
          StatusBarManager.setStyle(
            mergedProps.barStyle.value,
            mergedProps.barStyle.animated,
          );
        }
        if (!oldProps || oldProps.hidden.value !== mergedProps.hidden.value) {
          StatusBarManager.setHidden(
            mergedProps.hidden.value,
            mergedProps.hidden.animated ?
              mergedProps.hidden.transition :
              'none',
          );
        }

        if (!oldProps || oldProps.networkActivityIndicatorVisible !== mergedProps.networkActivityIndicatorVisible) {
          StatusBarManager.setNetworkActivityIndicatorVisible(
            mergedProps.networkActivityIndicatorVisible
          );
        }
      } else if (Platform.OS === 'android') {
        if (!oldProps || oldProps.backgroundColor.value !== mergedProps.backgroundColor.value) {
          StatusBarManager.setColor(
            processColor(mergedProps.backgroundColor.value),
            mergedProps.backgroundColor.animated,
          );
        }
        if (!oldProps || oldProps.hidden.value !== mergedProps.hidden.value) {
          StatusBarManager.setHidden(mergedProps.hidden.value);
        }
        if (!oldProps || oldProps.translucent !== mergedProps.translucent) {
          StatusBarManager.setTranslucent(mergedProps.translucent);
        }
      }
      // Update the current prop values.
      StatusBar._currentValues = mergedProps;
    });
  },

  render(): ?ReactElement {
    return null;
  },
});

module.exports = StatusBar;
<|endoftext|>