<commit_before>/* @flow weak */

/**
 * OfflineMobile Android
 * Sustainable Solutions (NZ) Ltd. 2016
 */

import React from 'react';
import {
  Dimensions,
  StyleSheet,
  TouchableOpacity,
  View,
} from 'react-native';
import Icon from 'react-native-vector-icons/Ionicons';

import { BottomModal } from './BottomModal';
import
{
  DARK_GREY,
  PAGE_CONTENT_PADDING_HORIZONTAL,
} from '../../globalStyles';

/**
 * A modal that can be displayed over the page content container, rendering any children
 * about two thirds of the way up, and a cross in the top right to close
 * @prop {boolean}    isOpen    Whether the modal is open
 * @prop {function}   onClose   A function to call if the close x is pressed
 * @prop {element}    children  The components to render within the modal
 */
export class PageContentModal extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      queryText: '',
    };
  }

  render() {
    const {
      onClose,
      ...modalProps,
    } = this.props;

    return (
      <BottomModal {...modalProps}
        style={localStyles.modal}
      >
        <TouchableOpacity onPress={onClose} style={localStyles.closeButton}>
          <Icon name="md-close" style={localStyles.closeIcon} />
        </TouchableOpacity>
        <View style={localStyles.childrenContainer}>
          {this.props.children}
        </View>
      </BottomModal>
     );
  }
}

PageContentModal.propTypes = {
  children: React.PropTypes.element,
  isOpen: React.PropTypes.bool.isRequired,
  onClose: React.PropTypes.func,
};
PageContentModal.defaultProps = {
  style: {},
  swipeToClose: false, // negating the default.
  backdropPressToClose: false, // negating the default.
  position: 'bottom',
  backdrop: false,
};

const localStyles = StyleSheet.create({
  modal: {
    height: Dimensions.get('window').height,
    width: Dimensions.get('window').width - 2 * PAGE_CONTENT_PADDING_HORIZONTAL,
    alignSelf: 'center',
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: DARK_GREY,
    opacity: 0.96,
  },
  childrenContainer: {
    flex: 1,
    position: 'absolute', // Otherwise it moves depending on size of autocomplete results
    top: 170,
    left: 0,
    right: 0,
  },
  closeButton: {
    position: 'absolute',
    top: 10,
    right: 20,
  },
  closeIcon: {
    fontSize: 36,
    color: 'white',
  },
});
<commit_msg>Position page modal content more nicely<commit_after>/* @flow weak */

/**
 * OfflineMobile Android
 * Sustainable Solutions (NZ) Ltd. 2016
 */

import React from 'react';
import {
  Dimensions,
  StyleSheet,
  TouchableOpacity,
  View,
} from 'react-native';
import Icon from 'react-native-vector-icons/Ionicons';

import { BottomModal } from './BottomModal';
import
{
  DARK_GREY,
  PAGE_CONTENT_PADDING_HORIZONTAL,
} from '../../globalStyles';

/**
 * A modal that can be displayed over the page content container, rendering any children
 * about two thirds of the way up, and a cross in the top right to close
 * @prop {boolean}    isOpen    Whether the modal is open
 * @prop {function}   onClose   A function to call if the close x is pressed
 * @prop {element}    children  The components to render within the modal
 */
export class PageContentModal extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      queryText: '',
    };
  }

  render() {
    const {
      onClose,
      ...modalProps,
    } = this.props;

    return (
      <BottomModal {...modalProps}
        style={localStyles.modal}
      >
        <TouchableOpacity onPress={onClose} style={localStyles.closeButton}>
          <Icon name="md-close" style={localStyles.closeIcon} />
        </TouchableOpacity>
        <View style={localStyles.childrenContainer}>
          {this.props.children}
        </View>
      </BottomModal>
     );
  }
}

PageContentModal.propTypes = {
  children: React.PropTypes.element,
  isOpen: React.PropTypes.bool.isRequired,
  onClose: React.PropTypes.func,
};
PageContentModal.defaultProps = {
  style: {},
  swipeToClose: false, // negating the default.
  backdropPressToClose: false, // negating the default.
  position: 'bottom',
  backdrop: false,
};

const localStyles = StyleSheet.create({
  modal: {
    height: Dimensions.get('window').height,
    width: Dimensions.get('window').width - 2 * PAGE_CONTENT_PADDING_HORIZONTAL,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: DARK_GREY,
    opacity: 0.88,
  },
  childrenContainer: {
    flex: 1,
    position: 'absolute', // Otherwise it moves depending on size of autocomplete results
    top: 170,
    left: PAGE_CONTENT_PADDING_HORIZONTAL,
    right: PAGE_CONTENT_PADDING_HORIZONTAL - 7, // TODO get rid of -7
  },
  closeButton: {
    position: 'absolute',
    top: 10,
    right: 20,
  },
  closeIcon: {
    fontSize: 36,
    color: 'white',
  },
});
<|endoftext|>


<commit_before>var _manifest;
var _manifestError;
var _offlineView;
var _mainView;
var _zIndex = 10000;
var _enableOfflineSupport = true;
var _lastKnownLocation;
var _lastKnownLocationFailed = false;
var _whiteList = [];

function bridgeNativeEvent(e) {
    _mainView.invokeScriptAsync('eval', "cordova.fireDocumentEvent('" + e.type + "', null, true);").start();
}

//document.addEventListener('backbutton', bridgeNativeEvent, false);
//document.addEventListener('pause', bridgeNativeEvent, false);
document.addEventListener('resume', bridgeNativeEvent, false);

WinJS.Application.addEventListener("checkpoint", function (args) {
    var promise = new WinJS.Promise(function (complete, error) {
        var asyncOp = _mainView.invokeScriptAsync('eval', "(function () {cordova.fireDocumentEvent('pause', null, true);})();");
        asyncOp.oncomplete = function (evt) { complete(); };
        asyncOp.onerror = function (err) { error(err); };
        asyncOp.start();
    });

    args.setPromise(promise);
});

// creates a webview to host content
function configureHost(url, zOrder, display) {
    var webView = document.createElement(cordova.platformId === 'windows8' ? 'iframe' : 'x-ms-webview');
    var style = webView.style;
    style.position = 'absolute';
    style.top = 0;
    style.left = 0;
    style.zIndex = zOrder;
    style.width = '100%';
    style.height = '100%';
    if (display) {
        style.display = display;
    }

    if (url) {
        webView.src = url;
    }

    webView.addEventListener("MSWebViewNavigationCompleted", navigationCompletedEvent, false);
    webView.addEventListener("MSWebViewNavigationStarting", navigationStartingEvent, false);

    document.body.appendChild(webView);

    return webView;
}

// handles webview's navigation starting event
function navigationStartingEvent(evt) {
    if (handleCordovaExecCalls(evt)) {
        evt.stopImmediatePropagation();
        evt.preventDefault();
        return;
    }

    if (evt.uri && evt.uri !== "") {
        var isInWhitelist = false;
        for (var i = 0; i < _whiteList.length; i++) {
            var rule = _whiteList[i];
            if (rule.test(evt.uri)) {
                isInWhitelist = true;
                break;
            }
        }

        // if the url to navigate to does not match any of the rules in the whitelist, open it outside de app
        if (!isInWhitelist) {
            evt.stopImmediatePropagation();
            evt.preventDefault();
            console.log("Whitelist rejection: url='" + evt.uri + "'");
            Windows.System.Launcher.launchUriAsync(new Windows.Foundation.Uri(evt.uri));
        }
    }
}

// handles webview's navigation completed event
function navigationCompletedEvent(evt) {
    if (evt.uri && evt.uri !== "") {
        if (evt.isSuccess) {
            _lastKnownLocationFailed = false;
            if (_offlineView) {
                _offlineView.style.display = 'none';
            }
        } else {
            _lastKnownLocationFailed = true;
        }

        _lastKnownLocation = evt.uri;
    }
}

function domContentLoadedEvent(evt) {
    hideExtendedSplashScreen();

    // inject Cordova
    if (_manifest && _manifest.mjs_cordova) {
        var pluginMode = _manifest.mjs_cordova.pluginMode || 'client';
        var cordovaBaseUrl = (_manifest.mjs_cordova.baseUrl || '').trim();
        if (cordovaBaseUrl.indexOf('/', cordovaBaseUrl.length - 1) === -1) {
            cordovaBaseUrl += '/';
        }

        _mainView.invokeScriptAsync('eval', 'window.hostedWebApp = { \'platform\': \'windows\', \'pluginMode\': \'' + pluginMode + '\', \'cordovaBaseUrl\': \'' + cordovaBaseUrl + '\'};').start();

        var scriptsToInject = [];
        if (pluginMode === 'client') {
            scriptsToInject.push('cordova.js');
        }

        scriptsToInject.push('hostedapp-bridge.js');
        injectScripts(scriptsToInject);
    }

    // inject custom scripts
    if (_manifest && _manifest.mjs_custom_scripts && _manifest.mjs_custom_scripts instanceof Array) {
        var scriptFiles = _manifest.mjs_custom_scripts.filter(function (item) {

            // ensure script applies to current platform
            if (item.platform && item.platform.split(';')
                .map(function (item) { return item.trim(); })
                .indexOf('windows') < 0) {
                return false;
            }

            // ensure script applies to current page
            var match = item.match;
            if (match) {
                if (typeof match === 'string' && match.length) {
                    match = [match];
                }

                return match.some(function (item) { return convertPatternToRegex(item).test(_mainView.src); });
            }

            return true;
        }).map(function (item) {
            return item.source;
        });

        if (scriptFiles.length) {
            injectScripts(scriptFiles);
        }
    }
}

// handles network connectivity change events
function connectivityEvent(evt) {
    console.log('Received a network connectivity change notification. The device is currently ' + evt.type + '.');
    if (_enableOfflineSupport) {
        if (evt.type === 'offline') {
            _offlineView.style.display = 'block';
        } else if (evt.type === 'online') {
            if (_lastKnownLocationFailed) {
                if (_lastKnownLocation) {
                    console.log("Reload last known location: '" + _lastKnownLocation + "'");
                    _mainView.src = _lastKnownLocation;
                }
            } else {
                _offlineView.style.display = 'none';
            }
        }
    }
}

// sets up a secondary webview to host the offline page
function configureOfflineSupport(offlinePage) {
    var offlinePageUrl = '///www/' + offlinePage;
    var url = new Windows.Foundation.Uri('ms-appx:' + offlinePageUrl);
    Windows.Storage.StorageFile.getFileFromApplicationUriAsync(url).then(
        function (file) {
            _offlineView = configureHost('ms-appx-web:' + offlinePageUrl, 10001, 'none');
        },
        function (err) {
            var message = 'It looks like you are offline. Please reconnect to use this application.';
            var offlinePageTemplate = '
' + message + '
';
            _offlineView = configureHost(null, _zIndex + 1, 'none');

            if (cordova.platformId === 'windows8') {
                _offlineView.style.backgroundColor = 'white';
                _offlineView.contentDocument.write(offlinePageTemplate);
            } else {
                _offlineView.navigateToString(offlinePageTemplate);
            }
        }).done(function () {
            document.addEventListener('offline', connectivityEvent, false);
            document.addEventListener('online', connectivityEvent, false);
        });
}

