<commit_before>// Copyright 2010 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 Event Types.
 *
 * @author arv@google.com (Erik Arvidsson)
 */

goog.provide('goog.events.EventType');

goog.require('goog.userAgent');

/**
 * Returns a prefixed event name for the current browser.
 * @param {string} eventName The name of the event.
 * @return {string} The prefixed event name.
 * @suppress {missingRequire|missingProvide}
 * @private
 */
goog.events.getVendorPrefixedName_ = function(eventName) {
  return goog.userAgent.WEBKIT ?
      'webkit' + eventName :
      (goog.userAgent.OPERA ? 'o' + eventName.toLowerCase() :
                              eventName.toLowerCase());
};

/**
 * Constants for event names.
 * @enum {string}
 */
goog.events.EventType = {
  // Mouse events
  CLICK: 'click',
  RIGHTCLICK: 'rightclick',
  DBLCLICK: 'dblclick',
  MOUSEDOWN: 'mousedown',
  MOUSEUP: 'mouseup',
  MOUSEOVER: 'mouseover',
  MOUSEOUT: 'mouseout',
  MOUSEMOVE: 'mousemove',
  MOUSEENTER: 'mouseenter',
  MOUSELEAVE: 'mouseleave',
  // Select start is non-standard.
  // See http://msdn.microsoft.com/en-us/library/ie/ms536969(v=vs.85).aspx.
  SELECTSTART: 'selectstart',  // IE, Safari, Chrome

  // Wheel events
  // http://www.w3.org/TR/DOM-Level-3-Events/#events-wheelevents
  WHEEL: 'wheel',

  // Key events
  KEYPRESS: 'keypress',
  KEYDOWN: 'keydown',
  KEYUP: 'keyup',

  // Focus
  BLUR: 'blur',
  FOCUS: 'focus',
  DEACTIVATE: 'deactivate',  // IE only
  // NOTE: The following two events are not stable in cross-browser usage.
  //     WebKit and Opera implement DOMFocusIn/Out.
  //     IE implements focusin/out.
  //     Gecko implements neither see bug at
  //     https://bugzilla.mozilla.org/show_bug.cgi?id=396927.
  // The DOM Events Level 3 Draft deprecates DOMFocusIn in favor of focusin:
  //     http://dev.w3.org/2006/webapi/DOM-Level-3-Events/html/DOM3-Events.html
  // You can use FOCUS in Capture phase until implementations converge.
  FOCUSIN: goog.userAgent.IE ? 'focusin' : 'DOMFocusIn',
  FOCUSOUT: goog.userAgent.IE ? 'focusout' : 'DOMFocusOut',

  // Forms
  CHANGE: 'change',
  RESET: 'reset',
  SELECT: 'select',
  SUBMIT: 'submit',
  INPUT: 'input',
  PROPERTYCHANGE: 'propertychange',  // IE only

  // Drag and drop
  DRAGSTART: 'dragstart',
  DRAG: 'drag',
  DRAGENTER: 'dragenter',
  DRAGOVER: 'dragover',
  DRAGLEAVE: 'dragleave',
  DROP: 'drop',
  DRAGEND: 'dragend',

  // Touch events
  // Note that other touch events exist, but we should follow the W3C list here.
  // http://www.w3.org/TR/touch-events/#list-of-touchevent-types
  TOUCHSTART: 'touchstart',
  TOUCHMOVE: 'touchmove',
  TOUCHEND: 'touchend',
  TOUCHCANCEL: 'touchcancel',

  // Misc
  BEFOREUNLOAD: 'beforeunload',
  CONSOLEMESSAGE: 'consolemessage',
  CONTEXTMENU: 'contextmenu',
  DOMCONTENTLOADED: 'DOMContentLoaded',
  ERROR: 'error',
  HELP: 'help',
  LOAD: 'load',
  LOSECAPTURE: 'losecapture',
  ORIENTATIONCHANGE: 'orientationchange',
  READYSTATECHANGE: 'readystatechange',
  RESIZE: 'resize',
  SCROLL: 'scroll',
  UNLOAD: 'unload',

  // HTML 5 History events
  // See http://www.w3.org/TR/html5/browsers.html#event-definitions-0
  HASHCHANGE: 'hashchange',
  PAGEHIDE: 'pagehide',
  PAGESHOW: 'pageshow',
  POPSTATE: 'popstate',

  // Copy and Paste
  // Support is limited. Make sure it works on your favorite browser
  // before using.
  // http://www.quirksmode.org/dom/events/cutcopypaste.html
  COPY: 'copy',
  PASTE: 'paste',
  CUT: 'cut',
  BEFORECOPY: 'beforecopy',
  BEFORECUT: 'beforecut',
  BEFOREPASTE: 'beforepaste',

  // HTML5 online/offline events.
  // http://www.w3.org/TR/offline-webapps/#related
  ONLINE: 'online',
  OFFLINE: 'offline',

  // HTML 5 worker events
  MESSAGE: 'message',
  CONNECT: 'connect',

  // CSS animation events.
  /** @suppress {missingRequire} */
  ANIMATIONSTART: goog.events.getVendorPrefixedName_('AnimationStart'),
  /** @suppress {missingRequire} */
  ANIMATIONEND: goog.events.getVendorPrefixedName_('AnimationEnd'),
  /** @suppress {missingRequire} */
  ANIMATIONITERATION: goog.events.getVendorPrefixedName_('AnimationIteration'),

  // CSS transition events. Based on the browser support described at:
  // https://developer.mozilla.org/en/css/css_transitions#Browser_compatibility
  /** @suppress {missingRequire} */
  TRANSITIONEND: goog.events.getVendorPrefixedName_('TransitionEnd'),

  // W3C Pointer Events
  // http://www.w3.org/TR/pointerevents/
  POINTERDOWN: 'pointerdown',
  POINTERUP: 'pointerup',
  POINTERCANCEL: 'pointercancel',
  POINTERMOVE: 'pointermove',
  POINTEROVER: 'pointerover',
  POINTEROUT: 'pointerout',
  POINTERENTER: 'pointerenter',
  POINTERLEAVE: 'pointerleave',
  GOTPOINTERCAPTURE: 'gotpointercapture',
  LOSTPOINTERCAPTURE: 'lostpointercapture',

  // IE specific events.
  // See http://msdn.microsoft.com/en-us/library/ie/hh772103(v=vs.85).aspx
  // Note: these events will be supplanted in IE11.
  MSGESTURECHANGE: 'MSGestureChange',
  MSGESTUREEND: 'MSGestureEnd',
  MSGESTUREHOLD: 'MSGestureHold',
  MSGESTURESTART: 'MSGestureStart',
  MSGESTURETAP: 'MSGestureTap',
  MSGOTPOINTERCAPTURE: 'MSGotPointerCapture',
  MSINERTIASTART: 'MSInertiaStart',
  MSLOSTPOINTERCAPTURE: 'MSLostPointerCapture',
  MSPOINTERCANCEL: 'MSPointerCancel',
  MSPOINTERDOWN: 'MSPointerDown',
  MSPOINTERENTER: 'MSPointerEnter',
  MSPOINTERHOVER: 'MSPointerHover',
  MSPOINTERLEAVE: 'MSPointerLeave',
  MSPOINTERMOVE: 'MSPointerMove',
  MSPOINTEROUT: 'MSPointerOut',
  MSPOINTEROVER: 'MSPointerOver',
  MSPOINTERUP: 'MSPointerUp',

  // Native IMEs/input tools events.
  TEXT: 'text',
  TEXTINPUT: 'textInput',
  COMPOSITIONSTART: 'compositionstart',
  COMPOSITIONUPDATE: 'compositionupdate',
  COMPOSITIONEND: 'compositionend',

  // Webview tag events
  // See http://developer.chrome.com/dev/apps/webview_tag.html
  EXIT: 'exit',
  LOADABORT: 'loadabort',
  LOADCOMMIT: 'loadcommit',
  LOADREDIRECT: 'loadredirect',
  LOADSTART: 'loadstart',
  LOADSTOP: 'loadstop',
  RESPONSIVE: 'responsive',
  SIZECHANGED: 'sizechanged',
  UNRESPONSIVE: 'unresponsive',

  // HTML5 Page Visibility API.  See details at
  // {@code goog.labs.dom.PageVisibilityMonitor}.
  VISIBILITYCHANGE: 'visibilitychange',

  // LocalStorage event.
  STORAGE: 'storage',

  // DOM Level 2 mutation events (deprecated).
  DOMSUBTREEMODIFIED: 'DOMSubtreeModified',
  DOMNODEINSERTED: 'DOMNodeInserted',
  DOMNODEREMOVED: 'DOMNodeRemoved',
  DOMNODEREMOVEDFROMDOCUMENT: 'DOMNodeRemovedFromDocument',
  DOMNODEINSERTEDINTODOCUMENT: 'DOMNodeInsertedIntoDocument',
  DOMATTRMODIFIED: 'DOMAttrModified',
  DOMCHARACTERDATAMODIFIED: 'DOMCharacterDataModified',

  // Print events.
  BEFOREPRINT: 'beforeprint',
  AFTERPRINT: 'afterprint'
};
<commit_msg>Add the 'timeupdate' event to goog.events.EventType<commit_after>// Copyright 2010 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 Event Types.
 *
 * @author arv@google.com (Erik Arvidsson)
 */

goog.provide('goog.events.EventType');

goog.require('goog.userAgent');

/**
 * Returns a prefixed event name for the current browser.
 * @param {string} eventName The name of the event.
 * @return {string} The prefixed event name.
 * @suppress {missingRequire|missingProvide}
 * @private
 */
goog.events.getVendorPrefixedName_ = function(eventName) {
  return goog.userAgent.WEBKIT ?
      'webkit' + eventName :
      (goog.userAgent.OPERA ? 'o' + eventName.toLowerCase() :
                              eventName.toLowerCase());
};

/**
 * Constants for event names.
 * @enum {string}
 */
