code
stringlengths
2
1.05M
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ 'use strict'; exports.__esModule = true; exports.default = void 0; var React = _interopRequireWildcard(require("react")); var _pick = _interopRequireDefault(require("../../modules/pick")); var _useMergeRefs = _interopRequireDefault(require("../../modules/useMergeRefs")); var _usePressEvents = _interopRequireDefault(require("../../modules/usePressEvents")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } var forwardPropsList = { accessibilityDisabled: true, accessibilityLabel: true, accessibilityLiveRegion: true, accessibilityRole: true, accessibilityState: true, accessibilityValue: true, children: true, disabled: true, focusable: true, nativeID: true, onBlur: true, onFocus: true, onLayout: true, testID: true }; var pickProps = function pickProps(props) { return (0, _pick.default)(props, forwardPropsList); }; function TouchableWithoutFeedback(props, forwardedRef) { var delayPressIn = props.delayPressIn, delayPressOut = props.delayPressOut, delayLongPress = props.delayLongPress, disabled = props.disabled, focusable = props.focusable, onLongPress = props.onLongPress, onPress = props.onPress, onPressIn = props.onPressIn, onPressOut = props.onPressOut, rejectResponderTermination = props.rejectResponderTermination; var hostRef = (0, React.useRef)(null); var pressConfig = (0, React.useMemo)(function () { return { cancelable: !rejectResponderTermination, disabled: disabled, delayLongPress: delayLongPress, delayPressStart: delayPressIn, delayPressEnd: delayPressOut, onLongPress: onLongPress, onPress: onPress, onPressStart: onPressIn, onPressEnd: onPressOut }; }, [disabled, delayPressIn, delayPressOut, delayLongPress, onLongPress, onPress, onPressIn, onPressOut, rejectResponderTermination]); var pressEventHandlers = (0, _usePressEvents.default)(hostRef, pressConfig); var element = React.Children.only(props.children); var children = [element.props.children]; var supportedProps = pickProps(props); supportedProps.accessibilityDisabled = disabled; supportedProps.focusable = !disabled && focusable !== false; supportedProps.ref = (0, _useMergeRefs.default)(forwardedRef, hostRef, element.ref); var elementProps = Object.assign(supportedProps, pressEventHandlers); return /*#__PURE__*/React.cloneElement.apply(React, [element, elementProps].concat(children)); } var MemoedTouchableWithoutFeedback = /*#__PURE__*/React.memo( /*#__PURE__*/React.forwardRef(TouchableWithoutFeedback)); MemoedTouchableWithoutFeedback.displayName = 'TouchableWithoutFeedback'; var _default = MemoedTouchableWithoutFeedback; exports.default = _default; module.exports = exports.default;
// Platform: android // commit f50d20a87431c79a54572263729461883f611a53 // File generated at :: Tue Feb 26 2013 13:37:51 GMT-0800 (PST) /* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ ;(function() { // file: lib/scripts/require.js var require, define; (function () { var modules = {}; // Stack of moduleIds currently being built. var requireStack = []; // Map of module ID -> index into requireStack of modules currently being built. var inProgressModules = {}; function build(module) { var factory = module.factory; module.exports = {}; delete module.factory; factory(require, module.exports, module); return module.exports; } require = function (id) { if (!modules[id]) { throw "module " + id + " not found"; } else if (id in inProgressModules) { var cycle = requireStack.slice(inProgressModules[id]).join('->') + '->' + id; throw "Cycle in require graph: " + cycle; } if (modules[id].factory) { try { inProgressModules[id] = requireStack.length; requireStack.push(id); return build(modules[id]); } finally { delete inProgressModules[id]; requireStack.pop(); } } return modules[id].exports; }; define = function (id, factory) { if (modules[id]) { throw "module " + id + " already defined"; } modules[id] = { id: id, factory: factory }; }; define.remove = function (id) { delete modules[id]; }; define.moduleMap = modules; })(); //Export for use in node if (typeof module === "object" && typeof require === "function") { module.exports.require = require; module.exports.define = define; } // file: lib/cordova.js define("cordova", function(require, exports, module) { var channel = require('cordova/channel'); /** * Listen for DOMContentLoaded and notify our channel subscribers. */ document.addEventListener('DOMContentLoaded', function() { channel.onDOMContentLoaded.fire(); }, false); if (document.readyState == 'complete' || document.readyState == 'interactive') { channel.onDOMContentLoaded.fire(); } /** * Intercept calls to addEventListener + removeEventListener and handle deviceready, * resume, and pause events. */ var m_document_addEventListener = document.addEventListener; var m_document_removeEventListener = document.removeEventListener; var m_window_addEventListener = window.addEventListener; var m_window_removeEventListener = window.removeEventListener; /** * Houses custom event handlers to intercept on document + window event listeners. */ var documentEventHandlers = {}, windowEventHandlers = {}; document.addEventListener = function(evt, handler, capture) { var e = evt.toLowerCase(); if (typeof documentEventHandlers[e] != 'undefined') { documentEventHandlers[e].subscribe(handler); } else { m_document_addEventListener.call(document, evt, handler, capture); } }; window.addEventListener = function(evt, handler, capture) { var e = evt.toLowerCase(); if (typeof windowEventHandlers[e] != 'undefined') { windowEventHandlers[e].subscribe(handler); } else { m_window_addEventListener.call(window, evt, handler, capture); } }; document.removeEventListener = function(evt, handler, capture) { var e = evt.toLowerCase(); // If unsubscribing from an event that is handled by a plugin if (typeof documentEventHandlers[e] != "undefined") { documentEventHandlers[e].unsubscribe(handler); } else { m_document_removeEventListener.call(document, evt, handler, capture); } }; window.removeEventListener = function(evt, handler, capture) { var e = evt.toLowerCase(); // If unsubscribing from an event that is handled by a plugin if (typeof windowEventHandlers[e] != "undefined") { windowEventHandlers[e].unsubscribe(handler); } else { m_window_removeEventListener.call(window, evt, handler, capture); } }; function createEvent(type, data) { var event = document.createEvent('Events'); event.initEvent(type, false, false); if (data) { for (var i in data) { if (data.hasOwnProperty(i)) { event[i] = data[i]; } } } return event; } if(typeof window.console === "undefined") { window.console = { log:function(){} }; } var cordova = { define:define, require:require, /** * Methods to add/remove your own addEventListener hijacking on document + window. */ addWindowEventHandler:function(event) { return (windowEventHandlers[event] = channel.create(event)); }, addStickyDocumentEventHandler:function(event) { return (documentEventHandlers[event] = channel.createSticky(event)); }, addDocumentEventHandler:function(event) { return (documentEventHandlers[event] = channel.create(event)); }, removeWindowEventHandler:function(event) { delete windowEventHandlers[event]; }, removeDocumentEventHandler:function(event) { delete documentEventHandlers[event]; }, /** * Retrieve original event handlers that were replaced by Cordova * * @return object */ getOriginalHandlers: function() { return {'document': {'addEventListener': m_document_addEventListener, 'removeEventListener': m_document_removeEventListener}, 'window': {'addEventListener': m_window_addEventListener, 'removeEventListener': m_window_removeEventListener}}; }, /** * Method to fire event from native code * bNoDetach is required for events which cause an exception which needs to be caught in native code */ fireDocumentEvent: function(type, data, bNoDetach) { var evt = createEvent(type, data); if (typeof documentEventHandlers[type] != 'undefined') { if( bNoDetach ) { documentEventHandlers[type].fire(evt); } else { setTimeout(function() { documentEventHandlers[type].fire(evt); }, 0); } } else { document.dispatchEvent(evt); } }, fireWindowEvent: function(type, data) { var evt = createEvent(type,data); if (typeof windowEventHandlers[type] != 'undefined') { setTimeout(function() { windowEventHandlers[type].fire(evt); }, 0); } else { window.dispatchEvent(evt); } }, /** * Plugin callback mechanism. */ // Randomize the starting callbackId to avoid collisions after refreshing or navigating. // This way, it's very unlikely that any new callback would get the same callbackId as an old callback. callbackId: Math.floor(Math.random() * 2000000000), callbacks: {}, callbackStatus: { NO_RESULT: 0, OK: 1, CLASS_NOT_FOUND_EXCEPTION: 2, ILLEGAL_ACCESS_EXCEPTION: 3, INSTANTIATION_EXCEPTION: 4, MALFORMED_URL_EXCEPTION: 5, IO_EXCEPTION: 6, INVALID_ACTION: 7, JSON_EXCEPTION: 8, ERROR: 9 }, /** * Called by native code when returning successful result from an action. */ callbackSuccess: function(callbackId, args) { try { cordova.callbackFromNative(callbackId, true, args.status, args.message, args.keepCallback); } catch (e) { console.log("Error in error callback: " + callbackId + " = "+e); } }, /** * Called by native code when returning error result from an action. */ callbackError: function(callbackId, args) { // TODO: Deprecate callbackSuccess and callbackError in favour of callbackFromNative. // Derive success from status. try { cordova.callbackFromNative(callbackId, false, args.status, args.message, args.keepCallback); } catch (e) { console.log("Error in error callback: " + callbackId + " = "+e); } }, /** * Called by native code when returning the result from an action. */ callbackFromNative: function(callbackId, success, status, message, keepCallback) { var callback = cordova.callbacks[callbackId]; if (callback) { if (success && status == cordova.callbackStatus.OK) { callback.success && callback.success(message); } else if (!success) { callback.fail && callback.fail(message); } // Clear callback if not expecting any more results if (!keepCallback) { delete cordova.callbacks[callbackId]; } } }, addConstructor: function(func) { channel.onCordovaReady.subscribe(function() { try { func(); } catch(e) { console.log("Failed to run constructor: " + e); } }); } }; // Register pause, resume and deviceready channels as events on document. channel.onPause = cordova.addDocumentEventHandler('pause'); channel.onResume = cordova.addDocumentEventHandler('resume'); channel.onDeviceReady = cordova.addStickyDocumentEventHandler('deviceready'); module.exports = cordova; }); // file: lib/common/argscheck.js define("cordova/argscheck", function(require, exports, module) { var exec = require('cordova/exec'); var utils = require('cordova/utils'); var moduleExports = module.exports; var typeMap = { 'A': 'Array', 'D': 'Date', 'N': 'Number', 'S': 'String', 'F': 'Function', 'O': 'Object' }; function extractParamName(callee, argIndex) { return (/.*?\((.*?)\)/).exec(callee)[1].split(', ')[argIndex]; } function checkArgs(spec, functionName, args, opt_callee) { if (!moduleExports.enableChecks) { return; } var errMsg = null; var typeName; for (var i = 0; i < spec.length; ++i) { var c = spec.charAt(i), cUpper = c.toUpperCase(), arg = args[i]; // Asterix means allow anything. if (c == '*') { continue; } typeName = utils.typeName(arg); if ((arg === null || arg === undefined) && c == cUpper) { continue; } if (typeName != typeMap[cUpper]) { errMsg = 'Expected ' + typeMap[cUpper]; break; } } if (errMsg) { errMsg += ', but got ' + typeName + '.'; errMsg = 'Wrong type for parameter "' + extractParamName(opt_callee || args.callee, i) + '" of ' + functionName + ': ' + errMsg; // Don't log when running jake test. if (typeof jasmine == 'undefined') { console.error(errMsg); } throw TypeError(errMsg); } } function getValue(value, defaultValue) { return value === undefined ? defaultValue : value; } moduleExports.checkArgs = checkArgs; moduleExports.getValue = getValue; moduleExports.enableChecks = true; }); // file: lib/common/builder.js define("cordova/builder", function(require, exports, module) { var utils = require('cordova/utils'); function each(objects, func, context) { for (var prop in objects) { if (objects.hasOwnProperty(prop)) { func.apply(context, [objects[prop], prop]); } } } function clobber(obj, key, value) { exports.replaceHookForTesting(obj, key); obj[key] = value; // Getters can only be overridden by getters. if (obj[key] !== value) { utils.defineGetter(obj, key, function() { return value; }); } } function assignOrWrapInDeprecateGetter(obj, key, value, message) { if (message) { utils.defineGetter(obj, key, function() { console.log(message); delete obj[key]; clobber(obj, key, value); return value; }); } else { clobber(obj, key, value); } } function include(parent, objects, clobber, merge) { each(objects, function (obj, key) { try { var result = obj.path ? require(obj.path) : {}; if (clobber) { // Clobber if it doesn't exist. if (typeof parent[key] === 'undefined') { assignOrWrapInDeprecateGetter(parent, key, result, obj.deprecated); } else if (typeof obj.path !== 'undefined') { // If merging, merge properties onto parent, otherwise, clobber. if (merge) { recursiveMerge(parent[key], result); } else { assignOrWrapInDeprecateGetter(parent, key, result, obj.deprecated); } } result = parent[key]; } else { // Overwrite if not currently defined. if (typeof parent[key] == 'undefined') { assignOrWrapInDeprecateGetter(parent, key, result, obj.deprecated); } else { // Set result to what already exists, so we can build children into it if they exist. result = parent[key]; } } if (obj.children) { include(result, obj.children, clobber, merge); } } catch(e) { utils.alert('Exception building cordova JS globals: ' + e + ' for key "' + key + '"'); } }); } /** * Merge properties from one object onto another recursively. Properties from * the src object will overwrite existing target property. * * @param target Object to merge properties into. * @param src Object to merge properties from. */ function recursiveMerge(target, src) { for (var prop in src) { if (src.hasOwnProperty(prop)) { if (target.prototype && target.prototype.constructor === target) { // If the target object is a constructor override off prototype. clobber(target.prototype, prop, src[prop]); } else { if (typeof src[prop] === 'object' && typeof target[prop] === 'object') { recursiveMerge(target[prop], src[prop]); } else { clobber(target, prop, src[prop]); } } } } } exports.buildIntoButDoNotClobber = function(objects, target) { include(target, objects, false, false); }; exports.buildIntoAndClobber = function(objects, target) { include(target, objects, true, false); }; exports.buildIntoAndMerge = function(objects, target) { include(target, objects, true, true); }; exports.recursiveMerge = recursiveMerge; exports.assignOrWrapInDeprecateGetter = assignOrWrapInDeprecateGetter; exports.replaceHookForTesting = function() {}; }); // file: lib/common/channel.js define("cordova/channel", function(require, exports, module) { var utils = require('cordova/utils'), nextGuid = 1; /** * Custom pub-sub "channel" that can have functions subscribed to it * This object is used to define and control firing of events for * cordova initialization, as well as for custom events thereafter. * * The order of events during page load and Cordova startup is as follows: * * onDOMContentLoaded* Internal event that is received when the web page is loaded and parsed. * onNativeReady* Internal event that indicates the Cordova native side is ready. * onCordovaReady* Internal event fired when all Cordova JavaScript objects have been created. * onCordovaInfoReady* Internal event fired when device properties are available. * onCordovaConnectionReady* Internal event fired when the connection property has been set. * onDeviceReady* User event fired to indicate that Cordova is ready * onResume User event fired to indicate a start/resume lifecycle event * onPause User event fired to indicate a pause lifecycle event * onDestroy* Internal event fired when app is being destroyed (User should use window.onunload event, not this one). * * The events marked with an * are sticky. Once they have fired, they will stay in the fired state. * All listeners that subscribe after the event is fired will be executed right away. * * The only Cordova events that user code should register for are: * deviceready Cordova native code is initialized and Cordova APIs can be called from JavaScript * pause App has moved to background * resume App has returned to foreground * * Listeners can be registered as: * document.addEventListener("deviceready", myDeviceReadyListener, false); * document.addEventListener("resume", myResumeListener, false); * document.addEventListener("pause", myPauseListener, false); * * The DOM lifecycle events should be used for saving and restoring state * window.onload * window.onunload * */ /** * Channel * @constructor * @param type String the channel name */ var Channel = function(type, sticky) { this.type = type; // Map of guid -> function. this.handlers = {}; // 0 = Non-sticky, 1 = Sticky non-fired, 2 = Sticky fired. this.state = sticky ? 1 : 0; // Used in sticky mode to remember args passed to fire(). this.fireArgs = null; // Used by onHasSubscribersChange to know if there are any listeners. this.numHandlers = 0; // Function that is called when the first listener is subscribed, or when // the last listener is unsubscribed. this.onHasSubscribersChange = null; }, channel = { /** * Calls the provided function only after all of the channels specified * have been fired. All channels must be sticky channels. */ join: function(h, c) { var len = c.length, i = len, f = function() { if (!(--i)) h(); }; for (var j=0; j<len; j++) { if (c[j].state === 0) { throw Error('Can only use join with sticky channels.'); } c[j].subscribe(f); } if (!len) h(); }, create: function(type) { return channel[type] = new Channel(type, false); }, createSticky: function(type) { return channel[type] = new Channel(type, true); }, /** * cordova Channels that must fire before "deviceready" is fired. */ deviceReadyChannelsArray: [], deviceReadyChannelsMap: {}, /** * Indicate that a feature needs to be initialized before it is ready to be used. * This holds up Cordova's "deviceready" event until the feature has been initialized * and Cordova.initComplete(feature) is called. * * @param feature {String} The unique feature name */ waitForInitialization: function(feature) { if (feature) { var c = channel[feature] || this.createSticky(feature); this.deviceReadyChannelsMap[feature] = c; this.deviceReadyChannelsArray.push(c); } }, /** * Indicate that initialization code has completed and the feature is ready to be used. * * @param feature {String} The unique feature name */ initializationComplete: function(feature) { var c = this.deviceReadyChannelsMap[feature]; if (c) { c.fire(); } } }; function forceFunction(f) { if (typeof f != 'function') throw "Function required as first argument!"; } /** * Subscribes the given function to the channel. Any time that * Channel.fire is called so too will the function. * Optionally specify an execution context for the function * and a guid that can be used to stop subscribing to the channel. * Returns the guid. */ Channel.prototype.subscribe = function(f, c) { // need a function to call forceFunction(f); if (this.state == 2) { f.apply(c || this, this.fireArgs); return; } var func = f, guid = f.observer_guid; if (typeof c == "object") { func = utils.close(c, f); } if (!guid) { // first time any channel has seen this subscriber guid = '' + nextGuid++; } func.observer_guid = guid; f.observer_guid = guid; // Don't add the same handler more than once. if (!this.handlers[guid]) { this.handlers[guid] = func; this.numHandlers++; if (this.numHandlers == 1) { this.onHasSubscribersChange && this.onHasSubscribersChange(); } } }; /** * Unsubscribes the function with the given guid from the channel. */ Channel.prototype.unsubscribe = function(f) { // need a function to unsubscribe forceFunction(f); var guid = f.observer_guid, handler = this.handlers[guid]; if (handler) { delete this.handlers[guid]; this.numHandlers--; if (this.numHandlers === 0) { this.onHasSubscribersChange && this.onHasSubscribersChange(); } } }; /** * Calls all functions subscribed to this channel. */ Channel.prototype.fire = function(e) { var fail = false, fireArgs = Array.prototype.slice.call(arguments); // Apply stickiness. if (this.state == 1) { this.state = 2; this.fireArgs = fireArgs; } if (this.numHandlers) { // Copy the values first so that it is safe to modify it from within // callbacks. var toCall = []; for (var item in this.handlers) { toCall.push(this.handlers[item]); } for (var i = 0; i < toCall.length; ++i) { toCall[i].apply(this, fireArgs); } if (this.state == 2 && this.numHandlers) { this.numHandlers = 0; this.handlers = {}; this.onHasSubscribersChange && this.onHasSubscribersChange(); } } }; // defining them here so they are ready super fast! // DOM event that is received when the web page is loaded and parsed. channel.createSticky('onDOMContentLoaded'); // Event to indicate the Cordova native side is ready. channel.createSticky('onNativeReady'); // Event to indicate that all Cordova JavaScript objects have been created // and it's time to run plugin constructors. channel.createSticky('onCordovaReady'); // Event to indicate that device properties are available channel.createSticky('onCordovaInfoReady'); // Event to indicate that the connection property has been set. channel.createSticky('onCordovaConnectionReady'); // Event to indicate that Cordova is ready channel.createSticky('onDeviceReady'); // Event to indicate a resume lifecycle event channel.create('onResume'); // Event to indicate a pause lifecycle event channel.create('onPause'); // Event to indicate a destroy lifecycle event channel.createSticky('onDestroy'); // Channels that must fire before "deviceready" is fired. channel.waitForInitialization('onCordovaReady'); channel.waitForInitialization('onCordovaConnectionReady'); module.exports = channel; }); // file: lib/common/commandProxy.js define("cordova/commandProxy", function(require, exports, module) { // internal map of proxy function var CommandProxyMap = {}; module.exports = { // example: cordova.commandProxy.add("Accelerometer",{getCurrentAcceleration: function(successCallback, errorCallback, options) {...},...); add:function(id,proxyObj) { console.log("adding proxy for " + id); CommandProxyMap[id] = proxyObj; return proxyObj; }, // cordova.commandProxy.remove("Accelerometer"); remove:function(id) { var proxy = CommandProxyMap[id]; delete CommandProxyMap[id]; CommandProxyMap[id] = null; return proxy; }, get:function(service,action) { return ( CommandProxyMap[service] ? CommandProxyMap[service][action] : null ); } }; }); // file: lib/android/exec.js define("cordova/exec", function(require, exports, module) { /** * Execute a cordova command. It is up to the native side whether this action * is synchronous or asynchronous. The native side can return: * Synchronous: PluginResult object as a JSON string * Asynchronous: Empty string "" * If async, the native side will cordova.callbackSuccess or cordova.callbackError, * depending upon the result of the action. * * @param {Function} success The success callback * @param {Function} fail The fail callback * @param {String} service The name of the service to use * @param {String} action Action to be run in cordova * @param {String[]} [args] Zero or more arguments to pass to the method */ var cordova = require('cordova'), nativeApiProvider = require('cordova/plugin/android/nativeapiprovider'), utils = require('cordova/utils'), jsToNativeModes = { PROMPT: 0, JS_OBJECT: 1, // This mode is currently for benchmarking purposes only. It must be enabled // on the native side through the ENABLE_LOCATION_CHANGE_EXEC_MODE // constant within CordovaWebViewClient.java before it will work. LOCATION_CHANGE: 2 }, nativeToJsModes = { // Polls for messages using the JS->Native bridge. POLLING: 0, // For LOAD_URL to be viable, it would need to have a work-around for // the bug where the soft-keyboard gets dismissed when a message is sent. LOAD_URL: 1, // For the ONLINE_EVENT to be viable, it would need to intercept all event // listeners (both through addEventListener and window.ononline) as well // as set the navigator property itself. ONLINE_EVENT: 2, // Uses reflection to access private APIs of the WebView that can send JS // to be executed. // Requires Android 3.2.4 or above. PRIVATE_API: 3 }, jsToNativeBridgeMode, // Set lazily. nativeToJsBridgeMode = nativeToJsModes.ONLINE_EVENT, pollEnabled = false, messagesFromNative = []; function androidExec(success, fail, service, action, args) { // Set default bridge modes if they have not already been set. // By default, we use the failsafe, since addJavascriptInterface breaks too often if (jsToNativeBridgeMode === undefined) { androidExec.setJsToNativeBridgeMode(jsToNativeModes.JS_OBJECT); } // Process any ArrayBuffers in the args into a string. for (var i = 0; i < args.length; i++) { if (utils.typeName(args[i]) == 'ArrayBuffer') { args[i] = window.btoa(String.fromCharCode.apply(null, new Uint8Array(args[i]))); } } var callbackId = service + cordova.callbackId++, argsJson = JSON.stringify(args), returnValue; // TODO: Returning the payload of a synchronous call was deprecated in 2.2.0. // Remove it after 6 months. function captureReturnValue(value) { returnValue = value; success && success(value); } cordova.callbacks[callbackId] = {success:captureReturnValue, fail:fail}; if (jsToNativeBridgeMode == jsToNativeModes.LOCATION_CHANGE) { window.location = 'http://cdv_exec/' + service + '#' + action + '#' + callbackId + '#' + argsJson; } else { var messages = nativeApiProvider.get().exec(service, action, callbackId, argsJson); androidExec.processMessages(messages); } if (cordova.callbacks[callbackId]) { if (success || fail) { cordova.callbacks[callbackId].success = success; } else { delete cordova.callbacks[callbackId]; } } return returnValue; } function pollOnce() { var msg = nativeApiProvider.get().retrieveJsMessages(); androidExec.processMessages(msg); } function pollingTimerFunc() { if (pollEnabled) { pollOnce(); setTimeout(pollingTimerFunc, 50); } } function hookOnlineApis() { function proxyEvent(e) { cordova.fireWindowEvent(e.type); } // The network module takes care of firing online and offline events. // It currently fires them only on document though, so we bridge them // to window here (while first listening for exec()-releated online/offline // events). window.addEventListener('online', pollOnce, false); window.addEventListener('offline', pollOnce, false); cordova.addWindowEventHandler('online'); cordova.addWindowEventHandler('offline'); document.addEventListener('online', proxyEvent, false); document.addEventListener('offline', proxyEvent, false); } hookOnlineApis(); androidExec.jsToNativeModes = jsToNativeModes; androidExec.nativeToJsModes = nativeToJsModes; androidExec.setJsToNativeBridgeMode = function(mode) { if (mode == jsToNativeModes.JS_OBJECT && !window._cordovaNative) { console.log('Falling back on PROMPT mode since _cordovaNative is missing.'); mode = jsToNativeModes.PROMPT; } nativeApiProvider.setPreferPrompt(mode == jsToNativeModes.PROMPT); jsToNativeBridgeMode = mode; }; androidExec.setNativeToJsBridgeMode = function(mode) { if (mode == nativeToJsBridgeMode) { return; } if (nativeToJsBridgeMode == nativeToJsModes.POLLING) { pollEnabled = false; } nativeToJsBridgeMode = mode; // Tell the native side to switch modes. nativeApiProvider.get().setNativeToJsBridgeMode(mode); if (mode == nativeToJsModes.POLLING) { pollEnabled = true; setTimeout(pollingTimerFunc, 1); } }; // Processes a single message, as encoded by NativeToJsMessageQueue.java. function processMessage(message) { try { var firstChar = message.charAt(0); if (firstChar == 'J') { eval(message.slice(1)); } else if (firstChar == 'S' || firstChar == 'F') { var success = firstChar == 'S'; var keepCallback = message.charAt(1) == '1'; var spaceIdx = message.indexOf(' ', 2); var status = +message.slice(2, spaceIdx); var nextSpaceIdx = message.indexOf(' ', spaceIdx + 1); var callbackId = message.slice(spaceIdx + 1, nextSpaceIdx); var payloadKind = message.charAt(nextSpaceIdx + 1); var payload; if (payloadKind == 's') { payload = message.slice(nextSpaceIdx + 2); } else if (payloadKind == 't') { payload = true; } else if (payloadKind == 'f') { payload = false; } else if (payloadKind == 'N') { payload = null; } else if (payloadKind == 'n') { payload = +message.slice(nextSpaceIdx + 2); } else if (payloadKind == 'A') { var data = message.slice(nextSpaceIdx + 2); var bytes = window.atob(data); var arraybuffer = new Uint8Array(bytes.length); for (var i = 0; i < bytes.length; i++) { arraybuffer[i] = bytes.charCodeAt(i); } payload = arraybuffer.buffer; } else { payload = JSON.parse(message.slice(nextSpaceIdx + 1)); } cordova.callbackFromNative(callbackId, success, status, payload, keepCallback); } else { console.log("processMessage failed: invalid message:" + message); } } catch (e) { console.log("processMessage failed: Message: " + message); console.log("processMessage failed: Error: " + e); console.log("processMessage failed: Stack: " + e.stack); } } // This is called from the NativeToJsMessageQueue.java. androidExec.processMessages = function(messages) { if (messages) { messagesFromNative.push(messages); while (messagesFromNative.length) { messages = messagesFromNative.shift(); // The Java side can send a * message to indicate that it // still has messages waiting to be retrieved. // TODO(agrieve): This is currently disabled on the Java side // since it breaks returning the result in exec of synchronous // plugins. Once we remove this ability, we can remove this comment. if (messages == '*') { window.setTimeout(pollOnce, 0); continue; } var spaceIdx = messages.indexOf(' '); var msgLen = +messages.slice(0, spaceIdx); var message = messages.substr(spaceIdx + 1, msgLen); messages = messages.slice(spaceIdx + msgLen + 1); // Put the remaining messages back into queue in case an exec() // is made by the callback. if (messages) { messagesFromNative.unshift(messages); } if (message) { processMessage(message); } } } }; module.exports = androidExec; }); // file: lib/common/modulemapper.js define("cordova/modulemapper", function(require, exports, module) { var builder = require('cordova/builder'), moduleMap = define.moduleMap, symbolList, deprecationMap; exports.reset = function() { symbolList = []; deprecationMap = {}; }; function addEntry(strategy, moduleName, symbolPath, opt_deprecationMessage) { if (!(moduleName in moduleMap)) { throw new Error('Module ' + moduleName + ' does not exist.'); } symbolList.push(strategy, moduleName, symbolPath); if (opt_deprecationMessage) { deprecationMap[symbolPath] = opt_deprecationMessage; } } // Note: Android 2.3 does have Function.bind(). exports.clobbers = function(moduleName, symbolPath, opt_deprecationMessage) { addEntry('c', moduleName, symbolPath, opt_deprecationMessage); }; exports.merges = function(moduleName, symbolPath, opt_deprecationMessage) { addEntry('m', moduleName, symbolPath, opt_deprecationMessage); }; exports.defaults = function(moduleName, symbolPath, opt_deprecationMessage) { addEntry('d', moduleName, symbolPath, opt_deprecationMessage); }; function prepareNamespace(symbolPath, context) { if (!symbolPath) { return context; } var parts = symbolPath.split('.'); var cur = context; for (var i = 0, part; part = parts[i]; ++i) { cur = cur[part] = cur[part] || {}; } return cur; } exports.mapModules = function(context) { var origSymbols = {}; context.CDV_origSymbols = origSymbols; for (var i = 0, len = symbolList.length; i < len; i += 3) { var strategy = symbolList[i]; var moduleName = symbolList[i + 1]; var symbolPath = symbolList[i + 2]; var lastDot = symbolPath.lastIndexOf('.'); var namespace = symbolPath.substr(0, lastDot); var lastName = symbolPath.substr(lastDot + 1); var module = require(moduleName); var deprecationMsg = symbolPath in deprecationMap ? 'Access made to deprecated symbol: ' + symbolPath + '. ' + deprecationMsg : null; var parentObj = prepareNamespace(namespace, context); var target = parentObj[lastName]; if (strategy == 'm' && target) { builder.recursiveMerge(target, module); } else if ((strategy == 'd' && !target) || (strategy != 'd')) { if (!(symbolPath in origSymbols)) { origSymbols[symbolPath] = target; } builder.assignOrWrapInDeprecateGetter(parentObj, lastName, module, deprecationMsg); } } }; exports.getOriginalSymbol = function(context, symbolPath) { var origSymbols = context.CDV_origSymbols; if (origSymbols && (symbolPath in origSymbols)) { return origSymbols[symbolPath]; } var parts = symbolPath.split('.'); var obj = context; for (var i = 0; i < parts.length; ++i) { obj = obj && obj[parts[i]]; } return obj; }; exports.loadMatchingModules = function(matchingRegExp) { for (var k in moduleMap) { if (matchingRegExp.exec(k)) { require(k); } } }; exports.reset(); }); // file: lib/android/platform.js define("cordova/platform", function(require, exports, module) { module.exports = { id: "android", initialize:function() { var channel = require("cordova/channel"), cordova = require('cordova'), exec = require('cordova/exec'), modulemapper = require('cordova/modulemapper'); modulemapper.loadMatchingModules(/cordova.*\/symbols$/); modulemapper.clobbers('cordova/plugin/android/app', 'navigator.app'); modulemapper.mapModules(window); // Inject a listener for the backbutton on the document. var backButtonChannel = cordova.addDocumentEventHandler('backbutton'); backButtonChannel.onHasSubscribersChange = function() { // If we just attached the first handler or detached the last handler, // let native know we need to override the back button. exec(null, null, "App", "overrideBackbutton", [this.numHandlers == 1]); }; // Add hardware MENU and SEARCH button handlers cordova.addDocumentEventHandler('menubutton'); cordova.addDocumentEventHandler('searchbutton'); // Let native code know we are all done on the JS side. // Native code will then un-hide the WebView. channel.join(function() { exec(null, null, "App", "show", []); }, [channel.onCordovaReady]); } }; }); // file: lib/common/plugin/Acceleration.js define("cordova/plugin/Acceleration", function(require, exports, module) { var Acceleration = function(x, y, z, timestamp) { this.x = x; this.y = y; this.z = z; this.timestamp = timestamp || (new Date()).getTime(); }; module.exports = Acceleration; }); // file: lib/common/plugin/Camera.js define("cordova/plugin/Camera", function(require, exports, module) { var argscheck = require('cordova/argscheck'), exec = require('cordova/exec'), Camera = require('cordova/plugin/CameraConstants'), CameraPopoverHandle = require('cordova/plugin/CameraPopoverHandle'); var cameraExport = {}; // Tack on the Camera Constants to the base camera plugin. for (var key in Camera) { cameraExport[key] = Camera[key]; } /** * Gets a picture from source defined by "options.sourceType", and returns the * image as defined by the "options.destinationType" option. * The defaults are sourceType=CAMERA and destinationType=FILE_URI. * * @param {Function} successCallback * @param {Function} errorCallback * @param {Object} options */ cameraExport.getPicture = function(successCallback, errorCallback, options) { argscheck.checkArgs('fFO', 'Camera.getPicture', arguments); options = options || {}; var getValue = argscheck.getValue; var quality = getValue(options.quality, 50); var destinationType = getValue(options.destinationType, Camera.DestinationType.FILE_URI); var sourceType = getValue(options.sourceType, Camera.PictureSourceType.CAMERA); var targetWidth = getValue(options.targetWidth, -1); var targetHeight = getValue(options.targetHeight, -1); var encodingType = getValue(options.encodingType, Camera.EncodingType.JPEG); var mediaType = getValue(options.mediaType, Camera.MediaType.PICTURE); var allowEdit = !!options.allowEdit; var correctOrientation = !!options.correctOrientation; var saveToPhotoAlbum = !!options.saveToPhotoAlbum; var popoverOptions = getValue(options.popoverOptions, null); var args = [quality, destinationType, sourceType, targetWidth, targetHeight, encodingType, mediaType, allowEdit, correctOrientation, saveToPhotoAlbum, popoverOptions]; exec(successCallback, errorCallback, "Camera", "takePicture", args); return new CameraPopoverHandle(); }; cameraExport.cleanup = function(successCallback, errorCallback) { exec(successCallback, errorCallback, "Camera", "cleanup", []); }; module.exports = cameraExport; }); // file: lib/common/plugin/CameraConstants.js define("cordova/plugin/CameraConstants", function(require, exports, module) { module.exports = { DestinationType:{ DATA_URL: 0, // Return base64 encoded string FILE_URI: 1, // Return file uri (content://media/external/images/media/2 for Android) NATIVE_URI: 2 // Return native uri (eg. asset-library://... for iOS) }, EncodingType:{ JPEG: 0, // Return JPEG encoded image PNG: 1 // Return PNG encoded image }, MediaType:{ PICTURE: 0, // allow selection of still pictures only. DEFAULT. Will return format specified via DestinationType VIDEO: 1, // allow selection of video only, ONLY RETURNS URL ALLMEDIA : 2 // allow selection from all media types }, PictureSourceType:{ PHOTOLIBRARY : 0, // Choose image from picture library (same as SAVEDPHOTOALBUM for Android) CAMERA : 1, // Take picture from camera SAVEDPHOTOALBUM : 2 // Choose image from picture library (same as PHOTOLIBRARY for Android) }, PopoverArrowDirection:{ ARROW_UP : 1, // matches iOS UIPopoverArrowDirection constants to specify arrow location on popover ARROW_DOWN : 2, ARROW_LEFT : 4, ARROW_RIGHT : 8, ARROW_ANY : 15 } }; }); // file: lib/common/plugin/CameraPopoverHandle.js define("cordova/plugin/CameraPopoverHandle", function(require, exports, module) { var exec = require('cordova/exec'); /** * A handle to an image picker popover. */ var CameraPopoverHandle = function() { this.setPosition = function(popoverOptions) { console.log('CameraPopoverHandle.setPosition is only supported on iOS.'); }; }; module.exports = CameraPopoverHandle; }); // file: lib/common/plugin/CameraPopoverOptions.js define("cordova/plugin/CameraPopoverOptions", function(require, exports, module) { var Camera = require('cordova/plugin/CameraConstants'); /** * Encapsulates options for iOS Popover image picker */ var CameraPopoverOptions = function(x,y,width,height,arrowDir){ // information of rectangle that popover should be anchored to this.x = x || 0; this.y = y || 32; this.width = width || 320; this.height = height || 480; // The direction of the popover arrow this.arrowDir = arrowDir || Camera.PopoverArrowDirection.ARROW_ANY; }; module.exports = CameraPopoverOptions; }); // file: lib/common/plugin/CaptureAudioOptions.js define("cordova/plugin/CaptureAudioOptions", function(require, exports, module) { /** * Encapsulates all audio capture operation configuration options. */ var CaptureAudioOptions = function(){ // Upper limit of sound clips user can record. Value must be equal or greater than 1. this.limit = 1; // Maximum duration of a single sound clip in seconds. this.duration = 0; // The selected audio mode. Must match with one of the elements in supportedAudioModes array. this.mode = null; }; module.exports = CaptureAudioOptions; }); // file: lib/common/plugin/CaptureError.js define("cordova/plugin/CaptureError", function(require, exports, module) { /** * The CaptureError interface encapsulates all errors in the Capture API. */ var CaptureError = function(c) { this.code = c || null; }; // Camera or microphone failed to capture image or sound. CaptureError.CAPTURE_INTERNAL_ERR = 0; // Camera application or audio capture application is currently serving other capture request. CaptureError.CAPTURE_APPLICATION_BUSY = 1; // Invalid use of the API (e.g. limit parameter has value less than one). CaptureError.CAPTURE_INVALID_ARGUMENT = 2; // User exited camera application or audio capture application before capturing anything. CaptureError.CAPTURE_NO_MEDIA_FILES = 3; // The requested capture operation is not supported. CaptureError.CAPTURE_NOT_SUPPORTED = 20; module.exports = CaptureError; }); // file: lib/common/plugin/CaptureImageOptions.js define("cordova/plugin/CaptureImageOptions", function(require, exports, module) { /** * Encapsulates all image capture operation configuration options. */ var CaptureImageOptions = function(){ // Upper limit of images user can take. Value must be equal or greater than 1. this.limit = 1; // The selected image mode. Must match with one of the elements in supportedImageModes array. this.mode = null; }; module.exports = CaptureImageOptions; }); // file: lib/common/plugin/CaptureVideoOptions.js define("cordova/plugin/CaptureVideoOptions", function(require, exports, module) { /** * Encapsulates all video capture operation configuration options. */ var CaptureVideoOptions = function(){ // Upper limit of videos user can record. Value must be equal or greater than 1. this.limit = 1; // Maximum duration of a single video clip in seconds. this.duration = 0; // The selected video mode. Must match with one of the elements in supportedVideoModes array. this.mode = null; }; module.exports = CaptureVideoOptions; }); // file: lib/common/plugin/CompassError.js define("cordova/plugin/CompassError", function(require, exports, module) { /** * CompassError. * An error code assigned by an implementation when an error has occurred * @constructor */ var CompassError = function(err) { this.code = (err !== undefined ? err : null); }; CompassError.COMPASS_INTERNAL_ERR = 0; CompassError.COMPASS_NOT_SUPPORTED = 20; module.exports = CompassError; }); // file: lib/common/plugin/CompassHeading.js define("cordova/plugin/CompassHeading", function(require, exports, module) { var CompassHeading = function(magneticHeading, trueHeading, headingAccuracy, timestamp) { this.magneticHeading = magneticHeading; this.trueHeading = trueHeading; this.headingAccuracy = headingAccuracy; this.timestamp = timestamp || new Date().getTime(); }; module.exports = CompassHeading; }); // file: lib/common/plugin/ConfigurationData.js define("cordova/plugin/ConfigurationData", function(require, exports, module) { /** * Encapsulates a set of parameters that the capture device supports. */ function ConfigurationData() { // The ASCII-encoded string in lower case representing the media type. this.type = null; // The height attribute represents height of the image or video in pixels. // In the case of a sound clip this attribute has value 0. this.height = 0; // The width attribute represents width of the image or video in pixels. // In the case of a sound clip this attribute has value 0 this.width = 0; } module.exports = ConfigurationData; }); // file: lib/common/plugin/Connection.js define("cordova/plugin/Connection", function(require, exports, module) { /** * Network status */ module.exports = { UNKNOWN: "unknown", ETHERNET: "ethernet", WIFI: "wifi", CELL_2G: "2g", CELL_3G: "3g", CELL_4G: "4g", CELL:"cellular", NONE: "none" }; }); // file: lib/common/plugin/Contact.js define("cordova/plugin/Contact", function(require, exports, module) { var argscheck = require('cordova/argscheck'), exec = require('cordova/exec'), ContactError = require('cordova/plugin/ContactError'), utils = require('cordova/utils'); /** * Converts primitives into Complex Object * Currently only used for Date fields */ function convertIn(contact) { var value = contact.birthday; try { contact.birthday = new Date(parseFloat(value)); } catch (exception){ console.log("Cordova Contact convertIn error: exception creating date."); } return contact; } /** * Converts Complex objects into primitives * Only conversion at present is for Dates. **/ function convertOut(contact) { var value = contact.birthday; if (value !== null) { // try to make it a Date object if it is not already if (!utils.isDate(value)){ try { value = new Date(value); } catch(exception){ value = null; } } if (utils.isDate(value)){ value = value.valueOf(); // convert to milliseconds } contact.birthday = value; } return contact; } /** * Contains information about a single contact. * @constructor * @param {DOMString} id unique identifier * @param {DOMString} displayName * @param {ContactName} name * @param {DOMString} nickname * @param {Array.<ContactField>} phoneNumbers array of phone numbers * @param {Array.<ContactField>} emails array of email addresses * @param {Array.<ContactAddress>} addresses array of addresses * @param {Array.<ContactField>} ims instant messaging user ids * @param {Array.<ContactOrganization>} organizations * @param {DOMString} birthday contact's birthday * @param {DOMString} note user notes about contact * @param {Array.<ContactField>} photos * @param {Array.<ContactField>} categories * @param {Array.<ContactField>} urls contact's web sites */ var Contact = function (id, displayName, name, nickname, phoneNumbers, emails, addresses, ims, organizations, birthday, note, photos, categories, urls) { this.id = id || null; this.rawId = null; this.displayName = displayName || null; this.name = name || null; // ContactName this.nickname = nickname || null; this.phoneNumbers = phoneNumbers || null; // ContactField[] this.emails = emails || null; // ContactField[] this.addresses = addresses || null; // ContactAddress[] this.ims = ims || null; // ContactField[] this.organizations = organizations || null; // ContactOrganization[] this.birthday = birthday || null; this.note = note || null; this.photos = photos || null; // ContactField[] this.categories = categories || null; // ContactField[] this.urls = urls || null; // ContactField[] }; /** * Removes contact from device storage. * @param successCB success callback * @param errorCB error callback */ Contact.prototype.remove = function(successCB, errorCB) { argscheck.checkArgs('FF', 'Contact.remove', arguments); var fail = errorCB && function(code) { errorCB(new ContactError(code)); }; if (this.id === null) { fail(ContactError.UNKNOWN_ERROR); } else { exec(successCB, fail, "Contacts", "remove", [this.id]); } }; /** * Creates a deep copy of this Contact. * With the contact ID set to null. * @return copy of this Contact */ Contact.prototype.clone = function() { var clonedContact = utils.clone(this); clonedContact.id = null; clonedContact.rawId = null; function nullIds(arr) { if (arr) { for (var i = 0; i < arr.length; ++i) { arr[i].id = null; } } } // Loop through and clear out any id's in phones, emails, etc. nullIds(clonedContact.phoneNumbers); nullIds(clonedContact.emails); nullIds(clonedContact.addresses); nullIds(clonedContact.ims); nullIds(clonedContact.organizations); nullIds(clonedContact.categories); nullIds(clonedContact.photos); nullIds(clonedContact.urls); return clonedContact; }; /** * Persists contact to device storage. * @param successCB success callback * @param errorCB error callback */ Contact.prototype.save = function(successCB, errorCB) { argscheck.checkArgs('FFO', 'Contact.save', arguments); var fail = errorCB && function(code) { errorCB(new ContactError(code)); }; var success = function(result) { if (result) { if (successCB) { var fullContact = require('cordova/plugin/contacts').create(result); successCB(convertIn(fullContact)); } } else { // no Entry object returned fail(ContactError.UNKNOWN_ERROR); } }; var dupContact = convertOut(utils.clone(this)); exec(success, fail, "Contacts", "save", [dupContact]); }; module.exports = Contact; }); // file: lib/common/plugin/ContactAddress.js define("cordova/plugin/ContactAddress", function(require, exports, module) { /** * Contact address. * @constructor * @param {DOMString} id unique identifier, should only be set by native code * @param formatted // NOTE: not a W3C standard * @param streetAddress * @param locality * @param region * @param postalCode * @param country */ var ContactAddress = function(pref, type, formatted, streetAddress, locality, region, postalCode, country) { this.id = null; this.pref = (typeof pref != 'undefined' ? pref : false); this.type = type || null; this.formatted = formatted || null; this.streetAddress = streetAddress || null; this.locality = locality || null; this.region = region || null; this.postalCode = postalCode || null; this.country = country || null; }; module.exports = ContactAddress; }); // file: lib/common/plugin/ContactError.js define("cordova/plugin/ContactError", function(require, exports, module) { /** * ContactError. * An error code assigned by an implementation when an error has occurred * @constructor */ var ContactError = function(err) { this.code = (typeof err != 'undefined' ? err : null); }; /** * Error codes */ ContactError.UNKNOWN_ERROR = 0; ContactError.INVALID_ARGUMENT_ERROR = 1; ContactError.TIMEOUT_ERROR = 2; ContactError.PENDING_OPERATION_ERROR = 3; ContactError.IO_ERROR = 4; ContactError.NOT_SUPPORTED_ERROR = 5; ContactError.PERMISSION_DENIED_ERROR = 20; module.exports = ContactError; }); // file: lib/common/plugin/ContactField.js define("cordova/plugin/ContactField", function(require, exports, module) { /** * Generic contact field. * @constructor * @param {DOMString} id unique identifier, should only be set by native code // NOTE: not a W3C standard * @param type * @param value * @param pref */ var ContactField = function(type, value, pref) { this.id = null; this.type = (type && type.toString()) || null; this.value = (value && value.toString()) || null; this.pref = (typeof pref != 'undefined' ? pref : false); }; module.exports = ContactField; }); // file: lib/common/plugin/ContactFindOptions.js define("cordova/plugin/ContactFindOptions", function(require, exports, module) { /** * ContactFindOptions. * @constructor * @param filter used to match contacts against * @param multiple boolean used to determine if more than one contact should be returned */ var ContactFindOptions = function(filter, multiple) { this.filter = filter || ''; this.multiple = (typeof multiple != 'undefined' ? multiple : false); }; module.exports = ContactFindOptions; }); // file: lib/common/plugin/ContactName.js define("cordova/plugin/ContactName", function(require, exports, module) { /** * Contact name. * @constructor * @param formatted // NOTE: not part of W3C standard * @param familyName * @param givenName * @param middle * @param prefix * @param suffix */ var ContactName = function(formatted, familyName, givenName, middle, prefix, suffix) { this.formatted = formatted || null; this.familyName = familyName || null; this.givenName = givenName || null; this.middleName = middle || null; this.honorificPrefix = prefix || null; this.honorificSuffix = suffix || null; }; module.exports = ContactName; }); // file: lib/common/plugin/ContactOrganization.js define("cordova/plugin/ContactOrganization", function(require, exports, module) { /** * Contact organization. * @constructor * @param {DOMString} id unique identifier, should only be set by native code // NOTE: not a W3C standard * @param name * @param dept * @param title * @param startDate * @param endDate * @param location * @param desc */ var ContactOrganization = function(pref, type, name, dept, title) { this.id = null; this.pref = (typeof pref != 'undefined' ? pref : false); this.type = type || null; this.name = name || null; this.department = dept || null; this.title = title || null; }; module.exports = ContactOrganization; }); // file: lib/common/plugin/Coordinates.js define("cordova/plugin/Coordinates", function(require, exports, module) { /** * This class contains position information. * @param {Object} lat * @param {Object} lng * @param {Object} alt * @param {Object} acc * @param {Object} head * @param {Object} vel * @param {Object} altacc * @constructor */ var Coordinates = function(lat, lng, alt, acc, head, vel, altacc) { /** * The latitude of the position. */ this.latitude = lat; /** * The longitude of the position, */ this.longitude = lng; /** * The accuracy of the position. */ this.accuracy = acc; /** * The altitude of the position. */ this.altitude = (alt !== undefined ? alt : null); /** * The direction the device is moving at the position. */ this.heading = (head !== undefined ? head : null); /** * The velocity with which the device is moving at the position. */ this.speed = (vel !== undefined ? vel : null); if (this.speed === 0 || this.speed === null) { this.heading = NaN; } /** * The altitude accuracy of the position. */ this.altitudeAccuracy = (altacc !== undefined) ? altacc : null; }; module.exports = Coordinates; }); // file: lib/common/plugin/DirectoryEntry.js define("cordova/plugin/DirectoryEntry", function(require, exports, module) { var argscheck = require('cordova/argscheck'), utils = require('cordova/utils'), exec = require('cordova/exec'), Entry = require('cordova/plugin/Entry'), FileError = require('cordova/plugin/FileError'), DirectoryReader = require('cordova/plugin/DirectoryReader'); /** * An interface representing a directory on the file system. * * {boolean} isFile always false (readonly) * {boolean} isDirectory always true (readonly) * {DOMString} name of the directory, excluding the path leading to it (readonly) * {DOMString} fullPath the absolute full path to the directory (readonly) * TODO: implement this!!! {FileSystem} filesystem on which the directory resides (readonly) */ var DirectoryEntry = function(name, fullPath) { DirectoryEntry.__super__.constructor.call(this, false, true, name, fullPath); }; utils.extend(DirectoryEntry, Entry); /** * Creates a new DirectoryReader to read entries from this directory */ DirectoryEntry.prototype.createReader = function() { return new DirectoryReader(this.fullPath); }; /** * Creates or looks up a directory * * @param {DOMString} path either a relative or absolute path from this directory in which to look up or create a directory * @param {Flags} options to create or exclusively create the directory * @param {Function} successCallback is called with the new entry * @param {Function} errorCallback is called with a FileError */ DirectoryEntry.prototype.getDirectory = function(path, options, successCallback, errorCallback) { argscheck.checkArgs('sOFF', 'DirectoryEntry.getDirectory', arguments); var win = successCallback && function(result) { var entry = new DirectoryEntry(result.name, result.fullPath); successCallback(entry); }; var fail = errorCallback && function(code) { errorCallback(new FileError(code)); }; exec(win, fail, "File", "getDirectory", [this.fullPath, path, options]); }; /** * Deletes a directory and all of it's contents * * @param {Function} successCallback is called with no parameters * @param {Function} errorCallback is called with a FileError */ DirectoryEntry.prototype.removeRecursively = function(successCallback, errorCallback) { argscheck.checkArgs('FF', 'DirectoryEntry.removeRecursively', arguments); var fail = errorCallback && function(code) { errorCallback(new FileError(code)); }; exec(successCallback, fail, "File", "removeRecursively", [this.fullPath]); }; /** * Creates or looks up a file * * @param {DOMString} path either a relative or absolute path from this directory in which to look up or create a file * @param {Flags} options to create or exclusively create the file * @param {Function} successCallback is called with the new entry * @param {Function} errorCallback is called with a FileError */ DirectoryEntry.prototype.getFile = function(path, options, successCallback, errorCallback) { argscheck.checkArgs('sOFF', 'DirectoryEntry.getFile', arguments); var win = successCallback && function(result) { var FileEntry = require('cordova/plugin/FileEntry'); var entry = new FileEntry(result.name, result.fullPath); successCallback(entry); }; var fail = errorCallback && function(code) { errorCallback(new FileError(code)); }; exec(win, fail, "File", "getFile", [this.fullPath, path, options]); }; module.exports = DirectoryEntry; }); // file: lib/common/plugin/DirectoryReader.js define("cordova/plugin/DirectoryReader", function(require, exports, module) { var exec = require('cordova/exec'), FileError = require('cordova/plugin/FileError') ; /** * An interface that lists the files and directories in a directory. */ function DirectoryReader(path) { this.path = path || null; } /** * Returns a list of entries from a directory. * * @param {Function} successCallback is called with a list of entries * @param {Function} errorCallback is called with a FileError */ DirectoryReader.prototype.readEntries = function(successCallback, errorCallback) { var win = typeof successCallback !== 'function' ? null : function(result) { var retVal = []; for (var i=0; i<result.length; i++) { var entry = null; if (result[i].isDirectory) { entry = new (require('cordova/plugin/DirectoryEntry'))(); } else if (result[i].isFile) { entry = new (require('cordova/plugin/FileEntry'))(); } entry.isDirectory = result[i].isDirectory; entry.isFile = result[i].isFile; entry.name = result[i].name; entry.fullPath = result[i].fullPath; retVal.push(entry); } successCallback(retVal); }; var fail = typeof errorCallback !== 'function' ? null : function(code) { errorCallback(new FileError(code)); }; exec(win, fail, "File", "readEntries", [this.path]); }; module.exports = DirectoryReader; }); // file: lib/common/plugin/Entry.js define("cordova/plugin/Entry", function(require, exports, module) { var argscheck = require('cordova/argscheck'), exec = require('cordova/exec'), FileError = require('cordova/plugin/FileError'), Metadata = require('cordova/plugin/Metadata'); /** * Represents a file or directory on the local file system. * * @param isFile * {boolean} true if Entry is a file (readonly) * @param isDirectory * {boolean} true if Entry is a directory (readonly) * @param name * {DOMString} name of the file or directory, excluding the path * leading to it (readonly) * @param fullPath * {DOMString} the absolute full path to the file or directory * (readonly) */ function Entry(isFile, isDirectory, name, fullPath, fileSystem) { this.isFile = !!isFile; this.isDirectory = !!isDirectory; this.name = name || ''; this.fullPath = fullPath || ''; this.filesystem = fileSystem || null; } /** * Look up the metadata of the entry. * * @param successCallback * {Function} is called with a Metadata object * @param errorCallback * {Function} is called with a FileError */ Entry.prototype.getMetadata = function(successCallback, errorCallback) { argscheck.checkArgs('FF', 'Entry.getMetadata', arguments); var success = successCallback && function(lastModified) { var metadata = new Metadata(lastModified); successCallback(metadata); }; var fail = errorCallback && function(code) { errorCallback(new FileError(code)); }; exec(success, fail, "File", "getMetadata", [this.fullPath]); }; /** * Set the metadata of the entry. * * @param successCallback * {Function} is called with a Metadata object * @param errorCallback * {Function} is called with a FileError * @param metadataObject * {Object} keys and values to set */ Entry.prototype.setMetadata = function(successCallback, errorCallback, metadataObject) { argscheck.checkArgs('FFO', 'Entry.setMetadata', arguments); exec(successCallback, errorCallback, "File", "setMetadata", [this.fullPath, metadataObject]); }; /** * Move a file or directory to a new location. * * @param parent * {DirectoryEntry} the directory to which to move this entry * @param newName * {DOMString} new name of the entry, defaults to the current name * @param successCallback * {Function} called with the new DirectoryEntry object * @param errorCallback * {Function} called with a FileError */ Entry.prototype.moveTo = function(parent, newName, successCallback, errorCallback) { argscheck.checkArgs('oSFF', 'Entry.moveTo', arguments); var fail = errorCallback && function(code) { errorCallback(new FileError(code)); }; // source path var srcPath = this.fullPath, // entry name name = newName || this.name, success = function(entry) { if (entry) { if (successCallback) { // create appropriate Entry object var result = (entry.isDirectory) ? new (require('cordova/plugin/DirectoryEntry'))(entry.name, entry.fullPath) : new (require('cordova/plugin/FileEntry'))(entry.name, entry.fullPath); successCallback(result); } } else { // no Entry object returned fail && fail(FileError.NOT_FOUND_ERR); } }; // copy exec(success, fail, "File", "moveTo", [srcPath, parent.fullPath, name]); }; /** * Copy a directory to a different location. * * @param parent * {DirectoryEntry} the directory to which to copy the entry * @param newName * {DOMString} new name of the entry, defaults to the current name * @param successCallback * {Function} called with the new Entry object * @param errorCallback * {Function} called with a FileError */ Entry.prototype.copyTo = function(parent, newName, successCallback, errorCallback) { argscheck.checkArgs('oSFF', 'Entry.copyTo', arguments); var fail = errorCallback && function(code) { errorCallback(new FileError(code)); }; // source path var srcPath = this.fullPath, // entry name name = newName || this.name, // success callback success = function(entry) { if (entry) { if (successCallback) { // create appropriate Entry object var result = (entry.isDirectory) ? new (require('cordova/plugin/DirectoryEntry'))(entry.name, entry.fullPath) : new (require('cordova/plugin/FileEntry'))(entry.name, entry.fullPath); successCallback(result); } } else { // no Entry object returned fail && fail(FileError.NOT_FOUND_ERR); } }; // copy exec(success, fail, "File", "copyTo", [srcPath, parent.fullPath, name]); }; /** * Return a URL that can be used to identify this entry. */ Entry.prototype.toURL = function() { // fullPath attribute contains the full URL return this.fullPath; }; /** * Returns a URI that can be used to identify this entry. * * @param {DOMString} mimeType for a FileEntry, the mime type to be used to interpret the file, when loaded through this URI. * @return uri */ Entry.prototype.toURI = function(mimeType) { console.log("DEPRECATED: Update your code to use 'toURL'"); // fullPath attribute contains the full URI return this.toURL(); }; /** * Remove a file or directory. It is an error to attempt to delete a * directory that is not empty. It is an error to attempt to delete a * root directory of a file system. * * @param successCallback {Function} called with no parameters * @param errorCallback {Function} called with a FileError */ Entry.prototype.remove = function(successCallback, errorCallback) { argscheck.checkArgs('FF', 'Entry.remove', arguments); var fail = errorCallback && function(code) { errorCallback(new FileError(code)); }; exec(successCallback, fail, "File", "remove", [this.fullPath]); }; /** * Look up the parent DirectoryEntry of this entry. * * @param successCallback {Function} called with the parent DirectoryEntry object * @param errorCallback {Function} called with a FileError */ Entry.prototype.getParent = function(successCallback, errorCallback) { argscheck.checkArgs('FF', 'Entry.getParent', arguments); var win = successCallback && function(result) { var DirectoryEntry = require('cordova/plugin/DirectoryEntry'); var entry = new DirectoryEntry(result.name, result.fullPath); successCallback(entry); }; var fail = errorCallback && function(code) { errorCallback(new FileError(code)); }; exec(win, fail, "File", "getParent", [this.fullPath]); }; module.exports = Entry; }); // file: lib/common/plugin/File.js define("cordova/plugin/File", function(require, exports, module) { /** * Constructor. * name {DOMString} name of the file, without path information * fullPath {DOMString} the full path of the file, including the name * type {DOMString} mime type * lastModifiedDate {Date} last modified date * size {Number} size of the file in bytes */ var File = function(name, fullPath, type, lastModifiedDate, size){ this.name = name || ''; this.fullPath = fullPath || null; this.type = type || null; this.lastModifiedDate = lastModifiedDate || null; this.size = size || 0; // These store the absolute start and end for slicing the file. this.start = 0; this.end = this.size; }; /** * Returns a "slice" of the file. Since Cordova Files don't contain the actual * content, this really returns a File with adjusted start and end. * Slices of slices are supported. * start {Number} The index at which to start the slice (inclusive). * end {Number} The index at which to end the slice (exclusive). */ File.prototype.slice = function(start, end) { var size = this.end - this.start; var newStart = 0; var newEnd = size; if (arguments.length) { if (start < 0) { newStart = Math.max(size + start, 0); } else { newStart = Math.min(size, start); } } if (arguments.length >= 2) { if (end < 0) { newEnd = Math.max(size + end, 0); } else { newEnd = Math.min(end, size); } } var newFile = new File(this.name, this.fullPath, this.type, this.lastModifiedData, this.size); newFile.start = this.start + newStart; newFile.end = this.start + newEnd; return newFile; }; module.exports = File; }); // file: lib/common/plugin/FileEntry.js define("cordova/plugin/FileEntry", function(require, exports, module) { var utils = require('cordova/utils'), exec = require('cordova/exec'), Entry = require('cordova/plugin/Entry'), FileWriter = require('cordova/plugin/FileWriter'), File = require('cordova/plugin/File'), FileError = require('cordova/plugin/FileError'); /** * An interface representing a file on the file system. * * {boolean} isFile always true (readonly) * {boolean} isDirectory always false (readonly) * {DOMString} name of the file, excluding the path leading to it (readonly) * {DOMString} fullPath the absolute full path to the file (readonly) * {FileSystem} filesystem on which the file resides (readonly) */ var FileEntry = function(name, fullPath) { FileEntry.__super__.constructor.apply(this, [true, false, name, fullPath]); }; utils.extend(FileEntry, Entry); /** * Creates a new FileWriter associated with the file that this FileEntry represents. * * @param {Function} successCallback is called with the new FileWriter * @param {Function} errorCallback is called with a FileError */ FileEntry.prototype.createWriter = function(successCallback, errorCallback) { this.file(function(filePointer) { var writer = new FileWriter(filePointer); if (writer.fileName === null || writer.fileName === "") { errorCallback && errorCallback(new FileError(FileError.INVALID_STATE_ERR)); } else { successCallback && successCallback(writer); } }, errorCallback); }; /** * Returns a File that represents the current state of the file that this FileEntry represents. * * @param {Function} successCallback is called with the new File object * @param {Function} errorCallback is called with a FileError */ FileEntry.prototype.file = function(successCallback, errorCallback) { var win = successCallback && function(f) { var file = new File(f.name, f.fullPath, f.type, f.lastModifiedDate, f.size); successCallback(file); }; var fail = errorCallback && function(code) { errorCallback(new FileError(code)); }; exec(win, fail, "File", "getFileMetadata", [this.fullPath]); }; module.exports = FileEntry; }); // file: lib/common/plugin/FileError.js define("cordova/plugin/FileError", function(require, exports, module) { /** * FileError */ function FileError(error) { this.code = error || null; } // File error codes // Found in DOMException FileError.NOT_FOUND_ERR = 1; FileError.SECURITY_ERR = 2; FileError.ABORT_ERR = 3; // Added by File API specification FileError.NOT_READABLE_ERR = 4; FileError.ENCODING_ERR = 5; FileError.NO_MODIFICATION_ALLOWED_ERR = 6; FileError.INVALID_STATE_ERR = 7; FileError.SYNTAX_ERR = 8; FileError.INVALID_MODIFICATION_ERR = 9; FileError.QUOTA_EXCEEDED_ERR = 10; FileError.TYPE_MISMATCH_ERR = 11; FileError.PATH_EXISTS_ERR = 12; module.exports = FileError; }); // file: lib/common/plugin/FileReader.js define("cordova/plugin/FileReader", function(require, exports, module) { var exec = require('cordova/exec'), modulemapper = require('cordova/modulemapper'), utils = require('cordova/utils'), File = require('cordova/plugin/File'), FileError = require('cordova/plugin/FileError'), ProgressEvent = require('cordova/plugin/ProgressEvent'), origFileReader = modulemapper.getOriginalSymbol(this, 'FileReader'); /** * This class reads the mobile device file system. * * For Android: * The root directory is the root of the file system. * To read from the SD card, the file name is "sdcard/my_file.txt" * @constructor */ var FileReader = function() { this._readyState = 0; this._error = null; this._result = null; this._fileName = ''; this._realReader = origFileReader ? new origFileReader() : {}; }; // States FileReader.EMPTY = 0; FileReader.LOADING = 1; FileReader.DONE = 2; utils.defineGetter(FileReader.prototype, 'readyState', function() { return this._fileName ? this._readyState : this._realReader.readyState; }); utils.defineGetter(FileReader.prototype, 'error', function() { return this._fileName ? this._error: this._realReader.error; }); utils.defineGetter(FileReader.prototype, 'result', function() { return this._fileName ? this._result: this._realReader.result; }); function defineEvent(eventName) { utils.defineGetterSetter(FileReader.prototype, eventName, function() { return this._realReader[eventName] || null; }, function(value) { this._realReader[eventName] = value; }); } defineEvent('onloadstart'); // When the read starts. defineEvent('onprogress'); // While reading (and decoding) file or fileBlob data, and reporting partial file data (progress.loaded/progress.total) defineEvent('onload'); // When the read has successfully completed. defineEvent('onerror'); // When the read has failed (see errors). defineEvent('onloadend'); // When the request has completed (either in success or failure). defineEvent('onabort'); // When the read has been aborted. For instance, by invoking the abort() method. function initRead(reader, file) { // Already loading something if (reader.readyState == FileReader.LOADING) { throw new FileError(FileError.INVALID_STATE_ERR); } reader._result = null; reader._error = null; reader._readyState = FileReader.LOADING; if (typeof file == 'string') { // Deprecated in Cordova 2.4. console.warning('Using a string argument with FileReader.readAs functions is deprecated.'); reader._fileName = file; } else if (typeof file.fullPath == 'string') { reader._fileName = file.fullPath; } else { reader._fileName = ''; return true; } reader.onloadstart && reader.onloadstart(new ProgressEvent("loadstart", {target:reader})); } /** * Abort reading file. */ FileReader.prototype.abort = function() { if (origFileReader && !this._fileName) { return this._realReader.abort(); } this._result = null; if (this._readyState == FileReader.DONE || this._readyState == FileReader.EMPTY) { return; } this._readyState = FileReader.DONE; // If abort callback if (typeof this.onabort === 'function') { this.onabort(new ProgressEvent('abort', {target:this})); } // If load end callback if (typeof this.onloadend === 'function') { this.onloadend(new ProgressEvent('loadend', {target:this})); } }; /** * Read text file. * * @param file {File} File object containing file properties * @param encoding [Optional] (see http://www.iana.org/assignments/character-sets) */ FileReader.prototype.readAsText = function(file, encoding) { if (initRead(this, file)) { return this._realReader.readAsText(file, encoding); } // Default encoding is UTF-8 var enc = encoding ? encoding : "UTF-8"; var me = this; var execArgs = [this._fileName, enc]; // Maybe add slice parameters. if (file.end < file.size) { execArgs.push(file.start, file.end); } else if (file.start > 0) { execArgs.push(file.start); } // Read file exec( // Success callback function(r) { // If DONE (cancelled), then don't do anything if (me._readyState === FileReader.DONE) { return; } // Save result me._result = r; // If onload callback if (typeof me.onload === "function") { me.onload(new ProgressEvent("load", {target:me})); } // DONE state me._readyState = FileReader.DONE; // If onloadend callback if (typeof me.onloadend === "function") { me.onloadend(new ProgressEvent("loadend", {target:me})); } }, // Error callback function(e) { // If DONE (cancelled), then don't do anything if (me._readyState === FileReader.DONE) { return; } // DONE state me._readyState = FileReader.DONE; // null result me._result = null; // Save error me._error = new FileError(e); // If onerror callback if (typeof me.onerror === "function") { me.onerror(new ProgressEvent("error", {target:me})); } // If onloadend callback if (typeof me.onloadend === "function") { me.onloadend(new ProgressEvent("loadend", {target:me})); } }, "File", "readAsText", execArgs); }; /** * Read file and return data as a base64 encoded data url. * A data url is of the form: * data:[<mediatype>][;base64],<data> * * @param file {File} File object containing file properties */ FileReader.prototype.readAsDataURL = function(file) { if (initRead(this, file)) { return this._realReader.readAsDataURL(file); } var me = this; var execArgs = [this._fileName]; // Maybe add slice parameters. if (file.end < file.size) { execArgs.push(file.start, file.end); } else if (file.start > 0) { execArgs.push(file.start); } // Read file exec( // Success callback function(r) { // If DONE (cancelled), then don't do anything if (me._readyState === FileReader.DONE) { return; } // DONE state me._readyState = FileReader.DONE; // Save result me._result = r; // If onload callback if (typeof me.onload === "function") { me.onload(new ProgressEvent("load", {target:me})); } // If onloadend callback if (typeof me.onloadend === "function") { me.onloadend(new ProgressEvent("loadend", {target:me})); } }, // Error callback function(e) { // If DONE (cancelled), then don't do anything if (me._readyState === FileReader.DONE) { return; } // DONE state me._readyState = FileReader.DONE; me._result = null; // Save error me._error = new FileError(e); // If onerror callback if (typeof me.onerror === "function") { me.onerror(new ProgressEvent("error", {target:me})); } // If onloadend callback if (typeof me.onloadend === "function") { me.onloadend(new ProgressEvent("loadend", {target:me})); } }, "File", "readAsDataURL", execArgs); }; /** * Read file and return data as a binary data. * * @param file {File} File object containing file properties */ FileReader.prototype.readAsBinaryString = function(file) { if (initRead(this, file)) { return this._realReader.readAsBinaryString(file); } // TODO - Can't return binary data to browser. console.log('method "readAsBinaryString" is not supported at this time.'); this.abort(); }; /** * Read file and return data as a binary data. * * @param file {File} File object containing file properties */ FileReader.prototype.readAsArrayBuffer = function(file) { if (initRead(this, file)) { return this._realReader.readAsArrayBuffer(file); } // TODO - Can't return binary data to browser. console.log('This method is not supported at this time.'); this.abort(); }; module.exports = FileReader; }); // file: lib/common/plugin/FileSystem.js define("cordova/plugin/FileSystem", function(require, exports, module) { var DirectoryEntry = require('cordova/plugin/DirectoryEntry'); /** * An interface representing a file system * * @constructor * {DOMString} name the unique name of the file system (readonly) * {DirectoryEntry} root directory of the file system (readonly) */ var FileSystem = function(name, root) { this.name = name || null; if (root) { this.root = new DirectoryEntry(root.name, root.fullPath); } }; module.exports = FileSystem; }); // file: lib/common/plugin/FileTransfer.js define("cordova/plugin/FileTransfer", function(require, exports, module) { var argscheck = require('cordova/argscheck'), exec = require('cordova/exec'), FileTransferError = require('cordova/plugin/FileTransferError'), ProgressEvent = require('cordova/plugin/ProgressEvent'); function newProgressEvent(result) { var pe = new ProgressEvent(); pe.lengthComputable = result.lengthComputable; pe.loaded = result.loaded; pe.total = result.total; return pe; } var idCounter = 0; /** * FileTransfer uploads a file to a remote server. * @constructor */ var FileTransfer = function() { this._id = ++idCounter; this.onprogress = null; // optional callback }; /** * Given an absolute file path, uploads a file on the device to a remote server * using a multipart HTTP request. * @param filePath {String} Full path of the file on the device * @param server {String} URL of the server to receive the file * @param successCallback (Function} Callback to be invoked when upload has completed * @param errorCallback {Function} Callback to be invoked upon error * @param options {FileUploadOptions} Optional parameters such as file name and mimetype * @param trustAllHosts {Boolean} Optional trust all hosts (e.g. for self-signed certs), defaults to false */ FileTransfer.prototype.upload = function(filePath, server, successCallback, errorCallback, options, trustAllHosts) { argscheck.checkArgs('ssFFO*', 'FileTransfer.upload', arguments); // check for options var fileKey = null; var fileName = null; var mimeType = null; var params = null; var chunkedMode = true; var headers = null; if (options) { fileKey = options.fileKey; fileName = options.fileName; mimeType = options.mimeType; headers = options.headers; if (options.chunkedMode !== null || typeof options.chunkedMode != "undefined") { chunkedMode = options.chunkedMode; } if (options.params) { params = options.params; } else { params = {}; } } var fail = errorCallback && function(e) { var error = new FileTransferError(e.code, e.source, e.target, e.http_status); errorCallback(error); }; var self = this; var win = function(result) { if (typeof result.lengthComputable != "undefined") { if (self.onprogress) { self.onprogress(newProgressEvent(result)); } } else { successCallback && successCallback(result); } }; exec(win, fail, 'FileTransfer', 'upload', [filePath, server, fileKey, fileName, mimeType, params, trustAllHosts, chunkedMode, headers, this._id]); }; /** * Downloads a file form a given URL and saves it to the specified directory. * @param source {String} URL of the server to receive the file * @param target {String} Full path of the file on the device * @param successCallback (Function} Callback to be invoked when upload has completed * @param errorCallback {Function} Callback to be invoked upon error * @param trustAllHosts {Boolean} Optional trust all hosts (e.g. for self-signed certs), defaults to false */ FileTransfer.prototype.download = function(source, target, successCallback, errorCallback, trustAllHosts) { argscheck.checkArgs('ssFF*', 'FileTransfer.download', arguments); var self = this; var win = function(result) { if (typeof result.lengthComputable != "undefined") { if (self.onprogress) { return self.onprogress(newProgressEvent(result)); } } else if (successCallback) { var entry = null; if (result.isDirectory) { entry = new (require('cordova/plugin/DirectoryEntry'))(); } else if (result.isFile) { entry = new (require('cordova/plugin/FileEntry'))(); } entry.isDirectory = result.isDirectory; entry.isFile = result.isFile; entry.name = result.name; entry.fullPath = result.fullPath; successCallback(entry); } }; var fail = errorCallback && function(e) { var error = new FileTransferError(e.code, e.source, e.target, e.http_status); errorCallback(error); }; exec(win, fail, 'FileTransfer', 'download', [source, target, trustAllHosts, this._id]); }; /** * Aborts the ongoing file transfer on this object * @param successCallback {Function} Callback to be invoked upon success * @param errorCallback {Function} Callback to be invoked upon error */ FileTransfer.prototype.abort = function(successCallback, errorCallback) { exec(successCallback, errorCallback, 'FileTransfer', 'abort', [this._id]); }; module.exports = FileTransfer; }); // file: lib/common/plugin/FileTransferError.js define("cordova/plugin/FileTransferError", function(require, exports, module) { /** * FileTransferError * @constructor */ var FileTransferError = function(code, source, target, status, body) { this.code = code || null; this.source = source || null; this.target = target || null; this.http_status = status || null; this.body = body || null; }; FileTransferError.FILE_NOT_FOUND_ERR = 1; FileTransferError.INVALID_URL_ERR = 2; FileTransferError.CONNECTION_ERR = 3; FileTransferError.ABORT_ERR = 4; module.exports = FileTransferError; }); // file: lib/common/plugin/FileUploadOptions.js define("cordova/plugin/FileUploadOptions", function(require, exports, module) { /** * Options to customize the HTTP request used to upload files. * @constructor * @param fileKey {String} Name of file request parameter. * @param fileName {String} Filename to be used by the server. Defaults to image.jpg. * @param mimeType {String} Mimetype of the uploaded file. Defaults to image/jpeg. * @param params {Object} Object with key: value params to send to the server. * @param headers {Object} Keys are header names, values are header values. Multiple * headers of the same name are not supported. */ var FileUploadOptions = function(fileKey, fileName, mimeType, params, headers) { this.fileKey = fileKey || null; this.fileName = fileName || null; this.mimeType = mimeType || null; this.params = params || null; this.headers = headers || null; }; module.exports = FileUploadOptions; }); // file: lib/common/plugin/FileUploadResult.js define("cordova/plugin/FileUploadResult", function(require, exports, module) { /** * FileUploadResult * @constructor */ var FileUploadResult = function() { this.bytesSent = 0; this.responseCode = null; this.response = null; }; module.exports = FileUploadResult; }); // file: lib/common/plugin/FileWriter.js define("cordova/plugin/FileWriter", function(require, exports, module) { var exec = require('cordova/exec'), FileError = require('cordova/plugin/FileError'), ProgressEvent = require('cordova/plugin/ProgressEvent'); /** * This class writes to the mobile device file system. * * For Android: * The root directory is the root of the file system. * To write to the SD card, the file name is "sdcard/my_file.txt" * * @constructor * @param file {File} File object containing file properties * @param append if true write to the end of the file, otherwise overwrite the file */ var FileWriter = function(file) { this.fileName = ""; this.length = 0; if (file) { this.fileName = file.fullPath || file; this.length = file.size || 0; } // default is to write at the beginning of the file this.position = 0; this.readyState = 0; // EMPTY this.result = null; // Error this.error = null; // Event handlers this.onwritestart = null; // When writing starts this.onprogress = null; // While writing the file, and reporting partial file data this.onwrite = null; // When the write has successfully completed. this.onwriteend = null; // When the request has completed (either in success or failure). this.onabort = null; // When the write has been aborted. For instance, by invoking the abort() method. this.onerror = null; // When the write has failed (see errors). }; // States FileWriter.INIT = 0; FileWriter.WRITING = 1; FileWriter.DONE = 2; /** * Abort writing file. */ FileWriter.prototype.abort = function() { // check for invalid state if (this.readyState === FileWriter.DONE || this.readyState === FileWriter.INIT) { throw new FileError(FileError.INVALID_STATE_ERR); } // set error this.error = new FileError(FileError.ABORT_ERR); this.readyState = FileWriter.DONE; // If abort callback if (typeof this.onabort === "function") { this.onabort(new ProgressEvent("abort", {"target":this})); } // If write end callback if (typeof this.onwriteend === "function") { this.onwriteend(new ProgressEvent("writeend", {"target":this})); } }; /** * Writes data to the file * * @param text to be written */ FileWriter.prototype.write = function(text) { // Throw an exception if we are already writing a file if (this.readyState === FileWriter.WRITING) { throw new FileError(FileError.INVALID_STATE_ERR); } // WRITING state this.readyState = FileWriter.WRITING; var me = this; // If onwritestart callback if (typeof me.onwritestart === "function") { me.onwritestart(new ProgressEvent("writestart", {"target":me})); } // Write file exec( // Success callback function(r) { // If DONE (cancelled), then don't do anything if (me.readyState === FileWriter.DONE) { return; } // position always increases by bytes written because file would be extended me.position += r; // The length of the file is now where we are done writing. me.length = me.position; // DONE state me.readyState = FileWriter.DONE; // If onwrite callback if (typeof me.onwrite === "function") { me.onwrite(new ProgressEvent("write", {"target":me})); } // If onwriteend callback if (typeof me.onwriteend === "function") { me.onwriteend(new ProgressEvent("writeend", {"target":me})); } }, // Error callback function(e) { // If DONE (cancelled), then don't do anything if (me.readyState === FileWriter.DONE) { return; } // DONE state me.readyState = FileWriter.DONE; // Save error me.error = new FileError(e); // If onerror callback if (typeof me.onerror === "function") { me.onerror(new ProgressEvent("error", {"target":me})); } // If onwriteend callback if (typeof me.onwriteend === "function") { me.onwriteend(new ProgressEvent("writeend", {"target":me})); } }, "File", "write", [this.fileName, text, this.position]); }; /** * Moves the file pointer to the location specified. * * If the offset is a negative number the position of the file * pointer is rewound. If the offset is greater than the file * size the position is set to the end of the file. * * @param offset is the location to move the file pointer to. */ FileWriter.prototype.seek = function(offset) { // Throw an exception if we are already writing a file if (this.readyState === FileWriter.WRITING) { throw new FileError(FileError.INVALID_STATE_ERR); } if (!offset && offset !== 0) { return; } // See back from end of file. if (offset < 0) { this.position = Math.max(offset + this.length, 0); } // Offset is bigger than file size so set position // to the end of the file. else if (offset > this.length) { this.position = this.length; } // Offset is between 0 and file size so set the position // to start writing. else { this.position = offset; } }; /** * Truncates the file to the size specified. * * @param size to chop the file at. */ FileWriter.prototype.truncate = function(size) { // Throw an exception if we are already writing a file if (this.readyState === FileWriter.WRITING) { throw new FileError(FileError.INVALID_STATE_ERR); } // WRITING state this.readyState = FileWriter.WRITING; var me = this; // If onwritestart callback if (typeof me.onwritestart === "function") { me.onwritestart(new ProgressEvent("writestart", {"target":this})); } // Write file exec( // Success callback function(r) { // If DONE (cancelled), then don't do anything if (me.readyState === FileWriter.DONE) { return; } // DONE state me.readyState = FileWriter.DONE; // Update the length of the file me.length = r; me.position = Math.min(me.position, r); // If onwrite callback if (typeof me.onwrite === "function") { me.onwrite(new ProgressEvent("write", {"target":me})); } // If onwriteend callback if (typeof me.onwriteend === "function") { me.onwriteend(new ProgressEvent("writeend", {"target":me})); } }, // Error callback function(e) { // If DONE (cancelled), then don't do anything if (me.readyState === FileWriter.DONE) { return; } // DONE state me.readyState = FileWriter.DONE; // Save error me.error = new FileError(e); // If onerror callback if (typeof me.onerror === "function") { me.onerror(new ProgressEvent("error", {"target":me})); } // If onwriteend callback if (typeof me.onwriteend === "function") { me.onwriteend(new ProgressEvent("writeend", {"target":me})); } }, "File", "truncate", [this.fileName, size]); }; module.exports = FileWriter; }); // file: lib/common/plugin/Flags.js define("cordova/plugin/Flags", function(require, exports, module) { /** * Supplies arguments to methods that lookup or create files and directories. * * @param create * {boolean} file or directory if it doesn't exist * @param exclusive * {boolean} used with create; if true the command will fail if * target path exists */ function Flags(create, exclusive) { this.create = create || false; this.exclusive = exclusive || false; } module.exports = Flags; }); // file: lib/common/plugin/GlobalizationError.js define("cordova/plugin/GlobalizationError", function(require, exports, module) { /** * Globalization error object * * @constructor * @param code * @param message */ var GlobalizationError = function(code, message) { this.code = code || null; this.message = message || ''; }; // Globalization error codes GlobalizationError.UNKNOWN_ERROR = 0; GlobalizationError.FORMATTING_ERROR = 1; GlobalizationError.PARSING_ERROR = 2; GlobalizationError.PATTERN_ERROR = 3; module.exports = GlobalizationError; }); // file: lib/common/plugin/InAppBrowser.js define("cordova/plugin/InAppBrowser", function(require, exports, module) { var exec = require('cordova/exec'); var channel = require('cordova/channel'); function InAppBrowser() { this.channels = { 'loadstart': channel.create('loadstart'), 'loadstop' : channel.create('loadstop'), 'exit' : channel.create('exit') }; } InAppBrowser.prototype = { _eventHandler: function (event) { if (event.type in this.channels) { this.channels[event.type].fire(event); } }, close: function (eventname) { exec(null, null, "InAppBrowser", "close", []); }, addEventListener: function (eventname,f) { if (eventname in this.channels) { this.channels[eventname].subscribe(f); } }, removeEventListener: function(eventname, f) { if (eventname in this.channels) { this.channels[eventname].unsubscribe(f); } } }; module.exports = function(strUrl, strWindowName, strWindowFeatures) { var iab = new InAppBrowser(); var cb = function(eventname) { iab._eventHandler(eventname); }; exec(cb, null, "InAppBrowser", "open", [strUrl, strWindowName, strWindowFeatures]); return iab; }; }); // file: lib/common/plugin/LocalFileSystem.js define("cordova/plugin/LocalFileSystem", function(require, exports, module) { var exec = require('cordova/exec'); /** * Represents a local file system. */ var LocalFileSystem = function() { }; LocalFileSystem.TEMPORARY = 0; //temporary, with no guarantee of persistence LocalFileSystem.PERSISTENT = 1; //persistent module.exports = LocalFileSystem; }); // file: lib/common/plugin/Media.js define("cordova/plugin/Media", function(require, exports, module) { var argscheck = require('cordova/argscheck'), utils = require('cordova/utils'), exec = require('cordova/exec'); var mediaObjects = {}; /** * This class provides access to the device media, interfaces to both sound and video * * @constructor * @param src The file name or url to play * @param successCallback The callback to be called when the file is done playing or recording. * successCallback() * @param errorCallback The callback to be called if there is an error. * errorCallback(int errorCode) - OPTIONAL * @param statusCallback The callback to be called when media status has changed. * statusCallback(int statusCode) - OPTIONAL */ var Media = function(src, successCallback, errorCallback, statusCallback) { argscheck.checkArgs('SFFF', 'Media', arguments); this.id = utils.createUUID(); mediaObjects[this.id] = this; this.src = src; this.successCallback = successCallback; this.errorCallback = errorCallback; this.statusCallback = statusCallback; this._duration = -1; this._position = -1; exec(null, this.errorCallback, "Media", "create", [this.id, this.src]); }; // Media messages Media.MEDIA_STATE = 1; Media.MEDIA_DURATION = 2; Media.MEDIA_POSITION = 3; Media.MEDIA_ERROR = 9; // Media states Media.MEDIA_NONE = 0; Media.MEDIA_STARTING = 1; Media.MEDIA_RUNNING = 2; Media.MEDIA_PAUSED = 3; Media.MEDIA_STOPPED = 4; Media.MEDIA_MSG = ["None", "Starting", "Running", "Paused", "Stopped"]; // "static" function to return existing objs. Media.get = function(id) { return mediaObjects[id]; }; /** * Start or resume playing audio file. */ Media.prototype.play = function(options) { exec(null, null, "Media", "startPlayingAudio", [this.id, this.src, options]); }; /** * Stop playing audio file. */ Media.prototype.stop = function() { var me = this; exec(function() { me._position = 0; }, this.errorCallback, "Media", "stopPlayingAudio", [this.id]); }; /** * Seek or jump to a new time in the track.. */ Media.prototype.seekTo = function(milliseconds) { var me = this; exec(function(p) { me._position = p; }, this.errorCallback, "Media", "seekToAudio", [this.id, milliseconds]); }; /** * Pause playing audio file. */ Media.prototype.pause = function() { exec(null, this.errorCallback, "Media", "pausePlayingAudio", [this.id]); }; /** * Get duration of an audio file. * The duration is only set for audio that is playing, paused or stopped. * * @return duration or -1 if not known. */ Media.prototype.getDuration = function() { return this._duration; }; /** * Get position of audio. */ Media.prototype.getCurrentPosition = function(success, fail) { var me = this; exec(function(p) { me._position = p; success(p); }, fail, "Media", "getCurrentPositionAudio", [this.id]); }; /** * Start recording audio file. */ Media.prototype.startRecord = function() { exec(null, this.errorCallback, "Media", "startRecordingAudio", [this.id, this.src]); }; /** * Stop recording audio file. */ Media.prototype.stopRecord = function() { exec(null, this.errorCallback, "Media", "stopRecordingAudio", [this.id]); }; /** * Release the resources. */ Media.prototype.release = function() { exec(null, this.errorCallback, "Media", "release", [this.id]); }; /** * Adjust the volume. */ Media.prototype.setVolume = function(volume) { exec(null, null, "Media", "setVolume", [this.id, volume]); }; /** * Audio has status update. * PRIVATE * * @param id The media object id (string) * @param msgType The 'type' of update this is * @param value Use of value is determined by the msgType */ Media.onStatus = function(id, msgType, value) { var media = mediaObjects[id]; if(media) { switch(msgType) { case Media.MEDIA_STATE : media.statusCallback && media.statusCallback(value); if(value == Media.MEDIA_STOPPED) { media.successCallback && media.successCallback(); } break; case Media.MEDIA_DURATION : media._duration = value; break; case Media.MEDIA_ERROR : media.errorCallback && media.errorCallback(value); break; case Media.MEDIA_POSITION : media._position = Number(value); break; default : console.error && console.error("Unhandled Media.onStatus :: " + msgType); break; } } else { console.error && console.error("Received Media.onStatus callback for unknown media :: " + id); } }; module.exports = Media; }); // file: lib/common/plugin/MediaError.js define("cordova/plugin/MediaError", function(require, exports, module) { /** * This class contains information about any Media errors. */ /* According to :: http://dev.w3.org/html5/spec-author-view/video.html#mediaerror We should never be creating these objects, we should just implement the interface which has 1 property for an instance, 'code' instead of doing : errorCallbackFunction( new MediaError(3,'msg') ); we should simply use a literal : errorCallbackFunction( {'code':3} ); */ var _MediaError = window.MediaError; if(!_MediaError) { window.MediaError = _MediaError = function(code, msg) { this.code = (typeof code != 'undefined') ? code : null; this.message = msg || ""; // message is NON-standard! do not use! }; } _MediaError.MEDIA_ERR_NONE_ACTIVE = _MediaError.MEDIA_ERR_NONE_ACTIVE || 0; _MediaError.MEDIA_ERR_ABORTED = _MediaError.MEDIA_ERR_ABORTED || 1; _MediaError.MEDIA_ERR_NETWORK = _MediaError.MEDIA_ERR_NETWORK || 2; _MediaError.MEDIA_ERR_DECODE = _MediaError.MEDIA_ERR_DECODE || 3; _MediaError.MEDIA_ERR_NONE_SUPPORTED = _MediaError.MEDIA_ERR_NONE_SUPPORTED || 4; // TODO: MediaError.MEDIA_ERR_NONE_SUPPORTED is legacy, the W3 spec now defines it as below. // as defined by http://dev.w3.org/html5/spec-author-view/video.html#error-codes _MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED = _MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED || 4; module.exports = _MediaError; }); // file: lib/common/plugin/MediaFile.js define("cordova/plugin/MediaFile", function(require, exports, module) { var utils = require('cordova/utils'), exec = require('cordova/exec'), File = require('cordova/plugin/File'), CaptureError = require('cordova/plugin/CaptureError'); /** * Represents a single file. * * name {DOMString} name of the file, without path information * fullPath {DOMString} the full path of the file, including the name * type {DOMString} mime type * lastModifiedDate {Date} last modified date * size {Number} size of the file in bytes */ var MediaFile = function(name, fullPath, type, lastModifiedDate, size){ MediaFile.__super__.constructor.apply(this, arguments); }; utils.extend(MediaFile, File); /** * Request capture format data for a specific file and type * * @param {Function} successCB * @param {Function} errorCB */ MediaFile.prototype.getFormatData = function(successCallback, errorCallback) { if (typeof this.fullPath === "undefined" || this.fullPath === null) { errorCallback(new CaptureError(CaptureError.CAPTURE_INVALID_ARGUMENT)); } else { exec(successCallback, errorCallback, "Capture", "getFormatData", [this.fullPath, this.type]); } }; module.exports = MediaFile; }); // file: lib/common/plugin/MediaFileData.js define("cordova/plugin/MediaFileData", function(require, exports, module) { /** * MediaFileData encapsulates format information of a media file. * * @param {DOMString} codecs * @param {long} bitrate * @param {long} height * @param {long} width * @param {float} duration */ var MediaFileData = function(codecs, bitrate, height, width, duration){ this.codecs = codecs || null; this.bitrate = bitrate || 0; this.height = height || 0; this.width = width || 0; this.duration = duration || 0; }; module.exports = MediaFileData; }); // file: lib/common/plugin/Metadata.js define("cordova/plugin/Metadata", function(require, exports, module) { /** * Information about the state of the file or directory * * {Date} modificationTime (readonly) */ var Metadata = function(time) { this.modificationTime = (typeof time != 'undefined'?new Date(time):null); }; module.exports = Metadata; }); // file: lib/common/plugin/Position.js define("cordova/plugin/Position", function(require, exports, module) { var Coordinates = require('cordova/plugin/Coordinates'); var Position = function(coords, timestamp) { if (coords) { this.coords = new Coordinates(coords.latitude, coords.longitude, coords.altitude, coords.accuracy, coords.heading, coords.velocity, coords.altitudeAccuracy); } else { this.coords = new Coordinates(); } this.timestamp = (timestamp !== undefined) ? timestamp : new Date(); }; module.exports = Position; }); // file: lib/common/plugin/PositionError.js define("cordova/plugin/PositionError", function(require, exports, module) { /** * Position error object * * @constructor * @param code * @param message */ var PositionError = function(code, message) { this.code = code || null; this.message = message || ''; }; PositionError.PERMISSION_DENIED = 1; PositionError.POSITION_UNAVAILABLE = 2; PositionError.TIMEOUT = 3; module.exports = PositionError; }); // file: lib/common/plugin/ProgressEvent.js define("cordova/plugin/ProgressEvent", function(require, exports, module) { // If ProgressEvent exists in global context, use it already, otherwise use our own polyfill // Feature test: See if we can instantiate a native ProgressEvent; // if so, use that approach, // otherwise fill-in with our own implementation. // // NOTE: right now we always fill in with our own. Down the road would be nice if we can use whatever is native in the webview. var ProgressEvent = (function() { /* var createEvent = function(data) { var event = document.createEvent('Events'); event.initEvent('ProgressEvent', false, false); if (data) { for (var i in data) { if (data.hasOwnProperty(i)) { event[i] = data[i]; } } if (data.target) { // TODO: cannot call <some_custom_object>.dispatchEvent // need to first figure out how to implement EventTarget } } return event; }; try { var ev = createEvent({type:"abort",target:document}); return function ProgressEvent(type, data) { data.type = type; return createEvent(data); }; } catch(e){ */ return function ProgressEvent(type, dict) { this.type = type; this.bubbles = false; this.cancelBubble = false; this.cancelable = false; this.lengthComputable = false; this.loaded = dict && dict.loaded ? dict.loaded : 0; this.total = dict && dict.total ? dict.total : 0; this.target = dict && dict.target ? dict.target : null; }; //} })(); module.exports = ProgressEvent; }); // file: lib/common/plugin/accelerometer.js define("cordova/plugin/accelerometer", function(require, exports, module) { /** * This class provides access to device accelerometer data. * @constructor */ var argscheck = require('cordova/argscheck'), utils = require("cordova/utils"), exec = require("cordova/exec"), Acceleration = require('cordova/plugin/Acceleration'); // Is the accel sensor running? var running = false; // Keeps reference to watchAcceleration calls. var timers = {}; // Array of listeners; used to keep track of when we should call start and stop. var listeners = []; // Last returned acceleration object from native var accel = null; // Tells native to start. function start() { exec(function(a) { var tempListeners = listeners.slice(0); accel = new Acceleration(a.x, a.y, a.z, a.timestamp); for (var i = 0, l = tempListeners.length; i < l; i++) { tempListeners[i].win(accel); } }, function(e) { var tempListeners = listeners.slice(0); for (var i = 0, l = tempListeners.length; i < l; i++) { tempListeners[i].fail(e); } }, "Accelerometer", "start", []); running = true; } // Tells native to stop. function stop() { exec(null, null, "Accelerometer", "stop", []); running = false; } // Adds a callback pair to the listeners array function createCallbackPair(win, fail) { return {win:win, fail:fail}; } // Removes a win/fail listener pair from the listeners array function removeListeners(l) { var idx = listeners.indexOf(l); if (idx > -1) { listeners.splice(idx, 1); if (listeners.length === 0) { stop(); } } } var accelerometer = { /** * Asynchronously acquires the current acceleration. * * @param {Function} successCallback The function to call when the acceleration data is available * @param {Function} errorCallback The function to call when there is an error getting the acceleration data. (OPTIONAL) * @param {AccelerationOptions} options The options for getting the accelerometer data such as timeout. (OPTIONAL) */ getCurrentAcceleration: function(successCallback, errorCallback, options) { argscheck.checkArgs('fFO', 'accelerometer.getCurrentAcceleration', arguments); var p; var win = function(a) { removeListeners(p); successCallback(a); }; var fail = function(e) { removeListeners(p); errorCallback && errorCallback(e); }; p = createCallbackPair(win, fail); listeners.push(p); if (!running) { start(); } }, /** * Asynchronously acquires the acceleration repeatedly at a given interval. * * @param {Function} successCallback The function to call each time the acceleration data is available * @param {Function} errorCallback The function to call when there is an error getting the acceleration data. (OPTIONAL) * @param {AccelerationOptions} options The options for getting the accelerometer data such as timeout. (OPTIONAL) * @return String The watch id that must be passed to #clearWatch to stop watching. */ watchAcceleration: function(successCallback, errorCallback, options) { argscheck.checkArgs('fFO', 'accelerometer.watchAcceleration', arguments); // Default interval (10 sec) var frequency = (options && options.frequency && typeof options.frequency == 'number') ? options.frequency : 10000; // Keep reference to watch id, and report accel readings as often as defined in frequency var id = utils.createUUID(); var p = createCallbackPair(function(){}, function(e) { removeListeners(p); errorCallback && errorCallback(e); }); listeners.push(p); timers[id] = { timer:window.setInterval(function() { if (accel) { successCallback(accel); } }, frequency), listeners:p }; if (running) { // If we're already running then immediately invoke the success callback // but only if we have retrieved a value, sample code does not check for null ... if (accel) { successCallback(accel); } } else { start(); } return id; }, /** * Clears the specified accelerometer watch. * * @param {String} id The id of the watch returned from #watchAcceleration. */ clearWatch: function(id) { // Stop javascript timer & remove from timer list if (id && timers[id]) { window.clearInterval(timers[id].timer); removeListeners(timers[id].listeners); delete timers[id]; } } }; module.exports = accelerometer; }); // file: lib/common/plugin/accelerometer/symbols.js define("cordova/plugin/accelerometer/symbols", function(require, exports, module) { var modulemapper = require('cordova/modulemapper'); modulemapper.defaults('cordova/plugin/Acceleration', 'Acceleration'); modulemapper.defaults('cordova/plugin/accelerometer', 'navigator.accelerometer'); }); // file: lib/android/plugin/android/app.js define("cordova/plugin/android/app", function(require, exports, module) { var exec = require('cordova/exec'); module.exports = { /** * Clear the resource cache. */ clearCache:function() { exec(null, null, "App", "clearCache", []); }, /** * Load the url into the webview or into new browser instance. * * @param url The URL to load * @param props Properties that can be passed in to the activity: * wait: int => wait msec before loading URL * loadingDialog: "Title,Message" => display a native loading dialog * loadUrlTimeoutValue: int => time in msec to wait before triggering a timeout error * clearHistory: boolean => clear webview history (default=false) * openExternal: boolean => open in a new browser (default=false) * * Example: * navigator.app.loadUrl("http://server/myapp/index.html", {wait:2000, loadingDialog:"Wait,Loading App", loadUrlTimeoutValue: 60000}); */ loadUrl:function(url, props) { exec(null, null, "App", "loadUrl", [url, props]); }, /** * Cancel loadUrl that is waiting to be loaded. */ cancelLoadUrl:function() { exec(null, null, "App", "cancelLoadUrl", []); }, /** * Clear web history in this web view. * Instead of BACK button loading the previous web page, it will exit the app. */ clearHistory:function() { exec(null, null, "App", "clearHistory", []); }, /** * Go to previous page displayed. * This is the same as pressing the backbutton on Android device. */ backHistory:function() { exec(null, null, "App", "backHistory", []); }, /** * Override the default behavior of the Android back button. * If overridden, when the back button is pressed, the "backKeyDown" JavaScript event will be fired. * * Note: The user should not have to call this method. Instead, when the user * registers for the "backbutton" event, this is automatically done. * * @param override T=override, F=cancel override */ overrideBackbutton:function(override) { exec(null, null, "App", "overrideBackbutton", [override]); }, /** * Exit and terminate the application. */ exitApp:function() { return exec(null, null, "App", "exitApp", []); } }; }); // file: lib/android/plugin/android/device.js define("cordova/plugin/android/device", function(require, exports, module) { var channel = require('cordova/channel'), utils = require('cordova/utils'), exec = require('cordova/exec'), app = require('cordova/plugin/android/app'); module.exports = { /* * DEPRECATED * This is only for Android. * * You must explicitly override the back button. */ overrideBackButton:function() { console.log("Device.overrideBackButton() is deprecated. Use App.overrideBackbutton(true)."); app.overrideBackbutton(true); }, /* * DEPRECATED * This is only for Android. * * This resets the back button to the default behavior */ resetBackButton:function() { console.log("Device.resetBackButton() is deprecated. Use App.overrideBackbutton(false)."); app.overrideBackbutton(false); }, /* * DEPRECATED * This is only for Android. * * This terminates the activity! */ exitApp:function() { console.log("Device.exitApp() is deprecated. Use App.exitApp()."); app.exitApp(); } }; }); // file: lib/android/plugin/android/nativeapiprovider.js define("cordova/plugin/android/nativeapiprovider", function(require, exports, module) { var nativeApi = this._cordovaNative || require('cordova/plugin/android/promptbasednativeapi'); var currentApi = nativeApi; module.exports = { get: function() { return currentApi; }, setPreferPrompt: function(value) { currentApi = value ? require('cordova/plugin/android/promptbasednativeapi') : nativeApi; }, // Used only by tests. set: function(value) { currentApi = value; } }; }); // file: lib/android/plugin/android/notification.js define("cordova/plugin/android/notification", function(require, exports, module) { var exec = require('cordova/exec'); /** * Provides Android enhanced notification API. */ module.exports = { activityStart : function(title, message) { // If title and message not specified then mimic Android behavior of // using default strings. if (typeof title === "undefined" && typeof message == "undefined") { title = "Busy"; message = 'Please wait...'; } exec(null, null, 'Notification', 'activityStart', [ title, message ]); }, /** * Close an activity dialog */ activityStop : function() { exec(null, null, 'Notification', 'activityStop', []); }, /** * Display a progress dialog with progress bar that goes from 0 to 100. * * @param {String} * title Title of the progress dialog. * @param {String} * message Message to display in the dialog. */ progressStart : function(title, message) { exec(null, null, 'Notification', 'progressStart', [ title, message ]); }, /** * Close the progress dialog. */ progressStop : function() { exec(null, null, 'Notification', 'progressStop', []); }, /** * Set the progress dialog value. * * @param {Number} * value 0-100 */ progressValue : function(value) { exec(null, null, 'Notification', 'progressValue', [ value ]); } }; }); // file: lib/android/plugin/android/promptbasednativeapi.js define("cordova/plugin/android/promptbasednativeapi", function(require, exports, module) { module.exports = { exec: function(service, action, callbackId, argsJson) { return prompt(argsJson, 'gap:'+JSON.stringify([service, action, callbackId])); }, setNativeToJsBridgeMode: function(value) { prompt(value, 'gap_bridge_mode:'); }, retrieveJsMessages: function() { return prompt('', 'gap_poll:'); } }; }); // file: lib/android/plugin/android/storage.js define("cordova/plugin/android/storage", function(require, exports, module) { var utils = require('cordova/utils'), exec = require('cordova/exec'), channel = require('cordova/channel'); var queryQueue = {}; /** * SQL result set object * PRIVATE METHOD * @constructor */ var DroidDB_Rows = function() { this.resultSet = []; // results array this.length = 0; // number of rows }; /** * Get item from SQL result set * * @param row The row number to return * @return The row object */ DroidDB_Rows.prototype.item = function(row) { return this.resultSet[row]; }; /** * SQL result set that is returned to user. * PRIVATE METHOD * @constructor */ var DroidDB_Result = function() { this.rows = new DroidDB_Rows(); }; /** * Callback from native code when query is complete. * PRIVATE METHOD * * @param id Query id */ function completeQuery(id, data) { var query = queryQueue[id]; if (query) { try { delete queryQueue[id]; // Get transaction var tx = query.tx; // If transaction hasn't failed // Note: We ignore all query results if previous query // in the same transaction failed. if (tx && tx.queryList[id]) { // Save query results var r = new DroidDB_Result(); r.rows.resultSet = data; r.rows.length = data.length; try { if (typeof query.successCallback === 'function') { query.successCallback(query.tx, r); } } catch (ex) { console.log("executeSql error calling user success callback: "+ex); } tx.queryComplete(id); } } catch (e) { console.log("executeSql error: "+e); } } } /** * Callback from native code when query fails * PRIVATE METHOD * * @param reason Error message * @param id Query id */ function failQuery(reason, id) { var query = queryQueue[id]; if (query) { try { delete queryQueue[id]; // Get transaction var tx = query.tx; // If transaction hasn't failed // Note: We ignore all query results if previous query // in the same transaction failed. if (tx && tx.queryList[id]) { tx.queryList = {}; try { if (typeof query.errorCallback === 'function') { query.errorCallback(query.tx, reason); } } catch (ex) { console.log("executeSql error calling user error callback: "+ex); } tx.queryFailed(id, reason); } } catch (e) { console.log("executeSql error: "+e); } } } /** * SQL query object * PRIVATE METHOD * * @constructor * @param tx The transaction object that this query belongs to */ var DroidDB_Query = function(tx) { // Set the id of the query this.id = utils.createUUID(); // Add this query to the queue queryQueue[this.id] = this; // Init result this.resultSet = []; // Set transaction that this query belongs to this.tx = tx; // Add this query to transaction list this.tx.queryList[this.id] = this; // Callbacks this.successCallback = null; this.errorCallback = null; }; /** * Transaction object * PRIVATE METHOD * @constructor */ var DroidDB_Tx = function() { // Set the id of the transaction this.id = utils.createUUID(); // Callbacks this.successCallback = null; this.errorCallback = null; // Query list this.queryList = {}; }; /** * Mark query in transaction as complete. * If all queries are complete, call the user's transaction success callback. * * @param id Query id */ DroidDB_Tx.prototype.queryComplete = function(id) { delete this.queryList[id]; // If no more outstanding queries, then fire transaction success if (this.successCallback) { var count = 0; var i; for (i in this.queryList) { if (this.queryList.hasOwnProperty(i)) { count++; } } if (count === 0) { try { this.successCallback(); } catch(e) { console.log("Transaction error calling user success callback: " + e); } } } }; /** * Mark query in transaction as failed. * * @param id Query id * @param reason Error message */ DroidDB_Tx.prototype.queryFailed = function(id, reason) { // The sql queries in this transaction have already been run, since // we really don't have a real transaction implemented in native code. // However, the user callbacks for the remaining sql queries in transaction // will not be called. this.queryList = {}; if (this.errorCallback) { try { this.errorCallback(reason); } catch(e) { console.log("Transaction error calling user error callback: " + e); } } }; /** * Execute SQL statement * * @param sql SQL statement to execute * @param params Statement parameters * @param successCallback Success callback * @param errorCallback Error callback */ DroidDB_Tx.prototype.executeSql = function(sql, params, successCallback, errorCallback) { // Init params array if (typeof params === 'undefined') { params = []; } // Create query and add to queue var query = new DroidDB_Query(this); queryQueue[query.id] = query; // Save callbacks query.successCallback = successCallback; query.errorCallback = errorCallback; // Call native code exec(null, null, "Storage", "executeSql", [sql, params, query.id]); }; var DatabaseShell = function() { }; /** * Start a transaction. * Does not support rollback in event of failure. * * @param process {Function} The transaction function * @param successCallback {Function} * @param errorCallback {Function} */ DatabaseShell.prototype.transaction = function(process, errorCallback, successCallback) { var tx = new DroidDB_Tx(); tx.successCallback = successCallback; tx.errorCallback = errorCallback; try { process(tx); } catch (e) { console.log("Transaction error: "+e); if (tx.errorCallback) { try { tx.errorCallback(e); } catch (ex) { console.log("Transaction error calling user error callback: "+e); } } } }; /** * Open database * * @param name Database name * @param version Database version * @param display_name Database display name * @param size Database size in bytes * @return Database object */ var DroidDB_openDatabase = function(name, version, display_name, size) { exec(null, null, "Storage", "openDatabase", [name, version, display_name, size]); var db = new DatabaseShell(); return db; }; module.exports = { openDatabase:DroidDB_openDatabase, failQuery:failQuery, completeQuery:completeQuery }; }); // file: lib/android/plugin/android/storage/openDatabase.js define("cordova/plugin/android/storage/openDatabase", function(require, exports, module) { var modulemapper = require('cordova/modulemapper'), storage = require('cordova/plugin/android/storage'); var originalOpenDatabase = modulemapper.getOriginalSymbol(window, 'openDatabase'); module.exports = function(name, version, desc, size) { // First patch WebSQL if necessary if (!originalOpenDatabase) { // Not defined, create an openDatabase function for all to use! return storage.openDatabase.apply(this, arguments); } // Defined, but some Android devices will throw a SECURITY_ERR - // so we wrap the whole thing in a try-catch and shim in our own // if the device has Android bug 16175. try { return originalOpenDatabase(name, version, desc, size); } catch (ex) { if (ex.code !== 18) { throw ex; } } return storage.openDatabase(name, version, desc, size); }; }); // file: lib/android/plugin/android/storage/symbols.js define("cordova/plugin/android/storage/symbols", function(require, exports, module) { var modulemapper = require('cordova/modulemapper'); modulemapper.clobbers('cordova/plugin/android/storage/openDatabase', 'openDatabase'); }); // file: lib/common/plugin/battery.js define("cordova/plugin/battery", function(require, exports, module) { /** * This class contains information about the current battery status. * @constructor */ var cordova = require('cordova'), exec = require('cordova/exec'); function handlers() { return battery.channels.batterystatus.numHandlers + battery.channels.batterylow.numHandlers + battery.channels.batterycritical.numHandlers; } var Battery = function() { this._level = null; this._isPlugged = null; // Create new event handlers on the window (returns a channel instance) this.channels = { batterystatus:cordova.addWindowEventHandler("batterystatus"), batterylow:cordova.addWindowEventHandler("batterylow"), batterycritical:cordova.addWindowEventHandler("batterycritical") }; for (var key in this.channels) { this.channels[key].onHasSubscribersChange = Battery.onHasSubscribersChange; } }; /** * Event handlers for when callbacks get registered for the battery. * Keep track of how many handlers we have so we can start and stop the native battery listener * appropriately (and hopefully save on battery life!). */ Battery.onHasSubscribersChange = function() { // If we just registered the first handler, make sure native listener is started. if (this.numHandlers === 1 && handlers() === 1) { exec(battery._status, battery._error, "Battery", "start", []); } else if (handlers() === 0) { exec(null, null, "Battery", "stop", []); } }; /** * Callback for battery status * * @param {Object} info keys: level, isPlugged */ Battery.prototype._status = function(info) { if (info) { var me = battery; var level = info.level; if (me._level !== level || me._isPlugged !== info.isPlugged) { // Fire batterystatus event cordova.fireWindowEvent("batterystatus", info); // Fire low battery event if (level === 20 || level === 5) { if (level === 20) { cordova.fireWindowEvent("batterylow", info); } else { cordova.fireWindowEvent("batterycritical", info); } } } me._level = level; me._isPlugged = info.isPlugged; } }; /** * Error callback for battery start */ Battery.prototype._error = function(e) { console.log("Error initializing Battery: " + e); }; var battery = new Battery(); module.exports = battery; }); // file: lib/common/plugin/battery/symbols.js define("cordova/plugin/battery/symbols", function(require, exports, module) { var modulemapper = require('cordova/modulemapper'); modulemapper.defaults('cordova/plugin/battery', 'navigator.battery'); }); // file: lib/common/plugin/camera/symbols.js define("cordova/plugin/camera/symbols", function(require, exports, module) { var modulemapper = require('cordova/modulemapper'); modulemapper.defaults('cordova/plugin/Camera', 'navigator.camera'); modulemapper.defaults('cordova/plugin/CameraConstants', 'Camera'); modulemapper.defaults('cordova/plugin/CameraPopoverOptions', 'CameraPopoverOptions'); }); // file: lib/common/plugin/capture.js define("cordova/plugin/capture", function(require, exports, module) { var exec = require('cordova/exec'), MediaFile = require('cordova/plugin/MediaFile'); /** * Launches a capture of different types. * * @param (DOMString} type * @param {Function} successCB * @param {Function} errorCB * @param {CaptureVideoOptions} options */ function _capture(type, successCallback, errorCallback, options) { var win = function(pluginResult) { var mediaFiles = []; var i; for (i = 0; i < pluginResult.length; i++) { var mediaFile = new MediaFile(); mediaFile.name = pluginResult[i].name; mediaFile.fullPath = pluginResult[i].fullPath; mediaFile.type = pluginResult[i].type; mediaFile.lastModifiedDate = pluginResult[i].lastModifiedDate; mediaFile.size = pluginResult[i].size; mediaFiles.push(mediaFile); } successCallback(mediaFiles); }; exec(win, errorCallback, "Capture", type, [options]); } /** * The Capture interface exposes an interface to the camera and microphone of the hosting device. */ function Capture() { this.supportedAudioModes = []; this.supportedImageModes = []; this.supportedVideoModes = []; } /** * Launch audio recorder application for recording audio clip(s). * * @param {Function} successCB * @param {Function} errorCB * @param {CaptureAudioOptions} options */ Capture.prototype.captureAudio = function(successCallback, errorCallback, options){ _capture("captureAudio", successCallback, errorCallback, options); }; /** * Launch camera application for taking image(s). * * @param {Function} successCB * @param {Function} errorCB * @param {CaptureImageOptions} options */ Capture.prototype.captureImage = function(successCallback, errorCallback, options){ _capture("captureImage", successCallback, errorCallback, options); }; /** * Launch device camera application for recording video(s). * * @param {Function} successCB * @param {Function} errorCB * @param {CaptureVideoOptions} options */ Capture.prototype.captureVideo = function(successCallback, errorCallback, options){ _capture("captureVideo", successCallback, errorCallback, options); }; module.exports = new Capture(); }); // file: lib/common/plugin/capture/symbols.js define("cordova/plugin/capture/symbols", function(require, exports, module) { var modulemapper = require('cordova/modulemapper'); modulemapper.clobbers('cordova/plugin/CaptureError', 'CaptureError'); modulemapper.clobbers('cordova/plugin/CaptureAudioOptions', 'CaptureAudioOptions'); modulemapper.clobbers('cordova/plugin/CaptureImageOptions', 'CaptureImageOptions'); modulemapper.clobbers('cordova/plugin/CaptureVideoOptions', 'CaptureVideoOptions'); modulemapper.clobbers('cordova/plugin/ConfigurationData', 'ConfigurationData'); modulemapper.clobbers('cordova/plugin/MediaFile', 'MediaFile'); modulemapper.clobbers('cordova/plugin/MediaFileData', 'MediaFileData'); modulemapper.clobbers('cordova/plugin/capture', 'navigator.device.capture'); }); // file: lib/common/plugin/compass.js define("cordova/plugin/compass", function(require, exports, module) { var argscheck = require('cordova/argscheck'), exec = require('cordova/exec'), utils = require('cordova/utils'), CompassHeading = require('cordova/plugin/CompassHeading'), CompassError = require('cordova/plugin/CompassError'), timers = {}, compass = { /** * Asynchronously acquires the current heading. * @param {Function} successCallback The function to call when the heading * data is available * @param {Function} errorCallback The function to call when there is an error * getting the heading data. * @param {CompassOptions} options The options for getting the heading data (not used). */ getCurrentHeading:function(successCallback, errorCallback, options) { argscheck.checkArgs('fFO', 'compass.getCurrentHeading', arguments); var win = function(result) { var ch = new CompassHeading(result.magneticHeading, result.trueHeading, result.headingAccuracy, result.timestamp); successCallback(ch); }; var fail = errorCallback && function(code) { var ce = new CompassError(code); errorCallback(ce); }; // Get heading exec(win, fail, "Compass", "getHeading", [options]); }, /** * Asynchronously acquires the heading repeatedly at a given interval. * @param {Function} successCallback The function to call each time the heading * data is available * @param {Function} errorCallback The function to call when there is an error * getting the heading data. * @param {HeadingOptions} options The options for getting the heading data * such as timeout and the frequency of the watch. For iOS, filter parameter * specifies to watch via a distance filter rather than time. */ watchHeading:function(successCallback, errorCallback, options) { argscheck.checkArgs('fFO', 'compass.watchHeading', arguments); // Default interval (100 msec) var frequency = (options !== undefined && options.frequency !== undefined) ? options.frequency : 100; var filter = (options !== undefined && options.filter !== undefined) ? options.filter : 0; var id = utils.createUUID(); if (filter > 0) { // is an iOS request for watch by filter, no timer needed timers[id] = "iOS"; compass.getCurrentHeading(successCallback, errorCallback, options); } else { // Start watch timer to get headings timers[id] = window.setInterval(function() { compass.getCurrentHeading(successCallback, errorCallback); }, frequency); } return id; }, /** * Clears the specified heading watch. * @param {String} watchId The ID of the watch returned from #watchHeading. */ clearWatch:function(id) { // Stop javascript timer & remove from timer list if (id && timers[id]) { if (timers[id] != "iOS") { clearInterval(timers[id]); } else { // is iOS watch by filter so call into device to stop exec(null, null, "Compass", "stopHeading", []); } delete timers[id]; } } }; module.exports = compass; }); // file: lib/common/plugin/compass/symbols.js define("cordova/plugin/compass/symbols", function(require, exports, module) { var modulemapper = require('cordova/modulemapper'); modulemapper.clobbers('cordova/plugin/CompassHeading', 'CompassHeading'); modulemapper.clobbers('cordova/plugin/CompassError', 'CompassError'); modulemapper.clobbers('cordova/plugin/compass', 'navigator.compass'); }); // file: lib/common/plugin/console-via-logger.js define("cordova/plugin/console-via-logger", function(require, exports, module) { //------------------------------------------------------------------------------ var logger = require("cordova/plugin/logger"); var utils = require("cordova/utils"); //------------------------------------------------------------------------------ // object that we're exporting //------------------------------------------------------------------------------ var console = module.exports; //------------------------------------------------------------------------------ // copy of the original console object //------------------------------------------------------------------------------ var WinConsole = window.console; //------------------------------------------------------------------------------ // whether to use the logger //------------------------------------------------------------------------------ var UseLogger = false; //------------------------------------------------------------------------------ // Timers //------------------------------------------------------------------------------ var Timers = {}; //------------------------------------------------------------------------------ // used for unimplemented methods //------------------------------------------------------------------------------ function noop() {} //------------------------------------------------------------------------------ // used for unimplemented methods //------------------------------------------------------------------------------ console.useLogger = function (value) { if (arguments.length) UseLogger = !!value; if (UseLogger) { if (logger.useConsole()) { throw new Error("console and logger are too intertwingly"); } } return UseLogger; }; //------------------------------------------------------------------------------ console.log = function() { if (logger.useConsole()) return; logger.log.apply(logger, [].slice.call(arguments)); }; //------------------------------------------------------------------------------ console.error = function() { if (logger.useConsole()) return; logger.error.apply(logger, [].slice.call(arguments)); }; //------------------------------------------------------------------------------ console.warn = function() { if (logger.useConsole()) return; logger.warn.apply(logger, [].slice.call(arguments)); }; //------------------------------------------------------------------------------ console.info = function() { if (logger.useConsole()) return; logger.info.apply(logger, [].slice.call(arguments)); }; //------------------------------------------------------------------------------ console.debug = function() { if (logger.useConsole()) return; logger.debug.apply(logger, [].slice.call(arguments)); }; //------------------------------------------------------------------------------ console.assert = function(expression) { if (expression) return; var message = utils.vformat(arguments[1], [].slice.call(arguments, 2)); console.log("ASSERT: " + message); }; //------------------------------------------------------------------------------ console.clear = function() {}; //------------------------------------------------------------------------------ console.dir = function(object) { console.log("%o", object); }; //------------------------------------------------------------------------------ console.dirxml = function(node) { console.log(node.innerHTML); }; //------------------------------------------------------------------------------ console.trace = noop; //------------------------------------------------------------------------------ console.group = console.log; //------------------------------------------------------------------------------ console.groupCollapsed = console.log; //------------------------------------------------------------------------------ console.groupEnd = noop; //------------------------------------------------------------------------------ console.time = function(name) { Timers[name] = new Date().valueOf(); }; //------------------------------------------------------------------------------ console.timeEnd = function(name) { var timeStart = Timers[name]; if (!timeStart) { console.warn("unknown timer: " + name); return; } var timeElapsed = new Date().valueOf() - timeStart; console.log(name + ": " + timeElapsed + "ms"); }; //------------------------------------------------------------------------------ console.timeStamp = noop; //------------------------------------------------------------------------------ console.profile = noop; //------------------------------------------------------------------------------ console.profileEnd = noop; //------------------------------------------------------------------------------ console.count = noop; //------------------------------------------------------------------------------ console.exception = console.log; //------------------------------------------------------------------------------ console.table = function(data, columns) { console.log("%o", data); }; //------------------------------------------------------------------------------ // return a new function that calls both functions passed as args //------------------------------------------------------------------------------ function wrappedOrigCall(orgFunc, newFunc) { return function() { var args = [].slice.call(arguments); try { orgFunc.apply(WinConsole, args); } catch (e) {} try { newFunc.apply(console, args); } catch (e) {} }; } //------------------------------------------------------------------------------ // For every function that exists in the original console object, that // also exists in the new console object, wrap the new console method // with one that calls both //------------------------------------------------------------------------------ for (var key in console) { if (typeof WinConsole[key] == "function") { console[key] = wrappedOrigCall(WinConsole[key], console[key]); } } }); // file: lib/common/plugin/contacts.js define("cordova/plugin/contacts", function(require, exports, module) { var argscheck = require('cordova/argscheck'), exec = require('cordova/exec'), ContactError = require('cordova/plugin/ContactError'), utils = require('cordova/utils'), Contact = require('cordova/plugin/Contact'); /** * Represents a group of Contacts. * @constructor */ var contacts = { /** * Returns an array of Contacts matching the search criteria. * @param fields that should be searched * @param successCB success callback * @param errorCB error callback * @param {ContactFindOptions} options that can be applied to contact searching * @return array of Contacts matching search criteria */ find:function(fields, successCB, errorCB, options) { argscheck.checkArgs('afFO', 'contacts.find', arguments); if (!fields.length) { errorCB && errorCB(new ContactError(ContactError.INVALID_ARGUMENT_ERROR)); } else { var win = function(result) { var cs = []; for (var i = 0, l = result.length; i < l; i++) { cs.push(contacts.create(result[i])); } successCB(cs); }; exec(win, errorCB, "Contacts", "search", [fields, options]); } }, /** * This function creates a new contact, but it does not persist the contact * to device storage. To persist the contact to device storage, invoke * contact.save(). * @param properties an object whose properties will be examined to create a new Contact * @returns new Contact object */ create:function(properties) { argscheck.checkArgs('O', 'contacts.create', arguments); var contact = new Contact(); for (var i in properties) { if (typeof contact[i] !== 'undefined' && properties.hasOwnProperty(i)) { contact[i] = properties[i]; } } return contact; } }; module.exports = contacts; }); // file: lib/common/plugin/contacts/symbols.js define("cordova/plugin/contacts/symbols", function(require, exports, module) { var modulemapper = require('cordova/modulemapper'); modulemapper.clobbers('cordova/plugin/contacts', 'navigator.contacts'); modulemapper.clobbers('cordova/plugin/Contact', 'Contact'); modulemapper.clobbers('cordova/plugin/ContactAddress', 'ContactAddress'); modulemapper.clobbers('cordova/plugin/ContactError', 'ContactError'); modulemapper.clobbers('cordova/plugin/ContactField', 'ContactField'); modulemapper.clobbers('cordova/plugin/ContactFindOptions', 'ContactFindOptions'); modulemapper.clobbers('cordova/plugin/ContactName', 'ContactName'); modulemapper.clobbers('cordova/plugin/ContactOrganization', 'ContactOrganization'); }); // file: lib/common/plugin/device.js define("cordova/plugin/device", function(require, exports, module) { var argscheck = require('cordova/argscheck'), channel = require('cordova/channel'), utils = require('cordova/utils'), exec = require('cordova/exec'); // Tell cordova channel to wait on the CordovaInfoReady event channel.waitForInitialization('onCordovaInfoReady'); /** * This represents the mobile device, and provides properties for inspecting the model, version, UUID of the * phone, etc. * @constructor */ function Device() { this.available = false; this.platform = null; this.version = null; this.name = null; this.uuid = null; this.cordova = null; this.model = null; var me = this; channel.onCordovaReady.subscribe(function() { me.getInfo(function(info) { me.available = true; me.platform = info.platform; me.version = info.version; me.name = info.name; me.uuid = info.uuid; me.cordova = info.cordova; me.model = info.model; channel.onCordovaInfoReady.fire(); },function(e) { me.available = false; utils.alert("[ERROR] Error initializing Cordova: " + e); }); }); } /** * Get device info * * @param {Function} successCallback The function to call when the heading data is available * @param {Function} errorCallback The function to call when there is an error getting the heading data. (OPTIONAL) */ Device.prototype.getInfo = function(successCallback, errorCallback) { argscheck.checkArgs('fF', 'Device.getInfo', arguments); exec(successCallback, errorCallback, "Device", "getDeviceInfo", []); }; module.exports = new Device(); }); // file: lib/android/plugin/device/symbols.js define("cordova/plugin/device/symbols", function(require, exports, module) { var modulemapper = require('cordova/modulemapper'); modulemapper.clobbers('cordova/plugin/device', 'device'); modulemapper.merges('cordova/plugin/android/device', 'device'); }); // file: lib/common/plugin/echo.js define("cordova/plugin/echo", function(require, exports, module) { var exec = require('cordova/exec'); /** * Sends the given message through exec() to the Echo plugin, which sends it back to the successCallback. * @param successCallback invoked with a FileSystem object * @param errorCallback invoked if error occurs retrieving file system * @param message The string to be echoed. * @param forceAsync Whether to force an async return value (for testing native->js bridge). */ module.exports = function(successCallback, errorCallback, message, forceAsync) { var action = forceAsync ? 'echoAsync' : 'echo'; if (!forceAsync && message.constructor == ArrayBuffer) { action = 'echoArrayBuffer'; } exec(successCallback, errorCallback, "Echo", action, [message]); }; }); // file: lib/android/plugin/file/symbols.js define("cordova/plugin/file/symbols", function(require, exports, module) { var modulemapper = require('cordova/modulemapper'), symbolshelper = require('cordova/plugin/file/symbolshelper'); symbolshelper(modulemapper.clobbers); }); // file: lib/common/plugin/file/symbolshelper.js define("cordova/plugin/file/symbolshelper", function(require, exports, module) { module.exports = function(exportFunc) { exportFunc('cordova/plugin/DirectoryEntry', 'DirectoryEntry'); exportFunc('cordova/plugin/DirectoryReader', 'DirectoryReader'); exportFunc('cordova/plugin/Entry', 'Entry'); exportFunc('cordova/plugin/File', 'File'); exportFunc('cordova/plugin/FileEntry', 'FileEntry'); exportFunc('cordova/plugin/FileError', 'FileError'); exportFunc('cordova/plugin/FileReader', 'FileReader'); exportFunc('cordova/plugin/FileSystem', 'FileSystem'); exportFunc('cordova/plugin/FileUploadOptions', 'FileUploadOptions'); exportFunc('cordova/plugin/FileUploadResult', 'FileUploadResult'); exportFunc('cordova/plugin/FileWriter', 'FileWriter'); exportFunc('cordova/plugin/Flags', 'Flags'); exportFunc('cordova/plugin/LocalFileSystem', 'LocalFileSystem'); exportFunc('cordova/plugin/Metadata', 'Metadata'); exportFunc('cordova/plugin/ProgressEvent', 'ProgressEvent'); exportFunc('cordova/plugin/requestFileSystem', 'requestFileSystem'); exportFunc('cordova/plugin/resolveLocalFileSystemURI', 'resolveLocalFileSystemURI'); }; }); // file: lib/common/plugin/filetransfer/symbols.js define("cordova/plugin/filetransfer/symbols", function(require, exports, module) { var modulemapper = require('cordova/modulemapper'); modulemapper.clobbers('cordova/plugin/FileTransfer', 'FileTransfer'); modulemapper.clobbers('cordova/plugin/FileTransferError', 'FileTransferError'); }); // file: lib/common/plugin/geolocation.js define("cordova/plugin/geolocation", function(require, exports, module) { var argscheck = require('cordova/argscheck'), utils = require('cordova/utils'), exec = require('cordova/exec'), PositionError = require('cordova/plugin/PositionError'), Position = require('cordova/plugin/Position'); var timers = {}; // list of timers in use // Returns default params, overrides if provided with values function parseParameters(options) { var opt = { maximumAge: 0, enableHighAccuracy: false, timeout: Infinity }; if (options) { if (options.maximumAge !== undefined && !isNaN(options.maximumAge) && options.maximumAge > 0) { opt.maximumAge = options.maximumAge; } if (options.enableHighAccuracy !== undefined) { opt.enableHighAccuracy = options.enableHighAccuracy; } if (options.timeout !== undefined && !isNaN(options.timeout)) { if (options.timeout < 0) { opt.timeout = 0; } else { opt.timeout = options.timeout; } } } return opt; } // Returns a timeout failure, closed over a specified timeout value and error callback. function createTimeout(errorCallback, timeout) { var t = setTimeout(function() { clearTimeout(t); t = null; errorCallback({ code:PositionError.TIMEOUT, message:"Position retrieval timed out." }); }, timeout); return t; } var geolocation = { lastPosition:null, // reference to last known (cached) position returned /** * Asynchronously acquires the current position. * * @param {Function} successCallback The function to call when the position data is available * @param {Function} errorCallback The function to call when there is an error getting the heading position. (OPTIONAL) * @param {PositionOptions} options The options for getting the position data. (OPTIONAL) */ getCurrentPosition:function(successCallback, errorCallback, options) { argscheck.checkArgs('fFO', 'geolocation.getCurrentPosition', arguments); options = parseParameters(options); // Timer var that will fire an error callback if no position is retrieved from native // before the "timeout" param provided expires var timeoutTimer = {timer:null}; var win = function(p) { clearTimeout(timeoutTimer.timer); if (!(timeoutTimer.timer)) { // Timeout already happened, or native fired error callback for // this geo request. // Don't continue with success callback. return; } var pos = new Position( { latitude:p.latitude, longitude:p.longitude, altitude:p.altitude, accuracy:p.accuracy, heading:p.heading, velocity:p.velocity, altitudeAccuracy:p.altitudeAccuracy }, (p.timestamp === undefined ? new Date() : ((p.timestamp instanceof Date) ? p.timestamp : new Date(p.timestamp))) ); geolocation.lastPosition = pos; successCallback(pos); }; var fail = function(e) { clearTimeout(timeoutTimer.timer); timeoutTimer.timer = null; var err = new PositionError(e.code, e.message); if (errorCallback) { errorCallback(err); } }; // Check our cached position, if its timestamp difference with current time is less than the maximumAge, then just // fire the success callback with the cached position. if (geolocation.lastPosition && options.maximumAge && (((new Date()).getTime() - geolocation.lastPosition.timestamp.getTime()) <= options.maximumAge)) { successCallback(geolocation.lastPosition); // If the cached position check failed and the timeout was set to 0, error out with a TIMEOUT error object. } else if (options.timeout === 0) { fail({ code:PositionError.TIMEOUT, message:"timeout value in PositionOptions set to 0 and no cached Position object available, or cached Position object's age exceeds provided PositionOptions' maximumAge parameter." }); // Otherwise we have to call into native to retrieve a position. } else { if (options.timeout !== Infinity) { // If the timeout value was not set to Infinity (default), then // set up a timeout function that will fire the error callback // if no successful position was retrieved before timeout expired. timeoutTimer.timer = createTimeout(fail, options.timeout); } else { // This is here so the check in the win function doesn't mess stuff up // may seem weird but this guarantees timeoutTimer is // always truthy before we call into native timeoutTimer.timer = true; } exec(win, fail, "Geolocation", "getLocation", [options.enableHighAccuracy, options.maximumAge]); } return timeoutTimer; }, /** * Asynchronously watches the geolocation for changes to geolocation. When a change occurs, * the successCallback is called with the new location. * * @param {Function} successCallback The function to call each time the location data is available * @param {Function} errorCallback The function to call when there is an error getting the location data. (OPTIONAL) * @param {PositionOptions} options The options for getting the location data such as frequency. (OPTIONAL) * @return String The watch id that must be passed to #clearWatch to stop watching. */ watchPosition:function(successCallback, errorCallback, options) { argscheck.checkArgs('fFO', 'geolocation.getCurrentPosition', arguments); options = parseParameters(options); var id = utils.createUUID(); // Tell device to get a position ASAP, and also retrieve a reference to the timeout timer generated in getCurrentPosition timers[id] = geolocation.getCurrentPosition(successCallback, errorCallback, options); var fail = function(e) { clearTimeout(timers[id].timer); var err = new PositionError(e.code, e.message); if (errorCallback) { errorCallback(err); } }; var win = function(p) { clearTimeout(timers[id].timer); if (options.timeout !== Infinity) { timers[id].timer = createTimeout(fail, options.timeout); } var pos = new Position( { latitude:p.latitude, longitude:p.longitude, altitude:p.altitude, accuracy:p.accuracy, heading:p.heading, velocity:p.velocity, altitudeAccuracy:p.altitudeAccuracy }, (p.timestamp === undefined ? new Date() : ((p.timestamp instanceof Date) ? p.timestamp : new Date(p.timestamp))) ); geolocation.lastPosition = pos; successCallback(pos); }; exec(win, fail, "Geolocation", "addWatch", [id, options.enableHighAccuracy]); return id; }, /** * Clears the specified heading watch. * * @param {String} id The ID of the watch returned from #watchPosition */ clearWatch:function(id) { if (id && timers[id] !== undefined) { clearTimeout(timers[id].timer); timers[id].timer = false; exec(null, null, "Geolocation", "clearWatch", [id]); } } }; module.exports = geolocation; }); // file: lib/common/plugin/geolocation/symbols.js define("cordova/plugin/geolocation/symbols", function(require, exports, module) { var modulemapper = require('cordova/modulemapper'); modulemapper.defaults('cordova/plugin/geolocation', 'navigator.geolocation'); modulemapper.clobbers('cordova/plugin/PositionError', 'PositionError'); modulemapper.clobbers('cordova/plugin/Position', 'Position'); modulemapper.clobbers('cordova/plugin/Coordinates', 'Coordinates'); }); // file: lib/common/plugin/globalization.js define("cordova/plugin/globalization", function(require, exports, module) { var argscheck = require('cordova/argscheck'), exec = require('cordova/exec'), GlobalizationError = require('cordova/plugin/GlobalizationError'); var globalization = { /** * Returns the string identifier for the client's current language. * It returns the language identifier string to the successCB callback with a * properties object as a parameter. If there is an error getting the language, * then the errorCB callback is invoked. * * @param {Function} successCB * @param {Function} errorCB * * @return Object.value {String}: The language identifier * * @error GlobalizationError.UNKNOWN_ERROR * * Example * globalization.getPreferredLanguage(function (language) {alert('language:' + language.value + '\n');}, * function () {}); */ getPreferredLanguage:function(successCB, failureCB) { argscheck.checkArgs('fF', 'Globalization.getPreferredLanguage', arguments); exec(successCB, failureCB, "Globalization","getPreferredLanguage", []); }, /** * Returns the string identifier for the client's current locale setting. * It returns the locale identifier string to the successCB callback with a * properties object as a parameter. If there is an error getting the locale, * then the errorCB callback is invoked. * * @param {Function} successCB * @param {Function} errorCB * * @return Object.value {String}: The locale identifier * * @error GlobalizationError.UNKNOWN_ERROR * * Example * globalization.getLocaleName(function (locale) {alert('locale:' + locale.value + '\n');}, * function () {}); */ getLocaleName:function(successCB, failureCB) { argscheck.checkArgs('fF', 'Globalization.getLocaleName', arguments); exec(successCB, failureCB, "Globalization","getLocaleName", []); }, /** * Returns a date formatted as a string according to the client's user preferences and * calendar using the time zone of the client. It returns the formatted date string to the * successCB callback with a properties object as a parameter. If there is an error * formatting the date, then the errorCB callback is invoked. * * The defaults are: formatLenght="short" and selector="date and time" * * @param {Date} date * @param {Function} successCB * @param {Function} errorCB * @param {Object} options {optional} * formatLength {String}: 'short', 'medium', 'long', or 'full' * selector {String}: 'date', 'time', or 'date and time' * * @return Object.value {String}: The localized date string * * @error GlobalizationError.FORMATTING_ERROR * * Example * globalization.dateToString(new Date(), * function (date) {alert('date:' + date.value + '\n');}, * function (errorCode) {alert(errorCode);}, * {formatLength:'short'}); */ dateToString:function(date, successCB, failureCB, options) { argscheck.checkArgs('dfFO', 'Globalization.dateToString', arguments); var dateValue = date.valueOf(); exec(successCB, failureCB, "Globalization", "dateToString", [{"date": dateValue, "options": options}]); }, /** * Parses a date formatted as a string according to the client's user * preferences and calendar using the time zone of the client and returns * the corresponding date object. It returns the date to the successCB * callback with a properties object as a parameter. If there is an error * parsing the date string, then the errorCB callback is invoked. * * The defaults are: formatLength="short" and selector="date and time" * * @param {String} dateString * @param {Function} successCB * @param {Function} errorCB * @param {Object} options {optional} * formatLength {String}: 'short', 'medium', 'long', or 'full' * selector {String}: 'date', 'time', or 'date and time' * * @return Object.year {Number}: The four digit year * Object.month {Number}: The month from (0 - 11) * Object.day {Number}: The day from (1 - 31) * Object.hour {Number}: The hour from (0 - 23) * Object.minute {Number}: The minute from (0 - 59) * Object.second {Number}: The second from (0 - 59) * Object.millisecond {Number}: The milliseconds (from 0 - 999), * not available on all platforms * * @error GlobalizationError.PARSING_ERROR * * Example * globalization.stringToDate('4/11/2011', * function (date) { alert('Month:' + date.month + '\n' + * 'Day:' + date.day + '\n' + * 'Year:' + date.year + '\n');}, * function (errorCode) {alert(errorCode);}, * {selector:'date'}); */ stringToDate:function(dateString, successCB, failureCB, options) { argscheck.checkArgs('sfFO', 'Globalization.stringToDate', arguments); exec(successCB, failureCB, "Globalization", "stringToDate", [{"dateString": dateString, "options": options}]); }, /** * Returns a pattern string for formatting and parsing dates according to the client's * user preferences. It returns the pattern to the successCB callback with a * properties object as a parameter. If there is an error obtaining the pattern, * then the errorCB callback is invoked. * * The defaults are: formatLength="short" and selector="date and time" * * @param {Function} successCB * @param {Function} errorCB * @param {Object} options {optional} * formatLength {String}: 'short', 'medium', 'long', or 'full' * selector {String}: 'date', 'time', or 'date and time' * * @return Object.pattern {String}: The date and time pattern for formatting and parsing dates. * The patterns follow Unicode Technical Standard #35 * http://unicode.org/reports/tr35/tr35-4.html * Object.timezone {String}: The abbreviated name of the time zone on the client * Object.utc_offset {Number}: The current difference in seconds between the client's * time zone and coordinated universal time. * Object.dst_offset {Number}: The current daylight saving time offset in seconds * between the client's non-daylight saving's time zone * and the client's daylight saving's time zone. * * @error GlobalizationError.PATTERN_ERROR * * Example * globalization.getDatePattern( * function (date) {alert('pattern:' + date.pattern + '\n');}, * function () {}, * {formatLength:'short'}); */ getDatePattern:function(successCB, failureCB, options) { argscheck.checkArgs('fFO', 'Globalization.getDatePattern', arguments); exec(successCB, failureCB, "Globalization", "getDatePattern", [{"options": options}]); }, /** * Returns an array of either the names of the months or days of the week * according to the client's user preferences and calendar. It returns the array of names to the * successCB callback with a properties object as a parameter. If there is an error obtaining the * names, then the errorCB callback is invoked. * * The defaults are: type="wide" and item="months" * * @param {Function} successCB * @param {Function} errorCB * @param {Object} options {optional} * type {String}: 'narrow' or 'wide' * item {String}: 'months', or 'days' * * @return Object.value {Array{String}}: The array of names starting from either * the first month in the year or the * first day of the week. * @error GlobalizationError.UNKNOWN_ERROR * * Example * globalization.getDateNames(function (names) { * for(var i = 0; i < names.value.length; i++) { * alert('Month:' + names.value[i] + '\n');}}, * function () {}); */ getDateNames:function(successCB, failureCB, options) { argscheck.checkArgs('fFO', 'Globalization.getDateNames', arguments); exec(successCB, failureCB, "Globalization", "getDateNames", [{"options": options}]); }, /** * Returns whether daylight savings time is in effect for a given date using the client's * time zone and calendar. It returns whether or not daylight savings time is in effect * to the successCB callback with a properties object as a parameter. If there is an error * reading the date, then the errorCB callback is invoked. * * @param {Date} date * @param {Function} successCB * @param {Function} errorCB * * @return Object.dst {Boolean}: The value "true" indicates that daylight savings time is * in effect for the given date and "false" indicate that it is not. * * @error GlobalizationError.UNKNOWN_ERROR * * Example * globalization.isDayLightSavingsTime(new Date(), * function (date) {alert('dst:' + date.dst + '\n');} * function () {}); */ isDayLightSavingsTime:function(date, successCB, failureCB) { argscheck.checkArgs('dfF', 'Globalization.isDayLightSavingsTime', arguments); var dateValue = date.valueOf(); exec(successCB, failureCB, "Globalization", "isDayLightSavingsTime", [{"date": dateValue}]); }, /** * Returns the first day of the week according to the client's user preferences and calendar. * The days of the week are numbered starting from 1 where 1 is considered to be Sunday. * It returns the day to the successCB callback with a properties object as a parameter. * If there is an error obtaining the pattern, then the errorCB callback is invoked. * * @param {Function} successCB * @param {Function} errorCB * * @return Object.value {Number}: The number of the first day of the week. * * @error GlobalizationError.UNKNOWN_ERROR * * Example * globalization.getFirstDayOfWeek(function (day) * { alert('Day:' + day.value + '\n');}, * function () {}); */ getFirstDayOfWeek:function(successCB, failureCB) { argscheck.checkArgs('fF', 'Globalization.getFirstDayOfWeek', arguments); exec(successCB, failureCB, "Globalization", "getFirstDayOfWeek", []); }, /** * Returns a number formatted as a string according to the client's user preferences. * It returns the formatted number string to the successCB callback with a properties object as a * parameter. If there is an error formatting the number, then the errorCB callback is invoked. * * The defaults are: type="decimal" * * @param {Number} number * @param {Function} successCB * @param {Function} errorCB * @param {Object} options {optional} * type {String}: 'decimal', "percent", or 'currency' * * @return Object.value {String}: The formatted number string. * * @error GlobalizationError.FORMATTING_ERROR * * Example * globalization.numberToString(3.25, * function (number) {alert('number:' + number.value + '\n');}, * function () {}, * {type:'decimal'}); */ numberToString:function(number, successCB, failureCB, options) { argscheck.checkArgs('nfFO', 'Globalization.numberToString', arguments); exec(successCB, failureCB, "Globalization", "numberToString", [{"number": number, "options": options}]); }, /** * Parses a number formatted as a string according to the client's user preferences and * returns the corresponding number. It returns the number to the successCB callback with a * properties object as a parameter. If there is an error parsing the number string, then * the errorCB callback is invoked. * * The defaults are: type="decimal" * * @param {String} numberString * @param {Function} successCB * @param {Function} errorCB * @param {Object} options {optional} * type {String}: 'decimal', "percent", or 'currency' * * @return Object.value {Number}: The parsed number. * * @error GlobalizationError.PARSING_ERROR * * Example * globalization.stringToNumber('1234.56', * function (number) {alert('Number:' + number.value + '\n');}, * function () { alert('Error parsing number');}); */ stringToNumber:function(numberString, successCB, failureCB, options) { argscheck.checkArgs('sfFO', 'Globalization.stringToNumber', arguments); exec(successCB, failureCB, "Globalization", "stringToNumber", [{"numberString": numberString, "options": options}]); }, /** * Returns a pattern string for formatting and parsing numbers according to the client's user * preferences. It returns the pattern to the successCB callback with a properties object as a * parameter. If there is an error obtaining the pattern, then the errorCB callback is invoked. * * The defaults are: type="decimal" * * @param {Function} successCB * @param {Function} errorCB * @param {Object} options {optional} * type {String}: 'decimal', "percent", or 'currency' * * @return Object.pattern {String}: The number pattern for formatting and parsing numbers. * The patterns follow Unicode Technical Standard #35. * http://unicode.org/reports/tr35/tr35-4.html * Object.symbol {String}: The symbol to be used when formatting and parsing * e.g., percent or currency symbol. * Object.fraction {Number}: The number of fractional digits to use when parsing and * formatting numbers. * Object.rounding {Number}: The rounding increment to use when parsing and formatting. * Object.positive {String}: The symbol to use for positive numbers when parsing and formatting. * Object.negative: {String}: The symbol to use for negative numbers when parsing and formatting. * Object.decimal: {String}: The decimal symbol to use for parsing and formatting. * Object.grouping: {String}: The grouping symbol to use for parsing and formatting. * * @error GlobalizationError.PATTERN_ERROR * * Example * globalization.getNumberPattern( * function (pattern) {alert('Pattern:' + pattern.pattern + '\n');}, * function () {}); */ getNumberPattern:function(successCB, failureCB, options) { argscheck.checkArgs('fFO', 'Globalization.getNumberPattern', arguments); exec(successCB, failureCB, "Globalization", "getNumberPattern", [{"options": options}]); }, /** * Returns a pattern string for formatting and parsing currency values according to the client's * user preferences and ISO 4217 currency code. It returns the pattern to the successCB callback with a * properties object as a parameter. If there is an error obtaining the pattern, then the errorCB * callback is invoked. * * @param {String} currencyCode * @param {Function} successCB * @param {Function} errorCB * * @return Object.pattern {String}: The currency pattern for formatting and parsing currency values. * The patterns follow Unicode Technical Standard #35 * http://unicode.org/reports/tr35/tr35-4.html * Object.code {String}: The ISO 4217 currency code for the pattern. * Object.fraction {Number}: The number of fractional digits to use when parsing and * formatting currency. * Object.rounding {Number}: The rounding increment to use when parsing and formatting. * Object.decimal: {String}: The decimal symbol to use for parsing and formatting. * Object.grouping: {String}: The grouping symbol to use for parsing and formatting. * * @error GlobalizationError.FORMATTING_ERROR * * Example * globalization.getCurrencyPattern('EUR', * function (currency) {alert('Pattern:' + currency.pattern + '\n');} * function () {}); */ getCurrencyPattern:function(currencyCode, successCB, failureCB) { argscheck.checkArgs('sfF', 'Globalization.getCurrencyPattern', arguments); exec(successCB, failureCB, "Globalization", "getCurrencyPattern", [{"currencyCode": currencyCode}]); } }; module.exports = globalization; }); // file: lib/common/plugin/globalization/symbols.js define("cordova/plugin/globalization/symbols", function(require, exports, module) { var modulemapper = require('cordova/modulemapper'); modulemapper.clobbers('cordova/plugin/globalization', 'navigator.globalization'); modulemapper.clobbers('cordova/plugin/GlobalizationError', 'GlobalizationError'); }); // file: lib/android/plugin/inappbrowser/symbols.js define("cordova/plugin/inappbrowser/symbols", function(require, exports, module) { var modulemapper = require('cordova/modulemapper'); modulemapper.clobbers('cordova/plugin/InAppBrowser', 'open'); }); // file: lib/common/plugin/logger.js define("cordova/plugin/logger", function(require, exports, module) { //------------------------------------------------------------------------------ // The logger module exports the following properties/functions: // // LOG - constant for the level LOG // ERROR - constant for the level ERROR // WARN - constant for the level WARN // INFO - constant for the level INFO // DEBUG - constant for the level DEBUG // logLevel() - returns current log level // logLevel(value) - sets and returns a new log level // useConsole() - returns whether logger is using console // useConsole(value) - sets and returns whether logger is using console // log(message,...) - logs a message at level LOG // error(message,...) - logs a message at level ERROR // warn(message,...) - logs a message at level WARN // info(message,...) - logs a message at level INFO // debug(message,...) - logs a message at level DEBUG // logLevel(level,message,...) - logs a message specified level // //------------------------------------------------------------------------------ var logger = exports; var exec = require('cordova/exec'); var utils = require('cordova/utils'); var UseConsole = true; var Queued = []; var DeviceReady = false; var CurrentLevel; /** * Logging levels */ var Levels = [ "LOG", "ERROR", "WARN", "INFO", "DEBUG" ]; /* * add the logging levels to the logger object and * to a separate levelsMap object for testing */ var LevelsMap = {}; for (var i=0; i<Levels.length; i++) { var level = Levels[i]; LevelsMap[level] = i; logger[level] = level; } CurrentLevel = LevelsMap.WARN; /** * Getter/Setter for the logging level * * Returns the current logging level. * * When a value is passed, sets the logging level to that value. * The values should be one of the following constants: * logger.LOG * logger.ERROR * logger.WARN * logger.INFO * logger.DEBUG * * The value used determines which messages get printed. The logging * values above are in order, and only messages logged at the logging * level or above will actually be displayed to the user. E.g., the * default level is WARN, so only messages logged with LOG, ERROR, or * WARN will be displayed; INFO and DEBUG messages will be ignored. */ logger.level = function (value) { if (arguments.length) { if (LevelsMap[value] === null) { throw new Error("invalid logging level: " + value); } CurrentLevel = LevelsMap[value]; } return Levels[CurrentLevel]; }; /** * Getter/Setter for the useConsole functionality * * When useConsole is true, the logger will log via the * browser 'console' object. Otherwise, it will use the * native Logger plugin. */ logger.useConsole = function (value) { if (arguments.length) UseConsole = !!value; if (UseConsole) { if (typeof console == "undefined") { throw new Error("global console object is not defined"); } if (typeof console.log != "function") { throw new Error("global console object does not have a log function"); } if (typeof console.useLogger == "function") { if (console.useLogger()) { throw new Error("console and logger are too intertwingly"); } } } return UseConsole; }; /** * Logs a message at the LOG level. * * Parameters passed after message are used applied to * the message with utils.format() */ logger.log = function(message) { logWithArgs("LOG", arguments); }; /** * Logs a message at the ERROR level. * * Parameters passed after message are used applied to * the message with utils.format() */ logger.error = function(message) { logWithArgs("ERROR", arguments); }; /** * Logs a message at the WARN level. * * Parameters passed after message are used applied to * the message with utils.format() */ logger.warn = function(message) { logWithArgs("WARN", arguments); }; /** * Logs a message at the INFO level. * * Parameters passed after message are used applied to * the message with utils.format() */ logger.info = function(message) { logWithArgs("INFO", arguments); }; /** * Logs a message at the DEBUG level. * * Parameters passed after message are used applied to * the message with utils.format() */ logger.debug = function(message) { logWithArgs("DEBUG", arguments); }; // log at the specified level with args function logWithArgs(level, args) { args = [level].concat([].slice.call(args)); logger.logLevel.apply(logger, args); } /** * Logs a message at the specified level. * * Parameters passed after message are used applied to * the message with utils.format() */ logger.logLevel = function(level, message /* , ... */) { // format the message with the parameters var formatArgs = [].slice.call(arguments, 2); message = utils.vformat(message, formatArgs); if (LevelsMap[level] === null) { throw new Error("invalid logging level: " + level); } if (LevelsMap[level] > CurrentLevel) return; // queue the message if not yet at deviceready if (!DeviceReady && !UseConsole) { Queued.push([level, message]); return; } // if not using the console, use the native logger if (!UseConsole) { exec(null, null, "Logger", "logLevel", [level, message]); return; } // make sure console is not using logger if (console.__usingCordovaLogger) { throw new Error("console and logger are too intertwingly"); } // log to the console switch (level) { case logger.LOG: console.log(message); break; case logger.ERROR: console.log("ERROR: " + message); break; case logger.WARN: console.log("WARN: " + message); break; case logger.INFO: console.log("INFO: " + message); break; case logger.DEBUG: console.log("DEBUG: " + message); break; } }; // when deviceready fires, log queued messages logger.__onDeviceReady = function() { if (DeviceReady) return; DeviceReady = true; for (var i=0; i<Queued.length; i++) { var messageArgs = Queued[i]; logger.logLevel(messageArgs[0], messageArgs[1]); } Queued = null; }; // add a deviceready event to log queued messages document.addEventListener("deviceready", logger.__onDeviceReady, false); }); // file: lib/common/plugin/logger/symbols.js define("cordova/plugin/logger/symbols", function(require, exports, module) { var modulemapper = require('cordova/modulemapper'); modulemapper.clobbers('cordova/plugin/logger', 'cordova.logger'); }); // file: lib/android/plugin/media/symbols.js define("cordova/plugin/media/symbols", function(require, exports, module) { var modulemapper = require('cordova/modulemapper'); modulemapper.defaults('cordova/plugin/Media', 'Media'); modulemapper.clobbers('cordova/plugin/MediaError', 'MediaError'); }); // file: lib/common/plugin/network.js define("cordova/plugin/network", function(require, exports, module) { var exec = require('cordova/exec'), cordova = require('cordova'), channel = require('cordova/channel'), utils = require('cordova/utils'); // Link the onLine property with the Cordova-supplied network info. // This works because we clobber the naviagtor object with our own // object in bootstrap.js. if (typeof navigator != 'undefined') { utils.defineGetter(navigator, 'onLine', function() { return this.connection.type != 'none'; }); } function NetworkConnection() { this.type = 'unknown'; } /** * Get connection info * * @param {Function} successCallback The function to call when the Connection data is available * @param {Function} errorCallback The function to call when there is an error getting the Connection data. (OPTIONAL) */ NetworkConnection.prototype.getInfo = function(successCallback, errorCallback) { exec(successCallback, errorCallback, "NetworkStatus", "getConnectionInfo", []); }; var me = new NetworkConnection(); var timerId = null; var timeout = 500; channel.onCordovaReady.subscribe(function() { me.getInfo(function(info) { me.type = info; if (info === "none") { // set a timer if still offline at the end of timer send the offline event timerId = setTimeout(function(){ cordova.fireDocumentEvent("offline"); timerId = null; }, timeout); } else { // If there is a current offline event pending clear it if (timerId !== null) { clearTimeout(timerId); timerId = null; } cordova.fireDocumentEvent("online"); } // should only fire this once if (channel.onCordovaConnectionReady.state !== 2) { channel.onCordovaConnectionReady.fire(); } }, function (e) { // If we can't get the network info we should still tell Cordova // to fire the deviceready event. if (channel.onCordovaConnectionReady.state !== 2) { channel.onCordovaConnectionReady.fire(); } console.log("Error initializing Network Connection: " + e); }); }); module.exports = me; }); // file: lib/common/plugin/networkstatus/symbols.js define("cordova/plugin/networkstatus/symbols", function(require, exports, module) { var modulemapper = require('cordova/modulemapper'); modulemapper.clobbers('cordova/plugin/network', 'navigator.network.connection', 'navigator.network.connection is deprecated. Use navigator.connection instead.'); modulemapper.clobbers('cordova/plugin/network', 'navigator.connection'); modulemapper.defaults('cordova/plugin/Connection', 'Connection'); }); // file: lib/common/plugin/notification.js define("cordova/plugin/notification", function(require, exports, module) { var exec = require('cordova/exec'); /** * Provides access to notifications on the device. */ module.exports = { /** * Open a native alert dialog, with a customizable title and button text. * * @param {String} message Message to print in the body of the alert * @param {Function} completeCallback The callback that is called when user clicks on a button. * @param {String} title Title of the alert dialog (default: Alert) * @param {String} buttonLabel Label of the close button (default: OK) */ alert: function(message, completeCallback, title, buttonLabel) { var _title = (title || "Alert"); var _buttonLabel = (buttonLabel || "OK"); exec(completeCallback, null, "Notification", "alert", [message, _title, _buttonLabel]); }, /** * Open a native confirm dialog, with a customizable title and button text. * The result that the user selects is returned to the result callback. * * @param {String} message Message to print in the body of the alert * @param {Function} resultCallback The callback that is called when user clicks on a button. * @param {String} title Title of the alert dialog (default: Confirm) * @param {String} buttonLabels Comma separated list of the labels of the buttons (default: 'OK,Cancel') */ confirm: function(message, resultCallback, title, buttonLabels) { var _title = (title || "Confirm"); var _buttonLabels = (buttonLabels || "OK,Cancel"); exec(resultCallback, null, "Notification", "confirm", [message, _title, _buttonLabels]); }, /** * Causes the device to vibrate. * * @param {Integer} mills The number of milliseconds to vibrate for. */ vibrate: function(mills) { exec(null, null, "Notification", "vibrate", [mills]); }, /** * Causes the device to beep. * On Android, the default notification ringtone is played "count" times. * * @param {Integer} count The number of beeps. */ beep: function(count) { exec(null, null, "Notification", "beep", [count]); } }; }); // file: lib/android/plugin/notification/symbols.js define("cordova/plugin/notification/symbols", function(require, exports, module) { var modulemapper = require('cordova/modulemapper'); modulemapper.clobbers('cordova/plugin/notification', 'navigator.notification'); modulemapper.merges('cordova/plugin/android/notification', 'navigator.notification'); }); // file: lib/common/plugin/requestFileSystem.js define("cordova/plugin/requestFileSystem", function(require, exports, module) { var argscheck = require('cordova/argscheck'), FileError = require('cordova/plugin/FileError'), FileSystem = require('cordova/plugin/FileSystem'), exec = require('cordova/exec'); /** * Request a file system in which to store application data. * @param type local file system type * @param size indicates how much storage space, in bytes, the application expects to need * @param successCallback invoked with a FileSystem object * @param errorCallback invoked if error occurs retrieving file system */ var requestFileSystem = function(type, size, successCallback, errorCallback) { argscheck.checkArgs('nnFF', 'requestFileSystem', arguments); var fail = function(code) { errorCallback && errorCallback(new FileError(code)); }; if (type < 0 || type > 3) { fail(FileError.SYNTAX_ERR); } else { // if successful, return a FileSystem object var success = function(file_system) { if (file_system) { if (successCallback) { // grab the name and root from the file system object var result = new FileSystem(file_system.name, file_system.root); successCallback(result); } } else { // no FileSystem object returned fail(FileError.NOT_FOUND_ERR); } }; exec(success, fail, "File", "requestFileSystem", [type, size]); } }; module.exports = requestFileSystem; }); // file: lib/common/plugin/resolveLocalFileSystemURI.js define("cordova/plugin/resolveLocalFileSystemURI", function(require, exports, module) { var argscheck = require('cordova/argscheck'), DirectoryEntry = require('cordova/plugin/DirectoryEntry'), FileEntry = require('cordova/plugin/FileEntry'), FileError = require('cordova/plugin/FileError'), exec = require('cordova/exec'); /** * Look up file system Entry referred to by local URI. * @param {DOMString} uri URI referring to a local file or directory * @param successCallback invoked with Entry object corresponding to URI * @param errorCallback invoked if error occurs retrieving file system entry */ module.exports = function(uri, successCallback, errorCallback) { argscheck.checkArgs('sFF', 'resolveLocalFileSystemURI', arguments); // error callback var fail = function(error) { errorCallback && errorCallback(new FileError(error)); }; // sanity check for 'not:valid:filename' if(!uri || uri.split(":").length > 2) { setTimeout( function() { fail(FileError.ENCODING_ERR); },0); return; } // if successful, return either a file or directory entry var success = function(entry) { var result; if (entry) { if (successCallback) { // create appropriate Entry object result = (entry.isDirectory) ? new DirectoryEntry(entry.name, entry.fullPath) : new FileEntry(entry.name, entry.fullPath); successCallback(result); } } else { // no Entry object returned fail(FileError.NOT_FOUND_ERR); } }; exec(success, fail, "File", "resolveLocalFileSystemURI", [uri]); }; }); // file: lib/common/plugin/splashscreen.js define("cordova/plugin/splashscreen", function(require, exports, module) { var exec = require('cordova/exec'); var splashscreen = { show:function() { exec(null, null, "SplashScreen", "show", []); }, hide:function() { exec(null, null, "SplashScreen", "hide", []); } }; module.exports = splashscreen; }); // file: lib/common/plugin/splashscreen/symbols.js define("cordova/plugin/splashscreen/symbols", function(require, exports, module) { var modulemapper = require('cordova/modulemapper'); modulemapper.clobbers('cordova/plugin/splashscreen', 'navigator.splashscreen'); }); // file: lib/common/symbols.js define("cordova/symbols", function(require, exports, module) { var modulemapper = require('cordova/modulemapper'); // Use merges here in case others symbols files depend on this running first, // but fail to declare the dependency with a require(). modulemapper.merges('cordova', 'cordova'); modulemapper.clobbers('cordova/exec', 'cordova.exec'); modulemapper.clobbers('cordova/exec', 'Cordova.exec'); }); // file: lib/common/utils.js define("cordova/utils", function(require, exports, module) { var utils = exports; /** * Defines a property getter / setter for obj[key]. */ utils.defineGetterSetter = function(obj, key, getFunc, opt_setFunc) { if (Object.defineProperty) { var desc = { get: getFunc, configurable: true }; if (opt_setFunc) { desc.set = opt_setFunc; } Object.defineProperty(obj, key, desc); } else { obj.__defineGetter__(key, getFunc); if (opt_setFunc) { obj.__defineSetter__(key, opt_setFunc); } } }; /** * Defines a property getter for obj[key]. */ utils.defineGetter = utils.defineGetterSetter; utils.arrayIndexOf = function(a, item) { if (a.indexOf) { return a.indexOf(item); } var len = a.length; for (var i = 0; i < len; ++i) { if (a[i] == item) { return i; } } return -1; }; /** * Returns whether the item was found in the array. */ utils.arrayRemove = function(a, item) { var index = utils.arrayIndexOf(a, item); if (index != -1) { a.splice(index, 1); } return index != -1; }; utils.typeName = function(val) { return Object.prototype.toString.call(val).slice(8, -1); }; /** * Returns an indication of whether the argument is an array or not */ utils.isArray = function(a) { return utils.typeName(a) == 'Array'; }; /** * Returns an indication of whether the argument is a Date or not */ utils.isDate = function(d) { return utils.typeName(d) == 'Date'; }; /** * Does a deep clone of the object. */ utils.clone = function(obj) { if(!obj || typeof obj == 'function' || utils.isDate(obj) || typeof obj != 'object') { return obj; } var retVal, i; if(utils.isArray(obj)){ retVal = []; for(i = 0; i < obj.length; ++i){ retVal.push(utils.clone(obj[i])); } return retVal; } retVal = {}; for(i in obj){ if(!(i in retVal) || retVal[i] != obj[i]) { retVal[i] = utils.clone(obj[i]); } } return retVal; }; /** * Returns a wrapped version of the function */ utils.close = function(context, func, params) { if (typeof params == 'undefined') { return function() { return func.apply(context, arguments); }; } else { return function() { return func.apply(context, params); }; } }; /** * Create a UUID */ utils.createUUID = function() { return UUIDcreatePart(4) + '-' + UUIDcreatePart(2) + '-' + UUIDcreatePart(2) + '-' + UUIDcreatePart(2) + '-' + UUIDcreatePart(6); }; /** * Extends a child object from a parent object using classical inheritance * pattern. */ utils.extend = (function() { // proxy used to establish prototype chain var F = function() {}; // extend Child from Parent return function(Child, Parent) { F.prototype = Parent.prototype; Child.prototype = new F(); Child.__super__ = Parent.prototype; Child.prototype.constructor = Child; }; }()); /** * Alerts a message in any available way: alert or console.log. */ utils.alert = function(msg) { if (window.alert) { window.alert(msg); } else if (console && console.log) { console.log(msg); } }; /** * Formats a string and arguments following it ala sprintf() * * see utils.vformat() for more information */ utils.format = function(formatString /* ,... */) { var args = [].slice.call(arguments, 1); return utils.vformat(formatString, args); }; /** * Formats a string and arguments following it ala vsprintf() * * format chars: * %j - format arg as JSON * %o - format arg as JSON * %c - format arg as '' * %% - replace with '%' * any other char following % will format it's * arg via toString(). * * for rationale, see FireBug's Console API: * http://getfirebug.com/wiki/index.php/Console_API */ utils.vformat = function(formatString, args) { if (formatString === null || formatString === undefined) return ""; if (arguments.length == 1) return formatString.toString(); if (typeof formatString != "string") return formatString.toString(); var pattern = /(.*?)%(.)(.*)/; var rest = formatString; var result = []; while (args.length) { var arg = args.shift(); var match = pattern.exec(rest); if (!match) break; rest = match[3]; result.push(match[1]); if (match[2] == '%') { result.push('%'); args.unshift(arg); continue; } result.push(formatted(arg, match[2])); } result.push(rest); return result.join(''); }; //------------------------------------------------------------------------------ function UUIDcreatePart(length) { var uuidpart = ""; for (var i=0; i<length; i++) { var uuidchar = parseInt((Math.random() * 256), 10).toString(16); if (uuidchar.length == 1) { uuidchar = "0" + uuidchar; } uuidpart += uuidchar; } return uuidpart; } //------------------------------------------------------------------------------ function formatted(object, formatChar) { try { switch(formatChar) { case 'j': case 'o': return JSON.stringify(object); case 'c': return ''; } } catch (e) { return "error JSON.stringify()ing argument: " + e; } if ((object === null) || (object === undefined)) { return Object.prototype.toString.call(object); } return object.toString(); } }); window.cordova = require('cordova'); // file: lib/scripts/bootstrap.js (function (context) { // Replace navigator before any modules are required(), to ensure it happens as soon as possible. // We replace it so that properties that can't be clobbered can instead be overridden. if (context.navigator) { var CordovaNavigator = function() {}; CordovaNavigator.prototype = context.navigator; context.navigator = new CordovaNavigator(); } var channel = require("cordova/channel"), _self = { boot: function () { /** * Create all cordova objects once page has fully loaded and native side is ready. */ channel.join(function() { var builder = require('cordova/builder'), platform = require('cordova/platform'); builder.buildIntoButDoNotClobber(platform.defaults, context); builder.buildIntoAndClobber(platform.clobbers, context); builder.buildIntoAndMerge(platform.merges, context); // Call the platform-specific initialization platform.initialize(); // Fire event to notify that all objects are created channel.onCordovaReady.fire(); // Fire onDeviceReady event once all constructors have run and // cordova info has been received from native side. channel.join(function() { require('cordova').fireDocumentEvent('deviceready'); }, channel.deviceReadyChannelsArray); }, [ channel.onDOMContentLoaded, channel.onNativeReady ]); } }; // boot up once native side is ready channel.onNativeReady.subscribe(_self.boot); // _nativeReady is global variable that the native side can set // to signify that the native code is ready. It is a global since // it may be called before any cordova JS is ready. if (window._nativeReady) { channel.onNativeReady.fire(); } }(window)); })();var PhoneGap = cordova;
/* @flow */ "use strict"; var _interopRequireDefault = require("babel-runtime/helpers/interop-require-default")["default"]; var _index = require("./index"); var _index2 = _interopRequireDefault(_index); _index2["default"]("AssignmentPattern", { visitor: ["left", "right"], aliases: ["Pattern", "LVal"], fields: { left: { validate: _index.assertNodeType("Identifier") }, right: { validate: _index.assertNodeType("Expression") } } }); _index2["default"]("ArrayPattern", { visitor: ["elements", "typeAnnotation"], aliases: ["Pattern", "LVal"], fields: { elements: { validate: _index.chain(_index.assertValueType("array"), _index.assertEach(_index.assertNodeType("Expression"))) } } }); _index2["default"]("ArrowFunctionExpression", { builder: ["params", "body", "async"], visitor: ["params", "body", "returnType"], aliases: ["Scopable", "Function", "BlockParent", "FunctionParent", "Expression", "Pureish"], fields: { params: { validate: _index.chain(_index.assertValueType("array"), _index.assertEach(_index.assertNodeType("LVal"))) }, body: { validate: _index.assertNodeType("BlockStatement", "Expression") }, async: { validate: _index.assertValueType("boolean"), "default": false } } }); _index2["default"]("ClassBody", { visitor: ["body"], fields: { body: { validate: _index.chain(_index.assertValueType("array"), _index.assertEach(_index.assertNodeType("ClassMethod", "ClassProperty"))) } } }); _index2["default"]("ClassDeclaration", { builder: ["id", "superClass", "body", "decorators"], visitor: ["id", "body", "superClass", "typeParameters", "superTypeParameters", "implements", "decorators"], aliases: ["Scopable", "Class", "Statement", "Declaration", "Pureish"], fields: { id: { validate: _index.assertNodeType("Identifier") }, body: { validate: _index.assertNodeType("ClassBody") }, superClass: { optional: true, validate: _index.assertNodeType("Expression") }, decorators: { validate: _index.chain(_index.assertValueType("array"), _index.assertEach(_index.assertNodeType("Decorator"))) } } }); _index2["default"]("ClassExpression", { inherits: "ClassDeclaration", aliases: ["Scopable", "Class", "Expression", "Pureish"], fields: { id: { optional: true, validate: _index.assertNodeType("Identifier") }, body: { validate: _index.assertNodeType("ClassBody") }, superClass: { optional: true, validate: _index.assertNodeType("Expression") }, decorators: { validate: _index.chain(_index.assertValueType("array"), _index.assertEach(_index.assertNodeType("Decorator"))) } } }); _index2["default"]("ExportAllDeclaration", { visitor: ["source"], aliases: ["Statement", "Declaration", "ModuleDeclaration", "ExportDeclaration"], fields: { source: { validate: _index.assertNodeType("StringLiteral") } } }); _index2["default"]("ExportDefaultDeclaration", { visitor: ["declaration"], aliases: ["Statement", "Declaration", "ModuleDeclaration", "ExportDeclaration"], fields: { declaration: { validate: _index.assertNodeType("FunctionDeclaration", "ClassDeclaration", "Expression") } } }); _index2["default"]("ExportNamedDeclaration", { visitor: ["declaration", "specifiers", "source"], aliases: ["Statement", "Declaration", "ModuleDeclaration", "ExportDeclaration"], fields: { declaration: { validate: _index.assertNodeType("Declaration"), optional: true }, specifiers: { validate: _index.chain(_index.assertValueType("array"), _index.assertEach(_index.assertNodeType("ExportSpecifier"))) }, source: { validate: _index.assertNodeType("StringLiteral"), optional: true } } }); _index2["default"]("ExportSpecifier", { visitor: ["local", "exported"], aliases: ["ModuleSpecifier"], fields: { local: { validate: _index.assertNodeType("Identifier") }, imported: { validate: _index.assertNodeType("Identifier") } } }); _index2["default"]("ForOfStatement", { visitor: ["left", "right", "body"], aliases: ["Scopable", "Statement", "For", "BlockParent", "Loop", "ForXStatement"], fields: { left: { validate: _index.assertNodeType("VariableDeclaration", "LVal") }, right: { validate: _index.assertNodeType("Expression") }, body: { validate: _index.assertNodeType("Statement") } } }); _index2["default"]("ImportDeclaration", { visitor: ["specifiers", "source"], aliases: ["Statement", "Declaration", "ModuleDeclaration"], fields: { specifiers: { validate: _index.chain(_index.assertValueType("array"), _index.assertEach(_index.assertNodeType("ImportSpecifier", "ImportDefaultSpecifier", "ImportNamespaceSpecifier"))) }, source: { validate: _index.assertNodeType("StringLiteral") } } }); _index2["default"]("ImportDefaultSpecifier", { visitor: ["local"], aliases: ["ModuleSpecifier"], fields: { local: { validate: _index.assertNodeType("Identifier") } } }); _index2["default"]("ImportNamespaceSpecifier", { visitor: ["local"], aliases: ["ModuleSpecifier"], fields: { local: { validate: _index.assertNodeType("Identifier") } } }); _index2["default"]("ImportSpecifier", { visitor: ["local", "imported"], aliases: ["ModuleSpecifier"], fields: { local: { validate: _index.assertNodeType("Identifier") }, imported: { validate: _index.assertNodeType("Identifier") } } }); _index2["default"]("MetaProperty", { visitor: ["meta", "property"], aliases: ["Expression"], fields: { // todo: limit to new.target meta: { validate: _index.assertValueType("string") }, property: { validate: _index.assertValueType("string") } } }); _index2["default"]("ClassMethod", { aliases: ["Function", "Scopable", "BlockParent", "FunctionParent", "Method"], builder: ["kind", "key", "params", "body", "computed", "static"], visitor: ["key", "params", "body", "decorators", "returnType", "typeParameters"], fields: { kind: { validate: _index.chain(_index.assertValueType("string"), _index.assertOneOf("get", "set", "method", "constructor")), "default": "method" }, computed: { "default": false, validate: _index.assertValueType("boolean") }, "static": { "default": false, validate: _index.assertValueType("boolean") }, key: { validate: function validate(node, key, val) { var expectedTypes = node.computed ? ["Expression"] : ["Identifier", "Literal"]; _index.assertNodeType.apply(undefined, expectedTypes)(node, key, val); } }, params: { validate: _index.chain(_index.assertValueType("array"), _index.assertEach(_index.assertNodeType("LVal"))) }, body: { validate: _index.assertNodeType("BlockStatement") }, generator: { "default": false, validate: _index.assertValueType("boolean") }, async: { "default": false, validate: _index.assertValueType("boolean") } } }); _index2["default"]("ObjectPattern", { visitor: ["properties", "typeAnnotation"], aliases: ["Pattern", "LVal"], fields: { properties: { validate: _index.chain(_index.assertValueType("array"), _index.assertEach(_index.assertNodeType("RestProperty", "Property"))) } } }); _index2["default"]("SpreadElement", { visitor: ["argument"], aliases: ["UnaryLike"], fields: { argument: { validate: _index.assertNodeType("Expression") } } }); _index2["default"]("Super", { aliases: ["Expression"] }); _index2["default"]("TaggedTemplateExpression", { visitor: ["tag", "quasi"], aliases: ["Expression"], fields: { tag: { validate: _index.assertNodeType("Expression") }, quasi: { validate: _index.assertNodeType("TemplateLiteral") } } }); _index2["default"]("TemplateElement", { builder: ["value", "tail"], fields: { value: { // todo: flatten `raw` into main node }, tail: { validate: _index.assertValueType("boolean"), "default": false } } }); _index2["default"]("TemplateLiteral", { visitor: ["quasis", "expressions"], aliases: ["Expression", "Literal"], fields: { // todo } }); _index2["default"]("YieldExpression", { builder: ["argument", "delegate"], visitor: ["argument"], aliases: ["Expression", "Terminatorless"], fields: { delegate: { validate: _index.assertValueType("boolean"), "default": false }, argument: { optional: true, validate: _index.assertNodeType("Expression") } } });
// Copyright 2006 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Manages a pool of XhrIo's. This handles all the details of * dealing with the XhrPool and provides a simple interface for sending requests * and managing events. * * This class supports queueing & prioritization of requests (XhrIoPool * handles this) and retrying of requests. * * The events fired by the XhrManager are an aggregation of the events of * each of its XhrIo objects (with some filtering, i.e., ERROR only called * when there are no more retries left). For this reason, all send requests have * to have an id, so that the user of this object can know which event is for * which request. * */ goog.provide('goog.net.XhrManager'); goog.provide('goog.net.XhrManager.Event'); goog.provide('goog.net.XhrManager.Request'); goog.require('goog.Disposable'); goog.require('goog.events'); goog.require('goog.events.Event'); goog.require('goog.events.EventHandler'); goog.require('goog.events.EventTarget'); goog.require('goog.net.EventType'); goog.require('goog.net.XhrIo'); goog.require('goog.net.XhrIoPool'); goog.require('goog.structs.Map'); // TODO(user): Add some time in between retries. /** * A manager of an XhrIoPool. * @param {number=} opt_maxRetries Max. number of retries (Default: 1). * @param {goog.structs.Map=} opt_headers Map of default headers to add to every * request. * @param {number=} opt_minCount Min. number of objects (Default: 1). * @param {number=} opt_maxCount Max. number of objects (Default: 10). * @param {number=} opt_timeoutInterval Timeout (in ms) before aborting an * attempt (Default: 0ms). * @constructor * @extends {goog.events.EventTarget} */ goog.net.XhrManager = function( opt_maxRetries, opt_headers, opt_minCount, opt_maxCount, opt_timeoutInterval) { /** * Maximum number of retries for a given request * @type {number} * @private */ this.maxRetries_ = goog.isDef(opt_maxRetries) ? opt_maxRetries : 1; /** * Timeout interval for an attempt of a given request. * @type {number} * @private */ this.timeoutInterval_ = goog.isDef(opt_timeoutInterval) ? Math.max(0, opt_timeoutInterval) : 0; /** * The pool of XhrIo's to use. * @type {goog.net.XhrIoPool} * @private */ this.xhrPool_ = new goog.net.XhrIoPool( opt_headers, opt_minCount, opt_maxCount); /** * Map of ID's to requests. * @type {goog.structs.Map} * @private */ this.requests_ = new goog.structs.Map(); /** * The event handler. * @type {goog.events.EventHandler} * @private */ this.eventHandler_ = new goog.events.EventHandler(this); }; goog.inherits(goog.net.XhrManager, goog.events.EventTarget); /** * Error to throw when a send is attempted with an ID that the manager already * has registered for another request. * @type {string} * @private */ goog.net.XhrManager.ERROR_ID_IN_USE_ = '[goog.net.XhrManager] ID in use'; /** * The goog.net.EventType's to listen/unlisten for on the XhrIo object. * @type {Array.<goog.net.EventType>} * @private */ goog.net.XhrManager.XHR_EVENT_TYPES_ = [ goog.net.EventType.READY, goog.net.EventType.COMPLETE, goog.net.EventType.SUCCESS, goog.net.EventType.ERROR, goog.net.EventType.ABORT, goog.net.EventType.TIMEOUT]; /** * Sets the number of milliseconds after which an incomplete request will be * aborted. Zero means no timeout is set. * @param {number} ms Timeout interval in milliseconds; 0 means none. */ goog.net.XhrManager.prototype.setTimeoutInterval = function(ms) { this.timeoutInterval_ = Math.max(0, ms); }; /** * Returns the number of reuqests either in flight, or waiting to be sent. * @return {number} The number of requests in flight or pending send. */ goog.net.XhrManager.prototype.getOutstandingCount = function() { return this.requests_.getCount(); }; /** * Registers the given request to be sent. Throws an error if a request * already exists with the given ID. * NOTE: It is not sent immediately. It is queued and will be sent when an * XhrIo object becomes available, taking into account the request's * priority. * @param {string} id The id of the request. * @param {string} url Uri to make the request too. * @param {string=} opt_method Send method, default: GET. * @param {string=} opt_content Post data. * @param {Object|goog.structs.Map=} opt_headers Map of headers to add to the * request. * @param {*=} opt_priority The priority of the request. * @param {Function=} opt_callback Callback function for when request is * complete. The only param is the event object from the COMPLETE event. * @param {number=} opt_maxRetries The maximum number of times the request * should be retried. * @return {goog.net.XhrManager.Request} The queued request object. */ goog.net.XhrManager.prototype.send = function( id, url, opt_method, opt_content, opt_headers, opt_priority, opt_callback, opt_maxRetries) { var requests = this.requests_; // Check if there is already a request with the given id. if (requests.get(id)) { throw Error(goog.net.XhrManager.ERROR_ID_IN_USE_); } // Make the Request object. var request = new goog.net.XhrManager.Request( url, goog.bind(this.handleEvent_, this, id), opt_method, opt_content, opt_headers, opt_callback, goog.isDef(opt_maxRetries) ? opt_maxRetries : this.maxRetries_); this.requests_.set(id, request); // Setup the callback for the pool. var callback = goog.bind(this.handleAvailableXhr_, this, id); this.xhrPool_.getObject(callback, opt_priority); return request; }; /** * Aborts the request associated with id. * @param {string} id The id of the request to abort. * @param {boolean=} opt_force If true, remove the id now so it can be reused. * No events are fired and the callback is not called when forced. */ goog.net.XhrManager.prototype.abort = function(id, opt_force) { var request = this.requests_.get(id); if (request) { var xhrIo = request.xhrIo; request.setAborted(true); if (opt_force) { // We remove listeners to make sure nothing gets called if a new request // with the same id is made. this.removeXhrListener_(xhrIo, request.getXhrEventCallback()); goog.events.listenOnce( xhrIo, goog.net.EventType.READY, function() { this.xhrPool_.releaseObject(xhrIo); }, false, this); this.requests_.remove(id); } if (xhrIo) { xhrIo.abort(); } } }; /** * Handles when an XhrIo object becomes available. Sets up the events, fires * the READY event, and starts the process to send the request. * @param {string} id The id of the request the XhrIo is for. * @param {goog.net.XhrIo} xhrIo The available XhrIo object. * @private */ goog.net.XhrManager.prototype.handleAvailableXhr_ = function(id, xhrIo) { var request = this.requests_.get(id); // Make sure the request doesn't already have an XhrIo attached. This can // happen if a forced abort occurs before an XhrIo is available, and a new // request with the same id is made. if (request && !request.xhrIo) { this.addXhrListener_(xhrIo, request.getXhrEventCallback()); // Set properties for the XhrIo. xhrIo.setTimeoutInterval(this.timeoutInterval_); // Add a reference to the XhrIo object to the request. request.xhrIo = request.xhrLite = xhrIo; // Notify the listeners. this.dispatchEvent(new goog.net.XhrManager.Event( goog.net.EventType.READY, this, id, xhrIo)); // Send the request. this.retry_(id, xhrIo); // If the request was aborted before it got an XhrIo object, abort it now. if (request.getAborted()) { xhrIo.abort(); } } else { // If the request has an XhrIo object already, or no request exists, just // return the XhrIo back to the pool. this.xhrPool_.releaseObject(xhrIo); } }; /** * Handles all events fired by the XhrIo object for a given request. * @param {string} id The id of the request. * @param {goog.events.Event} e The event. * @return {Object} The return value from the handler, if any. * @private */ goog.net.XhrManager.prototype.handleEvent_ = function(id, e) { var xhrIo = /** @type {goog.net.XhrIo} */(e.target); switch (e.type) { case goog.net.EventType.READY: this.retry_(id, xhrIo); break; case goog.net.EventType.COMPLETE: return this.handleComplete_(id, xhrIo, e); case goog.net.EventType.SUCCESS: this.handleSuccess_(id, xhrIo); break; // A timeout is handled like an error. case goog.net.EventType.TIMEOUT: case goog.net.EventType.ERROR: this.handleError_(id, xhrIo); break; case goog.net.EventType.ABORT: this.handleAbort_(id, xhrIo); break; } return null; }; /** * Attempts to retry the given request. If the request has already attempted * the maximum number of retries, then it removes the request and releases * the XhrIo object back into the pool. * @param {string} id The id of the request. * @param {goog.net.XhrIo} xhrIo The XhrIo object. * @private */ goog.net.XhrManager.prototype.retry_ = function(id, xhrIo) { var request = this.requests_.get(id); // If the request has not completed and it is below its max. retries. if (request && !request.getCompleted() && !request.hasReachedMaxRetries()) { request.increaseAttemptCount(); xhrIo.send(request.getUrl(), request.getMethod(), request.getContent(), request.getHeaders()); } else { if (request) { // Remove the events on the XhrIo objects. this.removeXhrListener_(xhrIo, request.getXhrEventCallback()); // Remove the request. this.requests_.remove(id); } // Release the XhrIo object back into the pool. this.xhrPool_.releaseObject(xhrIo); } }; /** * Handles the complete of a request. Dispatches the COMPLETE event and sets the * the request as completed if the request has succeeded, or is done retrying. * @param {string} id The id of the request. * @param {goog.net.XhrIo} xhrIo The XhrIo object. * @param {goog.events.Event} e The original event. * @return {Object} The return value from the callback, if any. * @private */ goog.net.XhrManager.prototype.handleComplete_ = function(id, xhrIo, e) { // Only if the request is done processing should a COMPLETE event be fired. var request = this.requests_.get(id); if (xhrIo.getLastErrorCode() == goog.net.ErrorCode.ABORT || xhrIo.isSuccess() || request.hasReachedMaxRetries()) { this.dispatchEvent(new goog.net.XhrManager.Event( goog.net.EventType.COMPLETE, this, id, xhrIo)); // If the request exists, we mark it as completed and call the callback if (request) { request.setCompleted(true); // Call the complete callback as if it was set as a COMPLETE event on the // XhrIo directly. if (request.getCompleteCallback()) { return request.getCompleteCallback().call(xhrIo, e); } } } return null; }; /** * Handles the abort of an underlying XhrIo object. * @param {string} id The id of the request. * @param {goog.net.XhrIo} xhrIo The XhrIo object. * @private */ goog.net.XhrManager.prototype.handleAbort_ = function(id, xhrIo) { // Fire event. // NOTE: The complete event should always be fired before the abort event, so // the bulk of the work is done in handleComplete. this.dispatchEvent(new goog.net.XhrManager.Event( goog.net.EventType.ABORT, this, id, xhrIo)); }; /** * Handles the success of a request. Dispatches the SUCCESS event and sets the * the request as completed. * @param {string} id The id of the request. * @param {goog.net.XhrIo} xhrIo The XhrIo object. * @private */ goog.net.XhrManager.prototype.handleSuccess_ = function(id, xhrIo) { // Fire event. // NOTE: We don't release the XhrIo object from the pool here. // It is released in the retry method, when we know it is back in the // ready state. this.dispatchEvent(new goog.net.XhrManager.Event( goog.net.EventType.SUCCESS, this, id, xhrIo)); }; /** * Handles the error of a request. If the request has not reach its maximum * number of retries, then it lets the request retry naturally (will let the * request hit the READY state). Else, it dispatches the ERROR event. * @param {string} id The id of the request. * @param {goog.net.XhrIo} xhrIo The XhrIo object. * @private */ goog.net.XhrManager.prototype.handleError_ = function(id, xhrIo) { var request = this.requests_.get(id); // If the maximum number of retries has been reached. if (request.hasReachedMaxRetries()) { // Fire event. // NOTE: We don't release the XhrIo object from the pool here. // It is released in the retry method, when we know it is back in the // ready state. this.dispatchEvent(new goog.net.XhrManager.Event( goog.net.EventType.ERROR, this, id, xhrIo)); } }; /** * Remove listeners for XHR events on an XhrIo object. * @param {goog.net.XhrIo} xhrIo The object to stop listenening to events on. * @param {Function} func The callback to remove from event handling. * @param {string|Array.<string>=} opt_types Event types to remove listeners * for. Defaults to XHR_EVENT_TYPES_. * @private */ goog.net.XhrManager.prototype.removeXhrListener_ = function(xhrIo, func, opt_types) { var types = opt_types || goog.net.XhrManager.XHR_EVENT_TYPES_; this.eventHandler_.unlisten(xhrIo, types, func); }; /** * Adds a listener for XHR events on an XhrIo object. * @param {goog.net.XhrIo} xhrIo The object listen to events on. * @param {Function} func The callback when the event occurs. * @param {string|Array.<string>=} opt_types Event types to attach listeners to. * Defaults to XHR_EVENT_TYPES_. * @private */ goog.net.XhrManager.prototype.addXhrListener_ = function(xhrIo, func, opt_types) { var types = opt_types || goog.net.XhrManager.XHR_EVENT_TYPES_; this.eventHandler_.listen(xhrIo, types, func); }; /** * Disposes of the manager. */ goog.net.XhrManager.prototype.disposeInternal = function() { goog.net.XhrManager.superClass_.disposeInternal.call(this); this.xhrPool_.dispose(); this.xhrPool_ = null; this.eventHandler_.dispose(); this.eventHandler_ = null; // Call dispose on each request. var requests = this.requests_; goog.structs.forEach(requests, function(value, key) { value.dispose(); }); requests.clear(); this.requests_ = null; }; /** * An event dispatched by XhrManager. * * @param {goog.net.EventType} type Event Type. * @param {goog.net.XhrManager} target Reference to the object that is the * target of this event. * @param {string} id The id of the request this event is for. * @param {goog.net.XhrIo} xhrIo The XhrIo object of the request. * @constructor * @extends {goog.events.Event} */ goog.net.XhrManager.Event = function(type, target, id, xhrIo) { goog.events.Event.call(this, type, target); /** * The id of the request this event is for. * @type {string} */ this.id = id; /** * The XhrIo object of the request. * @type {goog.net.XhrIo} */ this.xhrIo = xhrIo; /** * The xhrLite field aliases xhrIo for backwards compatibility. * @type {goog.net.XhrLite} */ this.xhrLite = /** @type {goog.net.XhrLite} */ (xhrIo); }; goog.inherits(goog.net.XhrManager.Event, goog.events.Event); /** * Disposes of the event. */ goog.net.XhrManager.Event.prototype.disposeInternal = function() { goog.net.XhrManager.Event.superClass_.disposeInternal.call(this); delete this.id; this.xhrIo = null; this.xhrLite = null; }; /** * An encapsulation of everything needed to make a Xhr request. * NOTE: This is used internal to the XhrManager. * * @param {string} url Uri to make the request too. * @param {Function} xhrEventCallback Callback attached to the events of the * XhrIo object of the request. * @param {string=} opt_method Send method, default: GET. * @param {string=} opt_content Post data. * @param {Object|goog.structs.Map=} opt_headers Map of headers to add to the * request. * @param {Function=} opt_callback Callback function for when request is * complete. NOTE: Only 1 callback supported across all events. * @param {number=} opt_maxRetries The maximum number of times the request * should be retried (Default: 1). * * @constructor * @extends {goog.Disposable} */ goog.net.XhrManager.Request = function(url, xhrEventCallback, opt_method, opt_content, opt_headers, opt_callback, opt_maxRetries) { goog.Disposable.call(this); /** * Uri to make the request too. * @type {string} * @private */ this.url_ = url; /** * Send method. * @type {string} * @private */ this.method_ = opt_method || 'GET'; /** * Post data. * @type {string|undefined} * @private */ this.content_ = opt_content; /** * Map of headers * @type {Object|goog.structs.Map|null} * @private */ this.headers_ = opt_headers || null; /** * The maximum number of times the request should be retried. * @type {number} * @private */ this.maxRetries_ = goog.isDef(opt_maxRetries) ? opt_maxRetries : 1; /** * The number of attempts so far. * @type {number} * @private */ this.attemptCount_ = 0; /** * Whether the request has been completed. * @type {boolean} * @private */ this.completed_ = false; /** * Whether the request has been aborted. * @type {boolean} * @private */ this.aborted_ = false; /** * Callback attached to the events of the XhrIo object. * @type {Function|undefined} * @private */ this.xhrEventCallback_ = xhrEventCallback; /** * Callback function called when request is complete. * @type {Function|undefined} * @private */ this.completeCallback_ = opt_callback; /** * The XhrIo instance handling this request. Set in handleAvailableXhr. * @type {goog.net.XhrIo} */ this.xhrIo = null; }; goog.inherits(goog.net.XhrManager.Request, goog.Disposable); /** * Gets the uri. * @return {string} The uri to make the request to. */ goog.net.XhrManager.Request.prototype.getUrl = function() { return this.url_; }; /** * Gets the send method. * @return {string} The send method. */ goog.net.XhrManager.Request.prototype.getMethod = function() { return this.method_; }; /** * Gets the post data. * @return {string|undefined} The post data. */ goog.net.XhrManager.Request.prototype.getContent = function() { return this.content_; }; /** * Gets the map of headers. * @return {Object|goog.structs.Map} The map of headers. */ goog.net.XhrManager.Request.prototype.getHeaders = function() { return this.headers_; }; /** * Gets the maximum number of times the request should be retried. * @return {number} The maximum number of times the request should be retried. */ goog.net.XhrManager.Request.prototype.getMaxRetries = function() { return this.maxRetries_; }; /** * Gets the number of attempts so far. * @return {number} The number of attempts so far. */ goog.net.XhrManager.Request.prototype.getAttemptCount = function() { return this.attemptCount_; }; /** * Increases the number of attempts so far. */ goog.net.XhrManager.Request.prototype.increaseAttemptCount = function() { this.attemptCount_++; }; /** * Returns whether the request has reached the maximum number of retries. * @return {boolean} Whether the request has reached the maximum number of * retries. */ goog.net.XhrManager.Request.prototype.hasReachedMaxRetries = function() { return this.attemptCount_ > this.maxRetries_; }; /** * Sets the completed status. * @param {boolean} complete The completed status. */ goog.net.XhrManager.Request.prototype.setCompleted = function(complete) { this.completed_ = complete; }; /** * Gets the completed status. * @return {boolean} The completed status. */ goog.net.XhrManager.Request.prototype.getCompleted = function() { return this.completed_; }; /** * Sets the aborted status. * @param {boolean} aborted True if the request was aborted, otherwise False. */ goog.net.XhrManager.Request.prototype.setAborted = function(aborted) { this.aborted_ = aborted; }; /** * Gets the aborted status. * @return {boolean} True if request was aborted, otherwise False. */ goog.net.XhrManager.Request.prototype.getAborted = function() { return this.aborted_; }; /** * Gets the callback attached to the events of the XhrIo object. * @return {Function|undefined} The callback attached to the events of the * XhrIo object. */ goog.net.XhrManager.Request.prototype.getXhrEventCallback = function() { return this.xhrEventCallback_; }; /** * Gets the callback for when the request is complete. * @return {Function|undefined} The callback for when the request is complete. */ goog.net.XhrManager.Request.prototype.getCompleteCallback = function() { return this.completeCallback_; }; /** * Disposes of the request. */ goog.net.XhrManager.Request.prototype.disposeInternal = function() { goog.net.XhrManager.Request.superClass_.disposeInternal.call(this); delete this.xhrEventCallback_; delete this.completeCallback_; };
YUI.add('anim-node-plugin', function(Y) { /** * Binds an Anim instance to a Node instance * @module anim * @namespace plugin * @submodule anim-node-plugin */ var NodeFX = function(config) { config = (config) ? Y.merge(config) : {}; config.node = config.host; NodeFX.superclass.constructor.apply(this, arguments); }; NodeFX.NAME = "nodefx"; NodeFX.NS = "fx"; Y.extend(NodeFX, Y.Anim); Y.namespace('Plugin'); Y.Plugin.NodeFX = NodeFX; }, '@VERSION@' ,{requires:['anim-base', 'node-base']});
Package.describe({ summary: "Meteor's client-side datastore: a port of MongoDB to Javascript", version: '1.0.9' }); Package.onUse(function (api) { api.export('LocalCollection'); api.export('Minimongo'); api.export('MinimongoTest', { testOnly: true }); api.use(['underscore', 'ejson', 'id-map', 'ordered-dict', 'tracker', 'mongo-id', 'random', 'diff-sequence']); // This package is used for geo-location queries such as $near api.use('geojson-utils'); // This package is used to get diff results on arrays and objects api.use('diff-sequence'); api.addFiles([ 'minimongo.js', 'wrap_transform.js', 'helpers.js', 'selector.js', 'sort.js', 'projection.js', 'modify.js', 'diff.js', 'id_map.js', 'observe.js', 'objectid.js' ]); // Functionality used only by oplog tailing on the server side api.addFiles([ 'selector_projection.js', 'selector_modifier.js', 'sorter_projection.js' ], 'server'); }); Package.onTest(function (api) { api.use('minimongo', ['client', 'server']); api.use('test-helpers', 'client'); api.use(['tinytest', 'underscore', 'ejson', 'ordered-dict', 'random', 'tracker', 'reactive-var', 'mongo-id']); api.addFiles('minimongo_tests.js', 'client'); api.addFiles('wrap_transform_tests.js'); api.addFiles('minimongo_server_tests.js', 'server'); });
/** * Magellan module. * @module foundation.magellan */ !function(Foundation, $) { 'use strict'; /** * Creates a new instance of Magellan. * @class * @fires Magellan#init * @param {Object} element - jQuery object to add the trigger to. * @param {Object} options - Overrides to the default plugin settings. */ function Magellan(element, options) { this.$element = element; this.options = $.extend({}, Magellan.defaults, this.$element.data(), options); this._init(); Foundation.registerPlugin(this, 'Magellan'); } /** * Default settings for plugin */ Magellan.defaults = { /** * Amount of time, in ms, the animated scrolling should take between locations. * @option * @example 500 */ animationDuration: 500, /** * Animation style to use when scrolling between locations. * @option * @example 'ease-in-out' */ animationEasing: 'linear', /** * Number of pixels to use as a marker for location changes. * @option * @example 50 */ threshold: 50, /** * Class applied to the active locations link on the magellan container. * @option * @example 'active' */ activeClass: 'active', /** * Allows the script to manipulate the url of the current page, and if supported, alter the history. * @option * @example true */ deepLinking: false, /** * Number of pixels to offset the scroll of the page on item click if using a sticky nav bar. * @option * @example 25 */ barOffset: 0 }; /** * Initializes the Magellan plugin and calls functions to get equalizer functioning on load. * @private */ Magellan.prototype._init = function() { var id = this.$element[0].id || Foundation.GetYoDigits(6, 'magellan'), _this = this; this.$targets = $('[data-magellan-target]'); this.$links = this.$element.find('a'); this.$element.attr({ 'data-resize': id, 'data-scroll': id, 'id': id }); this.$active = $(); this.scrollPos = parseInt(window.pageYOffset, 10); this._events(); }; /** * Calculates an array of pixel values that are the demarcation lines between locations on the page. * Can be invoked if new elements are added or the size of a location changes. * @function */ Magellan.prototype.calcPoints = function(){ var _this = this, body = document.body, html = document.documentElement; this.points = []; this.winHeight = Math.round(Math.max(window.innerHeight, html.clientHeight)); this.docHeight = Math.round(Math.max(body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight)); this.$targets.each(function(){ var $tar = $(this), pt = Math.round($tar.offset().top - _this.options.threshold); $tar.targetPoint = pt; _this.points.push(pt); }); }; /** * Initializes events for Magellan. * @private */ Magellan.prototype._events = function() { var _this = this, $body = $('html, body'), opts = { duration: _this.options.animationDuration, easing: _this.options.animationEasing }; $(window).one('load', function(){ if(_this.options.deepLinking){ if(location.hash){ _this.scrollToLoc(location.hash); } } _this.calcPoints(); _this._updateActive(); }); this.$element.on({ 'resizeme.zf.trigger': this.reflow.bind(this), 'scrollme.zf.trigger': this._updateActive.bind(this) }).on('click.zf.magellan', 'a[href^="#"]', function(e) { e.preventDefault(); var arrival = this.getAttribute('href'); _this.scrollToLoc(arrival); }); }; /** * Function to scroll to a given location on the page. * @param {String} loc - a properly formatted jQuery id selector. * @example '#foo' * @function */ Magellan.prototype.scrollToLoc = function(loc){ var scrollPos = $(loc).offset().top - this.options.threshold / 2 - this.options.barOffset; $(document.body).stop(true).animate({ scrollTop: scrollPos }, { duration: this.options.animationDuration, easiing: this.options.animationEasing }); }; /** * Calls necessary functions to update Magellan upon DOM change * @function */ Magellan.prototype.reflow = function(){ this.calcPoints(); this._updateActive(); }; /** * Updates the visibility of an active location link, and updates the url hash for the page, if deepLinking enabled. * @private * @function * @fires Magellan#update */ Magellan.prototype._updateActive = function(/*evt, elem, scrollPos*/){ var winPos = /*scrollPos ||*/ parseInt(window.pageYOffset, 10), curIdx; if(winPos + this.winHeight === this.docHeight){ curIdx = this.points.length - 1; } else if(winPos < this.points[0]){ curIdx = 0; } else{ var isDown = this.scrollPos < winPos, _this = this, curVisible = this.points.filter(function(p, i){ return isDown ? p <= winPos : p - _this.options.threshold <= winPos;//&& winPos >= _this.points[i -1] - _this.options.threshold; }); curIdx = curVisible.length ? curVisible.length - 1 : 0; } this.$active.removeClass(this.options.activeClass); this.$active = this.$links.eq(curIdx).addClass(this.options.activeClass); if(this.options.deepLinking){ var hash = this.$active[0].getAttribute('href'); if(window.history.pushState){ window.history.pushState(null, null, hash); }else{ window.location.hash = hash; } } this.scrollPos = winPos; /** * Fires when magellan is finished updating to the new active element. * @event Magellan#update */ this.$element.trigger('update.zf.magellan', [this.$active]); }; /** * Destroys an instance of Magellan and resets the url of the window. * @function */ Magellan.prototype.destroy = function(){ this.$element.off('.zf.trigger .zf.magellan') .find('.' + this.options.activeClass).removeClass(this.options.activeClass); if(this.options.deepLinking){ var hash = this.$active[0].getAttribute('href'); window.location.hash.replace(hash, ''); } Foundation.unregisterPlugin(this); }; Foundation.plugin(Magellan, 'Magellan'); // Exports for AMD/Browserify if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') module.exports = Magellan; if (typeof define === 'function') define(['foundation'], function() { return Magellan; }); }(Foundation, jQuery);
/* Language: Rust Author: Andrey Vlasovskikh <andrey.vlasovskikh@gmail.com> */ function(hljs) { var TITLE = { className: 'title', begin: hljs.UNDERSCORE_IDENT_RE }; var QUOTE_STRING = { className: 'string', begin: '"', end: '"', contains: [hljs.BACKSLASH_ESCAPE], relevance: 0 }; var NUMBER = { className: 'number', begin: '\\b(0[xb][A-Za-z0-9_]+|[0-9_]+(\\.[0-9_]+)?([uif](8|16|32|64)?)?)', relevance: 0 }; var KEYWORDS = 'alt any as assert be bind block bool break char check claim const cont dir do else enum ' + 'export f32 f64 fail false float fn for i16 i32 i64 i8 if iface impl import in int let ' + 'log mod mutable native note of prove pure resource ret self str syntax true type u16 u32 ' + 'u64 u8 uint unchecked unsafe use vec while'; return { defaultMode: { keywords: KEYWORDS, illegal: '</', contains: [ hljs.C_LINE_COMMENT_MODE, hljs.C_BLOCK_COMMENT_MODE, QUOTE_STRING, hljs.APOS_STRING_MODE, NUMBER, { className: 'function', beginWithKeyword: true, end: '(\\(|<)', keywords: 'fn', contains: [TITLE] }, { className: 'preprocessor', begin: '#\\[', end: '\\]' }, { beginWithKeyword: true, end: '(=|<)', keywords: 'type', contains: [TITLE], illegal: '\\S' }, { beginWithKeyword: true, end: '({|<)', keywords: 'iface enum', contains: [TITLE], illegal: '\\S' } ] } }; }
(function () { var image = (function () { 'use strict'; var global = tinymce.util.Tools.resolve('tinymce.PluginManager'); var hasDimensions = function (editor) { return editor.settings.image_dimensions === false ? false : true; }; var hasAdvTab = function (editor) { return editor.settings.image_advtab === true ? true : false; }; var getPrependUrl = function (editor) { return editor.getParam('image_prepend_url', ''); }; var getClassList = function (editor) { return editor.getParam('image_class_list'); }; var hasDescription = function (editor) { return editor.settings.image_description === false ? false : true; }; var hasImageTitle = function (editor) { return editor.settings.image_title === true ? true : false; }; var hasImageCaption = function (editor) { return editor.settings.image_caption === true ? true : false; }; var getImageList = function (editor) { return editor.getParam('image_list', false); }; var hasUploadUrl = function (editor) { return editor.getParam('images_upload_url', false); }; var hasUploadHandler = function (editor) { return editor.getParam('images_upload_handler', false); }; var getUploadUrl = function (editor) { return editor.getParam('images_upload_url'); }; var getUploadHandler = function (editor) { return editor.getParam('images_upload_handler'); }; var getUploadBasePath = function (editor) { return editor.getParam('images_upload_base_path'); }; var getUploadCredentials = function (editor) { return editor.getParam('images_upload_credentials'); }; var $_9cq6y3c6jfuw8p0n = { hasDimensions: hasDimensions, hasAdvTab: hasAdvTab, getPrependUrl: getPrependUrl, getClassList: getClassList, hasDescription: hasDescription, hasImageTitle: hasImageTitle, hasImageCaption: hasImageCaption, getImageList: getImageList, hasUploadUrl: hasUploadUrl, hasUploadHandler: hasUploadHandler, getUploadUrl: getUploadUrl, getUploadHandler: getUploadHandler, getUploadBasePath: getUploadBasePath, getUploadCredentials: getUploadCredentials }; var global$1 = typeof window !== 'undefined' ? window : Function('return this;')(); var path = function (parts, scope) { var o = scope !== undefined && scope !== null ? scope : global$1; for (var i = 0; i < parts.length && o !== undefined && o !== null; ++i) o = o[parts[i]]; return o; }; var resolve = function (p, scope) { var parts = p.split('.'); return path(parts, scope); }; var step = function (o, part) { if (o[part] === undefined || o[part] === null) o[part] = {}; return o[part]; }; var forge = function (parts, target) { var o = target !== undefined ? target : global$1; for (var i = 0; i < parts.length; ++i) o = step(o, parts[i]); return o; }; var namespace = function (name, target) { var parts = name.split('.'); return forge(parts, target); }; var $_5mb36jcajfuw8p19 = { path: path, resolve: resolve, forge: forge, namespace: namespace }; var unsafe = function (name, scope) { return $_5mb36jcajfuw8p19.resolve(name, scope); }; var getOrDie = function (name, scope) { var actual = unsafe(name, scope); if (actual === undefined || actual === null) throw name + ' not available on this browser'; return actual; }; var $_ba69mec9jfuw8p15 = { getOrDie: getOrDie }; function FileReader () { var f = $_ba69mec9jfuw8p15.getOrDie('FileReader'); return new f(); } var global$2 = tinymce.util.Tools.resolve('tinymce.util.Promise'); var global$3 = tinymce.util.Tools.resolve('tinymce.util.Tools'); var global$4 = tinymce.util.Tools.resolve('tinymce.util.XHR'); var parseIntAndGetMax = function (val1, val2) { return Math.max(parseInt(val1, 10), parseInt(val2, 10)); }; var getImageSize = function (url, callback) { var img = document.createElement('img'); function done(width, height) { if (img.parentNode) { img.parentNode.removeChild(img); } callback({ width: width, height: height }); } img.onload = function () { var width = parseIntAndGetMax(img.width, img.clientWidth); var height = parseIntAndGetMax(img.height, img.clientHeight); done(width, height); }; img.onerror = function () { done(0, 0); }; var style = img.style; style.visibility = 'hidden'; style.position = 'fixed'; style.bottom = style.left = '0px'; style.width = style.height = 'auto'; document.body.appendChild(img); img.src = url; }; var buildListItems = function (inputList, itemCallback, startItems) { function appendItems(values, output) { output = output || []; global$3.each(values, function (item) { var menuItem = { text: item.text || item.title }; if (item.menu) { menuItem.menu = appendItems(item.menu); } else { menuItem.value = item.value; itemCallback(menuItem); } output.push(menuItem); }); return output; } return appendItems(inputList, startItems || []); }; var removePixelSuffix = function (value) { if (value) { value = value.replace(/px$/, ''); } return value; }; var addPixelSuffix = function (value) { if (value.length > 0 && /^[0-9]+$/.test(value)) { value += 'px'; } return value; }; var mergeMargins = function (css) { if (css.margin) { var splitMargin = css.margin.split(' '); switch (splitMargin.length) { case 1: css['margin-top'] = css['margin-top'] || splitMargin[0]; css['margin-right'] = css['margin-right'] || splitMargin[0]; css['margin-bottom'] = css['margin-bottom'] || splitMargin[0]; css['margin-left'] = css['margin-left'] || splitMargin[0]; break; case 2: css['margin-top'] = css['margin-top'] || splitMargin[0]; css['margin-right'] = css['margin-right'] || splitMargin[1]; css['margin-bottom'] = css['margin-bottom'] || splitMargin[0]; css['margin-left'] = css['margin-left'] || splitMargin[1]; break; case 3: css['margin-top'] = css['margin-top'] || splitMargin[0]; css['margin-right'] = css['margin-right'] || splitMargin[1]; css['margin-bottom'] = css['margin-bottom'] || splitMargin[2]; css['margin-left'] = css['margin-left'] || splitMargin[1]; break; case 4: css['margin-top'] = css['margin-top'] || splitMargin[0]; css['margin-right'] = css['margin-right'] || splitMargin[1]; css['margin-bottom'] = css['margin-bottom'] || splitMargin[2]; css['margin-left'] = css['margin-left'] || splitMargin[3]; } delete css.margin; } return css; }; var createImageList = function (editor, callback) { var imageList = $_9cq6y3c6jfuw8p0n.getImageList(editor); if (typeof imageList === 'string') { global$4.send({ url: imageList, success: function (text) { callback(JSON.parse(text)); } }); } else if (typeof imageList === 'function') { imageList(callback); } else { callback(imageList); } }; var waitLoadImage = function (editor, data, imgElm) { function selectImage() { imgElm.onload = imgElm.onerror = null; if (editor.selection) { editor.selection.select(imgElm); editor.nodeChanged(); } } imgElm.onload = function () { if (!data.width && !data.height && $_9cq6y3c6jfuw8p0n.hasDimensions(editor)) { editor.dom.setAttribs(imgElm, { width: imgElm.clientWidth, height: imgElm.clientHeight }); } selectImage(); }; imgElm.onerror = selectImage; }; var blobToDataUri = function (blob) { return new global$2(function (resolve, reject) { var reader = new FileReader(); reader.onload = function () { resolve(reader.result); }; reader.onerror = function () { reject(FileReader.error.message); }; reader.readAsDataURL(blob); }); }; var $_7v7yldc7jfuw8p0q = { getImageSize: getImageSize, buildListItems: buildListItems, removePixelSuffix: removePixelSuffix, addPixelSuffix: addPixelSuffix, mergeMargins: mergeMargins, createImageList: createImageList, waitLoadImage: waitLoadImage, blobToDataUri: blobToDataUri }; var global$5 = tinymce.util.Tools.resolve('tinymce.dom.DOMUtils'); var typeOf = function (x) { if (x === null) return 'null'; var t = typeof x; if (t === 'object' && Array.prototype.isPrototypeOf(x)) return 'array'; if (t === 'object' && String.prototype.isPrototypeOf(x)) return 'string'; return t; }; var isType = function (type) { return function (value) { return typeOf(value) === type; }; }; var $_rbqovckjfuw8p27 = { isString: isType('string'), isObject: isType('object'), isArray: isType('array'), isNull: isType('null'), isBoolean: isType('boolean'), isUndefined: isType('undefined'), isFunction: isType('function'), isNumber: isType('number') }; var shallow = function (old, nu) { return nu; }; var deep = function (old, nu) { var bothObjects = $_rbqovckjfuw8p27.isObject(old) && $_rbqovckjfuw8p27.isObject(nu); return bothObjects ? deepMerge(old, nu) : nu; }; var baseMerge = function (merger) { return function () { var objects = new Array(arguments.length); for (var i = 0; i < objects.length; i++) objects[i] = arguments[i]; if (objects.length === 0) throw new Error('Can\'t merge zero objects'); var ret = {}; for (var j = 0; j < objects.length; j++) { var curObject = objects[j]; for (var key in curObject) if (curObject.hasOwnProperty(key)) { ret[key] = merger(ret[key], curObject[key]); } } return ret; }; }; var deepMerge = baseMerge(deep); var merge = baseMerge(shallow); var $_ajpvnqcjjfuw8p25 = { deepMerge: deepMerge, merge: merge }; var DOM = global$5.DOM; var getHspace = function (image) { if (image.style.marginLeft && image.style.marginRight && image.style.marginLeft === image.style.marginRight) { return $_7v7yldc7jfuw8p0q.removePixelSuffix(image.style.marginLeft); } else { return ''; } }; var getVspace = function (image) { if (image.style.marginTop && image.style.marginBottom && image.style.marginTop === image.style.marginBottom) { return $_7v7yldc7jfuw8p0q.removePixelSuffix(image.style.marginTop); } else { return ''; } }; var getBorder = function (image) { if (image.style.borderWidth) { return $_7v7yldc7jfuw8p0q.removePixelSuffix(image.style.borderWidth); } else { return ''; } }; var getAttrib = function (image, name) { if (image.hasAttribute(name)) { return image.getAttribute(name); } else { return ''; } }; var getStyle = function (image, name) { return image.style[name] ? image.style[name] : ''; }; var hasCaption = function (image) { return image.parentNode !== null && image.parentNode.nodeName === 'FIGURE'; }; var setAttrib = function (image, name, value) { image.setAttribute(name, value); }; var wrapInFigure = function (image) { var figureElm = DOM.create('figure', { class: 'image' }); DOM.insertAfter(figureElm, image); figureElm.appendChild(image); figureElm.appendChild(DOM.create('figcaption', { contentEditable: true }, 'Caption')); figureElm.contentEditable = 'false'; }; var removeFigure = function (image) { var figureElm = image.parentNode; DOM.insertAfter(image, figureElm); DOM.remove(figureElm); }; var toggleCaption = function (image) { if (hasCaption(image)) { removeFigure(image); } else { wrapInFigure(image); } }; var normalizeStyle = function (image, normalizeCss) { var attrValue = image.getAttribute('style'); var value = normalizeCss(attrValue !== null ? attrValue : ''); if (value.length > 0) { image.setAttribute('style', value); image.setAttribute('data-mce-style', value); } else { image.removeAttribute('style'); } }; var setSize = function (name, normalizeCss) { return function (image, name, value) { if (image.style[name]) { image.style[name] = $_7v7yldc7jfuw8p0q.addPixelSuffix(value); normalizeStyle(image, normalizeCss); } else { setAttrib(image, name, value); } }; }; var getSize = function (image, name) { if (image.style[name]) { return $_7v7yldc7jfuw8p0q.removePixelSuffix(image.style[name]); } else { return getAttrib(image, name); } }; var setHspace = function (image, value) { var pxValue = $_7v7yldc7jfuw8p0q.addPixelSuffix(value); image.style.marginLeft = pxValue; image.style.marginRight = pxValue; }; var setVspace = function (image, value) { var pxValue = $_7v7yldc7jfuw8p0q.addPixelSuffix(value); image.style.marginTop = pxValue; image.style.marginBottom = pxValue; }; var setBorder = function (image, value) { var pxValue = $_7v7yldc7jfuw8p0q.addPixelSuffix(value); image.style.borderWidth = pxValue; }; var setBorderStyle = function (image, value) { image.style.borderStyle = value; }; var getBorderStyle = function (image) { return getStyle(image, 'borderStyle'); }; var isFigure = function (elm) { return elm.nodeName === 'FIGURE'; }; var defaultData = function () { return { src: '', alt: '', title: '', width: '', height: '', class: '', style: '', caption: false, hspace: '', vspace: '', border: '', borderStyle: '' }; }; var getStyleValue = function (normalizeCss, data) { var image = document.createElement('img'); setAttrib(image, 'style', data.style); if (getHspace(image) || data.hspace !== '') { setHspace(image, data.hspace); } if (getVspace(image) || data.vspace !== '') { setVspace(image, data.vspace); } if (getBorder(image) || data.border !== '') { setBorder(image, data.border); } if (getBorderStyle(image) || data.borderStyle !== '') { setBorderStyle(image, data.borderStyle); } return normalizeCss(image.getAttribute('style')); }; var create = function (normalizeCss, data) { var image = document.createElement('img'); write(normalizeCss, $_ajpvnqcjjfuw8p25.merge(data, { caption: false }), image); setAttrib(image, 'alt', data.alt); if (data.caption) { var figure = DOM.create('figure', { class: 'image' }); figure.appendChild(image); figure.appendChild(DOM.create('figcaption', { contentEditable: true }, 'Caption')); figure.contentEditable = 'false'; return figure; } else { return image; } }; var read = function (normalizeCss, image) { return { src: getAttrib(image, 'src'), alt: getAttrib(image, 'alt'), title: getAttrib(image, 'title'), width: getSize(image, 'width'), height: getSize(image, 'height'), class: getAttrib(image, 'class'), style: normalizeCss(getAttrib(image, 'style')), caption: hasCaption(image), hspace: getHspace(image), vspace: getVspace(image), border: getBorder(image), borderStyle: getStyle(image, 'borderStyle') }; }; var updateProp = function (image, oldData, newData, name, set) { if (newData[name] !== oldData[name]) { set(image, name, newData[name]); } }; var normalized = function (set, normalizeCss) { return function (image, name, value) { set(image, value); normalizeStyle(image, normalizeCss); }; }; var write = function (normalizeCss, newData, image) { var oldData = read(normalizeCss, image); updateProp(image, oldData, newData, 'caption', function (image, _name, _value) { return toggleCaption(image); }); updateProp(image, oldData, newData, 'src', setAttrib); updateProp(image, oldData, newData, 'alt', setAttrib); updateProp(image, oldData, newData, 'title', setAttrib); updateProp(image, oldData, newData, 'width', setSize('width', normalizeCss)); updateProp(image, oldData, newData, 'height', setSize('height', normalizeCss)); updateProp(image, oldData, newData, 'class', setAttrib); updateProp(image, oldData, newData, 'style', normalized(function (image, value) { return setAttrib(image, 'style', value); }, normalizeCss)); updateProp(image, oldData, newData, 'hspace', normalized(setHspace, normalizeCss)); updateProp(image, oldData, newData, 'vspace', normalized(setVspace, normalizeCss)); updateProp(image, oldData, newData, 'border', normalized(setBorder, normalizeCss)); updateProp(image, oldData, newData, 'borderStyle', normalized(setBorderStyle, normalizeCss)); }; var normalizeCss = function (editor, cssText) { var css = editor.dom.styles.parse(cssText); var mergedCss = $_7v7yldc7jfuw8p0q.mergeMargins(css); var compressed = editor.dom.styles.parse(editor.dom.styles.serialize(mergedCss)); return editor.dom.styles.serialize(compressed); }; var getSelectedImage = function (editor) { var imgElm = editor.selection.getNode(); var figureElm = editor.dom.getParent(imgElm, 'figure.image'); if (figureElm) { return editor.dom.select('img', figureElm)[0]; } if (imgElm && (imgElm.nodeName !== 'IMG' || imgElm.getAttribute('data-mce-object') || imgElm.getAttribute('data-mce-placeholder'))) { return null; } return imgElm; }; var splitTextBlock = function (editor, figure) { var dom = editor.dom; var textBlock = dom.getParent(figure.parentNode, function (node) { return editor.schema.getTextBlockElements()[node.nodeName]; }); if (textBlock) { return dom.split(textBlock, figure); } else { return figure; } }; var readImageDataFromSelection = function (editor) { var image = getSelectedImage(editor); return image ? read(function (css) { return normalizeCss(editor, css); }, image) : defaultData(); }; var insertImageAtCaret = function (editor, data) { var elm = create(function (css) { return normalizeCss(editor, css); }, data); editor.dom.setAttrib(elm, 'data-mce-id', '__mcenew'); editor.focus(); editor.selection.setContent(elm.outerHTML); var insertedElm = editor.dom.select('*[data-mce-id="__mcenew"]')[0]; editor.dom.setAttrib(insertedElm, 'data-mce-id', null); if (isFigure(insertedElm)) { var figure = splitTextBlock(editor, insertedElm); editor.selection.select(figure); } else { editor.selection.select(insertedElm); } }; var syncSrcAttr = function (editor, image) { editor.dom.setAttrib(image, 'src', image.getAttribute('src')); }; var deleteImage = function (editor, image) { if (image) { var elm = editor.dom.is(image.parentNode, 'figure.image') ? image.parentNode : image; editor.dom.remove(elm); editor.focus(); editor.nodeChanged(); if (editor.dom.isEmpty(editor.getBody())) { editor.setContent(''); editor.selection.setCursorLocation(); } } }; var writeImageDataToSelection = function (editor, data) { var image = getSelectedImage(editor); write(function (css) { return normalizeCss(editor, css); }, data, image); syncSrcAttr(editor, image); if (isFigure(image.parentNode)) { var figure = image.parentNode; splitTextBlock(editor, figure); editor.selection.select(image.parentNode); } else { editor.selection.select(image); $_7v7yldc7jfuw8p0q.waitLoadImage(editor, data, image); } }; var insertOrUpdateImage = function (editor, data) { var image = getSelectedImage(editor); if (image) { if (data.src) { writeImageDataToSelection(editor, data); } else { deleteImage(editor, image); } } else if (data.src) { insertImageAtCaret(editor, data); } }; var updateVSpaceHSpaceBorder = function (editor) { return function (evt) { var dom = editor.dom; var rootControl = evt.control.rootControl; if (!$_9cq6y3c6jfuw8p0n.hasAdvTab(editor)) { return; } var data = rootControl.toJSON(); var css = dom.parseStyle(data.style); rootControl.find('#vspace').value(''); rootControl.find('#hspace').value(''); css = $_7v7yldc7jfuw8p0q.mergeMargins(css); if (css['margin-top'] && css['margin-bottom'] || css['margin-right'] && css['margin-left']) { if (css['margin-top'] === css['margin-bottom']) { rootControl.find('#vspace').value($_7v7yldc7jfuw8p0q.removePixelSuffix(css['margin-top'])); } else { rootControl.find('#vspace').value(''); } if (css['margin-right'] === css['margin-left']) { rootControl.find('#hspace').value($_7v7yldc7jfuw8p0q.removePixelSuffix(css['margin-right'])); } else { rootControl.find('#hspace').value(''); } } if (css['border-width']) { rootControl.find('#border').value($_7v7yldc7jfuw8p0q.removePixelSuffix(css['border-width'])); } else { rootControl.find('#border').value(''); } if (css['border-style']) { rootControl.find('#borderStyle').value(css['border-style']); } else { rootControl.find('#borderStyle').value(''); } rootControl.find('#style').value(dom.serializeStyle(dom.parseStyle(dom.serializeStyle(css)))); }; }; var updateStyle = function (editor, win) { win.find('#style').each(function (ctrl) { var value = getStyleValue(function (css) { return normalizeCss(editor, css); }, $_ajpvnqcjjfuw8p25.merge(defaultData(), win.toJSON())); ctrl.value(value); }); }; var makeTab = function (editor) { return { title: 'Advanced', type: 'form', pack: 'start', items: [ { label: 'Style', name: 'style', type: 'textbox', onchange: updateVSpaceHSpaceBorder(editor) }, { type: 'form', layout: 'grid', packV: 'start', columns: 2, padding: 0, defaults: { type: 'textbox', maxWidth: 50, onchange: function (evt) { updateStyle(editor, evt.control.rootControl); } }, items: [ { label: 'Vertical space', name: 'vspace' }, { label: 'Border width', name: 'border' }, { label: 'Horizontal space', name: 'hspace' }, { label: 'Border style', type: 'listbox', name: 'borderStyle', width: 90, maxWidth: 90, onselect: function (evt) { updateStyle(editor, evt.control.rootControl); }, values: [ { text: 'Select...', value: '' }, { text: 'Solid', value: 'solid' }, { text: 'Dotted', value: 'dotted' }, { text: 'Dashed', value: 'dashed' }, { text: 'Double', value: 'double' }, { text: 'Groove', value: 'groove' }, { text: 'Ridge', value: 'ridge' }, { text: 'Inset', value: 'inset' }, { text: 'Outset', value: 'outset' }, { text: 'None', value: 'none' }, { text: 'Hidden', value: 'hidden' } ] } ] } ] }; }; var $_dlliegcfjfuw8p1m = { makeTab: makeTab }; var doSyncSize = function (widthCtrl, heightCtrl) { widthCtrl.state.set('oldVal', widthCtrl.value()); heightCtrl.state.set('oldVal', heightCtrl.value()); }; var doSizeControls = function (win, f) { var widthCtrl = win.find('#width')[0]; var heightCtrl = win.find('#height')[0]; var constrained = win.find('#constrain')[0]; if (widthCtrl && heightCtrl && constrained) { f(widthCtrl, heightCtrl, constrained.checked()); } }; var doUpdateSize = function (widthCtrl, heightCtrl, isContrained) { var oldWidth = widthCtrl.state.get('oldVal'); var oldHeight = heightCtrl.state.get('oldVal'); var newWidth = widthCtrl.value(); var newHeight = heightCtrl.value(); if (isContrained && oldWidth && oldHeight && newWidth && newHeight) { if (newWidth !== oldWidth) { newHeight = Math.round(newWidth / oldWidth * newHeight); if (!isNaN(newHeight)) { heightCtrl.value(newHeight); } } else { newWidth = Math.round(newHeight / oldHeight * newWidth); if (!isNaN(newWidth)) { widthCtrl.value(newWidth); } } } doSyncSize(widthCtrl, heightCtrl); }; var syncSize = function (win) { doSizeControls(win, doSyncSize); }; var updateSize = function (win) { doSizeControls(win, doUpdateSize); }; var createUi = function () { var recalcSize = function (evt) { updateSize(evt.control.rootControl); }; return { type: 'container', label: 'Dimensions', layout: 'flex', align: 'center', spacing: 5, items: [ { name: 'width', type: 'textbox', maxLength: 5, size: 5, onchange: recalcSize, ariaLabel: 'Width' }, { type: 'label', text: 'x' }, { name: 'height', type: 'textbox', maxLength: 5, size: 5, onchange: recalcSize, ariaLabel: 'Height' }, { name: 'constrain', type: 'checkbox', checked: true, text: 'Constrain proportions' } ] }; }; var $_1ahiincmjfuw8p2c = { createUi: createUi, syncSize: syncSize, updateSize: updateSize }; var onSrcChange = function (evt, editor) { var srcURL, prependURL, absoluteURLPattern; var meta = evt.meta || {}; var control = evt.control; var rootControl = control.rootControl; var imageListCtrl = rootControl.find('#image-list')[0]; if (imageListCtrl) { imageListCtrl.value(editor.convertURL(control.value(), 'src')); } global$3.each(meta, function (value, key) { rootControl.find('#' + key).value(value); }); if (!meta.width && !meta.height) { srcURL = editor.convertURL(control.value(), 'src'); prependURL = $_9cq6y3c6jfuw8p0n.getPrependUrl(editor); absoluteURLPattern = new RegExp('^(?:[a-z]+:)?//', 'i'); if (prependURL && !absoluteURLPattern.test(srcURL) && srcURL.substring(0, prependURL.length) !== prependURL) { srcURL = prependURL + srcURL; } control.value(srcURL); $_7v7yldc7jfuw8p0q.getImageSize(editor.documentBaseURI.toAbsolute(control.value()), function (data) { if (data.width && data.height && $_9cq6y3c6jfuw8p0n.hasDimensions(editor)) { rootControl.find('#width').value(data.width); rootControl.find('#height').value(data.height); $_1ahiincmjfuw8p2c.syncSize(rootControl); } }); } }; var onBeforeCall = function (evt) { evt.meta = evt.control.rootControl.toJSON(); }; var getGeneralItems = function (editor, imageListCtrl) { var generalFormItems = [ { name: 'src', type: 'filepicker', filetype: 'image', label: 'Source', autofocus: true, onchange: function (evt) { onSrcChange(evt, editor); }, onbeforecall: onBeforeCall }, imageListCtrl ]; if ($_9cq6y3c6jfuw8p0n.hasDescription(editor)) { generalFormItems.push({ name: 'alt', type: 'textbox', label: 'Image description' }); } if ($_9cq6y3c6jfuw8p0n.hasImageTitle(editor)) { generalFormItems.push({ name: 'title', type: 'textbox', label: 'Image Title' }); } if ($_9cq6y3c6jfuw8p0n.hasDimensions(editor)) { generalFormItems.push($_1ahiincmjfuw8p2c.createUi()); } if ($_9cq6y3c6jfuw8p0n.getClassList(editor)) { generalFormItems.push({ name: 'class', type: 'listbox', label: 'Class', values: $_7v7yldc7jfuw8p0q.buildListItems($_9cq6y3c6jfuw8p0n.getClassList(editor), function (item) { if (item.value) { item.textStyle = function () { return editor.formatter.getCssText({ inline: 'img', classes: [item.value] }); }; } }) }); } if ($_9cq6y3c6jfuw8p0n.hasImageCaption(editor)) { generalFormItems.push({ name: 'caption', type: 'checkbox', label: 'Caption' }); } return generalFormItems; }; var makeTab$1 = function (editor, imageListCtrl) { return { title: 'General', type: 'form', items: getGeneralItems(editor, imageListCtrl) }; }; var $_e4gxykcljfuw8p29 = { makeTab: makeTab$1, getGeneralItems: getGeneralItems }; var url = function () { return $_ba69mec9jfuw8p15.getOrDie('URL'); }; var createObjectURL = function (blob) { return url().createObjectURL(blob); }; var revokeObjectURL = function (u) { url().revokeObjectURL(u); }; var $_52xhfhcojfuw8p2i = { createObjectURL: createObjectURL, revokeObjectURL: revokeObjectURL }; var global$6 = tinymce.util.Tools.resolve('tinymce.ui.Factory'); function XMLHttpRequest () { var f = $_ba69mec9jfuw8p15.getOrDie('XMLHttpRequest'); return new f(); } var noop = function () { }; var pathJoin = function (path1, path2) { if (path1) { return path1.replace(/\/$/, '') + '/' + path2.replace(/^\//, ''); } return path2; }; function Uploader (settings) { var defaultHandler = function (blobInfo, success, failure, progress) { var xhr, formData; xhr = new XMLHttpRequest(); xhr.open('POST', settings.url); xhr.withCredentials = settings.credentials; xhr.upload.onprogress = function (e) { progress(e.loaded / e.total * 100); }; xhr.onerror = function () { failure('Image upload failed due to a XHR Transport error. Code: ' + xhr.status); }; xhr.onload = function () { var json; if (xhr.status < 200 || xhr.status >= 300) { failure('HTTP Error: ' + xhr.status); return; } json = JSON.parse(xhr.responseText); if (!json || typeof json.location !== 'string') { failure('Invalid JSON: ' + xhr.responseText); return; } success(pathJoin(settings.basePath, json.location)); }; formData = new FormData(); formData.append('file', blobInfo.blob(), blobInfo.filename()); xhr.send(formData); }; var uploadBlob = function (blobInfo, handler) { return new global$2(function (resolve, reject) { try { handler(blobInfo, resolve, reject, noop); } catch (ex) { reject(ex.message); } }); }; var isDefaultHandler = function (handler) { return handler === defaultHandler; }; var upload = function (blobInfo) { return !settings.url && isDefaultHandler(settings.handler) ? global$2.reject('Upload url missing from the settings.') : uploadBlob(blobInfo, settings.handler); }; settings = global$3.extend({ credentials: false, handler: defaultHandler }, settings); return { upload: upload }; } var onFileInput = function (editor) { return function (evt) { var Throbber = global$6.get('Throbber'); var rootControl = evt.control.rootControl; var throbber = new Throbber(rootControl.getEl()); var file = evt.control.value(); var blobUri = $_52xhfhcojfuw8p2i.createObjectURL(file); var uploader = Uploader({ url: $_9cq6y3c6jfuw8p0n.getUploadUrl(editor), basePath: $_9cq6y3c6jfuw8p0n.getUploadBasePath(editor), credentials: $_9cq6y3c6jfuw8p0n.getUploadCredentials(editor), handler: $_9cq6y3c6jfuw8p0n.getUploadHandler(editor) }); var finalize = function () { throbber.hide(); $_52xhfhcojfuw8p2i.revokeObjectURL(blobUri); }; throbber.show(); return $_7v7yldc7jfuw8p0q.blobToDataUri(file).then(function (dataUrl) { var blobInfo = editor.editorUpload.blobCache.create({ blob: file, blobUri: blobUri, name: file.name ? file.name.replace(/\.[^\.]+$/, '') : null, base64: dataUrl.split(',')[1] }); return uploader.upload(blobInfo).then(function (url) { var src = rootControl.find('#src'); src.value(url); rootControl.find('tabpanel')[0].activateTab(0); src.fire('change'); finalize(); return url; }); }).catch(function (err) { editor.windowManager.alert(err); finalize(); }); }; }; var acceptExts = '.jpg,.jpeg,.png,.gif'; var makeTab$2 = function (editor) { return { title: 'Upload', type: 'form', layout: 'flex', direction: 'column', align: 'stretch', padding: '20 20 20 20', items: [ { type: 'container', layout: 'flex', direction: 'column', align: 'center', spacing: 10, items: [ { text: 'Browse for an image', type: 'browsebutton', accept: acceptExts, onchange: onFileInput(editor) }, { text: 'OR', type: 'label' } ] }, { text: 'Drop an image here', type: 'dropzone', accept: acceptExts, height: 100, onchange: onFileInput(editor) } ] }; }; var $_9k5u99cnjfuw8p2f = { makeTab: makeTab$2 }; var noop$1 = function () { var x = []; for (var _i = 0; _i < arguments.length; _i++) { x[_i] = arguments[_i]; } }; var noarg = function (f) { return function () { var x = []; for (var _i = 0; _i < arguments.length; _i++) { x[_i] = arguments[_i]; } return f(); }; }; var compose = function (fa, fb) { return function () { var x = []; for (var _i = 0; _i < arguments.length; _i++) { x[_i] = arguments[_i]; } return fa(fb.apply(null, arguments)); }; }; var constant = function (value) { return function () { return value; }; }; var identity = function (x) { return x; }; var tripleEquals = function (a, b) { return a === b; }; var curry = function (f) { var x = []; for (var _i = 1; _i < arguments.length; _i++) { x[_i - 1] = arguments[_i]; } var args = new Array(arguments.length - 1); for (var i = 1; i < arguments.length; i++) args[i - 1] = arguments[i]; return function () { var x = []; for (var _i = 0; _i < arguments.length; _i++) { x[_i] = arguments[_i]; } var newArgs = new Array(arguments.length); for (var j = 0; j < newArgs.length; j++) newArgs[j] = arguments[j]; var all = args.concat(newArgs); return f.apply(null, all); }; }; var not = function (f) { return function () { var x = []; for (var _i = 0; _i < arguments.length; _i++) { x[_i] = arguments[_i]; } return !f.apply(null, arguments); }; }; var die = function (msg) { return function () { throw new Error(msg); }; }; var apply = function (f) { return f(); }; var call = function (f) { f(); }; var never = constant(false); var always = constant(true); var $_ajqvh7csjfuw8p2q = { noop: noop$1, noarg: noarg, compose: compose, constant: constant, identity: identity, tripleEquals: tripleEquals, curry: curry, not: not, die: die, apply: apply, call: call, never: never, always: always }; var submitForm = function (editor, evt) { var win = evt.control.getRoot(); $_1ahiincmjfuw8p2c.updateSize(win); editor.undoManager.transact(function () { var data = $_ajpvnqcjjfuw8p25.merge(readImageDataFromSelection(editor), win.toJSON()); insertOrUpdateImage(editor, data); }); editor.editorUpload.uploadImagesAuto(); }; function Dialog (editor) { function showDialog(imageList) { var data = readImageDataFromSelection(editor); var win, imageListCtrl; if (imageList) { imageListCtrl = { type: 'listbox', label: 'Image list', name: 'image-list', values: $_7v7yldc7jfuw8p0q.buildListItems(imageList, function (item) { item.value = editor.convertURL(item.value || item.url, 'src'); }, [{ text: 'None', value: '' }]), value: data.src && editor.convertURL(data.src, 'src'), onselect: function (e) { var altCtrl = win.find('#alt'); if (!altCtrl.value() || e.lastControl && altCtrl.value() === e.lastControl.text()) { altCtrl.value(e.control.text()); } win.find('#src').value(e.control.value()).fire('change'); }, onPostRender: function () { imageListCtrl = this; } }; } if ($_9cq6y3c6jfuw8p0n.hasAdvTab(editor) || $_9cq6y3c6jfuw8p0n.hasUploadUrl(editor) || $_9cq6y3c6jfuw8p0n.hasUploadHandler(editor)) { var body = [$_e4gxykcljfuw8p29.makeTab(editor, imageListCtrl)]; if ($_9cq6y3c6jfuw8p0n.hasAdvTab(editor)) { body.push($_dlliegcfjfuw8p1m.makeTab(editor)); } if ($_9cq6y3c6jfuw8p0n.hasUploadUrl(editor) || $_9cq6y3c6jfuw8p0n.hasUploadHandler(editor)) { body.push($_9k5u99cnjfuw8p2f.makeTab(editor)); } win = editor.windowManager.open({ title: 'Insert/edit image', data: data, bodyType: 'tabpanel', body: body, onSubmit: $_ajqvh7csjfuw8p2q.curry(submitForm, editor) }); } else { win = editor.windowManager.open({ title: 'Insert/edit image', data: data, body: $_e4gxykcljfuw8p29.getGeneralItems(editor, imageListCtrl), onSubmit: $_ajqvh7csjfuw8p2q.curry(submitForm, editor) }); } $_1ahiincmjfuw8p2c.syncSize(win); } function open() { $_7v7yldc7jfuw8p0q.createImageList(editor, showDialog); } return { open: open }; } var register = function (editor) { editor.addCommand('mceImage', Dialog(editor).open); }; var $_cbuvmdc4jfuw8p0d = { register: register }; var hasImageClass = function (node) { var className = node.attr('class'); return className && /\bimage\b/.test(className); }; var toggleContentEditableState = function (state) { return function (nodes) { var i = nodes.length, node; var toggleContentEditable = function (node) { node.attr('contenteditable', state ? 'true' : null); }; while (i--) { node = nodes[i]; if (hasImageClass(node)) { node.attr('contenteditable', state ? 'false' : null); global$3.each(node.getAll('figcaption'), toggleContentEditable); } } }; }; var setup = function (editor) { editor.on('preInit', function () { editor.parser.addNodeFilter('figure', toggleContentEditableState(true)); editor.serializer.addNodeFilter('figure', toggleContentEditableState(false)); }); }; var $_191db6ctjfuw8p2t = { setup: setup }; var register$1 = function (editor) { editor.addButton('image', { icon: 'image', tooltip: 'Insert/edit image', onclick: Dialog(editor).open, stateSelector: 'img:not([data-mce-object],[data-mce-placeholder]),figure.image' }); editor.addMenuItem('image', { icon: 'image', text: 'Image', onclick: Dialog(editor).open, context: 'insert', prependToContext: true }); }; var $_9nl4e0cujfuw8p2v = { register: register$1 }; global.add('image', function (editor) { $_191db6ctjfuw8p2t.setup(editor); $_9nl4e0cujfuw8p2v.register(editor); $_cbuvmdc4jfuw8p0d.register(editor); }); function Plugin () { } return Plugin; }()); })();
'use strict'; var StreamReader = function() { this._queue = []; this._queueSize = 0; this._cursor = 0; }; StreamReader.prototype.put = function(buffer) { if (!buffer || buffer.length === 0) return; if (!buffer.copy) buffer = new Buffer(buffer); this._queue.push(buffer); this._queueSize += buffer.length; }; StreamReader.prototype.read = function(length) { if (length > this._queueSize) return null; var buffer = new Buffer(length), queue = this._queue, remain = length, n = queue.length, i = 0, chunk, size; while (remain > 0 && i < n) { chunk = queue[i]; size = Math.min(remain, chunk.length - this._cursor); chunk.copy(buffer, length - remain, this._cursor, this._cursor + size); remain -= size; this._queueSize -= size; this._cursor = (this._cursor + size) % chunk.length; i += 1; } queue.splice(0, this._cursor === 0 ? i : i - 1); return buffer; }; module.exports = StreamReader;
describe('Google Calendar plugin', function() { var options; var currentRequest; beforeEach(function() { affix('#cal'); options = { defaultView: 'month', defaultDate: '2014-05-01', events: 'http://www.google.com/calendar/feeds/notarealfeed/public/basic' }; // workaround. wanted to use mockedAjaxCalls(), but JSONP requests get mangled later on currentRequest = null; $.mockjaxSettings.log = function(mockHandler, request) { currentRequest = currentRequest || $.extend({}, request); // copy }; // fake the JSONP call (which actually calls to /full) $.mockjax({ url: 'http://www.google.com/calendar/feeds/notarealfeed/public/*', responseText: JSON.parse( '{"version":"1.0","encoding":"UTF-8","feed":{"xmlns":"http://www.w3.org/2005/Atom","xmlns$openSearch"' + ':"http://a9.com/-/spec/opensearchrss/1.0/","xmlns$gCal":"http://schemas.google.com/gCal/2005","xmlns' + '$gd":"http://schemas.google.com/g/2005","id":{"$t":"http://www.google.com/calendar/feeds/usa__en%40h' + 'oliday.calendar.google.com/public/full"},"updated":{"$t":"2014-05-22T13:00:40.000Z"},"category":[{"s' + 'cheme":"http://schemas.google.com/g/2005#kind","term":"http://schemas.google.com/g/2005#event"}],"ti' + 'tle":{"$t":"Holidays in United States","type":"text"},"subtitle":{"$t":"Holidays and Observances in ' + 'United States","type":"text"},"link":[{"rel":"alternate","type":"text/html","href":"http://www.googl' + 'e.com/calendar/embed?src=usa__en%40holiday.calendar.google.com"},{"rel":"http://schemas.google.com/g' + '/2005#feed","type":"application/atom+xml","href":"http://www.google.com/calendar/feeds/usa__en%40hol' + 'iday.calendar.google.com/public/full"},{"rel":"http://schemas.google.com/g/2005#batch","type":"appli' + 'cation/atom+xml","href":"http://www.google.com/calendar/feeds/usa__en%40holiday.calendar.google.com/' + 'public/full/batch"},{"rel":"self","type":"application/atom+xml","href":"http://www.google.com/calend' + 'ar/feeds/usa__en%40holiday.calendar.google.com/public/full?alt=json-in-script&max-results=9999&start' + '-min=2014-04-27T00%3A00%3A00Z&singleevents=true&start-max=2014-06-08T00%3A00%3A00Z"}],"author":[{"na' + 'me":{"$t":"Holidays in United States"}}],"generator":{"$t":"Google Calendar","version":"1.0","uri":"' + 'http://www.google.com/calendar"},"openSearch$totalResults":{"$t":2},"openSearch$startIndex":{"$t":1}' + ',"openSearch$itemsPerPage":{"$t":9999},"gCal$timezone":{"value":"UTC"},"gCal$timesCleaned":{"value":' + '0},"entry":[{"id":{"$t":"http://www.google.com/calendar/feeds/usa__en%40holiday.calendar.google.com/' + 'public/full/20140511_60o30dr560o30e1g60o30dr4ck"},"published":{"$t":"2014-05-22T13:00:40.000Z"},"upd' + 'ated":{"$t":"2014-05-22T13:00:40.000Z"},"category":[{"scheme":"http://schemas.google.com/g/2005#kind' + '","term":"http://schemas.google.com/g/2005#event"}],"title":{"$t":"Mothers Day","type":"text"},"cont' + 'ent":{"$t":"","type":"text"},"link":[{"rel":"alternate","type":"text/html","href":"http://www.google' + '.com/calendar/event?eid=MjAxNDA1MTFfNjBvMzBkcjU2MG8zMGUxZzYwbzMwZHI0Y2sgdXNhX19lbkBo","title":"alter' + 'nate"},{"rel":"self","type":"application/atom+xml","href":"http://www.google.com/calendar/feeds/usa_' + '_en%40holiday.calendar.google.com/public/full/20140511_60o30dr560o30e1g60o30dr4ck"}],"author":[{"nam' + 'e":{"$t":"Holidays in United States"}}],"gd$comments":{"gd$feedLink":{"href":"http://www.google.com/' + 'calendar/feeds/usa__en%40holiday.calendar.google.com/public/full/20140511_60o30dr560o30e1g60o30dr4ck' + '/comments"}},"gd$eventStatus":{"value":"http://schemas.google.com/g/2005#event.confirmed"},"gd$where' + '":[{}],"gd$who":[{"email":"usa__en@holiday.calendar.google.com","rel":"http://schemas.google.com/g/2' + '005#event.organizer","valueString":"Holidays in United States"}],"gd$when":[{"endTime":"2014-05-12",' + '"startTime":"2014-05-11"}],"gd$transparency":{"value":"http://schemas.google.com/g/2005#event.transp' + 'arent"},"gCal$anyoneCanAddSelf":{"value":"false"},"gCal$guestsCanInviteOthers":{"value":"true"},"gCa' + 'l$guestsCanModify":{"value":"false"},"gCal$guestsCanSeeGuests":{"value":"true"},"gCal$sequence":{"va' + 'lue":0},"gCal$uid":{"value":"20140511_60o30dr560o30e1g60o30dr4ck@google.com"}},{"id":{"$t":"http://w' + 'ww.google.com/calendar/feeds/usa__en%40holiday.calendar.google.com/public/full/20140526_60o30dr56co3' + '0e1g60o30dr4ck"},"published":{"$t":"2014-05-22T13:00:40.000Z"},"updated":{"$t":"2014-05-22T13:00:40.' + '000Z"},"category":[{"scheme":"http://schemas.google.com/g/2005#kind","term":"http://schemas.google.c' + 'om/g/2005#event"}],"title":{"$t":"Memorial Day","type":"text"},"content":{"$t":"","type":"text"},"li' + 'nk":[{"rel":"alternate","type":"text/html","href":"http://www.google.com/calendar/event?eid=MjAxNDA1' + 'MjZfNjBvMzBkcjU2Y28zMGUxZzYwbzMwZHI0Y2sgdXNhX19lbkBo","title":"alternate"},{"rel":"self","type":"app' + 'lication/atom+xml","href":"http://www.google.com/calendar/feeds/usa__en%40holiday.calendar.google.co' + 'm/public/full/20140526_60o30dr56co30e1g60o30dr4ck"}],"author":[{"name":{"$t":"Holidays in United Sta' + 'tes"}}],"gd$comments":{"gd$feedLink":{"href":"http://www.google.com/calendar/feeds/usa__en%40holiday' + '.calendar.google.com/public/full/20140526_60o30dr56co30e1g60o30dr4ck/comments"}},"gd$eventStatus":{"' + 'value":"http://schemas.google.com/g/2005#event.confirmed"},"gd$where":[{}],"gd$who":[{"email":"usa__' + 'en@holiday.calendar.google.com","rel":"http://schemas.google.com/g/2005#event.organizer","valueStrin' + 'g":"Holidays in United States"}],"gd$when":[{"endTime":"2014-05-27","startTime":"2014-05-26"}],"gd$t' + 'ransparency":{"value":"http://schemas.google.com/g/2005#event.transparent"},"gCal$anyoneCanAddSelf":' + '{"value":"false"},"gCal$guestsCanInviteOthers":{"value":"true"},"gCal$guestsCanModify":{"value":"fal' + 'se"},"gCal$guestsCanSeeGuests":{"value":"true"},"gCal$sequence":{"value":0},"gCal$uid":{"value":"201' + '40526_60o30dr56co30e1g60o30dr4ck@google.com"}}]}}' ) }); }); afterEach(function() { $.mockjaxClear(); $.mockjaxSettings.log = function() { }; }); it('sends request correctly when no timezone', function() { $('#cal').fullCalendar(options); expect(currentRequest.data['start-min']).toEqual('2014-04-27'); expect(currentRequest.data['start-max']).toEqual('2014-06-08'); expect(currentRequest.data.ctz).toBeUndefined(); }); it('sends request correctly when local timezone', function() { options.timezone = 'local'; $('#cal').fullCalendar(options); expect(currentRequest.data['start-min']).toEqual('2014-04-27'); expect(currentRequest.data['start-max']).toEqual('2014-06-08'); expect(currentRequest.data.ctz).toBeUndefined(); }); it('sends request correctly when UTC timezone', function() { options.timezone = 'UTC'; $('#cal').fullCalendar(options); expect(currentRequest.data['start-min']).toEqual('2014-04-27'); expect(currentRequest.data['start-max']).toEqual('2014-06-08'); expect(currentRequest.data.ctz).toEqual('UTC'); }); it('sends request correctly when custom timezone', function() { options.timezone = 'America/Chicago'; $('#cal').fullCalendar(options); expect(currentRequest.data['start-min']).toEqual('2014-04-27'); expect(currentRequest.data['start-max']).toEqual('2014-06-08'); expect(currentRequest.data.ctz).toEqual('America/Chicago'); }); });
/** * ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v13.0.1 * @link http://www.ag-grid.com/ * @license MIT */ "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var textCellEditor_1 = require("./textCellEditor"); var PopupTextCellEditor = (function (_super) { __extends(PopupTextCellEditor, _super); function PopupTextCellEditor() { return _super !== null && _super.apply(this, arguments) || this; } PopupTextCellEditor.prototype.isPopup = function () { return true; }; return PopupTextCellEditor; }(textCellEditor_1.TextCellEditor)); exports.PopupTextCellEditor = PopupTextCellEditor;
import ElOption from '../select/src/option'; /* istanbul ignore next */ ElOption.install = function(Vue) { Vue.component(ElOption.name, ElOption); }; export default ElOption;
!function(){var a="undefined"!=typeof window?this.numeral:require("../numeral");a.register("locale","fi",{delimiters:{thousands:" ",decimal:","},abbreviations:{thousand:"k",million:"M",billion:"G",trillion:"T"},ordinal:function(a){return"."},currency:{symbol:"€"}})}();
Ext.define("Ext.theme.neptune.Titlebar",{override:"Ext.TitleBar",config:{defaultButtonUI:"alt"}});Ext.define("Ext.theme.neptune.tip.ToolTip",{override:"Ext.tip.ToolTip",bodyBorder:false});Ext.namespace("Ext.theme.is").Neptune=true;Ext.theme.name="Neptune";Ext.theme.getDocCls=function(){return Ext.platformTags.desktop?"":"x-big"};
/** * jsPDF AutoTable plugin v2.0.32 * Copyright (c) 2014 Simon Bengtsson, https://github.com/simonbengtsson/jsPDF-AutoTable * * Licensed under the MIT License. * http://opensource.org/licenses/mit-license * * @preserve */ (function (jsPDF) { 'use strict'; jsPDF = 'default' in jsPDF ? jsPDF['default'] : jsPDF; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; }; var classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; var createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var Table = function Table() { classCallCheck(this, Table); this.height = 0; this.width = 0; this.contentWidth = 0; this.rows = []; this.columns = []; this.headerRow = null; this.settings = {}; this.pageCount = 1; }; var Row = function Row(raw) { classCallCheck(this, Row); this.raw = raw || {}; this.index = 0; this.styles = {}; this.cells = {}; this.height = 0; this.y = 0; }; var Cell = function Cell(raw) { classCallCheck(this, Cell); this.raw = raw; this.styles = {}; this.text = ''; this.contentWidth = 0; this.textPos = {}; this.height = 0; this.width = 0; this.x = 0; this.y = 0; }; var Column = function Column(dataKey, index) { classCallCheck(this, Column); this.dataKey = dataKey; this.index = index; this.options = {}; this.styles = {}; this.contentWidth = 0; this.width = 0; this.x = 0; }; /** * Ratio between font size and font height. The number comes from jspdf's source code */ var FONT_ROW_RATIO = 1.15; /** * Styles for the themes (overriding the default styles) */ var themes = { 'striped': { table: { fillColor: 255, textColor: 80, fontStyle: 'normal', fillStyle: 'F' }, header: { textColor: 255, fillColor: [41, 128, 185], rowHeight: 23, fontStyle: 'bold' }, body: {}, alternateRow: { fillColor: 245 } }, 'grid': { table: { fillColor: 255, textColor: 80, fontStyle: 'normal', lineWidth: 0.1, fillStyle: 'DF' }, header: { textColor: 255, fillColor: [26, 188, 156], rowHeight: 23, fillStyle: 'F', fontStyle: 'bold' }, body: {}, alternateRow: {} }, 'plain': { header: { fontStyle: 'bold' } } }; function getDefaults() { return { // Styling theme: 'striped', // 'striped', 'grid' or 'plain' styles: {}, headerStyles: {}, bodyStyles: {}, alternateRowStyles: {}, columnStyles: {}, // Properties startY: false, // false indicates the margin.top value margin: 40, pageBreak: 'auto', // 'auto', 'avoid', 'always' tableWidth: 'auto', // number, 'auto', 'wrap' // Hooks createdHeaderCell: function createdHeaderCell(cell, data) {}, createdCell: function createdCell(cell, data) {}, drawHeaderRow: function drawHeaderRow(row, data) {}, drawRow: function drawRow(row, data) {}, drawHeaderCell: function drawHeaderCell(cell, data) {}, drawCell: function drawCell(cell, data) {}, beforePageContent: function beforePageContent(data) {}, afterPageContent: function afterPageContent(data) {} }; } // Base style for all themes function defaultStyles() { return { cellPadding: 5, fontSize: 10, font: "helvetica", // helvetica, times, courier lineColor: 200, lineWidth: 0.1, fontStyle: 'normal', // normal, bold, italic, bolditalic overflow: 'ellipsize', // visible, hidden, ellipsize or linebreak fillColor: 255, textColor: 20, halign: 'left', // left, center, right valign: 'top', // top, middle, bottom fillStyle: 'F', // 'S', 'F' or 'DF' (stroke, fill or fill then stroke) rowHeight: 20, columnWidth: 'auto' }; } var Config = function () { function Config() { classCallCheck(this, Config); } createClass(Config, null, [{ key: 'initSettings', value: function initSettings(userOptions) { var settings = Object.assign({}, getDefaults(), userOptions); // Options if (typeof settings.extendWidth !== 'undefined') { settings.tableWidth = settings.extendWidth ? 'auto' : 'wrap'; console.error("Use of deprecated option: extendWidth, use tableWidth instead."); } if (typeof settings.margins !== 'undefined') { if (typeof settings.margin === 'undefined') settings.margin = settings.margins; console.error("Use of deprecated option: margins, use margin instead."); } [['padding', 'cellPadding'], ['lineHeight', 'rowHeight'], 'fontSize', 'overflow'].forEach(function (o) { var deprecatedOption = typeof o === 'string' ? o : o[0]; var style = typeof o === 'string' ? o : o[1]; if (typeof settings[deprecatedOption] !== 'undefined') { if (typeof settings.styles[style] === 'undefined') { settings.styles[style] = settings[deprecatedOption]; } console.error("Use of deprecated option: " + deprecatedOption + ", use the style " + style + " instead."); } }); // Unifying var marginSetting = settings.margin; settings.margin = {}; if (typeof marginSetting.horizontal === 'number') { marginSetting.right = marginSetting.horizontal; marginSetting.left = marginSetting.horizontal; } if (typeof marginSetting.vertical === 'number') { marginSetting.top = marginSetting.vertical; marginSetting.bottom = marginSetting.vertical; } ['top', 'right', 'bottom', 'left'].forEach(function (side, i) { if (typeof marginSetting === 'number') { settings.margin[side] = marginSetting; } else { var key = Array.isArray(marginSetting) ? i : side; settings.margin[side] = typeof marginSetting[key] === 'number' ? marginSetting[key] : 40; } }); return settings; } }, { key: 'styles', value: function styles(_styles) { _styles.unshift(defaultStyles()); _styles.unshift({}); return Object.assign.apply(this, _styles); } }]); return Config; }(); function interopDefault(ex) { return ex && typeof ex === 'object' && 'default' in ex ? ex['default'] : ex; } function createCommonjsModule(fn, module) { return module = { exports: {} }, fn(module, module.exports), module.exports; } var _global = createCommonjsModule(function (module) { // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 var global = module.exports = typeof window != 'undefined' && window.Math == Math ? window : typeof self != 'undefined' && self.Math == Math ? self : Function('return this')(); if(typeof __g == 'number')__g = global; // eslint-disable-line no-undef }); var _global$1 = interopDefault(_global); var require$$0 = Object.freeze({ default: _global$1 }); var _has = createCommonjsModule(function (module) { var hasOwnProperty = {}.hasOwnProperty; module.exports = function(it, key){ return hasOwnProperty.call(it, key); }; }); var _has$1 = interopDefault(_has); var require$$2 = Object.freeze({ default: _has$1 }); var _fails = createCommonjsModule(function (module) { module.exports = function(exec){ try { return !!exec(); } catch(e){ return true; } }; }); var _fails$1 = interopDefault(_fails); var require$$0$2 = Object.freeze({ default: _fails$1 }); var _descriptors = createCommonjsModule(function (module) { // Thank's IE8 for his funny defineProperty module.exports = !interopDefault(require$$0$2)(function(){ return Object.defineProperty({}, 'a', {get: function(){ return 7; }}).a != 7; }); }); var _descriptors$1 = interopDefault(_descriptors); var require$$0$1 = Object.freeze({ default: _descriptors$1 }); var _core = createCommonjsModule(function (module) { var core = module.exports = {version: '2.4.0'}; if(typeof __e == 'number')__e = core; // eslint-disable-line no-undef }); var _core$1 = interopDefault(_core); var version = _core.version; var require$$0$3 = Object.freeze({ default: _core$1, version: version }); var _isObject = createCommonjsModule(function (module) { module.exports = function(it){ return typeof it === 'object' ? it !== null : typeof it === 'function'; }; }); var _isObject$1 = interopDefault(_isObject); var require$$3$1 = Object.freeze({ default: _isObject$1 }); var _anObject = createCommonjsModule(function (module) { var isObject = interopDefault(require$$3$1); module.exports = function(it){ if(!isObject(it))throw TypeError(it + ' is not an object!'); return it; }; }); var _anObject$1 = interopDefault(_anObject); var require$$2$1 = Object.freeze({ default: _anObject$1 }); var _domCreate = createCommonjsModule(function (module) { var isObject = interopDefault(require$$3$1) , document = interopDefault(require$$0).document // in old IE typeof document.createElement is 'object' , is = isObject(document) && isObject(document.createElement); module.exports = function(it){ return is ? document.createElement(it) : {}; }; }); var _domCreate$1 = interopDefault(_domCreate); var require$$1$3 = Object.freeze({ default: _domCreate$1 }); var _ie8DomDefine = createCommonjsModule(function (module) { module.exports = !interopDefault(require$$0$1) && !interopDefault(require$$0$2)(function(){ return Object.defineProperty(interopDefault(require$$1$3)('div'), 'a', {get: function(){ return 7; }}).a != 7; }); }); var _ie8DomDefine$1 = interopDefault(_ie8DomDefine); var require$$1$2 = Object.freeze({ default: _ie8DomDefine$1 }); var _toPrimitive = createCommonjsModule(function (module) { // 7.1.1 ToPrimitive(input [, PreferredType]) var isObject = interopDefault(require$$3$1); // instead of the ES6 spec version, we didn't implement @@toPrimitive case // and the second argument - flag - preferred type is a string module.exports = function(it, S){ if(!isObject(it))return it; var fn, val; if(S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val; if(typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it)))return val; if(!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val; throw TypeError("Can't convert object to primitive value"); }; }); var _toPrimitive$1 = interopDefault(_toPrimitive); var require$$3$2 = Object.freeze({ default: _toPrimitive$1 }); var _objectDp = createCommonjsModule(function (module, exports) { var anObject = interopDefault(require$$2$1) , IE8_DOM_DEFINE = interopDefault(require$$1$2) , toPrimitive = interopDefault(require$$3$2) , dP = Object.defineProperty; exports.f = interopDefault(require$$0$1) ? Object.defineProperty : function defineProperty(O, P, Attributes){ anObject(O); P = toPrimitive(P, true); anObject(Attributes); if(IE8_DOM_DEFINE)try { return dP(O, P, Attributes); } catch(e){ /* empty */ } if('get' in Attributes || 'set' in Attributes)throw TypeError('Accessors not supported!'); if('value' in Attributes)O[P] = Attributes.value; return O; }; }); var _objectDp$1 = interopDefault(_objectDp); var f = _objectDp.f; var require$$3 = Object.freeze({ default: _objectDp$1, f: f }); var _propertyDesc = createCommonjsModule(function (module) { module.exports = function(bitmap, value){ return { enumerable : !(bitmap & 1), configurable: !(bitmap & 2), writable : !(bitmap & 4), value : value }; }; }); var _propertyDesc$1 = interopDefault(_propertyDesc); var require$$3$3 = Object.freeze({ default: _propertyDesc$1 }); var _hide = createCommonjsModule(function (module) { var dP = interopDefault(require$$3) , createDesc = interopDefault(require$$3$3); module.exports = interopDefault(require$$0$1) ? function(object, key, value){ return dP.f(object, key, createDesc(1, value)); } : function(object, key, value){ object[key] = value; return object; }; }); var _hide$1 = interopDefault(_hide); var require$$1$1 = Object.freeze({ default: _hide$1 }); var _uid = createCommonjsModule(function (module) { var id = 0 , px = Math.random(); module.exports = function(key){ return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36)); }; }); var _uid$1 = interopDefault(_uid); var require$$0$4 = Object.freeze({ default: _uid$1 }); var _redefine = createCommonjsModule(function (module) { var global = interopDefault(require$$0) , hide = interopDefault(require$$1$1) , has = interopDefault(require$$2) , SRC = interopDefault(require$$0$4)('src') , TO_STRING = 'toString' , $toString = Function[TO_STRING] , TPL = ('' + $toString).split(TO_STRING); interopDefault(require$$0$3).inspectSource = function(it){ return $toString.call(it); }; (module.exports = function(O, key, val, safe){ var isFunction = typeof val == 'function'; if(isFunction)has(val, 'name') || hide(val, 'name', key); if(O[key] === val)return; if(isFunction)has(val, SRC) || hide(val, SRC, O[key] ? '' + O[key] : TPL.join(String(key))); if(O === global){ O[key] = val; } else { if(!safe){ delete O[key]; hide(O, key, val); } else { if(O[key])O[key] = val; else hide(O, key, val); } } // add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative })(Function.prototype, TO_STRING, function toString(){ return typeof this == 'function' && this[SRC] || $toString.call(this); }); }); var _redefine$1 = interopDefault(_redefine); var require$$7 = Object.freeze({ default: _redefine$1 }); var _aFunction = createCommonjsModule(function (module) { module.exports = function(it){ if(typeof it != 'function')throw TypeError(it + ' is not a function!'); return it; }; }); var _aFunction$1 = interopDefault(_aFunction); var require$$0$6 = Object.freeze({ default: _aFunction$1 }); var _ctx = createCommonjsModule(function (module) { // optional / simple context binding var aFunction = interopDefault(require$$0$6); module.exports = function(fn, that, length){ aFunction(fn); if(that === undefined)return fn; switch(length){ case 1: return function(a){ return fn.call(that, a); }; case 2: return function(a, b){ return fn.call(that, a, b); }; case 3: return function(a, b, c){ return fn.call(that, a, b, c); }; } return function(/* ...args */){ return fn.apply(that, arguments); }; }; }); var _ctx$1 = interopDefault(_ctx); var require$$0$5 = Object.freeze({ default: _ctx$1 }); var _export = createCommonjsModule(function (module) { var global = interopDefault(require$$0) , core = interopDefault(require$$0$3) , hide = interopDefault(require$$1$1) , redefine = interopDefault(require$$7) , ctx = interopDefault(require$$0$5) , PROTOTYPE = 'prototype'; var $export = function(type, name, source){ var IS_FORCED = type & $export.F , IS_GLOBAL = type & $export.G , IS_STATIC = type & $export.S , IS_PROTO = type & $export.P , IS_BIND = type & $export.B , target = IS_GLOBAL ? global : IS_STATIC ? global[name] || (global[name] = {}) : (global[name] || {})[PROTOTYPE] , exports = IS_GLOBAL ? core : core[name] || (core[name] = {}) , expProto = exports[PROTOTYPE] || (exports[PROTOTYPE] = {}) , key, own, out, exp; if(IS_GLOBAL)source = name; for(key in source){ // contains in native own = !IS_FORCED && target && target[key] !== undefined; // export native or passed out = (own ? target : source)[key]; // bind timers to global for call from export context exp = IS_BIND && own ? ctx(out, global) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out; // extend global if(target)redefine(target, key, out, type & $export.U); // export if(exports[key] != out)hide(exports, key, exp); if(IS_PROTO && expProto[key] != out)expProto[key] = out; } }; global.core = core; // type bitmap $export.F = 1; // forced $export.G = 2; // global $export.S = 4; // static $export.P = 8; // proto $export.B = 16; // bind $export.W = 32; // wrap $export.U = 64; // safe $export.R = 128; // real proto method for `library` module.exports = $export; }); var _export$1 = interopDefault(_export); var require$$1 = Object.freeze({ default: _export$1 }); var _meta = createCommonjsModule(function (module) { var META = interopDefault(require$$0$4)('meta') , isObject = interopDefault(require$$3$1) , has = interopDefault(require$$2) , setDesc = interopDefault(require$$3).f , id = 0; var isExtensible = Object.isExtensible || function(){ return true; }; var FREEZE = !interopDefault(require$$0$2)(function(){ return isExtensible(Object.preventExtensions({})); }); var setMeta = function(it){ setDesc(it, META, {value: { i: 'O' + ++id, // object ID w: {} // weak collections IDs }}); }; var fastKey = function(it, create){ // return primitive with prefix if(!isObject(it))return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it; if(!has(it, META)){ // can't set metadata to uncaught frozen object if(!isExtensible(it))return 'F'; // not necessary to add metadata if(!create)return 'E'; // add missing metadata setMeta(it); // return object ID } return it[META].i; }; var getWeak = function(it, create){ if(!has(it, META)){ // can't set metadata to uncaught frozen object if(!isExtensible(it))return true; // not necessary to add metadata if(!create)return false; // add missing metadata setMeta(it); // return hash weak collections IDs } return it[META].w; }; // add metadata on freeze-family methods calling var onFreeze = function(it){ if(FREEZE && meta.NEED && isExtensible(it) && !has(it, META))setMeta(it); return it; }; var meta = module.exports = { KEY: META, NEED: false, fastKey: fastKey, getWeak: getWeak, onFreeze: onFreeze }; }); var _meta$1 = interopDefault(_meta); var KEY = _meta.KEY; var NEED = _meta.NEED; var fastKey = _meta.fastKey; var getWeak = _meta.getWeak; var onFreeze = _meta.onFreeze; var require$$24 = Object.freeze({ default: _meta$1, KEY: KEY, NEED: NEED, fastKey: fastKey, getWeak: getWeak, onFreeze: onFreeze }); var _shared = createCommonjsModule(function (module) { var global = interopDefault(require$$0) , SHARED = '__core-js_shared__' , store = global[SHARED] || (global[SHARED] = {}); module.exports = function(key){ return store[key] || (store[key] = {}); }; }); var _shared$1 = interopDefault(_shared); var require$$1$4 = Object.freeze({ default: _shared$1 }); var _wks = createCommonjsModule(function (module) { var store = interopDefault(require$$1$4)('wks') , uid = interopDefault(require$$0$4) , Symbol = interopDefault(require$$0).Symbol , USE_SYMBOL = typeof Symbol == 'function'; var $exports = module.exports = function(name){ return store[name] || (store[name] = USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : uid)('Symbol.' + name)); }; $exports.store = store; }); var _wks$1 = interopDefault(_wks); var require$$0$7 = Object.freeze({ default: _wks$1 }); var _setToStringTag = createCommonjsModule(function (module) { var def = interopDefault(require$$3).f , has = interopDefault(require$$2) , TAG = interopDefault(require$$0$7)('toStringTag'); module.exports = function(it, tag, stat){ if(it && !has(it = stat ? it : it.prototype, TAG))def(it, TAG, {configurable: true, value: tag}); }; }); var _setToStringTag$1 = interopDefault(_setToStringTag); var require$$2$2 = Object.freeze({ default: _setToStringTag$1 }); var _wksExt = createCommonjsModule(function (module, exports) { exports.f = interopDefault(require$$0$7); }); var _wksExt$1 = interopDefault(_wksExt); var f$1 = _wksExt.f; var require$$1$5 = Object.freeze({ default: _wksExt$1, f: f$1 }); var _library = createCommonjsModule(function (module) { module.exports = false; }); var _library$1 = interopDefault(_library); var require$$9 = Object.freeze({ default: _library$1 }); var _wksDefine = createCommonjsModule(function (module) { var global = interopDefault(require$$0) , core = interopDefault(require$$0$3) , LIBRARY = interopDefault(require$$9) , wksExt = interopDefault(require$$1$5) , defineProperty = interopDefault(require$$3).f; module.exports = function(name){ var $Symbol = core.Symbol || (core.Symbol = LIBRARY ? {} : global.Symbol || {}); if(name.charAt(0) != '_' && !(name in $Symbol))defineProperty($Symbol, name, {value: wksExt.f(name)}); }; }); var _wksDefine$1 = interopDefault(_wksDefine); var require$$17 = Object.freeze({ default: _wksDefine$1 }); var _cof = createCommonjsModule(function (module) { var toString = {}.toString; module.exports = function(it){ return toString.call(it).slice(8, -1); }; }); var _cof$1 = interopDefault(_cof); var require$$1$9 = Object.freeze({ default: _cof$1 }); var _iobject = createCommonjsModule(function (module) { // fallback for non-array-like ES3 and non-enumerable old V8 strings var cof = interopDefault(require$$1$9); module.exports = Object('z').propertyIsEnumerable(0) ? Object : function(it){ return cof(it) == 'String' ? it.split('') : Object(it); }; }); var _iobject$1 = interopDefault(_iobject); var require$$1$8 = Object.freeze({ default: _iobject$1 }); var _defined = createCommonjsModule(function (module) { // 7.2.1 RequireObjectCoercible(argument) module.exports = function(it){ if(it == undefined)throw TypeError("Can't call method on " + it); return it; }; }); var _defined$1 = interopDefault(_defined); var require$$0$8 = Object.freeze({ default: _defined$1 }); var _toIobject = createCommonjsModule(function (module) { // to indexed object, toObject with fallback for non-array-like ES3 strings var IObject = interopDefault(require$$1$8) , defined = interopDefault(require$$0$8); module.exports = function(it){ return IObject(defined(it)); }; }); var _toIobject$1 = interopDefault(_toIobject); var require$$1$7 = Object.freeze({ default: _toIobject$1 }); var _toInteger = createCommonjsModule(function (module) { // 7.1.4 ToInteger var ceil = Math.ceil , floor = Math.floor; module.exports = function(it){ return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it); }; }); var _toInteger$1 = interopDefault(_toInteger); var require$$0$9 = Object.freeze({ default: _toInteger$1 }); var _toLength = createCommonjsModule(function (module) { // 7.1.15 ToLength var toInteger = interopDefault(require$$0$9) , min = Math.min; module.exports = function(it){ return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991 }; }); var _toLength$1 = interopDefault(_toLength); var require$$1$11 = Object.freeze({ default: _toLength$1 }); var _toIndex = createCommonjsModule(function (module) { var toInteger = interopDefault(require$$0$9) , max = Math.max , min = Math.min; module.exports = function(index, length){ index = toInteger(index); return index < 0 ? max(index + length, 0) : min(index, length); }; }); var _toIndex$1 = interopDefault(_toIndex); var require$$0$10 = Object.freeze({ default: _toIndex$1 }); var _arrayIncludes = createCommonjsModule(function (module) { // false -> Array#indexOf // true -> Array#includes var toIObject = interopDefault(require$$1$7) , toLength = interopDefault(require$$1$11) , toIndex = interopDefault(require$$0$10); module.exports = function(IS_INCLUDES){ return function($this, el, fromIndex){ var O = toIObject($this) , length = toLength(O.length) , index = toIndex(fromIndex, length) , value; // Array#includes uses SameValueZero equality algorithm if(IS_INCLUDES && el != el)while(length > index){ value = O[index++]; if(value != value)return true; // Array#toIndex ignores holes, Array#includes - not } else for(;length > index; index++)if(IS_INCLUDES || index in O){ if(O[index] === el)return IS_INCLUDES || index || 0; } return !IS_INCLUDES && -1; }; }; }); var _arrayIncludes$1 = interopDefault(_arrayIncludes); var require$$1$10 = Object.freeze({ default: _arrayIncludes$1 }); var _sharedKey = createCommonjsModule(function (module) { var shared = interopDefault(require$$1$4)('keys') , uid = interopDefault(require$$0$4); module.exports = function(key){ return shared[key] || (shared[key] = uid(key)); }; }); var _sharedKey$1 = interopDefault(_sharedKey); var require$$0$11 = Object.freeze({ default: _sharedKey$1 }); var _objectKeysInternal = createCommonjsModule(function (module) { var has = interopDefault(require$$2) , toIObject = interopDefault(require$$1$7) , arrayIndexOf = interopDefault(require$$1$10)(false) , IE_PROTO = interopDefault(require$$0$11)('IE_PROTO'); module.exports = function(object, names){ var O = toIObject(object) , i = 0 , result = [] , key; for(key in O)if(key != IE_PROTO)has(O, key) && result.push(key); // Don't enum bug & hidden keys while(names.length > i)if(has(O, key = names[i++])){ ~arrayIndexOf(result, key) || result.push(key); } return result; }; }); var _objectKeysInternal$1 = interopDefault(_objectKeysInternal); var require$$1$6 = Object.freeze({ default: _objectKeysInternal$1 }); var _enumBugKeys = createCommonjsModule(function (module) { // IE 8- don't enum bug keys module.exports = ( 'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf' ).split(','); }); var _enumBugKeys$1 = interopDefault(_enumBugKeys); var require$$0$12 = Object.freeze({ default: _enumBugKeys$1 }); var _objectKeys = createCommonjsModule(function (module) { // 19.1.2.14 / 15.2.3.14 Object.keys(O) var $keys = interopDefault(require$$1$6) , enumBugKeys = interopDefault(require$$0$12); module.exports = Object.keys || function keys(O){ return $keys(O, enumBugKeys); }; }); var _objectKeys$1 = interopDefault(_objectKeys); var require$$2$3 = Object.freeze({ default: _objectKeys$1 }); var _keyof = createCommonjsModule(function (module) { var getKeys = interopDefault(require$$2$3) , toIObject = interopDefault(require$$1$7); module.exports = function(object, el){ var O = toIObject(object) , keys = getKeys(O) , length = keys.length , index = 0 , key; while(length > index)if(O[key = keys[index++]] === el)return key; }; }); var _keyof$1 = interopDefault(_keyof); var require$$16 = Object.freeze({ default: _keyof$1 }); var _objectGops = createCommonjsModule(function (module, exports) { exports.f = Object.getOwnPropertySymbols; }); var _objectGops$1 = interopDefault(_objectGops); var f$2 = _objectGops.f; var require$$4 = Object.freeze({ default: _objectGops$1, f: f$2 }); var _objectPie = createCommonjsModule(function (module, exports) { exports.f = {}.propertyIsEnumerable; }); var _objectPie$1 = interopDefault(_objectPie); var f$3 = _objectPie.f; var require$$0$13 = Object.freeze({ default: _objectPie$1, f: f$3 }); var _enumKeys = createCommonjsModule(function (module) { // all enumerable object keys, includes symbols var getKeys = interopDefault(require$$2$3) , gOPS = interopDefault(require$$4) , pIE = interopDefault(require$$0$13); module.exports = function(it){ var result = getKeys(it) , getSymbols = gOPS.f; if(getSymbols){ var symbols = getSymbols(it) , isEnum = pIE.f , i = 0 , key; while(symbols.length > i)if(isEnum.call(it, key = symbols[i++]))result.push(key); } return result; }; }); var _enumKeys$1 = interopDefault(_enumKeys); var require$$15 = Object.freeze({ default: _enumKeys$1 }); var _isArray = createCommonjsModule(function (module) { // 7.2.2 IsArray(argument) var cof = interopDefault(require$$1$9); module.exports = Array.isArray || function isArray(arg){ return cof(arg) == 'Array'; }; }); var _isArray$1 = interopDefault(_isArray); var require$$0$14 = Object.freeze({ default: _isArray$1 }); var _objectDps = createCommonjsModule(function (module) { var dP = interopDefault(require$$3) , anObject = interopDefault(require$$2$1) , getKeys = interopDefault(require$$2$3); module.exports = interopDefault(require$$0$1) ? Object.defineProperties : function defineProperties(O, Properties){ anObject(O); var keys = getKeys(Properties) , length = keys.length , i = 0 , P; while(length > i)dP.f(O, P = keys[i++], Properties[P]); return O; }; }); var _objectDps$1 = interopDefault(_objectDps); var require$$4$2 = Object.freeze({ default: _objectDps$1 }); var _html = createCommonjsModule(function (module) { module.exports = interopDefault(require$$0).document && document.documentElement; }); var _html$1 = interopDefault(_html); var require$$0$15 = Object.freeze({ default: _html$1 }); var _objectCreate = createCommonjsModule(function (module) { // 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) var anObject = interopDefault(require$$2$1) , dPs = interopDefault(require$$4$2) , enumBugKeys = interopDefault(require$$0$12) , IE_PROTO = interopDefault(require$$0$11)('IE_PROTO') , Empty = function(){ /* empty */ } , PROTOTYPE = 'prototype'; // Create object with fake `null` prototype: use iframe Object with cleared prototype var createDict = function(){ // Thrash, waste and sodomy: IE GC bug var iframe = interopDefault(require$$1$3)('iframe') , i = enumBugKeys.length , lt = '<' , gt = '>' , iframeDocument; iframe.style.display = 'none'; interopDefault(require$$0$15).appendChild(iframe); iframe.src = 'javascript:'; // eslint-disable-line no-script-url // createDict = iframe.contentWindow.Object; // html.removeChild(iframe); iframeDocument = iframe.contentWindow.document; iframeDocument.open(); iframeDocument.write(lt + 'script' + gt + 'document.F=Object' + lt + '/script' + gt); iframeDocument.close(); createDict = iframeDocument.F; while(i--)delete createDict[PROTOTYPE][enumBugKeys[i]]; return createDict(); }; module.exports = Object.create || function create(O, Properties){ var result; if(O !== null){ Empty[PROTOTYPE] = anObject(O); result = new Empty; Empty[PROTOTYPE] = null; // add "__proto__" for Object.getPrototypeOf polyfill result[IE_PROTO] = O; } else result = createDict(); return Properties === undefined ? result : dPs(result, Properties); }; }); var _objectCreate$1 = interopDefault(_objectCreate); var require$$4$1 = Object.freeze({ default: _objectCreate$1 }); var _objectGopn = createCommonjsModule(function (module, exports) { // 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O) var $keys = interopDefault(require$$1$6) , hiddenKeys = interopDefault(require$$0$12).concat('length', 'prototype'); exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O){ return $keys(O, hiddenKeys); }; }); var _objectGopn$1 = interopDefault(_objectGopn); var f$5 = _objectGopn.f; var require$$0$16 = Object.freeze({ default: _objectGopn$1, f: f$5 }); var _objectGopnExt = createCommonjsModule(function (module) { // fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window var toIObject = interopDefault(require$$1$7) , gOPN = interopDefault(require$$0$16).f , toString = {}.toString; var windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames ? Object.getOwnPropertyNames(window) : []; var getWindowNames = function(it){ try { return gOPN(it); } catch(e){ return windowNames.slice(); } }; module.exports.f = function getOwnPropertyNames(it){ return windowNames && toString.call(it) == '[object Window]' ? getWindowNames(it) : gOPN(toIObject(it)); }; }); var _objectGopnExt$1 = interopDefault(_objectGopnExt); var f$4 = _objectGopnExt.f; var require$$8 = Object.freeze({ default: _objectGopnExt$1, f: f$4 }); var _objectGopd = createCommonjsModule(function (module, exports) { var pIE = interopDefault(require$$0$13) , createDesc = interopDefault(require$$3$3) , toIObject = interopDefault(require$$1$7) , toPrimitive = interopDefault(require$$3$2) , has = interopDefault(require$$2) , IE8_DOM_DEFINE = interopDefault(require$$1$2) , gOPD = Object.getOwnPropertyDescriptor; exports.f = interopDefault(require$$0$1) ? gOPD : function getOwnPropertyDescriptor(O, P){ O = toIObject(O); P = toPrimitive(P, true); if(IE8_DOM_DEFINE)try { return gOPD(O, P); } catch(e){ /* empty */ } if(has(O, P))return createDesc(!pIE.f.call(O, P), O[P]); }; }); var _objectGopd$1 = interopDefault(_objectGopd); var f$6 = _objectGopd.f; var require$$7$1 = Object.freeze({ default: _objectGopd$1, f: f$6 }); var es6_symbol = createCommonjsModule(function (module) { 'use strict'; // ECMAScript 6 symbols shim var global = interopDefault(require$$0) , has = interopDefault(require$$2) , DESCRIPTORS = interopDefault(require$$0$1) , $export = interopDefault(require$$1) , redefine = interopDefault(require$$7) , META = interopDefault(require$$24).KEY , $fails = interopDefault(require$$0$2) , shared = interopDefault(require$$1$4) , setToStringTag = interopDefault(require$$2$2) , uid = interopDefault(require$$0$4) , wks = interopDefault(require$$0$7) , wksExt = interopDefault(require$$1$5) , wksDefine = interopDefault(require$$17) , keyOf = interopDefault(require$$16) , enumKeys = interopDefault(require$$15) , isArray = interopDefault(require$$0$14) , anObject = interopDefault(require$$2$1) , toIObject = interopDefault(require$$1$7) , toPrimitive = interopDefault(require$$3$2) , createDesc = interopDefault(require$$3$3) , _create = interopDefault(require$$4$1) , gOPNExt = interopDefault(require$$8) , $GOPD = interopDefault(require$$7$1) , $DP = interopDefault(require$$3) , $keys = interopDefault(require$$2$3) , gOPD = $GOPD.f , dP = $DP.f , gOPN = gOPNExt.f , $Symbol = global.Symbol , $JSON = global.JSON , _stringify = $JSON && $JSON.stringify , PROTOTYPE = 'prototype' , HIDDEN = wks('_hidden') , TO_PRIMITIVE = wks('toPrimitive') , isEnum = {}.propertyIsEnumerable , SymbolRegistry = shared('symbol-registry') , AllSymbols = shared('symbols') , OPSymbols = shared('op-symbols') , ObjectProto = Object[PROTOTYPE] , USE_NATIVE = typeof $Symbol == 'function' , QObject = global.QObject; // Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173 var setter = !QObject || !QObject[PROTOTYPE] || !QObject[PROTOTYPE].findChild; // fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687 var setSymbolDesc = DESCRIPTORS && $fails(function(){ return _create(dP({}, 'a', { get: function(){ return dP(this, 'a', {value: 7}).a; } })).a != 7; }) ? function(it, key, D){ var protoDesc = gOPD(ObjectProto, key); if(protoDesc)delete ObjectProto[key]; dP(it, key, D); if(protoDesc && it !== ObjectProto)dP(ObjectProto, key, protoDesc); } : dP; var wrap = function(tag){ var sym = AllSymbols[tag] = _create($Symbol[PROTOTYPE]); sym._k = tag; return sym; }; var isSymbol = USE_NATIVE && typeof $Symbol.iterator == 'symbol' ? function(it){ return typeof it == 'symbol'; } : function(it){ return it instanceof $Symbol; }; var $defineProperty = function defineProperty(it, key, D){ if(it === ObjectProto)$defineProperty(OPSymbols, key, D); anObject(it); key = toPrimitive(key, true); anObject(D); if(has(AllSymbols, key)){ if(!D.enumerable){ if(!has(it, HIDDEN))dP(it, HIDDEN, createDesc(1, {})); it[HIDDEN][key] = true; } else { if(has(it, HIDDEN) && it[HIDDEN][key])it[HIDDEN][key] = false; D = _create(D, {enumerable: createDesc(0, false)}); } return setSymbolDesc(it, key, D); } return dP(it, key, D); }; var $defineProperties = function defineProperties(it, P){ anObject(it); var keys = enumKeys(P = toIObject(P)) , i = 0 , l = keys.length , key; while(l > i)$defineProperty(it, key = keys[i++], P[key]); return it; }; var $create = function create(it, P){ return P === undefined ? _create(it) : $defineProperties(_create(it), P); }; var $propertyIsEnumerable = function propertyIsEnumerable(key){ var E = isEnum.call(this, key = toPrimitive(key, true)); if(this === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key))return false; return E || !has(this, key) || !has(AllSymbols, key) || has(this, HIDDEN) && this[HIDDEN][key] ? E : true; }; var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(it, key){ it = toIObject(it); key = toPrimitive(key, true); if(it === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key))return; var D = gOPD(it, key); if(D && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key]))D.enumerable = true; return D; }; var $getOwnPropertyNames = function getOwnPropertyNames(it){ var names = gOPN(toIObject(it)) , result = [] , i = 0 , key; while(names.length > i){ if(!has(AllSymbols, key = names[i++]) && key != HIDDEN && key != META)result.push(key); } return result; }; var $getOwnPropertySymbols = function getOwnPropertySymbols(it){ var IS_OP = it === ObjectProto , names = gOPN(IS_OP ? OPSymbols : toIObject(it)) , result = [] , i = 0 , key; while(names.length > i){ if(has(AllSymbols, key = names[i++]) && (IS_OP ? has(ObjectProto, key) : true))result.push(AllSymbols[key]); } return result; }; // 19.4.1.1 Symbol([description]) if(!USE_NATIVE){ $Symbol = function Symbol(){ if(this instanceof $Symbol)throw TypeError('Symbol is not a constructor!'); var tag = uid(arguments.length > 0 ? arguments[0] : undefined); var $set = function(value){ if(this === ObjectProto)$set.call(OPSymbols, value); if(has(this, HIDDEN) && has(this[HIDDEN], tag))this[HIDDEN][tag] = false; setSymbolDesc(this, tag, createDesc(1, value)); }; if(DESCRIPTORS && setter)setSymbolDesc(ObjectProto, tag, {configurable: true, set: $set}); return wrap(tag); }; redefine($Symbol[PROTOTYPE], 'toString', function toString(){ return this._k; }); $GOPD.f = $getOwnPropertyDescriptor; $DP.f = $defineProperty; interopDefault(require$$0$16).f = gOPNExt.f = $getOwnPropertyNames; interopDefault(require$$0$13).f = $propertyIsEnumerable; interopDefault(require$$4).f = $getOwnPropertySymbols; if(DESCRIPTORS && !interopDefault(require$$9)){ redefine(ObjectProto, 'propertyIsEnumerable', $propertyIsEnumerable, true); } wksExt.f = function(name){ return wrap(wks(name)); } } $export($export.G + $export.W + $export.F * !USE_NATIVE, {Symbol: $Symbol}); for(var symbols = ( // 19.4.2.2, 19.4.2.3, 19.4.2.4, 19.4.2.6, 19.4.2.8, 19.4.2.9, 19.4.2.10, 19.4.2.11, 19.4.2.12, 19.4.2.13, 19.4.2.14 'hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables' ).split(','), i = 0; symbols.length > i; )wks(symbols[i++]); for(var symbols = $keys(wks.store), i = 0; symbols.length > i; )wksDefine(symbols[i++]); $export($export.S + $export.F * !USE_NATIVE, 'Symbol', { // 19.4.2.1 Symbol.for(key) 'for': function(key){ return has(SymbolRegistry, key += '') ? SymbolRegistry[key] : SymbolRegistry[key] = $Symbol(key); }, // 19.4.2.5 Symbol.keyFor(sym) keyFor: function keyFor(key){ if(isSymbol(key))return keyOf(SymbolRegistry, key); throw TypeError(key + ' is not a symbol!'); }, useSetter: function(){ setter = true; }, useSimple: function(){ setter = false; } }); $export($export.S + $export.F * !USE_NATIVE, 'Object', { // 19.1.2.2 Object.create(O [, Properties]) create: $create, // 19.1.2.4 Object.defineProperty(O, P, Attributes) defineProperty: $defineProperty, // 19.1.2.3 Object.defineProperties(O, Properties) defineProperties: $defineProperties, // 19.1.2.6 Object.getOwnPropertyDescriptor(O, P) getOwnPropertyDescriptor: $getOwnPropertyDescriptor, // 19.1.2.7 Object.getOwnPropertyNames(O) getOwnPropertyNames: $getOwnPropertyNames, // 19.1.2.8 Object.getOwnPropertySymbols(O) getOwnPropertySymbols: $getOwnPropertySymbols }); // 24.3.2 JSON.stringify(value [, replacer [, space]]) $JSON && $export($export.S + $export.F * (!USE_NATIVE || $fails(function(){ var S = $Symbol(); // MS Edge converts symbol values to JSON as {} // WebKit converts symbol values to JSON as null // V8 throws on boxed symbols return _stringify([S]) != '[null]' || _stringify({a: S}) != '{}' || _stringify(Object(S)) != '{}'; })), 'JSON', { stringify: function stringify(it){ if(it === undefined || isSymbol(it))return; // IE8 returns string on undefined var args = [it] , i = 1 , replacer, $replacer; while(arguments.length > i)args.push(arguments[i++]); replacer = args[1]; if(typeof replacer == 'function')$replacer = replacer; if($replacer || !isArray(replacer))replacer = function(key, value){ if($replacer)value = $replacer.call(this, key, value); if(!isSymbol(value))return value; }; args[1] = replacer; return _stringify.apply($JSON, args); } }); // 19.4.3.4 Symbol.prototype[@@toPrimitive](hint) $Symbol[PROTOTYPE][TO_PRIMITIVE] || interopDefault(require$$1$1)($Symbol[PROTOTYPE], TO_PRIMITIVE, $Symbol[PROTOTYPE].valueOf); // 19.4.3.5 Symbol.prototype[@@toStringTag] setToStringTag($Symbol, 'Symbol'); // 20.2.1.9 Math[@@toStringTag] setToStringTag(Math, 'Math', true); // 24.3.3 JSON[@@toStringTag] setToStringTag(global.JSON, 'JSON', true); }); interopDefault(es6_symbol); var _classof = createCommonjsModule(function (module) { // getting tag from 19.1.3.6 Object.prototype.toString() var cof = interopDefault(require$$1$9) , TAG = interopDefault(require$$0$7)('toStringTag') // ES3 wrong here , ARG = cof(function(){ return arguments; }()) == 'Arguments'; // fallback for IE11 Script Access Denied error var tryGet = function(it, key){ try { return it[key]; } catch(e){ /* empty */ } }; module.exports = function(it){ var O, T, B; return it === undefined ? 'Undefined' : it === null ? 'Null' // @@toStringTag case : typeof (T = tryGet(O = Object(it), TAG)) == 'string' ? T // builtinTag case : ARG ? cof(O) // ES3 arguments fallback : (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B; }; }); var _classof$1 = interopDefault(_classof); var require$$2$4 = Object.freeze({ default: _classof$1 }); var es6_object_toString = createCommonjsModule(function (module) { 'use strict'; // 19.1.3.6 Object.prototype.toString() var classof = interopDefault(require$$2$4) , test = {}; test[interopDefault(require$$0$7)('toStringTag')] = 'z'; if(test + '' != '[object z]'){ interopDefault(require$$7)(Object.prototype, 'toString', function toString(){ return '[object ' + classof(this) + ']'; }, true); } }); interopDefault(es6_object_toString); var symbol = createCommonjsModule(function (module) { module.exports = interopDefault(require$$0$3).Symbol; }); interopDefault(symbol); var _addToUnscopables = createCommonjsModule(function (module) { // 22.1.3.31 Array.prototype[@@unscopables] var UNSCOPABLES = interopDefault(require$$0$7)('unscopables') , ArrayProto = Array.prototype; if(ArrayProto[UNSCOPABLES] == undefined)interopDefault(require$$1$1)(ArrayProto, UNSCOPABLES, {}); module.exports = function(key){ ArrayProto[UNSCOPABLES][key] = true; }; }); var _addToUnscopables$1 = interopDefault(_addToUnscopables); var require$$4$3 = Object.freeze({ default: _addToUnscopables$1 }); var _iterStep = createCommonjsModule(function (module) { module.exports = function(done, value){ return {value: value, done: !!done}; }; }); var _iterStep$1 = interopDefault(_iterStep); var require$$3$4 = Object.freeze({ default: _iterStep$1 }); var _iterators = createCommonjsModule(function (module) { module.exports = {}; }); var _iterators$1 = interopDefault(_iterators); var require$$4$4 = Object.freeze({ default: _iterators$1 }); var _iterCreate = createCommonjsModule(function (module) { 'use strict'; var create = interopDefault(require$$4$1) , descriptor = interopDefault(require$$3$3) , setToStringTag = interopDefault(require$$2$2) , IteratorPrototype = {}; // 25.1.2.1.1 %IteratorPrototype%[@@iterator]() interopDefault(require$$1$1)(IteratorPrototype, interopDefault(require$$0$7)('iterator'), function(){ return this; }); module.exports = function(Constructor, NAME, next){ Constructor.prototype = create(IteratorPrototype, {next: descriptor(1, next)}); setToStringTag(Constructor, NAME + ' Iterator'); }; }); var _iterCreate$1 = interopDefault(_iterCreate); var require$$3$5 = Object.freeze({ default: _iterCreate$1 }); var _toObject = createCommonjsModule(function (module) { // 7.1.13 ToObject(argument) var defined = interopDefault(require$$0$8); module.exports = function(it){ return Object(defined(it)); }; }); var _toObject$1 = interopDefault(_toObject); var require$$2$5 = Object.freeze({ default: _toObject$1 }); var _objectGpo = createCommonjsModule(function (module) { // 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O) var has = interopDefault(require$$2) , toObject = interopDefault(require$$2$5) , IE_PROTO = interopDefault(require$$0$11)('IE_PROTO') , ObjectProto = Object.prototype; module.exports = Object.getPrototypeOf || function(O){ O = toObject(O); if(has(O, IE_PROTO))return O[IE_PROTO]; if(typeof O.constructor == 'function' && O instanceof O.constructor){ return O.constructor.prototype; } return O instanceof Object ? ObjectProto : null; }; }); var _objectGpo$1 = interopDefault(_objectGpo); var require$$1$12 = Object.freeze({ default: _objectGpo$1 }); var _iterDefine = createCommonjsModule(function (module) { 'use strict'; var LIBRARY = interopDefault(require$$9) , $export = interopDefault(require$$1) , redefine = interopDefault(require$$7) , hide = interopDefault(require$$1$1) , has = interopDefault(require$$2) , Iterators = interopDefault(require$$4$4) , $iterCreate = interopDefault(require$$3$5) , setToStringTag = interopDefault(require$$2$2) , getPrototypeOf = interopDefault(require$$1$12) , ITERATOR = interopDefault(require$$0$7)('iterator') , BUGGY = !([].keys && 'next' in [].keys()) // Safari has buggy iterators w/o `next` , FF_ITERATOR = '@@iterator' , KEYS = 'keys' , VALUES = 'values'; var returnThis = function(){ return this; }; module.exports = function(Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED){ $iterCreate(Constructor, NAME, next); var getMethod = function(kind){ if(!BUGGY && kind in proto)return proto[kind]; switch(kind){ case KEYS: return function keys(){ return new Constructor(this, kind); }; case VALUES: return function values(){ return new Constructor(this, kind); }; } return function entries(){ return new Constructor(this, kind); }; }; var TAG = NAME + ' Iterator' , DEF_VALUES = DEFAULT == VALUES , VALUES_BUG = false , proto = Base.prototype , $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT] , $default = $native || getMethod(DEFAULT) , $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined , $anyNative = NAME == 'Array' ? proto.entries || $native : $native , methods, key, IteratorPrototype; // Fix native if($anyNative){ IteratorPrototype = getPrototypeOf($anyNative.call(new Base)); if(IteratorPrototype !== Object.prototype){ // Set @@toStringTag to native iterators setToStringTag(IteratorPrototype, TAG, true); // fix for some old engines if(!LIBRARY && !has(IteratorPrototype, ITERATOR))hide(IteratorPrototype, ITERATOR, returnThis); } } // fix Array#{values, @@iterator}.name in V8 / FF if(DEF_VALUES && $native && $native.name !== VALUES){ VALUES_BUG = true; $default = function values(){ return $native.call(this); }; } // Define iterator if((!LIBRARY || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])){ hide(proto, ITERATOR, $default); } // Plug for library Iterators[NAME] = $default; Iterators[TAG] = returnThis; if(DEFAULT){ methods = { values: DEF_VALUES ? $default : getMethod(VALUES), keys: IS_SET ? $default : getMethod(KEYS), entries: $entries }; if(FORCED)for(key in methods){ if(!(key in proto))redefine(proto, key, methods[key]); } else $export($export.P + $export.F * (BUGGY || VALUES_BUG), NAME, methods); } return methods; }; }); var _iterDefine$1 = interopDefault(_iterDefine); var require$$0$17 = Object.freeze({ default: _iterDefine$1 }); var es6_array_iterator = createCommonjsModule(function (module) { 'use strict'; var addToUnscopables = interopDefault(require$$4$3) , step = interopDefault(require$$3$4) , Iterators = interopDefault(require$$4$4) , toIObject = interopDefault(require$$1$7); // 22.1.3.4 Array.prototype.entries() // 22.1.3.13 Array.prototype.keys() // 22.1.3.29 Array.prototype.values() // 22.1.3.30 Array.prototype[@@iterator]() module.exports = interopDefault(require$$0$17)(Array, 'Array', function(iterated, kind){ this._t = toIObject(iterated); // target this._i = 0; // next index this._k = kind; // kind // 22.1.5.2.1 %ArrayIteratorPrototype%.next() }, function(){ var O = this._t , kind = this._k , index = this._i++; if(!O || index >= O.length){ this._t = undefined; return step(1); } if(kind == 'keys' )return step(0, index); if(kind == 'values')return step(0, O[index]); return step(0, [index, O[index]]); }, 'values'); // argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7) Iterators.Arguments = Iterators.Array; addToUnscopables('keys'); addToUnscopables('values'); addToUnscopables('entries'); }); interopDefault(es6_array_iterator); var iterator = createCommonjsModule(function (module) { module.exports = interopDefault(require$$0$3).Array.values; }); interopDefault(iterator); var _objectAssign = createCommonjsModule(function (module) { 'use strict'; // 19.1.2.1 Object.assign(target, source, ...) var getKeys = interopDefault(require$$2$3) , gOPS = interopDefault(require$$4) , pIE = interopDefault(require$$0$13) , toObject = interopDefault(require$$2$5) , IObject = interopDefault(require$$1$8) , $assign = Object.assign; // should work with symbols and should have deterministic property order (V8 bug) module.exports = !$assign || interopDefault(require$$0$2)(function(){ var A = {} , B = {} , S = Symbol() , K = 'abcdefghijklmnopqrst'; A[S] = 7; K.split('').forEach(function(k){ B[k] = k; }); return $assign({}, A)[S] != 7 || Object.keys($assign({}, B)).join('') != K; }) ? function assign(target, source){ // eslint-disable-line no-unused-vars var T = toObject(target) , aLen = arguments.length , index = 1 , getSymbols = gOPS.f , isEnum = pIE.f; while(aLen > index){ var S = IObject(arguments[index++]) , keys = getSymbols ? getKeys(S).concat(getSymbols(S)) : getKeys(S) , length = keys.length , j = 0 , key; while(length > j)if(isEnum.call(S, key = keys[j++]))T[key] = S[key]; } return T; } : $assign; }); var _objectAssign$1 = interopDefault(_objectAssign); var require$$0$18 = Object.freeze({ default: _objectAssign$1 }); var es6_object_assign = createCommonjsModule(function (module) { // 19.1.3.1 Object.assign(target, source) var $export = interopDefault(require$$1); $export($export.S + $export.F, 'Object', {assign: interopDefault(require$$0$18)}); }); interopDefault(es6_object_assign); var assign = createCommonjsModule(function (module) { module.exports = interopDefault(require$$0$3).Object.assign; }); interopDefault(assign); var es6_array_isArray = createCommonjsModule(function (module) { // 22.1.2.2 / 15.4.3.2 Array.isArray(arg) var $export = interopDefault(require$$1); $export($export.S, 'Array', {isArray: interopDefault(require$$0$14)}); }); interopDefault(es6_array_isArray); var isArray = createCommonjsModule(function (module) { module.exports = interopDefault(require$$0$3).Array.isArray; }); interopDefault(isArray); var _objectToArray = createCommonjsModule(function (module) { var getKeys = interopDefault(require$$2$3) , toIObject = interopDefault(require$$1$7) , isEnum = interopDefault(require$$0$13).f; module.exports = function(isEntries){ return function(it){ var O = toIObject(it) , keys = getKeys(O) , length = keys.length , i = 0 , result = [] , key; while(length > i)if(isEnum.call(O, key = keys[i++])){ result.push(isEntries ? [key, O[key]] : O[key]); } return result; }; }; }); var _objectToArray$1 = interopDefault(_objectToArray); var require$$0$19 = Object.freeze({ default: _objectToArray$1 }); var es7_object_values = createCommonjsModule(function (module) { // https://github.com/tc39/proposal-object-values-entries var $export = interopDefault(require$$1) , $values = interopDefault(require$$0$19)(false); $export($export.S, 'Object', { values: function values(it){ return $values(it); } }); }); interopDefault(es7_object_values); var values = createCommonjsModule(function (module) { module.exports = interopDefault(require$$0$3).Object.values; }); interopDefault(values); var doc; var cursor; var styleModifiers; var pageSize; var settings; var table; // The current Table instance /** * Create a table from a set of rows and columns. * * @param {Object[]|String[]} headers Either as an array of objects or array of strings * @param {Object[][]|String[][]} data Either as an array of objects or array of strings * @param {Object} [options={}] Options that will override the default ones */ jsPDF.API.autoTable = function (headers, data, options) { validateInput(headers, data, options); doc = this; pageSize = doc.internal.pageSize; styleModifiers = { fillColor: doc.setFillColor, textColor: doc.setTextColor, fontStyle: doc.setFontStyle, lineColor: doc.setDrawColor, lineWidth: doc.setLineWidth, font: doc.setFont, fontSize: doc.setFontSize }; settings = Config.initSettings(options || {}); // Need a cursor y as it needs to be reset after each page (row.y can't do that) // Also prefer cursor to column.x as the cursor is easier to modify in the hooks cursor = { x: settings.margin.left, y: settings.startY === false ? settings.margin.top : settings.startY }; var userStyles = { textColor: 30, // Setting text color to dark gray as it can't be obtained from jsPDF fontSize: doc.internal.getFontSize(), fontStyle: doc.internal.getFont().fontStyle }; // Create the table model with its columns, rows and cells createModels(headers, data); calculateWidths(this, pageSize.width); // Page break if there is room for only the first data row var firstRowHeight = table.rows[0] && settings.pageBreak === 'auto' ? table.rows[0].height : 0; var minTableBottomPos = settings.startY + settings.margin.bottom + table.headerRow.height + firstRowHeight; if (settings.pageBreak === 'avoid') { minTableBottomPos += table.height; } if (settings.pageBreak === 'always' && settings.startY !== false || settings.startY !== false && minTableBottomPos > pageSize.height) { this.addPage(this.addPage); cursor.y = settings.margin.top; } applyStyles(userStyles); settings.beforePageContent(hooksData()); if (settings.drawHeaderRow(table.headerRow, hooksData({ row: table.headerRow })) !== false) { printRow(table.headerRow, settings.drawHeaderCell); } applyStyles(userStyles); printRows(this.addPage); settings.afterPageContent(hooksData()); applyStyles(userStyles); return this; }; /** * Returns the Y position of the last drawn cell * @returns int */ jsPDF.API.autoTableEndPosY = function () { if (typeof cursor === 'undefined' || typeof cursor.y === 'undefined') { return 0; } return cursor.y; }; /** * Parses an html table * * @param tableElem Html table element * @param includeHiddenElements If to include hidden rows and columns (defaults to false) * @returns Object Object with two properties, columns and rows */ jsPDF.API.autoTableHtmlToJson = function (tableElem, includeHiddenElements) { includeHiddenElements = includeHiddenElements || false; var columns = {}, rows = []; var header = tableElem.rows[0]; for (var k = 0; k < header.cells.length; k++) { var cell = header.cells[k]; var style = window.getComputedStyle(cell); if (includeHiddenElements || style.display !== 'none') { columns[k] = cell ? cell.textContent.trim() : ''; } } for (var i = 1; i < tableElem.rows.length; i++) { var tableRow = tableElem.rows[i]; var style = window.getComputedStyle(tableRow); if (includeHiddenElements || style.display !== 'none') { var rowData = []; var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = Object.keys(columns)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var j = _step.value; var cell = tableRow.cells[j]; var val = cell ? cell.textContent.trim() : ''; rowData.push(val); } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator.return) { _iterator.return(); } } finally { if (_didIteratorError) { throw _iteratorError; } } } rows.push(rowData); } } return { columns: Object.values(columns), rows: rows, data: rows }; // data prop deprecated }; /** * Add a new page including an autotable header etc. Use this function in the hooks. * * @param tableElem Html table element * @param includeHiddenElements If to include hidden rows and columns (defaults to false) * @returns Object Object with two properties, columns and rows */ jsPDF.API.autoTableAddPage = function () { addPage(doc.addPage); }; /** * Improved text function with halign and valign support * Inspiration from: http://stackoverflow.com/questions/28327510/align-text-right-using-jspdf/28433113#28433113 */ jsPDF.API.autoTableText = function (text, x, y, styles) { if (typeof x !== 'number' || typeof y !== 'number') { console.error('The x and y parameters are required. Missing for the text: ', text); } var fontSize = this.internal.getFontSize() / this.internal.scaleFactor; // As defined in jsPDF source code var lineHeightProportion = FONT_ROW_RATIO; var splitRegex = /\r\n|\r|\n/g; var splittedText = null; var lineCount = 1; if (styles.valign === 'middle' || styles.valign === 'bottom' || styles.halign === 'center' || styles.halign === 'right') { splittedText = typeof text === 'string' ? text.split(splitRegex) : text; lineCount = splittedText.length || 1; } // Align the top y += fontSize * (2 - lineHeightProportion); if (styles.valign === 'middle') y -= lineCount / 2 * fontSize;else if (styles.valign === 'bottom') y -= lineCount * fontSize; if (styles.halign === 'center' || styles.halign === 'right') { var alignSize = fontSize; if (styles.halign === 'center') alignSize *= 0.5; if (lineCount >= 1) { for (var iLine = 0; iLine < splittedText.length; iLine++) { this.text(splittedText[iLine], x - this.getStringUnitWidth(splittedText[iLine]) * alignSize, y); y += fontSize; } return doc; } x -= this.getStringUnitWidth(text) * alignSize; } this.text(text, x, y); return this; }; function validateInput(headers, data, options) { if (!headers || (typeof headers === 'undefined' ? 'undefined' : _typeof(headers)) !== 'object') { console.error("The headers should be an object or array, is: " + (typeof headers === 'undefined' ? 'undefined' : _typeof(headers))); } if (!data || (typeof data === 'undefined' ? 'undefined' : _typeof(data)) !== 'object') { console.error("The data should be an object or array, is: " + (typeof data === 'undefined' ? 'undefined' : _typeof(data))); } if (!!options && (typeof options === 'undefined' ? 'undefined' : _typeof(options)) !== 'object') { console.error("The data should be an object or array, is: " + (typeof data === 'undefined' ? 'undefined' : _typeof(data))); } if (!Array.prototype.forEach) { console.error("The current browser does not support Array.prototype.forEach which is required for " + "jsPDF-AutoTable. You can try polyfilling it by including this script " + "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach#Polyfill"); } } /** * Create models from the user input * * @param inputHeaders * @param inputData */ function createModels(inputHeaders, inputData) { table = new Table(); var splitRegex = /\r\n|\r|\n/g; // Header row and columns var headerRow = new Row(inputHeaders); headerRow.index = -1; var themeStyles = Config.styles([themes[settings.theme].table, themes[settings.theme].header]); headerRow.styles = Object.assign({}, themeStyles, settings.styles, settings.headerStyles); // Columns and header row inputHeaders.forEach(function (rawColumn, dataKey) { var index = dataKey; if ((typeof rawColumn === 'undefined' ? 'undefined' : _typeof(rawColumn)) === 'object') { dataKey = typeof rawColumn.dataKey !== 'undefined' ? rawColumn.dataKey : rawColumn.key; } if (typeof rawColumn.width !== 'undefined') { console.error("Use of deprecated option: column.width, use column.styles.columnWidth instead."); } var col = new Column(dataKey, index); col.styles = settings.columnStyles[col.dataKey] || {}; table.columns.push(col); var cell = new Cell(); cell.raw = (typeof rawColumn === 'undefined' ? 'undefined' : _typeof(rawColumn)) === 'object' ? rawColumn.title : rawColumn; cell.styles = Object.assign({}, headerRow.styles); cell.text = '' + cell.raw; cell.contentWidth = cell.styles.cellPadding * 2 + getStringWidth(cell.text, cell.styles); cell.text = cell.text.split(splitRegex); headerRow.cells[dataKey] = cell; settings.createdHeaderCell(cell, { column: col, row: headerRow, settings: settings }); }); table.headerRow = headerRow; // Rows och cells inputData.forEach(function (rawRow, i) { var row = new Row(rawRow); var isAlternate = i % 2 === 0; var themeStyles = Config.styles([themes[settings.theme].table, isAlternate ? themes[settings.theme].alternateRow : {}]); var userStyles = Object.assign({}, settings.styles, settings.bodyStyles, isAlternate ? settings.alternateRowStyles : {}); row.styles = Object.assign({}, themeStyles, userStyles); row.index = i; table.columns.forEach(function (column) { var cell = new Cell(); cell.raw = rawRow[column.dataKey]; cell.styles = Object.assign({}, row.styles, column.styles); cell.text = typeof cell.raw !== 'undefined' ? '' + cell.raw : ''; // Stringify 0 and false, but not undefined row.cells[column.dataKey] = cell; settings.createdCell(cell, hooksData({ column: column, row: row })); cell.contentWidth = cell.styles.cellPadding * 2 + getStringWidth(cell.text, cell.styles); cell.text = cell.text.split(splitRegex); }); table.rows.push(row); }); } /** * Calculate the column widths */ function calculateWidths(doc, pageWidth) { // Column and table content width var tableContentWidth = 0; table.columns.forEach(function (column) { column.contentWidth = table.headerRow.cells[column.dataKey].contentWidth; table.rows.forEach(function (row) { var cellWidth = row.cells[column.dataKey].contentWidth; if (cellWidth > column.contentWidth) { column.contentWidth = cellWidth; } }); column.width = column.contentWidth; tableContentWidth += column.contentWidth; }); table.contentWidth = tableContentWidth; var maxTableWidth = pageWidth - settings.margin.left - settings.margin.right; var preferredTableWidth = maxTableWidth; // settings.tableWidth === 'auto' if (typeof settings.tableWidth === 'number') { preferredTableWidth = settings.tableWidth; } else if (settings.tableWidth === 'wrap') { preferredTableWidth = table.contentWidth; } table.width = preferredTableWidth < maxTableWidth ? preferredTableWidth : maxTableWidth; // To avoid subjecting columns with little content with the chosen overflow method, // never shrink a column more than the table divided by column count (its "fair part") var dynamicColumns = []; var dynamicColumnsContentWidth = 0; var fairWidth = table.width / table.columns.length; var staticWidth = 0; table.columns.forEach(function (column) { var colStyles = Config.styles([themes[settings.theme].table, settings.styles, column.styles]); if (colStyles.columnWidth === 'wrap') { column.width = column.contentWidth; } else if (typeof colStyles.columnWidth === 'number') { column.width = colStyles.columnWidth; } else if (colStyles.columnWidth === 'auto' || true) { if (column.contentWidth <= fairWidth && table.contentWidth > table.width) { column.width = column.contentWidth; } else { dynamicColumns.push(column); dynamicColumnsContentWidth += column.contentWidth; column.width = 0; } } staticWidth += column.width; }); // Distributes extra width or trims columns down to fit distributeWidth(dynamicColumns, staticWidth, dynamicColumnsContentWidth, fairWidth); // Row height, table height and text overflow table.height = 0; var all = table.rows.concat(table.headerRow); all.forEach(function (row, i) { var lineBreakCount = 0; table.columns.forEach(function (col) { var cell = row.cells[col.dataKey]; applyStyles(cell.styles); var textSpace = col.width - cell.styles.cellPadding * 2; if (cell.styles.overflow === 'linebreak') { // Add one pt to textSpace to fix rounding error try { cell.text = doc.splitTextToSize(cell.text, textSpace + 1, { fontSize: cell.styles.fontSize }); } catch (e) { if (e instanceof TypeError && Array.isArray(cell.text)) { cell.text = doc.splitTextToSize(cell.text.join(' '), textSpace + 1, { fontSize: cell.styles.fontSize }); } else { throw e; } } } else if (cell.styles.overflow === 'ellipsize') { cell.text = ellipsize(cell.text, textSpace, cell.styles); } else if (cell.styles.overflow === 'visible') { // Do nothing } else if (cell.styles.overflow === 'hidden') { cell.text = ellipsize(cell.text, textSpace, cell.styles, ''); } else if (typeof cell.styles.overflow === 'function') { cell.text = cell.styles.overflow(cell.text, textSpace); } else { console.error("Unrecognized overflow type: " + cell.styles.overflow); } var count = Array.isArray(cell.text) ? cell.text.length - 1 : 0; if (count > lineBreakCount) { lineBreakCount = count; } }); row.heightStyle = row.styles.rowHeight; // TODO Pick the highest row based on font size as well row.height = row.heightStyle + lineBreakCount * row.styles.fontSize * FONT_ROW_RATIO; table.height += row.height; }); } function distributeWidth(dynamicColumns, staticWidth, dynamicColumnsContentWidth, fairWidth) { var extraWidth = table.width - staticWidth - dynamicColumnsContentWidth; for (var i = 0; i < dynamicColumns.length; i++) { var col = dynamicColumns[i]; var ratio = col.contentWidth / dynamicColumnsContentWidth; // A column turned out to be none dynamic, start over recursively var isNoneDynamic = col.contentWidth + extraWidth * ratio < fairWidth; if (extraWidth < 0 && isNoneDynamic) { dynamicColumns.splice(i, 1); dynamicColumnsContentWidth -= col.contentWidth; col.width = fairWidth; staticWidth += col.width; distributeWidth(dynamicColumns, staticWidth, dynamicColumnsContentWidth, fairWidth); break; } else { col.width = col.contentWidth + extraWidth * ratio; } } } function addPage(jspdfAddPage) { settings.afterPageContent(hooksData()); jspdfAddPage(); table.pageCount++; cursor = { x: settings.margin.left, y: settings.margin.top }; settings.beforePageContent(hooksData()); if (settings.drawHeaderRow(table.headerRow, hooksData({ row: table.headerRow })) !== false) { printRow(table.headerRow, settings.drawHeaderCell); } } /** * Add a new page if cursor is at the end of page */ function isNewPage(rowHeight) { var afterRowPos = cursor.y + rowHeight + settings.margin.bottom; return afterRowPos >= pageSize.height; } function printRows(jspdfAddPage) { table.rows.forEach(function (row, i) { if (isNewPage(row.height)) { var samePageThreshold = 3; // TODO Fix cell height > page height /*if (row.height > row.heightStyle * samePageThreshold) { var remainingPageSpace = pageSize.height - cursor.y - settings.margin.bottom; var lineCount = Math.floor(remainingPageSpace / (row.styles.fontSize * FONT_ROW_RATIO)); table.columns.forEach(function(col) { var arr = row.cells[col.dataKey].text; if (arr.length > lineCount) { arr.splice(lineCount - 1, arr.length, "..."); } }); row.height = remainingPageSpace; if (settings.drawRow(row, hooksData({row: row})) !== false) { printRow(row, settings.drawCell); } row = new Row(rawRow); }*/ addPage(jspdfAddPage); } row.y = cursor.y; if (settings.drawRow(row, hooksData({ row: row })) !== false) { printRow(row, settings.drawCell); } }); } function printRow(row, hookHandler) { cursor.x = settings.margin.left; for (var i = 0; i < table.columns.length; i++) { var column = table.columns[i]; var cell = row.cells[column.dataKey]; if (!cell) { continue; } applyStyles(cell.styles); cell.x = cursor.x; cell.y = cursor.y; cell.height = row.height; cell.width = column.width; if (cell.styles.valign === 'top') { cell.textPos.y = cursor.y + cell.styles.cellPadding; } else if (cell.styles.valign === 'bottom') { cell.textPos.y = cursor.y + row.height - cell.styles.cellPadding; } else { cell.textPos.y = cursor.y + row.height / 2; } if (cell.styles.halign === 'right') { cell.textPos.x = cell.x + cell.width - cell.styles.cellPadding; } else if (cell.styles.halign === 'center') { cell.textPos.x = cell.x + cell.width / 2; } else { cell.textPos.x = cell.x + cell.styles.cellPadding; } var data = hooksData({ column: column, row: row }); if (hookHandler(cell, data) !== false) { doc.rect(cell.x, cell.y, cell.width, cell.height, cell.styles.fillStyle); doc.autoTableText(cell.text, cell.textPos.x, cell.textPos.y, { halign: cell.styles.halign, valign: cell.styles.valign }); } cursor.x += cell.width; } cursor.y += row.height; } function applyStyles(styles) { Object.keys(styleModifiers).forEach(function (name) { var style = styles[name]; var modifier = styleModifiers[name]; if (typeof style !== 'undefined') { if (style.constructor === Array) { modifier.apply(this, style); } else { modifier(style); } } }); } function hooksData(additionalData) { return Object.assign({ pageCount: table.pageCount, settings: settings, table: table, cursor: cursor }, additionalData || {}); } function getStringWidth(text, styles) { applyStyles(styles); var w = doc.getStringUnitWidth(text); return w * styles.fontSize; } /** * Ellipsize the text to fit in the width */ function ellipsize(text, width, styles, ellipsizeStr) { ellipsizeStr = typeof ellipsizeStr !== 'undefined' ? ellipsizeStr : '...'; if (Array.isArray(text)) { text.forEach(function (str, i) { text[i] = ellipsize(str, width, styles, ellipsizeStr); }); return text; } if (width >= getStringWidth(text, styles)) { return text; } while (width < getStringWidth(text + ellipsizeStr, styles)) { if (text.length < 2) { break; } text = text.substring(0, text.length - 1); } return text.trim() + ellipsizeStr; } }(jsPDF));
(function () { 'use strict'; module.exports = function () { // You can use normal require here, cucumber is NOT run in a Meteor context (by design) var url = require('url'); var path = require('path'); this.Given(/^I am a new user$/, function () { // no callbacks! DDP has been promisified so you can just return it return this.server.call('reset', []); // this.ddp is a connection to the mirror }); this.Given(/^I am on route "([^"]*)"$/, function (relativePath, callback) { // WebdriverIO supports Promises/A+ out the box, so you can return that too this.browser. // this.browser is a pre-configured WebdriverIO + PhantomJS instance url(url.resolve(process.env.HOST, relativePath)). // process.env.HOST always points to the mirror call(callback); }); this.Then(/^I should see the title "([^"]*)"$/, function (expectedTitle, callback) { // you can use chai-as-promised in step definitions also this.browser. waitForVisible('h1'). // WebdriverIO chain-able promise magic getTitle().should.become(expectedTitle).and.notify(callback); }); this.When(/^I upload a new image$/, function (callback) { var filePath = path.join(__filename, '../../../files/face.png'); this.browser //.chooseFile('#upload-file', '/home/netanel/Pictures/hospital.jpg') .click('#upload-file') .keys(filePath) .pause(3000) .call(callback); }); this.Then(/^I should see the image in the table$/, function (callback) { this.browser .getText('table tr:first-child a') .should.eventually.equal('face.png').and.notify(callback); }); }; })();
(function($angular) { "use strict"; // The truest wisdom is a resolute determination... var module = $angular.module('ngDroplet', []).directive('droplet', ['$rootScope', '$window', '$timeout', '$q', function DropletDirective($rootScope, $window, $timeout, $q) { return { /** * @property restrict * @type {String} */ restrict: 'EA', /** * @property require * @type {String} */ require: '?ngModel', /** * @property scope * @type {Object} */ scope: { interface: '=ngModel' }, /** * @method controller * @param $scope {Object} * @return {void} */ controller: ['$scope', function DropletController($scope) { /** * @constant FILE_TYPES * @type {Object} */ $scope.FILE_TYPES = { VALID: 1, INVALID: 2, DELETED: 4, UPLOADED: 8 }; // Dynamically add the `ALL` property. $scope.FILE_TYPES.ALL = Object.keys($scope.FILE_TYPES).reduce(function map(current, key) { return (current |= $scope.FILE_TYPES[key]); }, 0); /** * @property files * @type {Array} */ $scope.files = []; /** * @property isUploading * @type {Boolean} */ $scope.isUploading = false; /** * @property isError * @type {Boolean} */ $scope.isError = false; /** * @method _isValid * @param value {String|Number} * @param values {Array} * @return {Boolean} * @private */ var _isValid = function _isValid(value, values) { /** * @method conditionallyLowercase * @param value {String|Number} * @return {String|Number} */ var conditionallyLowercase = function conditionallyLowercase(value) { if (typeof value === 'string') { return value.toLowerCase(); } return value; }; return values.some(function some(currentValue) { var isRegExp = (currentValue instanceof $window.RegExp); if (isRegExp) { // Evaluate the status code as a regular expression. return currentValue.test(conditionallyLowercase(value)); } return conditionallyLowercase(currentValue) === conditionallyLowercase(value); }); }; /** * Responsible for determining if the event is actually a jQuery event, which has therefore * placed the original event inside of the `originalEvent` property. * * @method getEvent * @param event {Object} * @return {Object} */ $scope.getEvent = function getEvent(event) { if ('originalEvent' in event) { // jQuery likes to send across its own event, and place the original event // in the `originalEvent` property. return event.originalEvent; } return event; }; /** * @method isValidHTTPStatus * @param statusCode {Number} * @return {Boolean} */ $scope.isValidHTTPStatus = function isValidHTTPStatus(statusCode) { return _isValid(statusCode, $scope.options.statuses.success); }; /** * @method isValidExtension * @param extension {String} * @return {Boolean} */ $scope.isValidExtension = function isValidExtension(extension) { return _isValid(extension, $scope.options.extensions); }; /** * @property options * @type {Object} */ $scope.options = { /** * URL that will be called when making the POST request. * * @property requestUrl * @type {String} */ requestUrl: '', /** * Determines whether the X-File-Size header is appended to the request. * * @property disableXFileSize * @type {Boolean} */ disableXFileSize: false, /** * @property parserFn * @type {Function} */ parserFn: function parserFunction(responseText) { return $window.JSON.parse(responseText); }, /** * Whether to use the array notation for the file parameter, or not. * * @property useArray * @type {Boolean} */ useArray: true, /** * Additional headers to append to the request. * * @property requestHeaders * @type {Object} */ requestHeaders: {}, /** * Additional POST to data to be appended to the FormData object. * * @property requestPostData * @type {Object} */ requestPostData: {}, /** * List of valid extensions for uploading to the server. * * @property extensions * @type {Array} */ extensions: [], /** * @property statuses * @type {Object} */ statuses: { /** * List of HTTP status codes that denote a successful HTTP request. * * @property success * @type {Array} */ success: [/2.{2}/] } }; /** * @property requestProgress * @type {Object} */ $scope.requestProgress = { percent: 0, total: 0, loaded: 0 }; /** * @property listeners * @type {Object} */ $scope.listeners = { /** * @property files * @type {Array} */ files: [], /** * @property deferred * @type {$q.defer|null} */ deferred: null, /** * @property httpRequest * @type {XMLHttpRequest|null} */ httpRequest: null, /** * Invoked once everything has been uploaded. * * @method success * @return {void} */ success: function success() { this.httpRequest.onreadystatechange = function onReadyStateChange() { if (this.httpRequest.readyState === 4) { if ($scope.isValidHTTPStatus(this.httpRequest.status)) { $scope.$apply(function apply() { // Parse the response, and then emit the event passing along the response // and the uploaded files! var response = $scope.options.parserFn(this.httpRequest.responseText); $rootScope.$broadcast('$dropletSuccess', response, this.files); this.deferred.resolve(response, this.files); $scope.finishedUploading(); $angular.forEach(this.files, function forEach(model) { // Advance the status of the file to that of an uploaded file. model.setType($scope.FILE_TYPES.UPLOADED); }); }.bind(this)); return; } // Error was thrown instead. this.httpRequest.upload.onerror(); } }.bind(this); }, /** * Invoked when an error is thrown when uploading the files. * * @method error * @return {void} */ error: function error() { this.httpRequest.upload.onerror = function onError() { $scope.$apply(function apply() { $scope.finishedUploading(); $scope.isError = true; var response = $scope.options.parserFn(this.httpRequest.responseText); $rootScope.$broadcast('$dropletError', response); this.deferred.reject(response); }.bind(this)); }.bind(this); }, /** * Invoked each time there's a progress update on the files being uploaded. * * @method progress * @return {void} */ progress: function progress() { var requestLength = $scope.getRequestLength(this.files); this.httpRequest.upload.onprogress = function onProgress(event) { $scope.$apply(function apply() { if (event.lengthComputable) { // Update the progress object. $scope.requestProgress.percent = Math.round((event.loaded / requestLength) * 100); $scope.requestProgress.loaded = event.loaded; $scope.requestProgress.total = requestLength; } }); }; } }; /** * @method createModelBlueprint * @return {void} */ (function createModelBlueprint() { /** * @model DropletModel * @constructor */ $scope.DropletModel = function DropletModel() {}; /** * @property prototype * @type {Object} */ $scope.DropletModel.prototype = { /** * @method file * @param file {File} * @return {void} */ load: function load(file) { if (!(file instanceof $window.File) && !(file instanceof $window.Blob)) { $scope.throwException('Loaded files must be an instance of the "File" or "Blob" objects'); } this.file = file; this.date = new $window.Date(); this.mimeType = file.type; this.extension = $scope.getExtension(file); // File has been added! $rootScope.$broadcast('$dropletFileAdded', this); }, /** * @method deleteFile * @return {void} */ deleteFile: function deleteFile() { this.setType($scope.FILE_TYPES.DELETED); // File has been deleted! $rootScope.$broadcast('$dropletFileDeleted', this); }, /** * @method setType * @param type {Number} * @return {void} */ setType: function setType(type) { this.type = type; }, /** * @method isImage * @return {Boolean} */ isImage: function isImage() { return !!this.file.type.match(/^image\//i); } }; })(); /** * @method finishedUploading * @return {void} */ $scope.finishedUploading = function finishedUploading() { $scope.progress = { percent: 0, total: 0, loaded: 0 }; $scope.isUploading = false; }; /** * Utility method for iterating over files of a given type. * * @method forEachFile * @param type {Number} * @param callbackFn {Function} * @return {void} */ $scope.forEachFile = function forEachFile(type, callbackFn) { $angular.forEach($scope.filterFiles(type || $scope.FILE_TYPES.VALID), function forEach(model) { callbackFn(model); }); }; /** * @method addFile * @param file {File} * @param type {Number} * @return {Object} */ $scope.addFile = function addFile(file, type) { // If the developer didn't specify the type then we'll assume it's a valid file // that they're adding. type = type || $scope.FILE_TYPES.VALID; // Create the model and then register the file. var model = new $scope.DropletModel(); model.setType(type); model.load(file); $scope.files.push(model); return model; }; /** * @method filterFiles * @param type {Number} * @return {Array} */ $scope.filterFiles = function filterFiles(type) { return $scope.files.filter(function filter(file) { return type & file.type; }); }; /** * @method getExtension * @param file {File} * @return {String} */ $scope.getExtension = function getExtension(file) { var str, separator; if ( typeof file.name !== 'undefined' ) { str = file.name; separator = '.'; } else { str = file.type; separator = '/'; } if (str.indexOf(separator) === -1) { // Filename doesn't actually have an extension. return ''; } return str.split(separator).pop().trim().toLowerCase(); }; /** * @method traverseFiles * @param files {FileList} * @return {void} */ $scope.traverseFiles = function traverseFiles(files) { for (var index = 0, numFiles = files.length; index < numFiles; index++) { var file = files[index], extension = $scope.getExtension(file), type = $scope.FILE_TYPES.VALID; if (!$scope.isValidExtension(extension)) { // Invalid extension which we must reject! type = $scope.FILE_TYPES.INVALID; } // Finally we'll register the file using the type that has been deduced. $scope.addFile(file, type); } }; /** * @method uploadFiles * @return {$q.promise} */ $scope.uploadFiles = function uploadFiles() { // Reset... $scope.isError = false; var httpRequest = new $window.XMLHttpRequest(), formData = new $window.FormData(), queuedFiles = $scope.filterFiles($scope.FILE_TYPES.VALID), fileProperty = $scope.options.useArray ? 'file[]' : 'file', requestLength = $scope.getRequestLength(queuedFiles), deferred = $q.defer(); // Initiate the HTTP request. httpRequest.open('post', $scope.options.requestUrl, true); /** * @method appendCustomData * @return {void} */ (function appendCustomData() { if (!$scope.options.disableXFileSize) { // Setup the file size of the request. httpRequest.setRequestHeader('X-File-Size', requestLength); } // ...And any other additional HTTP request headers, and POST data. $scope.addRequestHeaders(httpRequest); $scope.addPostData(formData); })(); /** * @method attachEventListeners * @return {void} */ (function attachEventListeners() { // Define the files property so that each listener has the same interface. $scope.listeners.files = queuedFiles; $scope.listeners.deferred = deferred; $scope.listeners.httpRequest = httpRequest; // Configure the event listeners for the impending request. $scope.listeners.progress(); $scope.listeners.success(); $scope.listeners.error(); })(); // Iterate all of the valid files to append them to the previously created // `formData` object. $angular.forEach(queuedFiles, function forEach(model) { formData.append(fileProperty, model.file); }); // Voila... $scope.isUploading = true; httpRequest.send(formData); return deferred.promise; }; /** * Iterate over any additional headers added by the developer and append to the current * request being generated. * * @method addRequestHeaders * @param httpRequest {XMLHttpRequest} * @return {Array} */ $scope.addRequestHeaders = function addRequestHeaders(httpRequest) { for (var header in $scope.options.requestHeaders) { if ($scope.options.requestHeaders.hasOwnProperty(header)) { httpRequest.setRequestHeader(header, $scope.options.requestHeaders[header]); } } return Object.keys($scope.options.requestHeaders); }; /** * Iterate over any additional POST data that must be bundled with the request. * * @method addPostData * @param formData {FormData} * @return {Array} */ $scope.addPostData = function addPostData(formData) { for (var header in $scope.options.requestPostData) { if ($scope.options.requestPostData.hasOwnProperty(header)) { formData.append(header, $scope.options.requestPostData[header]); } } return Object.keys($scope.options.requestPostData); }; /** * Determine the size of the request based on the files preparing to be uploaded. * * @method getRequestLength * @param [files=[]] {Array} * @return {Number} */ $scope.getRequestLength = function getRequestLength(files) { var allFiles = files || $scope.filterFiles($scope.FILE_TYPES.VALID); // Iterate over all of the files to determine the size of all the specified files. return allFiles.reduce(function reduce(previousValue, currentModel) { return previousValue + currentModel.file.size; }, 0); }; /** * @method throwException * @param message {String} * @return {void} */ $scope.throwException = function throwException(message) { throw "ngDroplet: " + message + "."; }; /** * Responsible for setting up the interface that allows the developer to interact * with the directive from outside. * * @method setupDirectiveInterface * @return {void} */ (function setupDirectiveInterface() { /** * @property interface * @type {Object} */ $scope.interface = { /** * @constant FILE_TYPES * @type {Object} */ FILE_TYPES: $scope.FILE_TYPES, /** * @method uploadFiles * @return {void} */ uploadFiles: $scope.uploadFiles, /** * @property progress * @type {Object} */ progress: $scope.requestProgress, /** * @method useParser * @param parserFn {Function} * @return {void} */ useParser: function useParser(parserFn) { if (typeof parserFn !== 'function') { $scope.throwException('Parser function must be typeof "function"'); } $scope.options.parserFn = parserFn; }, /** * @method isUploading * @return {Boolean} */ isUploading: function isUploading() { return $scope.isUploading; }, /** * @method isError * @type {Boolean} */ isError: function isError() { return $scope.isError; }, /** * Determines if there are files ready and waiting to be uploaded. * * @method isReady * @return {Boolean} */ isReady: function isReady() { return !!$scope.filterFiles($scope.FILE_TYPES.VALID).length; }, /** * @method addFile * @param file {File} * @param type {Number} * @return {void} */ addFile: $scope.addFile, /** * @method traverseFiles * @param files {FileList} * @return {void} */ traverseFiles: $scope.traverseFiles, /** * @method disableXFileSize * @return {void} */ disableXFileSize: function disableXFileSize() { $scope.options.disableXFileSize = true; }, /** * @method useArray * @param value {Boolean} * @return {void} */ useArray: function useArray(value) { $scope.options.useArray = !!value; }, /** * @method setRequestUrl * @param url {String} * @return {void} */ setRequestUrl: function setRequestUrl(url) { $scope.options.requestUrl = url; }, /** * @method setRequestHeaders * @param headers {Object} * @return {void} */ setRequestHeaders: function setRequestHeaders(headers) { $scope.options.requestHeaders = headers; }, /** * @method setPostData * @param data {Object} * @return {void} */ setPostData: function setPostData(data) { $scope.options.requestPostData = data; }, /** * @method getFiles * @param type {Number} * @return {Array} */ getFiles: function getFiles(type) { if (type) { // Apply any necessary filters if a bitwise value has been supplied. return $scope.filterFiles(type); } // Otherwise we'll yield the entire set of files. return $scope.files; }, /** * @method allowedExtensions * @param extensions {Array} * @return {void} */ allowedExtensions: function allowedExtensions(extensions) { if (!$angular.isArray(extensions)) { // Developer didn't pass an array of extensions! $scope.throwException('Extensions must be an array'); } $scope.options.extensions = extensions; }, /** * @method defineHTTPSuccess * @param statuses {Array} * @return {void} */ defineHTTPSuccess: function defineHTTPSuccess(statuses) { if (!$angular.isArray(statuses)) { // Developer didn't pass an array of extensions! $scope.throwException('Status list must be an array'); } $scope.options.statuses.success = statuses; } }; $timeout(function timeout() { // Emit the event to notify any listening scopes that the interface has been attached // for communicating with the directive. $rootScope.$broadcast('$dropletReady', $scope.interface); }); })(); }], /** * @method link * @param scope {Object} * @param element {Object} * @return {void} */ link: function link(scope, element) { /** * @method _preventDefault * @param event {Object} * @return {void} * @private */ var _preventDefault = function _preventDefault(event) { event = scope.getEvent(event); // Remove all of the possible class names. element.removeClass('event-dragleave'); element.removeClass('event-dragenter'); element.removeClass('event-dragover'); element.removeClass('event-drop'); // ...And then add the current class name. element.addClass('event-' + event.type); event.preventDefault(); event.stopPropagation(); }; // Events that merely need their default behaviour quelling. element.bind('dragover dragenter dragleave', _preventDefault); // Bind to the "drop" event which will contain the items the user dropped // onto the element. element.bind('drop', function onDrop(event) { _preventDefault(event); scope.$apply(function apply() { event = scope.getEvent(event); scope.traverseFiles(event.dataTransfer.files); }); }); } } }]).directive('dropletPreview', ['$window', function DropletPreviewDirective($window) { return { /** * @property scope * @type {Object} */ scope: { model: '=ngModel' }, /** * @property restrict * @type {String} */ restrict: 'EA', /** * @property replace * @type {Boolean} */ replace: true, /** * @property template * @type {String} */ template: '<img ng-show="model.isImage()" style="background-image: url({{imageData}})" class="droplet-preview" />', /** * @method link * @param scope {Object} * @return {void} */ link: function link(scope) { /** * @property imageData * @type {String} */ scope.imageData = ''; // Instantiate the file reader for reading the image data. var fileReader = new $window.FileReader(); /** * @method onload * @return {void} */ fileReader.onload = function onload(event) { scope.$apply(function apply() { // Voila! Define the image data. scope.imageData = event.target.result; }); }; if (scope.model.isImage()) { // Initialise the loading of the image into the file reader. fileReader.readAsDataURL(scope.model.file); } } } }]); /** * @method createInputElements * @return {void} */ (function createInputElements() { /** * @method createDirective * @return {void} */ var createDirective = function createDirective(name, htmlMarkup) { module.directive(name, function DropletUploadSingleDirective() { return { /** * @property restrict * @type {String} */ restrict: 'EA', /** * @property require * @type {String} */ require: 'ngModel', /** * @property replace * @type {Boolean} */ replace: true, /** * @property processFileList * @type {String} */ template: htmlMarkup, /** * @property scope * @type {Object} */ scope: { interface: '=ngModel' }, /** * @method link * @param scope {Object} * @param element {Object} * @return {void} */ link: function link(scope, element) { // Subscribe to the "change" event. element.bind('change', function onChange() { scope.$apply(function apply() { scope.interface.traverseFiles(element[0].files); }); }); // Reset the `value` of the element each time a user clicks. element.bind('click', function onClick() { this.value = null; }); } } }); }; // Create the actual input elements. createDirective('dropletUploadSingle', '<input class="droplet-upload droplet-single" type="file" />'); createDirective('dropletUploadMultiple', '<input class="droplet-upload droplet-multiple" type="file" multiple="multiple" />'); })(); })(window.angular);
import "../interpolate/ease"; import "../selection/each"; import "transition"; d3_transitionPrototype.ease = function(value) { var id = this.id, ns = this.namespace; if (arguments.length < 1) return this.node()[ns][id].ease; if (typeof value !== "function") value = d3.ease.apply(d3, arguments); return d3_selection_each(this, function(node) { node[ns][id].ease = value; }); };
/** * Disallows an extra comma following the final element of an array or object literal. * * Type: `Boolean` * * Value: `true` * * JSHint: [`es3`](http://jshint.com/docs/options/#es3) * * #### Example * * ```js * "disallowTrailingComma": true * ``` * * ##### Valid * * ```js * var foo = [1, 2, 3]; * var bar = {a: "a", b: "b"} * const [1, 2, 3]; * const {a: "a", b: "b"} * ``` * * ##### Invalid * * ```js * var foo = [1, 2, 3, ]; * var bar = {a: "a", b: "b", } * ``` */ var assert = require('assert'); module.exports = function() {}; module.exports.prototype = { configure: function(options) { assert( options === true, this.getOptionName() + ' option requires a true value or should be removed' ); }, getOptionName: function() { return 'disallowTrailingComma'; }, check: function(file, errors) { file.iterateNodesByType([ 'ObjectExpression', 'ArrayExpression', 'ObjectPattern', 'ArrayPattern' ], function(node) { var closingToken = file.getLastNodeToken(node); var comma = closingToken.getPreviousCodeToken(); if (comma.type === 'Punctuator' && comma.value === ',') { errors.add( 'Extra comma following the final element of an array or object literal', comma ); } }); }, _fix: function(file, error) { error.element.remove(); } };
var _ref; console.log((_ref = [123], x = _ref[0], _ref));
'use strict'; /* jshint -W030 */ var chai = require('chai') , expect = chai.expect , Support = require(__dirname + '/support') , dialect = Support.getTestDialect() , Promise = require(__dirname + '/../../lib/promise') , Transaction = require(__dirname + '/../../lib/transaction') , sinon = require('sinon') , current = Support.sequelize; if (current.dialect.supports.transactions) { describe(Support.getTestDialectTeaser('Transaction'), function() { this.timeout(5000); describe('constructor', function() { it('stores options', function() { var transaction = new Transaction(this.sequelize); expect(transaction.options).to.be.an.instanceOf(Object); }); it('generates an identifier', function() { var transaction = new Transaction(this.sequelize); expect(transaction.id).to.exist; }); }); describe('commit', function() { it('is a commit method available', function() { expect(Transaction).to.respondTo('commit'); }); }); describe('rollback', function() { it('is a rollback method available', function() { expect(Transaction).to.respondTo('rollback'); }); }); describe('autoCallback', function() { it('supports automatically committing', function() { return this.sequelize.transaction(function() { return Promise.resolve(); }); }); it('supports automatically rolling back with a thrown error', function() { var t; return (expect(this.sequelize.transaction(function(transaction) { t = transaction; throw new Error('Yolo'); })).to.eventually.be.rejected).then(function() { expect(t.finished).to.be.equal('rollback'); }); }); it('supports automatically rolling back with a rejection', function() { var t; return (expect(this.sequelize.transaction(function(transaction) { t = transaction; return Promise.reject('Swag'); })).to.eventually.be.rejected).then(function() { expect(t.finished).to.be.equal('rollback'); }); }); it('errors when no promise chain is returned', function() { var t; return (expect(this.sequelize.transaction(function(transaction) { t = transaction; })).to.eventually.be.rejected).then(function() { expect(t.finished).to.be.equal('rollback'); }); }); if (dialect === 'postgres' || dialect === 'mssql') { it('do not rollback if already committed', function() { var SumSumSum = this.sequelize.define('transaction', { value: { type: Support.Sequelize.DECIMAL(10, 3), field: 'value' } }) , transTest = function (val) { return self.sequelize.transaction({isolationLevel: 'SERIALIZABLE'}, function(t) { return SumSumSum.sum('value', {transaction: t}).then(function (balance) { return SumSumSum.create({value: -val}, {transaction: t}); }); }); } , self = this; // Attention: this test is a bit racy. If you find a nicer way to test this: go ahead return SumSumSum.sync({force: true}).then(function () { return (expect(Promise.join(transTest(80), transTest(80), transTest(80))).to.eventually.be.rejectedWith('could not serialize access due to read/write dependencies among transactions')); }).delay(100).then(function() { if (self.sequelize.test.$runningQueries !== 0) { return self.sequelize.Promise.delay(200); } return void 0; }).then(function() { if (self.sequelize.test.$runningQueries !== 0) { return self.sequelize.Promise.delay(500); } }); }); } }); it('does not allow queries after commit', function() { var self = this; return expect( this.sequelize.transaction().then(function(t) { return self.sequelize.query('SELECT 1+1', {transaction: t, raw: true}).then(function() { return t.commit(); }).then(function() { return self.sequelize.query('SELECT 1+1', {transaction: t, raw: true}); }); }) ).to.eventually.be.rejected; }); it('does not allow queries after rollback', function() { var self = this; return expect( this.sequelize.transaction().then(function(t) { return self.sequelize.query('SELECT 1+1', {transaction: t, raw: true}).then(function() { return t.commit(); }).then(function() { return self.sequelize.query('SELECT 1+1', {transaction: t, raw: true}); }); }) ).to.eventually.be.rejected; }); if (dialect === 'sqlite'){ it('provides persistent transactions', function () { var sequelize = new Support.Sequelize('database', 'username', 'password', {dialect: 'sqlite'}) , User = sequelize.define('user', { username: Support.Sequelize.STRING, awesome: Support.Sequelize.BOOLEAN }) , persistentTransaction; return sequelize.transaction().then(function(t) { return sequelize.sync({ transaction:t }).then(function( ) { return t; }); }).then(function(t) { return User.create({}, {transaction:t}).then(function( ) { return t.commit(); }); }).then(function() { return sequelize.transaction().then(function(t) { persistentTransaction = t; }); }).then(function() { return User.findAll({transaction: persistentTransaction}).then(function(users) { expect(users.length).to.equal(1); return persistentTransaction.commit(); }); }); }); } if (current.dialect.supports.lock) { describe('row locking', function () { it('supports for update', function() { var User = this.sequelize.define('user', { username: Support.Sequelize.STRING, awesome: Support.Sequelize.BOOLEAN }) , self = this , t1Spy = sinon.spy() , t2Spy = sinon.spy(); return this.sequelize.sync({ force: true }).then(function() { return User.create({ username: 'jan'}); }).then(function() { return self.sequelize.transaction().then(function(t1) { return User.find({ where: { username: 'jan' }, lock: t1.LOCK.UPDATE, transaction: t1 }).then(function(t1Jan) { return self.sequelize.transaction({ isolationLevel: Transaction.ISOLATION_LEVELS.READ_COMMITTED }).then(function(t2) { return Promise.join( User.find({ where: { username: 'jan' }, lock: t2.LOCK.UPDATE, transaction: t2 }).then(function() { t2Spy(); return t2.commit().then(function() { expect(t2Spy).to.have.been.calledAfter(t1Spy); // Find should not succeed before t1 has comitted }); }), t1Jan.updateAttributes({ awesome: true }, { transaction: t1 }).then(function() { t1Spy(); return Promise.delay(2000).then(function () { return t1.commit(); }); }) ); }); }); }); }); }); it('fail locking with outer joins', function() { var User = this.sequelize.define('User', { username: Support.Sequelize.STRING }) , Task = this.sequelize.define('Task', { title: Support.Sequelize.STRING, active: Support.Sequelize.BOOLEAN }) , self = this; User.belongsToMany(Task, { through: 'UserTasks' }); Task.belongsToMany(User, { through: 'UserTasks' }); return this.sequelize.sync({ force: true }).then(function() { return Promise.join( User.create({ username: 'John'}), Task.create({ title: 'Get rich', active: false}), function (john, task1) { return john.setTasks([task1]); }).then(function() { return self.sequelize.transaction(function(t1) { if (current.dialect.supports.lockOuterJoinFailure) { return expect(User.find({ where: { username: 'John' }, include: [Task], lock: t1.LOCK.UPDATE, transaction: t1 })).to.be.rejectedWith('FOR UPDATE cannot be applied to the nullable side of an outer join'); } else { return User.find({ where: { username: 'John' }, include: [Task], lock: t1.LOCK.UPDATE, transaction: t1 }); } }); }); }); }); if (current.dialect.supports.lockOf) { it('supports for update of table', function() { var User = this.sequelize.define('User', { username: Support.Sequelize.STRING }, { tableName: 'Person' }) , Task = this.sequelize.define('Task', { title: Support.Sequelize.STRING, active: Support.Sequelize.BOOLEAN }) , self = this; User.belongsToMany(Task, { through: 'UserTasks' }); Task.belongsToMany(User, { through: 'UserTasks' }); return this.sequelize.sync({ force: true }).then(function() { return Promise.join( User.create({ username: 'John'}), Task.create({ title: 'Get rich', active: false}), Task.create({ title: 'Die trying', active: false}), function (john, task1) { return john.setTasks([task1]); }).then(function() { return self.sequelize.transaction(function(t1) { return User.find({ where: { username: 'John' }, include: [Task], lock: { level: t1.LOCK.UPDATE, of: User }, transaction: t1 }).then(function(t1John) { // should not be blocked by the lock of the other transaction return self.sequelize.transaction(function(t2) { return Task.update({ active: true }, { where: { active: false }, transaction: t2 }); }).then(function() { return t1John.save({ transaction: t1 }); }); }); }); }); }); }); } if (current.dialect.supports.lockKey) { it('supports for key share', function() { var User = this.sequelize.define('user', { username: Support.Sequelize.STRING, awesome: Support.Sequelize.BOOLEAN }) , self = this , t1Spy = sinon.spy() , t2Spy = sinon.spy(); return this.sequelize.sync({ force: true }).then(function() { return User.create({ username: 'jan'}); }).then(function() { return self.sequelize.transaction().then(function(t1) { return User.find({ where: { username: 'jan' }, lock: t1.LOCK.NO_KEY_UPDATE, transaction: t1 }).then(function(t1Jan) { return self.sequelize.transaction().then(function(t2) { return Promise.join( User.find({ where: { username: 'jan' }, lock: t2.LOCK.KEY_SHARE, transaction: t2 }).then(function() { t2Spy(); return t2.commit(); }), t1Jan.update({ awesome: true }, { transaction: t1 }).then(function() { return Promise.delay(2000).then(function () { t1Spy(); expect(t1Spy).to.have.been.calledAfter(t2Spy); return t1.commit(); }); }) ); }); }); }); }); }); } it('supports for share', function() { var User = this.sequelize.define('user', { username: Support.Sequelize.STRING, awesome: Support.Sequelize.BOOLEAN }) , self = this , t1Spy = sinon.spy() , t2FindSpy = sinon.spy() , t2UpdateSpy = sinon.spy(); return this.sequelize.sync({ force: true }).then(function() { return User.create({ username: 'jan'}); }).then(function() { return self.sequelize.transaction().then(function(t1) { return User.find({ where: { username: 'jan' }, lock: t1.LOCK.SHARE, transaction: t1 }).then(function(t1Jan) { return self.sequelize.transaction({ isolationLevel: Transaction.ISOLATION_LEVELS.READ_COMMITTED }).then(function(t2) { return Promise.join( User.find({ where: { username: 'jan' }, transaction: t2 }).then(function(t2Jan) { t2FindSpy(); return t2Jan.updateAttributes({ awesome: false }, { transaction: t2 }).then(function() { t2UpdateSpy(); return t2.commit().then(function() { expect(t2FindSpy).to.have.been.calledBefore(t1Spy); // The find call should have returned expect(t2UpdateSpy).to.have.been.calledAfter(t1Spy); // But the update call should not happen before the first transaction has committed }); }); }), t1Jan.updateAttributes({ awesome: true }, { transaction: t1 }).then(function() { return Promise.delay(2000).then(function () { t1Spy(); return t1.commit(); }); }) ); }); }); }); }); }); }); } }); }
//jshint node:true, eqnull:true /*global describe, it, before*/ 'use strict'; var esformatter = require('esformatter'); var fs = require('fs'); var path = require('path'); var plugin = require('../'); var disparity = require('disparity'); var basePath = path.join(__dirname, 'compare'); esformatter.register(plugin); formatAndCompare('input.js', 'output.js'); function formatAndCompare(inputFile, expectedFile) { var input = getFile(inputFile); var expected = getFile(expectedFile); var output = esformatter.format(input); if (output !== expected) { process.stderr.write(disparity.chars(output, expected, { paths: ['actual', 'expected'] })); process.exit(1); } else { console.error('ok %s', inputFile); } } function getFile(name) { return fs.readFileSync(path.join(basePath, name)).toString(); }
'use strict'; module.exports = { set: function (v) { this.setProperty('-webkit-line-align', v); }, get: function () { return this.getPropertyValue('-webkit-line-align'); }, enumerable: true };
hljs.registerLanguage("dockerfile",function(e){return{aliases:["docker"],cI:!0,k:"from maintainer expose env arg user onbuild stopsignal",c:[e.HCM,e.ASM,e.QSM,e.NM,{bK:"run cmd entrypoint volume add copy workdir label healthcheck shell",starts:{e:/[^\\]$/,sL:"bash"}}],i:"</"}});
/** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactLink * @typechecks static-only */ "use strict"; /** * ReactLink encapsulates a common pattern in which a component wants to modify * a prop received from its parent. ReactLink allows the parent to pass down a * value coupled with a callback that, when invoked, expresses an intent to * modify that value. For example: * * React.createClass({ * getInitialState: function() { * return {value: ''}; * }, * render: function() { * var valueLink = new ReactLink(this.state.value, this._handleValueChange); * return <input valueLink={valueLink} />; * }, * this._handleValueChange: function(newValue) { * this.setState({value: newValue}); * } * }); * * We have provided some sugary mixins to make the creation and * consumption of ReactLink easier; see LinkedValueUtils and LinkedStateMixin. */ var React = require('React'); /** * @param {*} value current value of the link * @param {function} requestChange callback to request a change */ function ReactLink(value, requestChange) { this.value = value; this.requestChange = requestChange; } /** * Creates a PropType that enforces the ReactLink API and optionally checks the * type of the value being passed inside the link. Example: * * MyComponent.propTypes = { * tabIndexLink: ReactLink.PropTypes.link(React.PropTypes.number) * } */ function createLinkTypeChecker(linkType) { var shapes = { value: typeof linkType === 'undefined' ? React.PropTypes.any.isRequired : linkType.isRequired, requestChange: React.PropTypes.func.isRequired }; return React.PropTypes.shape(shapes); } ReactLink.PropTypes = { link: createLinkTypeChecker }; module.exports = ReactLink;
/* Project: angular-gantt v1.2.13 - Gantt chart component for AngularJS Authors: Marco Schweighauser, Rémi Alvergnat License: MIT Homepage: https://www.angular-gantt.com Github: https://github.com/angular-gantt/angular-gantt.git */ !function(){"use strict";angular.module("gantt.resizeSensor",["gantt"]).directive("ganttResizeSensor",[function(){return{restrict:"E",require:"^gantt",scope:{enabled:"=?"},link:function(a,b,c,d){function e(){var a=b.parent().parent().parent()[0].querySelectorAll("div.gantt")[0];return new ResizeSensor(a,function(){d.gantt.$scope.ganttElementWidth=a.clientWidth,d.gantt.$scope.$apply()})}var f=d.gantt.api;if(a.options&&"object"==typeof a.options.progress)for(var g in a.options.progress)a[g]=a.options[g];void 0===a.enabled&&(a.enabled=!0);var h,i=!1;f.core.on.rendered(a,function(){i=!0,void 0!==h&&h.detach(),a.enabled&&(ElementQueries.update(),h=e())}),a.$watch("enabled",function(a){i&&(a&&void 0===h?(ElementQueries.update(),h=e()):a||void 0===h||(h.detach(),h=void 0))})}}}])}(),angular.module("gantt.resizeSensor.templates",[]).run(["$templateCache",function(a){}]); //# sourceMappingURL=angular-gantt-resizeSensor-plugin.min.js.map
CKEDITOR.plugins.setLang("autoembed","zh-cn",{embeddingInProgress:"正在尝试嵌入粘贴的 URL 里的媒体内容...",embeddingFailed:"此 URL 无法自动嵌入媒体内容。"});
/* * ng-tasty * https://github.com/Zizzamia/ng-tasty * Version: 0.2.7 - 2014-09-08 * License: MIT */ angular.module("ngTasty", ["ngTasty.tpls", "ngTasty.filter","ngTasty.service","ngTasty.table"]); angular.module("ngTasty.tpls", ["template/table/head.html","template/table/pagination.html"]); /** * @ngdoc * @name * */ angular.module('ngTasty.filter', [ 'ngTasty.filter.cleanFieldName', 'ngTasty.filter.filterInt', 'ngTasty.filter.range' ]); /** * @ngdoc filter * @name cleanFieldName * * @description * Calling toString will return the ... * * @example ng-bind="key | cleanFieldName" * */ angular.module('ngTasty.filter.cleanFieldName', []) .filter('cleanFieldName', function() { return function (input) { return input.replace(/[^a-zA-Z0-9-]+/g, '-').toLowerCase(); }; }); /** * @ngdoc filter * @name filterInt * @kind function * */ angular.module('ngTasty.filter.filterInt', []) .filter('filterInt', function() { return function (input) { if(/^(\-|\+)?([0-9]+|Infinity)$/.test(input)) { return Number(input); } return NaN; }; }); /** * @ngdoc filter * @name range * @kind function * * @description * Create a list containing arithmetic progressions. The arguments must * be plain integers. If the step argument is omitted, it defaults to 1. * If the start argument is omitted, it defaults to 0. * * @example ng-repeat="n in [] | range:1:30" */ angular.module('ngTasty.filter.range', []) .filter('range', ["$filter", function($filter) { return function(input, start, stop, step) { start = $filter('filterInt')(start); stop = $filter('filterInt')(stop); step = $filter('filterInt')(step); if (isNaN(start)) { start = 0; } if (isNaN(stop)) { stop = start; start = 0; } if (isNaN(step)) { step = 1; } if ((step > 0 && start >= stop) || (step < 0 && start <= stop)){ return []; } for (var i = start; step > 0 ? i < stop : i > stop; i += step){ input.push(i); } return input; }; }]); /** * @ngdoc * @name * */ angular.module('ngTasty.service', [ 'ngTasty.service.tastyUtil', 'ngTasty.service.debounce', 'ngTasty.service.setProperty', 'ngTasty.service.joinObjects' ]); /** * @ngdoc * @name * */ angular.module('ngTasty.service.tastyUtil', [ 'ngTasty.service.debounce', 'ngTasty.service.setProperty', 'ngTasty.service.joinObjects' ]) .factory('tastyUtil', ["debounce", "setProperty", "joinObjects", function(debounce, setProperty, joinObjects) { return { 'debounce': debounce, 'setProperty': setProperty, 'joinObjects': joinObjects }; }]); /** * @ngdoc * @name * */ angular.module('ngTasty.service.debounce', []) .factory('debounce', ["$timeout", function($timeout) { return function(func, wait, immediate) { var timeout; return function() { var context = this, args = arguments; $timeout.cancel(timeout); timeout = $timeout(function() { timeout = null; func.apply(context, args); }, wait); }; }; }]); /** * @ngdoc * @name * */ angular.module('ngTasty.service.setProperty', []) .factory('setProperty', function() { return function(objOne, objTwo, attrname) { if (typeof objTwo[attrname] !== 'undefined' && objTwo[attrname] !== null) { objOne[attrname] = objTwo[attrname]; } return objOne; }; }); /** * @ngdoc * @name * */ angular.module('ngTasty.service.joinObjects', []) .factory('joinObjects', ["setProperty", function(setProperty) { return function(objOne, objTwo) { for (var attrname in objTwo) { setProperty(objOne, objTwo, attrname); } return objOne; }; }]); /** * @ngdoc directive * @name tastyTable * * @example <table tasty-table> <tbody></tbody> </table> * */ angular.module('ngTasty.table', [ 'ngTasty.filter.cleanFieldName', 'ngTasty.filter.range', 'ngTasty.service.tastyUtil' ]) .constant('tableConfig', { query: { 'page': 'page', 'count': 'count', 'sortBy': 'sort-by', 'sortOrder': 'sort-order', }, resource: undefined, resourceCallback: undefined, listItemsPerPage: [5, 25, 50, 100], itemsPerPage: 5 }) .controller('TableController', ["$scope", "$attrs", "$timeout", "$filter", "tableConfig", "tastyUtil", function($scope, $attrs, $timeout, $filter, tableConfig, tastyUtil) { 'use strict'; this.$scope = $scope; // Default configs $scope.query = tableConfig.query; $scope.resource = tableConfig.resource; $scope.resourceCallback = tableConfig.resourceCallback; // Defualt variables $scope.clientSide = true; $scope.url = ''; $scope.header = { 'columns': [] }; $scope.rows = []; $scope.params = {}; $scope.pagination = { 'count': 5, 'page': 1, 'pages': 1, 'size': 0 }; $scope.theadDirective = false; $scope.paginationDirective = false; /* Set custom configs * In the future you will have a way to change * these values by an isolate optional scope variable, * more info here https://github.com/angular/angular.js/issues/6404 */ if (angular.isDefined($attrs.query)) { $scope.query = $scope.$parent[$attrs.query]; } if (!angular.isDefined($attrs.resource) && !angular.isDefined($attrs.resourceCallback)) { throw 'AngularJS tastyTable directive: need the resource or resource-callback attribute'; } if (angular.isDefined($attrs.resource)) { $scope.resource = $scope.$parent[$attrs.resource]; if (!angular.isObject($scope.resource)) { throw 'AngularJS tastyTable directive: the resource ('+ $attrs.resource + ') it\'s not an object'; } else if (!$scope.resource.header && !$scope.resource.rows) { throw 'AngularJS tastyTable directive: the resource ('+ $attrs.resource + ') has the property header or rows undefined'; } } if (angular.isDefined($attrs.resourceCallback)) { $scope.resourceCallback = $scope.$parent[$attrs.resourceCallback]; if (!angular.isFunction($scope.resourceCallback)) { throw 'AngularJS tastyTable directive: the resource-callback ('+ $attrs.resourceCallback + ') it\'s not a function'; } $scope.clientSide = false; } // In TableController, by using `this` we build an API // for other directives to talk to this one. this.activate = function(directiveName) { $scope[directiveName + 'Directive'] = true; $scope.params[directiveName] = true; }; this.setParams = function(key, value) { $scope.params[key] = value; }; $scope.setDirectivesValues = function (resource) { var sortBy; if (!angular.isObject(resource)) { throw 'AngularJS tastyTable directive: the resource '+ 'it\'s not an object'; } else if (!resource.header && !resource.rows) { throw 'AngularJS tastyTable directive: the resource '+ 'has the property header or rows undefined'; } sortBy = resource.sortBy || $scope.params.sortBy; sortBy = sortBy || resource.header[0].key; $scope.header = { 'columns': resource.header, 'sortBy': sortBy, 'sortOrder': resource.sortOrder || $scope.params.sortOrder }; $scope.rows = resource.rows; $scope.pagination = resource.pagination || $scope.pagination; }; $scope.buildClientResource = function() { var fromRow, toRow, rowToShow, reverse, listSortBy; if ($scope.theadDirective) { reverse = $scope.header.sortOrder === 'asc' ? false : true; listSortBy = [function(item) { return item[$scope.header.sortBy]; }]; if ($scope.header.columns[0].key !== $scope.header.sortBy) { listSortBy.push(function(item) { return item[$scope.header.columns[0].key]; }); } $scope.rows = $filter('orderBy')($scope.rows, listSortBy, reverse); } if ($scope.paginationDirective) { $scope.pagination.page = $scope.params.page; $scope.pagination.count = $scope.params.count; $scope.pagination.size = $scope.rows.length; $scope.pagination.pages = Math.ceil($scope.rows.length / $scope.pagination.count); toRow = $scope.pagination.count * $scope.pagination.page; fromRow = toRow - $scope.pagination.count; if (fromRow >= 0 && toRow >= 0) { rowToShow = $scope.rows.slice(fromRow, toRow); $scope.rows = rowToShow; } } }; $scope.buildUrl = function(params, filters) { var urlQuery, value, url; urlQuery = {}; if ($scope.theadDirective) { urlQuery = tastyUtil.setProperty(urlQuery, params, 'sortBy'); urlQuery = tastyUtil.setProperty(urlQuery, params, 'sortOrder'); } if ($scope.paginationDirective) { urlQuery = tastyUtil.setProperty(urlQuery, params, 'page'); urlQuery = tastyUtil.setProperty(urlQuery, params, 'count'); } if ($attrs.filters) { urlQuery = tastyUtil.joinObjects(urlQuery, filters); } return Object.keys(urlQuery).map(function(key) { value = urlQuery[key]; if ($scope.query[key]) { key = $scope.query[key]; } return encodeURIComponent(key) + '=' + encodeURIComponent(value); }).join('&'); }; $scope.updateClientSideResource = tastyUtil.debounce(function() { $scope.setDirectivesValues($scope.resource); $scope.buildClientResource(); }, 100); $scope.updateServerSideResource = tastyUtil.debounce(function() { $scope.url = $scope.buildUrl($scope.params, $scope[$attrs.filters]); $scope.resourceCallback($scope.url, $scope.params).then(function (resource) { $scope.setDirectivesValues(resource); }); }, 100); $scope.initTable = function () { $scope.params['sortBy'] = undefined; $scope.params['sortOrder'] = 'asc'; $scope.params['page'] = 1; $scope.params['count'] = undefined; if ($scope.clientSide) { $scope.updateClientSideResource(); } else { $scope.updateServerSideResource(); } }; // AngularJs $watch callbacks if ($attrs.filters) { $scope.$watch($attrs.filters, function (newValue, oldValue){ if (newValue !== oldValue) { $scope.updateServerSideResource(); } }, true); } $scope.$watchCollection('params', function (newValue, oldValue){ if (newValue !== oldValue) { if ($scope.clientSide) { $scope.updateClientSideResource(); } else { $scope.updateServerSideResource(); } } }); if ($scope.resource) { $scope.$parent.$watch($attrs.resource, function (newValue, oldValue){ if (newValue !== oldValue) { $scope.resource = newValue; $scope.updateClientSideResource(); } }, true); } // Init table $scope.initTable(); }]) .directive('tastyTable', function(){ return { restrict: 'A', scope: true, controller: 'TableController' }; }) /** * @ngdoc directive * @name tastyThead * * @example <table tasty-table> <thead table-head></thead> <tbody></tbody> </table> * */ .directive('tastyThead', ["$filter", function($filter) { return { restrict: 'AE', require: '^tastyTable', scope: { 'notSortBy': '=' }, templateUrl: 'template/table/head.html', link: function (scope, element, attrs, tastyTable) { 'use strict'; // Thead it's called tastyTable.activate('thead'); scope.columns = []; scope.setColumns = function () { var lenHeader, width, i, active, sortable, sort; scope.columns = []; lenHeader = scope.header.columns.length; scope.header.columns.forEach(function (column, index) { width = parseFloat((100 / lenHeader).toFixed(2)); sortable = true; active = false; if (scope.notSortBy) { sortable = scope.notSortBy.indexOf(column.key) < 0; } if (column.key === scope.header.sortBy || '-' + column.key === scope.header.sortBy) { active = true; } sort = $filter('cleanFieldName')(column.key); scope.columns.push({ 'key': column.key, 'name': column.name, 'active': active, 'sortable': sortable, 'width': { 'width': width + '%' }, 'isSortUp': scope.header.sortBy === '-' + sort, 'isSortDown': scope.header.sortBy === sort }); }); if (scope.header.sortOrder === 'dsc' && scope.header.sortBy[0] !== '-') { scope.header.sortBy = '-' + scope.header.sortBy; } }; scope.sortBy = function (column) { if (scope.notSortBy && scope.notSortBy.indexOf(column.key) >= 0) { return false; } var columnName; columnName = $filter('cleanFieldName')(column.key); if (scope.header.sortBy == columnName) { scope.header.sortBy = '-' + columnName; tastyTable.setParams('sortOrder', 'dsc'); } else { scope.header.sortBy = columnName; tastyTable.setParams('sortOrder', 'asc'); } tastyTable.setParams('sortBy', column.key); }; scope.classToShow = function (column) { var listClassToShow = []; if (column.sortable) { listClassToShow.push('sortable'); } if (column.active) { listClassToShow.push('active'); } return listClassToShow; }; tastyTable.$scope.$watchCollection('header', function (newValue, oldValue){ if (newValue && (newValue !== oldValue)) { scope.header = newValue; scope.setColumns(); } }); } }; }]) /** * @ngdoc directive * @name tastyPagination * * @example <div tasty-table> <table> ... </table> <div table-pagination></div> </div> * */ .controller('TablePaginationController', ["$scope", "$attrs", "tableConfig", function($scope, $attrs, tableConfig) { if (angular.isDefined($attrs.itemsPerPage)) { $scope.itemsPerPage = $scope.$parent[$attrs.itemsPerPage]; } if (angular.isDefined($attrs.listItemsPerPage)) { $scope.listItemsPerPage = $scope.$parent[$attrs.listItemsPerPage]; } // Default configs $scope.itemsPerPage = $scope.itemsPerPage || tableConfig.itemsPerPage; $scope.listItemsPerPage = $scope.listItemsPerPage || tableConfig.listItemsPerPage; }]) .directive('tastyPagination', ["$filter", function($filter) { return { restrict: 'AE', require: '^tastyTable', scope: {}, templateUrl: 'template/table/pagination.html', controller: 'TablePaginationController', link: function (scope, element, attrs, tastyTable) { 'use strict'; var getPage, setCount, setPaginationRange, setPreviousRange, setRemainingRange, setPaginationRanges; // Pagination it's called tastyTable.activate('pagination'); // Internal variable scope.pagination = {}; scope.pagMinRange = 1; scope.pagMaxRange = 1; getPage = function (numPage) { tastyTable.setParams('page', numPage); }; setCount = function(count) { var maxItems, page; //scope.pagination.count = count; maxItems = count * scope.pagination.page; if (maxItems > scope.pagination.size) { page = Math.ceil(scope.pagination.size / count); tastyTable.setParams('page', page); } tastyTable.setParams('count', count); }; setPaginationRange = function () { var currentPage, totalPages; currentPage = scope.pagination.page; if (currentPage > scope.pagination.pages) { currentPage = scope.pagination.pages; } scope.pagMinRange = (currentPage - 2) > 0 ? (currentPage - 2) : 1; scope.pagMaxRange = (currentPage + 2); scope.pagination.page = currentPage; setPaginationRanges(); }; setPreviousRange = function () { if (scope.pagHideMinRange === true || scope.pagMinRange < 1) { return false; } scope.pagMaxRange = scope.pagMinRange; scope.pagMinRange = scope.pagMaxRange - scope.itemsPerPage; setPaginationRanges(); }; setRemainingRange = function () { if (scope.pagHideMaxRange === true || scope.pagMaxRange > scope.pagination.pages) { return false; } scope.pagMinRange = scope.pagMaxRange; scope.pagMaxRange = scope.pagMinRange + scope.itemsPerPage; if (scope.pagMaxRange > scope.pagination.pages) { scope.pagMaxRange = scope.pagination.pages; } scope.pagMinRange = scope.pagMaxRange - scope.itemsPerPage; setPaginationRanges(); }; setPaginationRanges = function () { scope.pagMinRange = scope.pagMinRange > 0 ? scope.pagMinRange : 1; scope.pagMaxRange = scope.pagMinRange + 5; if (scope.pagMaxRange > scope.pagination.pages) { scope.pagMaxRange = scope.pagination.pages + 1; } scope.pagHideMinRange = scope.pagMinRange <= 1; scope.pagHideMaxRange = scope.pagMaxRange >= scope.pagination.pages; scope.classPageMinRange = scope.pagHideMinRange ? 'disabled' : ''; scope.classPageMaxRange = scope.pagHideMaxRange ? 'disabled' : ''; for (var i = 2; i < scope.listItemsPerPage.length; i++) { if (scope.pagination.size < scope.listItemsPerPage[i]) { scope.listItemsPerPageShow = scope.listItemsPerPage.slice(0, i); break; } } scope.rangePage = $filter('range')([], scope.pagMinRange, scope.pagMaxRange); }; scope.classPaginationCount = function (count) { if (count == scope.pagination.count) { return 'active'; } return ''; }; scope.classNumPage = function (numPage) { if (numPage == scope.pagination.page) { return 'active'; } return false; }; scope.page = { 'get': getPage, 'setCount': setCount, 'previous': setPreviousRange, 'remaining': setRemainingRange }; tastyTable.$scope.$watchCollection('pagination', function (newValue, oldValue){ if (newValue && (newValue !== oldValue)) { scope.pagination = newValue; setPaginationRange(); } }); // Init Pagination scope.page.setCount(scope.itemsPerPage); } }; }]); angular.module('template/table/head.html', []).run(['$templateCache', function($templateCache) { $templateCache.put('template/table/head.html', '<tr>\n' + ' <th ng-repeat="column in columns track by $index" \n' + ' ng-class="classToShow(column)"\n' + ' ng-style="column.width" ng-click="sortBy(column)">\n' + ' <span ng-bind="column.name"></span>\n' + ' <span ng-if="column.isSortUp" class="fa fa-sort-up"></span>\n' + ' <span ng-if="column.isSortDown" class="fa fa-sort-down"></span>\n' + ' </th> \n' + '</tr>'); }]); angular.module('template/table/pagination.html', []).run(['$templateCache', function($templateCache) { $templateCache.put('template/table/pagination.html', '<div class="row">\n' + ' <div class="col-xs-3 text-left">\n' + ' <div class="btn-group">\n' + ' <button type="button" class="btn btn-default" \n' + ' ng-repeat="count in listItemsPerPageShow" \n' + ' ng-class="classPaginationCount(count)" \n' + ' ng-click="page.setCount(count)" ng-bind="count"></button>\n' + ' </div>\n' + ' </div>\n' + ' <div class="col-xs-6 text-center">\n' + ' <ul class="pagination">\n' + ' <li ng-class="classPageMinRange">\n' + ' <span ng-click="page.previous()">&laquo;</span>\n' + ' </li>\n' + ' <li ng-repeat="numPage in rangePage" ng-class="classNumPage(numPage)">\n' + ' <span ng-click="page.get(numPage)">\n' + ' <span ng-bind="numPage"></span>\n' + ' <span class="sr-only" ng-if="classNumPage(numPage)">(current)</span>\n' + ' </span>\n' + ' </li>\n' + ' <li ng-class="classPageMaxRange">\n' + ' <span ng-click="page.remaining()">&raquo;</span>\n' + ' </li>\n' + ' </ul>\n' + ' </div>\n' + ' <div class="col-xs-3 text-right">\n' + ' <p>Page <span ng-bind="pagination.page"></span> \n' + ' of <span ng-bind="pagination.pages"></span>,\n' + ' of <span ng-bind="pagination.size"></span> entries</p>\n' + ' </div>\n' + '</div>'); }]);
angular.module('templates-files_object_default_options', ['../test/fixtures/one.tpl.html']); angular.module("../test/fixtures/one.tpl.html", []).run(["$templateCache", function($templateCache) { $templateCache.put("../test/fixtures/one.tpl.html", "1 2 3"); }]);
/* * JCF directive for basic AngularJS 1.x integration */ angular.module("jcf",[]).directive("jcf",function(){return{restrict:"A",link:function(c,n,e){jcf.replace(n),c.$watch(e.ngModel,function(c){jcf.refresh(n)}),c.$on("$destroy",function(){jcf.destroy(n)})}}});
'use strict'; angular.module("ngLocale", [], ["$provide", function($provide) { var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; function getDecimals(n) { n = n + ''; var i = n.indexOf('.'); return (i == -1) ? 0 : n.length - i - 1; } function getVF(n, opt_precision) { var v = opt_precision; if (undefined === v) { v = Math.min(getDecimals(n), 3); } var base = Math.pow(10, v); var f = ((n * base) | 0) % base; return {v: v, f: f}; } function getWT(v, f) { if (f === 0) { return {w: 0, t: 0}; } while ((f % 10) === 0) { f /= 10; v--; } return {w: v, t: f}; } $provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": [ "AM", "PM" ], "DAY": [ "s\u00f8ndag", "mandag", "tirsdag", "onsdag", "torsdag", "fredag", "l\u00f8rdag" ], "MONTH": [ "januar", "februar", "marts", "april", "maj", "juni", "juli", "august", "september", "oktober", "november", "december" ], "SHORTDAY": [ "s\u00f8n.", "man.", "tir.", "ons.", "tor.", "fre.", "l\u00f8r." ], "SHORTMONTH": [ "jan.", "feb.", "mar.", "apr.", "maj", "jun.", "jul.", "aug.", "sep.", "okt.", "nov.", "dec." ], "fullDate": "EEEE 'den' d. MMMM y", "longDate": "d. MMM y", "medium": "dd/MM/y HH.mm.ss", "mediumDate": "dd/MM/y", "mediumTime": "HH.mm.ss", "short": "dd/MM/yy HH.mm", "shortDate": "dd/MM/yy", "shortTime": "HH.mm" }, "NUMBER_FORMATS": { "CURRENCY_SYM": "kr", "DECIMAL_SEP": ",", "GROUP_SEP": ".", "PATTERNS": [ { "gSize": 3, "lgSize": 3, "macFrac": 0, "maxFrac": 3, "minFrac": 0, "minInt": 1, "negPre": "-", "negSuf": "", "posPre": "", "posSuf": "" }, { "gSize": 3, "lgSize": 3, "macFrac": 0, "maxFrac": 2, "minFrac": 2, "minInt": 1, "negPre": "-", "negSuf": "\u00a0\u00a4", "posPre": "", "posSuf": "\u00a0\u00a4" } ] }, "id": "da-gl", "pluralCat": function (n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); var wt = getWT(vf.v, vf.f); if (n == 1 || wt.t != 0 && (i == 0 || i == 1)) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;} }); }]);
'use strict'; /** * Module dependencies. */ var _ = require('lodash'), chalk = require('chalk'), glob = require('glob'), fs = require('fs'), path = require('path'); /** * Get files by glob patterns */ var getGlobbedPaths = function (globPatterns, excludes) { // URL paths regex var urlRegex = new RegExp('^(?:[a-z]+:)?\/\/', 'i'); // The output array var output = []; // If glob pattern is array so we use each pattern in a recursive way, otherwise we use glob if (_.isArray(globPatterns)) { globPatterns.forEach(function (globPattern) { output = _.union(output, getGlobbedPaths(globPattern, excludes)); }); } else if (_.isString(globPatterns)) { if (urlRegex.test(globPatterns)) { output.push(globPatterns); } else { var files = glob.sync(globPatterns); if (excludes) { files = files.map(function (file) { if (_.isArray(excludes)) { for (var i in excludes) { file = file.replace(excludes[i], ''); } } else { file = file.replace(excludes, ''); } return file; }); } output = _.union(output, files); } } return output; }; /** * Validate NODE_ENV existance */ var validateEnvironmentVariable = function () { var environmentFiles = glob.sync('./config/env/' + process.env.NODE_ENV + '.js'); console.log(); if (!environmentFiles.length) { if (process.env.NODE_ENV) { console.error(chalk.red('+ Error: No configuration file found for "' + process.env.NODE_ENV + '" environment using development instead')); } else { console.error(chalk.red('+ Error: NODE_ENV is not defined! Using default development environment')); } process.env.NODE_ENV = 'development'; } // Reset console color console.log(chalk.white('')); }; /** * Validate Secure=true parameter can actually be turned on * because it requires certs and key files to be available */ var validateSecureMode = function (config) { if (config.secure !== true) { return true; } var privateKey = fs.existsSync('./config/sslcerts/key.pem'); var certificate = fs.existsSync('./config/sslcerts/cert.pem'); if (!privateKey || !certificate) { console.log(chalk.red('+ Error: Certificate file or key file is missing, falling back to non-SSL mode')); console.log(chalk.red(' To create them, simply run the following from your shell: sh ./scripts/generate-ssl-certs.sh')); console.log(); config.secure = false; } }; /** * Initialize global configuration files */ var initGlobalConfigFolders = function (config, assets) { // Appending files config.folders = { server: {}, client: {} }; // Setting globbed client paths config.folders.client = getGlobbedPaths(path.join(process.cwd(), 'modules/*/client/'), process.cwd().replace(new RegExp(/\\/g), '/')); }; /** * Initialize global configuration files */ var initGlobalConfigFiles = function (config, assets) { // Appending files config.files = { server: {}, client: {} }; // Setting Globbed model files config.files.server.models = getGlobbedPaths(assets.server.models); // Setting Globbed route files config.files.server.routes = getGlobbedPaths(assets.server.routes); // Setting Globbed config files config.files.server.configs = getGlobbedPaths(assets.server.config); // Setting Globbed socket files config.files.server.sockets = getGlobbedPaths(assets.server.sockets); // Setting Globbed policies files config.files.server.policies = getGlobbedPaths(assets.server.policies); // Setting Globbed js files config.files.client.js = getGlobbedPaths(assets.client.lib.js, 'public/').concat(getGlobbedPaths(assets.client.js, ['client/', 'public/'])); // Setting Globbed css files config.files.client.css = getGlobbedPaths(assets.client.lib.css, 'public/').concat(getGlobbedPaths(assets.client.css, ['client/', 'public/'])); // Setting Globbed test files config.files.client.tests = getGlobbedPaths(assets.client.tests); }; /** * Initialize global configuration */ var initGlobalConfig = function () { // Validate NDOE_ENV existance validateEnvironmentVariable(); // Get the default assets var defaultAssets = require(path.join(process.cwd(), 'config/assets/default')); // Get the current assets var environmentAssets = require(path.join(process.cwd(), 'config/assets/', process.env.NODE_ENV)) || {}; // Merge assets var assets = _.merge(defaultAssets, environmentAssets); // Get the default config var defaultConfig = require(path.join(process.cwd(), 'config/env/default')); // Get the current config var environmentConfig = require(path.join(process.cwd(), 'config/env/', process.env.NODE_ENV)) || {}; // Merge config files var envConf = _.merge(defaultConfig, environmentConfig); var config = _.merge(envConf, (fs.existsSync(path.join(process.cwd(), 'config/env/local.js')) && require(path.join(process.cwd(), 'config/env/local.js'))) || {}); // Initialize global globbed files initGlobalConfigFiles(config, assets); // Initialize global globbed folders initGlobalConfigFolders(config, assets); // Validate Secure SSL mode can be used validateSecureMode(config); // Expose configuration utilities config.utils = { getGlobbedPaths: getGlobbedPaths }; return config; }; /** * Set configuration object */ module.exports = initGlobalConfig();
import settings from "./_settings"; export default () => { return settings; }
/** * Japanese translation * @author Tomoaki Yoshida <info@yoshida-studio.jp> * @author Naoki Sawada <hypweb@gmail.com> * @version 2016-03-25 */ if (elFinder && elFinder.prototype && typeof(elFinder.prototype.i18) == 'object') { elFinder.prototype.i18.jp = { translator : 'Tomoaki Yoshida &lt;info@yoshida-studio.jp&gt;, Naoki Sawada &lt;hypweb@gmail.com&gt;', language : 'Japanese', direction : 'ltr', dateFormat : 'Y/m/d h:i A', // Mar 13, 2012 05:27 PM fancyDateFormat : '$1 h:i A', // will produce smth like: Today 12:25 PM messages : { /********************************** errors **********************************/ 'error' : 'エラー', 'errUnknown' : '不明なエラーです', 'errUnknownCmd' : '不明なコマンドです', 'errJqui' : '無効なjQuery UI コンフィグレーションです。セレクタブルコンポーネント、ドラッガブルコンポーネント、ドロッパブルコンポーネントがあるかを確認して下さい', 'errNode' : 'elFinderはDOM Elementが必要です', 'errURL' : '無効なelFinder コンフィグレーションです! URLを設定してください', 'errAccess' : 'アクセスが拒否されました', 'errConnect' : 'バックエンドとの接続ができません', 'errAbort' : '接続が中断されました', 'errTimeout' : '接続がタイムアウトしました.', 'errNotFound' : 'バックエンドが見つかりません', 'errResponse' : '無効なバックエンドレスポンスです', 'errConf' : 'バックエンドの設定が有効ではありません', 'errJSON' : 'PHP JSON モジュールがインストールされていません', 'errNoVolumes' : '読み込み可能なボリュームが入手できません', 'errCmdParams' : 'コマンド "$1"のパラメーターが無効です', 'errDataNotJSON' : 'JSONデータではありません', 'errDataEmpty' : '空のデータです', 'errCmdReq' : 'バックエンドリクエストがコマンド名を要求しています', 'errOpen' : '"$1"を開くことができません', 'errNotFolder' : 'オブジェクトがフォルダーではありません', 'errNotFile' : 'オブジェクトがファイルではありません', 'errRead' : '"$1"を読むことができません', 'errWrite' : '"$1"に書きこむことができません', 'errPerm' : '権限がありません', 'errLocked' : '"$1" はロックされているので名前の変更、移動、削除ができません', 'errExists' : '"$1"というファイル名はすでに存在しています', 'errInvName' : '無効なファイル名です', 'errFolderNotFound' : 'フォルダーが見つかりません', 'errFileNotFound' : 'ファイルが見つかりません', 'errTrgFolderNotFound' : 'ターゲットとするフォルダー "$1" が見つかりません', 'errPopup' : 'ポップアップウィンドウが開けません。ファイルを開くにはブラウザの設定を変更してください', 'errMkdir' : '"$1"フォルダーを作成することができません', 'errMkfile' : '"$1"ファイルを作成することができません', 'errRename' : '"$1"の名前を変更することができません', 'errCopyFrom' : '"$1"からのファイルコピーが許可されていません', 'errCopyTo' : '"$1"へのファイルコピーが許可されていません', 'errMkOutLink' : 'ボリュームルート外へのリンクを作成することはできません', // from v2.1 added 03.10.2015 'errUpload' : 'アップロードエラー', // old name - errUploadCommon 'errUploadFile' : '"$1"がアップロードできません', // old name - errUpload 'errUploadNoFiles' : 'アップロードされたファイルがありません', 'errUploadTotalSize' : 'データが許容サイズを超えています', // old name - errMaxSize 'errUploadFileSize' : 'ファイルが許容サイズを超えています', // old name - errFileMaxSize 'errUploadMime' : '許可されていないファイル形式です', 'errUploadTransfer' : '"$1" 転送エラーです', 'errUploadTemp' : 'アップロード用一時ファイルが作成できません', // from v2.1 added 26.09.2015 'errNotReplace' : 'アイテム "$1" は、すでにこの場所にありますがアイテムのタイプが違うので置き換えることはできません', // new 'errReplace' : '"$1"を置き換えることができません', 'errSave' : '"$1"を保存することができません', 'errCopy' : '"$1"をコピーすることができません', 'errMove' : '"$1"を移動することができません', 'errCopyInItself' : '"$1"をそれ自身の中にコピーすることはできません', 'errRm' : '"$1"を削除することができません', 'errRmSrc' : '元ファイルを削除することができません', 'errExtract' : '"$1"を解凍することができません', 'errArchive' : 'アーカイブを作成することができません', 'errArcType' : 'サポート外のアーカイブ形式です', 'errNoArchive' : 'アーカイブでないかサポートされていないアーカイブ形式です', 'errCmdNoSupport' : 'サポートされていないコマンドです', 'errReplByChild' : 'フォルダ "$1" に含まれてるアイテムを置き換えることはできません', 'errArcSymlinks' : 'シンボリックリンクまたは許容されないファイル名を含むアーカイブはセキュリティ上、解凍できません', // edited 24.06.2012 'errArcMaxSize' : 'アーカイブが許容されたサイズを超えています', 'errResize' : '"$1"をリサイズできません', 'errResizeDegree' : 'イメージの回転角度が不正です', // added 7.3.2013 'errResizeRotate' : 'イメージを回転できません', // added 7.3.2013 'errResizeSize' : '指定されたイメージサイズが不正です', // added 7.3.2013 'errResizeNoChange' : 'イメージサイズなどの変更がありません', // added 7.3.2013 'errUsupportType' : 'このファイルタイプはサポートされません', 'errNotUTF8Content' : 'ファイル "$1" には UTF-8 以外の文字が含まれているので編集できません', // added 9.11.2011 'errNetMount' : '"$1"をマウントできません', // added 17.04.2012 'errNetMountNoDriver' : 'サポートされていないプロトコルです', // added 17.04.2012 'errNetMountFailed' : 'マウントに失敗しました', // added 17.04.2012 'errNetMountHostReq' : 'ホスト名は必須です', // added 18.04.2012 'errSessionExpires' : 'アクションがなかったため、セッションが期限切れになりました', 'errCreatingTempDir' : '一時ディレクトリを作成できません:"$1"', 'errFtpDownloadFile' : 'FTP からファイルをダウンロードできません:"$1"', 'errFtpUploadFile' : 'FTP へファイルをアップロードできません:"$1"', 'errFtpMkdir' : 'FTP にリモートディレクトリを作成できません:"$1"', 'errArchiveExec' : 'ファイルのアーカイブ中にエラーが発生しました:"$1"', 'errExtractExec' : 'ファイルの抽出中にエラーが発生しました:"$1"', 'errNetUnMount' : 'アンマウントできません', // from v2.1 added 30.04.2012 'errConvUTF8' : 'UTF-8 に変換できませんでした', // from v2.1 added 08.04.2014 'errFolderUpload' : 'フォルダをアップロードしたいのであれば、Google Chrome を使用してください', // from v2.1 added 26.6.2015 'errSearchTimeout' : '"$1"を検索中にタイムアウトしました。検索結果は部分的です。', // from v2.1 added 12.1.2016 'errReauthRequire' : '再認可が必要です', // from v2.1.10 added 3.24.2016 /******************************* commands names ********************************/ 'cmdarchive' : 'アーカイブ作成', 'cmdback' : '戻る', 'cmdcopy' : 'コピー', 'cmdcut' : 'カット', 'cmddownload' : 'ダウンロード', 'cmdduplicate' : '複製', 'cmdedit' : 'ファイル編集', 'cmdextract' : 'アーカイブを解凍', 'cmdforward' : '進む', 'cmdgetfile' : 'ファイル選択', 'cmdhelp' : 'このソフトウェアについて', 'cmdhome' : 'ホーム', 'cmdinfo' : '情報', 'cmdmkdir' : '新規フォルダー', 'cmdmkdirin' : '新規フォルダーへ', // from v2.1.7 added 19.2.2016 'cmdmkfile' : '新規テキストファイル', 'cmdopen' : '開く', 'cmdpaste' : 'ペースト', 'cmdquicklook' : 'プレビュー', 'cmdreload' : 'リロード', 'cmdrename' : 'リネーム', 'cmdrm' : '削除', 'cmdsearch' : 'ファイルを探す', 'cmdup' : '親ディレクトリーへ移動', 'cmdupload' : 'ファイルアップロード', 'cmdview' : 'ビュー', 'cmdresize' : 'リサイズと回転', 'cmdsort' : 'ソート', 'cmdnetmount' : 'ネットワークボリュームをマウント', // added 18.04.2012 'cmdnetunmount': 'アンマウント', // from v2.1 added 30.04.2012 'cmdplaces' : 'お気に入りへ', // added 28.12.2014 'cmdchmod' : '属性変更', // from v2.1 added 20.6.2015 'cmdopendir' : 'フォルダを開く', // from v2.1 added 13.1.2016 /*********************************** buttons ***********************************/ 'btnClose' : '閉じる', 'btnSave' : '保存', 'btnRm' : '削除', 'btnApply' : '適用', 'btnCancel' : 'キャンセル', 'btnNo' : 'いいえ', 'btnYes' : 'はい', 'btnMount' : 'マウント', // added 18.04.2012 'btnApprove': '$1へ行き認可する', // from v2.1 added 26.04.2012 'btnUnmount': 'アンマウント', // from v2.1 added 30.04.2012 'btnConv' : '変換', // from v2.1 added 08.04.2014 'btnCwd' : 'この場所', // from v2.1 added 22.5.2015 'btnVolume' : 'ボリューム', // from v2.1 added 22.5.2015 'btnAll' : '全て', // from v2.1 added 22.5.2015 'btnMime' : 'MIMEタイプ', // from v2.1 added 22.5.2015 'btnFileName':'ファイル名', // from v2.1 added 22.5.2015 'btnSaveClose': '保存して閉じる', // from v2.1 added 12.6.2015 'btnBackup' : 'バックアップ', // fromv2.1 added 28.11.2015 /******************************** notifications ********************************/ 'ntfopen' : 'フォルダーを開いています', 'ntffile' : 'ファイルを開いています', 'ntfreload' : 'フォルダーを再読込しています', 'ntfmkdir' : 'ディレクトリーを作成しています', 'ntfmkfile' : 'ファイルを作成しています', 'ntfrm' : 'ファイルを削除しています', 'ntfcopy' : 'ファイルをコピーしています', 'ntfmove' : 'ファイルを移動しています', 'ntfprepare' : 'ファイルコピーを準備しています', 'ntfrename' : 'ファイル名を変更しています', 'ntfupload' : 'ファイルをアップロードしています', 'ntfdownload' : 'ファイルをダウンロードしています', 'ntfsave' : 'ファイルを保存しています', 'ntfarchive' : 'アーカイブ作成しています', 'ntfextract' : 'アーカイブを解凍しています', 'ntfsearch' : 'ファイル検索中', 'ntfresize' : 'リサイズしています', 'ntfsmth' : '処理をしています', 'ntfloadimg' : 'イメージを読み込んでいます', 'ntfnetmount' : 'ネットワークボリュームをマウントしています', // added 18.04.2012 'ntfnetunmount': 'ネットワークボリュームをアンマウントしています', // from v2.1 added 30.04.2012 'ntfdim' : '画像サイズを取得しています', // added 20.05.2013 'ntfreaddir' : 'ホルダ情報を読み取っています', // from v2.1 added 01.07.2013 'ntfurl' : 'リンクURLを取得しています', // from v2.1 added 11.03.2014 'ntfchmod' : 'ファイル属性を変更しています', // from v2.1 added 20.6.2015 'ntfpreupload': 'アップロードファイル名を検証しています', // from v2.1 added 31.11.2015 'ntfzipdl' : 'ダウンロード用ファイルを作成しています', // from v2.1.7 added 23.1.2016 /************************************ dates **********************************/ 'dateUnknown' : '不明', 'Today' : '今日', 'Yesterday' : '昨日', 'msJan' : '1月', 'msFeb' : '2月', 'msMar' : '3月', 'msApr' : '4月', 'msMay' : '5月', 'msJun' : '6月', 'msJul' : '7月', 'msAug' : '8月', 'msSep' : '9月', 'msOct' : '10月', 'msNov' : '11月', 'msDec' : '12月', 'January' : '1月', 'February' : '2月', 'March' : '3月', 'April' : '4月', 'May' : '5月', 'June' : '6月', 'July' : '7月', 'August' : '8月', 'September' : '9月', 'October' : '10月', 'November' : '11月', 'December' : '12月', 'Sunday' : '日曜日', 'Monday' : '月曜日', 'Tuesday' : '火曜日', 'Wednesday' : '水曜日', 'Thursday' : '木曜日', 'Friday' : '金曜日', 'Saturday' : '土曜日', 'Sun' : '(日)', 'Mon' : '(月)', 'Tue' : '(火)', 'Wed' : '(水)', 'Thu' : '(木)', 'Fri' : '(金)', 'Sat' : '(土)', /******************************** sort variants ********************************/ 'sortname' : '名前順', 'sortkind' : '種類順', 'sortsize' : 'サイズ順', 'sortdate' : '日付順', 'sortFoldersFirst' : 'フォルダ優先', /********************************** new items **********************************/ 'untitled file.txt' : '新規ファイル.txt', // added 10.11.2015 'untitled folder' : '新規フォルダ', // added 10.11.2015 'Archive' : '新規アーカイブ', // from v2.1 added 10.11.2015 /********************************** messages **********************************/ 'confirmReq' : '処理を実行しますか?', 'confirmRm' : '本当にファイルを削除しますか?<br/>この操作は取り消せません!', 'confirmRepl' : '古いファイルを新しいファイルで上書きしますか?', 'confirmConvUTF8' : 'UTF-8 以外の文字が含まれています。<br/>UTF-8 に変換しますか?<br/>変換後の保存でコンテンツは UTF-8 になります。', // from v2.1 added 08.04.2014 'confirmNotSave' : '変更されています。<br/>保存せずに閉じると編集内容が失われます。', // from v2.1 added 15.7.2015 'apllyAll' : '全てに適用します', 'name' : '名前', 'size' : 'サイズ', 'perms' : '権限', 'modify' : '更新', 'kind' : '種類', 'read' : '読み取り', 'write' : '書き込み', 'noaccess' : 'アクセス禁止', 'and' : ',', 'unknown' : '不明', 'selectall' : '全てのファイルを選択', 'selectfiles' : 'ファイル選択', 'selectffile' : '最初のファイルを選択', 'selectlfile' : '最後のファイルを選択', 'viewlist' : 'リスト形式で表示', 'viewicons' : 'アイコン形式で表示', 'places' : 'お気に入り', 'calc' : '計算中', 'path' : 'パス', 'aliasfor' : 'エイリアス', 'locked' : 'ロック', 'dim' : 'サイズ', 'files' : 'ファイル', 'folders' : 'フォルダー', 'items' : 'アイテム', 'yes' : 'はい', 'no' : 'いいえ', 'link' : 'リンク', 'searcresult' : '検索結果', 'selected' : '選択されたアイテム', 'about' : 'アバウト', 'shortcuts' : 'ショートカット', 'help' : 'ヘルプ', 'webfm' : 'ウェブファイルマネージャー', 'ver' : 'バージョン', 'protocolver' : 'プロトコルバージョン', 'homepage' : 'プロジェクトホーム', 'docs' : 'ドキュメンテーション', 'github' : 'Github でフォーク', 'twitter' : 'Twitter でフォロー', 'facebook' : 'Facebookグループ に参加', 'team' : 'チーム', 'chiefdev' : 'チーフデベロッパー', 'developer' : 'デベロッパー', 'contributor' : 'コントリビュータ', 'maintainer' : 'メインテナー', 'translator' : '翻訳者', 'icons' : 'アイコン', 'dontforget' : 'タオル忘れちゃだめよ~', 'shortcutsof' : 'ショートカットは利用できません', 'dropFiles' : 'ここにファイルをドロップ', 'or' : 'または', 'selectForUpload' : 'アップロードするファイルを選択', 'moveFiles' : 'ファイルを移動', 'copyFiles' : 'ファイルをコピー', 'rmFromPlaces' : 'ここから削除', 'aspectRatio' : '縦横比維持', 'scale' : '表示縮尺', 'width' : '幅', 'height' : '高さ', 'resize' : 'リサイズ', 'crop' : '切り抜き', 'rotate' : '回転', 'rotate-cw' : '90度左回転', 'rotate-ccw' : '90度右回転', 'degree' : '度', 'netMountDialogTitle' : 'ネットワークボリュームのマウント', // added 18.04.2012 'protocol' : 'プロトコル', // added 18.04.2012 'host' : 'ホスト名', // added 18.04.2012 'port' : 'ポート', // added 18.04.2012 'user' : 'ユーザー名', // added 18.04.2012 'pass' : 'パスワード', // added 18.04.2012 'confirmUnmount' : '$1をアンマウントしますか?', // from v2.1 added 30.04.2012 'dropFilesBrowser': 'ブラウザからファイルをドロップまたは貼り付け', // from v2.1 added 30.05.2012 'dropPasteFiles' : 'ファイル,URLリストをドロップまたは貼り付け', // from v2.1 added 07.04.2014 'encoding' : '文字コード', // from v2.1 added 19.12.2014 'locale' : 'ロケール', // from v2.1 added 19.12.2014 'searchTarget' : '検索範囲: $1', // from v2.1 added 22.5.2015 'searchMime' : '指定した MIME タイプで検索', // from v2.1 added 22.5.2015 'owner' : 'オーナー', // from v2.1 added 20.6.2015 'group' : 'グループ', // from v2.1 added 20.6.2015 'other' : 'その他', // from v2.1 added 20.6.2015 'execute' : '実行', // from v2.1 added 20.6.2015 'perm' : 'パーミッション', // from v2.1 added 20.6.2015 'mode' : '属性', // from v2.1 added 20.6.2015 'emptyFolder' : '空のフォルダ', // from v2.1.6 added 30.12.2015 'emptyFolderDrop' : '空のフォルダ\\Aアイテムを追加するにはここへドロップ', // from v2.1.6 added 30.12.2015 'emptyFolderLTap' : '空のフォルダ\\Aアイテムを追加するにはここをロングタップ', // from v2.1.6 added 30.12.2015 'quality' : '品質', // from v2.1.6 added 5.1.2016 'autoSync' : '自動更新', // from v2.1.6 added 10.1.2016 'moveUp' : '上へ移動', // from v2.1.6 added 18.1.2016 'getLink' : 'リンクURLを取得', // from v2.1.7 added 9.2.2016 'selectedItems' : '選択アイテム ($1)', // from v2.1.7 added 2.19.2016 'folderId' : 'フォルダID', // from v2.1.10 added 3.25.2016 'offlineAccess' : 'オフライン アクセスを可能にする', // from v2.1.10 added 3.25.2016 'reAuth' : '再認証する', // from v2.1.10 added 3.25.2016 /********************************** mimetypes **********************************/ 'kindUnknown' : '不明', 'kindFolder' : 'フォルダー', 'kindAlias' : '別名', 'kindAliasBroken' : '宛先不明の別名', // applications 'kindApp' : 'アプリケーション', 'kindPostscript' : 'Postscript ドキュメント', 'kindMsOffice' : 'Microsoft Office ドキュメント', 'kindMsWord' : 'Microsoft Word ドキュメント', 'kindMsExcel' : 'Microsoft Excel ドキュメント', 'kindMsPP' : 'Microsoft Powerpoint プレゼンテーション', 'kindOO' : 'Open Office ドキュメント', 'kindAppFlash' : 'Flash アプリケーション', 'kindPDF' : 'PDF', 'kindTorrent' : 'Bittorrent ファイル', 'kind7z' : '7z アーカイブ', 'kindTAR' : 'TAR アーカイブ', 'kindGZIP' : 'GZIP アーカイブ', 'kindBZIP' : 'BZIP アーカイブ', 'kindXZ' : 'XZ アーカイブ', 'kindZIP' : 'ZIP アーカイブ', 'kindRAR' : 'RAR アーカイブ', 'kindJAR' : 'Java JAR ファイル', 'kindTTF' : 'True Type フォント', 'kindOTF' : 'Open Type フォント', 'kindRPM' : 'RPM パッケージ', // texts 'kindText' : 'Text ドキュメント', 'kindTextPlain' : 'プレインテキスト', 'kindPHP' : 'PHP ソース', 'kindCSS' : 'スタイルシート', 'kindHTML' : 'HTML ドキュメント', 'kindJS' : 'Javascript ソース', 'kindRTF' : 'Rich Text フォーマット', 'kindC' : 'C ソース', 'kindCHeader' : 'C ヘッダーソース', 'kindCPP' : 'C++ ソース', 'kindCPPHeader' : 'C++ ヘッダーソース', 'kindShell' : 'Unix shell スクリプト', 'kindPython' : 'Python ソース', 'kindJava' : 'Java ソース', 'kindRuby' : 'Ruby ソース', 'kindPerl' : 'Perl スクリプト', 'kindSQL' : 'SQL ソース', 'kindXML' : 'XML ドキュメント', 'kindAWK' : 'AWK ソース', 'kindCSV' : 'CSV', 'kindDOCBOOK' : 'Docbook XML ドキュメント', 'kindMarkdown' : 'Markdown テキスト', // added 20.7.2015 // images 'kindImage' : 'イメージ', 'kindBMP' : 'BMP イメージ', 'kindJPEG' : 'JPEG イメージ', 'kindGIF' : 'GIF イメージ', 'kindPNG' : 'PNG イメージ', 'kindTIFF' : 'TIFF イメージ', 'kindTGA' : 'TGA イメージ', 'kindPSD' : 'Adobe Photoshop イメージ', 'kindXBITMAP' : 'X bitmap イメージ', 'kindPXM' : 'Pixelmator イメージ', // media 'kindAudio' : 'オーディオメディア', 'kindAudioMPEG' : 'MPEG オーディオ', 'kindAudioMPEG4' : 'MPEG-4 オーディオ', 'kindAudioMIDI' : 'MIDI オーディオ', 'kindAudioOGG' : 'Ogg Vorbis オーディオ', 'kindAudioWAV' : 'WAV オーディオ', 'AudioPlaylist' : 'MP3 プレイリスト', 'kindVideo' : 'ビデオメディア', 'kindVideoDV' : 'DV ムービー', 'kindVideoMPEG' : 'MPEG ムービー', 'kindVideoMPEG4' : 'MPEG-4 ムービー', 'kindVideoAVI' : 'AVI ムービー', 'kindVideoMOV' : 'Quick Time ムービー', 'kindVideoWM' : 'Windows Media ムービー', 'kindVideoFlash' : 'Flash ムービー', 'kindVideoMKV' : 'Matroska ムービー', 'kindVideoOGG' : 'Ogg ムービー' } }; }
typeof module !== "undefined"
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ /** * @fileOverview Defines the {@link CKEDITOR.lang} object, for the * German language. */ /**#@+ @type String @example */ /** * Contains the dictionary of language entries. * @namespace */ CKEDITOR.lang['de'] = { /** * The language reading direction. Possible values are "rtl" for * Right-To-Left languages (like Arabic) and "ltr" for Left-To-Right * languages (like English). * @default 'ltr' */ dir : 'ltr', /* * Screenreader titles. Please note that screenreaders are not always capable * of reading non-English words. So be careful while translating it. */ editorTitle : 'WYSIWYG-Editor, %1, drücken Sie ALT 0 für Hilfe.', // ARIA descriptions. toolbars : 'Editor Symbolleisten', editor : 'WYSIWYG-Editor', // Toolbar buttons without dialogs. source : 'Quellcode', newPage : 'Neue Seite', save : 'Speichern', preview : 'Vorschau', cut : 'Ausschneiden', copy : 'Kopieren', paste : 'Einfügen', print : 'Drucken', underline : 'Unterstrichen', bold : 'Fett', italic : 'Kursiv', selectAll : 'Alles auswählen', removeFormat : 'Formatierungen entfernen', strike : 'Durchgestrichen', subscript : 'Tiefgestellt', superscript : 'Hochgestellt', horizontalrule : 'Horizontale Linie einfügen', pagebreak : 'Seitenumbruch einfügen', pagebreakAlt : 'Seitenumbruch einfügen', unlink : 'Link entfernen', undo : 'Rückgängig', redo : 'Wiederherstellen', // Common messages and labels. common : { browseServer : 'Server durchsuchen', url : 'URL', protocol : 'Protokoll', upload : 'Hochladen', uploadSubmit : 'Zum Server senden', image : 'Bild', flash : 'Flash', form : 'Formular', checkbox : 'Checkbox', radio : 'Radiobutton', textField : 'Textfeld einzeilig', textarea : 'Textfeld mehrzeilig', hiddenField : 'Verstecktes Feld', button : 'Klickbutton', select : 'Auswahlfeld', imageButton : 'Bildbutton', notSet : '<nichts>', id : 'ID', name : 'Name', langDir : 'Schreibrichtung', langDirLtr : 'Links nach Rechts (LTR)', langDirRtl : 'Rechts nach Links (RTL)', langCode : 'Sprachenkürzel', longDescr : 'Langform URL', cssClass : 'Stylesheet Klasse', advisoryTitle : 'Titel Beschreibung', cssStyle : 'Style', ok : 'OK', cancel : 'Abbrechen', close : 'Schließen', preview : 'Vorschau', generalTab : 'Allgemein', advancedTab : 'Erweitert', validateNumberFailed : 'Dieser Wert ist keine Nummer.', confirmNewPage : 'Alle nicht gespeicherten Änderungen gehen verlohren. Sind Sie sicher die neue Seite zu laden?', confirmCancel : 'Einige Optionen wurden geändert. Wollen Sie den Dialog dennoch schließen?', options : 'Optionen', target : 'Zielseite', targetNew : 'Neues Fenster (_blank)', targetTop : 'Oberstes Fenster (_top)', targetSelf : 'Gleiches Fenster (_self)', targetParent : 'Oberes Fenster (_parent)', langDirLTR : 'Links nach Rechts (LNR)', langDirRTL : 'Rechts nach Links (RNL)', styles : 'Style', cssClasses : 'Stylesheet Klasse', width : 'Breite', height : 'Höhe', align : 'Ausrichtung', alignLeft : 'Links', alignRight : 'Rechts', alignCenter : 'Zentriert', alignTop : 'Oben', alignMiddle : 'Mitte', alignBottom : 'Unten', invalidHeight : 'Höhe muss eine Zahl sein.', invalidWidth : 'Breite muss eine Zahl sein.', invalidCssLength : 'Wert spezifiziert für "%1" Feld muss ein positiver numerischer Wert sein mit oder ohne korrekte CSS Messeinheit (px, %, in, cm, mm, em, ex, pt oder pc).', invalidHtmlLength : 'Wert spezifiziert für "%1" Feld muss ein positiver numerischer Wert sein mit oder ohne korrekte HTML Messeinheit (px oder %).', invalidInlineStyle : 'Wert spezifiziert für inline Stilart muss enthalten ein oder mehr Tupels mit dem Format "Name : Wert" getrennt mit Semikolons.', cssLengthTooltip : 'Gebe eine Zahl ein für ein Wert in pixels oder eine Zahl mit einer korrekten CSS Messeinheit (px, %, in, cm, mm, em, ex, pt oder pc).', // Put the voice-only part of the label in the span. unavailable : '%1<span class="cke_accessibility">, nicht verfügbar</span>' }, contextmenu : { options : 'Kontextmenü Optionen' }, // Special char dialog. specialChar : { toolbar : 'Sonderzeichen einfügen/editieren', title : 'Sonderzeichen auswählen', options : 'Sonderzeichen Optionen' }, // Link dialog. link : { toolbar : 'Link einfügen/editieren', other : '<andere>', menu : 'Link editieren', title : 'Link', info : 'Link-Info', target : 'Zielseite', upload : 'Hochladen', advanced : 'Erweitert', type : 'Link-Typ', toUrl : 'URL', toAnchor : 'Anker in dieser Seite', toEmail : 'E-Mail', targetFrame : '<Frame>', targetPopup : '<Pop-up Fenster>', targetFrameName : 'Ziel-Fenster-Name', targetPopupName : 'Pop-up Fenster-Name', popupFeatures : 'Pop-up Fenster-Eigenschaften', popupResizable : 'Größe änderbar', popupStatusBar : 'Statusleiste', popupLocationBar: 'Adress-Leiste', popupToolbar : 'Symbolleiste', popupMenuBar : 'Menü-Leiste', popupFullScreen : 'Vollbild (IE)', popupScrollBars : 'Rollbalken', popupDependent : 'Abhängig (Netscape)', popupLeft : 'Linke Position', popupTop : 'Obere Position', id : 'Id', langDir : 'Schreibrichtung', langDirLTR : 'Links nach Rechts (LTR)', langDirRTL : 'Rechts nach Links (RTL)', acccessKey : 'Zugriffstaste', name : 'Name', langCode : 'Sprachenkürzel', tabIndex : 'Tab-Index', advisoryTitle : 'Titel Beschreibung', advisoryContentType : 'Inhaltstyp', cssClasses : 'Stylesheet Klasse', charset : 'Ziel-Zeichensatz', styles : 'Style', rel : 'Beziehung', selectAnchor : 'Anker auswählen', anchorName : 'nach Anker Name', anchorId : 'nach Element Id', emailAddress : 'E-Mail Addresse', emailSubject : 'Betreffzeile', emailBody : 'Nachrichtentext', noAnchors : '(keine Anker im Dokument vorhanden)', noUrl : 'Bitte geben Sie die Link-URL an', noEmail : 'Bitte geben Sie e-Mail Adresse an' }, // Anchor dialog anchor : { toolbar : 'Anker einfügen/editieren', menu : 'Anker-Eigenschaften', title : 'Anker-Eigenschaften', name : 'Anker Name', errorName : 'Bitte geben Sie den Namen des Ankers ein', remove : 'Anker entfernen' }, // List style dialog list: { numberedTitle : 'Nummerierte Listen-Eigenschaften', bulletedTitle : 'Listen-Eigenschaften', type : 'Typ', start : 'Start', validateStartNumber :'List Startnummer muss eine ganze Zahl sein.', circle : 'Ring', disc : 'Kreis', square : 'Quadrat', none : 'Keine', notset : '<nicht gesetzt>', armenian : 'Armenisch Nummerierung', georgian : 'Georgisch Nummerierung (an, ban, gan, etc.)', lowerRoman : 'Klein römisch (i, ii, iii, iv, v, etc.)', upperRoman : 'Groß römisch (I, II, III, IV, V, etc.)', lowerAlpha : 'Klein alpha (a, b, c, d, e, etc.)', upperAlpha : 'Groß alpha (A, B, C, D, E, etc.)', lowerGreek : 'Klein griechisch (alpha, beta, gamma, etc.)', decimal : 'Dezimal (1, 2, 3, etc.)', decimalLeadingZero : 'Dezimal mit führende Null (01, 02, 03, etc.)' }, // Find And Replace Dialog findAndReplace : { title : 'Suchen und Ersetzen', find : 'Suchen', replace : 'Ersetzen', findWhat : 'Suche nach:', replaceWith : 'Ersetze mit:', notFoundMsg : 'Der gesuchte Text wurde nicht gefunden.', findOptions : 'Suchoptionen', matchCase : 'Groß-Kleinschreibung beachten', matchWord : 'Nur ganze Worte suchen', matchCyclic : 'Zyklische Suche', replaceAll : 'Alle ersetzen', replaceSuccessMsg : '%1 vorkommen ersetzt.' }, // Table Dialog table : { toolbar : 'Tabelle', title : 'Tabellen-Eigenschaften', menu : 'Tabellen-Eigenschaften', deleteTable : 'Tabelle löschen', rows : 'Zeile', columns : 'Spalte', border : 'Rahmen', widthPx : 'Pixel', widthPc : '%', widthUnit : 'Breite Einheit', cellSpace : 'Zellenabstand außen', cellPad : 'Zellenabstand innen', caption : 'Überschrift', summary : 'Inhaltsübersicht', headers : 'Kopfzeile', headersNone : 'Keine', headersColumn : 'Erste Spalte', headersRow : 'Erste Zeile', headersBoth : 'Beide', invalidRows : 'Die Anzahl der Zeilen muß größer als 0 sein.', invalidCols : 'Die Anzahl der Spalten muß größer als 0 sein..', invalidBorder : 'Die Rahmenbreite muß eine Zahl sein.', invalidWidth : 'Die Tabellenbreite muss eine Zahl sein.', invalidHeight : 'Die Tabellenbreite muß eine Zahl sein.', invalidCellSpacing : 'Der Zellenabstand außen muß eine positive Zahl sein.', invalidCellPadding : 'Der Zellenabstand innen muß eine positive Zahl sein.', cell : { menu : 'Zelle', insertBefore : 'Zelle davor einfügen', insertAfter : 'Zelle danach einfügen', deleteCell : 'Zelle löschen', merge : 'Zellen verbinden', mergeRight : 'Nach rechts verbinden', mergeDown : 'Nach unten verbinden', splitHorizontal : 'Zelle horizontal teilen', splitVertical : 'Zelle vertikal teilen', title : 'Zellen-Eigenschaften', cellType : 'Zellart', rowSpan : 'Anzahl Zeilen verbinden', colSpan : 'Anzahl Spalten verbinden', wordWrap : 'Zeilenumbruch', hAlign : 'Horizontale Ausrichtung', vAlign : 'Vertikale Ausrichtung', alignBaseline : 'Grundlinie', bgColor : 'Hintergrundfarbe', borderColor : 'Rahmenfarbe', data : 'Daten', header : 'Überschrift', yes : 'Ja', no : 'Nein', invalidWidth : 'Zellenbreite muß eine Zahl sein.', invalidHeight : 'Zellenhöhe muß eine Zahl sein.', invalidRowSpan : '"Anzahl Zeilen verbinden" muss eine Ganzzahl sein.', invalidColSpan : '"Anzahl Spalten verbinden" muss eine Ganzzahl sein.', chooseColor : 'Wählen' }, row : { menu : 'Zeile', insertBefore : 'Zeile oberhalb einfügen', insertAfter : 'Zeile unterhalb einfügen', deleteRow : 'Zeile entfernen' }, column : { menu : 'Spalte', insertBefore : 'Spalte links davor einfügen', insertAfter : 'Spalte rechts danach einfügen', deleteColumn : 'Spalte löschen' } }, // Button Dialog. button : { title : 'Button-Eigenschaften', text : 'Text (Wert)', type : 'Typ', typeBtn : 'Button', typeSbm : 'Absenden', typeRst : 'Zurücksetzen' }, // Checkbox and Radio Button Dialogs. checkboxAndRadio : { checkboxTitle : 'Checkbox-Eigenschaften', radioTitle : 'Optionsfeld-Eigenschaften', value : 'Wert', selected : 'ausgewählt' }, // Form Dialog. form : { title : 'Formular-Eigenschaften', menu : 'Formular-Eigenschaften', action : 'Action', method : 'Method', encoding : 'Zeichenkodierung' }, // Select Field Dialog. select : { title : 'Auswahlfeld-Eigenschaften', selectInfo : 'Info', opAvail : 'Mögliche Optionen', value : 'Wert', size : 'Größe', lines : 'Linien', chkMulti : 'Erlaube Mehrfachauswahl', opText : 'Text', opValue : 'Wert', btnAdd : 'Hinzufügen', btnModify : 'Ändern', btnUp : 'Hoch', btnDown : 'Runter', btnSetValue : 'Setze als Standardwert', btnDelete : 'Entfernen' }, // Textarea Dialog. textarea : { title : 'Textfeld (mehrzeilig) Eigenschaften', cols : 'Spalten', rows : 'Reihen' }, // Text Field Dialog. textfield : { title : 'Textfeld (einzeilig) Eigenschaften', name : 'Name', value : 'Wert', charWidth : 'Zeichenbreite', maxChars : 'Max. Zeichen', type : 'Typ', typeText : 'Text', typePass : 'Passwort' }, // Hidden Field Dialog. hidden : { title : 'Verstecktes Feld-Eigenschaften', name : 'Name', value : 'Wert' }, // Image Dialog. image : { title : 'Bild-Eigenschaften', titleButton : 'Bildbutton-Eigenschaften', menu : 'Bild-Eigenschaften', infoTab : 'Bild-Info', btnUpload : 'Zum Server senden', upload : 'Hochladen', alt : 'Alternativer Text', lockRatio : 'Größenverhältnis beibehalten', resetSize : 'Größe zurücksetzen', border : 'Rahmen', hSpace : 'Horizontal-Abstand', vSpace : 'Vertikal-Abstand', alertUrl : 'Bitte geben Sie die Bild-URL an', linkTab : 'Link', button2Img : 'Möchten Sie den gewählten Bild-Button in ein einfaches Bild umwandeln?', img2Button : 'Möchten Sie das gewählten Bild in einen Bild-Button umwandeln?', urlMissing : 'Imagequelle URL fehlt.', validateBorder : 'Rahmen muß eine ganze Zahl sein.', validateHSpace : 'Horizontal-Abstand muß eine ganze Zahl sein.', validateVSpace : 'Vertikal-Abstand muß eine ganze Zahl sein.' }, // Flash Dialog flash : { properties : 'Flash-Eigenschaften', propertiesTab : 'Eigenschaften', title : 'Flash-Eigenschaften', chkPlay : 'Automatisch Abspielen', chkLoop : 'Endlosschleife', chkMenu : 'Flash-Menü aktivieren', chkFull : 'Vollbildmodus erlauben', scale : 'Skalierung', scaleAll : 'Alles anzeigen', scaleNoBorder : 'Ohne Rand', scaleFit : 'Passgenau', access : 'Skript Zugang', accessAlways : 'Immer', accessSameDomain: 'Gleiche Domain', accessNever : 'Nie', alignAbsBottom : 'Abs Unten', alignAbsMiddle : 'Abs Mitte', alignBaseline : 'Baseline', alignTextTop : 'Text Oben', quality : 'Qualität', qualityBest : 'Beste', qualityHigh : 'Hoch', qualityAutoHigh : 'Auto Hoch', qualityMedium : 'Medium', qualityAutoLow : 'Auto Niedrig', qualityLow : 'Niedrig', windowModeWindow: 'Fenster', windowModeOpaque: 'Deckend', windowModeTransparent : 'Transparent', windowMode : 'Fenster Modus', flashvars : 'Variablen für Flash', bgcolor : 'Hintergrundfarbe', hSpace : 'Horizontal-Abstand', vSpace : 'Vertikal-Abstand', validateSrc : 'Bitte geben Sie die Link-URL an', validateHSpace : 'HSpace muss eine Zahl sein.', validateVSpace : 'VSpace muss eine Zahl sein.' }, // Speller Pages Dialog spellCheck : { toolbar : 'Rechtschreibprüfung', title : 'Rechtschreibprüfung', notAvailable : 'Entschuldigung, aber dieser Dienst steht im Moment nicht zur Verfügung.', errorLoading : 'Fehler beim laden des Dienstanbieters: %s.', notInDic : 'Nicht im Wörterbuch', changeTo : 'Ändern in', btnIgnore : 'Ignorieren', btnIgnoreAll : 'Alle Ignorieren', btnReplace : 'Ersetzen', btnReplaceAll : 'Alle Ersetzen', btnUndo : 'Rückgängig', noSuggestions : ' - keine Vorschläge - ', progress : 'Rechtschreibprüfung läuft...', noMispell : 'Rechtschreibprüfung abgeschlossen - keine Fehler gefunden', noChanges : 'Rechtschreibprüfung abgeschlossen - keine Worte geändert', oneChange : 'Rechtschreibprüfung abgeschlossen - ein Wort geändert', manyChanges : 'Rechtschreibprüfung abgeschlossen - %1 Wörter geändert', ieSpellDownload : 'Rechtschreibprüfung nicht installiert. Möchten Sie sie jetzt herunterladen?' }, smiley : { toolbar : 'Smiley', title : 'Smiley auswählen', options : 'Smiley Optionen' }, elementsPath : { eleLabel : 'Elements Pfad', eleTitle : '%1 Element' }, numberedlist : 'Nummerierte Liste', bulletedlist : 'Liste', indent : 'Einzug erhöhen', outdent : 'Einzug verringern', justify : { left : 'Linksbündig', center : 'Zentriert', right : 'Rechtsbündig', block : 'Blocksatz' }, blockquote : 'Zitatblock', clipboard : { title : 'Einfügen', cutError : 'Die Sicherheitseinstellungen Ihres Browsers lassen es nicht zu, den Text automatisch auszuschneiden. Bitte benutzen Sie die System-Zwischenablage über STRG-X (ausschneiden) und STRG-V (einfügen).', copyError : 'Die Sicherheitseinstellungen Ihres Browsers lassen es nicht zu, den Text automatisch kopieren. Bitte benutzen Sie die System-Zwischenablage über STRG-C (kopieren).', pasteMsg : 'Bitte fügen Sie den Text in der folgenden Box über die Tastatur (mit <STRONG>Strg+V</STRONG>) ein und bestätigen Sie mit <STRONG>OK</STRONG>.', securityMsg : 'Aufgrund von Sicherheitsbeschränkungen Ihres Browsers kann der Editor nicht direkt auf die Zwischenablage zugreifen. Bitte fügen Sie den Inhalt erneut in diesem Fenster ein.', pasteArea : 'Einfügebereich' }, pastefromword : { confirmCleanup : 'Der Text, den Sie einfügen möchten, scheint aus MS-Word kopiert zu sein. Möchten Sie ihn zuvor bereinigen lassen?', toolbar : 'Aus MS-Word einfügen', title : 'Aus MS-Word einfügen', error : 'Aufgrund eines internen Fehlers war es nicht möglich die eingefügten Daten zu bereinigen' }, pasteText : { button : 'Als Text einfügen', title : 'Als Text einfügen' }, templates : { button : 'Vorlagen', title : 'Vorlagen', options : 'Vorlagen Optionen', insertOption : 'Aktuellen Inhalt ersetzen', selectPromptMsg : 'Klicken Sie auf eine Vorlage, um sie im Editor zu öffnen (der aktuelle Inhalt wird dabei gelöscht!):', emptyListMsg : '(keine Vorlagen definiert)' }, showBlocks : 'Blöcke anzeigen', stylesCombo : { label : 'Stil', panelTitle : 'Formatierungenstil', panelTitle1 : 'Block Stilart', panelTitle2 : 'Inline Stilart', panelTitle3 : 'Objekt Stilart' }, format : { label : 'Format', panelTitle : 'Format', tag_p : 'Normal', tag_pre : 'Formatiert', tag_address : 'Addresse', tag_h1 : 'Überschrift 1', tag_h2 : 'Überschrift 2', tag_h3 : 'Überschrift 3', tag_h4 : 'Überschrift 4', tag_h5 : 'Überschrift 5', tag_h6 : 'Überschrift 6', tag_div : 'Normal (DIV)' }, div : { title : 'Div Container erzeugen', toolbar : 'Div Container erzeugen', cssClassInputLabel : 'Stylesheet Klasse', styleSelectLabel : 'Style', IdInputLabel : 'Id', languageCodeInputLabel : 'Sprachenkürzel', inlineStyleInputLabel : 'Inline Stil', advisoryTitleInputLabel : 'Tooltip', langDirLabel : 'Sprache Richtung', langDirLTRLabel : 'Links nach Rechs (LTR)', langDirRTLLabel : 'Rechs nach Links (RTL)', edit : 'Div bearbeiten', remove : 'Div entfernen' }, iframe : { title : 'IFrame-Eigenschaften', toolbar : 'IFrame', noUrl : 'Bitte geben Sie die IFrame-URL an', scrolling : 'Rollbalken anzeigen', border : 'Rahmen anzeigen' }, font : { label : 'Schriftart', voiceLabel : 'Schriftart', panelTitle : 'Schriftart' }, fontSize : { label : 'Größe', voiceLabel : 'Schrifgröße', panelTitle : 'Größe' }, colorButton : { textColorTitle : 'Textfarbe', bgColorTitle : 'Hintergrundfarbe', panelTitle : 'Farben', auto : 'Automatisch', more : 'Weitere Farben...' }, colors : { '000' : 'Schwarz', '800000' : 'Kastanienbraun', '8B4513' : 'Braun', '2F4F4F' : 'Dunkles Schiefergrau', '008080' : 'Blaugrün', '000080' : 'Navy', '4B0082' : 'Indigo', '696969' : 'Dunkelgrau', 'B22222' : 'Ziegelrot', 'A52A2A' : 'Braun', 'DAA520' : 'Goldgelb', '006400' : 'Dunkelgrün', '40E0D0' : 'Türkis', '0000CD' : 'Medium Blau', '800080' : 'Lila', '808080' : 'Grau', 'F00' : 'Rot', 'FF8C00' : 'Dunkelorange', 'FFD700' : 'Gold', '008000' : 'Grün', '0FF' : 'Cyan', '00F' : 'Blau', 'EE82EE' : 'Hellviolett', 'A9A9A9' : 'Dunkelgrau', 'FFA07A' : 'Helles Lachsrosa', 'FFA500' : 'Orange', 'FFFF00' : 'Gelb', '00FF00' : 'Lime', 'AFEEEE' : 'Blaß-Türkis', 'ADD8E6' : 'Hellblau', 'DDA0DD' : 'Pflaumenblau', 'D3D3D3' : 'Hellgrau', 'FFF0F5' : 'Lavendel', 'FAEBD7' : 'Antik Weiß', 'FFFFE0' : 'Hellgelb', 'F0FFF0' : 'Honigtau', 'F0FFFF' : 'Azurblau', 'F0F8FF' : 'Alice Blau', 'E6E6FA' : 'Lavendel', 'FFF' : 'Weiß' }, scayt : { title : 'Rechtschreibprüfung während der Texteingabe (SCAYT)', opera_title : 'Nicht von Opera unterstützt', enable : 'SCAYT einschalten', disable : 'SCAYT ausschalten', about : 'Über SCAYT', toggle : 'SCAYT umschalten', options : 'Optionen', langs : 'Sprachen', moreSuggestions : 'Mehr Vorschläge', ignore : 'Ignorieren', ignoreAll : 'Alle ignorieren', addWord : 'Wort hinzufügen', emptyDic : 'Wörterbuchname sollte leer sein.', optionsTab : 'Optionen', allCaps : 'Groß geschriebenen Wörter ignorieren', ignoreDomainNames : 'Domain-Namen ignorieren', mixedCase : 'Wörter mit gemischte Setzkasten ignorieren', mixedWithDigits : 'Wörter mit Zahlen ignorieren', languagesTab : 'Sprachen', dictionariesTab : 'Wörterbücher', dic_field_name : 'Wörterbuchname', dic_create : 'Erzeugen', dic_restore : 'Wiederherstellen', dic_delete : 'Löschen', dic_rename : 'Umbenennen', dic_info : 'Anfangs wird das Benutzerwörterbuch in einem Cookie gespeichert. Allerdings sind Cookies in der Größe begrenzt. Wenn das Benutzerwörterbuch bis zu einem Punkt wächst, wo es nicht mehr in einem Cookie gespeichert werden kann, wird das Benutzerwörterbuch auf dem Server gespeichert. Um Ihr persönliches Wörterbuch auf dem Server zu speichern, müssen Sie einen Namen für das Wörterbuch angeben. Falls Sie schon ein gespeicherte Wörterbuch haben, geben Sie bitte dessen Namen ein und klicken Sie auf die Schaltfläche Wiederherstellen.', aboutTab : 'Über' }, about : { title : 'Über CKEditor', dlgTitle : 'Über CKEditor', help : 'Prüfe $1 für Hilfe.', userGuide : 'CKEditor Benutzerhandbuch', moreInfo : 'Für Informationen über unsere Lizenzbestimmungen besuchen sie bitte unsere Webseite:', copy : 'Copyright &copy; $1. Alle Rechte vorbehalten.' }, maximize : 'Maximieren', minimize : 'Minimieren', fakeobjects : { anchor : 'Anker', flash : 'Flash Animation', iframe : 'IFrame', hiddenfield : 'Verstecktes Feld', unknown : 'Unbekanntes Objekt' }, resize : 'Zum Vergrößern ziehen', colordialog : { title : 'Farbe wählen', options : 'Farbeoptionen', highlight : 'Hervorheben', selected : 'Ausgewählte Farbe', clear : 'Entfernen' }, toolbarCollapse : 'Symbolleiste einklappen', toolbarExpand : 'Symbolleiste ausklappen', toolbarGroups : { document : 'Dokument', clipboard : 'Zwischenablage/Rückgängig', editing : 'Editieren', forms : 'Formularen', basicstyles : 'Grundstile', paragraph : 'Absatz', links : 'Links', insert : 'Einfügen', styles : 'Stile', colors : 'Farben', tools : 'Werkzeuge' }, bidi : { ltr : 'Leserichtung von Links nach Rechts', rtl : 'Leserichtung von Rechts nach Links' }, docprops : { label : 'Dokument-Eigenschaften', title : 'Dokument-Eigenschaften', design : 'Design', meta : 'Metadaten', chooseColor : 'Wählen', other : '<andere>', docTitle : 'Seitentitel', charset : 'Zeichenkodierung', charsetOther : 'Andere Zeichenkodierung', charsetASCII : 'ASCII', charsetCE : 'Zentraleuropäisch', charsetCT : 'traditionell Chinesisch (Big5)', charsetCR : 'Kyrillisch', charsetGR : 'Griechisch', charsetJP : 'Japanisch', charsetKR : 'Koreanisch', charsetTR : 'Türkisch', charsetUN : 'Unicode (UTF-8)', charsetWE : 'Westeuropäisch', docType : 'Dokumententyp', docTypeOther : 'Anderer Dokumententyp', xhtmlDec : 'Beziehe XHTML Deklarationen ein', bgColor : 'Hintergrundfarbe', bgImage : 'Hintergrundbild URL', bgFixed : 'feststehender Hintergrund', txtColor : 'Textfarbe', margin : 'Seitenränder', marginTop : 'Oben', marginLeft : 'Links', marginRight : 'Rechts', marginBottom : 'Unten', metaKeywords : 'Schlüsselwörter (durch Komma getrennt)', metaDescription : 'Dokument-Beschreibung', metaAuthor : 'Autor', metaCopyright : 'Copyright', previewHtml : '<p>Das ist ein <strong>Beispieltext</strong>. Du schreibst in <a href="javascript:void(0)">CKEditor</a>.</p>' } };
// Copyright 2006 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Drag Utilities. * * Provides extensible functionality for drag & drop behaviour. * * @see ../demos/drag.html * @see ../demos/dragger.html */ goog.provide('goog.fx.DragEvent'); goog.provide('goog.fx.Dragger'); goog.provide('goog.fx.Dragger.EventType'); goog.require('goog.dom'); goog.require('goog.events'); goog.require('goog.events.Event'); goog.require('goog.events.EventHandler'); goog.require('goog.events.EventTarget'); goog.require('goog.events.EventType'); goog.require('goog.math.Coordinate'); goog.require('goog.math.Rect'); goog.require('goog.style'); goog.require('goog.style.bidi'); goog.require('goog.userAgent'); /** * A class that allows mouse or touch-based dragging (moving) of an element * * @param {Element} target The element that will be dragged. * @param {Element=} opt_handle An optional handle to control the drag, if null * the target is used. * @param {goog.math.Rect=} opt_limits Object containing left, top, width, * and height. * * @extends {goog.events.EventTarget} * @constructor */ goog.fx.Dragger = function(target, opt_handle, opt_limits) { goog.events.EventTarget.call(this); this.target = target; this.handle = opt_handle || target; this.limits = opt_limits || new goog.math.Rect(NaN, NaN, NaN, NaN); this.document_ = goog.dom.getOwnerDocument(target); this.eventHandler_ = new goog.events.EventHandler(this); this.registerDisposable(this.eventHandler_); // Add listener. Do not use the event handler here since the event handler is // used for listeners added and removed during the drag operation. goog.events.listen(this.handle, [goog.events.EventType.TOUCHSTART, goog.events.EventType.MOUSEDOWN], this.startDrag, false, this); }; goog.inherits(goog.fx.Dragger, goog.events.EventTarget); /** * Whether setCapture is supported by the browser. * @type {boolean} * @private */ goog.fx.Dragger.HAS_SET_CAPTURE_ = // IE and Gecko after 1.9.3 has setCapture // WebKit does not yet: https://bugs.webkit.org/show_bug.cgi?id=27330 goog.userAgent.IE || goog.userAgent.GECKO && goog.userAgent.isVersionOrHigher('1.9.3'); /** * Constants for event names. * @enum {string} */ goog.fx.Dragger.EventType = { // The drag action was canceled before the START event. Possible reasons: // disabled dragger, dragging with the right mouse button or releasing the // button before reaching the hysteresis distance. EARLY_CANCEL: 'earlycancel', START: 'start', BEFOREDRAG: 'beforedrag', DRAG: 'drag', END: 'end' }; /** * Reference to drag target element. * @type {Element} */ goog.fx.Dragger.prototype.target; /** * Reference to the handler that initiates the drag. * @type {Element} */ goog.fx.Dragger.prototype.handle; /** * Object representing the limits of the drag region. * @type {goog.math.Rect} */ goog.fx.Dragger.prototype.limits; /** * Whether the element is rendered right-to-left. We initialize this lazily. * @type {boolean|undefined}} * @private */ goog.fx.Dragger.prototype.rightToLeft_; /** * Current x position of mouse or touch relative to viewport. * @type {number} */ goog.fx.Dragger.prototype.clientX = 0; /** * Current y position of mouse or touch relative to viewport. * @type {number} */ goog.fx.Dragger.prototype.clientY = 0; /** * Current x position of mouse or touch relative to screen. Deprecated because * it doesn't take into affect zoom level or pixel density. * @type {number} * @deprecated Consider switching to clientX instead. */ goog.fx.Dragger.prototype.screenX = 0; /** * Current y position of mouse or touch relative to screen. Deprecated because * it doesn't take into affect zoom level or pixel density. * @type {number} * @deprecated Consider switching to clientY instead. */ goog.fx.Dragger.prototype.screenY = 0; /** * The x position where the first mousedown or touchstart occurred. * @type {number} */ goog.fx.Dragger.prototype.startX = 0; /** * The y position where the first mousedown or touchstart occurred. * @type {number} */ goog.fx.Dragger.prototype.startY = 0; /** * Current x position of drag relative to target's parent. * @type {number} */ goog.fx.Dragger.prototype.deltaX = 0; /** * Current y position of drag relative to target's parent. * @type {number} */ goog.fx.Dragger.prototype.deltaY = 0; /** * The current page scroll value. * @type {goog.math.Coordinate} */ goog.fx.Dragger.prototype.pageScroll; /** * Whether dragging is currently enabled. * @type {boolean} * @private */ goog.fx.Dragger.prototype.enabled_ = true; /** * Whether object is currently being dragged. * @type {boolean} * @private */ goog.fx.Dragger.prototype.dragging_ = false; /** * The amount of distance, in pixels, after which a mousedown or touchstart is * considered a drag. * @type {number} * @private */ goog.fx.Dragger.prototype.hysteresisDistanceSquared_ = 0; /** * Timestamp of when the mousedown or touchstart occurred. * @type {number} * @private */ goog.fx.Dragger.prototype.mouseDownTime_ = 0; /** * Reference to a document object to use for the events. * @type {Document} * @private */ goog.fx.Dragger.prototype.document_; /** * The SCROLL event target used to make drag element follow scrolling. * @type {EventTarget} * @private */ goog.fx.Dragger.prototype.scrollTarget_; /** * Whether IE drag events cancelling is on. * @type {boolean} * @private */ goog.fx.Dragger.prototype.ieDragStartCancellingOn_ = false; /** * Whether the dragger implements the changes described in http://b/6324964, * making it truly RTL. This is a temporary flag to allow clients to transition * to the new behavior at their convenience. At some point it will be the * default. * @type {boolean} * @private */ goog.fx.Dragger.prototype.useRightPositioningForRtl_ = false; /** * Turns on/off true RTL behavior. This should be called immediately after * construction. This is a temporary flag to allow clients to transition * to the new component at their convenience. At some point true will be the * default. * @param {boolean} useRightPositioningForRtl True if "right" should be used for * positioning, false if "left" should be used for positioning. */ goog.fx.Dragger.prototype.enableRightPositioningForRtl = function(useRightPositioningForRtl) { this.useRightPositioningForRtl_ = useRightPositioningForRtl; }; /** * Returns the event handler, intended for subclass use. * @return {goog.events.EventHandler} The event handler. */ goog.fx.Dragger.prototype.getHandler = function() { return this.eventHandler_; }; /** * Sets (or reset) the Drag limits after a Dragger is created. * @param {goog.math.Rect?} limits Object containing left, top, width, * height for new Dragger limits. If target is right-to-left and * enableRightPositioningForRtl(true) is called, then rect is interpreted as * right, top, width, and height. */ goog.fx.Dragger.prototype.setLimits = function(limits) { this.limits = limits || new goog.math.Rect(NaN, NaN, NaN, NaN); }; /** * Sets the distance the user has to drag the element before a drag operation is * started. * @param {number} distance The number of pixels after which a mousedown and * move is considered a drag. */ goog.fx.Dragger.prototype.setHysteresis = function(distance) { this.hysteresisDistanceSquared_ = Math.pow(distance, 2); }; /** * Gets the distance the user has to drag the element before a drag operation is * started. * @return {number} distance The number of pixels after which a mousedown and * move is considered a drag. */ goog.fx.Dragger.prototype.getHysteresis = function() { return Math.sqrt(this.hysteresisDistanceSquared_); }; /** * Sets the SCROLL event target to make drag element follow scrolling. * * @param {EventTarget} scrollTarget The event target that dispatches SCROLL * events. */ goog.fx.Dragger.prototype.setScrollTarget = function(scrollTarget) { this.scrollTarget_ = scrollTarget; }; /** * Enables cancelling of built-in IE drag events. * @param {boolean} cancelIeDragStart Whether to enable cancelling of IE * dragstart event. */ goog.fx.Dragger.prototype.setCancelIeDragStart = function(cancelIeDragStart) { this.ieDragStartCancellingOn_ = cancelIeDragStart; }; /** * @return {boolean} Whether the dragger is enabled. */ goog.fx.Dragger.prototype.getEnabled = function() { return this.enabled_; }; /** * Set whether dragger is enabled * @param {boolean} enabled Whether dragger is enabled. */ goog.fx.Dragger.prototype.setEnabled = function(enabled) { this.enabled_ = enabled; }; /** @override */ goog.fx.Dragger.prototype.disposeInternal = function() { goog.fx.Dragger.superClass_.disposeInternal.call(this); goog.events.unlisten(this.handle, [goog.events.EventType.TOUCHSTART, goog.events.EventType.MOUSEDOWN], this.startDrag, false, this); this.cleanUpAfterDragging_(); this.target = null; this.handle = null; }; /** * Whether the DOM element being manipulated is rendered right-to-left. * @return {boolean} True if the DOM element is rendered right-to-left, false * otherwise. * @private */ goog.fx.Dragger.prototype.isRightToLeft_ = function() { if (!goog.isDef(this.rightToLeft_)) { this.rightToLeft_ = goog.style.isRightToLeft(this.target); } return this.rightToLeft_; }; /** * Event handler that is used to start the drag * @param {goog.events.BrowserEvent} e Event object. */ goog.fx.Dragger.prototype.startDrag = function(e) { var isMouseDown = e.type == goog.events.EventType.MOUSEDOWN; // Dragger.startDrag() can be called by AbstractDragDrop with a mousemove // event and IE does not report pressed mouse buttons on mousemove. Also, // it does not make sense to check for the button if the user is already // dragging. if (this.enabled_ && !this.dragging_ && (!isMouseDown || e.isMouseActionButton())) { this.maybeReinitTouchEvent_(e); if (this.hysteresisDistanceSquared_ == 0) { if (this.fireDragStart_(e)) { this.dragging_ = true; e.preventDefault(); } else { // If the start drag is cancelled, don't setup for a drag. return; } } else { // Need to preventDefault for hysteresis to prevent page getting selected. e.preventDefault(); } this.setupDragHandlers(); this.clientX = this.startX = e.clientX; this.clientY = this.startY = e.clientY; this.screenX = e.screenX; this.screenY = e.screenY; this.deltaX = this.useRightPositioningForRtl_ ? goog.style.bidi.getOffsetStart(this.target) : this.target.offsetLeft; this.deltaY = this.target.offsetTop; this.pageScroll = goog.dom.getDomHelper(this.document_).getDocumentScroll(); this.mouseDownTime_ = goog.now(); } else { this.dispatchEvent(goog.fx.Dragger.EventType.EARLY_CANCEL); } }; /** * Sets up event handlers when dragging starts. * @protected */ goog.fx.Dragger.prototype.setupDragHandlers = function() { var doc = this.document_; var docEl = doc.documentElement; // Use bubbling when we have setCapture since we got reports that IE has // problems with the capturing events in combination with setCapture. var useCapture = !goog.fx.Dragger.HAS_SET_CAPTURE_; this.eventHandler_.listen(doc, [goog.events.EventType.TOUCHMOVE, goog.events.EventType.MOUSEMOVE], this.handleMove_, useCapture); this.eventHandler_.listen(doc, [goog.events.EventType.TOUCHEND, goog.events.EventType.MOUSEUP], this.endDrag, useCapture); if (goog.fx.Dragger.HAS_SET_CAPTURE_) { docEl.setCapture(false); this.eventHandler_.listen(docEl, goog.events.EventType.LOSECAPTURE, this.endDrag); } else { // Make sure we stop the dragging if the window loses focus. // Don't use capture in this listener because we only want to end the drag // if the actual window loses focus. Since blur events do not bubble we use // a bubbling listener on the window. this.eventHandler_.listen(goog.dom.getWindow(doc), goog.events.EventType.BLUR, this.endDrag); } if (goog.userAgent.IE && this.ieDragStartCancellingOn_) { // Cancel IE's 'ondragstart' event. this.eventHandler_.listen(doc, goog.events.EventType.DRAGSTART, goog.events.Event.preventDefault); } if (this.scrollTarget_) { this.eventHandler_.listen(this.scrollTarget_, goog.events.EventType.SCROLL, this.onScroll_, useCapture); } }; /** * Fires a goog.fx.Dragger.EventType.START event. * @param {goog.events.BrowserEvent} e Browser event that triggered the drag. * @return {boolean} False iff preventDefault was called on the DragEvent. * @private */ goog.fx.Dragger.prototype.fireDragStart_ = function(e) { return this.dispatchEvent(new goog.fx.DragEvent( goog.fx.Dragger.EventType.START, this, e.clientX, e.clientY, e)); }; /** * Unregisters the event handlers that are only active during dragging, and * releases mouse capture. * @private */ goog.fx.Dragger.prototype.cleanUpAfterDragging_ = function() { this.eventHandler_.removeAll(); if (goog.fx.Dragger.HAS_SET_CAPTURE_) { this.document_.releaseCapture(); } }; /** * Event handler that is used to end the drag. * @param {goog.events.BrowserEvent} e Event object. * @param {boolean=} opt_dragCanceled Whether the drag has been canceled. */ goog.fx.Dragger.prototype.endDrag = function(e, opt_dragCanceled) { this.cleanUpAfterDragging_(); if (this.dragging_) { this.maybeReinitTouchEvent_(e); this.dragging_ = false; var x = this.limitX(this.deltaX); var y = this.limitY(this.deltaY); var dragCanceled = opt_dragCanceled || e.type == goog.events.EventType.TOUCHCANCEL; this.dispatchEvent(new goog.fx.DragEvent( goog.fx.Dragger.EventType.END, this, e.clientX, e.clientY, e, x, y, dragCanceled)); } else { this.dispatchEvent(goog.fx.Dragger.EventType.EARLY_CANCEL); } }; /** * Event handler that is used to end the drag by cancelling it. * @param {goog.events.BrowserEvent} e Event object. */ goog.fx.Dragger.prototype.endDragCancel = function(e) { this.endDrag(e, true); }; /** * Re-initializes the event with the first target touch event or, in the case * of a stop event, the last changed touch. * @param {goog.events.BrowserEvent} e A TOUCH... event. * @private */ goog.fx.Dragger.prototype.maybeReinitTouchEvent_ = function(e) { var type = e.type; if (type == goog.events.EventType.TOUCHSTART || type == goog.events.EventType.TOUCHMOVE) { e.init(e.getBrowserEvent().targetTouches[0], e.currentTarget); } else if (type == goog.events.EventType.TOUCHEND || type == goog.events.EventType.TOUCHCANCEL) { e.init(e.getBrowserEvent().changedTouches[0], e.currentTarget); } }; /** * Event handler that is used on mouse / touch move to update the drag * @param {goog.events.BrowserEvent} e Event object. * @private */ goog.fx.Dragger.prototype.handleMove_ = function(e) { if (this.enabled_) { this.maybeReinitTouchEvent_(e); // dx in right-to-left cases is relative to the right. var sign = this.useRightPositioningForRtl_ && this.isRightToLeft_() ? -1 : 1; var dx = sign * (e.clientX - this.clientX); var dy = e.clientY - this.clientY; this.clientX = e.clientX; this.clientY = e.clientY; this.screenX = e.screenX; this.screenY = e.screenY; if (!this.dragging_) { var diffX = this.startX - this.clientX; var diffY = this.startY - this.clientY; var distance = diffX * diffX + diffY * diffY; if (distance > this.hysteresisDistanceSquared_) { if (this.fireDragStart_(e)) { this.dragging_ = true; } else { // DragListGroup disposes of the dragger if BEFOREDRAGSTART is // canceled. if (!this.isDisposed()) { this.endDrag(e); } return; } } } var pos = this.calculatePosition_(dx, dy); var x = pos.x; var y = pos.y; if (this.dragging_) { var rv = this.dispatchEvent(new goog.fx.DragEvent( goog.fx.Dragger.EventType.BEFOREDRAG, this, e.clientX, e.clientY, e, x, y)); // Only do the defaultAction and dispatch drag event if predrag didn't // prevent default if (rv) { this.doDrag(e, x, y, false); e.preventDefault(); } } } }; /** * Calculates the drag position. * * @param {number} dx The horizontal movement delta. * @param {number} dy The vertical movement delta. * @return {goog.math.Coordinate} The newly calculated drag element position. * @private */ goog.fx.Dragger.prototype.calculatePosition_ = function(dx, dy) { // Update the position for any change in body scrolling var pageScroll = goog.dom.getDomHelper(this.document_).getDocumentScroll(); dx += pageScroll.x - this.pageScroll.x; dy += pageScroll.y - this.pageScroll.y; this.pageScroll = pageScroll; this.deltaX += dx; this.deltaY += dy; var x = this.limitX(this.deltaX); var y = this.limitY(this.deltaY); return new goog.math.Coordinate(x, y); }; /** * Event handler for scroll target scrolling. * @param {goog.events.BrowserEvent} e The event. * @private */ goog.fx.Dragger.prototype.onScroll_ = function(e) { var pos = this.calculatePosition_(0, 0); e.clientX = this.clientX; e.clientY = this.clientY; this.doDrag(e, pos.x, pos.y, true); }; /** * @param {goog.events.BrowserEvent} e The closure object * representing the browser event that caused a drag event. * @param {number} x The new horizontal position for the drag element. * @param {number} y The new vertical position for the drag element. * @param {boolean} dragFromScroll Whether dragging was caused by scrolling * the associated scroll target. * @protected */ goog.fx.Dragger.prototype.doDrag = function(e, x, y, dragFromScroll) { this.defaultAction(x, y); this.dispatchEvent(new goog.fx.DragEvent( goog.fx.Dragger.EventType.DRAG, this, e.clientX, e.clientY, e, x, y)); }; /** * Returns the 'real' x after limits are applied (allows for some * limits to be undefined). * @param {number} x X-coordinate to limit. * @return {number} The 'real' X-coordinate after limits are applied. */ goog.fx.Dragger.prototype.limitX = function(x) { var rect = this.limits; var left = !isNaN(rect.left) ? rect.left : null; var width = !isNaN(rect.width) ? rect.width : 0; var maxX = left != null ? left + width : Infinity; var minX = left != null ? left : -Infinity; return Math.min(maxX, Math.max(minX, x)); }; /** * Returns the 'real' y after limits are applied (allows for some * limits to be undefined). * @param {number} y Y-coordinate to limit. * @return {number} The 'real' Y-coordinate after limits are applied. */ goog.fx.Dragger.prototype.limitY = function(y) { var rect = this.limits; var top = !isNaN(rect.top) ? rect.top : null; var height = !isNaN(rect.height) ? rect.height : 0; var maxY = top != null ? top + height : Infinity; var minY = top != null ? top : -Infinity; return Math.min(maxY, Math.max(minY, y)); }; /** * Overridable function for handling the default action of the drag behaviour. * Normally this is simply moving the element to x,y though in some cases it * might be used to resize the layer. This is basically a shortcut to * implementing a default ondrag event handler. * @param {number} x X-coordinate for target element. In right-to-left, x this * is the number of pixels the target should be moved to from the right. * @param {number} y Y-coordinate for target element. */ goog.fx.Dragger.prototype.defaultAction = function(x, y) { if (this.useRightPositioningForRtl_ && this.isRightToLeft_()) { this.target.style.right = x + 'px'; } else { this.target.style.left = x + 'px'; } this.target.style.top = y + 'px'; }; /** * @return {boolean} Whether the dragger is currently in the midst of a drag. */ goog.fx.Dragger.prototype.isDragging = function() { return this.dragging_; }; /** * Object representing a drag event * @param {string} type Event type. * @param {goog.fx.Dragger} dragobj Drag object initiating event. * @param {number} clientX X-coordinate relative to the viewport. * @param {number} clientY Y-coordinate relative to the viewport. * @param {goog.events.BrowserEvent} browserEvent The closure object * representing the browser event that caused this drag event. * @param {number=} opt_actX Optional actual x for drag if it has been limited. * @param {number=} opt_actY Optional actual y for drag if it has been limited. * @param {boolean=} opt_dragCanceled Whether the drag has been canceled. * @constructor * @extends {goog.events.Event} */ goog.fx.DragEvent = function(type, dragobj, clientX, clientY, browserEvent, opt_actX, opt_actY, opt_dragCanceled) { goog.events.Event.call(this, type); /** * X-coordinate relative to the viewport * @type {number} */ this.clientX = clientX; /** * Y-coordinate relative to the viewport * @type {number} */ this.clientY = clientY; /** * The closure object representing the browser event that caused this drag * event. * @type {goog.events.BrowserEvent} */ this.browserEvent = browserEvent; /** * The real x-position of the drag if it has been limited * @type {number} */ this.left = goog.isDef(opt_actX) ? opt_actX : dragobj.deltaX; /** * The real y-position of the drag if it has been limited * @type {number} */ this.top = goog.isDef(opt_actY) ? opt_actY : dragobj.deltaY; /** * Reference to the drag object for this event * @type {goog.fx.Dragger} */ this.dragger = dragobj; /** * Whether drag was canceled with this event. Used to differentiate between * a legitimate drag END that can result in an action and a drag END which is * a result of a drag cancelation. For now it can happen 1) with drag END * event on FireFox when user drags the mouse out of the window, 2) with * drag END event on IE7 which is generated on MOUSEMOVE event when user * moves the mouse into the document after the mouse button has been * released, 3) when TOUCHCANCEL is raised instead of TOUCHEND (on touch * events). * @type {boolean} */ this.dragCanceled = !!opt_dragCanceled; }; goog.inherits(goog.fx.DragEvent, goog.events.Event);
//! moment.js locale configuration //! locale : Estonian [et] //! author : Henry Kehlmann : https://github.com/madhenry //! improvements : Illimar Tambek : https://github.com/ragulka import moment from '../moment'; function processRelativeTime(number, withoutSuffix, key, isFuture) { var format = { 's' : ['mõne sekundi', 'mõni sekund', 'paar sekundit'], 'm' : ['ühe minuti', 'üks minut'], 'mm': [number + ' minuti', number + ' minutit'], 'h' : ['ühe tunni', 'tund aega', 'üks tund'], 'hh': [number + ' tunni', number + ' tundi'], 'd' : ['ühe päeva', 'üks päev'], 'M' : ['kuu aja', 'kuu aega', 'üks kuu'], 'MM': [number + ' kuu', number + ' kuud'], 'y' : ['ühe aasta', 'aasta', 'üks aasta'], 'yy': [number + ' aasta', number + ' aastat'] }; if (withoutSuffix) { return format[key][2] ? format[key][2] : format[key][1]; } return isFuture ? format[key][0] : format[key][1]; } export default moment.defineLocale('et', { months : 'jaanuar_veebruar_märts_aprill_mai_juuni_juuli_august_september_oktoober_november_detsember'.split('_'), monthsShort : 'jaan_veebr_märts_apr_mai_juuni_juuli_aug_sept_okt_nov_dets'.split('_'), weekdays : 'pühapäev_esmaspäev_teisipäev_kolmapäev_neljapäev_reede_laupäev'.split('_'), weekdaysShort : 'P_E_T_K_N_R_L'.split('_'), weekdaysMin : 'P_E_T_K_N_R_L'.split('_'), longDateFormat : { LT : 'H:mm', LTS : 'H:mm:ss', L : 'DD.MM.YYYY', LL : 'D. MMMM YYYY', LLL : 'D. MMMM YYYY H:mm', LLLL : 'dddd, D. MMMM YYYY H:mm' }, calendar : { sameDay : '[Täna,] LT', nextDay : '[Homme,] LT', nextWeek : '[Järgmine] dddd LT', lastDay : '[Eile,] LT', lastWeek : '[Eelmine] dddd LT', sameElse : 'L' }, relativeTime : { future : '%s pärast', past : '%s tagasi', s : processRelativeTime, m : processRelativeTime, mm : processRelativeTime, h : processRelativeTime, hh : processRelativeTime, d : processRelativeTime, dd : '%d päeva', M : processRelativeTime, MM : processRelativeTime, y : processRelativeTime, yy : processRelativeTime }, ordinalParse: /\d{1,2}\./, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } });
/* AnythingSlider v1.4.5 By Chris Coyier: http://css-tricks.com with major improvements by Doug Neiner: http://pixelgraphics.us/ based on work by Remy Sharp: http://jqueryfordesigners.com/ To use the navigationFormatter function, you must have a function that accepts two paramaters, and returns a string of HTML text. index = integer index (1 based); panel = jQuery wrapped LI item this tab references @return = Must return a string of HTML/Text navigationFormatter: function(index, panel){ return "Panel #" + index; // This would have each tab with the text 'Panel #X' where X = index } */ (function($) { $.anythingSlider = function(el, options) { // To avoid scope issues, use 'base' instead of 'this' // to reference this class from internal events and functions. var base = this; // Wraps the ul in the necessary divs and then gives Access to jQuery element base.$el = $(el).addClass('anythingBase').wrap('<div class="anythingSlider"><div class="anythingWindow" /></div>'); // Add a reverse reference to the DOM object base.$el.data("AnythingSlider", base); base.init = function(){ base.options = $.extend({}, $.anythingSlider.defaults, options); // Cache existing DOM elements for later // base.$el = original ul // for wrap - get parent() then closest in case the ul has "anythingSlider" class base.$wrapper = base.$el.parent().closest('div.anythingSlider').addClass('noTransitions anythingSlider-' + base.options.theme); base.$window = base.$el.closest('div.anythingWindow').addClass('noTransitions'); base.$controls = $('<div class="anythingControls"></div>').appendTo(base.$wrapper); base.$items = base.$el.find('> li').addClass('panel'); base.$objects = base.$items.find('object'); // Set up a few defaults & get details base.currentPage = base.options.startPanel; base.pages = base.$items.length; base.timer = null; // slideshow timer (setInterval) container base.flag = false; // event flag to prevent multiple calls (used in control click/focusin) base.playing = false; // slideshow state base.hovered = false; // actively hovering over the slider base.hasObj = !!base.$objects.length; // embedded objects exist in the slider base.panelSize = []; // will contain dimensions and left position of each panel // Get index (run time) of this slider on the page base.runTimes = $('div.anythingSlider').index(base.$wrapper) + 1; // Make sure easing function exists. if (!$.isFunction($.easing[base.options.easing])) { base.options.easing = "swing"; } // Set up Theme if (base.options.theme != 'default') { if (!$('link[href*=' + base.options.theme + ']').length){ $('body').append('<link rel="stylesheet" href="' + base.options.themeDirectory.replace(/\{themeName\}/g, base.options.theme) + '" type="text/css" />'); } } // Set the dimensions if (base.options.resizeContents) { if (base.options.width) { base.$wrapper.add(base.$items).css('width', base.options.width); } if (base.options.height) { base.$wrapper.add(base.$items).css('height', base.options.height); } if (base.hasObj){ base.$objects.find('embed').andSelf().css({ width : '100%', height: '100%' }); } } // initialize youtube api - doesn't work in IE (someone have a solution?) base.$objects.each(function(){ if ($(this).find('[src*=youtube]').length){ $(this) .prepend('<param name="wmode" value="' + base.options.addWmodeToObject +'"/>') .parent().wrap('<div id="yt-temp"></div>') .find('embed[src*=youtube]').attr('src', function(i,s){ return s + '&enablejsapi=1&version=3'; }) .attr('wmode',base.options.addWmodeToObject).end() .find('param[value*=youtube]').attr('value', function(i,v){ return v + '&enablejsapi=1&version=3'; }).end() // detach/appendTo required for Chrome .detach() .appendTo($('#yt-temp')) .unwrap(); } }); // Remove navigation & player if there is only one page if (base.pages === 1) { base.options.autoPlay = false; base.options.buildNavigation = false; base.options.buildArrows = false; } // If autoPlay functionality is included, then initialize the settings if (base.options.autoPlay) { base.playing = !base.options.startStopped; // Sets the playing variable to false if startStopped is true base.buildAutoPlay(); } // Build the navigation base.buildNavigation(); // Top and tail the list with 'visible' number of items, top has the last section, and tail has the first // This supports the "infinite" scrolling, also ensures any cloned elements don't duplicate an ID base.$el.prepend( base.$items.filter(':last').clone().addClass('cloned').removeAttr('id') ); base.$el.append( base.$items.filter(':first').clone().addClass('cloned').removeAttr('id') ); // We just added two items, time to re-cache the list, then get the dimensions of each panel base.$items = base.$el.find('> li'); // reselect base.setDimensions(); if (!base.options.resizeContents) { $(window).load(function(){ base.setDimensions(); }); } // set dimensions after all images load // Build forwards/backwards buttons if (base.options.buildArrows) { base.buildNextBackButtons(); } // If pauseOnHover then add hover effects if (base.options.pauseOnHover) { base.$wrapper.hover(function() { if (base.playing) { base.$el.trigger('slideshow_paused', base); if ($.isFunction(base.options.onShowPause)) { base.options.onShowPause(base); } base.clearTimer(true); } }, function() { if (base.playing) { base.$el.trigger('slideshow_unpaused', base); if ($.isFunction(base.options.onShowUnpause)) { base.options.onShowUnpause(base); } base.startStop(base.playing, true); } }); } // If a hash can not be used to trigger the plugin, then go to start panel if ((base.options.hashTags === true && !base.gotoHash()) || base.options.hashTags === false) { base.setCurrentPage(base.options.startPanel, false); } // Fix tabbing through the page base.$items.find('a').focus(function(){ base.$items.find('.focusedLink').removeClass('focusedLink'); $(this).addClass('focusedLink'); base.$items.each(function(i){ if ($(this).find('a.focusedLink').length) { base.gotoPage(i); return false; } }); }); // Hide/Show navigation & play/stop controls base.slideControls(false); base.$wrapper.hover(function(e){ base.hovered = (e.type=="mouseenter") ? true : false; base.slideControls( base.hovered, false ); }); // Add keyboard navigation $(document).keyup(function(e){ if (base.$wrapper.is('.activeSlider')) { switch (e.which) { case 39: // right arrow base.goForward(); break; case 37: //left arrow base.goBack(); break; } } }); }; // Creates the numbered navigation links base.buildNavigation = function() { base.$nav = $('<ul class="thumbNav noTransitions" />').appendTo(base.$controls); if (base.options.playRtl) { base.$wrapper.addClass('rtl'); } if (base.options.buildNavigation && (base.pages > 1)) { base.$items.each(function(i,el) { var index = i + 1, $a = $("<a href='#'></a>").addClass('panel' + index).wrap("<li />"); base.$nav.append($a); // If a formatter function is present, use it if ($.isFunction(base.options.navigationFormatter)) { var tmp = base.options.navigationFormatter(index, $(this)); $a.html(tmp); // Add formatting to title attribute if text is hidden if (parseInt($a.css('text-indent'),10) < 0) { $a.addClass(base.options.tooltipClass).attr('title', tmp); } } else { $a.text(index); } $a.bind(base.options.clickControls, function(e) { if (!base.flag) { // prevent running functions twice (once for click, second time for focusin) base.flag = true; setTimeout(function(){ base.flag = false; }, 100); base.gotoPage(index); if (base.options.hashTags) { base.setHash('panel' + base.runTimes + '-' + index); } } e.preventDefault(); }); }); } }; // Creates the Forward/Backward buttons base.buildNextBackButtons = function() { base.$forward = $('<span class="arrow forward noTransitions"><a href="#">' + base.options.forwardText + '</a></span>'); base.$back = $('<span class="arrow back noTransitions"><a href="#">' + base.options.backText + '</a></span>'); // Bind to the forward and back buttons base.$back.bind(base.options.clickArrows, function(e) { base.goBack(); e.preventDefault(); }); base.$forward.bind(base.options.clickArrows, function(e) { base.goForward(); e.preventDefault(); }); // using tab to get to arrow links will show they have focus (outline is disabled in css) base.$back.add(base.$forward).find('a').bind('focusin focusout',function(){ $(this).toggleClass('hover'); }); // Append elements to page base.$wrapper.prepend(base.$forward).prepend(base.$back); base.$arrowWidth = base.$forward.width(); }; // Creates the Start/Stop button base.buildAutoPlay = function(){ base.$startStop = $("<a href='#' class='start-stop'></a>").html(base.playing ? base.options.stopText : base.options.startText); base.$controls.append(base.$startStop); base.$startStop .bind(base.options.clickSlideshow, function(e) { base.startStop(!base.playing); if (base.playing) { if (base.options.playRtl) { base.goBack(true); } else { base.goForward(true); } } e.preventDefault(); }) // show button has focus while tabbing .bind('focusin focusout',function(){ $(this).toggleClass('hover'); }); // Use the same setting, but trigger the start; base.startStop(base.playing); }; // Set panel dimensions to either resize content or adjust panel to content base.setDimensions = function(){ var w, h, c, cw, dw, leftEdge = 0, bww = base.$window.width(), winw = $(window).width(); base.$items.each(function(i){ c = $(this).children('*'); if (base.options.resizeContents){ // get viewport width & height from options (if set), or css w = parseInt(base.options.width,10) || bww; h = parseInt(base.options.height,10) || base.$window.height(); // resize panel $(this).css({ width: w, height: h }); // resize panel contents, if solitary (wrapped content or solitary image) if (c.length == 1){ c.css({ width: '100%', height: '100%' }); } } else { // get panel width & height and save it w = $(this).width(); // if not defined, it will return the width of the ul parent dw = (w >= winw) ? true : false; // width defined from css? if (c.length == 1 && dw){ cw = (c.width() >= winw) ? bww : c.width(); // get width of solitary child $(this).css('width', cw); // set width of panel c.css('max-width', cw); // set max width for all children w = cw; } w = (dw) ? base.options.width || bww : w; $(this).css('width', w); h = $(this).outerHeight(); // get height after setting width $(this).css('height', h); } base.panelSize[i] = [w,h,leftEdge]; leftEdge += w; }); // Set total width of slider, but don't go beyond the set max overall width (limited by Opera) base.$el.css('width', (leftEdge < base.options.maxOverallWidth) ? leftEdge : base.options.maxOverallWidth); }; base.gotoPage = function(page, autoplay) { if (typeof(page) === "undefined" || page === null) { page = base.options.startPage; base.setCurrentPage(base.options.startPage); } // pause YouTube videos before scrolling or prevent change if playing if (base.checkVideo(base.playing)) { return; } base.$el.trigger('slide_init', base); if ($.isFunction(base.options.onSlideInit)) { base.options.onSlideInit(base); } base.slideControls(true, false); // Just check for bounds if (page > base.pages + 1) { page = base.pages; } if (page < 0 ) { page = 1; } // When autoplay isn't passed, we stop the timer if (autoplay !== true) { autoplay = false; } // Stop the slider when we reach the last page, if the option stopAtEnd is set to true if (!autoplay || (base.options.stopAtEnd && page == base.pages)) { base.startStop(false); } base.$el.trigger('slide_begin', base); if ($.isFunction(base.options.onSlideBegin)) { base.options.onSlideBegin(base); } // resize slider if content size varies if (!base.options.resizeContents) { // animating the wrapper resize before the window prevents flickering in Firefox base.$wrapper.filter(':not(:animated)').animate( { width: base.panelSize[page][0], height: base.panelSize[page][1] }, { queue: false, duration: base.options.animationTime, easing: base.options.easing } ); } // Animate Slider base.$window.filter(':not(:animated)').animate( { scrollLeft : base.panelSize[page][2] }, { queue: false, duration: base.options.animationTime, easing: base.options.easing, complete: function(){ base.endAnimation(page); } } ); }; base.endAnimation = function(page){ if (page === 0) { base.$window.scrollLeft(base.panelSize[base.pages][2]); page = base.pages; } else if (page > base.pages) { // reset back to start position base.$window.scrollLeft(base.panelSize[1][2]); page = 1; } base.setCurrentPage(page, false); if (!base.hovered) { base.slideControls(false); } // continue YouTube video if in current panel if (base.hasObj){ var emb = base.$items.eq(base.currentPage).find('embed[src*=youtube]'); try { if (emb.length && $.isFunction(emb[0].getPlayerState) && emb[0].getPlayerState() > 0) { emb[0].playVideo(); } } catch(err) {} } base.$el.trigger('slide_complete', base); if ($.isFunction(base.options.onSlideComplete)) { // Added setTimeout (zero time) to ensure animation is complete... for some reason this code: // alert(base.$window.is(':animated')); // alerts true setTimeout(function(){ base.options.onSlideComplete(base); }, 0); } }; base.setCurrentPage = function(page, move) { // Set visual if (base.options.buildNavigation){ base.$nav.find('.cur').removeClass('cur'); base.$nav.find('a').eq(page - 1).addClass('cur'); } // Only change left if move does not equal false if (!move) { base.$wrapper.css({ // .add(base.$window) width: base.panelSize[page][0], height: base.panelSize[page][1] }); base.$wrapper.scrollLeft(0); // reset in case tabbing changed this scrollLeft base.$window.scrollLeft( base.panelSize[page][2] ); } // Update local variable base.currentPage = page; // Set current slider as active so keyboard navigation works properly if (!base.$wrapper.is('.activeSlider')){ $('.activeSlider').removeClass('activeSlider'); base.$wrapper.addClass('activeSlider'); } }; base.goForward = function(autoplay) { if (autoplay !== true) { autoplay = false; base.startStop(false); } base.gotoPage(base.currentPage + 1, autoplay); }; base.goBack = function(autoplay) { if (autoplay !== true) { autoplay = false; base.startStop(false); } base.gotoPage(base.currentPage - 1, autoplay); }; // This method tries to find a hash that matches panel-X // If found, it tries to find a matching item // If that is found as well, then that item starts visible base.gotoHash = function(){ var hash = window.location.hash.match(/^#?panel(\d+)-(\d+)$/); if (hash) { var panel = parseInt(hash[1],10); if (panel == base.runTimes) { var slide = parseInt(hash[2],10), $item = base.$items.filter(':eq(' + slide + ')'); if ($item.length !== 0) { base.setCurrentPage(slide, false); return true; } } } return false; // An item wasn't found; }; // Taken from AJAXY jquery.history Plugin base.setHash = function (hash){ // Write hash if ( typeof window.location.hash !== 'undefined' ) { if ( window.location.hash !== hash ) { window.location.hash = hash; } } else if ( location.hash !== hash ) { location.hash = hash; } // Done return hash; }; // <-- End AJAXY code // Slide controls (nav and play/stop button up or down base.slideControls = function(toggle, playing){ var dir = (toggle) ? 'slideDown' : 'slideUp', t1 = (toggle) ? 0 : base.options.animationTime, t2 = (toggle) ? base.options.animationTime: 0, sign = (toggle) ? 0 : 1; // 0 = visible, 1 = hidden if (base.options.toggleControls) { base.$controls.stop(true,true).delay(t1)[dir](base.options.animationTime/2).delay(t2); } if (base.options.toggleArrows) { if (!base.hovered && base.playing) { sign = 1; } base.$forward.stop(true,true).delay(t1).animate({ right: sign * base.$arrowWidth, opacity: t2 }, base.options.animationTime/2); base.$back.stop(true,true).delay(t1).animate({ left: sign * base.$arrowWidth, opacity: t2 }, base.options.animationTime/2); } }; base.clearTimer = function(paused){ // Clear the timer only if it is set if (base.timer) { window.clearInterval(base.timer); if (!paused) { base.$el.trigger('slideshow_stop', base); if ($.isFunction(base.options.onShowStop)) { base.options.onShowStop(base); } } } }; // Handles stopping and playing the slideshow // Pass startStop(false) to stop and startStop(true) to play base.startStop = function(playing, paused) { if (playing !== true) { playing = false; } // Default if not supplied is false if (playing && !paused) { base.$el.trigger('slideshow_start', base); if ($.isFunction(base.options.onShowStart)) { base.options.onShowStart(base); } } // Update variable base.playing = playing; // Toggle playing and text if (base.options.autoPlay) { base.$startStop.toggleClass('playing', playing).html( playing ? base.options.stopText : base.options.startText ); // add button text to title attribute if it is hidden by text-indent if (parseInt(base.$startStop.css('text-indent'),10) < 0) { base.$startStop.addClass(base.options.tooltipClass).attr('title', playing ? 'Stop' : 'Start'); } } if (playing){ base.clearTimer(true); // Just in case this was triggered twice in a row base.timer = window.setInterval(function() { // prevent autoplay if video is playing if (!base.checkVideo(playing)) { if (base.options.playRtl) { base.goBack(true); } else { base.goForward(true); } } }, base.options.delay); } else { base.clearTimer(); } }; base.checkVideo = function(playing){ // pause YouTube videos before scrolling? var emb, ps, stopAdvance = false; if (base.hasObj){ base.$objects.each(function(){ // this only works on youtube videos emb = $(this).find('embed[src*=youtube]'); try { if (emb.length && $.isFunction(emb[0].getPlayerState)) { // player states: unstarted (-1), ended (0), playing (1), paused (2), buffering (3), video cued (5). ps = emb[0].getPlayerState(); // if autoplay, video playing, video is in current panel and resume option are true, then don't advance if (playing && ps == 1 && base.$items.index(emb.closest('li')) == base.currentPage && base.options.resumeOnVideoEnd) { stopAdvance = true; } else { // pause video if not autoplaying (if already initialized) if (ps > 0) { emb[0].pauseVideo(); } } } } catch(err) {} }); } return stopAdvance; }; // Trigger the initialization base.init(); }; $.anythingSlider.defaults = { // Appearance width : null, // Override the default CSS width height : null, // Override the default CSS height resizeContents : true, // If true, solitary images/objects in the panel will expand to fit the viewport tooltipClass : 'tooltip', // Class added to navigation & start/stop button (text copied to title if it is hidden by a negative text indent) theme : 'default', // Theme name themeDirectory : 'css/theme-{themeName}.css', // Theme directory & filename {themeName} is replaced by the theme value above // Navigation startPanel : 1, // This sets the initial panel hashTags : true, // Should links change the hashtag in the URL? buildArrows : true, // If true, builds the forwards and backwards buttons toggleArrows : false, // If true, side navigation arrows will slide out on hovering & hide @ other times buildNavigation : true, // If true, builds a list of anchor links to link to each panel toggleControls : false, // if true, slide in controls (navigation + play/stop button) on hover and slide change, hide @ other times navigationFormatter : null, // Details at the top of the file on this use (advanced use) forwardText : "&raquo;", // Link text used to move the slider forward (hidden by CSS, replaced with arrow image) backText : "&laquo;", // Link text used to move the slider back (hidden by CSS, replace with arrow image) // Slideshow options autoPlay : true, // This turns off the entire slideshow FUNCTIONALY, not just if it starts running or not startStopped : false, // If autoPlay is on, this can force it to start stopped pauseOnHover : true, // If true & the slideshow is active, the slideshow will pause on hover resumeOnVideoEnd : true, // If true & the slideshow is active & a youtube video is playing, it will pause the autoplay until the video is complete stopAtEnd : false, // If true & the slideshow is active, the slideshow will stop on the last page playRtl : false, // If true, the slideshow will move right-to-left startText : "Start", // Start button text stopText : "Stop", // Stop button text delay : 3000, // How long between slideshow transitions in AutoPlay mode (in milliseconds) animationTime : 600, // How long the slideshow transition takes (in milliseconds) easing : "swing", // Anything other than "linear" or "swing" requires the easing plugin // Callbacks onShowStart : null, // Callback on slideshow start onShowStop : null, // Callback after slideshow stops onShowPause : null, // Callback when slideshow pauses onShowUnpause : null, // Callback when slideshow unpauses - may not trigger properly if user clicks on any controls onSlideInit : null, // Callback when slide initiates, before control animation onSlideBegin : null, // Callback before slide animates onSlideComplete : null, // Callback when slide completes // Interactivity clickArrows : "click", // Event used to activate arrow functionality (e.g. "click" or "mouseenter") clickControls : "click focusin", // Events used to activate navigation control functionality clickSlideshow : "click", // Event used to activate slideshow play/stop button // Misc options addWmodeToObject : "opaque", // If your slider has an embedded object, the script will automatically add a wmode parameter with this setting maxOverallWidth : 32766 // Max width (in pixels) of combined sliders (side-to-side); set to 32766 to prevent problems with Opera }; $.fn.anythingSlider = function(options) { // initialize the slider if ((typeof(options)).match('object|undefined')){ return this.each(function(i){ if ($(this).is('.anythingBase')) { return; } // prevent multiple initializations (new $.anythingSlider(this, options)); }); // If options is a number, process as an external link to page #: $(element).anythingSlider(#) } else if (/\d/.test(options) && !isNaN(options)) { return this.each(function(i) { var anySlide = $(this).data('AnythingSlider'); if (anySlide) { var page = (typeof(options) == "number") ? options : parseInt($.trim(options),10); // accepts " 2 " // ignore out of bound pages if ( page < 1 || page > anySlide.pages ) { return; } anySlide.gotoPage(page); } }); } }; })(jQuery);
YUI.add('uploader-html5', function (Y, NAME) { /** * This module provides a UI for file selection and multiple file upload capability using * HTML5 XMLHTTPRequest Level 2 as a transport engine. * The supported features include: automatic upload queue management, upload progress * tracking, drag-and-drop support, server response retrieval and error reporting. * * @module uploader-html5 */ // Shorthands for the external modules var substitute = Y.substitute, UploaderQueue = Y.Uploader.Queue; /** * This module provides a UI for file selection and multiple file upload capability using * HTML5 XMLHTTPRequest Level 2 as a transport engine. * @class UploaderHTML5 * @extends Widget * @constructor */ function UploaderHTML5(config) { UploaderHTML5.superclass.constructor.apply ( this, arguments ); } Y.UploaderHTML5 = Y.extend( UploaderHTML5, Y.Widget, { /** * Stored reference to the instance of the file input field used to * initiate the file selection dialog. * * @property _fileInputField * @type {Node} * @protected */ _fileInputField: null, /** * Stored reference to the click event binding of the `Select Files` * button. * * @property _buttonBinding * @type {EventHandle} * @protected */ _buttonBinding: null, /** * Stored reference to the instance of Uploader.Queue used to manage * the upload process. This is a read-only property that only exists * during an active upload process. Only one queue can be active at * a time; if an upload start is attempted while a queue is active, * it will be ignored. * * @property queue * @type {Y.Uploader.Queue} */ queue: null, // Y.UploaderHTML5 prototype /** * Construction logic executed during UploaderHTML5 instantiation. * * @method initializer * @protected */ initializer : function () { this._fileInputField = null; this.queue = null; this._buttonBinding = null; this._fileList = []; // Publish available events /** * Signals that files have been selected. * * @event fileselect * @param event {Event} The event object for the `fileselect` with the * following payload: * <dl> * <dt>fileList</dt> * <dd>An `Array` of files selected by the user, encapsulated * in Y.FileHTML5 objects.</dd> * </dl> */ this.publish("fileselect"); /** * Signals that an upload of multiple files has been started. * * @event uploadstart * @param event {Event} The event object for the `uploadstart`. */ this.publish("uploadstart"); /** * Signals that an upload of a specific file has started. * * @event fileuploadstart * @param event {Event} The event object for the `fileuploadstart` with the * following payload: * <dl> * <dt>file</dt> * <dd>A reference to the Y.File that dispatched the event.</dd> * <dt>originEvent</dt> * <dd>The original event dispatched by Y.File.</dd> * </dl> */ this.publish("fileuploadstart"); /** * Reports on upload progress of a specific file. * * @event uploadprogress * @param event {Event} The event object for the `uploadprogress` with the * following payload: * <dl> * <dt>file</dt> * <dd>The pointer to the instance of `Y.File` that dispatched the event.</dd> * <dt>bytesLoaded</dt> * <dd>The number of bytes of the file that has been uploaded</dd> * <dt>bytesTotal</dt> * <dd>The total number of bytes in the file</dd> * <dt>percentLoaded</dt> * <dd>The fraction of the file that has been uploaded, out of 100</dd> * <dt>originEvent</dt> * <dd>The original event dispatched by the HTML5 uploader</dd> * </dl> */ this.publish("uploadprogress"); /** * Reports on the total upload progress of the file list. * * @event totaluploadprogress * @param event {Event} The event object for the `totaluploadprogress` with the * following payload: * <dl> * <dt>bytesLoaded</dt> * <dd>The number of bytes of the file list that has been uploaded</dd> * <dt>bytesTotal</dt> * <dd>The total number of bytes in the file list</dd> * <dt>percentLoaded</dt> * <dd>The fraction of the file list that has been uploaded, out of 100</dd> * </dl> */ this.publish("totaluploadprogress"); /** * Signals that a single file upload has been completed. * * @event uploadcomplete * @param event {Event} The event object for the `uploadcomplete` with the * following payload: * <dl> * <dt>file</dt> * <dd>The pointer to the instance of `Y.File` whose upload has been completed.</dd> * <dt>originEvent</dt> * <dd>The original event fired by the SWF Uploader</dd> * <dt>data</dt> * <dd>Data returned by the server.</dd> * </dl> */ this.publish("uploadcomplete"); /** * Signals that the upload process of the entire file list has been completed. * * @event alluploadscomplete * @param event {Event} The event object for the `alluploadscomplete`. */ this.publish("alluploadscomplete"); /** * Signals that a error has occurred in a specific file's upload process. * * @event uploaderror * @param event {Event} The event object for the `uploaderror` with the * following payload: * <dl> * <dt>originEvent</dt> * <dd>The original error event fired by the HTML5 Uploader. </dd> * <dt>file</dt> * <dd>The pointer at the instance of Y.File that returned the error.</dd> * <dt>status</dt> * <dd>The status reported by the XMLHttpRequest object.</dd> * <dt>statusText</dt> * <dd>The statusText reported by the XMLHttpRequest object.</dd> * </dl> */ this.publish("uploaderror"); /** * Signals that a dragged object has entered into the uploader's associated drag-and-drop area. * * @event dragenter * @param event {Event} The event object for the `dragenter`. */ this.publish("dragenter"); /** * Signals that an object has been dragged over the uploader's associated drag-and-drop area. * * @event dragover * @param event {Event} The event object for the `dragover`. */ this.publish("dragover"); /** * Signals that an object has been dragged off of the uploader's associated drag-and-drop area. * * @event dragleave * @param event {Event} The event object for the `dragleave`. */ this.publish("dragleave"); /** * Signals that an object has been dropped over the uploader's associated drag-and-drop area. * * @event drop * @param event {Event} The event object for the `drop`. */ this.publish("drop"); }, /** * Create the DOM structure for the UploaderHTML5. * UploaderHTML5's DOM structure consists of a "Select Files" button that can * be replaced by the developer's widget of choice; and a hidden file input field * that is used to instantiate the File Select dialog. * * @method renderUI * @protected */ renderUI : function () { var boundingBox = this.get("boundingBox"), contentBox = this.get('contentBox'), selButton = this.get("selectFilesButton"); selButton.setStyles({width:"100%", height:"100%"}); contentBox.append(selButton); this._fileInputField = Y.Node.create(UploaderHTML5.HTML5FILEFIELD_TEMPLATE); contentBox.append(this._fileInputField); }, /** * Binds to the UploaderHTML5 UI and subscribes to the necessary events. * * @method bindUI * @protected */ bindUI : function () { this._bindSelectButton(); this._setMultipleFiles(); this._setFileFilters(); this._bindDropArea(); this._triggerEnabled(); this.after("multipleFilesChange", this._setMultipleFiles, this); this.after("fileFiltersChange", this._setFileFilters, this); this.after("enabledChange", this._triggerEnabled, this); this.after("selectFilesButtonChange", this._bindSelectButton, this); this.after("dragAndDropAreaChange", this._bindDropArea, this); this.after("tabIndexChange", function (ev) {this.get("selectFilesButton").set("tabIndex", this.get("tabIndex"));}, this); this._fileInputField.on("change", this._updateFileList, this); this.get("selectFilesButton").set("tabIndex", this.get("tabIndex")); }, /** * Recreates the file field to null out the previous list of files and * thus allow for an identical file list selection. * * @method _rebindFileField * @protected */ _rebindFileField : function () { this._fileInputField.remove(true); this._fileInputField = Y.Node.create(UploaderHTML5.HTML5FILEFIELD_TEMPLATE); this.get("contentBox").append(this._fileInputField); this._fileInputField.on("change", this._updateFileList, this); this._setMultipleFiles(); this._setFileFilters(); }, /** * Binds the specified drop area's drag and drop events to the * uploader's custom handler. * * @method _bindDropArea * @protected */ _bindDropArea : function (event) { var ev = event || {prevVal: null}; if (ev.prevVal !== null) { ev.prevVal.detach('drop', this._ddEventHandler); ev.prevVal.detach('dragenter', this._ddEventHandler); ev.prevVal.detach('dragover', this._ddEventHandler); ev.prevVal.detach('dragleave', this._ddEventHandler); } var ddArea = this.get("dragAndDropArea"); if (ddArea !== null) { ddArea.on('drop', this._ddEventHandler, this); ddArea.on('dragenter', this._ddEventHandler, this); ddArea.on('dragover', this._ddEventHandler, this); ddArea.on('dragleave', this._ddEventHandler, this); } }, /** * Binds the instantiation of the file select dialog to the current file select * control. * * @method _bindSelectButton * @protected */ _bindSelectButton : function () { this._buttonBinding = this.get("selectFilesButton").on("click", this.openFileSelectDialog, this); }, /** * Handles the drag and drop events from the uploader's specified drop * area. * * @method _ddEventHandler * @protected */ _ddEventHandler : function (event) { event.stopPropagation(); event.preventDefault(); switch (event.type) { case "dragenter": this.fire("dragenter"); break; case "dragover": this.fire("dragover"); break; case "dragleave": this.fire("dragleave"); break; case "drop": var newfiles = event._event.dataTransfer.files, parsedFiles = [], filterFunc = this.get("fileFilterFunction"); if (filterFunc) { Y.each(newfiles, function (value) { var newfile = new Y.FileHTML5(value); if (filterFunc(newfile)) { parsedFiles.push(newfile); } }); } else { Y.each(newfiles, function (value) { parsedFiles.push(new Y.FileHTML5(value)); }); } if (parsedFiles.length > 0) { var oldfiles = this.get("fileList"); this.set("fileList", this.get("appendNewFiles") ? oldfiles.concat(parsedFiles) : parsedFiles); this.fire("fileselect", {fileList: parsedFiles}); } this.fire("drop"); break; } }, /** * Adds or removes a specified state CSS class to the underlying uploader button. * * @method _setButtonClass * @protected * @param state {String} The name of the state enumerated in `buttonClassNames` attribute * from which to derive the needed class name. * @param add {Boolean} A Boolean indicating whether to add or remove the class. */ _setButtonClass : function (state, add) { if (add) { this.get("selectFilesButton").addClass(this.get("buttonClassNames")[state]); } else { this.get("selectFilesButton").removeClass(this.get("buttonClassNames")[state]); } }, /** * Syncs the state of the `multipleFiles` attribute between this class * and the file input field. * * @method _setMultipleFiles * @protected */ _setMultipleFiles : function () { if (this.get("multipleFiles") === true) { this._fileInputField.set("multiple", "multiple"); } else { this._fileInputField.set("multiple", ""); } }, /** * Syncs the state of the `fileFilters` attribute between this class * and the file input field. * * @method _setFileFilters * @protected */ _setFileFilters : function () { if (this.get("fileFilters").length > 0) { this._fileInputField.set("accept", this.get("fileFilters").join(",")); } else { this._fileInputField.set("accept", ""); } }, /** * Syncs the state of the `enabled` attribute between this class * and the underlying button. * * @method _triggerEnabled * @private */ _triggerEnabled : function () { if (this.get("enabled") && this._buttonBinding === null) { this._bindSelectButton(); this._setButtonClass("disabled", false); this.get("selectFilesButton").setAttribute("aria-disabled", "false"); } else if (!this.get("enabled") && this._buttonBinding) { this._buttonBinding.detach(); this._buttonBinding = null; this._setButtonClass("disabled", true); this.get("selectFilesButton").setAttribute("aria-disabled", "true"); } }, /** * Getter for the `fileList` attribute * * @method _getFileList * @private */ _getFileList : function (arr) { return this._fileList.concat(); }, /** * Setter for the `fileList` attribute * * @method _setFileList * @private */ _setFileList : function (val) { this._fileList = val.concat(); return this._fileList.concat(); }, /** * Adjusts the content of the `fileList` based on the results of file selection * and the `appendNewFiles` attribute. If the `appendNewFiles` attribute is true, * then selected files are appended to the existing list; otherwise, the list is * cleared and populated with the newly selected files. * * @method _updateFileList * @param ev {Event} The file selection event received from the uploader. * @protected */ _updateFileList : function (ev) { var newfiles = ev.target.getDOMNode().files, parsedFiles = [], filterFunc = this.get("fileFilterFunction"); if (filterFunc) { Y.each(newfiles, function (value) { var newfile = new Y.FileHTML5(value); if (filterFunc(newfile)) { parsedFiles.push(newfile); } }); } else { Y.each(newfiles, function (value) { parsedFiles.push(new Y.FileHTML5(value)); }); } if (parsedFiles.length > 0) { var oldfiles = this.get("fileList"); this.set("fileList", this.get("appendNewFiles") ? oldfiles.concat(parsedFiles) : parsedFiles ); this.fire("fileselect", {fileList: parsedFiles}); } this._rebindFileField(); }, /** * Handles and retransmits events fired by `Y.File` and `Y.Uploader.Queue`. * * @method _uploadEventHandler * @param event The event dispatched during the upload process. * @protected */ _uploadEventHandler : function (event) { switch (event.type) { case "file:uploadstart": this.fire("fileuploadstart", event); break; case "file:uploadprogress": this.fire("uploadprogress", event); break; case "uploaderqueue:totaluploadprogress": this.fire("totaluploadprogress", event); break; case "file:uploadcomplete": this.fire("uploadcomplete", event); break; case "uploaderqueue:alluploadscomplete": this.queue = null; this.fire("alluploadscomplete", event); break; case "file:uploaderror": case "uploaderqueue:uploaderror": this.fire("uploaderror", event); break; case "file:uploadcancel": case "uploaderqueue:uploadcancel": this.fire("uploadcancel", event); break; } }, /** * Opens the File Selection dialog by simulating a click on the file input field. * * @method openFileSelectDialog */ openFileSelectDialog : function () { var fileDomNode = this._fileInputField.getDOMNode(); if (fileDomNode.click) { fileDomNode.click(); } }, /** * Starts the upload of a specific file. * * @method upload * @param file {Y.File} Reference to the instance of the file to be uploaded. * @param url {String} The URL to upload the file to. * @param postVars {Object} (optional) A set of key-value pairs to send as variables along with the file upload HTTP request. * If not specified, the values from the attribute `postVarsPerFile` are used instead. */ upload : function (file, url, postvars) { var uploadURL = url || this.get("uploadURL"), postVars = postvars || this.get("postVarsPerFile"), fileId = file.get("id"); postVars = postVars.hasOwnProperty(fileId) ? postVars[fileId] : postVars; if (file instanceof Y.FileHTML5) { file.on("uploadstart", this._uploadEventHandler, this); file.on("uploadprogress", this._uploadEventHandler, this); file.on("uploadcomplete", this._uploadEventHandler, this); file.on("uploaderror", this._uploadEventHandler, this); file.on("uploadcancel", this._uploadEventHandler, this); file.startUpload(uploadURL, postVars, this.get("fileFieldName")); } }, /** * Starts the upload of all files on the file list, using an automated queue. * * @method uploadAll * @param url {String} The URL to upload the files to. * @param postVars {Object} (optional) A set of key-value pairs to send as variables along with the file upload HTTP request. * If not specified, the values from the attribute `postVarsPerFile` are used instead. */ uploadAll : function (url, postvars) { this.uploadThese(this.get("fileList"), url, postvars); }, /** * Starts the upload of the files specified in the first argument, using an automated queue. * * @method uploadThese * @param files {Array} The list of files to upload. * @param url {String} The URL to upload the files to. * @param postVars {Object} (optional) A set of key-value pairs to send as variables along with the file upload HTTP request. * If not specified, the values from the attribute `postVarsPerFile` are used instead. */ uploadThese : function (files, url, postvars) { if (!this.queue) { var uploadURL = url || this.get("uploadURL"), postVars = postvars || this.get("postVarsPerFile"); this.queue = new UploaderQueue({simUploads: this.get("simLimit"), errorAction: this.get("errorAction"), fileFieldName: this.get("fileFieldName"), fileList: files, uploadURL: uploadURL, perFileParameters: postVars, retryCount: this.get("retryCount"), uploadHeaders: this.get("uploadHeaders"), withCredentials: this.get("withCredentials") }); this.queue.on("uploadstart", this._uploadEventHandler, this); this.queue.on("uploadprogress", this._uploadEventHandler, this); this.queue.on("totaluploadprogress", this._uploadEventHandler, this); this.queue.on("uploadcomplete", this._uploadEventHandler, this); this.queue.on("alluploadscomplete", this._uploadEventHandler, this); this.queue.on("uploadcancel", this._uploadEventHandler, this); this.queue.on("uploaderror", this._uploadEventHandler, this); this.queue.startUpload(); this.fire("uploadstart"); } else if (this.queue._currentState === UploaderQueue.UPLOADING) { this.queue.set("perFileParameters", this.get("postVarsPerFile")); Y.each(files, function (file) { this.queue.addToQueueBottom(file); }, this); } } }, { /** * The template for the hidden file input field container. The file input field will only * accept clicks if its visibility is set to hidden (and will not if it's `display` value * is set to `none`) * * @property HTML5FILEFIELD_TEMPLATE * @type {String} * @static */ HTML5FILEFIELD_TEMPLATE: "<input type='file' style='visibility:hidden; width:0px; height: 0px;'>", /** * The template for the "Select Files" button. * * @property SELECT_FILES_BUTTON * @type {String} * @static * @default "<button type='button' class='yui3-button' role='button' aria-label='{selectButtonLabel}' tabindex='{tabIndex}'>{selectButtonLabel}</button>" */ SELECT_FILES_BUTTON: "<button type='button' class='yui3-button' role='button' aria-label='{selectButtonLabel}' tabindex='{tabIndex}'>{selectButtonLabel}</button>", /** * The static property reflecting the type of uploader that `Y.Uploader` * aliases. The UploaderHTML5 value is `"html5"`. * * @property TYPE * @type {String} * @static */ TYPE: "html5", /** * The identity of the widget. * * @property NAME * @type String * @default 'uploader' * @readOnly * @protected * @static */ NAME: "uploader", /** * Static property used to define the default attribute configuration of * the Widget. * * @property ATTRS * @type {Object} * @protected * @static */ ATTRS: { /** * A Boolean indicating whether newly selected files should be appended * to the existing file list, or whether they should replace it. * * @attribute appendNewFiles * @type {Boolean} * @default true */ appendNewFiles : { value: true }, /** * The names of CSS classes that correspond to different button states * of the "Select Files" control. These classes are assigned to the * "Select Files" control based on the configuration of the uploader. * Currently, the only class name used is that corresponding to the * `disabled` state of the uploader. Other button states should be managed * directly via CSS selectors. * <ul> * <li> <strong>`disabled`</strong>: the class corresponding to the disabled state * of the "Select Files" button.</li> * </ul> * @attribute buttonClassNames * @type {Object} * @default { * disabled: "yui3-button-disabled" * } */ buttonClassNames: { value: { "hover": "yui3-button-hover", "active": "yui3-button-active", "disabled": "yui3-button-disabled", "focus": "yui3-button-selected" } }, /** * The node that serves as the drop target for files. * * @attribute dragAndDropArea * @type {Node} * @default null */ dragAndDropArea: { value: null, setter: function (val) { return Y.one(val); } }, /** * A Boolean indicating whether the uploader is enabled or disabled for user input. * * @attribute enabled * @type {Boolean} * @default true */ enabled : { value: true }, /** * The action performed when an upload error occurs for a specific file being uploaded. * The possible values are: * <ul> * <li> <strong>`UploaderQueue.CONTINUE`</strong>: the error is ignored and the upload process is continued.</li> * <li> <strong>`UploaderQueue.STOP`</strong>: the upload process is stopped as soon as any other parallel file * uploads are finished.</li> * <li> <strong>`UploaderQueue.RESTART_ASAP`</strong>: the file is added back to the front of the queue.</li> * <li> <strong>`UploaderQueue.RESTART_AFTER`</strong>: the file is added to the back of the queue.</li> * </ul> * @attribute errorAction * @type {String} * @default UploaderQueue.CONTINUE */ errorAction: { value: "continue", validator: function (val, name) { return (val === UploaderQueue.CONTINUE || val === UploaderQueue.STOP || val === UploaderQueue.RESTART_ASAP || val === UploaderQueue.RESTART_AFTER); } }, /** * An array indicating what fileFilters should be applied to the file * selection dialog. Each element in the array should be a string * indicating the Media (MIME) type for the files that should be supported * for selection. The Media type strings should be properly formatted * or this parameter will be ignored. Examples of valid strings include: * "audio/*", "video/*", "application/pdf", etc. More information * on valid Media type strings is available here: * http://www.iana.org/assignments/media-types/index.html * @attribute fileFilters * @type {Array} * @default [] */ fileFilters: { value: [] }, /** * A filtering function that is applied to every file selected by the user. * The function receives the `Y.File` object and must return a Boolean value. * If a `false` value is returned, the file in question is not added to the * list of files to be uploaded. * Use this function to put limits on file sizes or check the file names for * correct extension, but make sure that a server-side check is also performed, * since any client-side restrictions are only advisory and can be circumvented. * * @attribute fileFilterFunction * @type {Function} * @default null */ fileFilterFunction: { value: null }, /** * A String specifying what should be the POST field name for the file * content in the upload request. * * @attribute fileFieldName * @type {String} * @default Filedata */ fileFieldName: { value: "Filedata" }, /** * The array of files to be uploaded. All elements in the array * must be instances of `Y.File` and be instantiated with an instance * of native JavaScript File() class. * * @attribute fileList * @type {Array} * @default [] */ fileList: { value: [], getter: "_getFileList", setter: "_setFileList" }, /** * A Boolean indicating whether multiple file selection is enabled. * * @attribute multipleFiles * @type {Boolean} * @default false */ multipleFiles: { value: false }, /** * An object, keyed by `fileId`, containing sets of key-value pairs * that should be passed as POST variables along with each corresponding * file. This attribute is only used if no POST variables are specifed * in the upload method call. * * @attribute postVarsPerFile * @type {Object} * @default {} */ postVarsPerFile: { value: {} }, /** * The label for the "Select Files" widget. This is the value that replaces the * `{selectButtonLabel}` token in the `SELECT_FILES_BUTTON` template. * * @attribute selectButtonLabel * @type {String} * @default "Select Files" */ selectButtonLabel: { value: "Select Files" }, /** * The widget that serves as the "Select Files control for the file uploader * * * @attribute selectFilesButton * @type {Node | Widget} * @default A standard HTML button with YUI CSS Button skin. */ selectFilesButton : { valueFn: function () { return Y.Node.create(substitute(Y.UploaderHTML5.SELECT_FILES_BUTTON, {selectButtonLabel: this.get("selectButtonLabel"), tabIndex: this.get("tabIndex")})); } }, /** * The number of files that can be uploaded * simultaneously if the automatic queue management * is used. This value can be in the range between 2 * and 5. * * @attribute simLimit * @type {Number} * @default 2 */ simLimit: { value: 2, validator: function (val, name) { return (val >= 1 && val <= 5); } }, /** * The URL to which file upload requested are POSTed. Only used if a different url is not passed to the upload method call. * * @attribute uploadURL * @type {String} * @default "" */ uploadURL: { value: "" }, /** * Additional HTTP headers that should be included * in the upload request. * * * @attribute uploadHeaders * @type {Object} * @default {} */ uploadHeaders: { value: {} }, /** * A Boolean that specifies whether the file should be * uploaded with the appropriate user credentials for the * domain. * * @attribute withCredentials * @type {Boolean} * @default true */ withCredentials: { value: true }, /** * The number of times to try re-uploading a file that failed to upload before * cancelling its upload. * * @attribute retryCount * @type {Number} * @default 3 */ retryCount: { value: 3 } } }); Y.UploaderHTML5.Queue = UploaderQueue; }, '@VERSION@', {"requires": ["widget", "node-event-simulate", "substitute", "file-html5", "uploader-queue"]});
'use strict'; angular.module("ngLocale", [], ["$provide", function($provide) { var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; function getDecimals(n) { n = n + ''; var i = n.indexOf('.'); return (i == -1) ? 0 : n.length - i - 1; } function getVF(n, opt_precision) { var v = opt_precision; if (undefined === v) { v = Math.min(getDecimals(n), 3); } var base = Math.pow(10, v); var f = ((n * base) | 0) % base; return {v: v, f: f}; } $provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": [ "AM", "PM" ], "DAY": [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ], "ERANAMES": [ "Before Christ", "Anno Domini" ], "ERAS": [ "BC", "AD" ], "FIRSTDAYOFWEEK": 0, "MONTH": [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ], "SHORTDAY": [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ], "SHORTMONTH": [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ], "STANDALONEMONTH": [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ], "WEEKENDRANGE": [ 5, 6 ], "fullDate": "EEEE, d MMMM y", "longDate": "d MMMM y", "medium": "d MMM y HH:mm:ss", "mediumDate": "d MMM y", "mediumTime": "HH:mm:ss", "short": "dd/MM/y HH:mm", "shortDate": "dd/MM/y", "shortTime": "HH:mm" }, "NUMBER_FORMATS": { "CURRENCY_SYM": "\u20ac", "DECIMAL_SEP": ",", "GROUP_SEP": ".", "PATTERNS": [ { "gSize": 3, "lgSize": 3, "maxFrac": 3, "minFrac": 0, "minInt": 1, "negPre": "-", "negSuf": "", "posPre": "", "posSuf": "" }, { "gSize": 3, "lgSize": 3, "maxFrac": 2, "minFrac": 2, "minInt": 1, "negPre": "-\u00a4\u00a0", "negSuf": "", "posPre": "\u00a4\u00a0", "posSuf": "" } ] }, "id": "en-at", "localeID": "en_AT", "pluralCat": function(n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;} }); }]);
/** * @author: Dennis Hernández * @webSite: http://djhvscf.github.io/Blog * @version: v1.0.0 * * @update zhixin wen <wenzhixin2010@gmail.com> */ !function ($) { 'use strict'; $.extend($.fn.bootstrapTable.defaults, { keyEvents: false }); var BootstrapTable = $.fn.bootstrapTable.Constructor, _init = BootstrapTable.prototype.init; BootstrapTable.prototype.init = function () { _init.apply(this, Array.prototype.slice.apply(arguments)); this.initKeyEvents(); }; BootstrapTable.prototype.initKeyEvents = function () { if (this.options.keyEvents) { var that = this; $(document).off('keydown').on('keydown', function (e) { var $search = that.$toolbar.find('.search input'), $refresh = that.$toolbar.find('button[name="refresh"]'), $toggle = that.$toolbar.find('button[name="toggle"]'), $paginationSwitch = that.$toolbar.find('button[name="paginationSwitch"]'); if (document.activeElement === $search.get(0)) { return true; } switch (e.keyCode) { case 83: //s if (!that.options.search) { return; } $search.focus(); return false; case 82: //r if (!that.options.showRefresh) { return; } $refresh.click(); return false; case 84: //t if (!that.options.showToggle) { return; } $toggle.click(); return false; case 80: //p if (!that.options.showPaginationSwitch) { return; } $paginationSwitch.click(); return false; case 37: // left if (!that.options.pagination) { return; } that.prevPage(); return false; case 39: // right if (!that.options.pagination) { return; } that.nextPage(); return; } }); } }; }(jQuery);
YUI.add('swf', function (Y, NAME) { /** * Embed a Flash applications in a standard manner and communicate with it * via External Interface. * @module swf */ var Event = Y.Event, SWFDetect = Y.SWFDetect, Lang = Y.Lang, uA = Y.UA, Node = Y.Node, Escape = Y.Escape, // private FLASH_CID = "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000", FLASH_TYPE = "application/x-shockwave-flash", FLASH_VER = "10.0.22", EXPRESS_INSTALL_URL = "http://fpdownload.macromedia.com/pub/flashplayer/update/current/swf/autoUpdater.swf?" + Math.random(), EVENT_HANDLER = "SWF.eventHandler", possibleAttributes = {align:"", allowFullScreen:"", allowNetworking:"", allowScriptAccess:"", base:"", bgcolor:"", loop:"", menu:"", name:"", play: "", quality:"", salign:"", scale:"", tabindex:"", wmode:""}; /** * The SWF utility is a tool for embedding Flash applications in HTML pages. * @module swf * @title SWF Utility * @requires event-custom, node, swfdetect */ /** * Creates the SWF instance and keeps the configuration data * * @class SWF * @augments Y.Event.Target * @constructor * @param {String|HTMLElement} id The id of the element, or the element itself that the SWF will be inserted into. * The width and height of the SWF will be set to the width and height of this container element. * @param {String} swfURL The URL of the SWF to be embedded into the page. * @param {Object} p_oAttributes (optional) Configuration parameters for the Flash application and values for Flashvars * to be passed to the SWF. The p_oAttributes object allows the following additional properties: * <dl> * <dt>version : String</dt> * <dd>The minimum version of Flash required on the user's machine.</dd> * <dt>fixedAttributes : Object</dt> * <dd>An object literal containing one or more of the following String keys and their values: <code>align, * allowFullScreen, allowNetworking, allowScriptAccess, base, bgcolor, menu, name, quality, salign, scale, * tabindex, wmode.</code> event from the thumb</dd> * </dl> */ function SWF (p_oElement /*:String*/, swfURL /*:String*/, p_oAttributes /*:Object*/ ) { this._id = Y.guid("yuiswf"); var _id = this._id; var oElement = Node.one(p_oElement); var p_oAttributes = p_oAttributes || {}; var flashVersion = p_oAttributes.version || FLASH_VER; var flashVersionSplit = (flashVersion + '').split("."); var isFlashVersionRight = SWFDetect.isFlashVersionAtLeast(parseInt(flashVersionSplit[0], 10), parseInt(flashVersionSplit[1], 10), parseInt(flashVersionSplit[2], 10)); var canExpressInstall = (SWFDetect.isFlashVersionAtLeast(8,0,0)); var shouldExpressInstall = canExpressInstall && !isFlashVersionRight && p_oAttributes.useExpressInstall; var flashURL = (shouldExpressInstall)?EXPRESS_INSTALL_URL:swfURL; var objstring = '<object '; var w, h; var flashvarstring = "yId=" + Y.id + "&YUISwfId=" + _id + "&YUIBridgeCallback=" + EVENT_HANDLER + "&allowedDomain=" + document.location.hostname; Y.SWF._instances[_id] = this; if (oElement && (isFlashVersionRight || shouldExpressInstall) && flashURL) { objstring += 'id="' + _id + '" '; if (uA.ie) { objstring += 'classid="' + FLASH_CID + '" '; } else { objstring += 'type="' + FLASH_TYPE + '" data="' + Escape.html(flashURL) + '" '; } w = "100%"; h = "100%"; objstring += 'width="' + w + '" height="' + h + '">'; if (uA.ie) { objstring += '<param name="movie" value="' + Escape.html(flashURL) + '"/>'; } for (var attribute in p_oAttributes.fixedAttributes) { if (possibleAttributes.hasOwnProperty(attribute)) { objstring += '<param name="' + Escape.html(attribute) + '" value="' + Escape.html(p_oAttributes.fixedAttributes[attribute]) + '"/>'; } } for (var flashvar in p_oAttributes.flashVars) { var fvar = p_oAttributes.flashVars[flashvar]; if (Lang.isString(fvar)) { flashvarstring += "&" + Escape.html(flashvar) + "=" + Escape.html(encodeURIComponent(fvar)); } } if (flashvarstring) { objstring += '<param name="flashVars" value="' + flashvarstring + '"/>'; } objstring += "</object>"; //using innerHTML as setHTML/setContent causes some issues with ExternalInterface for IE versions of the player oElement.set("innerHTML", objstring); this._swf = Node.one("#" + _id); } else { /** * Fired when the Flash player version on the user's machine is * below the required value. * * @event wrongflashversion */ var event = {}; event.type = "wrongflashversion"; this.publish("wrongflashversion", {fireOnce:true}); this.fire("wrongflashversion", event); } } /** * @private * The static collection of all instances of the SWFs on the page. * @property _instances * @type Object */ SWF._instances = SWF._instances || {}; /** * @private * Handles an event coming from within the SWF and delegate it * to a specific instance of SWF. * @method eventHandler * @param swfid {String} the id of the SWF dispatching the event * @param event {Object} the event being transmitted. */ SWF.eventHandler = function (swfid, event) { SWF._instances[swfid]._eventHandler(event); }; SWF.prototype = { /** * @private * Propagates a specific event from Flash to JS. * @method _eventHandler * @param event {Object} The event to be propagated from Flash. */ _eventHandler: function(event) { if (event.type === "swfReady") { this.publish("swfReady", {fireOnce:true}); this.fire("swfReady", event); } else if(event.type === "log") { Y.log(event.message, event.category, this.toString()); } else { this.fire(event.type, event); } }, /** * Calls a specific function exposed by the SWF's * ExternalInterface. * @method callSWF * @param func {String} the name of the function to call * @param args {Array} the set of arguments to pass to the function. */ callSWF: function (func, args) { if (!args) { args= []; } if (this._swf._node[func]) { return(this._swf._node[func].apply(this._swf._node, args)); } else { return null; } }, /** * Public accessor to the unique name of the SWF instance. * * @method toString * @return {String} Unique name of the SWF instance. */ toString: function() { return "SWF " + this._id; } }; Y.augment(SWF, Y.EventTarget); Y.SWF = SWF; }, '@VERSION@', {"requires": ["event-custom", "node", "swfdetect", "escape"]});
/** * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * https://raw.github.com/facebook/regenerator/master/LICENSE file. An * additional grant of patent rights can be found in the PATENTS file in * the same directory. */ "use strict"; var _Symbol = require("babel-runtime/core-js/symbol")["default"]; var _Object$create = require("babel-runtime/core-js/object/create")["default"]; var _Object$setPrototypeOf = require("babel-runtime/core-js/object/set-prototype-of")["default"]; var _Promise = require("babel-runtime/core-js/promise")["default"]; !(function (global) { "use strict"; var hasOwn = Object.prototype.hasOwnProperty; var undefined; // More compressible than void 0. var $Symbol = typeof _Symbol === "function" ? _Symbol : {}; var iteratorSymbol = $Symbol.iterator || "@@iterator"; var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; var inModule = typeof module === "object"; var runtime = global.regeneratorRuntime; if (runtime) { if (inModule) { // If regeneratorRuntime is defined globally and we're in a module, // make the exports object identical to regeneratorRuntime. module.exports = runtime; } // Don't bother evaluating the rest of this file if the runtime was // already defined globally. return; } // Define the runtime globally (as expected by generated code) as either // module.exports (if we're in a module) or a new, empty object. runtime = global.regeneratorRuntime = inModule ? module.exports : {}; function wrap(innerFn, outerFn, self, tryLocsList) { // If outerFn provided, then outerFn.prototype instanceof Generator. var generator = _Object$create((outerFn || Generator).prototype); var context = new Context(tryLocsList || []); // The ._invoke method unifies the implementations of the .next, // .throw, and .return methods. generator._invoke = makeInvokeMethod(innerFn, self, context); return generator; } runtime.wrap = wrap; // Try/catch helper to minimize deoptimizations. Returns a completion // record like context.tryEntries[i].completion. This interface could // have been (and was previously) designed to take a closure to be // invoked without arguments, but in all the cases we care about we // already have an existing method we want to call, so there's no need // to create a new function object. We can even get away with assuming // the method takes exactly one argument, since that happens to be true // in every case, so we don't have to touch the arguments object. The // only additional allocation required is the completion record, which // has a stable shape and so hopefully should be cheap to allocate. function tryCatch(fn, obj, arg) { try { return { type: "normal", arg: fn.call(obj, arg) }; } catch (err) { return { type: "throw", arg: err }; } } var GenStateSuspendedStart = "suspendedStart"; var GenStateSuspendedYield = "suspendedYield"; var GenStateExecuting = "executing"; var GenStateCompleted = "completed"; // Returning this object from the innerFn has the same effect as // breaking out of the dispatch switch statement. var ContinueSentinel = {}; // Dummy constructor functions that we use as the .constructor and // .constructor.prototype properties for functions that return Generator // objects. For full spec compliance, you may wish to configure your // minifier not to mangle the names of these two functions. function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype; GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype; GeneratorFunctionPrototype.constructor = GeneratorFunction; GeneratorFunctionPrototype[toStringTagSymbol] = GeneratorFunction.displayName = "GeneratorFunction"; // Helper for defining the .next, .throw, and .return methods of the // Iterator interface in terms of a single ._invoke method. function defineIteratorMethods(prototype) { ["next", "throw", "return"].forEach(function (method) { prototype[method] = function (arg) { return this._invoke(method, arg); }; }); } runtime.isGeneratorFunction = function (genFun) { var ctor = typeof genFun === "function" && genFun.constructor; return ctor ? ctor === GeneratorFunction || // For the native GeneratorFunction constructor, the best we can // do is to check its .name property. (ctor.displayName || ctor.name) === "GeneratorFunction" : false; }; runtime.mark = function (genFun) { if (_Object$setPrototypeOf) { _Object$setPrototypeOf(genFun, GeneratorFunctionPrototype); } else { genFun.__proto__ = GeneratorFunctionPrototype; if (!(toStringTagSymbol in genFun)) { genFun[toStringTagSymbol] = "GeneratorFunction"; } } genFun.prototype = _Object$create(Gp); return genFun; }; // Within the body of any async function, `await x` is transformed to // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test // `value instanceof AwaitArgument` to determine if the yielded value is // meant to be awaited. Some may consider the name of this method too // cutesy, but they are curmudgeons. runtime.awrap = function (arg) { return new AwaitArgument(arg); }; function AwaitArgument(arg) { this.arg = arg; } function AsyncIterator(generator) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if (record.type === "throw") { reject(record.arg); } else { var result = record.arg; var value = result.value; if (value instanceof AwaitArgument) { return _Promise.resolve(value.arg).then(function (value) { invoke("next", value, resolve, reject); }, function (err) { invoke("throw", err, resolve, reject); }); } return _Promise.resolve(value).then(function (unwrapped) { // When a yielded Promise is resolved, its final value becomes // the .value of the Promise<{value,done}> result for the // current iteration. If the Promise is rejected, however, the // result for this iteration will be rejected with the same // reason. Note that rejections of yielded Promises are not // thrown back into the generator function, as is the case // when an awaited Promise is rejected. This difference in // behavior between yield and await is important, because it // allows the consumer to decide what to do with the yielded // rejection (swallow it and continue, manually .throw it back // into the generator, abandon iteration, whatever). With // await, by contrast, there is no opportunity to examine the // rejection reason outside the generator function, so the // only option is to throw it from the await expression, and // let the generator function handle the exception. result.value = unwrapped; resolve(result); }, reject); } } if (typeof process === "object" && process.domain) { invoke = process.domain.bind(invoke); } var previousPromise; function enqueue(method, arg) { function callInvokeWithMethodAndArg() { return new _Promise(function (resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = // If enqueue has been called before, then we want to wait until // all previous Promises have been resolved before calling invoke, // so that results are always delivered in the correct order. If // enqueue has not been called before, then it is important to // call invoke immediately, without waiting on a callback to fire, // so that the async generator function has the opportunity to do // any necessary setup in a predictable way. This predictability // is why the Promise constructor synchronously invokes its // executor callback, and why async functions synchronously // execute code before the first await. Since we implement simple // async functions in terms of async generators, it is especially // important to get this right, even though it requires care. previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, // Avoid propagating failures to Promises returned by later // invocations of the iterator. callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } // Define the unified helper method that is used to implement .next, // .throw, and .return (see defineIteratorMethods). this._invoke = enqueue; } defineIteratorMethods(AsyncIterator.prototype); // Note that simple async functions are implemented on top of // AsyncIterator objects; they just return a Promise for the value of // the final result produced by the iterator. runtime.async = function (innerFn, outerFn, self, tryLocsList) { var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList)); return runtime.isGeneratorFunction(outerFn) ? iter // If outerFn is a generator, return the full iterator. : iter.next().then(function (result) { return result.done ? result.value : iter.next(); }); }; function makeInvokeMethod(innerFn, self, context) { var state = GenStateSuspendedStart; return function invoke(method, arg) { if (state === GenStateExecuting) { throw new Error("Generator is already running"); } if (state === GenStateCompleted) { if (method === "throw") { throw arg; } // Be forgiving, per 25.3.3.3.3 of the spec: // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume return doneResult(); } while (true) { var delegate = context.delegate; if (delegate) { if (method === "return" || method === "throw" && delegate.iterator[method] === undefined) { // A return or throw (when the delegate iterator has no throw // method) always terminates the yield* loop. context.delegate = null; // If the delegate iterator has a return method, give it a // chance to clean up. var returnMethod = delegate.iterator["return"]; if (returnMethod) { var record = tryCatch(returnMethod, delegate.iterator, arg); if (record.type === "throw") { // If the return method threw an exception, let that // exception prevail over the original return or throw. method = "throw"; arg = record.arg; continue; } } if (method === "return") { // Continue with the outer return, now that the delegate // iterator has been terminated. continue; } } var record = tryCatch(delegate.iterator[method], delegate.iterator, arg); if (record.type === "throw") { context.delegate = null; // Like returning generator.throw(uncaught), but without the // overhead of an extra function call. method = "throw"; arg = record.arg; continue; } // Delegate generator ran and handled its own exceptions so // regardless of what the method was, we continue as if it is // "next" with an undefined arg. method = "next"; arg = undefined; var info = record.arg; if (info.done) { context[delegate.resultName] = info.value; context.next = delegate.nextLoc; } else { state = GenStateSuspendedYield; return info; } context.delegate = null; } if (method === "next") { if (state === GenStateSuspendedYield) { context.sent = arg; } else { context.sent = undefined; } } else if (method === "throw") { if (state === GenStateSuspendedStart) { state = GenStateCompleted; throw arg; } if (context.dispatchException(arg)) { // If the dispatched exception was caught by a catch block, // then let that catch block handle the exception normally. method = "next"; arg = undefined; } } else if (method === "return") { context.abrupt("return", arg); } state = GenStateExecuting; var record = tryCatch(innerFn, self, context); if (record.type === "normal") { // If an exception is thrown from innerFn, we leave state === // GenStateExecuting and loop back for another invocation. state = context.done ? GenStateCompleted : GenStateSuspendedYield; var info = { value: record.arg, done: context.done }; if (record.arg === ContinueSentinel) { if (context.delegate && method === "next") { // Deliberately forget the last sent value so that we don't // accidentally pass it on to the delegate. arg = undefined; } } else { return info; } } else if (record.type === "throw") { state = GenStateCompleted; // Dispatch the exception by looping back around to the // context.dispatchException(arg) call above. method = "throw"; arg = record.arg; } } }; } // Define Generator.prototype.{next,throw,return} in terms of the // unified ._invoke helper method. defineIteratorMethods(Gp); Gp[iteratorSymbol] = function () { return this; }; Gp[toStringTagSymbol] = "Generator"; Gp.toString = function () { return "[object Generator]"; }; function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; if (1 in locs) { entry.catchLoc = locs[1]; } if (2 in locs) { entry.finallyLoc = locs[2]; entry.afterLoc = locs[3]; } this.tryEntries.push(entry); } function resetTryEntry(entry) { var record = entry.completion || {}; record.type = "normal"; delete record.arg; entry.completion = record; } function Context(tryLocsList) { // The root entry object (effectively a try statement without a catch // or a finally block) gives us a place to store values thrown from // locations where there is no enclosing try statement. this.tryEntries = [{ tryLoc: "root" }]; tryLocsList.forEach(pushTryEntry, this); this.reset(true); } runtime.keys = function (object) { var keys = []; for (var key in object) { keys.push(key); } keys.reverse(); // Rather than returning an object with a next method, we keep // things simple and return the next function itself. return function next() { while (keys.length) { var key = keys.pop(); if (key in object) { next.value = key; next.done = false; return next; } } // To avoid creating an additional object, we just hang the .value // and .done properties off the next function object itself. This // also ensures that the minifier will not anonymize the function. next.done = true; return next; }; }; function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) { return iteratorMethod.call(iterable); } if (typeof iterable.next === "function") { return iterable; } if (!isNaN(iterable.length)) { var i = -1, next = function next() { while (++i < iterable.length) { if (hasOwn.call(iterable, i)) { next.value = iterable[i]; next.done = false; return next; } } next.value = undefined; next.done = true; return next; }; return next.next = next; } } // Return an iterator with no values. return { next: doneResult }; } runtime.values = values; function doneResult() { return { value: undefined, done: true }; } Context.prototype = { constructor: Context, reset: function reset(skipTempReset) { this.prev = 0; this.next = 0; this.sent = undefined; this.done = false; this.delegate = null; this.tryEntries.forEach(resetTryEntry); if (!skipTempReset) { for (var name in this) { // Not sure about the optimal order of these conditions: if (name.charAt(0) === "t" && hasOwn.call(this, name) && !isNaN(+name.slice(1))) { this[name] = undefined; } } } }, stop: function stop() { this.done = true; var rootEntry = this.tryEntries[0]; var rootRecord = rootEntry.completion; if (rootRecord.type === "throw") { throw rootRecord.arg; } return this.rval; }, dispatchException: function dispatchException(exception) { if (this.done) { throw exception; } var context = this; function handle(loc, caught) { record.type = "throw"; record.arg = exception; context.next = loc; return !!caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; var record = entry.completion; if (entry.tryLoc === "root") { // Exception thrown outside of any try block that could handle // it, so set the completion value of the entire function to // throw the exception. return handle("end"); } if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, "catchLoc"); var hasFinally = hasOwn.call(entry, "finallyLoc"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) { return handle(entry.catchLoc, true); } else if (this.prev < entry.finallyLoc) { return handle(entry.finallyLoc); } } else if (hasCatch) { if (this.prev < entry.catchLoc) { return handle(entry.catchLoc, true); } } else if (hasFinally) { if (this.prev < entry.finallyLoc) { return handle(entry.finallyLoc); } } else { throw new Error("try statement without catch or finally"); } } } }, abrupt: function abrupt(type, arg) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { var finallyEntry = entry; break; } } if (finallyEntry && (type === "break" || type === "continue") && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc) { // Ignore the finally entry if control is not jumping to a // location outside the try/catch block. finallyEntry = null; } var record = finallyEntry ? finallyEntry.completion : {}; record.type = type; record.arg = arg; if (finallyEntry) { this.next = finallyEntry.finallyLoc; } else { this.complete(record); } return ContinueSentinel; }, complete: function complete(record, afterLoc) { if (record.type === "throw") { throw record.arg; } if (record.type === "break" || record.type === "continue") { this.next = record.arg; } else if (record.type === "return") { this.rval = record.arg; this.next = "end"; } else if (record.type === "normal" && afterLoc) { this.next = afterLoc; } }, finish: function finish(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) { this.complete(entry.completion, entry.afterLoc); resetTryEntry(entry); return ContinueSentinel; } } }, "catch": function _catch(tryLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc === tryLoc) { var record = entry.completion; if (record.type === "throw") { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } // The context.catch method must only be called with a location // argument that corresponds to a known catch block. throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(iterable, resultName, nextLoc) { this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }; return ContinueSentinel; } }; })( // Among the various tricks for obtaining a reference to the global // object, this seems to be the most reliable technique that does not // use indirect eval (which violates Content Security Policy). typeof global === "object" ? global : typeof window === "object" ? window : typeof self === "object" ? self : undefined);
/* Copyright (c) 2006-2010 by OpenLayers Contributors (see authors.txt for * full list of contributors). Published under the Clear BSD license. * See http://svn.openlayers.org/trunk/openlayers/license.txt for the * full text of the license. */ /** * @requires OpenLayers/Layer/Grid.js * @requires OpenLayers/Tile/Image.js * @requires OpenLayers/Format/ArcXML.js * @requires OpenLayers/Request.js */ /** * Class: OpenLayers.Layer.ArcIMS * Instances of OpenLayers.Layer.ArcIMS are used to display data from ESRI ArcIMS * Mapping Services. Create a new ArcIMS layer with the <OpenLayers.Layer.ArcIMS> * constructor. * * Inherits from: * - <OpenLayers.Layer.Grid> */ OpenLayers.Layer.ArcIMS = OpenLayers.Class(OpenLayers.Layer.Grid, { /** * Constant: DEFAULT_PARAMS * {Object} Default query string parameters. */ DEFAULT_PARAMS: { ClientVersion: "9.2", ServiceName: '' }, /** * APIProperty: tileSize * {<OpenLayers.Size>} Size for tiles. Default is 512x512. */ tileSize: null, /** * APIProperty: featureCoordSys * {String} Code for feature coordinate system. Default is "4326". */ featureCoordSys: "4326", /** * APIProperty: filterCoordSys * {String} Code for filter coordinate system. Default is "4326". */ filterCoordSys: "4326", /** * APIProperty: layers * {Array} An array of objects with layer properties. */ layers: null, /** * APIProperty: async * {Boolean} Request images asynchronously. Default is true. */ async: true, /** * APIProperty: name * {String} Layer name. Default is "ArcIMS". */ name: "ArcIMS", /** * APIProperty: isBaseLayer * {Boolean} The layer is a base layer. Default is true. */ isBaseLayer: true, /** * Constant: DEFAULT_OPTIONS * {Object} Default layers properties. */ DEFAULT_OPTIONS: { tileSize: new OpenLayers.Size(512, 512), featureCoordSys: "4326", filterCoordSys: "4326", layers: null, isBaseLayer: true, async: true, name: "ArcIMS" }, /** * Constructor: OpenLayers.Layer.ArcIMS * Create a new ArcIMS layer object. * * Example: * (code) * var arcims = new OpenLayers.Layer.ArcIMS( * "Global Sample", * "http://sample.avencia.com/servlet/com.esri.esrimap.Esrimap", * { * service: "OpenLayers_Sample", * layers: [ * // layers to manipulate * {id: "1", visible: true} * ] * } * ); * (end) * * Parameters: * name - {String} A name for the layer * url - {String} Base url for the ArcIMS server * options - {Object} Optional object with properties to be set on the * layer. */ initialize: function(name, url, options) { this.tileSize = new OpenLayers.Size(512, 512); // parameters this.params = OpenLayers.Util.applyDefaults( {ServiceName: options.serviceName}, this.DEFAULT_PARAMS ); this.options = OpenLayers.Util.applyDefaults( options, this.DEFAULT_OPTIONS ); OpenLayers.Layer.Grid.prototype.initialize.apply( this, [name, url, this.params, options] ); //layer is transparent if (this.transparent) { // unless explicitly set in options, make layer an overlay if (!this.isBaseLayer) { this.isBaseLayer = false; } // jpegs can never be transparent, so intelligently switch the // format, depending on the browser's capabilities if (this.format == "image/jpeg") { this.format = OpenLayers.Util.alphaHack() ? "image/gif" : "image/png"; } } // create an empty layer list if no layers specified in the options if (this.options.layers === null) { this.options.layers = []; } }, /** * Method: destroy * Destroy this layer */ destroy: function() { // for now, nothing special to do here. OpenLayers.Layer.Grid.prototype.destroy.apply(this, arguments); }, /** * Method: getURL * Return an image url this layer. * * Parameters: * bounds - {<OpenLayers.Bounds>} A bounds representing the bbox for the * request. * * Returns: * {String} A string with the map image's url. */ getURL: function(bounds) { var url = ""; bounds = this.adjustBounds(bounds); // create an arcxml request to generate the image var axlReq = new OpenLayers.Format.ArcXML( OpenLayers.Util.extend(this.options, { requesttype: "image", envelope: bounds.toArray(), tileSize: this.tileSize }) ); // create a synchronous ajax request to get an arcims image var req = new OpenLayers.Request.POST({ url: this.getFullRequestString(), data: axlReq.write(), async: false }); // if the response exists if (req != null) { var doc = req.responseXML; if (!doc || !doc.documentElement) { doc = req.responseText; } // create a new arcxml format to read the response var axlResp = new OpenLayers.Format.ArcXML(); var arcxml = axlResp.read(doc); url = this.getUrlOrImage(arcxml.image.output); } return url; }, /** * Method: getURLasync * Get an image url this layer asynchronously, and execute a callback * when the image url is generated. * * Parameters: * bounds - {<OpenLayers.Bounds>} A bounds representing the bbox for the * request. * scope - {Object} The scope of the callback method. * prop - {String} The name of the property in the scoped object to * recieve the image url. * callback - {Function} Function to call when image url is retrieved. */ getURLasync: function(bounds, scope, prop, callback) { bounds = this.adjustBounds(bounds); // create an arcxml request to generate the image var axlReq = new OpenLayers.Format.ArcXML( OpenLayers.Util.extend(this.options, { requesttype: "image", envelope: bounds.toArray(), tileSize: this.tileSize }) ); // create an asynchronous ajax request to get an arcims image OpenLayers.Request.POST({ url: this.getFullRequestString(), async: true, data: axlReq.write(), callback: function(req) { // process the response from ArcIMS, and call the callback function // to set the image URL var doc = req.responseXML; if (!doc || !doc.documentElement) { doc = req.responseText; } // create a new arcxml format to read the response var axlResp = new OpenLayers.Format.ArcXML(); var arcxml = axlResp.read(doc); scope[prop] = this.getUrlOrImage(arcxml.image.output); // call the callback function to recieve the updated property on the // scoped object callback.apply(scope); }, scope: this }); }, /** * Method: getUrlOrImage * Extract a url or image from the ArcXML image output. * * Parameters: * output - {Object} The image.output property of the object returned from * the ArcXML format read method. * * Returns: * {String} A URL for an image (potentially with the data protocol). */ getUrlOrImage: function(output) { var ret = ""; if(output.url) { // If the image response output url is a string, then the image // data is not inline. ret = output.url; } else if(output.data) { // The image data is inline and base64 encoded, create a data // url for the image. This will only work for small images, // due to browser url length limits. ret = "data:image/" + output.type + ";base64," + output.data; } return ret; }, /** * Method: setLayerQuery * Set the query definition on this layer. Query definitions are used to * render parts of the spatial data in an image, and can be used to * filter features or layers in the ArcIMS service. * * Parameters: * id - {String} The ArcIMS layer ID. * queryDef - {Object} The query definition to apply to this layer. */ setLayerQuery: function(id, querydef) { // find the matching layer, if it exists for (var lyr = 0; lyr < this.options.layers.length; lyr++) { if (id == this.options.layers[lyr].id) { // replace this layer definition this.options.layers[lyr].query = querydef; return; } } // no layer found, create a new definition this.options.layers.push({id: id, visible: true, query: querydef}); }, /** * Method: getFeatureInfo * Get feature information from ArcIMS. Using the applied geometry, apply * the options to the query (buffer, area/envelope intersection), and * query the ArcIMS service. * * A note about accuracy: * ArcIMS interprets the accuracy attribute in feature requests to be * something like the 'modulus' operator on feature coordinates, * applied to the database geometry of the feature. It doesn't round, * so your feature coordinates may be up to (1 x accuracy) offset from * the actual feature coordinates. If the accuracy of the layer is not * specified, the accuracy will be computed to be approximately 1 * feature coordinate per screen pixel. * * Parameters: * geometry - {<OpenLayers.LonLat>} or {<OpenLayers.Geometry.Polygon>} The * geometry to use when making the query. This should be a closed * polygon for behavior approximating a free selection. * layer - {Object} The ArcIMS layer definition. This is an anonymous object * that looks like: * (code) * { * id: "ArcXML layer ID", // the ArcXML layer ID * query: { * where: "STATE = 'PA'", // the where clause of the query * accuracy: 100 // the accuracy of the returned feature * } * } * (end) * options - {Object} Object with non-default properties to set on the layer. * Supported properties are buffer, callback, scope, and any other * properties applicable to the ArcXML format. Set the 'callback' and * 'scope' for an object and function to recieve the parsed features * from ArcIMS. */ getFeatureInfo: function(geometry, layer, options) { // set the buffer to 1 unit (dd/m/ft?) by default var buffer = options.buffer || 1; // empty callback by default var callback = options.callback || function() {}; // default scope is window (global) var scope = options.scope || window; // apply these option to the request options var requestOptions = {}; OpenLayers.Util.extend(requestOptions, this.options); // this is a feature request requestOptions.requesttype = "feature"; if (geometry instanceof OpenLayers.LonLat) { // create an envelope if the geometry is really a lon/lat requestOptions.polygon = null; requestOptions.envelope = [ geometry.lon - buffer, geometry.lat - buffer, geometry.lon + buffer, geometry.lat + buffer ]; } else if (geometry instanceof OpenLayers.Geometry.Polygon) { // use the polygon assigned, and empty the envelope requestOptions.envelope = null; requestOptions.polygon = geometry; } // create an arcxml request to get feature requests var arcxml = new OpenLayers.Format.ArcXML(requestOptions); // apply any get feature options to the arcxml request OpenLayers.Util.extend(arcxml.request.get_feature, options); arcxml.request.get_feature.layer = layer.id; if (typeof layer.query.accuracy == "number") { // set the accuracy if it was specified arcxml.request.get_feature.query.accuracy = layer.query.accuracy; } else { // guess that the accuracy is 1 per screen pixel var mapCenter = this.map.getCenter(); var viewPx = this.map.getViewPortPxFromLonLat(mapCenter); viewPx.x++; var mapOffCenter = this.map.getLonLatFromPixel(viewPx); arcxml.request.get_feature.query.accuracy = mapOffCenter.lon - mapCenter.lon; } // set the get_feature query to be the same as the layer passed in arcxml.request.get_feature.query.where = layer.query.where; // use area_intersection arcxml.request.get_feature.query.spatialfilter.relation = "area_intersection"; // create a new asynchronous request to get the feature info OpenLayers.Request.POST({ url: this.getFullRequestString({'CustomService': 'Query'}), data: arcxml.write(), callback: function(request) { // parse the arcxml response var response = arcxml.parseResponse(request.responseText); if (!arcxml.iserror()) { // if the arcxml is not an error, call the callback with the features parsed callback.call(scope, response.features); } else { // if the arcxml is an error, return null features selected callback.call(scope, null); } } }); }, /** * Method: clone * Create a clone of this layer * * Returns: * {<OpenLayers.Layer.ArcIMS>} An exact clone of this layer */ clone: function (obj) { if (obj == null) { obj = new OpenLayers.Layer.ArcIMS(this.name, this.url, this.getOptions()); } //get all additions from superclasses obj = OpenLayers.Layer.Grid.prototype.clone.apply(this, [obj]); // copy/set any non-init, non-simple values here return obj; }, /** * Method: addTile * addTile creates a tile, initializes it, and adds it to the layer div. * * Parameters: * bounds - {<OpenLayers.Bounds>} * position - {<OpenLayers.Pixel>} * * Returns: * {<OpenLayers.Tile.Image>} The added image tile. */ addTile:function(bounds,position) { return new OpenLayers.Tile.Image( this, position, bounds, null, this.tileSize ); }, CLASS_NAME: "OpenLayers.Layer.ArcIMS" });
import authConfig from './common/constants/authConfig'; export function configure(aurelia) { aurelia.use .standardConfiguration() .developmentLogging() .plugin('aurelia-auth', (baseConfig) => { baseConfig.configure(authConfig); }); aurelia.start().then(() => aurelia.setRoot('root')); }
import {sqrt} from "../math.js"; const sqrt3 = sqrt(3); export default { draw(context, size) { const y = -sqrt(size / (sqrt3 * 3)); context.moveTo(0, y * 2); context.lineTo(-sqrt3 * y, -y); context.lineTo(sqrt3 * y, -y); context.closePath(); } };
import * as d3 from 'd3'; import _ from 'lodash'; import { geoExtent, geoPointInPolygon } from '../geo/index'; import { modeSelect } from '../modes/index'; import { uiLasso } from '../ui/index'; export function behaviorLasso(context) { var behavior = function(selection) { var lasso; function mousedown() { var button = 0; // left if (d3.event.button === button && d3.event.shiftKey === true) { lasso = null; selection .on('mousemove.lasso', mousemove) .on('mouseup.lasso', mouseup); d3.event.stopPropagation(); } } function mousemove() { if (!lasso) { lasso = uiLasso(context); context.surface().call(lasso); } lasso.p(context.mouse()); } function normalize(a, b) { return [ [Math.min(a[0], b[0]), Math.min(a[1], b[1])], [Math.max(a[0], b[0]), Math.max(a[1], b[1])]]; } function lassoed() { if (!lasso) return []; var graph = context.graph(), bounds = lasso.extent().map(context.projection.invert), extent = geoExtent(normalize(bounds[0], bounds[1])); return _.map(context.intersects(extent).filter(function(entity) { return entity.type === 'node' && geoPointInPolygon(context.projection(entity.loc), lasso.coordinates) && !context.features().isHidden(entity, graph, entity.geometry(graph)); }), 'id'); } function mouseup() { selection .on('mousemove.lasso', null) .on('mouseup.lasso', null); if (!lasso) return; var ids = lassoed(); lasso.close(); if (ids.length) { context.enter(modeSelect(context, ids)); } } selection .on('mousedown.lasso', mousedown); }; behavior.off = function(selection) { selection.on('mousedown.lasso', null); }; return behavior; }
var packageData = require('./package.json') var userValidate = require('npm-user-validate') var MockTransport = function (options) { this.options = options || {} this.sentMail = [] this.name = 'Mock' this.version = packageData.version } function validate (addr) { try { var err = userValidate.email(addr) if (err != null) return err } catch (_err) { return new Error('Error validating address.') } return null } MockTransport.prototype.send = function (mail, callback) { var err if (!mail.data.to) { return callback(new Error('I need to know who this email is being sent to :-(')) } if (Array.isArray(mail.data.to)) { for (var i = 0; i < mail.data.to.length; i++) { var addr = mail.data.to[i] err = validate(addr) if (err != null) { return callback(err) } } } else { err = validate(mail.data.to) if (err != null) { return callback(err) } } this.sentMail.push(mail) return callback() } module.exports = function (options) { return new MockTransport(options) }
import mod1970 from './mod1970'; var value=mod1970+1; export default value;
iD.svg.Lines = function(projection) { var highway_stack = { motorway: 0, motorway_link: 1, trunk: 2, trunk_link: 3, primary: 4, primary_link: 5, secondary: 6, tertiary: 7, unclassified: 8, residential: 9, service: 10, footway: 11 }; function waystack(a, b) { var as = 0, bs = 0; if (a.tags.highway) { as -= highway_stack[a.tags.highway]; } if (b.tags.highway) { bs -= highway_stack[b.tags.highway]; } return as - bs; } return function drawLines(surface, graph, entities, filter) { var ways = [], pathdata = {}, onewaydata = {}, getPath = iD.svg.Path(projection, graph); for (var i = 0; i < entities.length; i++) { var entity = entities[i], outer = iD.geo.simpleMultipolygonOuterMember(entity, graph); if (outer) { ways.push(entity.mergeTags(outer.tags)); } else if (entity.geometry(graph) === 'line') { ways.push(entity); } } ways = ways.filter(getPath); pathdata = _.groupBy(ways, function(way) { return way.layer(); }); _.forOwn(pathdata, function(v, k) { onewaydata[k] = _(v) .filter(function(d) { return d.isOneWay(); }) .map(iD.svg.OneWaySegments(projection, graph, 35)) .flatten() .valueOf(); }); var layergroup = surface .select('.layer-lines') .selectAll('g.layergroup') .data(d3.range(-10, 11)); layergroup.enter() .append('g') .attr('class', function(d) { return 'layer layergroup layer' + String(d); }); var linegroup = layergroup .selectAll('g.linegroup') .data(['shadow', 'casing', 'stroke']); linegroup.enter() .append('g') .attr('class', function(d) { return 'layer linegroup line-' + d; }); var lines = linegroup .selectAll('path') .filter(filter) .data( function() { return pathdata[this.parentNode.parentNode.__data__] || []; }, iD.Entity.key ); // Optimization: call simple TagClasses only on enter selection. This // works because iD.Entity.key is defined to include the entity v attribute. lines.enter() .append('path') .attr('class', function(d) { return 'way line ' + this.parentNode.__data__ + ' ' + d.id; }) .call(iD.svg.TagClasses()); lines .sort(waystack) .attr('d', getPath) .call(iD.svg.TagClasses().tags(iD.svg.MultipolygonMemberTags(graph))); lines.exit() .remove(); var onewaygroup = layergroup .selectAll('g.onewaygroup') .data(['oneway']); onewaygroup.enter() .append('g') .attr('class', 'layer onewaygroup'); var oneways = onewaygroup .selectAll('path') .filter(filter) .data( function() { return onewaydata[this.parentNode.parentNode.__data__] || []; }, function(d) { return [d.id, d.index]; } ); oneways.enter() .append('path') .attr('class', 'oneway') .attr('marker-mid', 'url(#oneway-marker)'); oneways .attr('d', function(d) { return d.d; }); if (iD.detect().ie) { oneways.each(function() { this.parentNode.insertBefore(this, this); }); } oneways.exit() .remove(); }; };
module.exports = { xstream: { run: '@cycle/run', import: 'import xs from \'xstream\'', stream: 'xs' }, rxjs: { run: '@cycle/rxjs-run', import: 'import Rx from \'rxjs/Rx\'', stream: 'Rx.Observable' }, most: { run: '@cycle/most-run', import: 'import * as most from \'most\'', stream: 'most' } }
import fs from 'fs'; import del from 'del'; import shell from 'shelljs'; import gulp from 'gulp'; import git from 'gulp-git'; import paths from '../paths'; const version = JSON.parse(fs.readFileSync('./package.json', 'utf8')).version; let cloneRepo = () => new Promise((resolve, reject) => { git.clone('git@github.com:TheCodeDestroyer/cerberus.git', { args: `${paths.masterClone} -b master` }, function(err) { if (err) { console.error(err); reject(); } else { resolve(); } }); }); let copyDist = () => new Promise((resolve, reject) => { gulp.src(`${paths.dest}/**/*`) .pipe(gulp.dest(paths.masterClone)) .on('error', reject) .on('end', resolve); }); let addAndCommitFiles = () => new Promise((resolve, reject) => { gulp.src(`${paths.masterClone}/*`) .pipe(git.add({ args: '-A', cwd: paths.masterClone })) .pipe(git.commit('New version: v' + version, { cwd: paths.masterClone })) .on('error', reject) .on('end', resolve); }); let pushToDeploy = () => new Promise((resolve, reject) => { git.push('origin', 'master', { cwd: paths.masterClone }, (err) => { if (err) { console.error(err); reject(); } else { resolve(); } }); }); gulp.task('updateMaster', (cb) => { del(paths.masterClone) .then(() => cloneRepo()) .then(() => del(`${paths.masterClone}/**/*`)) .then(() => copyDist()) .then(() => addAndCommitFiles()) .then(() => pushToDeploy()) .then(() => { cb(); }); }); gulp.task('npmPublish', (cb) => { const npmExec = shell.which('npm'); shell.exec(`${npmExec} publish ${paths.masterClone}`, () => { cb(); }); });
const request = require('request'); const debug = require('debug')('NURSE_TRAIN'); const Orders = require('../models/order.model'); const Patient = require('../models/patients.model'); const Hospital = require('../models/hospital.model'); const wechatPatient = require('./wechat-patient.controller'); // 环境变量 const env = process.env.NODE_ENV || 'development'; const isProd = env === 'production' ? true : false; // APP 配置 const config = isProd ? require('../config.prod') : require('../config'); function create(req, res, next) { const { openId, hospitalId, departmentId, orderDate, orderMealType, patientName, inHospitalId, patientMobile, patientBedNo, totalFee } = req.body; console.log("order create: " + JSON.stringify(req.body)); Patient.updateOne(openId, { 'realName': patientName, 'mobile': patientMobile, 'inHospitalId': inHospitalId, 'bedNo': patientBedNo }); var orderTimeTips = { 'reminderDay': req.body["orderTimeTips[reminderDay]"], 'reminderTime': req.body["orderTimeTips[reminderTime]"], 'shippingStart': req.body["orderTimeTips[shippingStart]"], 'shippingEnd': req.body["orderTimeTips[shippingEnd]"] } console.log(orderTimeTips); var obj = req.body; var remarks = []; for (var i = 0;; i++) { var t = "remarks[" + i + "]"; if (t in obj) { console.log("has property: " + obj[t]); remarks.push(obj[t]); } else { break; } } var dishes = []; for (var i = 0;; i++) { var t1 = "dishes[" + i + "][dishId]"; var t2 = "dishes[" + i + "][dishType]"; var t3 = "dishes[" + i + "][dishName]"; var t4 = "dishes[" + i + "][price]"; var t5 = "dishes[" + i + "][count]"; if (t1 in obj && t2 in obj && t3 in obj && t4 in obj && t5 in obj) { console.log("has property: " + obj[t1] + " " + obj[t2] + " " + obj[t3] + " " + obj[t4] + " " + obj[t5]); var dish = { 'dishId': obj[t1], 'dishType': obj[t2], 'dishName': obj[t3], 'price': obj[t4], 'count': obj[t5] }; dishes.push(dish); } else { break; } } var status = 1; const order = new Orders({ openId, hospitalId, departmentId, orderDate, orderMealType, orderTimeTips, remarks, patientName, inHospitalId, patientMobile, patientBedNo, totalFee, status, dishes }); console.log("create here."); order.save() .then(ret => { console.log("create order: " + JSON.stringify(ret)); res.json({ success: true, data: ret }); }) .catch(e => next(e)); } function remove(req, res, next) { const { catalog } = req; catalog.remove() .then(oldCatalog => res.json({ success: true, data: oldCatalog })) .catch(e => next(e)); } function load(req, res, next, id) { Catalog.get(id) .then(catalog => { req.catalog = catalog; return next(); }) .catch(e => next(e)); } function findOne(req, res) { return res.json({success: true, data: req.catalog}); } function listOrders(req, res, next) { const { hospitalId, deptId, orderDate, orderTime, date, type = 2, size = 10, page = 1 } = req.query; console.log("listOrders, hospitalId: " + hospitalId + " deptId: " + deptId + " orderDate: " + orderDate + " orderTime: " + orderTime); Orders.list({ 'hospitalId': hospitalId, 'departmentId': deptId, 'orderDate': orderDate, 'orderMealType': orderTime }) .then(orders => { console.log(orders); res.json({ success: true, page: { current: 1, total: orders.length }, data: orders }); }) .catch(e => next(e)); } function listOrdersByUserId(req, res, next) { const { openId, hospitalId } = req.query; console.log("listOrdersByUserId, openId: " + openId + " hospitalId: " + hospitalId); Orders.list({ 'openId': openId, 'hospitalId': hospitalId }) .then(orders => { console.log(orders); res.json({ success: true, page: { current: 1, total: orders.length }, data: orders }); }) .catch(e => next(e)); } function revokeOrder(req, res, next) { var orderId = req.params.orderId; var data = { 'status': 4 }; Orders.updateOne(orderId, data) .then(order => { res.json({ success: true, data: order }); }) .catch(e => next(e)); } function confirmOrder(req, res, next) { var orderId = req.params.orderId; var data = { 'status': 2 }; Orders.updateOne(orderId, data) .then(ret => { res.json({ success: true, data: ret }); Orders.get({'_id': orderId}) .then(order => { var msg = { 'type': "confirm", 'order': order }; Hospital.get({'_id': order.hospitalId}) .then(hosp => { if (hosp) { console.log(hosp); var i = 0; var len = hosp.departments.length; for (i = 0; i < len; i++) { if (order.departmentId == hosp.departments[i]._id) { break; } } if (i == len) { res.json({ success: false, errMsg: "此科室病区不存在!" }); return; } msg.order.departmentName = hosp.departments[i].name; wechatPatient.sendMessage(order.openId, msg); } }); }); }) .catch(e => next(e)); } function cancelOrder(req, res, next) { var orderId = req.params.orderId; var data = { 'status': 3, 'comment': req.body.comment }; Orders.updateOne(orderId, data) .then(order => { res.json({ success: true, data: order }); Orders.get({'_id': orderId}) .then(order => { var msg = { 'type': "cancel", 'order': order }; Hospital.get({'_id': order.hospitalId}) .then(hosp => { if (hosp) { console.log(hosp); var i = 0; var len = hosp.departments.length; for (i = 0; i < len; i++) { if (order.departmentId == hosp.departments[i]._id) { break; } } if (i == len) { res.json({ success: false, errMsg: "此科室病区不存在!" }); return; } msg.order.departmentName = hosp.departments[i].name; wechatPatient.sendMessage(order.openId, msg); } }); }); }) .catch(e => next(e)); } function getCancelReason(req, res, next) { var orderId = req.params.orderId; console.log("getCancelReason, orderId: " + orderId); Orders.get({'_id': orderId}) .then(order => { if (order) { res.json({ success: true, data: order.comment }); } else { res.json({ success: false, errMsg: "您查找的订单ID不存在!" }) } }) .catch(e => next(e)); } module.exports = { create, remove, load, findOne, listOrders, listOrdersByUserId, revokeOrder, confirmOrder, cancelOrder, getCancelReason, };
'use strict'; var mongoose = require('mongoose'); mongoose.Promise = Promise; var logger = require('./logger'); var mongoURI = require('./config').get('database.mongoURI'); mongoose.connect(mongoURI); var db = mongoose.connection; db.on('error', logger.error.bind(logger, 'connection error')); module.exports = { open: function() { return new Promise(function(resolve) { db.once('open', resolve); }); }, close: function() { mongoose.connection.close(); } };
import setPath from './setPath' import ipc from 'ipc' export default function requestPathDialog () { return (dispatch, getState) => { ipc.once('pathDialogResponse', response => { if (response.error) { console.log('pathDialogResponse', response) } else { dispatch(setPath(response.path)) } }) ipc.send('pathDialogRequest') } }
var ffi = require('ffi'), ref = require('ref'), RefArray = require('ref-array'), Struct = require('ref-struct'), Union = require('ref-union'), _library = require('./../../'); loadDependentSymbols(); _library._preload['zif_fsockopen'] = ['zval', 'pointer', 'zval', function () { _library.zif_fsockopen = ['void', ['int', ref.refType(_library.zval), ref.refType(ref.refType(_library.zval)), ref.refType(_library.zval), 'int']]; _library._functions['zif_fsockopen'] = _library.zif_fsockopen; }]; _library._preload['zif_pfsockopen'] = ['zval', 'pointer', 'zval', function () { _library.zif_pfsockopen = ['void', ['int', ref.refType(_library.zval), ref.refType(ref.refType(_library.zval)), ref.refType(_library.zval), 'int']]; _library._functions['zif_pfsockopen'] = _library.zif_pfsockopen; }]; function loadDependentSymbols() { require('./../../Zend/zend.js'); require('./../../Zend/zend_API.js'); require('./../../Zend/zend_ast.js'); require('./../../Zend/zend_compile.js'); require('./../../Zend/zend_hash.js'); require('./../../Zend/zend_ini.js'); require('./../../Zend/zend_iterators.js'); require('./../../Zend/zend_modules.js'); require('./../../Zend/zend_object_handlers.js'); require('./../../Zend/zend_types.js'); }
import mod521 from './mod521'; var value=mod521+1; export default value;
/** * This is a test for packaging the components as separate modules */ 'use strict'; var path = require('path'); var webpack = require('webpack'); var ExtractTextPlugin = require('extract-text-webpack-plugin'); module.exports = { context: __dirname, debug: true, devtool: '#source-map', // NOTE: when running this via `npm run build:dist-modules` // you will need to edit the resulting index.js file // to only include these two files entry: { Legend: './Legend/Legend', DiscreteBarChart: './DiscreteBarChart/DiscreteBarChart' }, eslint: { failOnError: true }, externals: [ { 'cartodb-client': 'cartodb-client', 'd3': 'd3', 'intro.js': 'intro.js', 'leaflet': 'leaflet', 'lodash': 'lodash', 'react': { root: 'React', commonjs: 'react', commonjs2: 'react', amd: 'react' }, 'react-dom': 'react-dom', 'react-leaflet': 'react-leaflet', 'topojson': 'topojson', } ], module: { loaders: [ { test: /\.js[x]?$/, loader: 'babel-loader', query: { cacheDirectory: true, optional: ['runtime'], stage: 0 }, exclude: /node_modules/ }, { test: /\.scss$/, loader: ExtractTextPlugin.extract('style-loader', 'css-loader?-advanced!sass-loader?sourceMap'), exclude: /node_modules/ }, { test: /\.json$/, loader: 'json-loader' } ], preLoaders: [ { test: /\.js[x]?$/, loader: 'eslint-loader', exclude: /node_modules/ } ] }, output: { path: path.join(__dirname, '..', 'dist-modules'), filename: '[name]/[name].js', library: ['@panorama/toolkit', '[name]'], libraryTarget: 'umd' }, plugins: [ new webpack.optimize.DedupePlugin(), new webpack.optimize.OccurenceOrderPlugin(true), new webpack.optimize.AggressiveMergingPlugin(), new ExtractTextPlugin('components.css', { allChunks: true }) ], resolve: { extensions: ['', '.js', '.jsx', '.json'], modulesDirectories: ['components', 'node_modules'] }, resolveLoader: { root: path.join(__dirname, '..', 'node_modules') } };
const { green, red } = require('chalk') const { EOL } = require('os') module.exports = class Result { constructor (matcher, error) { this.matcher = matcher this.error = error } toString () { const status = this.error ? '✗' : '✓' const color = this.error ? red : green const item = color(`${status} ${this.matcher}`) return this.error ? item + EOL + this.error : item } toTree () { return this.toString() } }
module.exports = { /** * The main entry point for the Dexter module * * @param {AppStep} step Accessor for the configuration for the step using this module. Use step.input('{key}') to retrieve input data. * @param {AppData} dexter Container for all data used in this workflow. */ run: function(step, dexter) { var string1 = step.input('string1')[0]; var string2 = step.input('string2')[0]; var separate_with_space = step.input('separate_with_space')[0] != 'false'; var result; if (separate_with_space) { result = string1 + " " + string2; } else { result = string1 + string2; } this.complete({result: result}); } };
var _ = require('lodash'); var async = require('async'); var bignum = require('bignumber.js'); var radr = require('radr-lib'); var transactions = require('./transactions'); var validator = require('./../lib/schema-validator'); var remote = require('./../lib/remote.js'); var serverLib = require('./../lib/server-lib'); var utils = require('./../lib/utils'); var remote = require('./../lib/remote.js'); var dbinterface = require('./../lib/db-interface.js'); var config = require('./../lib/config.js'); var RestToTxConverter = require('./../lib/rest-to-tx-converter.js'); var TxToRestConverter = require('./../lib/tx-to-rest-converter.js'); var SubmitTransactionHooks = require('./../lib/submit_transaction_hooks.js'); var respond = require('./../lib/response-handler.js'); var errors = require('./../lib/errors.js'); var InvalidRequestError = errors.InvalidRequestError; var NetworkError = errors.NetworkError; var NotFoundError = errors.NotFoundError; var TimeOutError = errors.TimeOutError; var DEFAULT_RESULTS_PER_PAGE = 10; module.exports = { submit: submitPayment, get: getPayment, getAccountPayments: getAccountPayments, getPathFind: getPathFind }; /** * Submit a payment in the ripple-rest format. * * @global * @param {/config/config-loader} config * * @body * @param {Payment} request.body.payment * @param {String} request.body.secret * @param {String} request.body.client_resource_id * @param {Number String} req.body.last_ledger_sequence - last ledger sequence that this payment can end up in * @param {Number String} req.body.max_fee - maximum fee the payer is willing to pay * @param {Number String} req.body.fixed_fee - fixed fee the payer wants to pay the network for accepting this transaction * * @query * @param {String "true"|"false"} request.query.validated Used to force request to wait until rippled has finished validating the submitted transaction * * @param {Express.js Response} response * @param {Express.js Next} next */ function submitPayment(request, response, next) { var params = request.params; Object.keys(request.body).forEach(function(param) { params[param] = request.body[param]; }); params.max_fee = request.body.max_fee ? utils.xrpToDrops(request.body.max_fee) : void(0); params.fixed_fee = request.body.fixed_fee ? utils.xrpToDrops(request.body.fixed_fee) : void(0); if (params.payment.destination_amount && (params.payment.destination_amount.currency !== 'VRP' || params.payment.destination_amount.currency !== 'VBC') && _.isEmpty(params.payment.destination_amount.issuer)) { params.payment.destination_amount.issuer = params.payment.destination_account; } // TODO: Fix this in radr-lib. For now, always set issuer of VBC to ACCOUNT_TWOFIFTYFIVE just as VRP is implicitly set to ACCOUNT_ZERO if (params.payment.destination_amount && params.payment.destination_amount.currency === 'VBC') { params.payment.destination_amount.issuer = radr.UInt160.ACCOUNT_TWOFIFTYFIVE; } if (params.payment.source_amount && params.payment.source_amount.currency === 'VBC') { params.payment.source_amount.issuer = radr.UInt160.ACCOUNT_TWOFIFTYFIVE; } var options = { secret: params.secret, validated: request.query.validated === 'true', blockDuplicates: true, clientResourceId: params.client_resource_id, saveTransaction: true }; var hooks = { validateParams: validateParams, initializeTransaction: initializeTransaction, formatTransactionResponse: formatTransactionResponse, setTransactionParameters: setTransactionParameters }; transactions.submit(options, new SubmitTransactionHooks(hooks), function(err, payment) { if (err) { return next(err); } respond.success(response, payment); }); function validateParams(callback) { var payment = params.payment; if (!payment) { return callback(new InvalidRequestError('Missing parameter: payment. Submission must have payment object in JSON form')); } if (!params.client_resource_id) { return callback(new InvalidRequestError('Missing parameter: client_resource_id. All payments must be submitted with a client_resource_id to prevent duplicate payments')); } if (!validator.isValid(params.client_resource_id, 'ResourceId')) { return callback(new InvalidRequestError('Invalid parameter: client_resource_id. Must be a string of ASCII-printable characters. Note that 256-bit hex strings are disallowed because of the potential confusion with transaction hashes.')); } if (!radr.UInt160.is_valid(payment.source_account)) { return callback(new InvalidRequestError('Invalid parameter: source_account. Must be a valid Radr address')); } if (!radr.UInt160.is_valid(payment.destination_account)) { return callback(new InvalidRequestError('Invalid parameter: destination_account. Must be a valid Radr address')); } // Tags if (payment.source_tag && (!validator.isValid(payment.source_tag, 'UINT32'))) { return callback(new InvalidRequestError('Invalid parameter: source_tag. Must be a string representation of an unsiged 32-bit integer')); } if (payment.destination_tag && (!validator.isValid(payment.destination_tag, 'UINT32'))) { return callback(new InvalidRequestError('Invalid parameter: destination_tag. Must be a string representation of an unsiged 32-bit integer')); } // Amounts // destination_amount is required, source_amount is optional if (!payment.destination_amount || (!validator.isValid(payment.destination_amount, 'Amount'))) { return callback(new InvalidRequestError('Invalid parameter: destination_amount. Must be a valid Amount object')); } if (payment.source_amount && (!validator.isValid(payment.source_amount, 'Amount'))) { return callback(new InvalidRequestError('Invalid parameter: source_amount. Must be a valid Amount object')); } // No issuer for XRP if (payment.destination_amount && (payment.destination_amount.currency.toUpperCase() === 'VRP') && payment.destination_amount.issuer) { return callback(new InvalidRequestError('Invalid parameter: destination_amount. VRP/VBC cannot have issuer')); } if (payment.source_amount && (payment.source_amount.currency.toUpperCase() === 'VRP') && payment.source_amount.issuer) { return callback(new InvalidRequestError('Invalid parameter: source_amount. VRP/VBC cannot have issuer')); } // Must have issuer for non-XRP payments if (payment.destination_amount && (payment.destination_amount.currency.toUpperCase() !== 'VRP' && payment.destination_amount.currency.toUpperCase() !== 'VBC') && !payment.destination_amount.issuer) { return callback(new InvalidRequestError('Invalid parameter: destination_amount. Non-VBC/VRP payment must have an issuer')); } // Slippage if (payment.source_slippage && !validator.isValid(payment.source_slippage, 'FloatString')) { return callback(new InvalidRequestError('Invalid parameter: source_slippage. Must be a valid FloatString')); } // Advanced options // Invoice id if (payment.invoice_id && !validator.isValid(payment.invoice_id, 'Hash256')) { return callback(new InvalidRequestError('Invalid parameter: invoice_id. Must be a valid Hash256')); } // paths if (payment.paths) { if (typeof payment.paths === 'string') { try { JSON.parse(payment.paths); } catch (exception) { return callback(new InvalidRequestError('Invalid parameter: paths. Must be a valid JSON string or object')); } } else if (typeof payment.paths === 'object') { try { JSON.parse(JSON.stringify(payment.paths)); } catch (exception) { return callback(new InvalidRequestError('Invalid parameter: paths. Must be a valid JSON string or object')); } } } // partial payment if (payment.hasOwnProperty('partial_payment') && typeof payment.partial_payment !== 'boolean') { return callback(new InvalidRequestError('Invalid parameter: partial_payment. Must be a boolean')); } // direct Ripple if (payment.hasOwnProperty('no_direct_ripple') && typeof payment.no_direct_ripple !== 'boolean') { return callback(new InvalidRequestError('Invalid parameter: no_direct_ripple. Must be a boolean')); } // memos if (payment.hasOwnProperty('memos')) { if (!Array.isArray(payment.memos)) { return callback(new InvalidRequestError('Invalid parameter: memos. Must be an array with memo objects')); } if (payment.memos.length === 0) { return callback(new InvalidRequestError('Invalid parameter: memos. Must contain at least one Memo object, otherwise omit the memos property')); } for (var m = 0; m < payment.memos.length; m++) { var memo = payment.memos[m]; if (memo.MemoType && !/(undefined|string)/.test(typeof memo.MemoType)) { return callback(new InvalidRequestError('Invalid parameter: MemoType. MemoType must be a string')); } if (!/(undefined|string)/.test(typeof memo.MemoData)) { return callback(new InvalidRequestError('Invalid parameter: MemoData. MemoData must be a string')); } if (!memo.MemoData && !memo.MemoType) { return callback(new InvalidRequestError('Missing parameter: MemoData or MemoType. For a memo object MemoType or MemoData are both optional, as long as one of them is present')); } } } callback(null); }; function initializeTransaction(callback) { RestToTxConverter.convert(params.payment, function(error, transaction) { if (error) { return callback(error); } callback(null, transaction); }); }; function formatTransactionResponse(message, meta, callback) { if (meta.state === 'validated') { var transaction = message.tx_json; transaction.meta = message.metadata; transaction.ledger_index = transaction.inLedger = message.ledger_index; return formatPaymentHelper(params.payment.source_account, transaction, callback); } var urlBase = utils.getUrlBase(request); callback(null, { client_resource_id: params.client_resource_id, status_url: urlBase + '/v1/accounts/' + params.payment.source_account + '/payments/' + params.client_resource_id }); }; function setTransactionParameters(transaction) { var ledgerIndex; var maxFee = Number(params.max_fee ? params.max_fee.value : void(0)); var fixedFee = Number(params.fixed_fee ? params.fixed_fee.value : void(0)); if (Number(params.last_ledger_sequence) > 0) { ledgerIndex = Number(params.last_ledger_sequence); } else { ledgerIndex = Number(remote._ledger_current_index) + transactions.DEFAULT_LEDGER_BUFFER; } transaction.lastLedger(ledgerIndex); if (maxFee >= 0) { transaction.maxFee(maxFee); } if (fixedFee >= 0) { transaction.setFixedFee(fixedFee); } transaction.clientID(params.client_resource_id); }; }; /** * Retrieve the details of a particular payment from the Remote or * the local database and return it in the radr-rest Payment format. * * @param {Remote} remote * @param {/lib/db-interface} dbinterface * @param {RadrAddress} req.params.account * @param {Hex-encoded String|ASCII printable character String} req.params.identifier * @param {Express.js Response} res * @param {Express.js Next} next */ function getPayment(request, response, next) { var options = { account: request.params.account, identifier: request.params.identifier }; function validateOptions(callback) { var invalid; if (!options.account) { invalid = 'Missing parameter: account. Must provide account to get payment details'; } if (!radr.UInt160.is_valid(options.account)) { invalid = 'Parameter is not a valid Radr address: account'; } if (!options.identifier) { invalid = 'Missing parameter: hash or client_resource_id. '+ 'Must provide transaction hash or client_resource_id to get payment details'; } if (!validator.isValid(options.identifier, 'Hash256') && !validator.isValid(options.identifier, 'ResourceId')) { invalid = 'Invalid Parameter: hash or client_resource_id. ' + 'Must provide a transaction hash or client_resource_id to get payment details'; } if (invalid) { callback(new InvalidRequestError(invalid)); } else { callback(); } }; // If the transaction was not in the outgoing_transactions db, get it from radrd function getTransaction(callback) { transactions.getTransaction(request.params.account, request.params.identifier, function(error, transaction) { callback(error, transaction); }); }; var steps = [ validateOptions, getTransaction, function (transaction, callback) { return formatPaymentHelper(options.account, transaction, callback); } ]; async.waterfall(steps, function(error, result) { if (error) { next(error); } else { respond.success(response, result); } }); }; /** * Formats the local database transaction into radr-rest Payment format * * @param {RadrAddress} account * @param {Transaction} transaction * @param {Function} callback * * @callback * @param {Error} error * @param {RadrRestTransaction} transaction */ function formatPaymentHelper(account, transaction, callback) { function checkIsPayment(callback) { var isPayment = transaction && /^payment$/i.test(transaction.TransactionType); if (isPayment) { callback(null, transaction); } else { callback(new InvalidRequestError('Not a payment. The transaction corresponding to the given identifier is not a payment.')); } }; function getPaymentMetadata(transaction) { return { client_resource_id: transaction.client_resource_id || '', hash: transaction.hash || '', ledger: !_.isUndefined(transaction.inLedger) ? String(transaction.inLedger) : String(transaction.ledger_index), state: transaction.state || transaction.meta ? (transaction.meta.TransactionResult === 'tesSUCCESS' ? 'validated' : 'failed') : '' }; } function formatTransaction(transaction, callback) { if (transaction) { TxToRestConverter.parsePaymentFromTx(transaction, { account: account }, function(err, parsedPayment) { if (err) { return callback(err); } var result = { payment: parsedPayment }; _.extend(result, getPaymentMetadata(transaction)); return callback(null, result); }); } else { callback(new NotFoundError('Payment Not Found. This may indicate that the payment was never validated and written into ' + 'the Radr ledger and it was not submitted through this radr-rest instance. ' + 'This error may also be seen if the databases of either radr-rest ' + 'or radrd were recently created or deleted.')); } }; var steps = [ checkIsPayment, formatTransaction ]; async.waterfall(steps, callback); }; /** * Retrieve the details of multiple payments from the Remote * and the local database. * * This function calls transactions.getAccountTransactions * recursively to retrieve results_per_page number of transactions * and filters the results by type "payment", along with the other * client-specified parameters. * * @param {Remote} remote * @param {/lib/db-interface} dbinterface * @param {RadrAddress} req.params.account * @param {RadrAddress} req.query.source_account * @param {RadrAddress} req.query.destination_account * @param {String "incoming"|"outgoing"} req.query.direction * @param {Number} [-1] req.query.start_ledger * @param {Number} [-1] req.query.end_ledger * @param {Boolean} [false] req.query.earliest_first * @param {Boolean} [false] req.query.exclude_failed * @param {Number} [20] req.query.results_per_page * @param {Number} [1] req.query.page * @param {Express.js Response} res * @param {Express.js Next} next */ function getAccountPayments(request, response, next) { var options; function getTransactions(callback) { options = { account: request.params.account, source_account: request.query.source_account, destination_account: request.query.destination_account, direction: request.query.direction, ledger_index_min: request.query.start_ledger, ledger_index_max: request.query.end_ledger, earliest_first: (request.query.earliest_first === 'true'), exclude_failed: (request.query.exclude_failed === 'true'), min: request.query.results_per_page, max: request.query.results_per_page, offset: (request.query.results_per_page || DEFAULT_RESULTS_PER_PAGE) * ((request.query.page || 1) - 1), types: [ 'payment' ] }; transactions.getAccountTransactions(options, response, callback); }; function attachDate(transactions, callback) { var groupedTx = _.groupBy(transactions, function(tx) { return tx.ledger_index; }); async.each(_.keys(groupedTx), function(ledger, next) { remote.requestLedger({ ledger_index: Number(ledger) }, function(err, data) { if (err) { return next(err); } _.each(groupedTx[ledger], function(tx) { tx.date = data.ledger.close_time; }) return next(null); }); }, function(err) { if (err) { return callback(err); } return callback(null, transactions); }); } function formatTransactions(transactions, callback) { if (!Array.isArray(transactions)) { return callback(null); } else { async.map(transactions, function (transaction, async_map_callback) { return formatPaymentHelper(options.account, transaction, async_map_callback); }, callback ); } }; function attachResourceId(transactions, callback) { async.map(transactions, function(paymentResult, async_map_callback) { var hash = paymentResult.hash; var payment = paymentResult.payment; dbinterface.getTransaction({ hash: hash }, function(error, db_entry) { if (error) { return async_map_callback(error); } var client_resource_id = ''; if (db_entry && db_entry.client_resource_id) { client_resource_id = db_entry.client_resource_id; } paymentResult.client_resource_id = client_resource_id; async_map_callback(null, paymentResult); }); }, callback); }; var steps = [ getTransactions, attachDate, formatTransactions, attachResourceId ]; async.waterfall(steps, function(error, payments) { if (error) { next(error); } else { respond.success(response, { payments: payments }); } }); }; /** * Get a ripple path find, a.k.a. payment options, * for a given set of parameters and respond to the * client with an array of fully-formed Payments. * * @param {Remote} remote * @param {/lib/db-interface} dbinterface * @param {RadrAddress} req.params.source_account * @param {Amount Array ["USD r...,XRP,..."]} req.query.source_currencies Note that Express.js middleware replaces "+" signs with spaces. Clients should use "+" signs but the values here will end up as spaces * @param {RadrAddress} req.params.destination_account * @param {Amount "1+USD+r..."} req.params.destination_amount_string * @param {Express.js Response} res * @param {Express.js Next} next */ function getPathFind(request, response, next) { // Parse and validate parameters var params = { source_account: request.params.account, destination_account: request.params.destination_account, destination_amount: {}, source_currencies: [] }; if (!params.source_account) { next(new InvalidRequestError('Missing parameter: source_account. Must be a valid Radr address')); return; } if (!params.destination_account) { next(new InvalidRequestError('Missing parameter: destination_account. Must be a valid Radr address')); return; } if (!radr.UInt160.is_valid(params.source_account)) { return next(new errors.InvalidRequestError('Parameter is not a valid Radr address: account')); } if (!radr.UInt160.is_valid(params.destination_account)) { return next(new errors.InvalidRequestError('Parameter is not a valid Radr address: destination_account')); } // Parse destination amount if (!request.params.destination_amount_string) { next(new InvalidRequestError('Missing parameter: destination_amount. Must be an amount string in the form value+currency+issuer')); return; } params.destination_amount = utils.parseCurrencyQuery(request.params.destination_amount_string); if (!radr.UInt160.is_valid(params.source_account)) { next(new InvalidRequestError('Invalid parameter: source_account. Must be a valid Radr address')); return; } if (!radr.UInt160.is_valid(params.destination_account)){ next(new InvalidRequestError('Invalid parameter: destination_account. Must be a valid Radr address')); return; } if (!validator.isValid(params.destination_amount, 'Amount')) { next(new InvalidRequestError('Invalid parameter: destination_amount. Must be an amount string in the form value+currency+issuer')); return; } // Parse source currencies // Note that the source_currencies should be in the form // "USD r...,BTC,XRP". The issuer is optional but if provided should be // separated from the currency by a single space. if (request.query.source_currencies) { var sourceCurrencyStrings = request.query.source_currencies.split(','); for (var c = 0; c < sourceCurrencyStrings.length; c++) { // Remove leading and trailing spaces sourceCurrencyStrings[c] = sourceCurrencyStrings[c].replace(/(^[ ])|([ ]$)/g, ''); // If there is a space, there should be a valid issuer after the space if (/ /.test(sourceCurrencyStrings[c])) { var currencyIssuerArray = sourceCurrencyStrings[c].split(' '); var currencyObject = { currency: currencyIssuerArray[0], issuer: currencyIssuerArray[1] }; if (validator.isValid(currencyObject.currency, 'Currency') && radr.UInt160.is_valid(currencyObject.issuer)) { params.source_currencies.push(currencyObject); } else { next(new InvalidRequestError('Invalid parameter: source_currencies. Must be a list of valid currencies')); return; } } else { if (validator.isValid(sourceCurrencyStrings[c], 'Currency')) { params.source_currencies.push({ currency: sourceCurrencyStrings[c] }); } else { next(new InvalidRequestError('Invalid parameter: source_currencies. Must be a list of valid currencies')); return; } } } } function prepareOptions(callback) { var pathfindParams = { src_account: params.source_account, dst_account: params.destination_account, dst_amount: ((params.destination_amount.currency === 'VRP' || params.destination_amount.currency === 'VBC') ? utils.xrpToDrops(params.destination_amount) : params.destination_amount) }; if (typeof pathfindParams.dst_amount === 'object' && !pathfindParams.dst_amount.issuer) { pathfindParams.dst_amount.issuer = pathfindParams.dst_account; } if (params.source_currencies.length > 0) { pathfindParams.src_currencies = params.source_currencies; } callback(null, pathfindParams); }; function findPath(pathfindParams, callback) { var request = remote.requestRipplePathFind(pathfindParams); request.once('error', callback); request.once('success', function(pathfindResults) { pathfindResults.source_account = pathfindParams.src_account; pathfindResults.source_currencies = pathfindParams.src_currencies; pathfindResults.destination_amount = pathfindParams.dst_amount; callback(null, pathfindResults); }); function reconnectRadrd() { remote.disconnect(function() { remote.connect(); }); }; request.timeout(serverLib.CONNECTION_TIMEOUT, function() { request.removeAllListeners(); reconnectRadrd(); callback(new TimeOutError('Path request timeout')); }); request.request(); }; function addDirectXrpPath(pathfindResults, callback) { // Check if destination_amount is XRP and if destination_account accepts XRP if (typeof pathfindResults.destination_amount.currency === 'string' || pathfindResults.destination_currencies.indexOf('XRP') === -1) { return callback(null, pathfindResults); } // Check source_account balance remote.requestAccountInfo({account: pathfindResults.source_account}, function(error, result) { if (error) { return callback(new Error('Cannot get account info for source_account. ' + error)); } if (!result || !result.account_data || !result.account_data.Balance) { return callback(new Error('Internal Error. Malformed account info : ' + JSON.stringify(result))); } // Add XRP "path" only if the source_account has enough money to execute the payment if (bignum(result.account_data.Balance).greaterThan(pathfindResults.destination_amount)) { pathfindResults.alternatives.unshift({ paths_canonical: [], paths_computed: [], source_amount: pathfindResults.destination_amount }); } callback(null, pathfindResults); }); }; function formatPath(pathfindResults, callback) { if (pathfindResults.alternatives && pathfindResults.alternatives.length > 0) { return TxToRestConverter.parsePaymentsFromPathFind(pathfindResults, callback); } if (pathfindResults.destination_currencies.indexOf(params.destination_amount.currency) === -1) { callback(new NotFoundError('No paths found. ' + 'The destination_account does not accept ' + params.destination_amount.currency + ', they only accept: ' + pathfindResults.destination_currencies.join(', '))); } else if (pathfindResults.source_currencies && pathfindResults.source_currencies.length > 0) { callback(new NotFoundError('No paths found.' + ' Please ensure that the source_account has sufficient funds to execute' + ' the payment in one of the specified source_currencies. If it does' + ' there may be insufficient liquidity in the network to execute' + ' this payment right now')); } else { callback(new NotFoundError('No paths found.' + ' Please ensure that the source_account has sufficient funds to execute' + ' the payment. If it does there may be insufficient liquidity in the' + ' network to execute this payment right now')); } }; var steps = [ prepareOptions, findPath, addDirectXrpPath, formatPath ]; async.waterfall(steps, function(error, payments) { if (error) { next(error); } else { respond.success(response, { payments: payments }); } }); };
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.BSONSymbol = void 0; /** * A class representation of the BSON Symbol type. * @public */ var BSONSymbol = /** @class */ (function () { /** * @param value - the string representing the symbol. */ function BSONSymbol(value) { if (!(this instanceof BSONSymbol)) return new BSONSymbol(value); this.value = value; } /** Access the wrapped string value. */ BSONSymbol.prototype.valueOf = function () { return this.value; }; BSONSymbol.prototype.toString = function () { return this.value; }; /** @internal */ BSONSymbol.prototype.inspect = function () { return "new BSONSymbol(\"" + this.value + "\")"; }; BSONSymbol.prototype.toJSON = function () { return this.value; }; /** @internal */ BSONSymbol.prototype.toExtendedJSON = function () { return { $symbol: this.value }; }; /** @internal */ BSONSymbol.fromExtendedJSON = function (doc) { return new BSONSymbol(doc.$symbol); }; /** @internal */ BSONSymbol.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () { return this.inspect(); }; return BSONSymbol; }()); exports.BSONSymbol = BSONSymbol; Object.defineProperty(BSONSymbol.prototype, '_bsontype', { value: 'Symbol' }); //# sourceMappingURL=symbol.js.map
import 'babel-polyfill'; import {pre} from './tool/run'; import Koa from 'koa' import Cheerio from 'cheerio' import Router from 'koa-router'; import router from './router'; import config from '../config.json'; import favicon from 'koa-favicon'; import ResType from './router/type/ResType'; import cors from 'kcors'; import static_serve from 'koa-serve-static'; import path from 'path'; import FileStreamRotator from 'file-stream-rotator'; import morgan from 'koa-morgan'; const app = new Koa(); const port = process.PORT || 3000; /* 跨域 */ app.use(cors()); /* 服务器内部错误捕获 */ app.use(async (ctx, next) => { try { await next(); // next is now a function } catch (err) { ctx.body = new ResType(500, err.message, null); } }); /* icon */ app.use(favicon(__dirname + '/../public/favicon.ico')); /* http log */ app.use(morgan('combined', { stream: FileStreamRotator.getStream({ date_format: 'YYYY-MM-DD', filename: __dirname + '/../log/http' + '/access-%DATE%.log', frequency: 'daily', verbose: false }) })); /* http日志 */ // app.use(async function (ctx, next) { // log.http(`${ctx.request.method} ${ctx.request.url}`); // await next(); // }); /* 路由 */ router.get('/', async (ctx, next) => { throw(new Error('hello world')); ctx.body = 'hello world'; }); app .use(router.routes()) .use(router.allowedMethods()); /* 静态文件服务 */ app.use(static_serve(path.join(__dirname, '../public'))); /* 404 */ app.use(async (ctx, next) => { if (ctx.status == 404) { ctx.body = new ResType(404, 'not found', null); } next(); }); /*start server*/ app.listen(port, () => { log.info(`Server is listening on port:${port}`); });
const MongoClient = require('mongodb').MongoClient; const pino = require('pino')(); const config = require('../config'); module.exports = { client: null, collection: name => module.exports.client.collection(name) }; MongoClient.connect(config.mongodb).then(function (client) { pino.info('MongoDB connected'); module.exports.client = client; });
import React, { PropTypes, Component } from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import styles from './Notification.css'; import ReactCSSTransitionGroup from 'react-addons-css-transition-group'; import { showNotification } from 'actions/componentActions.js'; const TIMER = 3000; @connect(state => ({ shown: state.getIn(['components', 'Notification', 'shown']), msg: state.getIn(['components', 'Notification', 'msg']), status: state.getIn(['components', 'Notification', 'status']), }), dispatch => ({ hideNotification: bindActionCreators(showNotification, dispatch), })) export default class Notification extends Component { static propTypes = { shown: PropTypes.bool, msg: PropTypes.string, hideNotification: PropTypes.func, status: PropTypes.string, }; componentWillReceiveProps(props) { if (!this.props.shown && props.shown) { setTimeout(() => this.hideNotification(), TIMER); } } hideNotification = () => { const { status } = this.props; this.props.hideNotification({ shown: false, msg: '', status }); } render() { const { shown, msg, status } = this.props; let shownClass; switch (status) { case 'error': shownClass = 'NotificationError'; break; case 'warning': shownClass = 'NotificationWarning'; break; case 'success': shownClass = 'NotificationSuccess'; break; default: shownClass = 'NotificationSuccess'; } const className = shown ? styles[`${shownClass}Shown`] : styles[shownClass]; return ( <ReactCSSTransitionGroup className={ className } transitionName='Notification' transitionEnterTimeout={ 300 } transitionLeaveTimeout={ 300 } > { shown && <div onClick={ this.hideNotification }>{ msg }</div> } </ReactCSSTransitionGroup> ); } }
// // Handles the intent to take or ignore a suggestion in training mode // 'use strict'; const playgame = require('../PlayGame'); const bjUtils = require('../BlackjackUtils'); module.exports = { canHandle: function(handlerInput) { const request = handlerInput.requestEnvelope.request; const attributes = handlerInput.attributesManager.getSessionAttributes(); const game = attributes[attributes.currentGame]; if (game.suggestion) { if ((request.type === 'IntentRequest') && ((request.intent.name === 'AMAZON.YesIntent') || (request.intent.name === 'AMAZON.NoIntent'))) { return true; } else { return (request.type === 'LaunchRequest'); } } return false; }, handle: function(handlerInput) { const request = handlerInput.requestEnvelope.request; const event = handlerInput.requestEnvelope; const attributes = handlerInput.attributesManager.getSessionAttributes(); const game = attributes[attributes.currentGame]; let action; if (!attributes.tookSuggestion) { attributes.tookSuggestion = {}; } if (request.intent.name === 'AMAZON.YesIntent') { // OK, play what was suggested action = game.suggestion.suggestion; attributes.tookSuggestion.yes = (attributes.tookSuggestion.yes + 1) || 1; } else { action = game.suggestion.player; attributes.tookSuggestion.no = (attributes.tookSuggestion.no + 1) || 1; } return new Promise((resolve, reject) => { playgame.playBlackjackAction(attributes, event.request.locale, event.session.user.userId, {action: action}, (error, response, speech, reprompt) => { resolve(bjUtils.getResponse(handlerInput, error, response, speech, reprompt)); }); }); }, };
(function() { 'use strict'; // Development /*$(document).on('click', 'a.clang', function(e) { e.preventDefault(); var code = $(this).attr('data-lang'); if (!code) return; $.ajax({ type: "POST", url: config.ajax_url+'/change_language', data: {code: code}, success: function(t) { t = $.parseJSON(t); if (typeof t === 'object' && t.status === true) { window.location.reload(); } } }); });*/ // minified $(document).on("click","a.clang",function(a){a.preventDefault();var t=$(this).attr("data-lang");t&&$.ajax({type:"POST",url:config.ajax_url+'/change_language',data:{code:t},success:function(a){a=$.parseJSON(a),"object"==typeof a&&a.status===!0&&window.location.reload()}})}); }());
require('../../dist/litespeed'); document.body.innerHTML = '<input type="text" id="test1" data-ls-bind="{{service.title}}" />' + '<input type="text" id="test2" data-ls-bind="{{service.author.name}}" />'; const element1 = document.getElementById('test1'); const element2 = document.getElementById('test2'); const view = window.ls.view; const container = window.ls.container; const service = { 'title': 'Hello World', 'description': 'I am a mock service', 'author': { 'name': 'Eldad Fux' } }; container.set('service', service, true, true); let instance = container.get('service'); view.render(document.body); test('basic binding', () => { expect(function () { return element1.value; }()).toEqual('Hello World'); }); test('basic binding after service title change', () => { expect(function () { instance.title = 'New Title' return element1.value; }()).toEqual('New Title'); }); test('basic binding after service object change', () => { expect(function () { instance.author = {name: 'EF'} return element2.value; }()).toEqual('EF'); });
// (The MIT License) // // Copyright (c) 2012 Richard S Allinson <rsa@mountainmansoftware.com> // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // 'Software'), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. "use strict"; var Y = require('yui').use('test'); var mdc = require('../../'); var dim = require('../fixtures/dimensions'); var cfg = require('../fixtures/configs'); var assert = Y.Test.Assert; var testCase = new Y.Test.Case({ name: "mdc basic", 'test if we can use the module': function () { assert.isTrue(typeof mdc.version !== 'undefined'); }, 'test if we can use a simple config': function () { var config = mdc.create(); config.set(cfg.simple); // Y.log(JSON.stringify(cfg.test_a,null,4)); assert.isTrue(config.get('title') === 'Test A'); assert.isTrue(config.get('links.home') === 'http://www.sample.com'); assert.isTrue(config.get('links.mail') === 'http://mail.sample.com'); }, 'test if we can use a simple config with dimensions': function () { var config = mdc.create(dim); config.set(cfg.simple); // Y.log(JSON.stringify(cfg.test_a,null,4)); assert.isTrue(config.get('title') === 'Test A'); assert.isTrue(config.get('links.home') === 'http://www.sample.com'); assert.isTrue(config.get('links.mail') === 'http://mail.sample.com'); }, 'test if we can use a bundle config with dimensions first': function () { var config = mdc.create(dim, cfg.bundle); // Y.log(JSON.stringify(config.getBundle(),null,4)); assert.isTrue(config.get('title') === 'Test A'); assert.isTrue(config.get('links.home') === 'http://www.sample.com'); assert.isTrue(config.get('links.mail') === 'http://mail.sample.com'); }, 'test if we can use bundle settings with dimensions as first argument': function () { var config = mdc.create(dim, cfg.bundle); // Y.log(JSON.stringify(config.getBundle(),null,4)); assert.isTrue(config.get('title') === 'Test A'); assert.isTrue(config.get('links.home') === 'http://www.sample.com'); assert.isTrue(config.get('links.mail') === 'http://mail.sample.com'); }, 'test if we can use a simple config with dimensions and context device:ipad': function () { var config = mdc.create(), context; config.setBundle(dim, cfg.bundle); context = { 'device': 'ipad' }; //Y.log(JSON.stringify(ycb,null,4)); assert.isTrue(config.get('title', context) === 'Test A', config.get('title', context)); assert.isTrue(config.get('logo', context) === 'ipad.png', config.get('logo', context)); assert.isTrue(config.get('links.home', context) === 'http://ipad.sample.com', config.get('links.home', context)); assert.isTrue(config.get('links.mail', context) === 'http://ipad.mail.sample.com', config.get('links.mail', context)); }, 'test if we can use a simple config with dimensions and context device:iphone': function () { var config = mdc.create(), context; config.setBundle(dim, cfg.bundle); context = { 'device': 'iphone' }; //Y.log(JSON.stringify(ycb,null,4)); assert.isTrue(config.get('title', context) === 'Test A', config.get('title', context)); assert.isTrue(config.get('logo', context) === 'iphone.png', config.get('logo', context)); assert.isTrue(config.get('links.home', context) === 'http://iphone.sample.com', config.get('links.home', context)); assert.isTrue(config.get('links.mail', context) === 'http://iphone.mail.sample.com', config.get('links.mail', context)); }, 'test if we can use a simple config with dimensions and context device:iphone&lang:fr_CA': function () { var config = mdc.create(), context; config.setBundle(dim, cfg.bundle); context = { 'device': 'iphone', 'lang': 'fr_CA' }; //Y.log(JSON.stringify(ycb,null,4)); assert.isTrue(config.get('title', context) === 'Test A', config.get('title', context)); assert.isTrue(config.get('logo', context) === 'fr_iphone.png', config.get('logo', context)); assert.isTrue(config.get('links.home', context) === 'http://iphone.sample.com', config.get('links.home', context)); assert.isTrue(config.get('links.mail', context) === 'http://iphone.mail.sample.com', config.get('links.mail', context)); }, 'test if we can use a simple config with dimensions and context device:iphone&lang:en_US': function () { var config = mdc.create(), context; config.setBundle(dim, cfg.bundle); context = { 'device': 'iphone', 'lang': 'en_US' }; //Y.log(JSON.stringify(ycb,null,4)); assert.isTrue(config.get('title', context) === 'Test A', config.get('title', context)); assert.isTrue(config.get('logo', context) === 'iphone.png', config.get('logo', context)); assert.isTrue(config.get('links.home', context) === 'http://iphone.sample.com', config.get('links.home', context)); assert.isTrue(config.get('links.mail', context) === 'http://iphone.mail.sample.com', config.get('links.mail', context)); }, 'test if we can use a simple config with dimensions and context lang:en_US': function () { var config = mdc.create(), context; config.setBundle(dim, cfg.bundle); context = { 'lang': 'en_US' }; //Y.log(JSON.stringify(ycb,null,4)); assert.isTrue(config.get('title', context) === 'Test A', config.get('title', context)); assert.isTrue(config.get('logo', context) === 'en_US.png', config.get('logo', context)); assert.isTrue(config.get('links.home', context) === 'http://www.sample.com', config.get('links.home', context)); assert.isTrue(config.get('links.mail', context) === 'http://mail.sample.com', config.get('links.mail', context)); }, 'test if we can use a simple config with dimensions and context lang:fr': function () { var config = mdc.create(), context; config.setBundle(dim, cfg.bundle); context = { 'lang': 'fr' }; //Y.log(JSON.stringify(ycb,null,4)); assert.isTrue(config.get('title', context) === 'Test A', config.get('title', context)); assert.isTrue(config.get('logo', context) === 'fr.png', config.get('logo', context)); assert.isTrue(config.get('links.home', context) === 'http://www.sample.com', config.get('links.home', context)); assert.isTrue(config.get('links.mail', context) === 'http://fr.mail.sample.com', config.get('links.mail', context)); }, 'test if we can use a simple config with dimensions and context lang:fr&device:desktop': function () { var config = mdc.create(), context; config.setBundle(dim, cfg.bundle); context = { 'lang': 'fr', 'device': 'desktop' }; //Y.log(JSON.stringify(ycb,null,4)); assert.isTrue(config.get('title', context) === 'Test A', config.get('title', context)); assert.isTrue(config.get('logo', context) === 'desktop.png', config.get('logo', context)); assert.isTrue(config.get('links.home', context) === 'http://desktop.sample.com', config.get('links.home', context)); assert.isTrue(config.get('links.mail', context) === 'http://desktop.mail.sample.com', config.get('links.mail', context)); } }); module.exports = testCase;
const config = require('../config'); const gulp = require('gulp'); const svgstore = require('gulp-svgstore'); const svgmin = require('gulp-svgmin'); const path = require('path'); const size = require('gulp-size'); const rename = require('gulp-rename'); gulp.task('svg', function () { return gulp .src(path.join(config.paths.svg, '**', '*.svg')) .pipe(rename({prefix: 'i-'})) .pipe(svgmin()) .pipe(svgstore()) .pipe(rename('sprite.svg')) .pipe(size({title: 'SVG', gzip: config.prod})) .pipe(gulp.dest(config.paths.views)); });
/** * Messages model methods file */ // module dependencies var Q = require('q'); var settings = require('../../settings'); var socketsLib = require('../../socket'); var commonUtils = require('../../utils/common'); /** * Messages model static methods */ exports.static = { /** * Create message instance with author and content * @param {string} author Author name (TODO: or user model) * @param {string} content Content of message * @returns {Q.promise} Q promise with message instance resolve */ createWith: function (author, content) { return Q.ninvoke(this, 'create', { author: author, create: new Date(), content: content }); }, /** * Convert messages to one HTML in reverse order * @param {messages[]} messages Array of messages * @returns {Q.promise} Q promise with html content resolve */ getBatchHTML: function (messages) { var promise = Q(''); for (var i = messages.length - 1; i >= 0; i--) { promise = commonUtils.promiseAppender(promise, messages[i].getHTML()); } return promise; } }; /** * Messages model instance methods */ exports.instance = { /** * Emit a message to group and broadcast it * @param {group} group Group instance */ emitTo : function (group) { var message = this; Q.ninvoke(message, 'setGroup', group) .invoke('getHTML') .then(function (html) { // TODO: this is logic of socket socketsLib.server.sockets .in(group.name).emit('message', { id: message.id, html: html }); }) .done(); }, /** * Convert message instance to HTML format with chat/message * @returns {Q.promise} Q promise with html resolve */ getHTML : function () { // TODO: user_id support var message = this; return Q.ninvoke(app, 'render', 'chat/message', { content: require('markdown').markdown.toHTML(message.content), author: message.author, create: message.create, format: require('../../utils/common').formatTime, avatar: require('gravatar').url('name:'+message.author, settings.gravatar) }); } };
/*jslint browser: true*/ /*global Tangram */ var picking = false; map = (function () { // (function () { // 'use strict'; // defaults var map_start_location = [0, 0, 2]; // world var style_file = 'schools.yaml'; /*** URL parsing ***/ // leaflet-style URL hash pattern: // #[zoom],[lat],[lng] var url_hash = window.location.hash.slice(1).split('/'); // location var defaultpos = true; // use default position // location is passed through url if (url_hash.length == 3) { var defaultpos = false; map_start_location = [url_hash[1],url_hash[2], url_hash[0]]; // convert from strings map_start_location = map_start_location.map(Number); } // normal case, eg: http://tangrams.github.io/nameless-maps/?roads#4/0/0 var url_search = window.location.search.slice(1).split('/')[0]; // console.log('url_search', url_search); if (url_search.length > 0) { style_file = url_search + ".yaml"; // console.log('style_file', style_file); } /*** Map ***/ var map = L.map('map', {"keyboardZoomOffset" : .05, "scrollWheelZoom": false } ); map.setView(map_start_location.slice(0, 2), map_start_location[2]); var layer = Tangram.leafletLayer({ scene: style_file, attribution: '<a href="https://mapzen.com/tangram" target="_blank">Tangram</a> | &copy; OSM contributors | <a href="https://mapzen.com/" target="_blank">Mapzen</a>' }); window.layer = layer; var scene = layer.scene; window.scene = scene; var latlng = {}; // setView expects format ([lat, long], zoom) var hash = new L.Hash(map); function updateKey(value) { keytext = value; for (layer in scene.config.layers) { if (layer == "earth") continue; scene.config.layers[layer].properties.key_text = value; } scene.rebuildGeometry(); scene.requestRedraw(); } function updateValue(value) { valuetext = value; for (layer in scene.config.layers) { if (layer == "earth") continue; scene.config.layers[layer].properties.value_text = value; } scene.rebuildGeometry(); scene.requestRedraw(); } // Feature selection function initFeatureSelection () { var popup = document.getElementById('popup'); // click-popup // feature edit popup map.getContainer().addEventListener('mousemove', function (event) { picking = true; latlng = map.mouseEventToLatLng(event); var pixel = { x: event.clientX, y: event.clientY }; scene.getFeatureAt(pixel).then(function(selection) { if (!selection || selection.feature == null || selection.feature.properties == null) { picking = false; popup.style.visibility = 'hidden'; return; } var properties = selection.feature.properties; // generate osm edit link var url = 'https://www.openstreetmap.org/edit?'; var position = '19' + '/' + latlng.lat + '/' + latlng.lng; if (properties.id) { url += 'node=' + properties.id + '#map=' + position; } var josmUrl = 'http://www.openstreetmap.org/edit?editor=remote#map='+position; popup.style.left = (pixel.x + 0) + 'px'; popup.style.top = (pixel.y + 0) + 'px'; if ( (properties.kind == 'school' || properties.kind == 'kindergarten' || properties.kind == 'university') && !properties.area ) { popup.style.visibility = 'visible'; popup.innerHTML = '<span class="labelInner">' + 'You found a school that needs help!' + '</span><br>'; popup.appendChild(createEditLinkElement(url, 'iD', 'Edit with iD ➹')); popup.appendChild(createEditLinkElement(josmUrl, 'JOSM', 'Edit with JOSM ➹')); } }); }); map.getContainer().addEventListener('mousedown', function (event) { info.style.visibility = 'hidden'; popup.style.visibility = 'hidden'; }); } function createEditLinkElement (url, type, label) { var el = document.createElement('div'); var anchor = document.createElement('a'); el.className = 'labelInner'; anchor.href = url; anchor.target = '_blank'; anchor.textContent = label; anchor.addEventListener('click', function (event) { trackOutboundLink(url, 'editing_schools', type); }, false); el.appendChild(anchor); return el; } /** * Function that tracks a click on an outbound link in Google Analytics. * This function takes a valid URL string as an argument, and uses that URL string * as the event label. Setting the transport method to 'beacon' lets the hit be sent * using 'navigator.sendBeacon' in browser that support it. */ function trackOutboundLink (url, post_name, editor) { // ga('send', 'event', [eventCategory], [eventAction], [eventLabel], [eventValue], [fieldsObject]); ga('send', 'event', 'outbound', post_name, url, { 'transport': 'beacon', // If opening a link in the current window, this opens the url AFTER // registering the hit with Analytics. Disabled because here want the // link to open in a new window, so this hit can occur in the current tab. //'hitCallback': function(){document.location = url;} }); } function long2tile(lon,zoom) { return (Math.floor((lon+180)/360*Math.pow(2,zoom))); } function lat2tile(lat,zoom) { return (Math.floor((1-Math.log(Math.tan(lat*Math.PI/180) + 1/Math.cos(lat*Math.PI/180))/Math.PI)/2 *Math.pow(2,zoom))); } /***** Render loop *****/ function addGUI () { // Link to edit in OSM - hold 'e' and click function onMapClick(e) { var pixel = { x: e.clientX, y: e.clientY }; var latlng = map.mouseEventToLatLng(e.originalEvent); if (key.shift) { var url = 'https://www.openstreetmap.org/edit?'; scene.getFeatureAt(pixel).then(function(selection) { console.log(selection.feature, selection.changed); if (selection.feature && selection.feature.id) { url += 'way=' + selection.feature.id; } if (latlng) { url += '#map=' + map.getZoom() + '/' + latlng.lat + '/' + latlng.lng; } window.open(url, '_blank'); }); } if (key.command) { // find minimum max_zoom of all sources var max_zoom = 21; for (source in scene.config.sources) { if (scene.config.sources.hasOwnProperty(source)) { if (scene.config.sources[source].max_zoom != "undefined") { max_zoom = Math.min(max_zoom, scene.config.sources[source].max_zoom); } } } var zoom = max_zoom < map.getZoom() ? max_zoom : Math.floor(map.getZoom()); var tileCoords = { x : long2tile(latlng.lng,zoom), y: lat2tile(latlng.lat,zoom), z: zoom }; var url = 'http://vector.mapzen.com/osm/all/' + zoom + '/' + tileCoords.x + '/' + tileCoords.y + '.topojson?api_key=vector-tiles-HqUVidw'; window.open(url, '_blank'); } } map.on('click', onMapClick); } function inIframe () { try { return window.self !== window.top; } catch (e) { return true; } } // Add map window.addEventListener('load', function () { // Scene initialized layer.on('init', function() { addGUI(); initFeatureSelection(); var camera = scene.config.cameras[scene.getActiveCamera()]; // if a camera position is set in the scene file, use that if (defaultpos && typeof camera.position != "undefined") { map_start_location = [camera.position[1], camera.position[0], camera.position[2]] } map.setView([map_start_location[0], map_start_location[1]], map_start_location[2]); }); if (!inIframe()) { map.scrollWheelZoom.enable(); } layer.addTo(map); }); return map; }());
const dao = require('./dao/Users'); const log = require('./log'); const Users = {}; Users.getOrCreateUser = data => { return new Promise((resolve, reject) => { dao.getUserAETs(data.email, (err, user) => { if (err) { reject(err); } else if (user) { log('returning existing user'); resolve(user); } else { dao.insert(data.name, data.email, (err, userId) => { if (err) { reject(err); } else { log('setting up new user'); dao.setUpUser(userId, err => { if (err) { reject(err); } else { log('returning user'); dao.getUserAETs(data.email, (err, user) => { if (err) reject(err); else resolve(user); }); } }); } }); } }); }); }; Users.getIdPassword = email => { return new Promise((resolve, reject) => { dao.getIdPassword(email, (err, result) => { if (err) { reject(err); } else { const [ existing = {} ] = result; resolve({ user_id: existing.id, password: existing.password }); } }); }); }; module.exports = Users;
/** * The main AWS namespace */ var AWS = { util: require('./util') }; /** * @api private * @!macro [new] nobrowser * @note This feature is not supported in the browser environment of the SDK. */ var _hidden = {}; _hidden.toString(); // hack to parse macro module.exports = AWS; AWS.util.update(AWS, { /** * @constant */ VERSION: '2.158.0', /** * @api private */ Signers: {}, /** * @api private */ Protocol: { Json: require('./protocol/json'), Query: require('./protocol/query'), Rest: require('./protocol/rest'), RestJson: require('./protocol/rest_json'), RestXml: require('./protocol/rest_xml') }, /** * @api private */ XML: { Builder: require('./xml/builder'), Parser: null // conditionally set based on environment }, /** * @api private */ JSON: { Builder: require('./json/builder'), Parser: require('./json/parser') }, /** * @api private */ Model: { Api: require('./model/api'), Operation: require('./model/operation'), Shape: require('./model/shape'), Paginator: require('./model/paginator'), ResourceWaiter: require('./model/resource_waiter') }, /** * @api private */ apiLoader: require('./api_loader') }); require('./service'); require('./config'); require('./http'); require('./sequential_executor'); require('./event_listeners'); require('./request'); require('./response'); require('./resource_waiter'); require('./signers/request_signer'); require('./param_validator'); /** * @readonly * @return [AWS.SequentialExecutor] a collection of global event listeners that * are attached to every sent request. * @see AWS.Request AWS.Request for a list of events to listen for * @example Logging the time taken to send a request * AWS.events.on('send', function startSend(resp) { * resp.startTime = new Date().getTime(); * }).on('complete', function calculateTime(resp) { * var time = (new Date().getTime() - resp.startTime) / 1000; * console.log('Request took ' + time + ' seconds'); * }); * * new AWS.S3().listBuckets(); // prints 'Request took 0.285 seconds' */ AWS.events = new AWS.SequentialExecutor();
/* Remove empty variable declarations created by CoffeeScript Example: ```coffeescript a = 1 # Translates to: # var a; # a = 1; ``` ```javascript var a = 1; ``` This transform finds all assignments and replaces them with variable declarators. */ module.exports = function(file, api) { const j = api.jscodeshift; const root = j(file.source); const getAssignmentCollection = declaratorPath => j(declaratorPath.scope.path) .find(j.ExpressionStatement, { expression: { type: "AssignmentExpression", operator: "=", left: { type: "Identifier", name: declaratorPath.value.id.name, }, }, }) .filter(exp => declaratorPath.scope === exp.scope); const declaratorsChanged = root .find(j.VariableDeclarator, { init: null, }) .filter( declaratorPath => getAssignmentCollection(declaratorPath).size() > 0 ) .forEach(declaratorPath => { getAssignmentCollection(declaratorPath) .replaceWith(assignmentPath => j.variableDeclaration( "var", [ j.variableDeclarator( declaratorPath.value.id, assignmentPath.value.expression.right ), ] ) ); const declarationPath = declaratorPath.parent; const declarations = declarationPath.value.declarations; const indexOfDeclaration = declarations.indexOf(declaratorPath.value); declarations.splice(indexOfDeclaration, 1); if (declarations.length === 0) { j(declarationPath).remove(); } }) .size() > 0; if (declaratorsChanged) { return root.toSource(); } return null; };
'use strict'; const gulp = require('gulp'); const eslint = require('gulp-eslint'); const GulpSSH = require('gulp-ssh'); const config = require('config'); gulp.task('lint', () => { return gulp.src(['**/*.js', '!node_modules/**']) .pipe(eslint({ useEslintrc: true })) .pipe(eslint.format()); }); let sshConfig = { host: 'jse.me', port: 22, username: config.douser, password: config.dopass }; let gulpSSH = new GulpSSH({ ignoreErrors: false, sshConfig: sshConfig }); gulp.task('deploy', () => { return gulpSSH .shell(['cd /var/www/slangbot', 'git pull origin master', 'npm install', 'pm2 restart index.js'], { filePath: 'shell.log' }) .pipe(gulp.dest('logs')); });
import React from 'react'; import { storiesOf } from '@storybook/react'; import LoginPage from './LoginPage.js'; storiesOf('Research/LoginPage', module) //eslint-disable-line no-undef .add('normal', () => { return <LoginPage />; });
/* global jsio, assert, describe, beforeEach, it, Model, ModelPool */ jsio('import DevkitHelper.model as Model'); jsio('import DevkitHelper.modelpool as ModelPool'); var pool, setup = function () { 'use strict'; pool = new ModelPool({ ctor: Model, initCount: 2 }); }; describe('ModelPool:', function () { 'use strict'; beforeEach(setup); describe('init()', function () { it('make sure model pool initiated properly', function () { assert.equal(2, pool._models.length); }); }); describe('_createNewModel()', function () { it('make createNewModel is creating new instance', function () { var context = { _models: [], _ctor: Model, _obtained: {} }; pool._createNewModel.call(context); assert.equal(true, context._models[0] instanceof Model); }); }); describe('obtainModel()', function () { it('make sure model is returned', function () { assert.equal(true, pool.obtainModel() instanceof Model); assert.equal(1, pool._models.length); }); it('make sure obtainedFromPool private property is set', function () { assert.equal(true, pool.obtainModel()._obtainedFromPool); }); it('make sure pool index is incrementing', function () { pool.obtainModel(); assert.equal(1, pool._models.length); pool.obtainModel(); assert.equal(0, pool._models.length); }); it('make sure new model is created on extra request', function () { pool.obtainModel(); pool.obtainModel(); assert.equal(true, pool.obtainModel() instanceof Model); assert.equal(0, pool._models.length); }); }); describe('releaseModel()', function () { it('make sure model is released', function () { var model = pool.obtainModel(); assert.equal(true, pool.releaseModel(model)); }); it('make sure non-pooled models are not released', function () { var model = new Model(); assert.equal(false, pool.releaseModel(model)); }); it('make sure pool index is re-adjusted', function () { var model1 = pool.obtainModel(), model2 = pool.obtainModel(); pool.releaseModel(model1); assert.equal(1, pool._models.length); pool.releaseModel(model2); assert.equal(2, pool._models.length); }); }); describe('releaseAllModels()', function () { it('make sure model is released', function () { pool.obtainModel(); pool.releaseAllModels(); assert.equal(2, pool._models.length); }); }); });
'use strict'; // Setting up route angular.module('core').config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) { // Redirect to home view when route not found $urlRouterProvider.otherwise('/'); // Home state routing $stateProvider. state('home', { url: '/', templateUrl: 'modules/core/views/home.client.view.html' }). state('about', { url: '/about', templateUrl: 'modules/core/views/about.client.view.html' }); } ]);
'use strict'; const chai = require('chai'); const expect = chai.expect; const Support = require(__dirname + '/support'); const InstanceValidator = require('../../lib/instance-validator'); const sinon = require('sinon'); const Promise = Support.sequelize.Promise; const SequelizeValidationError = require('../../lib/errors').ValidationError; describe(Support.getTestDialectTeaser('InstanceValidator'), () => { beforeEach(() => { this.User = Support.sequelize.define('user'); }); it('configures itself to run hooks by default', () => { const instanceValidator = new InstanceValidator(); expect(instanceValidator.options.hooks).to.equal(true); }); describe('validate', () => { it('runs the validation sequence and hooks when the hooks option is true', () => { const instanceValidator = new InstanceValidator(this.User.build(), {hooks: true}); const _validate = sinon.spy(instanceValidator, '_validate'); const _validateAndRunHooks = sinon.spy(instanceValidator, '_validateAndRunHooks'); instanceValidator.validate(); expect(_validateAndRunHooks).to.have.been.calledOnce; expect(_validate).to.not.have.been.called; }); it('runs the validation sequence but skips hooks if the hooks option is false', () => { const instanceValidator = new InstanceValidator(this.User.build(), {hooks: false}); const _validate = sinon.spy(instanceValidator, '_validate'); const _validateAndRunHooks = sinon.spy(instanceValidator, '_validateAndRunHooks'); instanceValidator.validate(); expect(_validate).to.have.been.calledOnce; expect(_validateAndRunHooks).to.not.have.been.called; }); }); describe('_validateAndRunHooks', () => { beforeEach(() => { this.successfulInstanceValidator = new InstanceValidator(this.User.build()); sinon.stub(this.successfulInstanceValidator, '_validate').returns(Promise.resolve()); }); it('should run beforeValidate and afterValidate hooks when _validate is successful', () => { const beforeValidate = sinon.spy(); const afterValidate = sinon.spy(); this.User.beforeValidate(beforeValidate); this.User.afterValidate(afterValidate); return expect(this.successfulInstanceValidator._validateAndRunHooks()).to.be.fulfilled.then(() => { expect(beforeValidate).to.have.been.calledOnce; expect(afterValidate).to.have.been.calledOnce; }); }); it('should run beforeValidate hook but not afterValidate hook when _validate is unsuccessful', () => { const failingInstanceValidator = new InstanceValidator(this.User.build()); sinon.stub(failingInstanceValidator, '_validate').returns(Promise.reject()); const beforeValidate = sinon.spy(); const afterValidate = sinon.spy(); this.User.beforeValidate(beforeValidate); this.User.afterValidate(afterValidate); return expect(failingInstanceValidator._validateAndRunHooks()).to.be.rejected.then(() => { expect(beforeValidate).to.have.been.calledOnce; expect(afterValidate).to.not.have.been.called; }); }); it('should emit an error from after hook when afterValidate fails', () => { this.User.afterValidate(() => { throw new Error('after validation error'); }); return expect(this.successfulInstanceValidator._validateAndRunHooks()).to.be.rejectedWith('after validation error'); }); describe('validatedFailed hook', () => { it('should call validationFailed hook when validation fails', () => { const failingInstanceValidator = new InstanceValidator(this.User.build()); sinon.stub(failingInstanceValidator, '_validate').returns(Promise.reject()); const validationFailedHook = sinon.spy(); this.User.validationFailed(validationFailedHook); return expect(failingInstanceValidator._validateAndRunHooks()).to.be.rejected.then(() => { expect(validationFailedHook).to.have.been.calledOnce; }); }); it('should not replace the validation error in validationFailed hook by default', () => { const failingInstanceValidator = new InstanceValidator(this.User.build()); sinon.stub(failingInstanceValidator, '_validate').returns(Promise.reject(new SequelizeValidationError())); const validationFailedHook = sinon.stub().returns(Promise.resolve()); this.User.validationFailed(validationFailedHook); return expect(failingInstanceValidator._validateAndRunHooks()).to.be.rejected.then((err) => { expect(err.name).to.equal('SequelizeValidationError'); }); }); it('should replace the validation error if validationFailed hook creates a new error', () => { const failingInstanceValidator = new InstanceValidator(this.User.build()); sinon.stub(failingInstanceValidator, '_validate').returns(Promise.reject(new SequelizeValidationError())); const validationFailedHook = sinon.stub().throws(new Error('validation failed hook error')); this.User.validationFailed(validationFailedHook); return expect(failingInstanceValidator._validateAndRunHooks()).to.be.rejected.then((err) => { expect(err.message).to.equal('validation failed hook error'); }); }); }); }); });
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ myApp.constant('CORE_CONFIG', { HTTP_PROTOCOL: 'http://', SERVER_IP: WEB_URL, WEB_SERVICE: WEB_URL+'index.php/api' } ); myApp.constant('WEB_API', { // ALL CASA WEB SERVICES GETDATA: '/Student/StudentData', FOLDERSCAN: '/CropImageApi/folderscan', convertImage: '/CropImageApi/ConvertImage', SaveCoordinates: '/CropImageApi/SaveCoordinates', GetData: '/CropImageApi/GetData', } );
/** * grunt-submodule – copyright © 2014, Jonas Pommerening * Released under the MIT license. * https://github.com/jpommerening/grunt-submodule.git */ 'use strict'; var fs = require('fs'); var path = require('path'); var grunt = require('grunt'); if (process.argv.length < 5) { console.error('Usage: node ' + __filename + ' <base> <submodule> <gruntfile> [tasks...]'); process.exit(1); } /* needed args: base, submodule, gruntfile, tasks */ var base = path.resolve(process.argv[2]); var submodule = path.resolve(process.argv[3]); var gruntfile = path.resolve(submodule, process.argv[4]); var args = process.argv.slice(5); var tasks = []; var options = {}; args.forEach(function (arg) { var option = /^--(no-)?([^=]+)(=.+)?$/.exec(arg); if (!option) { tasks.push(arg); } else if (option[1]) { options[option[2]] = false; } else if (option[3]) { options[option[2]] = option[3].substr(1); } else { options[option[2]] = true; } }); function loadTasks(orig, directory) { [ path.join(submodule, directory), path.join(base, directory) ].forEach(function (directory) { if (grunt.file.exists(directory)) { orig(directory); } }); } function loadNpmTasks(orig, module) { [ submodule, base ].forEach(function (directory) { if (grunt.file.exists(path.join(directory, 'node_modules', module))) { var cwd = process.cwd(); process.chdir(directory); orig(module); process.chdir(cwd); } }); } function errorToObject(e) { var message = typeof e === 'string' ? e : e.message; return { message: message, stack: e.stack }; } grunt.event.onAny(function () { process.send({ event: this.event, arguments: [].slice.apply(arguments) }); }); grunt.fail.fatal = function (e, errcode) { process.send({ fail: 'fatal', error: errorToObject(e), errcode: errcode }); grunt.task.clearQueue(); grunt.util.exit(typeof errcode === 'number' ? errcode : grunt.fail.code.FATAL_ERROR); }; grunt.fail.warn = function (e, errcode) { process.send({ fail: 'warn', error: errorToObject(e), errcode: errcode }); grunt.task.clearQueue(); }; function uncaughtHandler(err) { grunt.fail.fatal(err, grunt.fail.code.TASK_FAILURE); } grunt.loadTasks = grunt.task.loadTasks = loadTasks.bind(grunt.task, grunt.task.loadTasks); grunt.loadNpmTasks = grunt.task.loadNpmTasks = loadNpmTasks.bind(grunt.task, grunt.task.loadNpmTasks); process.on('uncaughtException', uncaughtHandler); grunt.option.init(options); grunt.task.init(tasks); grunt.task.options({ error: function (err) { grunt.fail.warn(err, grunt.fail.code.TASK_FAILURE); process.disconnect(); }, done: function () { process.removeListener('uncaughtException', uncaughtHandler); process.disconnect(); grunt.util.exit(0); } }); process.chdir(submodule); if (grunt.file.exists(gruntfile)) { require(gruntfile)(grunt); } else { grunt.fail.fatal(new Error('Gruntfile ' + gruntfile + ' does not exist!')); } tasks.forEach(function (task) { grunt.task.run(task); }); grunt.task.start({asyncDone: true});
/* js-model JavaScript library, version 0.10.0 * (c) 2010-2011 Ben Pickles * * Released under MIT license. */ var Model=function(a,c){var b=function(e){this.attributes=jQuery.extend({},e);this.changes={};this.errors=new Model.Errors(this);this.uid=[a,Model.UID.generate()].join("-");jQuery.isFunction(this.initialize)&&this.initialize()};Model.Module.extend.call(b,Model.Module);b._name=a;b.collection=[];b.unique_key="id";b.extend(Model.Callbacks).extend(Model.ClassMethods).include(Model.Callbacks).include(Model.InstanceMethods);jQuery.isFunction(c)&&c.call(b,b,b.prototype);return b}; Model.Callbacks={bind:function(a,c){this.callbacks=this.callbacks||{};this.callbacks[a]=this.callbacks[a]||[];this.callbacks[a].push(c);return this},trigger:function(a,c){this.callbacks=this.callbacks||{};var b=this.callbacks[a];if(b)for(var e=0;e<b.length;e++)b[e].apply(this,c||[]);return this},unbind:function(a,c){this.callbacks=this.callbacks||{};if(c)for(var b=this.callbacks[a]||[],e=0;e<b.length;e++)b[e]===c&&this.callbacks[a].splice(e,1);else delete this.callbacks[a];return this}}; Model.ClassMethods={add:function(){for(var a=[],c=0;c<arguments.length;c++){var b=arguments[c],e=b.id();if(jQuery.inArray(b,this.collection)===-1&&!(e&&this.find(e))){this.collection.push(b);a.push(b)}}a.length>0&&this.trigger("add",a);return this},all:function(){return this.collection.slice()},chain:function(a){return jQuery.extend({},this,{collection:a})},count:function(){return this.all().length},detect:function(a){for(var c=this.all(),b,e=0,f=c.length;e<f;e++){b=c[e];if(a.call(b,b,e))return b}}, each:function(a){for(var c=this.all(),b=0,e=c.length;b<e;b++)a.call(c[b],c[b],b);return this},find:function(a){return this.detect(function(){return this.id()==a})},first:function(){return this.all()[0]},load:function(a){if(this._persistence){var c=this;this._persistence.read(function(b){for(var e=0,f=b.length;e<f;e++)c.add(b[e]);a&&a.call(c,b)})}return this},last:function(){var a=this.all();return a[a.length-1]},map:function(a){for(var c=this.all(),b=[],e=0,f=c.length;e<f;e++)b.push(a.call(c[e],c[e], e));return b},persistence:function(a){if(arguments.length==0)return this._persistence;else{var c=Array.prototype.slice.call(arguments,1);c.unshift(this);this._persistence=a.apply(a,c);return this}},pluck:function(a){for(var c=this.all(),b=[],e=0,f=c.length;e<f;e++)b.push(c[e].attr(a));return b},remove:function(a){for(var c,b=0,e=this.collection.length;b<e;b++)if(this.collection[b]===a){c=b;break}if(c!=undefined){this.collection.splice(c,1);this.trigger("remove",[a]);return true}else return false}, reverse:function(){return this.chain(this.all().reverse())},select:function(a){for(var c=this.all(),b=[],e,f=0,d=c.length;f<d;f++){e=c[f];a.call(e,e,f)&&b.push(e)}return this.chain(b)},sort:function(a){return this.chain(this.all().sort(a))},sortBy:function(a){var c=jQuery.isFunction(a);return this.sort(function(b,e){var f=c?a.call(b):b.attr(a),d=c?a.call(e):e.attr(a);return f<d?-1:f>d?1:0})}};Model.Errors=function(a){this.errors={};this.model=a}; Model.Errors.prototype={add:function(a,c){this.errors[a]||(this.errors[a]=[]);this.errors[a].push(c);return this},all:function(){return this.errors},clear:function(){this.errors={};return this},each:function(a){for(var c in this.errors)for(var b=0;b<this.errors[c].length;b++)a.call(this,c,this.errors[c][b]);return this},on:function(a){return this.errors[a]||[]},size:function(){var a=0;this.each(function(){a++});return a}}; Model.InstanceMethods={asJSON:function(){return this.attr()},attr:function(a,c){if(arguments.length===0)return jQuery.extend({},this.attributes,this.changes);else if(arguments.length===2){if(this.attributes[a]===c)delete this.changes[a];else this.changes[a]=c;return this}else if(typeof a==="object"){for(var b in a)this.attr(b,a[b]);return this}else return a in this.changes?this.changes[a]:this.attributes[a]},callPersistMethod:function(a,c){var b=this,e=function(f){if(f){b.merge(b.changes).reset(); a==="destroy"?b.constructor.remove(b):b.constructor.add(b);b.trigger(a)}var d;if(c)d=c.apply(b,arguments);return d};if(this.constructor._persistence)this.constructor._persistence[a](this,e);else e.call(this,true)},destroy:function(a){this.callPersistMethod("destroy",a);return this},id:function(){return this.attributes[this.constructor.unique_key]},merge:function(a){jQuery.extend(this.attributes,a);return this},newRecord:function(){return this.id()===undefined},reset:function(){this.errors.clear(); this.changes={};return this},save:function(a){if(this.valid())this.callPersistMethod(this.newRecord()?"create":"update",a);else a&&a(false);return this},valid:function(){this.errors.clear();this.validate();return this.errors.size()===0},validate:function(){return this}}; Model.localStorage=function(a){if(!window.localStorage)return{create:function(f,d){d(true)},destroy:function(f,d){d(true)},read:function(f){f([])},update:function(f,d){d(true)}};var c=[a._name,"collection"].join("-"),b=function(){var f=localStorage[c];return f?JSON.parse(f):[]},e=function(f){localStorage.setItem(f.uid,JSON.stringify(f.asJSON()));f=f.uid;var d=b();if(jQuery.inArray(f,d)===-1){d.push(f);localStorage.setItem(c,JSON.stringify(d))}};return{create:function(f,d){e(f);d(true)},destroy:function(f, d){localStorage.removeItem(f.uid);var g=f.uid,h=b();g=jQuery.inArray(g,h);if(g>-1){h.splice(g,1);localStorage.setItem(c,JSON.stringify(h))}d(true)},read:function(f){if(!f)return false;for(var d=a.map(function(){return this.uid}),g=b(),h=[],i,j,l=0,k=g.length;l<k;l++){j=g[l];if(jQuery.inArray(j,d)==-1){i=JSON.parse(localStorage[j]);i=new a(i);i.uid=j;h.push(i)}}f(h)},update:function(f,d){e(f);d(true)}}};Model.Log=function(){window.console&&window.console.log.apply(window.console,arguments)}; Model.Module={extend:function(a){jQuery.extend(this,a);return this},include:function(a){jQuery.extend(this.prototype,a);return this}}; Model.REST=function(a,c,b){var e=/:([\w\d]+)/g,f=function(){for(var d=[],g;(g=e.exec(c))!==null;)d.push(g[1]);return d}();return jQuery.extend({path:function(d){var g=c;jQuery.each(f,function(h,i){g=g.replace(":"+i,d.attributes[i])});return g},create:function(d,g){return this.xhr("POST",this.create_path(d),d,g)},create_path:function(d){return this.path(d)},destroy:function(d,g){return this.xhr("DELETE",this.destroy_path(d),d,g)},destroy_path:function(d){return this.update_path(d)},params:function(d){var g; if(d){var h=d.asJSON();delete h[d.constructor.unique_key];g={};g[d.constructor._name.toLowerCase()]=h}else g=null;if(jQuery.ajaxSettings.data)g=jQuery.extend({},jQuery.ajaxSettings.data,g);return JSON.stringify(g)},read:function(d){return this.xhr("GET",this.read_path(),null,function(g,h,i){i=jQuery.makeArray(i);g=[];h=0;for(var j=i.length;h<j;h++)g.push(new a(i[h]));d(g)})},read_path:function(){return c},update:function(d,g){return this.xhr("PUT",this.update_path(d),d,g)},update_path:function(d){return[this.path(d), d.id()].join("/")},xhr:function(d,g,h,i){var j=this,l=d=="GET"?undefined:this.params(h);return jQuery.ajax({type:d,url:g,contentType:"application/json",dataType:"json",data:l,dataFilter:function(k){return/\S/.test(k)?k:undefined},complete:function(k,m){j.xhrComplete(k,m,h,i)}})},xhrComplete:function(d,g,h,i){var j=Model.REST["handle"+d.status];j&&j.call(this,d,g,h);g=g==="success";j=Model.REST.parseResponseData(d);g&&h&&j&&h.attr(j);i&&i.call(h,g,d,j)}},b)};Model.RestPersistence=Model.REST; Model.REST.handle422=function(a,c,b){if(a=Model.REST.parseResponseData(a)){b.errors.clear();for(var e in a)for(c=0;c<a[e].length;c++)b.errors.add(e,a[e][c])}};Model.REST.parseResponseData=function(a){try{return/\S/.test(a.responseText)?jQuery.parseJSON(a.responseText):undefined}catch(c){Model.Log(c)}};Model.UID={counter:0,generate:function(){return[(new Date).valueOf(),this.counter++].join("-")},reset:function(){this.counter=0;return this}};Model.VERSION="0.10.0";
import Sequelize from 'sequelize' import { sequelize } from '../adapters/db' const Versions = sequelize.define('versions', { id: { type: Sequelize.UUID, defaultValue: Sequelize.UUIDV4, primaryKey: true, allowNull: false }, version_number: { type: Sequelize.INTEGER, allowNull: false, defaultValue: 1 }, filename: { type: Sequelize.STRING }, active: { type: Sequelize.BOOLEAN, allowNull: false, defaultValue: false } }, { // sequelize should not add an 's' to the end of this model to form the associated table's name freezeTableName: true, underscored: true } ) Versions.getHighestVersionByTrakId = async function (trakId) { // get latest version of trak const [ latestVersion ] = await Versions.findAll({ where: { trak_id: trakId, active: true // don't get an invalid/orphaned version }, group: [ 'versions.id' ], limit: 1, order: sequelize.literal('max(version_number) DESC') }) return latestVersion } export default Versions
function validateLocationFilter() { var radius = document.forms["filter"]["radius"].value; var latitude = document.forms["filter"]["latitude"].value; var longitude = document.forms["filter"]["longitude"].value; if ((radius != "") || (latitude != "") || (longitude != "")) { if ((radius.length > 0) && (latitude.length > 0) && (longitude.length > 0)) { return true; } alert("To filter location, Radius, Latitude, and Longitude must all have values"); return false; } }
/* Define y exporta el modelo de la colección Archivos */ // Dependencias var mongoose = require('mongoose'); // controlador de la base de datos var Schema = mongoose.Schema; // "Modelo" de la colección var fs = require('fs'); // File system utility var filesize = require('filesize'); // Human readable file size string from number // Definición del esquema "Archivos", incluyendo nombre del campo y el tipo de dato (key: value_type) var ArchivoSchema = new Schema({ filename : {type: String, trim: true, required: true}, //index: {unique: true} location: {type: String, default: ''}, // required: true descripcion: {type: String}, directory: {type: Boolean, default: false}, usuario: {type: Schema.Types.ObjectId, ref: 'Usuarios'} }, { // Opciones: collection: 'archivos', timestamps: true, //timestamps: {createdAt: 'creacion', updatedAt: 'actualizacion'} autoIndex: false, toObject: {virtuals: true}, // habilitar virtuals toJSON: {virtuals: true} }); // Virtuals ArchivoSchema.virtual('size').get(function(){ // tamaño en el sistema de archivos var dirbase = 'public/files/'; try{ // Verifica si existe el archivo, en caso contrario se dispara excepción (se maneja en catch) fs.accessSync(dirbase + this.location + this.filename, (fs.constants || fs).F_OK); return filesize(fs.statSync(dirbase + this.location + this.filename).size, {round: 0}); }catch(err){ return filesize(0, {round: 0}); } }); // ArchivoSchema.virtual('extension').get(function(){ // var matches = /\.([^\.]*)$/g.exec(this.filename); // if(matches) // return matches[1]; // return ''; // }); ArchivoSchema.virtual('filetype').get(function(){ if(this.directory) return 'directory'; else if(/\.(jpe?g|gif|png|tiff|bmp|svg|webp)$/i.test(this.filename)) // imagenes return 'image'; else if(/\.(ogg|mp3|wav|m4a|wma|aac|flac)$/i.test(this.filename)) // audio return 'audio'; else if(/\.(mp4|avi|mkv|wmv|flv|3gp|ogv|webm)$/i.test(this.filename)) // video return 'video'; else if(/\.pdf$/i.test(this.filename)) // pdf return 'pdf'; else if(/\.(docx?|f?odt|txt)$/i.test(this.filename)) // documentos de texto return 'word'; else if(/\.(pptx?|f?odp)$/i.test(this.filename)) // presentaciones return 'presentation'; else if(/\.(xlsx?|f?ods|csv)$/i.test(this.filename)) // hoja de cálculo return 'spreadsheet'; return 'other'; }); // Compound index ArchivoSchema.index({filename: 1, location: 1}, {unique: true}); // exportar el modelo "Archivos" // module.exports permite pasar el modelo a otros archivos cuando es llamado module.exports = mongoose.model('Archivo', ArchivoSchema);
exports = module.exports = function(req, res) { var keystone = req.keystone; keystone.render(req, res, 'home', { section: 'home', page: 'home', title: keystone.get('name') || 'Keystone', orphanedLists: keystone.getOrphanedLists() }); };
'use strict'; var fs = require('fs'); var gulp = require('gulp'); var sass = require('gulp-sass'); var cssmin = require('gulp-cssmin'); var mocha = require('gulp-spawn-mocha'); var concat = require('gulp-concat'); var rename = require('gulp-rename'); var jshint = require('gulp-jshint'); var source = require('vinyl-source-stream'); var webpack = require('webpack-stream'); var del = require('del'); var stylish = require('jshint-stylish'); var pkg = require('./package.json'); var dirs = { cssSrc: './resource/css', cssDist: './public/css', jsSrc: './resource/js', jsDist: './public/js', }; var tests = { watch: ['test/**/*.test.js'], } var css = { src: dirs.cssSrc + '/' + pkg.name + '.scss', main: dirs.cssDist + '/crowi-main.css', dist: dirs.cssDist + '/crowi.css', revealSrc: dirs.cssSrc + '/' + pkg.name + '-reveal.scss', revealDist: dirs.cssDist + '/crowi-reveal.css', watch: ['resource/css/*.scss'], }; var js = { bundledSrc: [ 'node_modules/jquery/dist/jquery.js', 'node_modules/bootstrap-sass/assets/javascripts/bootstrap.js', 'node_modules/inline-attachment/src/inline-attachment.js', 'node_modules/jquery.cookie/jquery.cookie.js', 'resource/thirdparty-js/jquery.selection.js', ], src: dirs.jsSrc + '/app.js', bundled: dirs.jsDist + '/bundled.js', dist: dirs.jsDist + '/crowi.js', app: dirs.jsDist + '/app.js', admin: dirs.jsDist + '/admin.js', form: dirs.jsDist + '/form.js', presentation: dirs.jsDist + '/presentation.js', clientWatch: ['resource/js/**/*.js'], watch: ['test/**/*.test.js', 'app.js', 'lib/**/*.js'], lint: ['app.js', 'lib/**/*.js'], tests: tests.watch, }; var cssIncludePaths = [ 'node_modules/bootstrap-sass/assets/stylesheets', 'node_modules/font-awesome/scss', 'node_modules/reveal.js/css' ]; gulp.task('js:del', function() { var fileList = []; var actualFiles = fs.readdirSync(dirs.jsDist); fileList = actualFiles.map(function(fn){ if (!fn.match(/.js(on)?$/)) { return false } return dirs.jsDist + '/' + fn; }).filter(function(v) { return v; }); return del(fileList); }); gulp.task('js:concat', ['js:del'], function() { return gulp.src(js.bundledSrc) .pipe(concat('bundled.js')) // jQuery .pipe(gulp.dest(dirs.jsDist)); }); // move task for css and js to webpack over time. gulp.task('webpack', ['js:concat'], function() { return gulp.src(js.src) .pipe(webpack(require('./webpack.config.js'))) .pipe(gulp.dest(dirs.jsDist)); }); gulp.task('jshint', function() { return gulp.src(js.lint) .pipe(jshint()) .pipe(jshint.reporter(stylish)); }); gulp.task('test', function() { return gulp.src(js.tests) .pipe(mocha({ r: 'test/bootstrap.js', globals: ['chai'], R: 'dot', })); }); gulp.task('css:sass', function() { gulp.src(css.revealSrc) // reveal .pipe(sass({ outputStyle: 'nesed', sourceComments: 'map', includePaths: cssIncludePaths }).on('error', sass.logError)) .pipe(gulp.dest(dirs.cssDist)); return gulp.src(css.src) .pipe(sass({ outputStyle: 'nesed', sourceComments: 'map', includePaths: cssIncludePaths }).on('error', sass.logError)) .pipe(rename({suffix: '-main'})) // create -main.css to prepare concating with highlight.js's css .pipe(gulp.dest(dirs.cssDist)); }); gulp.task('css:concat', ['css:sass'], function() { return gulp.src([css.main, 'node_modules/highlight.js/styles/tomorrow-night.css']) .pipe(concat('crowi.css')) .pipe(gulp.dest(dirs.cssDist)) }); gulp.task('css:min', ['css:concat'], function() { gulp.src(css.revealDist) .pipe(cssmin()) .pipe(rename({suffix: '.min'})) .pipe(gulp.dest(dirs.cssDist)); return gulp.src(css.dist) .pipe(cssmin()) .pipe(rename({suffix: '.min'})) .pipe(gulp.dest(dirs.cssDist)); }); gulp.task('watch', function() { var watchLogger = function(event) { console.log('File ' + event.path + ' was ' + event.type + ', running tasks...'); }; var cssWatcher = gulp.watch(css.watch, ['css:concat']); cssWatcher.on('change', watchLogger); var jsWatcher = gulp.watch(js.clientWatch, ['webpack']); jsWatcher.on('change', watchLogger); var testWatcher = gulp.watch(js.watch, ['test']); testWatcher.on('change', watchLogger); }); gulp.task('css', ['css:sass', 'css:concat',]); gulp.task('default', ['css:min', 'webpack', ]); gulp.task('dev', ['css:concat', 'webpack', 'jshint', 'test']);
var globalEnv = require('./environment').globalEnv; var Env = require('./environment').Env; function evaluate(expr, env) { env = env || globalEnv; if (typeof expr === 'string') { return env.find( expr.valueOf() )[ expr.valueOf() ]; } else if (typeof expr === 'number') { return expr; } else if (expr[0] === '_') { return expr[1]; } else if (expr[0] === 'if') { var condition = expr[1]; var consequent = expr[2]; var alternate = expr[3]; if ( evaluate(condition, env) ) { return evaluate(consequent, env); } else { return evaluate(alternate, env); } } else if (expr[0] === 'def') { env[ expr[1] ] = evaluate( expr[2], env ); } else if (expr[0] === 'fn') { var _params = expr[1]; var body = expr[2]; return function() { return evaluate( exp, Env({ params: _params, args: arguments, superEnv: env }) ); }; } else if (expr[0] === 'seq') { var val; for (var i = 1; i < expr.length; i++) { val = evaluate( expr[i], env ); } return val; } else { var exps = []; for (i = 0; i < expr.length; i++) { exps[i] = evaluate( expr[i], env ); } var proc = exps.shift(); return proc.apply(env, exps); } } module.exports = evaluate;
(function(){ "use strict"; class CrawlerManager { constructor() { this.runningCrawlers = []; }; register(crawler) { this.runningCrawlers.push(crawler) return this.runningCrawlers.length; }; static get singletonInstance () { if(CrawlerManager._singletonInstance==null) { CrawlerManager._singletonInstance = new CrawlerManager(); } return CrawlerManager._singletonInstance; } } var singleton = CrawlerManager.singletonInstance; module.exports = singleton; })();
"use strict"; angular.module("snippetShare").controller("ShowMembersModalCtrl", function ($scope, $modalInstance,Board,board,members) { console.log("ShowRequestsModal is open. board/members", board, members); $scope.members = members; $scope.board = board; $scope.cancel = function () { $modalInstance.dismiss("cancel"); }; });
version https://git-lfs.github.com/spec/v1 oid sha256:2d5ccb2e5374e712e8454089ef6bbcbbd0e7b11cdecae3dd75fa40d5b7efe130 size 27581
/////////////////////////////////////////////////////////////////////////////// // // AutobahnJS - http://autobahn.ws, http://wamp.ws // // A JavaScript library for WAMP ("The Web Application Messaging Protocol"). // // Copyright (C) 2011-2014 Tavendo GmbH, http://tavendo.com // // Licensed under the MIT License. // http://www.opensource.org/licenses/mit-license.php // /////////////////////////////////////////////////////////////////////////////// var util = require('../util.js'); var log = require('../log.js'); function Factory (options) { var self = this; util.assert(options.url !== undefined, "options.url missing"); util.assert(typeof options.url === "string", "options.url must be a string"); if (!options.protocols) { options.protocols = ['wamp.2.json']; } else { util.assert(Array.isArray(options.protocols), "options.protocols must be an array"); } if (options.options) { util.assert(typeof options.options === "object", "options must be an object"); } self._options = options; } Factory.prototype.type = "websocket"; Factory.prototype.create = function () { var self = this; // the WAMP transport we create var transport = {}; // these will get defined further below transport.protocol = undefined; transport.send = undefined; transport.close = undefined; // these will get overridden by the WAMP session using this transport transport.onmessage = function () {}; transport.onopen = function () {}; transport.onclose = function () {}; transport.info = { type: 'websocket', url: null, protocol: 'wamp.2.json' }; // Test below used to be via the 'window' object in the browser. // This fails when running in a Web worker. // // running in Node.js // if (global.process && global.process.versions.node) { (function () { var WebSocket = require('ws'); // https://github.com/einaros/ws var websocket; var options = self._options.options || {}; var protocols; if (self._options.protocols) { protocols = self._options.protocols; if (Array.isArray(protocols)) { protocols = protocols.join(','); } options.protocol = protocols; } websocket = new WebSocket(self._options.url, options); transport.send = function (msg) { var payload = JSON.stringify(msg); websocket.send(payload, {binary: false}); }; transport.close = function (code, reason) { websocket.close(); }; websocket.on('open', function () { transport.onopen(); }); websocket.on('message', function (data, flags) { if (flags.binary) { // FIXME! } else { var msg = JSON.parse(data); transport.onmessage(msg); } }); // FIXME: improve mapping to WS API for the following // https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent#Close_codes // websocket.on('close', function (code, message) { var details = { code: code, reason: message, wasClean: code === 1000 } transport.onclose(details); }); websocket.on('error', function (error) { var details = { code: 1006, reason: '', wasClean: false } transport.onclose(details); }); })(); // // running in the browser // } else { (function () { var websocket; // Chrome, MSIE, newer Firefox if ("WebSocket" in global) { if (self._options.protocols) { websocket = new global.WebSocket(self._options.url, self._options.protocols); } else { websocket = new global.WebSocket(self._options.url); } // older versions of Firefox prefix the WebSocket object } else if ("MozWebSocket" in global) { if (self._options.protocols) { websocket = new global.MozWebSocket(self._options.url, self._options.protocols); } else { websocket = new global.MozWebSocket(self._options.url); } } else { throw "browser does not support WebSocket or WebSocket in Web workers"; } websocket.onmessage = function (evt) { log.debug("WebSocket transport receive", evt.data); var msg = JSON.parse(evt.data); transport.onmessage(msg); } websocket.onopen = function () { transport.info.url = self._options.url; transport.onopen(); } websocket.onclose = function (evt) { var details = { code: evt.code, reason: evt.message, wasClean: evt.wasClean } transport.onclose(details); } // do NOT do the following, since that will make // transport.onclose() fire twice (browsers already fire // websocket.onclose() for errors also) //websocket.onerror = websocket.onclose; transport.send = function (msg) { var payload = JSON.stringify(msg); log.debug("WebSocket transport send", payload); websocket.send(payload); } transport.close = function (code, reason) { websocket.close(code, reason); }; })(); } return transport; }; exports.Factory = Factory;
var ControllerHandler = require( "./controllerhandler" ); var Keyboard = ControllerHandler.extend({ initialize: function() { this.handlers = {}; }, /** * Load configuration. * @param {object} config - An mapping of keyboard keys to controller buttons. */ _configure: function() { this.initKeyCodes(); }, /** * Bind keyboard events. */ _enable: function() { this.bindHandler( "keydown" ); this.bindHandler( "keyup" ); }, /** * Unbind keyboard events. */ _disable: function() { this.unbindHandler( "keydown" ); this.unbindHandler( "keyup" ); }, /** * Bind keyboard event of specific type. * @param {string} type - Either 'keydown' or 'keyup'. */ bindHandler: function( type ) { window.addEventListener( type, this.getHandler( type ) ); }, /** * Unbind keyboard event of specific type. * @param {string} type - Either 'keydown' or 'keyup'. */ unbindHandler: function( type ) { window.removeEventListener( type, this.getHandler( type ) ); }, /** * Get keyboard event handler of specific type. * @param {string} type - Either 'keydown' or 'keyup'. */ getHandler: function( type ) { if ( this.handlers[ type ] ) { return this.handlers[ type ]; } var self = this, handler = type === "keydown" ? "press" : "depress"; this.handlers[ type ] = function( e ) { var keyCode = e.keyCode; if ( keyCode in self.keyCodes ) { self[ handler ]( self.keyCodes[ keyCode ] ); e.preventDefault(); } }; return this.handlers[ type ]; }, /** * Initialize keycodes from config. * Converts config key strings to numeric keycodes that can be used in event handlers. */ initKeyCodes: function() { var name, keyCode, keyCodes = {}; for ( name in this.config ) { if ( name in keyCodeMap ) { // special cases ('ctrl', 'shift', etc) keyCode = keyCodeMap[ name ]; } else { // letters and numbers keyCode = name.toUpperCase().charCodeAt(); } keyCodes[ keyCode ] = this.config[ name ]; } this.keyCodes = keyCodes; } }); var keyCodeMap = { "backspace": 8, "tab": 9, "return": 13, "shift": 16, "ctrl": 17, "alt": 18, "capslock": 20, "space": 32, "left": 37, "up": 38, "right": 39, "down": 40, }; module.exports = Keyboard;
import { addEmptyDays } from './../../frontend/src/utils/getDateUtil'; import { cummulative } from './../../frontend/src/utils/cummulativeUtil'; import arrayByKey from './arrayByKey'; import arrayByKeyFiltered from './arrayByKeyFiltered'; import arrayByKeyFilteredGreaterThan from './arrayByKeyFilteredGreaterThan'; import arrayMaxMin from './arrayMaxMin'; import daysBetween from './daysBetween'; import daysSince from './daysSince'; import groupByDuplicatesInArray from './groupByDuplicatesInArray'; import impactBy from './impactBy'; import itemsSum from './itemsSum'; import sortArrayByKey from './sortArrayByKey'; import totalSum from './totalSum'; // Create author stats object const authorStats = ({ author, objData }) => { // calculate total number of commits const totalNrCommits = itemsSum(objData); // calculate total impact const totalImpact = arrayByKey(objData, 'impact'); const totalImpactSum = totalSum(totalImpact); // calculate the ratio of impact per commit const totalImpactRatio = totalImpactSum / totalNrCommits; // variables to pass to final object const commits = totalNrCommits; const impact = totalImpactSum; const impactRatio = totalImpactRatio; // calculate author's commits on a given week day const daysWeek = arrayByKey(objData, 'date_day_week'); const weekdays = groupByDuplicatesInArray(daysWeek); // calculate days between first and last commits const commitsByAuthorDateUnixtimestamp = arrayByKey( objData, 'author_date_unix_timestamp' ); const commitDateFirst = arrayMaxMin(commitsByAuthorDateUnixtimestamp, 'min'); const commitDateLast = arrayMaxMin(commitsByAuthorDateUnixtimestamp, 'max'); const daysActive = daysBetween(commitDateFirst, commitDateLast); // calculate days since first and last commits const daysSinceFirstCommit = daysSince(commitDateFirst); const daysSinceLastCommit = daysSince(commitDateLast); // calculate staleness const staleness = daysSinceLastCommit / 365; // miscellaneous // total file changes const totalFileChanges = totalSum( arrayByKey(objData, 'files_changed') ); // total commits without file changes const totalCommitsWithoutFileChanges = itemsSum( arrayByKeyFiltered(objData, 'files_changed', '0') ); // total commits with no impact const totalCommitsWithoutImpact = itemsSum( arrayByKeyFiltered(objData, 'impact', '0') ); // total commits impact greater than 1000 const totalCommitsImpactGreaterThan = itemsSum( arrayByKeyFilteredGreaterThan(objData, 'impact', '1000') ); // total commits on weekends const totalCommitsOnSaturday = itemsSum( arrayByKeyFiltered(objData, 'date_day_week', 'Sat') ); const totalCommitsOnSunday = itemsSum( arrayByKeyFiltered(objData, 'date_day_week', 'Sun') ); const totalCommitsOnWeekends = totalCommitsOnSaturday + totalCommitsOnSunday; const fileChanges = totalFileChanges; const commitsWithoutFileChanges = totalCommitsWithoutFileChanges; const commitsWithoutImpact = totalCommitsWithoutImpact; const commitsImpactGtThousand = totalCommitsImpactGreaterThan; const commitsOnWeekend = totalCommitsOnWeekends; // calculate commits per time unit const commitsBySecondsCalendar = arrayByKey(objData, 'time_seconds'); const commitsByMinutesCalendar = arrayByKey(objData, 'time_minutes'); const commitsByHoursCalendar = arrayByKey(objData, 'time_hour'); const commitsByDaysCalendar = arrayByKey(objData, 'date_iso_8601'); const commitsByMonthDay = arrayByKey(objData, 'date_month_day'); const commitsByMonthName = arrayByKey(objData, 'date_month_name'); const commitsByMonthNr = arrayByKey(objData, 'date_month_number'); const commitsByYear = arrayByKey(objData, 'date_year'); const commitsPerSecond = groupByDuplicatesInArray(commitsBySecondsCalendar); const commitsPerMinute = groupByDuplicatesInArray(commitsByMinutesCalendar); const commitsPerHour = groupByDuplicatesInArray(commitsByHoursCalendar); const commitsPerDay = addEmptyDays({ dayList: groupByDuplicatesInArray(commitsByDaysCalendar) }); const commitsPerDayAverage = daysActive / totalNrCommits; const commitsPerDayCummulative = cummulative(commitsPerDay); const commitsPerMonthDay = groupByDuplicatesInArray(commitsByMonthDay); const commitsPerMonthName = groupByDuplicatesInArray(commitsByMonthName); const commitsPerMonthNr = groupByDuplicatesInArray(commitsByMonthNr); const commitsPerYear = groupByDuplicatesInArray(commitsByYear); const impactByDay = addEmptyDays({ dayList: impactBy(objData, "date_iso_8601") }); const impactByDayCummulative = cummulative(impactByDay); // total nr repositories const repositories = itemsSum( Object.keys( groupByDuplicatesInArray( arrayByKey(objData, 'repository') ) ) ); // repositories list const repositoriesList = Object.keys( groupByDuplicatesInArray( arrayByKey(objData, 'repository') ) ).sort(); return { author, commitDateFirst, commitDateLast, commits, commitsImpactGtThousand, commitsOnWeekend, commitsPerDay, commitsPerDayAverage, commitsPerDayCummulative, commitsPerHour, commitsPerMinute, commitsPerMonthDay, commitsPerMonthName, commitsPerMonthNr, commitsPerSecond, commitsPerYear, commitsWithoutFileChanges, commitsWithoutImpact, daysActive, daysSinceFirstCommit, daysSinceLastCommit, fileChanges, impact, impactByDay, impactByDayCummulative, impactRatio, repositories, repositoriesList, staleness, weekdays, } }; // Get author stats and output it on a dedicated array, with options // ------------------------------------------------------------ export const statsAuthors = ({ data, sortBy, sortDirection, count }) => { let output = null; var obja = {}; for (var i in data) { if (!obja.hasOwnProperty(data[i].author_email)) { obja[data[i].author_email] = []; } obja[data[i].author_email].push(data[i]); } // Create an array to receive customised stats var stats = []; // Iterate through 'obja' object for (var b in obja) { if (obja.hasOwnProperty(b)) { var objb = obja[b]; // Push new data to array stats.push(authorStats({ author: b, objData: objb })); } } if (sortBy && sortDirection) { output = sortArrayByKey(stats, sortBy, sortDirection); } else if (sortBy && !sortDirection) { output = sortArrayByKey(stats, sortBy); } else { output = stats; } if (count) { output = output.slice(0, count); } return output; };
import { UI_OPEN_SIDEBAR, UI_CLOSE_SIDEBAR, UI_WINDOW_RESIZE, LOCATION_CHANGE, APPLICATION_INIT } from 'actions' export const initialState = { sidebarOpened: false, isMobile: false, isMobileXS: false, isMobileSM: false } export function layout (state = initialState, action) { const computeMobileStatuses = () => { const innerWidth = process.env.BROWSER ? window.innerWidth : 1024 const isMobile = innerWidth < 1025 // 1024px - is the main breakpoint in UI const isMobileXS = innerWidth < 481 const isMobileSM = innerWidth > 480 && innerWidth < 767 return {isMobileSM, isMobileXS, isMobile} } switch (action.type) { case APPLICATION_INIT: case UI_WINDOW_RESIZE: { const {isMobile, isMobileSM, isMobileXS} = computeMobileStatuses() return { ...state, isMobile, isMobileSM, isMobileXS } } case UI_OPEN_SIDEBAR: return { ...state, sidebarOpened: true } case LOCATION_CHANGE: case UI_CLOSE_SIDEBAR: return { ...state, sidebarOpened: false } default: return state } }
/* global Vuex */ import auth from '~/modules/Auth/Client/Assets/js/auth.store' import conversation from '~/modules/Conversation/Client/Assets/js/conversation.store' import message from '~/modules/Message/Client/Assets/js/message.store' import createLogger from 'vuex/dist/logger' const debug = process.env.NODE_ENV !== 'production' export default new Vuex.Store({ modules: { auth, conversation, message }, strict: debug, plugins: debug ? [createLogger()] : [] })
import { expect } from 'chai'; import { Record, Map } from 'immutable'; import mutator from '../../src/util/mutator'; describe('@mutator decorator', () => { it('should allow property sets on nested mutable Records', () => { class A extends Record({ thing: 'stuff', stuff: 'things' }) {} class Test extends Record({ a: new A(), b: 2 }) { @mutator mutate1() { this.a.thing = 'otherstuff'; } @mutator mutate2() { this.b = 4; } @mutator mutate3() { this.a.thing = 'otherstuff'; this.b = 4; } } const test = new Test(); expect(test.mutate1().toJS()).to.eql({ a: { thing: 'otherstuff', stuff: 'things' }, b: 2 }); expect(test.mutate2().toJS()).to.eql({ a: { thing: 'stuff', stuff: 'things' }, b: 4 }); expect(test.mutate3().toJS()).to.eql({ a: { thing: 'otherstuff', stuff: 'things' }, b: 4 }); }); it('should allow one mutator calling another', () => { class A extends Record({ thing: 'stuff', stuff: 'things' }) { @mutator mutate(thing) { this.thing = thing; } } class Test extends Record({ a: new A(), b: 2 }) { @mutator mutate(thing) { this.a.mutate(thing); } } const test = new Test(); expect(test.mutate('otherstuff').toJS()).to.eql({ a: { thing: 'otherstuff', stuff: 'things' }, b: 2 }); }); it('should allow calling a mutator more than once from another mutator', () => { class A extends Record({ things: Map() }) { @mutator add(key, value) { this.things.set(key, value); } } class Test extends Record({ a: new A(), b: 2 }) { @mutator addToA(entries) { for (const [key, value] of entries) { this.a.add(key, value); } } } const test = new Test(); expect(test.addToA([['a', 1], ['b', 2], ['c', 3]]).toJS()).to.eql({ a: { things: { a: 1, b: 2, c: 3 } }, b: 2 }); }); });