// escapes regular expression reserved symbols
function escapeRegex(str) {
    return ("" + str).replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
}

// converts a string pattern to a regular expression
function convertPatternToRegex(pattern, excludeLineStart, excludeLineEnd) {
    var isNot = (pattern[0] == '!');
    if (isNot) { pattern = pattern.substr(1) };

    var regexBody = escapeRegex(pattern);

    excludeLineStart = !!excludeLineStart;
    excludeLineEnd = !!excludeLineEnd;

    regexBody = regexBody.replace(/\\\?/g, ".?").replace(/\\\*/g, ".*?");
    if (isNot) { regexBody = "((?!" + regexBody + ").)*"; }
    if (!excludeLineStart) { regexBody = "^" + regexBody; }
    if (!excludeLineEnd) { regexBody += "\/?$"; }

    return new RegExp(regexBody);
}

// initializes an array of the access rules defined in the manifest
function configureWhiteList(manifest) {
    if (manifest) {
        // Add base access rule based on the start_url and the scope
        var baseUrlPattern = new Windows.Foundation.Uri(manifest.start_url);
        if (manifest.scope && manifest.scope.length) {
            baseUrlPattern = baseUrlPattern.combineUri(manifest.scope);
        }

        baseUrlPattern = baseUrlPattern.combineUri('*');
        _whiteList.push(convertPatternToRegex(baseUrlPattern.absoluteUri));

        // add additional access rules
        if (manifest.mjs_access_whitelist && manifest.mjs_access_whitelist instanceof Array) {
            manifest.mjs_access_whitelist.forEach(function (rule) {
                _whiteList.push(convertPatternToRegex(rule.url));
            });
        }
    }
}

// hides the extended splash screen
function hideExtendedSplashScreen() {
    var extendedSplashScreen = document.getElementById("extendedSplashScreen");
    extendedSplashScreen.style.display = "none";
}

// handle the hardware backbutton
function navigateBack(e) {
    if (!_mainView.canGoBack) {
        return false;
    }

    try {
        _mainView.goBack();
    } catch (err) {
        return false;
    }

    return true;
}

var exec = require('cordova/exec');

function injectScripts(files, successCallback, errorCallback) {

    var script = (arguments.length > 3 && typeof arguments[3] === 'string') ? arguments[3] : '';
    var fileList = (arguments.length > 4 && typeof arguments[4] === 'string') ? arguments[4] : '';

    if (typeof files === 'string') {
        files = files.length ? [files] : [];
    }

    var fileName = files.shift();
    if (!fileName) {
        var asyncOp = _mainView.invokeScriptAsync('eval', script);
        asyncOp.oncomplete = function () { successCallback && successCallback(true); };
        asyncOp.onerror = function (err) {
            console.log('Error injecting script file(s): ' + fileList + ' - ' + asyncOp.error);
            errorCallback && errorCallback(err);
        };

        asyncOp.start()
        return;
    }

    console.log('Injecting script file: ' + fileName);
    var uri = new Windows.Foundation.Uri('ms-appx:///www/', fileName);

    var onSuccess = function (content) {
        script += '\r\n/****** ' + fileName + ' *****/\r\n' + content;
        injectScripts(files, successCallback, errorCallback, script, (fileList ? ', ' : '') + fileName);
    };

    var onError = function (err) {
        console.log('Error retrieving script file from app package: ' + fileName + ' - ' + err);
        if (errorCallback) {
            errorCallback(err);
        }
    };

    if (uri.schemeName == 'ms-appx') {
        Windows.Storage.StorageFile.getFileFromApplicationUriAsync(uri)
            .done(function (file) {
                Windows.Storage.FileIO.readTextAsync(file)
                    .done(onSuccess, onError);
            }, onError);
    } else {
        var httpClient = new Windows.Web.Http.HttpClient();
        httpClient.getStringAsync(uri).done(onSuccess, onError);
        httpClient.close();
    }
}

function handleCordovaExecCalls(evt) {
    if (evt.uri) {
        var targetUri = new Windows.Foundation.Uri(evt.uri);
        if (targetUri.host === '.cordova' && targetUri.path === '/exec') {
            var service = targetUri.queryParsed.getFirstValueByName('service');
            var action = targetUri.queryParsed.getFirstValueByName('action');
            var args = JSON.parse(decodeURIComponent(targetUri.queryParsed.getFirstValueByName('args')));
            var callbackId = targetUri.queryParsed.getFirstValueByName('callbackId');

            var success, fail;
            if (callbackId !== '0') {
                success = function (args) {
                    var params = args ? '"' + encodeURIComponent(JSON.stringify(args)) + '"' : '';
                    var script = 'cordova.callbacks["' + callbackId + '"].success(' + params + ');';
                    _mainView.invokeScriptAsync('eval', script).start();
                };

                fail = function (err) {
                    var params = args ? '"' + encodeURIComponent(JSON.stringify(err)) + '"' : '';
                    var script = 'cordova.callbacks["' + callbackId + '"].fail(' + params + ');';
                    _mainView.invokeScriptAsync('eval', script).start();
                };
            }

            exec(success, fail, service, action, args);

            return true;
        }
    }

    return false;
}

module.exports = {
    // loads the W3C manifest file and parses it
    loadManifest: function (successCallback, errorCallback, args) {
        var manifestFileName = (args && args instanceof Array && args.length > 0) ? args[0] : 'manifest.json';
        var configFile = 'ms-appx:///www/' + manifestFileName;
        var uri = new Windows.Foundation.Uri(configFile);
        Windows.Storage.StorageFile.getFileFromApplicationUriAsync(uri).then(
            function (file) {
                Windows.Storage.FileIO.readTextAsync(file).then(function (data) {
                    try {
                        _manifest = JSON.parse(data);
                        cordova.fireDocumentEvent("manifestLoaded", { manifest: _manifest });
                        successCallback &&  successCallback(_manifest);
                    } catch (err) {
                        _manifestError = 'Error parsing manifest file: ' + manifestFileName + ' - ' + err.message;
                        console.log(_manifestError);
                    }
                });
            },
            function (err) {
                _manifestError = 'Error reading manifest file: ' + manifestFileName + ' - ' + err;
                console.log(_manifestError);
                errorCallback && errorCallback(err);
            });
    },

    // returns the currently loaded manifest
    getManifest: function (successCallback, errorCallback) {
        if (_manifest) {
            successCallback && successCallback(_manifest);
        } else {
            errorCallback && errorCallback(new Error(_manifestError));
        }
    },

    // enables offline page support
    enableOfflinePage: function (successCallback, errorCallback) {
        _enableOfflineSupport = true;
        successCallback && successCallback();
    },

    // disables offline page support
    disableOfflinePage: function (successCallback, errorCallback) {
        _enableOfflineSupport = false;
        successCallback && successCallback();
    },

    getWebView: function () {
      return _mainView;
    },

    injectPluginScript: function (successCallback, errorCallback, file) {
        injectScripts(file, successCallback, errorCallback);
    }
}; // exports

cordova.commandProxy.add('HostedWebApp', module.exports);

module.exports.loadManifest(
    function (manifest) {
        configureOfflineSupport('offline.html');
        configureWhiteList(manifest);
        _mainView = configureHost(manifest ? manifest.start_url : 'about:blank', _zIndex);
        _mainView.addEventListener("MSWebViewDOMContentLoaded", domContentLoadedEvent, false);

        cordova.fireDocumentEvent("webviewCreated", { webView: _mainView });
        WinJS.Application.onbackclick = navigateBack;
    });
<commit_msg>Fixed issue when bridging checkpoint event in Windows<commit_after>var _manifest;
var _manifestError;
var _offlineView;
var _mainView;
var _zIndex = 10000;
var _enableOfflineSupport = true;
var _lastKnownLocation;
var _lastKnownLocationFailed = false;
var _whiteList = [];

function bridgeNativeEvent(e) {
    _mainView.invokeScriptAsync('eval', "cordova && cordova.fireDocumentEvent('" + e.type + "', null, true);").start();
}

//document.addEventListener('backbutton', bridgeNativeEvent, false);
document.addEventListener('pause', bridgeNativeEvent, false);
document.addEventListener('resume', bridgeNativeEvent, false);

// creates a webview to host content
function configureHost(url, zOrder, display) {
    var webView = document.createElement(cordova.platformId === 'windows8' ? 'iframe' : 'x-ms-webview');
    var style = webView.style;
    style.position = 'absolute';
    style.top = 0;
    style.left = 0;
    style.zIndex = zOrder;
    style.width = '100%';
    style.height = '100%';
    if (display) {
        style.display = display;
    }

    if (url) {
        webView.src = url;
    }

    webView.addEventListener("MSWebViewNavigationCompleted", navigationCompletedEvent, false);
    webView.addEventListener("MSWebViewNavigationStarting", navigationStartingEvent, false);

    document.body.appendChild(webView);

    return webView;
}

// handles webview's navigation starting event
function navigationStartingEvent(evt) {
    if (handleCordovaExecCalls(evt)) {
        evt.stopImmediatePropagation();
        evt.preventDefault();
        return;
    }

    if (evt.uri && evt.uri !== "") {
        var isInWhitelist = false;
        for (var i = 0; i < _whiteList.length; i++) {
            var rule = _whiteList[i];
            if (rule.test(evt.uri)) {
                isInWhitelist = true;
                break;
            }
        }

        // if the url to navigate to does not match any of the rules in the whitelist, open it outside de app
        if (!isInWhitelist) {
            evt.stopImmediatePropagation();
            evt.preventDefault();
            console.log("Whitelist rejection: url='" + evt.uri + "'");
            Windows.System.Launcher.launchUriAsync(new Windows.Foundation.Uri(evt.uri));
        }
    }
}

// handles webview's navigation completed event
function navigationCompletedEvent(evt) {
    if (evt.uri && evt.uri !== "") {
        if (evt.isSuccess) {
            _lastKnownLocationFailed = false;
            if (_offlineView) {
                _offlineView.style.display = 'none';
            }
        } else {
            _lastKnownLocationFailed = true;
        }

        _lastKnownLocation = evt.uri;
    }
}