goog.events.EventType = {
  // Mouse events
  CLICK: 'click',
  RIGHTCLICK: 'rightclick',
  DBLCLICK: 'dblclick',
  MOUSEDOWN: 'mousedown',
  MOUSEUP: 'mouseup',
  MOUSEOVER: 'mouseover',
  MOUSEOUT: 'mouseout',
  MOUSEMOVE: 'mousemove',
  MOUSEENTER: 'mouseenter',
  MOUSELEAVE: 'mouseleave',
  // Select start is non-standard.
  // See http://msdn.microsoft.com/en-us/library/ie/ms536969(v=vs.85).aspx.
  SELECTSTART: 'selectstart',  // IE, Safari, Chrome

  // Wheel events
  // http://www.w3.org/TR/DOM-Level-3-Events/#events-wheelevents
  WHEEL: 'wheel',

  // Key events
  KEYPRESS: 'keypress',
  KEYDOWN: 'keydown',
  KEYUP: 'keyup',

  // Focus
  BLUR: 'blur',
  FOCUS: 'focus',
  DEACTIVATE: 'deactivate',  // IE only
  // NOTE: The following two events are not stable in cross-browser usage.
  //     WebKit and Opera implement DOMFocusIn/Out.
  //     IE implements focusin/out.
  //     Gecko implements neither see bug at
  //     https://bugzilla.mozilla.org/show_bug.cgi?id=396927.
  // The DOM Events Level 3 Draft deprecates DOMFocusIn in favor of focusin:
  //     http://dev.w3.org/2006/webapi/DOM-Level-3-Events/html/DOM3-Events.html
  // You can use FOCUS in Capture phase until implementations converge.
  FOCUSIN: goog.userAgent.IE ? 'focusin' : 'DOMFocusIn',
  FOCUSOUT: goog.userAgent.IE ? 'focusout' : 'DOMFocusOut',

  // Forms
  CHANGE: 'change',
  RESET: 'reset',
  SELECT: 'select',
  SUBMIT: 'submit',
  INPUT: 'input',
  PROPERTYCHANGE: 'propertychange',  // IE only

  // Drag and drop
  DRAGSTART: 'dragstart',
  DRAG: 'drag',
  DRAGENTER: 'dragenter',
  DRAGOVER: 'dragover',
  DRAGLEAVE: 'dragleave',
  DROP: 'drop',
  DRAGEND: 'dragend',

  // Touch events
  // Note that other touch events exist, but we should follow the W3C list here.
  // http://www.w3.org/TR/touch-events/#list-of-touchevent-types
  TOUCHSTART: 'touchstart',
  TOUCHMOVE: 'touchmove',
  TOUCHEND: 'touchend',
  TOUCHCANCEL: 'touchcancel',

  // Misc
  BEFOREUNLOAD: 'beforeunload',
  CONSOLEMESSAGE: 'consolemessage',
  CONTEXTMENU: 'contextmenu',
  DOMCONTENTLOADED: 'DOMContentLoaded',
  ERROR: 'error',
  HELP: 'help',
  LOAD: 'load',
  LOSECAPTURE: 'losecapture',
  ORIENTATIONCHANGE: 'orientationchange',
  READYSTATECHANGE: 'readystatechange',
  RESIZE: 'resize',
  SCROLL: 'scroll',
  TIMEUPDATE: 'timeupdate',
  UNLOAD: 'unload',

  // HTML 5 History events
  // See http://www.w3.org/TR/html5/browsers.html#event-definitions-0
  HASHCHANGE: 'hashchange',
  PAGEHIDE: 'pagehide',
  PAGESHOW: 'pageshow',
  POPSTATE: 'popstate',

  // Copy and Paste
  // Support is limited. Make sure it works on your favorite browser
  // before using.
  // http://www.quirksmode.org/dom/events/cutcopypaste.html
  COPY: 'copy',
  PASTE: 'paste',
  CUT: 'cut',
  BEFORECOPY: 'beforecopy',
  BEFORECUT: 'beforecut',
  BEFOREPASTE: 'beforepaste',

  // HTML5 online/offline events.
  // http://www.w3.org/TR/offline-webapps/#related
  ONLINE: 'online',
  OFFLINE: 'offline',

  // HTML 5 worker events
  MESSAGE: 'message',
  CONNECT: 'connect',

  // CSS animation events.
  /** @suppress {missingRequire} */
  ANIMATIONSTART: goog.events.getVendorPrefixedName_('AnimationStart'),
  /** @suppress {missingRequire} */
  ANIMATIONEND: goog.events.getVendorPrefixedName_('AnimationEnd'),
  /** @suppress {missingRequire} */
  ANIMATIONITERATION: goog.events.getVendorPrefixedName_('AnimationIteration'),

  // CSS transition events. Based on the browser support described at:
  // https://developer.mozilla.org/en/css/css_transitions#Browser_compatibility
  /** @suppress {missingRequire} */
  TRANSITIONEND: goog.events.getVendorPrefixedName_('TransitionEnd'),

  // W3C Pointer Events
  // http://www.w3.org/TR/pointerevents/
  POINTERDOWN: 'pointerdown',
  POINTERUP: 'pointerup',
  POINTERCANCEL: 'pointercancel',
  POINTERMOVE: 'pointermove',
  POINTEROVER: 'pointerover',
  POINTEROUT: 'pointerout',
  POINTERENTER: 'pointerenter',
  POINTERLEAVE: 'pointerleave',
  GOTPOINTERCAPTURE: 'gotpointercapture',
  LOSTPOINTERCAPTURE: 'lostpointercapture',

  // IE specific events.
  // See http://msdn.microsoft.com/en-us/library/ie/hh772103(v=vs.85).aspx
  // Note: these events will be supplanted in IE11.
  MSGESTURECHANGE: 'MSGestureChange',
  MSGESTUREEND: 'MSGestureEnd',
  MSGESTUREHOLD: 'MSGestureHold',
  MSGESTURESTART: 'MSGestureStart',
  MSGESTURETAP: 'MSGestureTap',
  MSGOTPOINTERCAPTURE: 'MSGotPointerCapture',
  MSINERTIASTART: 'MSInertiaStart',
  MSLOSTPOINTERCAPTURE: 'MSLostPointerCapture',
  MSPOINTERCANCEL: 'MSPointerCancel',
  MSPOINTERDOWN: 'MSPointerDown',
  MSPOINTERENTER: 'MSPointerEnter',
  MSPOINTERHOVER: 'MSPointerHover',
  MSPOINTERLEAVE: 'MSPointerLeave',
  MSPOINTERMOVE: 'MSPointerMove',
  MSPOINTEROUT: 'MSPointerOut',
  MSPOINTEROVER: 'MSPointerOver',
  MSPOINTERUP: 'MSPointerUp',

  // Native IMEs/input tools events.
  TEXT: 'text',
  TEXTINPUT: 'textInput',
  COMPOSITIONSTART: 'compositionstart',
  COMPOSITIONUPDATE: 'compositionupdate',
  COMPOSITIONEND: 'compositionend',

  // Webview tag events
  // See http://developer.chrome.com/dev/apps/webview_tag.html
  EXIT: 'exit',
  LOADABORT: 'loadabort',
  LOADCOMMIT: 'loadcommit',
  LOADREDIRECT: 'loadredirect',
  LOADSTART: 'loadstart',
  LOADSTOP: 'loadstop',
  RESPONSIVE: 'responsive',
  SIZECHANGED: 'sizechanged',
  UNRESPONSIVE: 'unresponsive',

  // HTML5 Page Visibility API.  See details at
  // {@code goog.labs.dom.PageVisibilityMonitor}.
  VISIBILITYCHANGE: 'visibilitychange',

  // LocalStorage event.
  STORAGE: 'storage',

  // DOM Level 2 mutation events (deprecated).
  DOMSUBTREEMODIFIED: 'DOMSubtreeModified',
  DOMNODEINSERTED: 'DOMNodeInserted',
  DOMNODEREMOVED: 'DOMNodeRemoved',
  DOMNODEREMOVEDFROMDOCUMENT: 'DOMNodeRemovedFromDocument',
  DOMNODEINSERTEDINTODOCUMENT: 'DOMNodeInsertedIntoDocument',
  DOMATTRMODIFIED: 'DOMAttrModified',
  DOMCHARACTERDATAMODIFIED: 'DOMCharacterDataModified',

  // Print events.
  BEFOREPRINT: 'beforeprint',
  AFTERPRINT: 'afterprint'
};
<|endoftext|>


<commit_before>// Copyright 2010 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 Event Types.
 *
 * @author arv@google.com (Erik Arvidsson)
 * @author mirkov@google.com (Mirko Visontai)
 */

goog.provide('goog.events.EventType');

goog.require('goog.userAgent');

/**
 * Returns a prefixed event name for the current browser.
 * @param {string} eventName The name of the event.
 * @return {string} The prefixed event name.
 * @suppress {missingRequire|missingProvide}
 * @private
 */
goog.events.getVendorPrefixedName_ = function(eventName) {
  return goog.userAgent.WEBKIT ? 'webkit' + eventName :
      (goog.userAgent.OPERA ? 'o' + eventName.toLowerCase() :
          eventName.toLowerCase());
};

/**
 * Constants for event names.
 * @enum {string}
 */
goog.events.EventType = {
  // Mouse events
  CLICK: 'click',
  DBLCLICK: 'dblclick',
  MOUSEDOWN: 'mousedown',
  MOUSEUP: 'mouseup',
  MOUSEOVER: 'mouseover',
  MOUSEOUT: 'mouseout',
  MOUSEMOVE: 'mousemove',
  MOUSEENTER: 'mouseenter',
  MOUSELEAVE: 'mouseleave',
  // Select start is non-standard.
  // See http://msdn.microsoft.com/en-us/library/ie/ms536969(v=vs.85).aspx.
  SELECTSTART: 'selectstart', // IE, Safari, Chrome

  // Key events
  KEYPRESS: 'keypress',
  KEYDOWN: 'keydown',
  KEYUP: 'keyup',

  // Focus
  BLUR: 'blur',
  FOCUS: 'focus',
  DEACTIVATE: 'deactivate', // IE only
  // NOTE: The following two events are not stable in cross-browser usage.
  //     WebKit and Opera implement DOMFocusIn/Out.
  //     IE implements focusin/out.
  //     Gecko implements neither see bug at
  //     https://bugzilla.mozilla.org/show_bug.cgi?id=396927.
  // The DOM Events Level 3 Draft deprecates DOMFocusIn in favor of focusin:
  //     http://dev.w3.org/2006/webapi/DOM-Level-3-Events/html/DOM3-Events.html
  // You can use FOCUS in Capture phase until implementations converge.
  FOCUSIN: goog.userAgent.IE ? 'focusin' : 'DOMFocusIn',
  FOCUSOUT: goog.userAgent.IE ? 'focusout' : 'DOMFocusOut',

  // Forms
  CHANGE: 'change',
  SELECT: 'select',
  SUBMIT: 'submit',
  INPUT: 'input',
  PROPERTYCHANGE: 'propertychange', // IE only

  // Drag and drop
  DRAGSTART: 'dragstart',
  DRAG: 'drag',
  DRAGENTER: 'dragenter',
  DRAGOVER: 'dragover',
  DRAGLEAVE: 'dragleave',
  DROP: 'drop',
  DRAGEND: 'dragend',

  // WebKit touch events.
  TOUCHSTART: 'touchstart',
  TOUCHMOVE: 'touchmove',
  TOUCHEND: 'touchend',
  TOUCHCANCEL: 'touchcancel',

  // Misc
  BEFOREUNLOAD: 'beforeunload',
  CONSOLEMESSAGE: 'consolemessage',
  CONTEXTMENU: 'contextmenu',
  DOMCONTENTLOADED: 'DOMContentLoaded',
  ERROR: 'error',
  HELP: 'help',
  LOAD: 'load',
  LOSECAPTURE: 'losecapture',
  ORIENTATIONCHANGE: 'orientationchange',
  READYSTATECHANGE: 'readystatechange',
  RESIZE: 'resize',
  SCROLL: 'scroll',
  UNLOAD: 'unload',

  // HTML 5 History events
  // See http://www.w3.org/TR/html5/history.html#event-definitions
  HASHCHANGE: 'hashchange',
  PAGEHIDE: 'pagehide',
  PAGESHOW: 'pageshow',
  POPSTATE: 'popstate',

  // Copy and Paste
  // Support is limited. Make sure it works on your favorite browser
  // before using.
  // http://www.quirksmode.org/dom/events/cutcopypaste.html
  COPY: 'copy',
  PASTE: 'paste',
  CUT: 'cut',
  BEFORECOPY: 'beforecopy',
  BEFORECUT: 'beforecut',
  BEFOREPASTE: 'beforepaste',

  // HTML5 online/offline events.
  // http://www.w3.org/TR/offline-webapps/#related
  ONLINE: 'online',
  OFFLINE: 'offline',

  // HTML 5 worker events
  MESSAGE: 'message',
  CONNECT: 'connect',

  // CSS animation events.
  /** @suppress {missingRequire} */
  ANIMATIONSTART: goog.events.getVendorPrefixedName_('AnimationStart'),
  /** @suppress {missingRequire} */
  ANIMATIONEND: goog.events.getVendorPrefixedName_('AnimationEnd'),
  /** @suppress {missingRequire} */
  ANIMATIONITERATION: goog.events.getVendorPrefixedName_('AnimationIteration'),

  // CSS transition events. Based on the browser support described at:
  // https://developer.mozilla.org/en/css/css_transitions#Browser_compatibility
  /** @suppress {missingRequire} */
  TRANSITIONEND: goog.events.getVendorPrefixedName_('TransitionEnd'),

  // W3C Pointer Events
  // http://www.w3.org/TR/pointerevents/
  POINTERDOWN: 'pointerdown',
  POINTERUP: 'pointerup',
  POINTERCANCEL: 'pointercancel',
  POINTERMOVE: 'pointermove',
  POINTEROVER: 'pointerover',
  POINTEROUT: 'pointerout',
  POINTERENTER: 'pointerenter',
  POINTERLEAVE: 'pointerleave',
  GOTPOINTERCAPTURE: 'gotpointercapture',
  LOSTPOINTERCAPTURE: 'lostpointercapture',

  // IE specific events.
  // See http://msdn.microsoft.com/en-us/library/ie/hh772103(v=vs.85).aspx
  // Note: these events will be supplanted in IE11.
  MSGESTURECHANGE: 'MSGestureChange',
  MSGESTUREEND: 'MSGestureEnd',
  MSGESTUREHOLD: 'MSGestureHold',
  MSGESTURESTART: 'MSGestureStart',
  MSGESTURETAP: 'MSGestureTap',
  MSGOTPOINTERCAPTURE: 'MSGotPointerCapture',
  MSINERTIASTART: 'MSInertiaStart',
  MSLOSTPOINTERCAPTURE: 'MSLostPointerCapture',
  MSPOINTERCANCEL: 'MSPointerCancel',
  MSPOINTERDOWN: 'MSPointerDown',
  MSPOINTERENTER: 'MSPointerEnter',
  MSPOINTERHOVER: 'MSPointerHover',
  MSPOINTERLEAVE: 'MSPointerLeave',
  MSPOINTERMOVE: 'MSPointerMove',
  MSPOINTEROUT: 'MSPointerOut',
  MSPOINTEROVER: 'MSPointerOver',
  MSPOINTERUP: 'MSPointerUp',

  // Native IMEs/input tools events.
  TEXTINPUT: 'textinput',
  COMPOSITIONSTART: 'compositionstart',
  COMPOSITIONUPDATE: 'compositionupdate',
  COMPOSITIONEND: 'compositionend',

  // Webview tag events
  // See http://developer.chrome.com/dev/apps/webview_tag.html
  EXIT: 'exit',
  LOADABORT: 'loadabort',
  LOADCOMMIT: 'loadcommit',
  LOADREDIRECT: 'loadredirect',
  LOADSTART: 'loadstart',
  LOADSTOP: 'loadstop',
  RESPONSIVE: 'responsive',
  SIZECHANGED: 'sizechanged',
  UNRESPONSIVE: 'unresponsive',

  // HTML5 Page Visibility API.  See details at
  // {@code goog.labs.dom.PageVisibilityMonitor}.
  VISIBILITYCHANGE: 'visibilitychange',

  // LocalStorage event.
  STORAGE: 'storage'
};
<commit_msg>Add symbolic constants for DOM Level 2 mutation events. ------------- Created by MOE: http://code.google.com/p/moe-java MOE_MIGRATED_REVID=64057500<commit_after>// Copyright 2010 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 Event Types.
 *
 * @author arv@google.com (Erik Arvidsson)
 * @author mirkov@google.com (Mirko Visontai)
 */