function domContentLoadedEvent(evt) {
    hideExtendedSplashScreen();

    // inject Cordova
    if (_manifest && _manifest.mjs_cordova) {
        var pluginMode = _manifest.mjs_cordova.pluginMode || 'client';
        var cordovaBaseUrl = (_manifest.mjs_cordova.baseUrl || '').trim();
        if (cordovaBaseUrl.indexOf('/', cordovaBaseUrl.length - 1) === -1) {
            cordovaBaseUrl += '/';
        }

        _mainView.invokeScriptAsync('eval', 'window.hostedWebApp = { \'platform\': \'windows\', \'pluginMode\': \'' + pluginMode + '\', \'cordovaBaseUrl\': \'' + cordovaBaseUrl + '\'};').start();

        var scriptsToInject = [];
        if (pluginMode === 'client') {
            scriptsToInject.push('cordova.js');
        }

        scriptsToInject.push('hostedapp-bridge.js');
        injectScripts(scriptsToInject);
    }

    // inject custom scripts
    if (_manifest && _manifest.mjs_custom_scripts && _manifest.mjs_custom_scripts instanceof Array) {
        var scriptFiles = _manifest.mjs_custom_scripts.filter(function (item) {

            // ensure script applies to current platform
            if (item.platform && item.platform.split(';')
                .map(function (item) { return item.trim(); })
                .indexOf('windows') < 0) {
                return false;
            }

            // ensure script applies to current page
            var match = item.match;
            if (match) {
                if (typeof match === 'string' && match.length) {
                    match = [match];
                }

                return match.some(function (item) { return convertPatternToRegex(item).test(_mainView.src); });
            }

            return true;
        }).map(function (item) {
            return item.source;
        });

        if (scriptFiles.length) {
            injectScripts(scriptFiles);
        }
    }
}

// handles network connectivity change events
function connectivityEvent(evt) {
    console.log('Received a network connectivity change notification. The device is currently ' + evt.type + '.');
    if (_enableOfflineSupport) {
        if (evt.type === 'offline') {
            _offlineView.style.display = 'block';
        } else if (evt.type === 'online') {
            if (_lastKnownLocationFailed) {
                if (_lastKnownLocation) {
                    console.log("Reload last known location: '" + _lastKnownLocation + "'");
                    _mainView.src = _lastKnownLocation;
                }
            } else {
                _offlineView.style.display = 'none';
            }
        }
    }
}

// sets up a secondary webview to host the offline page
function configureOfflineSupport(offlinePage) {
    var offlinePageUrl = '///www/' + offlinePage;
    var url = new Windows.Foundation.Uri('ms-appx:' + offlinePageUrl);
    Windows.Storage.StorageFile.getFileFromApplicationUriAsync(url).then(
        function (file) {
            _offlineView = configureHost('ms-appx-web:' + offlinePageUrl, 10001, 'none');
        },
        function (err) {
            var message = 'It looks like you are offline. Please reconnect to use this application.';
            var offlinePageTemplate = '
' + message + '
';
            _offlineView = configureHost(null, _zIndex + 1, 'none');

            if (cordova.platformId === 'windows8') {
                _offlineView.style.backgroundColor = 'white';
                _offlineView.contentDocument.write(offlinePageTemplate);
            } else {
                _offlineView.navigateToString(offlinePageTemplate);
            }
        }).done(function () {
            document.addEventListener('offline', connectivityEvent, false);
            document.addEventListener('online', connectivityEvent, false);
        });
}

// escapes regular expression reserved symbols
function escapeRegex(str) {
    return ("" + str).replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
}

// converts a string pattern to a regular expression
function convertPatternToRegex(pattern, excludeLineStart, excludeLineEnd) {
    var isNot = (pattern[0] == '!');
    if (isNot) { pattern = pattern.substr(1) };

    var regexBody = escapeRegex(pattern);

    excludeLineStart = !!excludeLineStart;
    excludeLineEnd = !!excludeLineEnd;

    regexBody = regexBody.replace(/\\\?/g, ".?").replace(/\\\*/g, ".*?");
    if (isNot) { regexBody = "((?!" + regexBody + ").)*"; }
    if (!excludeLineStart) { regexBody = "^" + regexBody; }
    if (!excludeLineEnd) { regexBody += "\/?$"; }

    return new RegExp(regexBody);
}

// initializes an array of the access rules defined in the manifest
function configureWhiteList(manifest) {
    if (manifest) {
        // Add base access rule based on the start_url and the scope
        var baseUrlPattern = new Windows.Foundation.Uri(manifest.start_url);
        if (manifest.scope && manifest.scope.length) {
            baseUrlPattern = baseUrlPattern.combineUri(manifest.scope);
        }

        baseUrlPattern = baseUrlPattern.combineUri('*');
        _whiteList.push(convertPatternToRegex(baseUrlPattern.absoluteUri));

        // add additional access rules
        if (manifest.mjs_access_whitelist && manifest.mjs_access_whitelist instanceof Array) {
            manifest.mjs_access_whitelist.forEach(function (rule) {
                _whiteList.push(convertPatternToRegex(rule.url));
            });
        }
    }
}

// hides the extended splash screen
function hideExtendedSplashScreen() {
    var extendedSplashScreen = document.getElementById("extendedSplashScreen");
    extendedSplashScreen.style.display = "none";
}

// handle the hardware backbutton
function navigateBack(e) {
    if (!_mainView.canGoBack) {
        return false;
    }

    try {
        _mainView.goBack();
    } catch (err) {
        return false;
    }

    return true;
}

var exec = require('cordova/exec');

function injectScripts(files, successCallback, errorCallback) {

    var script = (arguments.length > 3 && typeof arguments[3] === 'string') ? arguments[3] : '';
    var fileList = (arguments.length > 4 && typeof arguments[4] === 'string') ? arguments[4] : '';

    if (typeof files === 'string') {
        files = files.length ? [files] : [];
    }

    var fileName = files.shift();
    if (!fileName) {
        var asyncOp = _mainView.invokeScriptAsync('eval', script);
        asyncOp.oncomplete = function () { successCallback && successCallback(true); };
        asyncOp.onerror = function (err) {
            console.log('Error injecting script file(s): ' + fileList + ' - ' + asyncOp.error);
            errorCallback && errorCallback(err);
        };

        asyncOp.start()
        return;
    }

    console.log('Injecting script file: ' + fileName);
    var uri = new Windows.Foundation.Uri('ms-appx:///www/', fileName);

    var onSuccess = function (content) {
        script += '\r\n/****** ' + fileName + ' *****/\r\n' + content;
        injectScripts(files, successCallback, errorCallback, script, (fileList ? ', ' : '') + fileName);
    };

    var onError = function (err) {
        console.log('Error retrieving script file from app package: ' + fileName + ' - ' + err);
        if (errorCallback) {
            errorCallback(err);
        }
    };

    if (uri.schemeName == 'ms-appx') {
        Windows.Storage.StorageFile.getFileFromApplicationUriAsync(uri)
            .done(function (file) {
                Windows.Storage.FileIO.readTextAsync(file)
                    .done(onSuccess, onError);
            }, onError);
    } else {
        var httpClient = new Windows.Web.Http.HttpClient();
        httpClient.getStringAsync(uri).done(onSuccess, onError);
        httpClient.close();
    }
}

function handleCordovaExecCalls(evt) {
    if (evt.uri) {
        var targetUri = new Windows.Foundation.Uri(evt.uri);
        if (targetUri.host === '.cordova' && targetUri.path === '/exec') {
            var service = targetUri.queryParsed.getFirstValueByName('service');
            var action = targetUri.queryParsed.getFirstValueByName('action');
            var args = JSON.parse(decodeURIComponent(targetUri.queryParsed.getFirstValueByName('args')));
            var callbackId = targetUri.queryParsed.getFirstValueByName('callbackId');

            var success, fail;
            if (callbackId !== '0') {
                success = function (args) {
                    var params = args ? '"' + encodeURIComponent(JSON.stringify(args)) + '"' : '';
                    var script = 'cordova.callbacks["' + callbackId + '"].success(' + params + ');';
                    _mainView.invokeScriptAsync('eval', script).start();
                };

                fail = function (err) {
                    var params = args ? '"' + encodeURIComponent(JSON.stringify(err)) + '"' : '';
                    var script = 'cordova.callbacks["' + callbackId + '"].fail(' + params + ');';
                    _mainView.invokeScriptAsync('eval', script).start();
                };
            }

            exec(success, fail, service, action, args);

            return true;
        }
    }

    return false;
}

module.exports = {
    // loads the W3C manifest file and parses it
    loadManifest: function (successCallback, errorCallback, args) {
        var manifestFileName = (args && args instanceof Array && args.length > 0) ? args[0] : 'manifest.json';
        var configFile = 'ms-appx:///www/' + manifestFileName;
        var uri = new Windows.Foundation.Uri(configFile);
        Windows.Storage.StorageFile.getFileFromApplicationUriAsync(uri).then(
            function (file) {
                Windows.Storage.FileIO.readTextAsync(file).then(function (data) {
                    try {
                        _manifest = JSON.parse(data);
                        cordova.fireDocumentEvent("manifestLoaded", { manifest: _manifest });
                        successCallback &&  successCallback(_manifest);
                    } catch (err) {
                        _manifestError = 'Error parsing manifest file: ' + manifestFileName + ' - ' + err.message;
                        console.log(_manifestError);
                    }
                });
            },
            function (err) {
                _manifestError = 'Error reading manifest file: ' + manifestFileName + ' - ' + err;
                console.log(_manifestError);
                errorCallback && errorCallback(err);
            });
    },

    // returns the currently loaded manifest
    getManifest: function (successCallback, errorCallback) {
        if (_manifest) {
            successCallback && successCallback(_manifest);
        } else {
            errorCallback && errorCallback(new Error(_manifestError));
        }
    },

    // enables offline page support
    enableOfflinePage: function (successCallback, errorCallback) {
        _enableOfflineSupport = true;
        successCallback && successCallback();
    },

    // disables offline page support
    disableOfflinePage: function (successCallback, errorCallback) {
        _enableOfflineSupport = false;
        successCallback && successCallback();
    },

    getWebView: function () {
      return _mainView;
    },

    injectPluginScript: function (successCallback, errorCallback, file) {
        injectScripts(file, successCallback, errorCallback);
    }
}; // exports

cordova.commandProxy.add('HostedWebApp', module.exports);

module.exports.loadManifest(
    function (manifest) {
        configureOfflineSupport('offline.html');
        configureWhiteList(manifest);
        _mainView = configureHost(manifest ? manifest.start_url : 'about:blank', _zIndex);
        _mainView.addEventListener("MSWebViewDOMContentLoaded", domContentLoadedEvent, false);

        cordova.fireDocumentEvent("webviewCreated", { webView: _mainView });
        WinJS.Application.onbackclick = navigateBack;
    });
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2014 Vanderbilt University, All rights reserved.
 *
 * Authors: Robert Kereskenyi
 *          Dana Zhang
 */