goog.provide('goog.events.EventType');

goog.require('goog.userAgent');

/**
 * Returns a prefixed event name for the current browser.
 * @param {string} eventName The name of the event.
 * @return {string} The prefixed event name.
 * @suppress {missingRequire|missingProvide}
 * @private
 */
goog.events.getVendorPrefixedName_ = function(eventName) {
  return goog.userAgent.WEBKIT ? 'webkit' + eventName :
      (goog.userAgent.OPERA ? 'o' + eventName.toLowerCase() :
          eventName.toLowerCase());
};

/**
 * Constants for event names.
 * @enum {string}
 */
goog.events.EventType = {
  // Mouse events
  CLICK: 'click',
  DBLCLICK: 'dblclick',
  MOUSEDOWN: 'mousedown',
  MOUSEUP: 'mouseup',
  MOUSEOVER: 'mouseover',
  MOUSEOUT: 'mouseout',
  MOUSEMOVE: 'mousemove',
  MOUSEENTER: 'mouseenter',
  MOUSELEAVE: 'mouseleave',
  // Select start is non-standard.
  // See http://msdn.microsoft.com/en-us/library/ie/ms536969(v=vs.85).aspx.
  SELECTSTART: 'selectstart', // IE, Safari, Chrome

  // Key events
  KEYPRESS: 'keypress',
  KEYDOWN: 'keydown',
  KEYUP: 'keyup',

  // Focus
  BLUR: 'blur',
  FOCUS: 'focus',
  DEACTIVATE: 'deactivate', // IE only
  // NOTE: The following two events are not stable in cross-browser usage.
  //     WebKit and Opera implement DOMFocusIn/Out.
  //     IE implements focusin/out.
  //     Gecko implements neither see bug at
  //     https://bugzilla.mozilla.org/show_bug.cgi?id=396927.
  // The DOM Events Level 3 Draft deprecates DOMFocusIn in favor of focusin:
  //     http://dev.w3.org/2006/webapi/DOM-Level-3-Events/html/DOM3-Events.html
  // You can use FOCUS in Capture phase until implementations converge.
  FOCUSIN: goog.userAgent.IE ? 'focusin' : 'DOMFocusIn',
  FOCUSOUT: goog.userAgent.IE ? 'focusout' : 'DOMFocusOut',

  // Forms
  CHANGE: 'change',
  SELECT: 'select',
  SUBMIT: 'submit',
  INPUT: 'input',
  PROPERTYCHANGE: 'propertychange', // IE only

  // Drag and drop
  DRAGSTART: 'dragstart',
  DRAG: 'drag',
  DRAGENTER: 'dragenter',
  DRAGOVER: 'dragover',
  DRAGLEAVE: 'dragleave',
  DROP: 'drop',
  DRAGEND: 'dragend',

  // WebKit touch events.
  TOUCHSTART: 'touchstart',
  TOUCHMOVE: 'touchmove',
  TOUCHEND: 'touchend',
  TOUCHCANCEL: 'touchcancel',

  // Misc
  BEFOREUNLOAD: 'beforeunload',
  CONSOLEMESSAGE: 'consolemessage',
  CONTEXTMENU: 'contextmenu',
  DOMCONTENTLOADED: 'DOMContentLoaded',
  ERROR: 'error',
  HELP: 'help',
  LOAD: 'load',
  LOSECAPTURE: 'losecapture',
  ORIENTATIONCHANGE: 'orientationchange',
  READYSTATECHANGE: 'readystatechange',
  RESIZE: 'resize',
  SCROLL: 'scroll',
  UNLOAD: 'unload',

  // HTML 5 History events
  // See http://www.w3.org/TR/html5/history.html#event-definitions
  HASHCHANGE: 'hashchange',
  PAGEHIDE: 'pagehide',
  PAGESHOW: 'pageshow',
  POPSTATE: 'popstate',

  // Copy and Paste
  // Support is limited. Make sure it works on your favorite browser
  // before using.
  // http://www.quirksmode.org/dom/events/cutcopypaste.html
  COPY: 'copy',
  PASTE: 'paste',
  CUT: 'cut',
  BEFORECOPY: 'beforecopy',
  BEFORECUT: 'beforecut',
  BEFOREPASTE: 'beforepaste',

  // HTML5 online/offline events.
  // http://www.w3.org/TR/offline-webapps/#related
  ONLINE: 'online',
  OFFLINE: 'offline',

  // HTML 5 worker events
  MESSAGE: 'message',
  CONNECT: 'connect',

  // CSS animation events.
  /** @suppress {missingRequire} */
  ANIMATIONSTART: goog.events.getVendorPrefixedName_('AnimationStart'),
  /** @suppress {missingRequire} */
  ANIMATIONEND: goog.events.getVendorPrefixedName_('AnimationEnd'),
  /** @suppress {missingRequire} */
  ANIMATIONITERATION: goog.events.getVendorPrefixedName_('AnimationIteration'),

  // CSS transition events. Based on the browser support described at:
  // https://developer.mozilla.org/en/css/css_transitions#Browser_compatibility
  /** @suppress {missingRequire} */
  TRANSITIONEND: goog.events.getVendorPrefixedName_('TransitionEnd'),

  // W3C Pointer Events
  // http://www.w3.org/TR/pointerevents/
  POINTERDOWN: 'pointerdown',
  POINTERUP: 'pointerup',
  POINTERCANCEL: 'pointercancel',
  POINTERMOVE: 'pointermove',
  POINTEROVER: 'pointerover',
  POINTEROUT: 'pointerout',
  POINTERENTER: 'pointerenter',
  POINTERLEAVE: 'pointerleave',
  GOTPOINTERCAPTURE: 'gotpointercapture',
  LOSTPOINTERCAPTURE: 'lostpointercapture',

  // IE specific events.
  // See http://msdn.microsoft.com/en-us/library/ie/hh772103(v=vs.85).aspx
  // Note: these events will be supplanted in IE11.
  MSGESTURECHANGE: 'MSGestureChange',
  MSGESTUREEND: 'MSGestureEnd',
  MSGESTUREHOLD: 'MSGestureHold',
  MSGESTURESTART: 'MSGestureStart',
  MSGESTURETAP: 'MSGestureTap',
  MSGOTPOINTERCAPTURE: 'MSGotPointerCapture',
  MSINERTIASTART: 'MSInertiaStart',
  MSLOSTPOINTERCAPTURE: 'MSLostPointerCapture',
  MSPOINTERCANCEL: 'MSPointerCancel',
  MSPOINTERDOWN: 'MSPointerDown',
  MSPOINTERENTER: 'MSPointerEnter',
  MSPOINTERHOVER: 'MSPointerHover',
  MSPOINTERLEAVE: 'MSPointerLeave',
  MSPOINTERMOVE: 'MSPointerMove',
  MSPOINTEROUT: 'MSPointerOut',
  MSPOINTEROVER: 'MSPointerOver',
  MSPOINTERUP: 'MSPointerUp',

  // Native IMEs/input tools events.
  TEXTINPUT: 'textinput',
  COMPOSITIONSTART: 'compositionstart',
  COMPOSITIONUPDATE: 'compositionupdate',
  COMPOSITIONEND: 'compositionend',

  // Webview tag events
  // See http://developer.chrome.com/dev/apps/webview_tag.html
  EXIT: 'exit',
  LOADABORT: 'loadabort',
  LOADCOMMIT: 'loadcommit',
  LOADREDIRECT: 'loadredirect',
  LOADSTART: 'loadstart',
  LOADSTOP: 'loadstop',
  RESPONSIVE: 'responsive',
  SIZECHANGED: 'sizechanged',
  UNRESPONSIVE: 'unresponsive',

  // HTML5 Page Visibility API.  See details at
  // {@code goog.labs.dom.PageVisibilityMonitor}.
  VISIBILITYCHANGE: 'visibilitychange',

  // LocalStorage event.
  STORAGE: 'storage',

  // DOM Level 2 mutation events (deprecated).
  DOMSUBTREEMODIFIED: 'DOMSubtreeModified',
  DOMNODEINSERTED: 'DOMNodeInserted',
  DOMNODEREMOVED: 'DOMNodeRemoved',
  DOMNODEREMOVEDFROMDOCUMENT: 'DOMNodeRemovedFromDocument',
  DOMNODEINSERTEDINTODOCUMENT: 'DOMNodeInsertedIntoDocument',
  DOMATTRMODIFIED: 'DOMAttrModified',
  DOMCHARACTERDATAMODIFIED: 'DOMCharacterDataModified'
};
<|endoftext|>


<commit_before>/* eslint-disable no-unused-vars */
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Select from '../select';
const Option = Select.Option;

class Options extends Component {
  constructor(props) {
    super(props);
    this.state = {
      value: props.pageSize
    }
  }
  onChange = value => {
    this.setState({value});
    this.props.onShowSizeChange(parseInt(value));
  }
  render() {
    const { prefixCls, pageSizeOptions, size } = this.props;
    const { value } = this.state;
    return (

        <Select value={value} size={size} onChange={this.onChange} ref='select'>
          {
            pageSizeOptions.map((item, index) => <Option value={item} key={index}>{item}条／页</Option>)
          }
        </Select>

    )
  }
}

export default Options;
<commit_msg>commit<commit_after>/* eslint-disable no-unused-vars */
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Select from '../select';
const Option = Select.Option;

class Options extends Component {
  constructor(props) {
    super(props);
    this.state = {
      value: props.pageSize.toString()
    }
  }
  onChange = value => {
    this.setState({value});
    this.props.onShowSizeChange(parseInt(value));
  }
  render() {
    const { prefixCls, pageSizeOptions, size } = this.props;
    const { value } = this.state;
    return (

        <Select value={value} size={size} onChange={this.onChange} ref='select'>
          {
            pageSizeOptions.map((item, index) => <Option value={item} key={index}>{item}条／页</Option>)
          }
        </Select>

    )
  }
}

export default Options;
<|endoftext|>


<commit_before>// Import Modules
const INDEX = require('../../index.js')

// Import Packages
const _ = require('lodash')
const merge = require('merge')

// Define helper variables
const ws = INDEX.connection
const mongo = INDEX.mongo

/**
 * Function to watch for updates on all collections
 */
const watchUpdates = () => {
  for (var model in mongo.models) {
    ws.subscribe(`conapp.${model}.update`, function(data) {
      mongo.models[model]
      .findOne({_id: item._id}).exec()
      .then(res => {
        // deletes save so it won't conflict on merging
        delete res.save

        // merges with new data
        merge(res, data)

        // saves Updated item
        return res.save()
      })
      .then(res => {
        console.log(res)
      })
      .catch(err => console.log(err))
    })
  }
}

/**
 * Function to watch for inserts on all collections
 */
const watchInserts = () => {
  for (var model in mongo.models) {
    ws.subscribe(`conapp.${model}.insert`, function(data) {
      const doc = new mongo.models[model](data)
      doc.save()
        .then(res => {
          console.log(res)
        })
        .catch(err => console.log(err))
    })
  }
}

/**
 * Function to watch for inserts on all collections
 */
const watchSync = () => {
  for (var model in mongo.models) {
    ws.subscribe(`conapp.fakenews.sync`, function() {
      console.log(`CALLED - conapp.${model}.sync`)
      mongo.models[model]
        .find({}).exec()
        .then(data => {
		console.log('----------------------------')
		console.log(data)
		ws.publish(`conapp.${model}.fetch.sync`, data)

	})
        .catch(err => console.log(err))
    })
  }
}

const watchersObj = {
  watchUpdates: watchUpdates,
  watchInserts: watchInserts,
  watchSync: watchSync
}

const runAllWatchers = () => _.mapValues(
  watchersObj,
  watcher => {
    var status = true

    try {
      watcher()
    } catch(e) {
      status = e
    }

    return status
  }
)

// Exports
module.exports = {
  list: watchersObj,
  watchersStatus: runAllWatchers()
}
<commit_msg>debbug<commit_after>// Import Modules
const INDEX = require('../../index.js')

// Import Packages
const _ = require('lodash')
const merge = require('merge')

// Define helper variables
const ws = INDEX.connection
const mongo = INDEX.mongo

/**
 * Function to watch for updates on all collections
 */
const watchUpdates = () => {
  for (var model in mongo.models) {
    ws.subscribe(`conapp.${model}.update`, function(data) {
      mongo.models[model]
      .findOne({_id: item._id}).exec()
      .then(res => {
        // deletes save so it won't conflict on merging
        delete res.save

        // merges with new data
        merge(res, data)

        // saves Updated item
        return res.save()
      })
      .then(res => {
        console.log(res)
      })
      .catch(err => console.log(err))
    })
  }
}

/**
 * Function to watch for inserts on all collections
 */
const watchInserts = () => {
  for (var model in mongo.models) {
    ws.subscribe(`conapp.${model}.insert`, function(data) {
      const doc = new mongo.models[model](data)
      doc.save()
        .then(res => {
          console.log(res)
        })
        .catch(err => console.log(err))
    })
  }
}

/**
 * Function to watch for inserts on all collections
 */
const watchSync = () => {
  console.log('Starting watch for sync routes')
  for (var model in mongo.models) {
    console.log('sync for '+ model)
    console.log(`Subscribing for conapp.${model}.sync`)
    ws.subscribe(`conapp.${model}.sync`, function() {
      console.log(`CALLED - conapp.${model}.sync`)
      mongo.models[model]
        .find({}).exec()
        .then(data => {
          console.log('Mongo consulted')
          console.log(data)
          ws.publish(`conapp.${model}.fetch.sync`, data)
	       })
        .catch(err => console.log(err))
    })
  }
}

const watchersObj = {
  watchUpdates: watchUpdates,
  watchInserts: watchInserts,
  watchSync: watchSync
}

const runAllWatchers = () => _.mapValues(
  watchersObj,
  watcher => {
    var status = true

    try {
      watcher()
    } catch(e) {
      status = e
    }

    return status
  }
)

// Exports
module.exports = {
  list: watchersObj,
  watchersStatus: runAllWatchers()
}
<|endoftext|>


<commit_before>"07-12-2007.9"<commit_msg>Upping version number for new release of Dojo coming up<commit_after>"08-15-2007.1"<|endoftext|>


<commit_before>// 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.

// Usage: The passed in function is called when the page is ready.
// CouchApp passes in the app object, which takes care of linking to
// the proper database, and provides access to the CouchApp helpers.
// $.CouchApp(function(app) {
//    app.db.view(...)
//    ...
// });

(function($) {

  function f(n) {    // Format integers to have at least two digits.
      return n < 10 ? '0' + n : n;
  }

  Date.prototype.toJSON = function() {
      return this.getUTCFullYear()   + '/' +
           f(this.getUTCMonth() + 1) + '/' +
           f(this.getUTCDate())      + ' ' +
           f(this.getUTCHours())     + ':' +
           f(this.getUTCMinutes())   + ':' +
           f(this.getUTCSeconds())   + ' +0000';
  };

  function Design(db, name) {
    this.view = function(view, opts) {
      db.view(name+'/'+view, opts);
    };
  };

  var login;

  function init(app) {
    $(function() {
      var dbname = document.location.href.split('/')[3];
      var dname = unescape(document.location.href).split('/')[5];
      var db = $.couch.db(dbname);
      var design = new Design(db, dname);

      // docForm applies CouchDB behavior to HTML forms.
      function docForm(formSelector, opts) {
        var localFormDoc = {};
        opts = opts || {};
        opts.fields = opts.fields || [];

        // turn the form into deep json
        // field names like 'author-email' get turned into json like
        // {"author":{"email":"quentin@example.com"}}
        function formToDeepJSON(form, fields, doc) {
          var form = $(form);
          opts.fields.forEach(function(field) {
            var val = form.find("[name="+field+"]").val()
            if (!val) return;
            var parts = field.split('-');
            var frontObj = doc, frontName = parts.shift();
            while (parts.length > 0) {
              frontObj[frontName] = frontObj[frontName] || {}
              frontObj = frontObj[frontName];
              frontName = parts.shift();
            }
            frontObj[frontName] = val;
          });
        };

        // Apply the behavior
        $(formSelector).submit(function(e) {
          e.preventDefault();
          // formToDeepJSON acts on localFormDoc by reference
          formToDeepJSON(this, opts.fields, localFormDoc);
          if (opts.beforeSave) opts.beforeSave(localFormDoc);
          db.saveDoc(localFormDoc, {
            success : function(resp) {
              if (opts.success) opts.success(resp, localFormDoc);
            }
          })

          return false;
        });

        // populate form from an existing doc
        function docToForm(doc) {
          var form = $(formSelector);
          // fills in forms
          opts.fields.forEach(function(field) {
            var parts = field.split('-');
            var run = true, frontObj = doc, frontName = parts.shift();
            while (frontObj && parts.length > 0) {
              frontObj = frontObj[frontName];
              frontName = parts.shift();
            }
            if (frontObj && frontObj[frontName])
              form.find("[name="+field+"]").val(frontObj[frontName]);
          });
        };

        if (opts.id) {
          db.openDoc(opts.id, {
            success: function(doc) {
              if (opts.onLoad) opts.onLoad(doc);
              localFormDoc = doc;
              docToForm(doc);
          }});
        } else if (opts.template) {
          if (opts.onLoad) opts.onLoad(opts.template);
          localFormDoc = opts.template;
          docToForm(localFormDoc);
        }
        var instance = {
          deleteDoc : function(opts) {
            opts = opts || {};
            if (confirm("Really delete this document?")) {
              db.removeDoc(localFormDoc, opts);
            }
          },
          localDoc : function() {
            formToDeepJSON(formSelector, opts.fields, localFormDoc);
            return localFormDoc;
          }
        }
        return instance;
      }

      function prettyDate(time){
      	var date = new Date(time),
      		diff = (((new Date()).getTime() - date.getTime()) / 1000),
      		day_diff = Math.floor(diff / 86400);

        // if ( isNaN(day_diff) || day_diff < 0 || day_diff >= 31 ) return;

      	return day_diff < 1 && (
      			diff < 60 && "just now" ||
      			diff < 120 && "1 minute ago" ||
      			diff < 3600 && Math.floor( diff / 60 ) + " minutes ago" ||
      			diff < 7200 && "1 hour ago" ||
      			diff < 86400 && Math.floor( diff / 3600 ) + " hours ago") ||
      		day_diff == 1 && "yesterday" ||
      		day_diff < 21 && day_diff + " days ago" ||
      		day_diff < 45 && Math.ceil( day_diff / 7 ) + " weeks ago" ||
      		day_diff < 730 && Math.ceil( day_diff / 31 ) + " months ago" ||
      		Math.ceil( day_diff / 365 ) + " years ago";
      };

      app({
        showPath : function(funcname, docid) {
          // I wish this was shared with path.js...
          return '/'+[dbname, '_design', dname, '_show', funcname, docid].join('/')
        },
        slugifyString : function(string) {
          return string.replace(/\W/g,'-').
            replace(/\-*$/,'').replace(/^\-*/,'').
            replace(/\-{2,}/,'-');
        },
        attemptLogin : function(win, fail) {
          // depends on nasty hack in blog validation function
          db.saveDoc({"author":"_self"}, { error: function(s, e, r) {
            var namep = r.split(':');
            if (namep[0] == '_self') {
              login = namep.pop();
              $.cookies.set("login", login, '/'+dbname)
              win && win(login);
            } else {
              $.cookies.set("login", "", '/'+dbname)
              fail && fail(s, e, r);
            }
          }});
        },
        loggedInNow : function(loggedIn, loggedOut) {
          login = login || $.cookies.get("login");
          if (login) {
            loggedIn && loggedIn(login);
          } else {
            loggedOut && loggedOut();
          }
        },
        db : db,
        design : design,
        docForm : docForm,
        prettyDate : prettyDate
      });
    });
  };

  $.CouchApp = $.CouchApp || init;

})(jQuery);
<commit_msg>add view function to couchapp app<commit_after>// 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.

// Usage: The passed in function is called when the page is ready.
// CouchApp passes in the app object, which takes care of linking to
// the proper database, and provides access to the CouchApp helpers.
// $.CouchApp(function(app) {
//    app.db.view(...)
//    ...
// });