define(['js/Panels/ModelEditor/ModelEditorControl',
    'js/Constants',
    'js/NodePropertyNames',
    'widgets/NetLabel/NetLabelWidget.Constants',
    './NetLabelControl.EventHandlers'], function (ModelEditorControl,
                                                  CONSTANTS,
                                                  NodePropertyNames,
                                                  NetLabelWidgetConstants,
                                                  NetLabelControlEventHandlers) {

    "use strict";

    var NetLabelControl;

    NetLabelControl = function (options) {
        ModelEditorControl.call(this, options);
    };

    _.extend(NetLabelControl.prototype, ModelEditorControl.prototype);
    _.extend(NetLabelControl.prototype, NetLabelControlEventHandlers.prototype);

    // todo: return src/dst texts instead -- in the initprop method these changes are made
    NetLabelControl.prototype.getConnectionDescriptor = function (gmeID) {

        var self = this,
            CONSTS =  CONSTANTS, // CONSTANTS can only be loaded by assigning it to a var
            gmeClient = self._client,
            connectionObj = gmeClient.getNode(gmeID),
            name = connectionObj.getAttribute(NodePropertyNames.Attributes.name),
            showAsLabel = connectionObj.getAttribute(NetLabelWidgetConstants.SHOW_AS_LABEL),
            connectionBaseId = connectionObj.getBaseId(),
            connectionBaseObj = gmeClient.getNode(connectionBaseId),
            defaultName = connectionBaseObj.getAttribute(NodePropertyNames.Attributes.name),
            srcID = connectionObj.getPointer(CONSTANTS.POINTER_SOURCE).to,
            dstID = connectionObj.getPointer(CONSTANTS.POINTER_TARGET).to,
            srcObj = gmeClient.getNode(srcID),
            dstObj = gmeClient.getNode(dstID),
            srcParentId = srcObj.getParentId(),
            dstParentId = dstObj.getParentId(),
            srcParentObj = gmeClient.getNode(srcParentId),
            dstParentObj = gmeClient.getNode(dstParentId);

        return {'name': name,
                'defaultName': defaultName,
                'showAsLabel': showAsLabel,
                'srcObj': srcObj,
                'dstObj': dstObj,
                'srcParentObj': srcParentObj,
                'dstParentObj': dstParentObj,
                'srcText': '',
                'dstText': ''};
    };

    return NetLabelControl;
});<commit_msg>GH-18 Passed in utils to widget from controller<commit_after>/*
 * Copyright (C) 2014 Vanderbilt University, All rights reserved.
 *
 * Authors: Robert Kereskenyi
 *          Dana Zhang
 */

define(['js/Panels/ModelEditor/ModelEditorControl',
    'js/Constants',
    'js/NodePropertyNames',
    'widgets/NetLabel/NetLabelWidget.Constants',
    './NetLabelControl.EventHandlers',
    'js/Utils/PreferencesHelper'], function (ModelEditorControl,
                                             CONSTANTS,
                                             NodePropertyNames,
                                             NetLabelWidgetConstants,
                                             NetLabelControlEventHandlers,
                                             PreferencesHelper) {

    "use strict";

    var NetLabelControl;

    NetLabelControl = function (options) {
        ModelEditorControl.call(this, options);
        this.designerCanvas._client = this._client;
    };

    _.extend(NetLabelControl.prototype, ModelEditorControl.prototype);
    _.extend(NetLabelControl.prototype, NetLabelControlEventHandlers.prototype);

    // todo: return src/dst texts instead -- in the initprop method these changes are made
    NetLabelControl.prototype.getConnectionDescriptor = function (gmeID) {

        var self = this,
            CONSTS =  CONSTANTS, // CONSTANTS can only be loaded by assigning it to a var
            gmeClient = self._client,
            connectionObj = gmeClient.getNode(gmeID),
            name = connectionObj.getAttribute(NodePropertyNames.Attributes.name),
            showAsLabel = connectionObj.getAttribute(NetLabelWidgetConstants.SHOW_AS_LABEL),
            connectionBaseId = connectionObj.getBaseId(),
            connectionBaseObj = gmeClient.getNode(connectionBaseId),
            defaultName = connectionBaseObj.getAttribute(NodePropertyNames.Attributes.name),
            srcID = connectionObj.getPointer(CONSTANTS.POINTER_SOURCE).to,
            dstID = connectionObj.getPointer(CONSTANTS.POINTER_TARGET).to,
            srcObj = gmeClient.getNode(srcID),
            dstObj = gmeClient.getNode(dstID),
            srcParentId = srcObj.getParentId(),
            dstParentId = dstObj.getParentId(),
            srcParentObj = gmeClient.getNode(srcParentId),
            dstParentObj = gmeClient.getNode(dstParentId);

        return {'name': name,
                'defaultName': defaultName,
                'showAsLabel': showAsLabel,
                'srcObj': srcObj,
                'dstObj': dstObj,
                'srcParentObj': srcParentObj,
                'dstParentObj': dstParentObj,
                'srcText': '',
                'dstText': ''};
    };

    NetLabelControl.prototype._onLoad = function (gmeID, objD) {
        var uiComponent,
            decClass,
            objDesc,
            sources = [],
            destinations = [],
            getDecoratorTerritoryQueries,
            territoryChanged = false,
            self = this;

        getDecoratorTerritoryQueries = function (decorator) {
            var query,
                entry;

            if (decorator) {
                query = decorator.getTerritoryQuery();

                if (query) {
                    for (entry in query) {
                        if (query.hasOwnProperty(entry)) {
                            self._selfPatterns[entry] = query[entry];
                            territoryChanged = true;
                        }
                    }
                }
            }
        };

        //component loaded
        //we are interested in the load of sub_components of the opened component
        if (this.currentNodeInfo.id !== gmeID) {
            if (objD) {
                if (objD.parentId == this.currentNodeInfo.id) {
                    objDesc = _.extend({}, objD);
                    this._GmeID2ComponentID[gmeID] = [];

                    if (objDesc.kind === "MODEL") {

                        this._GMEModels.push(gmeID);

                        decClass = this._getItemDecorator(objDesc.decorator);

                        objDesc.decoratorClass = decClass;
                        objDesc.control = this;
                        objDesc.metaInfo = {};
                        objDesc.metaInfo[CONSTANTS.GME_ID] = gmeID;
                        objDesc.preferencesHelper = PreferencesHelper.getPreferences();
                        objDesc.aspect = this._selectedAspect;

                        uiComponent = this.designerCanvas.createDesignerItem(objDesc);

                        this._GmeID2ComponentID[gmeID].push(uiComponent.id);
                        this._ComponentID2GmeID[uiComponent.id] = gmeID;

                        getDecoratorTerritoryQueries(uiComponent._decoratorInstance);

                    }

                    if (objDesc.kind === "CONNECTION") {

                        this._GMEConnections.push(gmeID);

                        var srcDst = this._getAllSourceDestinationPairsForConnection(objDesc.source, objDesc.target);
                        sources = srcDst.sources;
                        destinations = srcDst.destinations;

                        var k = sources.length;
                        var l = destinations.length;

                        if (k > 0 && l > 0) {
                            while (k--) {
                                while (l--) {
                                    objDesc.srcObjId = sources[k].objId;
                                    objDesc.srcSubCompId = sources[k].subCompId;
                                    objDesc.dstObjId = destinations[l].objId;
                                    objDesc.dstSubCompId = destinations[l].subCompId;
                                    objDesc.reconnectable = true;
                                    objDesc.editable = true;

                                    delete objDesc.source;
                                    delete objDesc.target;

                                    _.extend(objDesc, this.getConnectionDescriptor(gmeID));
                                    uiComponent = this.designerCanvas.createConnection(objDesc);

                                    this.logger.debug('Connection: ' + uiComponent.id + ' for GME object: ' + objDesc.id);

                                    this._GmeID2ComponentID[gmeID].push(uiComponent.id);
                                    this._ComponentID2GmeID[uiComponent.id] = gmeID;
                                }
                            }
                        } else {
                            //the connection is here, but no valid endpoint on canvas
                            //save the connection
                            this._delayedConnections.push(gmeID);
                        }
                    }
                } else {
                    //supposed to be the grandchild of the currently open node
                    //--> load of port
                    /*if(this._GMEModels.indexOf(objD.parentId) !== -1){
                     this._onUpdate(objD.parentId,this._getObjectDescriptor(objD.parentId));
                     }*/
                    this._checkComponentDependency(gmeID, CONSTANTS.TERRITORY_EVENT_LOAD);
                }
            }
        } else {
            //currently opened node
            this._updateSheetName(objD.name);
            this._updateAspects();
        }

        this.designerCanvas._ComponentID2GmeID = this._ComponentID2GmeID;
        return territoryChanged;

    };

    return NetLabelControl;
});<|endoftext|>


<commit_before>var PopupView = Backbone.View.extend({
    initialize: function () {
        _.bindAll(this, 'render');
        this.render();
    },
    render: function () {
        $(this.el).html(ich.PopupView(this.options));
        window.app.el.append(this.el);
        return this;
    },
    close: function() {
        this.remove();
        return false;
    },
    events: {
        'click .popup-close': 'close'
    }
});

<commit_msg>Close popup window when escape key is pressed.<commit_after>var PopupView = Backbone.View.extend({
    initialize: function () {
        _.bindAll(this, 'render');
        this.render();
    },
    render: function () {
        $(this.el).html(ich.PopupView(this.options));
        var that = this;
        $('body').keyup(function(e) {
          if (e.keyCode == 27) { that.close() }   // esc
        });
        window.app.el.append(this.el);
        return this;
    },
    close: function() {
        this.remove();
        return false;
    },
    events: {
        'click .popup-close': 'close'
    }
});

<|endoftext|>


<commit_before>/**
 * @preserve FastClick: polyfill to remove click delays on browsers with touch UIs.
 *
 * @version 0.6.9
 * @codingstandard ftlabs-jsv2
 * @copyright The Financial Times Limited [All Rights Reserved]
 * @license MIT License (see LICENSE.txt)
 */

/*jslint browser:true, node:true*/
/*global define, Event, Node*/

/**
 * Instantiate fast-clicking listeners on the specificed layer.
 *
 * @constructor
 * @param {Element} layer The layer to listen on
 */
function FastClick(layer) {
  'use strict';
  var oldOnClick, self = this;

  /**
   * Whether a click is currently being tracked.
   *
   * @type boolean
   */
  this.trackingClick = false;

  /**
   * Timestamp for when when click tracking started.
   *
   * @type number
   */
  this.trackingClickStart = 0;

  /**
   * The element being tracked for a click.
   *
   * @type EventTarget
   */
  this.targetElement = null;

  /**
   * X-coordinate of touch start event.
   *
   * @type number
   */
  this.touchStartX = 0;

  /**
   * Y-coordinate of touch start event.
   *
   * @type number
   */
  this.touchStartY = 0;

  /**
   * ID of the last touch, retrieved from Touch.identifier.
   *
   * @type number
   */
  this.lastTouchIdentifier = 0;

  /**
   * Touchmove boundary, beyond which a click will be cancelled.
   *
   * @type number
   */
  this.touchBoundary = 10;

  /**
   * The FastClick layer.
   *
   * @type Element
   */
  this.layer = layer;

  if (!layer || !layer.nodeType) {
    throw new TypeError('Layer must be a document node');
  }

  /** @type function() */
  this.onClick = function() { return FastClick.prototype.onClick.apply(self, arguments); };

  /** @type function() */
  this.onMouse = function() { return FastClick.prototype.onMouse.apply(self, arguments); };

  /** @type function() */
  this.onTouchStart = function() { return FastClick.prototype.onTouchStart.apply(self, arguments); };

  /** @type function() */
  this.onTouchMove = function() { return FastClick.prototype.onTouchMove.apply(self, arguments); };

  /** @type function() */
  this.onTouchEnd = function() { return FastClick.prototype.onTouchEnd.apply(self, arguments); };

  /** @type function() */
  this.onTouchCancel = function() { return FastClick.prototype.onTouchCancel.apply(self, arguments); };

  if (FastClick.notNeeded(layer)) {
    return;
  }

  // Set up event handlers as required
  if (this.deviceIsAndroid) {
    layer.addEventListener('mouseover', this.onMouse, true);
    layer.addEventListener('mousedown', this.onMouse, true);
    layer.addEventListener('mouseup', this.onMouse, true);
  }

  layer.addEventListener('click', this.onClick, true);
  layer.addEventListener('touchstart', this.onTouchStart, false);
  layer.addEventListener('touchmove', this.onTouchMove, false);
  layer.addEventListener('touchend', this.onTouchEnd, false);
  layer.addEventListener('touchcancel', this.onTouchCancel, false);

  // Hack is required for browsers that don't support Event#stopImmediatePropagation (e.g. Android 2)
  // which is how FastClick normally stops click events bubbling to callbacks registered on the FastClick
  // layer when they are cancelled.
  if (!Event.prototype.stopImmediatePropagation) {
    layer.removeEventListener = function(type, callback, capture) {
      var rmv = Node.prototype.removeEventListener;
      if (type === 'click') {
        rmv.call(layer, type, callback.hijacked || callback, capture);
      } else {
        rmv.call(layer, type, callback, capture);
      }
    };

    layer.addEventListener = function(type, callback, capture) {
      var adv = Node.prototype.addEventListener;
      if (type === 'click') {
        adv.call(layer, type, callback.hijacked || (callback.hijacked = function(event) {
          if (!event.propagationStopped) {
            callback(event);
          }
        }), capture);
      } else {
        adv.call(layer, type, callback, capture);
      }
    };
  }

  // If a handler is already declared in the element's onclick attribute, it will be fired before
  // FastClick's onClick handler. Fix this by pulling out the user-defined handler function and
  // adding it as listener.
  if (typeof layer.onclick === 'function') {

    // Android browser on at least 3.2 requires a new reference to the function in layer.onclick
    // - the old one won't work if passed to addEventListener directly.
    oldOnClick = layer.onclick;
    layer.addEventListener('click', function(event) {
      oldOnClick(event);
    }, false);
    layer.onclick = null;
  }
}

/**
 * Android requires exceptions.
 *
 * @type boolean
 */
FastClick.prototype.deviceIsAndroid = navigator.userAgent.indexOf('Android') > 0;

/**
 * iOS requires exceptions.
 *
 * @type boolean
 */
FastClick.prototype.deviceIsIOS = /iP(ad|hone|od)/.test(navigator.userAgent);

/**
 * iOS 4 requires an exception for select elements.
 *
 * @type boolean
 */
FastClick.prototype.deviceIsIOS4 = FastClick.prototype.deviceIsIOS && (/OS 4_\d(_\d)?/).test(navigator.userAgent);

/**
 * iOS 6.0(+?) requires the target element to be manually derived
 *
 * @type boolean
 */
FastClick.prototype.deviceIsIOSWithBadTarget = FastClick.prototype.deviceIsIOS && (/OS ([6-9]|\d{2})_\d/).test(navigator.userAgent);

/**
 * Determine whether a given element requires a native click.
 *
 * @param {EventTarget|Element} target Target DOM element
 * @returns {boolean} Returns true if the element needs a native click
 */
FastClick.prototype.needsClick = function(target) {
  'use strict';
  switch (target.nodeName.toLowerCase()) {

  // Don't send a synthetic click to disabled inputs (issue #62)
  case 'button':
  case 'select':
  case 'textarea':
    if (target.disabled) {
      return true;
    }

    break;
  case 'input':

    // File inputs need real clicks on iOS 6 due to a browser bug (issue #68)
    if ((this.deviceIsIOS && target.type === 'file') || target.disabled) {
      return true;
    }

    break;
  case 'label':
  case 'video':
    return true;
  }

  return (/\bneedsclick\b/).test(target.className);
};

/**
 * Determine whether a given element requires a call to focus to simulate click into element.
 *
 * @param {EventTarget|Element} target Target DOM element
 * @returns {boolean} Returns true if the element requires a call to focus to simulate native click.
 */
FastClick.prototype.needsFocus = function(target) {
  'use strict';
  switch (target.nodeName.toLowerCase()) {
  case 'textarea':
  case 'select':
    return true;
  case 'input':
    switch (target.type) {
    case 'button':
    case 'checkbox':
    case 'file':
    case 'image':
    case 'radio':
    case 'submit':
      return false;
    }

    // No point in attempting to focus disabled inputs
    return !target.disabled && !target.readOnly;
  default:
    return (/\bneedsfocus\b/).test(target.className);
  }
};

/**
 * Send a click event to the specified element.
 *
 * @param {EventTarget|Element} targetElement
 * @param {Event} event
 */
FastClick.prototype.sendClick = function(targetElement, event) {
  'use strict';
  var clickEvent, touch;

  // On some Android devices activeElement needs to be blurred otherwise the synthetic click will have no effect (#24)
  if (document.activeElement && document.activeElement !== targetElement) {
    document.activeElement.blur();
  }

  touch = event.changedTouches[0];

  // Synthesise a click event, with an extra attribute so it can be tracked
  clickEvent = document.createEvent('MouseEvents');
  clickEvent.initMouseEvent('click', true, true, window, 1, touch.screenX, touch.screenY, touch.clientX, touch.clientY, false, false, false, false, 0, null);
  clickEvent.forwardedTouchEvent = true;
  targetElement.dispatchEvent(clickEvent);
};

/**
 * @param {EventTarget|Element} targetElement
 */
FastClick.prototype.focus = function(targetElement) {
  'use strict';
  var length;

  if (this.deviceIsIOS && targetElement.setSelectionRange) {
    length = targetElement.value.length;
    targetElement.setSelectionRange(length, length);
  } else {
    targetElement.focus();
  }
};

/**
 * Check whether the given target element is a child of a scrollable layer and if so, set a flag on it.
 *
 * @param {EventTarget|Element} targetElement
 */
FastClick.prototype.updateScrollParent = function(targetElement) {
  'use strict';
  var scrollParent, parentElement;

  scrollParent = targetElement.fastClickScrollParent;

  // Attempt to discover whether the target element is contained within a scrollable layer. Re-check if the
  // target element was moved to another parent.
  if (!scrollParent || !scrollParent.contains(targetElement)) {
    parentElement = targetElement;
    do {
      if (parentElement.scrollHeight > parentElement.offsetHeight) {
        scrollParent = parentElement;
        targetElement.fastClickScrollParent = parentElement;
        break;
      }

      parentElement = parentElement.parentElement;
    } while (parentElement);
  }

  // Always update the scroll top tracker if possible.
  if (scrollParent) {
    scrollParent.fastClickLastScrollTop = scrollParent.scrollTop;
  }
};

/**
 * @param {EventTarget} targetElement
 * @returns {Element|EventTarget}
 */
FastClick.prototype.getTargetElementFromEventTarget = function(eventTarget) {
  'use strict';

  // On some older browsers (notably Safari on iOS 4.1 - see issue #56) the event target may be a text node.
  if (eventTarget.nodeType === Node.TEXT_NODE) {
    return eventTarget.parentNode;
  }

  return eventTarget;
};

/**
 * On touch start, record the position and scroll offset.
 *
 * @param {Event} event
 * @returns {boolean}
 */
FastClick.prototype.onTouchStart = function(event) {
  'use strict';
  var targetElement, touch, selection;

  // Ignore multiple touches, otherwise pinch-to-zoom is prevented if both fingers are on the FastClick element (issue #111).
  if (event.targetTouches.length > 1) {
    return true;
  }

  targetElement = this.getTargetElementFromEventTarget(event.target);
  touch = event.targetTouches[0];

  if (this.deviceIsIOS) {

    // Only trusted events will deselect text on iOS (issue #49)
    selection = window.getSelection();
    if (selection.rangeCount && !selection.isCollapsed) {
      return true;
    }

    if (!this.deviceIsIOS4) {

      // Weird things happen on iOS when an alert or confirm dialog is opened from a click event callback (issue #23):
      // when the user next taps anywhere else on the page, new touchstart and touchend events are dispatched
      // with the same identifier as the touch event that previously triggered the click that triggered the alert.
      // Sadly, there is an issue on iOS 4 that causes some normal touch events to have the same identifier as an
      // immediately preceeding touch event (issue #52), so this fix is unavailable on that platform.
      if (touch.identifier === this.lastTouchIdentifier) {
        event.preventDefault();
        return false;
      }

      this.lastTouchIdentifier = touch.identifier;

      // If the target element is a child of a scrollable layer (using -webkit-overflow-scrolling: touch) and:
      // 1) the user does a fling scroll on the scrollable layer
      // 2) the user stops the fling scroll with another tap
      // then the event.target of the last 'touchend' event will be the element that was under the user's finger
      // when the fling scroll was started, causing FastClick to send a click event to that layer - unless a check
      // is made to ensure that a parent layer was not scrolled before sending a synthetic click (issue #42).
      this.updateScrollParent(targetElement);
    }
  }

  this.trackingClick = true;
  this.trackingClickStart = event.timeStamp;
  this.targetElement = targetElement;

  this.touchStartX = touch.pageX;
  this.touchStartY = touch.pageY;

  // Prevent phantom clicks on fast double-tap (issue #36)
  if ((event.timeStamp - this.lastClickTime) < 200) {
    event.preventDefault();
  }

  return true;
};

/**
 * Based on a touchmove event object, check whether the touch has moved past a boundary since it started.
 *
 * @param {Event} event
 * @returns {boolean}
 */
FastClick.prototype.touchHasMoved = function(event) {
  'use strict';
  var touch = event.changedTouches[0], boundary = this.touchBoundary;

  if (Math.abs(touch.pageX - this.touchStartX) > boundary || Math.abs(touch.pageY - this.touchStartY) > boundary) {
    return true;
  }

  return false;
};

/**
 * Update the last position.
 *
 * @param {Event} event
 * @returns {boolean}
 */
FastClick.prototype.onTouchMove = function(event) {
  'use strict';
  if (!this.trackingClick) {
    return true;
  }

  // If the touch has moved, cancel the click tracking
  if (this.targetElement !== this.getTargetElementFromEventTarget(event.target) || this.touchHasMoved(event)) {
    this.trackingClick = false;
    this.targetElement = null;
  }

  return true;
};

/**
 * Attempt to find the labelled control for the given label element.
 *
 * @param {EventTarget|HTMLLabelElement} labelElement
 * @returns {Element|null}
 */
FastClick.prototype.findControl = function(labelElement) {
  'use strict';

  // Fast path for newer browsers supporting the HTML5 control attribute
  if (labelElement.control !== undefined) {
    return labelElement.control;
  }

  // All browsers under test that support touch events also support the HTML5 htmlFor attribute
  if (labelElement.htmlFor) {
    return document.getElementById(labelElement.htmlFor);
  }

  // If no for attribute exists, attempt to retrieve the first labellable descendant element
  // the list of which is defined here: http://www.w3.org/TR/html5/forms.html#category-label
  return labelElement.querySelector('button, input:not([type=hidden]), keygen, meter, output, progress, select, textarea');
};