(function($) {

  function f(n) {    // Format integers to have at least two digits.
      return n < 10 ? '0' + n : n;
  }

  Date.prototype.toJSON = function() {
      return this.getUTCFullYear()   + '/' +
           f(this.getUTCMonth() + 1) + '/' +
           f(this.getUTCDate())      + ' ' +
           f(this.getUTCHours())     + ':' +
           f(this.getUTCMinutes())   + ':' +
           f(this.getUTCSeconds())   + ' +0000';
  };

  function Design(db, name) {
    this.view = function(view, opts) {
      db.view(name+'/'+view, opts);
    };
  };

  var login;

  function init(app) {
    $(function() {
      var dbname = document.location.href.split('/')[3];
      var dname = unescape(document.location.href).split('/')[5];
      var db = $.couch.db(dbname);
      var design = new Design(db, dname);

      // docForm applies CouchDB behavior to HTML forms.
      function docForm(formSelector, opts) {
        var localFormDoc = {};
        opts = opts || {};
        opts.fields = opts.fields || [];

        // turn the form into deep json
        // field names like 'author-email' get turned into json like
        // {"author":{"email":"quentin@example.com"}}
        function formToDeepJSON(form, fields, doc) {
          var form = $(form);
          opts.fields.forEach(function(field) {
            var val = form.find("[name="+field+"]").val()
            if (!val) return;
            var parts = field.split('-');
            var frontObj = doc, frontName = parts.shift();
            while (parts.length > 0) {
              frontObj[frontName] = frontObj[frontName] || {}
              frontObj = frontObj[frontName];
              frontName = parts.shift();
            }
            frontObj[frontName] = val;
          });
        };

        // Apply the behavior
        $(formSelector).submit(function(e) {
          e.preventDefault();
          // formToDeepJSON acts on localFormDoc by reference
          formToDeepJSON(this, opts.fields, localFormDoc);
          if (opts.beforeSave) opts.beforeSave(localFormDoc);
          db.saveDoc(localFormDoc, {
            success : function(resp) {
              if (opts.success) opts.success(resp, localFormDoc);
            }
          })

          return false;
        });

        // populate form from an existing doc
        function docToForm(doc) {
          var form = $(formSelector);
          // fills in forms
          opts.fields.forEach(function(field) {
            var parts = field.split('-');
            var run = true, frontObj = doc, frontName = parts.shift();
            while (frontObj && parts.length > 0) {
              frontObj = frontObj[frontName];
              frontName = parts.shift();
            }
            if (frontObj && frontObj[frontName])
              form.find("[name="+field+"]").val(frontObj[frontName]);
          });
        };

        if (opts.id) {
          db.openDoc(opts.id, {
            success: function(doc) {
              if (opts.onLoad) opts.onLoad(doc);
              localFormDoc = doc;
              docToForm(doc);
          }});
        } else if (opts.template) {
          if (opts.onLoad) opts.onLoad(opts.template);
          localFormDoc = opts.template;
          docToForm(localFormDoc);
        }
        var instance = {
          deleteDoc : function(opts) {
            opts = opts || {};
            if (confirm("Really delete this document?")) {
              db.removeDoc(localFormDoc, opts);
            }
          },
          localDoc : function() {
            formToDeepJSON(formSelector, opts.fields, localFormDoc);
            return localFormDoc;
          }
        }
        return instance;
      }

      function prettyDate(time){
      	var date = new Date(time),
      		diff = (((new Date()).getTime() - date.getTime()) / 1000),
      		day_diff = Math.floor(diff / 86400);

        // if ( isNaN(day_diff) || day_diff < 0 || day_diff >= 31 ) return;

      	return day_diff < 1 && (
      			diff < 60 && "just now" ||
      			diff < 120 && "1 minute ago" ||
      			diff < 3600 && Math.floor( diff / 60 ) + " minutes ago" ||
      			diff < 7200 && "1 hour ago" ||
      			diff < 86400 && Math.floor( diff / 3600 ) + " hours ago") ||
      		day_diff == 1 && "yesterday" ||
      		day_diff < 21 && day_diff + " days ago" ||
      		day_diff < 45 && Math.ceil( day_diff / 7 ) + " weeks ago" ||
      		day_diff < 730 && Math.ceil( day_diff / 31 ) + " months ago" ||
      		Math.ceil( day_diff / 365 ) + " years ago";
      };

      app({
        showPath : function(funcname, docid) {
          // I wish this was shared with path.js...
          return '/'+[dbname, '_design', dname, '_show', funcname, docid].join('/')
        },
        slugifyString : function(string) {
          return string.replace(/\W/g,'-').
            replace(/\-*$/,'').replace(/^\-*/,'').
            replace(/\-{2,}/,'-');
        },
        attemptLogin : function(win, fail) {
          // depends on nasty hack in blog validation function
          db.saveDoc({"author":"_self"}, { error: function(s, e, r) {
            var namep = r.split(':');
            if (namep[0] == '_self') {
              login = namep.pop();
              $.cookies.set("login", login, '/'+dbname)
              win && win(login);
            } else {
              $.cookies.set("login", "", '/'+dbname)
              fail && fail(s, e, r);
            }
          }});
        },
        loggedInNow : function(loggedIn, loggedOut) {
          login = login || $.cookies.get("login");
          if (login) {
            loggedIn && loggedIn(login);
          } else {
            loggedOut && loggedOut();
          }
        },
        db : db,
        design : design,
        view : design.view,
        docForm : docForm,
        prettyDate : prettyDate
      });
    });
  };

  $.CouchApp = $.CouchApp || init;

})(jQuery);
<|endoftext|>


<commit_before>// Generic forms user page (Part A)

'use strict';

var generateSections = require('eregistrations/view/components/generate-form-sections')
  , progressRules    = require('./components/progress-rules')
  , _                = require('mano').i18n.bind('Registration');

exports._parent = require('./business-process-data-forms-tabbed');

exports['forms-sections-content'] = function () {
	var nextPageLink = this.section._nextSection.map(function (nextSection) {
		if (!nextSection) return exports._nextSectionUrl(this);
		return '/forms/' + nextSection.pageUrl + '/';
	}.bind(this));

	insert(
		_if(this.section._legend, div({ class: 'info-main' },
			md(this.section._legend))),
		disabler(
			exports._disableCondition(this),
			this.section.applicableSections ?
					[progressRules(this.section),
						generateSections(this.section.applicableSections, { viewContext: this })] :
					this.section.toDOMForm(document)
		),
		_if(nextPageLink, p({ class: 'user-next-step-button' },
			a({ href: nextPageLink }, _('Continue to next step'))))
	);
};

exports._disableCondition = function (context) {
	return not(eq(context.businessProcess._guideProgress, 1));
};

exports._nextSectionUrl = function (context) { return '/documents/'; };

exports._match = 'section';
<commit_msg>#1378 do not show nextPageLink when soction incomplete<commit_after>// Generic forms user page (Part A)

'use strict';

var generateSections = require('eregistrations/view/components/generate-form-sections')
  , progressRules    = require('./components/progress-rules')
  , _                = require('mano').i18n.bind('Registration');

exports._parent = require('./business-process-data-forms-tabbed');

exports['forms-sections-content'] = function () {
	var nextPageLink = this.section._nextSection.map(function (nextSection) {
		if (!nextSection) return exports._nextSectionUrl(this);
		return '/forms/' + nextSection.pageUrl + '/';
	}.bind(this));

	insert(
		_if(this.section._legend, div({ class: 'info-main' },
			md(this.section._legend))),
		disabler(
			exports._disableCondition(this),
			this.section.applicableSections ?
					[progressRules(this.section),
						generateSections(this.section.applicableSections, { viewContext: this })] :
					this.section.toDOMForm(document)
		),
		_if(and(nextPageLink, eq(this.section._status, 1)), p({ class: 'user-next-step-button' },
			a({ href: nextPageLink }, _('Continue to next step'))))
	);
};

exports._disableCondition = function (context) {
	return not(eq(context.businessProcess._guideProgress, 1));
};

exports._nextSectionUrl = function (context) { return '/documents/'; };

exports._match = 'section';
<|endoftext|>


<commit_before>/*
 * Dataexplore Controller
 */