/**
 * On touch end, determine whether to send a click event at once.
 *
 * @param {Event} event
 * @returns {boolean}
 */
FastClick.prototype.onTouchEnd = function(event) {
  'use strict';
  var forElement, trackingClickStart, targetTagName, scrollParent, touch, targetElement = this.targetElement;

  if (!this.trackingClick) {
    return true;
  }

  // Prevent phantom clicks on fast double-tap (issue #36)
  if ((event.timeStamp - this.lastClickTime) < 200) {
    this.cancelNextClick = true;
    return true;
  }

  this.lastClickTime = event.timeStamp;

  trackingClickStart = this.trackingClickStart;
  this.trackingClick = false;
  this.trackingClickStart = 0;

  // On some iOS devices, the targetElement supplied with the event is invalid if the layer
  // is performing a transition or scroll, and has to be re-detected manually. Note that
  // for this to function correctly, it must be called *after* the event target is checked!
  // See issue #57; also filed as rdar://13048589 .
  if (this.deviceIsIOSWithBadTarget) {
    touch = event.changedTouches[0];

    // In certain cases arguments of elementFromPoint can be negative, so prevent setting targetElement to null
    targetElement = document.elementFromPoint(touch.pageX - window.pageXOffset, touch.pageY - window.pageYOffset) || targetElement;
    targetElement.fastClickScrollParent = this.targetElement.fastClickScrollParent;
  }

  targetTagName = targetElement.tagName.toLowerCase();
  if (targetTagName === 'label') {
    forElement = this.findControl(targetElement);
    if (forElement) {
      this.focus(targetElement);
      if (this.deviceIsAndroid) {
        return false;
      }

      targetElement = forElement;
    }
  } else if (this.needsFocus(targetElement)) {

    // Case 1: If the touch started a while ago (best guess is 100ms based on tests for issue #36) then focus will be triggered anyway. Return early and unset the target element reference so that the subsequent click will be allowed through.
    // Case 2: Without this exception for input elements tapped when the document is contained in an iframe, then any inputted text won't be visible even though the value attribute is updated as the user types (issue #37).
    if ((event.timeStamp - trackingClickStart) > 100 || (this.deviceIsIOS && window.top !== window && targetTagName === 'input')) {
      this.targetElement = null;
      return false;
    }

    this.focus(targetElement);

    // Select elements need the event to go through on iOS 4, otherwise the selector menu won't open.
    if (!this.deviceIsIOS4 || targetTagName !== 'select') {
      this.targetElement = null;
      event.preventDefault();
    }

    return false;
  }

  if (this.deviceIsIOS && !this.deviceIsIOS4) {

    // Don't send a synthetic click event if the target element is contained within a parent layer that was scrolled
    // and this tap is being used to stop the scrolling (usually initiated by a fling - issue #42).
    scrollParent = targetElement.fastClickScrollParent;
    if (scrollParent && scrollParent.fastClickLastScrollTop !== scrollParent.scrollTop) {
      return true;
    }
  }

  // Prevent the actual click from going though - unless the target node is marked as requiring
  // real clicks or if it is in the whitelist in which case only non-programmatic clicks are permitted.
  if (!this.needsClick(targetElement)) {
    event.preventDefault();
    this.sendClick(targetElement, event);
  }

  return false;
};

/**
 * On touch cancel, stop tracking the click.
 *
 * @returns {void}
 */
FastClick.prototype.onTouchCancel = function() {
  'use strict';
  this.trackingClick = false;
  this.targetElement = null;
};

/**
 * Determine mouse events which should be permitted.
 *
 * @param {Event} event
 * @returns {boolean}
 */
FastClick.prototype.onMouse = function(event) {
  'use strict';

  // If a target element was never set (because a touch event was never fired) allow the event
  if (!this.targetElement) {
    return true;
  }

  if (event.forwardedTouchEvent) {
    return true;
  }

  // Programmatically generated events targeting a specific element should be permitted
  if (!event.cancelable) {
    return true;
  }

  // Derive and check the target element to see whether the mouse event needs to be permitted;
  // unless explicitly enabled, prevent non-touch click events from triggering actions,
  // to prevent ghost/doubleclicks.
  if (!this.needsClick(this.targetElement) || this.cancelNextClick) {

    // Prevent any user-added listeners declared on FastClick element from being fired.
    if (event.stopImmediatePropagation) {
      event.stopImmediatePropagation();
    } else {

      // Part of the hack for browsers that don't support Event#stopImmediatePropagation (e.g. Android 2)
      event.propagationStopped = true;
    }

    // Cancel the event
    event.stopPropagation();
    event.preventDefault();

    return false;
  }

  // If the mouse event is permitted, return true for the action to go through.
  return true;
};

/**
 * On actual clicks, determine whether this is a touch-generated click, a click action occurring
 * naturally after a delay after a touch (which needs to be cancelled to avoid duplication), or
 * an actual click which should be permitted.
 *
 * @param {Event} event
 * @returns {boolean}
 */
FastClick.prototype.onClick = function(event) {
  'use strict';
  var permitted;

  // It's possible for another FastClick-like library delivered with third-party code to fire a click event before FastClick does (issue #44). In that case, set the click-tracking flag back to false and return early. This will cause onTouchEnd to return early.
  if (this.trackingClick) {
    this.targetElement = null;
    this.trackingClick = false;
    return true;
  }

  // Very odd behaviour on iOS (issue #18): if a submit element is present inside a form and the user hits enter in the iOS simulator or clicks the Go button on the pop-up OS keyboard the a kind of 'fake' click event will be triggered with the submit-type input element as the target.
  if (event.target.type === 'submit' && event.detail === 0) {
    return true;
  }

  permitted = this.onMouse(event);

  // Only unset targetElement if the click is not permitted. This will ensure that the check for !targetElement in onMouse fails and the browser's click doesn't go through.
  if (!permitted) {
    this.targetElement = null;
  }

  // If clicks are permitted, return true for the action to go through.
  return permitted;
};

/**
 * Remove all FastClick's event listeners.
 *
 * @returns {void}
 */
FastClick.prototype.destroy = function() {
  'use strict';
  var layer = this.layer;

  if (this.deviceIsAndroid) {
    layer.removeEventListener('mouseover', this.onMouse, true);
    layer.removeEventListener('mousedown', this.onMouse, true);
    layer.removeEventListener('mouseup', this.onMouse, true);
  }

  layer.removeEventListener('click', this.onClick, true);
  layer.removeEventListener('touchstart', this.onTouchStart, false);
  layer.removeEventListener('touchmove', this.onTouchMove, false);
  layer.removeEventListener('touchend', this.onTouchEnd, false);
  layer.removeEventListener('touchcancel', this.onTouchCancel, false);
};

/**
 * Check whether FastClick is needed.
 *
 * @param {Element} layer The layer to listen on
 */
FastClick.notNeeded = function(layer) {
  'use strict';
  var metaViewport;

  // Devices that don't support touch don't need FastClick
  if (typeof window.ontouchstart === 'undefined') {
    return true;
  }

  if ((/Chrome\/[0-9]+/).test(navigator.userAgent)) {

    // Chrome on Android with user-scalable="no" doesn't need FastClick (issue #89)
    if (FastClick.prototype.deviceIsAndroid) {
      metaViewport = document.querySelector('meta[name=viewport]');
      if (metaViewport && metaViewport.content.indexOf('user-scalable=no') !== -1) {
        return true;
      }

    // Chrome desktop doesn't need FastClick (issue #15)
    } else {
      return true;
    }
  }

  // IE10 with -ms-touch-action: none, which disables double-tap-to-zoom (issue #97)
  if (layer.style.msTouchAction === 'none') {
    return true;
  }

  return false;
};

/**
 * Factory method for creating a FastClick object
 *
 * @param {Element} layer The layer to listen on
 */
FastClick.attach = function(layer) {
  'use strict';
  return new FastClick(layer);
};

if (typeof define !== 'undefined' && define.amd) {

  // AMD. Register as an anonymous module.
  define(function() {
    'use strict';
    return FastClick;
  });
} else if (typeof module !== 'undefined' && module.exports) {
  module.exports = FastClick.attach;
  module.exports.FastClick = FastClick;
} else {
  window.FastClick = FastClick;
}<commit_msg>Deleted fastclick.js<commit_after><|endoftext|>


<commit_before>/*jslint devel: true, nomen: true, indent: 2, maxlen: 100 */

"use strict";

var api = require('./lib/api');
var notifier = require('./lib/notifier');
var parser = require('./lib/parser');

var initialized = false;

/**
 *
 * Rollbar:
 *
 *  Handle caught and uncaught exceptions, and report messages back to rollbar.
 *
 *  This library requires an account at http://rollbar.com/.
 *
 * Example usage:
 *
 *  Express -
 *
 *     var express = require('express');
 *     var rollbar = require('rollbar');
 *
 *     var app = express();
 *
 *     app.get('/', function (req, res) {
 *       ...
 *     });
 *
 *     // Use the rollbar error handler to send exceptions to your rollbar account
 *     app.use(rollbar.errorHandler('ROLLBAR_ACCESS_TOKEN'));
 *
 *     app.listen(6943);
 *
 *  Standalone -
 *
 *     var rollbar = require('rollbar');
 *     rollbar.init('ROLLBAR_ACCESS_TOKEN');
 *     rollbar.reportMessage('Hello world', 'debug');
 *
 *  Uncaught exceptions -
 *
 *     var rollbar = require('rollbar');
 *     rollbar.handleUncaughtExceptions('ROLLBAR_ACCESS_TOKEN');
 *
 *  Send exceptions and request data -
 *
 *     app.get('/', function (req, res) {
 *       try {
 *         ...
 *       } catch (e) {
 *         rollbar.handleError(e, req);
 *       }
 *     });
 *
 *  Track people -
 *
 *     app.get('/', function (req, res) {
 *       req.userId = 12345; // or req.user_id
 *       rollbar.reportMessage('Interesting event', req);
 *     });
 */

exports.init = function (accessToken, options) {
  /*
   * Initialize the rollbar library.
   *
   * For more information on each option, see http://rollbar.com/docs/api_items/
   *
   * Supported options, (all optional):
   *
   *  host - Default: os.hostname() - the hostname of the server the node.js process is running on
   *  environment - Default: 'unspecified' - the environment the code is running in. e.g. 'staging'
   *  endpoint - Default: 'https://api.rollbar.com/api/1/' - the url to send items to
   *  root - the path to your code, (not including any trailing slash) which will be used to link
   *    source files on rollbar
   *  branch - the branch in your version control system for this code
   *  codeVersion - the version or revision of your code
   *
   */
  if (!initialized) {
    options = options || {};
    if (!accessToken && options.enabled !== false) {
      console.error('[Rollbar] Missing access_token.');
      return;
    }

    options.environment = options.environment || process.env.NODE_ENV || 'unspecified';

    api.init(accessToken, options);
    notifier.init(api, options);
    initialized = true;
  }
};