define([], function () {
  var url = 'data/explore/queries';
	var Controller = Em.Controller.extend({

    bindTooltips: function() {
      setTimeout(function () {
        $("[data-toggle='tooltip']").tooltip();
        $("[data-toggle='popover']").popover();
      }, 500)
    },

    contentDidChange: function() {
      this.clearAllTooltips();
      this.bindTooltips();
    }.observes('page'),

    renderExecuteBtn: function() {
      return true;
      return this.get('page') == 'query';
    }.property('page'),

		load: function () {
		  var self = this;

      //largestEver is the largest timestamp of a query that the controller has seen.
      //largest is the largest timestamp of a query on the current page.
      //smallestEver is the smallest timestamp of a query that the controller has seen.
      //smallest is the largest timestamp of a query on the current page.
		  self.pageMgr = {
        limit: 3,
        largestEver: 0,
        smallestEver: Infinity,
        firstPage: function () {
          this.offset = null;
          this.cursor = null;
        }
		  };
      self.pageMgr.firstPage();

		  this.set('objArr', []);
		  this.fetchQueries();
		  this.interval = setInterval(function () {
        self.fetchQueries();
		  }, 5000);
		  this.set('datasets', []);
		  this.loadDiscoverableDatasets();
		},

    clearAllTooltips: function () {
      $("[data-toggle='tooltip']").tooltip('hide');
      $("[data-toggle='popover']").popover('hide');
    },

		loadDiscoverableDatasets: function () {
		  var self = this;
      var datasets = self.get('datasets');
		  self.HTTP.rest('data/explore/tables', function(response) {
		    response.forEach(function (dataset) {
		      var name = dataset.table;
          self.HTTP.rest('data/explore/tables/' + name + '/schema', function(response, status) {
            var results = [];
            for(var key in response) {
              if(response.hasOwnProperty(key)){
                results.push({columns:[key, response[key]]});
              }
            }
            datasets.pushObject(Ember.Object.create({name:name, results:results}));

            if(datasets.length == 1){
              self.selectDataset(datasets[0]);
            }
          });
		    });
		  });
		},

    tableClicked: function (obj) {
      this.injectorTextArea.set('value', obj.statement);
      this.toggleTable(obj);
    },

		toggleTable: function (obj, hideAllFirst /* = true */, callback) {
      var self = this;
      hideAllFirst = typeof hideAllFirst !== 'undefined' ? hideAllFirst : true;
      if(hideAllFirst){
        self.hideAllTables(obj);
      }
      if(!obj.get('preview_cached') || !obj.get('has_results') || !obj.get('is_active')) {
        setTimeout(function(){
          $("[id='#" + obj.get('query_handle') + "']").tooltip('show');
          setTimeout(function(){
            $("[id='#" + obj.get('query_handle') + "']").tooltip('hide');
          }, 1000);
        }, 200)
        return;
      }
      obj.set('isSelected', !obj.get('isSelected'));
      $("#" + obj.query_handle).slideToggle(200, function () {
        var objArr = self.get('objArr');
        objArr.forEach(function (entry) {
          if (!$("#" + obj.query_handle + " :visible")) {
            entry.set('isSelected', false);
          }
        });
        if (typeof callback === "function") {
            callback();
        }
      });
    },

    hideAllTables: function (dontHide) {
      var objArr = this.get('objArr');
      for (var i=0; i<objArr.length; i++){
        var query = objArr[i];
        if(query === dontHide){
          continue;
        }
        if(query.get('isSelected')){
          this.toggleTable(query, false);
          query.set('isSelected', false);
        }
      }
    },

    hideTable: function (query, callback) {
      if(query.get('isSelected')){
        this.toggleTable(query, false, callback);
      } else if (typeof callback === "function") {
        callback();
      }
    },

    selectDataset: function (dataset) {
      this.set('selectedDataset', dataset);
      this.injectorTextArea.set('value', 'SELECT * FROM ' + dataset.name + ' LIMIT 5');
      var datasets = this.get('datasets');
      datasets.forEach(function (entry) {
        entry.set('isSelected', false);
      });
      dataset.set('isSelected', true);
    },

		unload: function () {},

    nextPage: function () {
      this.pageMgr.offset = this.smallest;
      this.pageMgr.cursor = "next";
      this.fetchQueries(true);
    },

    prevPage: function () {
      this.pageMgr.offset = this.largest;
      this.pageMgr.cursor = "prev";
      this.fetchQueries(true);
    },

    pageNavTooltip: function () {
      var className = this.pageMgr.cursor + "Btn";
      $("." + className).tooltip('show');
      setTimeout(function(){
        $("." + className).tooltip('hide');
      }, 2000);
    },

		fetchQueries: function (userAction) {
		  var self = this;

      if(self.largest == self.pageMgr.largestEver){
        //If the user is trying to go to a previous page when already viewing the most recent query:
        if(self.pageMgr.cursor === "prev" && userAction){
          self.pageNavTooltip();
        }
        if(!userAction){
          self.pageMgr.firstPage();
        }
      }

		  var url = 'data/explore/queries';
      url += '?limit=' + self.pageMgr.limit;
		  if(self.pageMgr.offset){
		    url += '&offset=' + self.pageMgr.offset;
		  }
		  if(self.pageMgr.cursor){
        url += '&cursor=' + self.pageMgr.cursor;
      }
      this.HTTP.rest(url, function (queries, status) {
        if(queries.length == 0){
          if(userAction){
            //When trying to go to next page, and there are no results there:
            self.pageNavTooltip();
          }
          return;
        }

        //Clear the local memory of the queries if the list of queries in the response is different than the local version (and our local version isn't empty)
        if(userAction || (  self.get('objArr').length && (self.get('objArr')[0].get('query_handle') != queries[0].query_handle)  )){
          self.set('objArr', []);
        }
		    var objArr = self.get('objArr');

        queries.forEach(function (query) {
          var existingObj = self.find(query.query_handle);
          if (!existingObj) {
            var newObj = Ember.Object.create(query);
            newObj.query_handle_hashed = "#" + newObj.query_handle;
            newObj.time_started = new Date(query.timestamp);
            newObj.time_started = newObj.time_started.toLocaleString();

            existingObj = objArr.pushObject(newObj);
          } else if (   existingObj.get('status')      !== query.status
                     || existingObj.get('has_results') !== query.has_results
                     || existingObj.get('is_active')   !== query.is_active) {
              //Avoid updating the local query object upon every response from the server.
              //Instead, only update the query object when attributes actually change.
              //Otherwise, emberjs will update the view (even when no attribute really changed) and the update can mess up any dynamic view (toggled tables).
              self.hideTable(existingObj, function () {
                existingObj.set('status', query.status);
                existingObj.set('has_results', query.has_results);
                existingObj.set('is_active', query.is_active);
              });
          }
          if ( existingObj.get('status') === 'FINISHED'
               && existingObj.get('has_results')
               && existingObj.get('is_active')
               && !existingObj.get('preview_cached') ) {
            self.getPreview(existingObj);
            self.getSchema(existingObj);
          }
        });

        if(objArr.length){
          //keep track of largest and smallest timestamps for the purposes of page navigation.
          self.largest = objArr[0].timestamp;
          self.smallest = objArr[objArr.length - 1].timestamp;
          if(self.largest > self.pageMgr.largestEver) {
            self.pageMgr.largestEver = self.largest;
          }
          if(self.smallest < self.pageMgr.smallestEver) {
            self.pageMgr.smallestEver = self.smallest;
          }
        }
        self.bindTooltips();
      });
		},

    getPreview: function (query) {
      var self = this;
      var handle = query.get('query_handle');
      this.HTTP.post('rest/data/explore/queries/' + handle + '/preview', function (response) {
        response = jQuery.parseJSON(response);
        if(response.length == 0){
          query.set('is_active', false);
        }
        query.set('preview_cached', response);
      });
    },

    downloadFile: function(filename, content) {
      var blob = new Blob([content]);
      var evt = document.createEvent("HTMLEvents");
      evt.initEvent("click");
      $("<a>", {
        download: filename,
        href: webkitURL.createObjectURL(blob)
      }).get(0).dispatchEvent(evt);
    },

    //TODO: make this functionality compatible with more browsers.
    download: function (query) {
      var self = this;
      var handle = query.get('query_handle');
      var url = 'rest/data/explore/queries/' + handle + '/download';

      var handle = query.get('query_handle');
      self.HTTP.post(url, function (response) {
        self.downloadFile('results_' + handle + '.txt', response);
      });
      this.hideTable(query, function () {
        query.set('is_active', false);
      });
    },

    deleteQuery: function (query) {
      var handle = query.get('query_handle');
      this.HTTP.del('rest/data/explore/queries/' + handle);
    },

    getSchema: function (query) {
      var self = this;
      var handle = query.get('query_handle');
      this.HTTP.rest('data/explore/queries/' + handle + '/schema', function (response) {
        query.set('schema', response);
      });
    },

    submitSQLQuery: function () {
      var self = this;
      var controller = this.get('controllers');
      var sqlString = controller.get("SQLQueryString") || this.injectorTextArea.get('value');
      this.HTTP.post('rest/data/explore/queries', {data: { "query": sqlString }},
        function (response, status) {
          if(status != 200) {
            $(".text-area-container").attr('data-content', response.message).popover('show')
            .click(function(){},function(){$(".text-area-container").popover('hide')});
            return;
          }
          self.transitionToRoute('DataExplore.Results');
          self.pageMgr.firstPage();
          self.fetchQueries();
          self.pageMgr.largestEver += 1;
        }
      );
      self.hideAllTables();
    },

    find: function (query_handle) {
      var objArr = this.get('objArr');
      for (var i=0; i<objArr.length; i++){
        if (query_handle === objArr[i].query_handle) {
          return objArr[i];
        }
      }
      return false;
    },

	});

	Controller.reopenClass({
		type: 'DataExplore',
		kind: 'Controller'
	});

	return Controller;

});
<commit_msg>Linting changes to controllers/data-explore.js<commit_after>/*
 * Dataexplore Controller
 */

define([], function () {
  var url = 'data/explore/queries';
	var Controller = Em.Controller.extend({

    bindTooltips: function () {
      setTimeout(function () {
        $("[data-toggle='tooltip']").tooltip();
        $("[data-toggle='popover']").popover();
      }, 500)
    },

    contentDidChange: function () {
      this.clearAllTooltips();
      this.bindTooltips();
    }.observes('page'),

    renderExecuteBtn: function () {
      return true;
      // Kind of redundant. Cannot have two consecutive returns statements.
      //return this.get('page') == 'query';
    }.property('page'),

    load: function () {
      var self = this;
      //largestEver is the largest timestamp of a query that the controller has seen.
      //largest is the largest timestamp of a query on the current page.
      //smallestEver is the smallest timestamp of a query that the controller has seen.
      //smallest is the largest timestamp of a query on the current page.
      self.pageMgr = {
        limit: 3,
        largestEver: 0,
        smallestEver: Infinity,
        firstPage: function () {
          this.offset = null;
          this.cursor = null;
        }
      };
      self.pageMgr.firstPage();
      this.set('objArr', []);
      this.fetchQueries();
      this.interval = setInterval(function () {
        self.fetchQueries();
      }, 5000);
      this.set('datasets', []);
      this.loadDiscoverableDatasets();
    },

    clearAllTooltips: function () {
      $("[data-toggle='tooltip']").tooltip('hide');
      $("[data-toggle='popover']").popover('hide');
    },

    loadDiscoverableDatasets: function () {
      var self = this;
        var datasets = self.get('datasets');
        self.HTTP.rest('data/explore/tables', function(response) {
          response.forEach(function (dataset) {
            var name = dataset.table;
            self.HTTP.rest('data/explore/tables/' + name + '/schema', function (response, status) {
              var results = [];
              for(var key in response) {
                if(response.hasOwnProperty(key)){
                  results.push({
                    columns:[key, response[key]]
                  });
                }
              }
              datasets.pushObject(Ember.Object.create({
                name:name,
                results:results
              }));
              if(datasets.length == 1) {
                self.selectDataset(datasets[0]);
              }
            });
          });
        });
    },

    tableClicked: function (obj) {
      this.injectorTextArea.set('value', obj.statement);
      this.toggleTable(obj);
    },

    toggleTable: function (obj, hideAllFirst /* = true */, callback) {
      var self = this;
      hideAllFirst = typeof hideAllFirst !== 'undefined' ? hideAllFirst : true;
      if(hideAllFirst) {
        self.hideAllTables(obj);
      }
      if(!obj.get('preview_cached') || !obj.get('has_results') || !obj.get('is_active')) {
        setTimeout(function (){
          $("[id='#" + obj.get('query_handle') + "']").tooltip('show');
          setTimeout(function (){
            $("[id='#" + obj.get('query_handle') + "']").tooltip('hide');
          }, 1000);
        }, 200)
        return;
      }
      obj.set('isSelected', !obj.get('isSelected'));
      $("#" + obj.query_handle).slideToggle(200, function () {
        var objArr = self.get('objArr');
        objArr.forEach(function (entry) {
          if (!$("#" + obj.query_handle + " :visible")) {
            entry.set('isSelected', false);
          }
        });
        if (typeof callback === "function") {
            callback();
        }
      });
    },

    hideAllTables: function (dontHide) {
      var objArr = this.get('objArr');
      for (var i=0; i<objArr.length; i++){
        var query = objArr[i];
        if(query === dontHide){
          continue;
        }
        if(query.get('isSelected')) {
          this.toggleTable(query, false);
          query.set('isSelected', false);
        }
      }
    },

    hideTable: function (query, callback) {
      if(query.get('isSelected')){
        this.toggleTable(query, false, callback);
      } else if (typeof callback === "function") {
        callback();
      }
    },

    selectDataset: function (dataset) {
      this.set('selectedDataset', dataset);
      this.injectorTextArea.set('value', 'SELECT * FROM ' + dataset.name + ' LIMIT 5');
      var datasets = this.get('datasets');
      datasets.forEach(function (entry) {
        entry.set('isSelected', false);
      });
      dataset.set('isSelected', true);
    },

    unload: function () {},

    nextPage: function () {
      this.pageMgr.offset = this.smallest;
      this.pageMgr.cursor = "next";
      this.fetchQueries(true);
    },

    prevPage: function () {
      this.pageMgr.offset = this.largest;
      this.pageMgr.cursor = "prev";
      this.fetchQueries(true);
    },

    pageNavTooltip: function () {
      var className = this.pageMgr.cursor + "Btn";
      $("." + className).tooltip('show');
      setTimeout(function(){
        $("." + className).tooltip('hide');
      }, 2000);
    },

    fetchQueries: function (userAction) {
      var self = this;
      if(self.largest == self.pageMgr.largestEver) {
        //If the user is trying to go to a previous page when already viewing the most recent query:
        if(self.pageMgr.cursor === "prev" && userAction) {
          self.pageNavTooltip();
        }
        if(!userAction) {
          self.pageMgr.firstPage();
        }
      }

      var url = 'data/explore/queries';
      url += '?limit=' + self.pageMgr.limit;
      if(self.pageMgr.offset) {
        url += '&offset=' + self.pageMgr.offset;
      }
      if(self.pageMgr.cursor) {
        url += '&cursor=' + self.pageMgr.cursor;
      }
      this.HTTP.rest(url, function (queries, status) {
        if(queries.length == 0){
          if(userAction) {
            //When trying to go to next page, and there are no results there:
            self.pageNavTooltip();
          }
          return;
        }

        //Clear the local memory of the queries if the list of queries in the response is different than the local version (and our local version isn't empty)
        if(userAction || (  self.get('objArr').length && (self.get('objArr')[0].get('query_handle') != queries[0].query_handle)  )) {
          self.set('objArr', []);
        }
        var objArr = self.get('objArr');
        queries.forEach(function (query) {
          var existingObj = self.find(query.query_handle);
          if (!existingObj) {
            var newObj = Ember.Object.create(query);
            newObj.query_handle_hashed = "#" + newObj.query_handle;
            newObj.time_started = new Date(query.timestamp);
            newObj.time_started = newObj.time_started.toLocaleString();

            existingObj = objArr.pushObject(newObj);
          } else if (   existingObj.get('status')      !== query.status
                     || existingObj.get('has_results') !== query.has_results
                     || existingObj.get('is_active')   !== query.is_active) {
              //Avoid updating the local query object upon every response from the server.
              //Instead, only update the query object when attributes actually change.
              //Otherwise, emberjs will update the view (even when no attribute really changed) and the update can mess up any dynamic view (toggled tables).
              self.hideTable(existingObj, function () {
                existingObj.set('status', query.status);
                existingObj.set('has_results', query.has_results);
                existingObj.set('is_active', query.is_active);
              });
          }
          if ( existingObj.get('status') === 'FINISHED'
               && existingObj.get('has_results')
               && existingObj.get('is_active')
               && !existingObj.get('preview_cached') ) {
            self.getPreview(existingObj);
            self.getSchema(existingObj);
          }
        });

        if(objArr.length) {
          //keep track of largest and smallest timestamps for the purposes of page navigation.
          self.largest = objArr[0].timestamp;
          self.smallest = objArr[objArr.length - 1].timestamp;
          if(self.largest > self.pageMgr.largestEver) {
            self.pageMgr.largestEver = self.largest;
          }
          if(self.smallest < self.pageMgr.smallestEver) {
            self.pageMgr.smallestEver = self.smallest;
          }
        }
        self.bindTooltips();
      });
    },

    getPreview: function (query) {
      var self = this;
      var handle = query.get('query_handle');
      this.HTTP.post('rest/data/explore/queries/' + handle + '/preview', function (response) {
        response = jQuery.parseJSON(response);
        if(response.length == 0) {
          query.set('is_active', false);
        }
        query.set('preview_cached', response);
      });
    },

    downloadFile: function(filename, content) {
      var blob = new Blob([content]);
      var evt = document.createEvent("HTMLEvents");
      evt.initEvent("click");
      $("<a>", {
        download: filename,
        href: webkitURL.createObjectURL(blob)
      }).get(0).dispatchEvent(evt);
    },

    //TODO: make this functionality compatible with more browsers.
    download: function (query) {
      var self = this;
      var handle = query.get('query_handle');
      var url = 'rest/data/explore/queries/' + handle + '/download';

      var handle = query.get('query_handle');
      self.HTTP.post(url, function (response) {
        self.downloadFile('results_' + handle + '.txt', response);
      });
      this.hideTable(query, function () {
        query.set('is_active', false);
      });
    },

    deleteQuery: function (query) {
      var handle = query.get('query_handle');
      this.HTTP.del('rest/data/explore/queries/' + handle);
    },

    getSchema: function (query) {
      var self = this;
      var handle = query.get('query_handle');
      this.HTTP.rest('data/explore/queries/' + handle + '/schema', function (response) {
        query.set('schema', response);
      });
    },

    submitSQLQuery: function () {
      var self = this;
      var controller = this.get('controllers');
      var sqlString = controller.get("SQLQueryString") || this.injectorTextArea.get('value');
      this.HTTP.post('rest/data/explore/queries', {
        data: {
          "query": sqlString
        }
      },
        function (response, status) {
          if(status != 200) {
            $(".text-area-container").attr('data-content', response.message).popover('show')
            .click(
              // Not sure if we require two function handlers here.
              function () {},
              function (){
                $(".text-area-container").popover('hide')
              });
            return;
          }
          self.transitionToRoute('DataExplore.Results');
          self.pageMgr.firstPage();
          self.fetchQueries();
          self.pageMgr.largestEver += 1;
        }
      );
      self.hideAllTables();
    },

    find: function (query_handle) {
      var objArr = this.get('objArr');
      for (var i=0; i<objArr.length; i++) {
        if (query_handle === objArr[i].query_handle) {
          return objArr[i];
        }
      }
      return false;
    },

  });

  Controller.reopenClass({
    type: 'DataExplore',
    kind: 'Controller'
  });

  return Controller;

});
<|endoftext|>


<commit_before>import proseMirror from "/apogeeapp/app/component/literatepage/proseMirrorSetup.js";
import LiteratePageComponentDisplay from "/apogeeapp/app/component/literatepage/LiteratePageComponentDisplay.js";
import "/apogeeapp/app/component/literatepage/literatepagetransaction.js";

import Component from "/apogeeapp/app/component/Component.js";
import ParentComponent from "/apogeeapp/app/component/ParentComponent.js";

/** This component represents a table object. */
export default class FolderComponent extends ParentComponent {

    constructor(workspaceUI,folder) {
        //extend parent component
        super(workspaceUI,folder,FolderComponent);

        //create an empty edit state to start
        this.editorData = proseMirror.createEditorState();
    };

    getEditorData() {
        return this.editorData;
    }

    setEditorData(editorData) {
        this.editorData = editorData;

        //this should be in an event for the change
        var tabDisplay = this.getTabDisplay();
        if(tabDisplay) {
            tabDisplay.updateDocumentData(this.editorData);
        }
    }

    /** This method is called to respond to transactions created in the editor. */
    applyTransaction(transaction) {

        //console.log("New Transaction:");
        //console.log("Doc changed: " + transaction.docChanged);

        if(transaction.docChanged) {
            //see if we need to delete any apogee nodes
            var deletedApogeeNodes = this.getDeletedApogeeNodes(this.editorData,transaction);

            if(deletedApogeeNodes.length > 0) {
                let doDelete = confirm("The selection includes Apogee nodes. Are you sure you want to delete them?");
                //do not do delete.
                //if(!doDelete) return null;
                if(!doDelete) alert("sorry - they will be deleted anyway, until the code is fixed.")
            }

            //delete the apogee nodes
            //(add this)

            var commandData = this.createEditorCommand(transaction);
            this.getWorkspaceUI().getApp().executeCommand(commandData);
        }
        else {
            //this is a editor state change that doesn't change the data
            this.editorData = this.editorData.apply(transaction);
            this.fieldUpdated("document");

            if(this.tabDisplay) {
                this.tabDisplay.updateDocumentData(this.editorData);
            }
        }
    }

    getDeletedApogeeNodes(editorData, transaction) {
        //prepare to get apogee nodes
        let apogeeNodes = [];
        let getApogeeNodes = node => {
        if(node.type.name == "apogeeComponent") {
            apogeeNodes.push(node);
        }
        //do not go inside any top level nodes
        return false;
        }

        //get all the replcaed apogee nodes
        transaction.steps.forEach( step => {
        if(step.jsonID == "replace") {
            editorData.doc.nodesBetween(step.from,step.to,getApogeeNodes);
        }
        else if(step.jsonID == "replaceAround") {
            editorData.doc.nodesBetween(step.from,step.gapFrom,getApogeeNodes);
            editorData.doc.nodesBetween(step.gapTo,step.to,getApogeeNodes);
        }
        });

        return apogeeNodes;

    }

    createEditorCommand(transaction) {
        var stepsJson = [];
        var inverseStepsJson = [];

        for(var i = 0; i < transaction.steps.length; i++) {
            var step = transaction.steps[i];
            stepsJson.push(step.toJSON());
            var stepDoc = transaction.docs[i];
            var inverseStep = step.invert(stepDoc);
            inverseStepsJson.push(inverseStep.toJSON());
        }

        var commandData = {};
        commandData.type = "literatePageTransaction";
        commandData.memberFullName = this.member.getFullName();
        commandData.steps = stepsJson;
        commandData.undoSteps = inverseStepsJson;

        return commandData;
    }

    getInsertIsOk() {
        var state = this.getEditorData();

        return (insertPoint(state.doc, state.selection.from, schema.nodes.apogeeComponent) != null);
    }

    insertComponentOnPage(childName) {
        var state = this.getEditorData();

        let { empty, $from, $to } = state.selection, content = Fragment.empty
        if (!empty && $from.sameParent($to) && $from.parent.inlineContent)
          content = $from.parent.content.cut($from.parentOffset, $to.parentOffset)
        let transaction = state.tr.replaceSelectionWith(schema.nodes.apogeeComponent.create({ "state": childName }));

        var commandData = this.createEditorCommand(transaction);
        return commandData;
    }

    removeComponentFromPage(childShortName) {
        var state = this.getEditorData();

        //let { empty, $from, $to } = proseMirror.getComponentRange(childName), content = Fragment.empty
        let {found,from,to} = proseMirror.getComponentRange(state,childShortName);
        //end test

        if(found) {
            let transaction = state.tr.delete(from, to);
            var commandData = this.createEditorCommand(transaction);
            return commandData;
        }
        else {
            return null;
        }
    }

    //end test code
    //=========================================================================

    instantiateTabDisplay() {
        var folder = this.getMember();
        return new LiteratePageComponentDisplay(this,folder,folder);
    }

    //==============================
    // serialization
    //==============================

    /** This serializes the table component. */
    writeToJson(json) {
        //save the editor state
        if(this.editorData) {
            json.data = this.editorData.toJSON();
        }

        //save the children
        var folder = this.getMember();
        var workspaceUI = this.getWorkspaceUI();
        json.children = workspaceUI.getFolderComponentContentJson(folder);

        return json;
    }

    readFromJson(json) {
        //read the editor state
        if((json.data)&&(json.data.doc)) {
            this.editorData = proseMirror.createEditorState(json.data.doc);
            this.fieldUpdated("document");
        }
    }

    /** This method is used to load the child components from a json */
    readChildrenFromJson(workspaceUI,childActionResults,json) {
        if(json.children) {
            workspaceUI.loadFolderComponentContentFromJson(childActionResults,json.children);
        }
        return true;
    }

    //======================================
    // Static methods
    //======================================

    //if we want to allow importing a workspace as this object, we must add this method to the generator
    static appendWorkspaceChildren(optionsJson,childrenJson) {
        optionsJson.children = childrenJson;
    }

}

//this is a method to help construct an emtpy folder component
FolderComponent.EMPTY_FOLDER_COMPONENT_JSON  = {
    "type":"apogeeapp.app.FolderComponent"
};

//======================================
// This is the component generator, to register the component
//======================================

FolderComponent.displayName = "Folder";
FolderComponent.uniqueName = "apogeeapp.app.FolderComponent";
FolderComponent.DEFAULT_WIDTH = 500;
FolderComponent.DEFAULT_HEIGHT = 500;
FolderComponent.ICON_RES_PATH = "/componentIcons/folder.png";
FolderComponent.TREE_ENTRY_SORT_ORDER = Component.FOLDER_COMPONENT_TYPE_SORT_ORDER;
FolderComponent.DEFAULT_MEMBER_JSON = {
    "type": "apogee.Folder"
};

<commit_msg>update delete command for editor to handel apogee componnent delete<commit_after>import proseMirror from "/apogeeapp/app/component/literatepage/proseMirrorSetup.js";
import LiteratePageComponentDisplay from "/apogeeapp/app/component/literatepage/LiteratePageComponentDisplay.js";
import "/apogeeapp/app/component/literatepage/literatepagetransaction.js";

import Component from "/apogeeapp/app/component/Component.js";
import ParentComponent from "/apogeeapp/app/component/ParentComponent.js";

/** This component represents a table object. */
export default class FolderComponent extends ParentComponent {

    constructor(workspaceUI,folder) {
        //extend parent component
        super(workspaceUI,folder,FolderComponent);

        //create an empty edit state to start
        this.editorData = proseMirror.createEditorState();
    };

    getEditorData() {
        return this.editorData;
    }

    setEditorData(editorData) {
        this.editorData = editorData;

        //this should be in an event for the change
        var tabDisplay = this.getTabDisplay();
        if(tabDisplay) {
            tabDisplay.updateDocumentData(this.editorData);
        }
    }