/*
 * reportMessage(message, level, request, callback)
 *
 * Sends a message to rollbar with optional level, request and callback.
 * The callback should take a single parameter to indicate if there was an
 * error.
 *
 * Parameters:
 *  message - a string to send to rollbar
 *  level - Default: 'error' - optional level, 'debug', 'info', 'warning', 'error', 'critical'
 *  request - optional request object to send along with the message
 *  callback - optional callback that will be invoked once the message was reported.
 *    callback should take 3 parameters: callback(err, payloadData, response)
 *
 * Examples:
 *
 *  rollbar.reportMessage("User purchased something awesome!", "info");
 *
 *  rollbar.reportMessage("Something suspicious...", "debug", null, function (err, payloadData) {
 *    if (err) {
 *      console.error('Error sending to Rollbar:', err);
 *    } else {
 *      console.log('Reported message to rollbar:');
 *      console.log(payloadData);
 *    }
 *  });
 *
 */
exports.reportMessage = notifier.reportMessage;

/*
 * reportMessageWithPayloadData(message, payloadData, request, callback)
 *
 * The same as reportMessage() but allows you to specify extra data along with the message.
 *
 * Parameters:
 *  message - a string to send to rollbar
 *  payloadData - an object containing key/values to be sent along with the message.
 *    e.g. {level: "warning", fingerprint: "CustomerFingerPrint"}
 *  request - optional request object to send along with the message
 *  callback - optional callback that will be invoked once the message has been sent to Rollbar.
 *    callback should take 3 parameters: callback(err, payloadData, response)
 *
 * Examples:
 *
 *  rollbar.reportMessageWithPayloadData("Memcache miss",
 *    {level: "debug", fingerprint: "Memcache-miss"}, null, function (err) {
 *    // message was queued/sent to rollbar
 *  });
 *
 */
exports.reportMessageWithPayloadData = notifier.reportMessageWithPayloadData;

/*
 * handleError(err, request, callback)
 *
 * Send a details about the error to rollbar along with optional request information.
 *
 * Parameters:
 *  err - an Exception/Error instance
 *  request - an optional request object to send along with the error
 *  callback - optional callback that will be invoked after the error was sent to Rollbar.
 *    callback should take 3 parameters: callback(err, payloadData, response)
 *
 * Examples:
 *
 *  rollbar.handleError(new Error("Could not connect to the database"));
 *
 *  rollbar.handleError(new Error("it's just foobar..."), function (err) {
 *    // error was queued/sent to rollbar
 *  });
 *
 *  rollbar.handleError(new Error("invalid request!"), req);
 *
 */
exports.handleError = notifier.handleError;

/*
 * handleErrorWithPayloadData(err, payloadData, request, callback)
 *
 * The same as handleError() but allows you to specify additional data to log along with the error,
 * as well as other payload options.
 *
 * Parameters:
 *  err - an Exception/Error instance
 *  payloadData - an object containing keys/values to be sent along with the error report.
 *    e.g. {level: "warning"}
 *  request - optional request object to send along with the message
 *  callback - optional callback that will be invoked after the error was sent to Rollbar.
 *    callback should take 3 parameters: callback(err, payloadData, response)
 *
 *  Examples:
 *
 *   rollbar.handleError(new Error("Could not connect to database"), {level: "warning"});
 *   rollbar.handleError(new Error("Could not connect to database"),
 *    {custom: {someKey: "its value, otherKey: ["other", "value"]}});
 *   rollbar.handleError(new Error("error message"), {}, req, function (err) {
 *     // error was queued/sent to rollbar
 *   });
 */
exports.handleErrorWithPayloadData = notifier.handleErrorWithPayloadData;

exports.errorHandler = function (accessToken, options) {
  /*
   * A middleware handler for connect and express.js apps. For a list
   * of supported options, see the init() docs above.
   *
   * All exceptions thrown from inside an express or connect get/post/etc... handler
   * will be sent to rollbar when this middleware is installed.
   */
  exports.init(accessToken, options);
  return function (err, req, res, next) {
    var cb = function (rollbarErr) {
      if (rollbarErr) {
        console.error('[Rollbar] Error reporting to rollbar, ignoring: ' + rollbarErr);
      }
      return next(err, req, res);
    };

    if (!err) {
      return next(err, req, res);
    }

    if (err instanceof Error) {
      return notifier.handleError(err, req, cb);
    }

    return notifier.reportMessage('Error: ' + err, 'error', req, cb);
  };
};

exports.handleUncaughtExceptions = function (accessToken, options) {
  /*
   * Registers a handler for the process.uncaughtException event.
   *
   * If options.exitOnUncaughtException is set to true, the notifier will
   * immediately send the uncaught exception + all queued items to rollbar,
   * then call process.exit(1).
   *
   * Note: The node.js authors advise against using these type of handlers.
   * More info: http://nodejs.org/api/process.html#process_event_uncaughtexception
   *
   */

  // Default to not exiting on uncaught exceptions unless options.exitOnUncaughtException is set.
  options = options || {};
  var exitOnUncaught = options.exitOnUncaughtException === undefined ?
        false : !!options.exitOnUncaughtException;
  delete options.exitOnUncaughtException;

  exports.init(accessToken, options);

  if (initialized) {
    process.on('uncaughtException', function (err) {
      console.error('[Rollbar] Handling uncaught exception.');
      console.error(err);

      notifier.handleError(err, function (err) {
        if (err) {
          console.error('[Rollbar] Encountered an error while handling an uncaught exception.');
          console.error(err);
        }

        if (exitOnUncaught) {
          process.exit(1);
        }
      });
    });
  } else {
    console.error('[Rollbar] Rollbar is not initialized. Uncaught exceptions will not be tracked.');
  }
};

exports.api = api;
exports.notifier = notifier;
<commit_msg>Add line comment for options.enabled<commit_after>/*jslint devel: true, nomen: true, indent: 2, maxlen: 100 */

"use strict";

var api = require('./lib/api');
var notifier = require('./lib/notifier');
var parser = require('./lib/parser');

var initialized = false;

/**
 *
 * Rollbar:
 *
 *  Handle caught and uncaught exceptions, and report messages back to rollbar.
 *
 *  This library requires an account at http://rollbar.com/.
 *
 * Example usage:
 *
 *  Express -
 *
 *     var express = require('express');
 *     var rollbar = require('rollbar');
 *
 *     var app = express();
 *
 *     app.get('/', function (req, res) {
 *       ...
 *     });
 *
 *     // Use the rollbar error handler to send exceptions to your rollbar account
 *     app.use(rollbar.errorHandler('ROLLBAR_ACCESS_TOKEN'));
 *
 *     app.listen(6943);
 *
 *  Standalone -
 *
 *     var rollbar = require('rollbar');
 *     rollbar.init('ROLLBAR_ACCESS_TOKEN');
 *     rollbar.reportMessage('Hello world', 'debug');
 *
 *  Uncaught exceptions -
 *
 *     var rollbar = require('rollbar');
 *     rollbar.handleUncaughtExceptions('ROLLBAR_ACCESS_TOKEN');
 *
 *  Send exceptions and request data -
 *
 *     app.get('/', function (req, res) {
 *       try {
 *         ...
 *       } catch (e) {
 *         rollbar.handleError(e, req);
 *       }
 *     });
 *
 *  Track people -
 *
 *     app.get('/', function (req, res) {
 *       req.userId = 12345; // or req.user_id
 *       rollbar.reportMessage('Interesting event', req);
 *     });
 */

exports.init = function (accessToken, options) {
  /*
   * Initialize the rollbar library.
   *
   * For more information on each option, see http://rollbar.com/docs/api_items/
   *
   * Supported options, (all optional):
   *
   *  host - Default: os.hostname() - the hostname of the server the node.js process is running on
   *  environment - Default: 'unspecified' - the environment the code is running in. e.g. 'staging'
   *  endpoint - Default: 'https://api.rollbar.com/api/1/' - the url to send items to
   *  root - the path to your code, (not including any trailing slash) which will be used to link
   *    source files on rollbar
   *  branch - the branch in your version control system for this code
   *  codeVersion - the version or revision of your code
   *  enabled - Default: true - determines if errors gets reported to Rollbar
   *
   */
  if (!initialized) {
    options = options || {};
    if (!accessToken && options.enabled !== false) {
      console.error('[Rollbar] Missing access_token.');
      return;
    }

    options.environment = options.environment || process.env.NODE_ENV || 'unspecified';

    api.init(accessToken, options);
    notifier.init(api, options);
    initialized = true;
  }
};

/*
 * reportMessage(message, level, request, callback)
 *
 * Sends a message to rollbar with optional level, request and callback.
 * The callback should take a single parameter to indicate if there was an
 * error.
 *
 * Parameters:
 *  message - a string to send to rollbar
 *  level - Default: 'error' - optional level, 'debug', 'info', 'warning', 'error', 'critical'
 *  request - optional request object to send along with the message
 *  callback - optional callback that will be invoked once the message was reported.
 *    callback should take 3 parameters: callback(err, payloadData, response)
 *
 * Examples:
 *
 *  rollbar.reportMessage("User purchased something awesome!", "info");
 *
 *  rollbar.reportMessage("Something suspicious...", "debug", null, function (err, payloadData) {
 *    if (err) {
 *      console.error('Error sending to Rollbar:', err);
 *    } else {
 *      console.log('Reported message to rollbar:');
 *      console.log(payloadData);
 *    }
 *  });
 *
 */
exports.reportMessage = notifier.reportMessage;

/*
 * reportMessageWithPayloadData(message, payloadData, request, callback)
 *
 * The same as reportMessage() but allows you to specify extra data along with the message.
 *
 * Parameters:
 *  message - a string to send to rollbar
 *  payloadData - an object containing key/values to be sent along with the message.
 *    e.g. {level: "warning", fingerprint: "CustomerFingerPrint"}
 *  request - optional request object to send along with the message
 *  callback - optional callback that will be invoked once the message has been sent to Rollbar.
 *    callback should take 3 parameters: callback(err, payloadData, response)
 *
 * Examples:
 *
 *  rollbar.reportMessageWithPayloadData("Memcache miss",
 *    {level: "debug", fingerprint: "Memcache-miss"}, null, function (err) {
 *    // message was queued/sent to rollbar
 *  });
 *
 */
exports.reportMessageWithPayloadData = notifier.reportMessageWithPayloadData;

/*
 * handleError(err, request, callback)
 *
 * Send a details about the error to rollbar along with optional request information.
 *
 * Parameters:
 *  err - an Exception/Error instance
 *  request - an optional request object to send along with the error
 *  callback - optional callback that will be invoked after the error was sent to Rollbar.
 *    callback should take 3 parameters: callback(err, payloadData, response)
 *
 * Examples:
 *
 *  rollbar.handleError(new Error("Could not connect to the database"));
 *
 *  rollbar.handleError(new Error("it's just foobar..."), function (err) {
 *    // error was queued/sent to rollbar
 *  });
 *
 *  rollbar.handleError(new Error("invalid request!"), req);
 *
 */
exports.handleError = notifier.handleError;

/*
 * handleErrorWithPayloadData(err, payloadData, request, callback)
 *
 * The same as handleError() but allows you to specify additional data to log along with the error,
 * as well as other payload options.
 *
 * Parameters:
 *  err - an Exception/Error instance
 *  payloadData - an object containing keys/values to be sent along with the error report.
 *    e.g. {level: "warning"}
 *  request - optional request object to send along with the message
 *  callback - optional callback that will be invoked after the error was sent to Rollbar.
 *    callback should take 3 parameters: callback(err, payloadData, response)
 *
 *  Examples:
 *
 *   rollbar.handleError(new Error("Could not connect to database"), {level: "warning"});
 *   rollbar.handleError(new Error("Could not connect to database"),
 *    {custom: {someKey: "its value, otherKey: ["other", "value"]}});
 *   rollbar.handleError(new Error("error message"), {}, req, function (err) {
 *     // error was queued/sent to rollbar
 *   });
 */
exports.handleErrorWithPayloadData = notifier.handleErrorWithPayloadData;

exports.errorHandler = function (accessToken, options) {
  /*
   * A middleware handler for connect and express.js apps. For a list
   * of supported options, see the init() docs above.
   *
   * All exceptions thrown from inside an express or connect get/post/etc... handler
   * will be sent to rollbar when this middleware is installed.
   */
  exports.init(accessToken, options);
  return function (err, req, res, next) {
    var cb = function (rollbarErr) {
      if (rollbarErr) {
        console.error('[Rollbar] Error reporting to rollbar, ignoring: ' + rollbarErr);
      }
      return next(err, req, res);
    };

    if (!err) {
      return next(err, req, res);
    }

    if (err instanceof Error) {
      return notifier.handleError(err, req, cb);
    }

    return notifier.reportMessage('Error: ' + err, 'error', req, cb);
  };
};

exports.handleUncaughtExceptions = function (accessToken, options) {
  /*
   * Registers a handler for the process.uncaughtException event.
   *
   * If options.exitOnUncaughtException is set to true, the notifier will
   * immediately send the uncaught exception + all queued items to rollbar,
   * then call process.exit(1).
   *
   * Note: The node.js authors advise against using these type of handlers.
   * More info: http://nodejs.org/api/process.html#process_event_uncaughtexception
   *
   */

  // Default to not exiting on uncaught exceptions unless options.exitOnUncaughtException is set.
  options = options || {};
  var exitOnUncaught = options.exitOnUncaughtException === undefined ?
        false : !!options.exitOnUncaughtException;
  delete options.exitOnUncaughtException;

  exports.init(accessToken, options);

  if (initialized) {
    process.on('uncaughtException', function (err) {
      console.error('[Rollbar] Handling uncaught exception.');
      console.error(err);

      notifier.handleError(err, function (err) {
        if (err) {
          console.error('[Rollbar] Encountered an error while handling an uncaught exception.');
          console.error(err);
        }

        if (exitOnUncaught) {
          process.exit(1);
        }
      });
    });
  } else {
    console.error('[Rollbar] Rollbar is not initialized. Uncaught exceptions will not be tracked.');
  }
};

exports.api = api;
exports.notifier = notifier;
<|endoftext|>


<commit_before>import React from 'react';
import { render } from 'react-dom';
// import css
import css from './stylles/styl.styl'
<commit_msg>more testing<commit_after>// let's go!
<|endoftext|>


<commit_before>import {React, Component} from '../imports';

// const NOTIFICATIONS_SHOW_LIMIT = 3;
const DEFAULT_NOTIFICATION_LIFETIME = 5000;
const DEFAULT_NOTIFICATION_TYPE = 'info';

/**
 * This class renders a notification list. To add new notifications here you have to publish a event to the window
 * with the name 'ws-notification-open' and the options listed below. To close all notifications just publish a event
 * with the name 'ws-notification-close-all' to the window object.
 *
 * Example with options:
 * @example window.dispatchEvent(new CustomEvent('ws-notification-open', {detail: {
 *   title: 'test', // Required string
 *   description: 'additional info', // Optional string
 *   type: 'warning', // Enum of info|success|warning|error. Default: info
 *   lifetime: 5000, // Lifetime of notification in milliseconds. Default: max int
 * }});
 */
export class WSNotification extends Component {

  /**
   * @constructor
   */
  constructor() {
    super();
    this.state = {
      notifications: []
    };
    // Bind functions to this scope
    this.addNotify = this.addNotify.bind(this);
    this.closeAllEvents = this.closeAllEvents.bind(this);
  }

  /**
   * Listen to events on window object
   * @returns {void}
   */
  componentDidMount() {
    window.addEventListener('ws-notification-open', this.addNotify);
    window.addEventListener('ws-notification-close-all', this.closeAllEvents);
  }

  /**
   * Trigger animation of new notification if needed
   * @param {Object} prevProps Previous react component properties
   * @param {Object} prevState Previous react component state
   * @returns {void}
   */
  componentDidUpdate(prevProps, prevState) {
    if (prevState.notifications.length < this.state.notifications.length) {
      this.animateIn();
    }
  }

  /**
   * Unbind event listener from window object
   * @returns {void}
   */
  componentWillUnmount() {
    window.removeEventListener('ws-notification-open');
    window.removeEventListener('ws-notification-close');
  }

  /**
   * Callback of event to add new notification to the list
   * @param {CustomEvent} event JavaScript event object
   * @returns {void}
   */
  addNotify(event) {
    const {title, description} = event.detail;
    let {type, lifetime} = event.detail;
    if (typeof lifetime === 'undefined') {
      lifetime = DEFAULT_NOTIFICATION_LIFETIME;
    } else if (!lifetime) {
      lifetime = 2147483647;
    }
    if (!type) {
      type = DEFAULT_NOTIFICATION_TYPE;
    }
    this.setState({
      notifications: this.state.notifications.concat([{title, description, type, lifetime}])
    });
  }

  /**
   * Start to animate in a notification
   * @param {Object} notification The notification to animate in
   * @returns {void}
   */
  animateIn() {
    const list = this.refs.list;
    list.style.transition = 'none';
    list.style.transform = 'translate3d(0, 80px, 0)';
    setTimeout(() => {
      list.style.transition = 'transform .35s cubic-bezier(.35, 1, .69, .98) .1s';
      list.style.transform = 'translate3d(0, 0, 0)';
    }, 0);
  }

  /**
   * Close all open notifications
   * @returns {void}
   */
  closeAllEvents() {
    for (let i = 0; i < this.state.notifications.length; i++) {
      this.close(i);
    }
  }

  /**
   * Close a specific notification
   * @param {Number} index The index of the notification in the list
   * @returns {void}
   */
  close(index) {
    const notification = this.refs[`notification-${index}`];
    if (notification) {
      const notifications = this.state.notifications.slice();
      notifications.splice(index, 1);
      setTimeout(() => {
        this.setState({
          notifications
        });
      }, 0);
    }
  }

  /**
   * Render the notification list
   * @returns {Object}
   */
  render() {
    return (

        {this.state.notifications.map((notification, i) =>
          <div
            className={`notification ${notification.type}`}
            key={`notification-${i}`}
            ref={`notification-${i}`}
            onClick={() => this.close(i)}
          >

{notification.title}

              {(notification.description) ?
{notification.description}
 : null}

        )}

);
  }
}
<commit_msg>Take out timeout for hiding, it's not needed as I took the animation out<commit_after>import {React, Component} from '../imports';

// const NOTIFICATIONS_SHOW_LIMIT = 3;
const DEFAULT_NOTIFICATION_LIFETIME = 5000;
const DEFAULT_NOTIFICATION_TYPE = 'info';

/**
 * This class renders a notification list. To add new notifications here you have to publish a event to the window
 * with the name 'ws-notification-open' and the options listed below. To close all notifications just publish a event
 * with the name 'ws-notification-close-all' to the window object.
 *
 * Example with options:
 * @example window.dispatchEvent(new CustomEvent('ws-notification-open', {detail: {
 *   title: 'test', // Required string
 *   description: 'additional info', // Optional string
 *   type: 'warning', // Enum of info|success|warning|error. Default: info
 *   lifetime: 5000, // Lifetime of notification in milliseconds. Default: max int
 * }});
 */
export class WSNotification extends Component {

  /**
   * @constructor
   */
  constructor() {
    super();
    this.state = {
      notifications: []
    };
    // Bind functions to this scope
    this.addNotify = this.addNotify.bind(this);
    this.closeAllEvents = this.closeAllEvents.bind(this);
  }

  /**
   * Listen to events on window object
   * @returns {void}
   */
  componentDidMount() {
    window.addEventListener('ws-notification-open', this.addNotify);
    window.addEventListener('ws-notification-close-all', this.closeAllEvents);
  }

  /**
   * Trigger animation of new notification if needed
   * @param {Object} prevProps Previous react component properties
   * @param {Object} prevState Previous react component state
   * @returns {void}
   */
  componentDidUpdate(prevProps, prevState) {
    if (prevState.notifications.length < this.state.notifications.length) {
      this.animateIn();
    }
  }

  /**
   * Unbind event listener from window object
   * @returns {void}
   */
  componentWillUnmount() {
    window.removeEventListener('ws-notification-open');
    window.removeEventListener('ws-notification-close');
  }

  /**
   * Callback of event to add new notification to the list
   * @param {CustomEvent} event JavaScript event object
   * @returns {void}
   */
  addNotify(event) {
    const {title, description} = event.detail;
    let {type, lifetime} = event.detail;
    if (typeof lifetime === 'undefined') {
      lifetime = DEFAULT_NOTIFICATION_LIFETIME;
    } else if (!lifetime) {
      lifetime = 2147483647;
    }
    if (!type) {
      type = DEFAULT_NOTIFICATION_TYPE;
    }
    this.setState({
      notifications: this.state.notifications.concat([{title, description, type, lifetime}])
    });
  }

  /**
   * Start to animate in a notification
   * @param {Object} notification The notification to animate in
   * @returns {void}
   */
  animateIn() {
    const list = this.refs.list;
    list.style.transition = 'none';
    list.style.transform = 'translate3d(0, 80px, 0)';
    setTimeout(() => {
      list.style.transition = 'transform .35s cubic-bezier(.35, 1, .69, .98) .1s';
      list.style.transform = 'translate3d(0, 0, 0)';
    }, 0);
  }

  /**
   * Close all open notifications
   * @returns {void}
   */
  closeAllEvents() {
    for (let i = 0; i < this.state.notifications.length; i++) {
      this.close(i);
    }
  }

  /**
   * Close a specific notification
   * @param {Number} index The index of the notification in the list
   * @returns {void}
   */
  close(index) {
    const notification = this.refs[`notification-${index}`];
    if (notification) {
      const notifications = this.state.notifications.slice();
      notifications.splice(index, 1);
      this.setState({
        notifications
      });
    }
  }

  /**
   * Render the notification list
   * @returns {Object}
   */
  render() {
    return (

        {this.state.notifications.map((notification, i) =>
          <div
            className={`notification ${notification.type}`}
            key={`notification-${i}`}
            ref={`notification-${i}`}
            onClick={() => this.close(i)}
          >

{notification.title}

              {(notification.description) ?
{notification.description}
 : null}

        )}

);
  }
}
<|endoftext|>