    /** This method is called to respond to transactions created in the editor. */
    applyTransaction(transaction) {

        //console.log("New Transaction:");
        //console.log("Doc changed: " + transaction.docChanged);

        if(transaction.docChanged) {

            //command
            let commandData;

            //see if we need to delete any apogee nodes
            var deletedApogeeComponents = this.getDeletedApogeeComponents(this.editorData,transaction);

            if(deletedApogeeComponents.length > 0) {
                let doDelete = confirm("Are you sure you want to delete these apogee nodes: " + deletedApogeeComponents);
                //do not do delete.
                if(!doDelete) return;

                //do the delete

                //we will use a combined command
                commandData = {};
                commandData.type = "compoundCommand";
                commandData.childCommands = [];

                //create the delete component commands
                deletedApogeeComponents.forEach(shortName => {
                    let fullName = this.member.getChildFullName(shortName);
                    let componentDeleteCommand = {};
                    componentDeleteCommand.type = "deleteComponent";
                    componentDeleteCommand.memberFullName = fullName;
                    commandData.childCommands.push(componentDeleteCommand);
                });
            }

            //create the editor command to delete the component node
            var editorCommand = this.createEditorCommand(transaction);

            //combine commands or use the editor command directly
            if(commandData) {
                commandData.childCommands.push(editorCommand);
            }
            else {
                commandData = editorCommand;
            }

            //execute the command
            this.getWorkspaceUI().getApp().executeCommand(commandData);
        }
        else {
            //this is a editor state change that doesn't change the data
            this.editorData = this.editorData.apply(transaction);
            this.fieldUpdated("document");

            if(this.tabDisplay) {
                this.tabDisplay.updateDocumentData(this.editorData);
            }
        }
    }

    getDeletedApogeeComponents(editorData, transaction) {
        //prepare to get apogee nodes
        let apogeeComponents = [];
        let getApogeeComponents = node => {
        if(node.type.name == "apogeeComponent") {
            var componentShortName = node.attrs.state; //we should change this node attribute name
            apogeeComponents.push(componentShortName);
        }
        //do not go inside any top level nodes
        return false;
        }

        //get all the replcaed apogee components
        transaction.steps.forEach( step => {
        if(step.jsonID == "replace") {
            editorData.doc.nodesBetween(step.from,step.to,getApogeeComponents);
        }
        else if(step.jsonID == "replaceAround") {
            editorData.doc.nodesBetween(step.from,step.gapFrom,getApogeeComponents);
            editorData.doc.nodesBetween(step.gapTo,step.to,getApogeeComponents);
        }
        });

        return apogeeComponents;

    }

    createEditorCommand(transaction) {
        var stepsJson = [];
        var inverseStepsJson = [];

        for(var i = 0; i < transaction.steps.length; i++) {
            var step = transaction.steps[i];
            stepsJson.push(step.toJSON());
            var stepDoc = transaction.docs[i];
            var inverseStep = step.invert(stepDoc);
            inverseStepsJson.push(inverseStep.toJSON());
        }

        var commandData = {};
        commandData.type = "literatePageTransaction";
        commandData.memberFullName = this.member.getFullName();
        commandData.steps = stepsJson;
        commandData.undoSteps = inverseStepsJson;

        return commandData;
    }

    getInsertIsOk() {
        var state = this.getEditorData();

        return (insertPoint(state.doc, state.selection.from, schema.nodes.apogeeComponent) != null);
    }

    insertComponentOnPage(childName) {
        var state = this.getEditorData();

        let { empty, $from, $to } = state.selection, content = Fragment.empty
        if (!empty && $from.sameParent($to) && $from.parent.inlineContent)
          content = $from.parent.content.cut($from.parentOffset, $to.parentOffset)
        let transaction = state.tr.replaceSelectionWith(schema.nodes.apogeeComponent.create({ "state": childName }));

        var commandData = this.createEditorCommand(transaction);
        return commandData;
    }

    removeComponentFromPage(childShortName) {
        var state = this.getEditorData();

        //let { empty, $from, $to } = proseMirror.getComponentRange(childName), content = Fragment.empty
        let {found,from,to} = proseMirror.getComponentRange(state,childShortName);
        //end test

        if(found) {
            let transaction = state.tr.delete(from, to);
            var commandData = this.createEditorCommand(transaction);
            return commandData;
        }
        else {
            return null;
        }
    }

    //end test code
    //=========================================================================

    instantiateTabDisplay() {
        var folder = this.getMember();
        return new LiteratePageComponentDisplay(this,folder,folder);
    }

    //==============================
    // serialization
    //==============================

    /** This serializes the table component. */
    writeToJson(json) {
        //save the editor state
        if(this.editorData) {
            json.data = this.editorData.toJSON();
        }

        //save the children
        var folder = this.getMember();
        var workspaceUI = this.getWorkspaceUI();
        json.children = workspaceUI.getFolderComponentContentJson(folder);

        return json;
    }

    readFromJson(json) {
        //read the editor state
        if((json.data)&&(json.data.doc)) {
            this.editorData = proseMirror.createEditorState(json.data.doc);
            this.fieldUpdated("document");
        }
    }

    /** This method is used to load the child components from a json */
    readChildrenFromJson(workspaceUI,childActionResults,json) {
        if(json.children) {
            workspaceUI.loadFolderComponentContentFromJson(childActionResults,json.children);
        }
        return true;
    }

    //======================================
    // Static methods
    //======================================

    //if we want to allow importing a workspace as this object, we must add this method to the generator
    static appendWorkspaceChildren(optionsJson,childrenJson) {
        optionsJson.children = childrenJson;
    }

}

//this is a method to help construct an emtpy folder component
FolderComponent.EMPTY_FOLDER_COMPONENT_JSON  = {
    "type":"apogeeapp.app.FolderComponent"
};

//======================================
// This is the component generator, to register the component
//======================================

FolderComponent.displayName = "Folder";
FolderComponent.uniqueName = "apogeeapp.app.FolderComponent";
FolderComponent.DEFAULT_WIDTH = 500;
FolderComponent.DEFAULT_HEIGHT = 500;
FolderComponent.ICON_RES_PATH = "/componentIcons/folder.png";
FolderComponent.TREE_ENTRY_SORT_ORDER = Component.FOLDER_COMPONENT_TYPE_SORT_ORDER;
FolderComponent.DEFAULT_MEMBER_JSON = {
    "type": "apogee.Folder"
};

<|endoftext|>


<commit_before>/* eslint-env jest */

// By default, we run functions in the queue immediately.
// Call this to disable that.
export const __disableAutomaticCommandQueueExecution = () => {
  window.googletag.cmd = []
}

// Run all functions in googletag.cmd.
export const __runCommandQueue = () => {
  window.googletag.cmd.forEach(cmd => cmd())
}

var mockPubadsRefresh = jest.fn()
const mockEnableSingleRequest = jest.fn()

// Set a mock function for googletag.pubads().refresh.
export const __setPubadsRefreshMock = mockFunction => {
  mockPubadsRefresh = mockFunction
}

const MockSlot = ({ adUnitPath, slotElementId }) => ({
  getAdUnitPath: () => adUnitPath,
  getSlotElementId: () => slotElementId,
  setTargeting: jest.fn(),
})

const mockSlots = [
  // Mock ad unit IDs from the adSettings mock.
  // Bottom leaderboard
  MockSlot({
    adUnitPath: '/99887766/HBTL',
    slotElementId: 'div-gpt-ad-24682468-0',
  }),
  // First (bottom) rectangle ad
  MockSlot({
    adUnitPath: '/11223344/HBTR',
    slotElementId: 'div-gpt-ad-1357913579-0',
  }),
  // Second (top) rectangle ad
  MockSlot({
    adUnitPath: '/44556677/HBTR2',
    slotElementId: 'div-gpt-ad-11235813-0',
  }),
]

const mockGetSlots = jest.fn(() => {
  return mockSlots
})
const mockSetTargeting = jest.fn()

// Mock an event fired.
export const __runEventListenerCallbacks = (eventName, ...args) => {
  eventListenerStore[eventName].forEach(f => f(...args))
}

const mockCmd = []
mockCmd.push = f => f()

const eventListenerStore = {}

export default () => {
  window.googletag = window.googletag || {
    cmd: mockCmd,
    pubads: jest.fn(() => ({
      addEventListener: (eventName, callback) => {
        if (!eventListenerStore[eventName]) {
          eventListenerStore[eventName] = []
        }
        eventListenerStore[eventName].push(callback)
      },
      getSlots: mockGetSlots,
      enableSingleRequest: mockEnableSingleRequest,
      refresh: mockPubadsRefresh,
      setTargeting: mockSetTargeting,
    })),
    defineSlot: jest.fn(() => ({
      addService: jest.fn(),
    })),
    enableServices: jest.fn(),
  }
  return window.googletag
}
<commit_msg>Use mock ad unit IDs in mock Google tag<commit_after>/* eslint-env jest */

import {
  VERTICAL_AD_UNIT_ID,
  VERTICAL_AD_SLOT_DOM_ID,
  SECOND_VERTICAL_AD_UNIT_ID,
  SECOND_VERTICAL_AD_SLOT_DOM_ID,
  HORIZONTAL_AD_UNIT_ID,
  HORIZONTAL_AD_SLOT_DOM_ID,
} from 'js/ads/adSettings'

// By default, we run functions in the queue immediately.
// Call this to disable that.
export const __disableAutomaticCommandQueueExecution = () => {
  window.googletag.cmd = []
}

// Run all functions in googletag.cmd.
export const __runCommandQueue = () => {
  window.googletag.cmd.forEach(cmd => cmd())
}

var mockPubadsRefresh = jest.fn()
const mockEnableSingleRequest = jest.fn()

// Set a mock function for googletag.pubads().refresh.
export const __setPubadsRefreshMock = mockFunction => {
  mockPubadsRefresh = mockFunction
}

const MockSlot = ({ adUnitPath, slotElementId }) => ({
  getAdUnitPath: () => adUnitPath,
  getSlotElementId: () => slotElementId,
  setTargeting: jest.fn(),
})

const mockSlots = [
  // Mock ad unit IDs from the adSettings mock.
  // Bottom leaderboard
  MockSlot({
    adUnitPath: HORIZONTAL_AD_UNIT_ID,
    slotElementId: HORIZONTAL_AD_SLOT_DOM_ID,
  }),
  // First (bottom) rectangle ad
  MockSlot({
    adUnitPath: VERTICAL_AD_UNIT_ID,
    slotElementId: VERTICAL_AD_SLOT_DOM_ID,
  }),
  // Second (top) rectangle ad
  MockSlot({
    adUnitPath: SECOND_VERTICAL_AD_UNIT_ID,
    slotElementId: SECOND_VERTICAL_AD_SLOT_DOM_ID,
  }),
]

const mockGetSlots = jest.fn(() => {
  return mockSlots
})
const mockSetTargeting = jest.fn()

// Mock an event fired.
export const __runEventListenerCallbacks = (eventName, ...args) => {
  eventListenerStore[eventName].forEach(f => f(...args))
}

const mockCmd = []
mockCmd.push = f => f()

const eventListenerStore = {}

export default () => {
  window.googletag = window.googletag || {
    cmd: mockCmd,
    pubads: jest.fn(() => ({
      addEventListener: (eventName, callback) => {
        if (!eventListenerStore[eventName]) {
          eventListenerStore[eventName] = []
        }
        eventListenerStore[eventName].push(callback)
      },
      getSlots: mockGetSlots,
      enableSingleRequest: mockEnableSingleRequest,
      refresh: mockPubadsRefresh,
      setTargeting: mockSetTargeting,
    })),
    defineSlot: jest.fn(() => ({
      addService: jest.fn(),
    })),
    enableServices: jest.fn(),
  }
  return window.googletag
}
<|endoftext|>