code
stringlengths 2
1.05M
|
---|
"use strict";angular.module("ngParallax",[]).directive("ngParallax",["$timeout",function(){return{restrict:"AE",scope:{pattern:"=",speed:"=",offset:"=",reverse:"="},link:function(e,t){function n(){var t=void 0!==window.pageYOffset?window.pageYOffset:(document.documentElement||document.body.parentNode||document.body).scrollTop;if(r)var n=t*(e.speed+1);else var n=t/(e.speed+1);var a="50% "+n+"px";o.style.backgroundPosition=a}var o=t[0];o.style.backgroundRepeat="repeat",o.style.backgroundAttachment="fixed",o.style.height="100%",o.style.margin="0 auto",o.style.position="relative",o.style.background="url("+e.pattern+")";var r=Boolean(e.reverse)||!1;window.document.addEventListener("scroll",function(){n()}),n()}}}]);
|
/**
* angular-drag-and-drop-lists v1.4.0
*
* Copyright (c) 2014 Marcel Juenemann [email protected]
* Copyright (c) 2014-2016 Google Inc.
* https://github.com/marceljuenemann/angular-drag-and-drop-lists
*
* License: MIT
*/
angular.module('dndLists', [])
/**
* Use the dnd-draggable attribute to make your element draggable
*
* Attributes:
* - dnd-draggable Required attribute. The value has to be an object that represents the data
* of the element. In case of a drag and drop operation the object will be
* serialized and unserialized on the receiving end.
* - dnd-selected Callback that is invoked when the element was clicked but not dragged.
* The original click event will be provided in the local event variable.
* - dnd-effect-allowed Use this attribute to limit the operations that can be performed. Options:
* - "move": The drag operation will move the element. This is the default.
* - "copy": The drag operation will copy the element. Shows a copy cursor.
* - "copyMove": The user can choose between copy and move by pressing the
* ctrl or shift key. *Not supported in IE:* In Internet Explorer this
* option will be the same as "copy". *Not fully supported in Chrome on
* Windows:* In the Windows version of Chrome the cursor will always be the
* move cursor. However, when the user drops an element and has the ctrl
* key pressed, we will perform a copy anyways.
* - HTML5 also specifies the "link" option, but this library does not
* actively support it yet, so use it at your own risk.
* - dnd-moved Callback that is invoked when the element was moved. Usually you will
* remove your element from the original list in this callback, since the
* directive is not doing that for you automatically. The original dragend
* event will be provided in the local event variable.
* - dnd-canceled Callback that is invoked if the element was dragged, but the operation was
* canceled and the element was not dropped. The original dragend event will
* be provided in the local event variable.
* - dnd-copied Same as dnd-moved, just that it is called when the element was copied
* instead of moved. The original dragend event will be provided in the local
* event variable.
* - dnd-dragstart Callback that is invoked when the element was dragged. The original
* dragstart event will be provided in the local event variable.
* - dnd-dragend Callback that is invoked when the drag operation ended. Available local
* variables are event and dropEffect.
* - dnd-type Use this attribute if you have different kinds of items in your
* application and you want to limit which items can be dropped into which
* lists. Combine with dnd-allowed-types on the dnd-list(s). This attribute
* should evaluate to a string, although this restriction is not enforced.
* - dnd-disable-if You can use this attribute to dynamically disable the draggability of the
* element. This is useful if you have certain list items that you don't want
* to be draggable, or if you want to disable drag & drop completely without
* having two different code branches (e.g. only allow for admins).
* **Note**: If your element is not draggable, the user is probably able to
* select text or images inside of it. Since a selection is always draggable,
* this breaks your UI. You most likely want to disable user selection via
* CSS (see user-select).
*
* CSS classes:
* - dndDragging This class will be added to the element while the element is being
* dragged. It will affect both the element you see while dragging and the
* source element that stays at it's position. Do not try to hide the source
* element with this class, because that will abort the drag operation.
* - dndDraggingSource This class will be added to the element after the drag operation was
* started, meaning it only affects the original element that is still at
* it's source position, and not the "element" that the user is dragging with
* his mouse pointer.
*/
.directive('dndDraggable', ['$parse', '$timeout', 'dndDropEffectWorkaround', 'dndDragTypeWorkaround',
function($parse, $timeout, dndDropEffectWorkaround, dndDragTypeWorkaround) {
return function(scope, element, attr) {
// Set the HTML5 draggable attribute on the element
element.attr("draggable", "true");
// If the dnd-disable-if attribute is set, we have to watch that
if (attr.dndDisableIf) {
scope.$watch(attr.dndDisableIf, function(disabled) {
element.attr("draggable", !disabled);
});
}
/**
* When the drag operation is started we have to prepare the dataTransfer object,
* which is the primary way we communicate with the target element
*/
element.on('dragstart', function(event) {
event = event.originalEvent || event;
// Check whether the element is draggable, since dragstart might be triggered on a child.
if (element.attr('draggable') == 'false') return true;
// Serialize the data associated with this element. IE only supports the Text drag type
event.dataTransfer.setData("Text", angular.toJson(scope.$eval(attr.dndDraggable)));
// Only allow actions specified in dnd-effect-allowed attribute
event.dataTransfer.effectAllowed = attr.dndEffectAllowed || "move";
// Add CSS classes. See documentation above
element.addClass("dndDragging");
$timeout(function() { element.addClass("dndDraggingSource"); }, 0);
// Workarounds for stupid browsers, see description below
dndDropEffectWorkaround.dropEffect = "none";
dndDragTypeWorkaround.isDragging = true;
// Save type of item in global state. Usually, this would go into the dataTransfer
// typename, but we have to use "Text" there to support IE
dndDragTypeWorkaround.dragType = attr.dndType ? scope.$eval(attr.dndType) : undefined;
// Try setting a proper drag image if triggered on a dnd-handle (won't work in IE).
if (event._dndHandle && event.dataTransfer.setDragImage) {
event.dataTransfer.setDragImage(element[0], 0, 0);
}
// Invoke callback
$parse(attr.dndDragstart)(scope, {event: event});
event.stopPropagation();
});
/**
* The dragend event is triggered when the element was dropped or when the drag
* operation was aborted (e.g. hit escape button). Depending on the executed action
* we will invoke the callbacks specified with the dnd-moved or dnd-copied attribute.
*/
element.on('dragend', function(event) {
event = event.originalEvent || event;
// Invoke callbacks. Usually we would use event.dataTransfer.dropEffect to determine
// the used effect, but Chrome has not implemented that field correctly. On Windows
// it always sets it to 'none', while Chrome on Linux sometimes sets it to something
// else when it's supposed to send 'none' (drag operation aborted).
var dropEffect = dndDropEffectWorkaround.dropEffect;
scope.$apply(function() {
switch (dropEffect) {
case "move":
$parse(attr.dndMoved)(scope, {event: event});
break;
case "copy":
$parse(attr.dndCopied)(scope, {event: event});
break;
case "none":
$parse(attr.dndCanceled)(scope, {event: event});
break;
}
$parse(attr.dndDragend)(scope, {event: event, dropEffect: dropEffect});
});
// Clean up
element.removeClass("dndDragging");
$timeout(function() { element.removeClass("dndDraggingSource"); }, 0);
dndDragTypeWorkaround.isDragging = false;
event.stopPropagation();
});
/**
* When the element is clicked we invoke the callback function
* specified with the dnd-selected attribute.
*/
element.on('click', function(event) {
if (!attr.dndSelected) return;
event = event.originalEvent || event;
scope.$apply(function() {
$parse(attr.dndSelected)(scope, {event: event});
});
// Prevent triggering dndSelected in parent elements.
event.stopPropagation();
});
/**
* Workaround to make element draggable in IE9
*/
element.on('selectstart', function() {
if (this.dragDrop) this.dragDrop();
});
};
}])
/**
* Use the dnd-list attribute to make your list element a dropzone. Usually you will add a single
* li element as child with the ng-repeat directive. If you don't do that, we will not be able to
* position the dropped element correctly. If you want your list to be sortable, also add the
* dnd-draggable directive to your li element(s). Both the dnd-list and it's direct children must
* have position: relative CSS style, otherwise the positioning algorithm will not be able to
* determine the correct placeholder position in all browsers.
*
* Attributes:
* - dnd-list Required attribute. The value has to be the array in which the data of
* the dropped element should be inserted.
* - dnd-allowed-types Optional array of allowed item types. When used, only items that had a
* matching dnd-type attribute will be dropable.
* - dnd-disable-if Optional boolean expresssion. When it evaluates to true, no dropping
* into the list is possible. Note that this also disables rearranging
* items inside the list.
* - dnd-horizontal-list Optional boolean expresssion. When it evaluates to true, the positioning
* algorithm will use the left and right halfs of the list items instead of
* the upper and lower halfs.
* - dnd-dragover Optional expression that is invoked when an element is dragged over the
* list. If the expression is set, but does not return true, the element is
* not allowed to be dropped. The following variables will be available:
* - event: The original dragover event sent by the browser.
* - index: The position in the list at which the element would be dropped.
* - type: The dnd-type set on the dnd-draggable, or undefined if unset.
* - external: Whether the element was dragged from an external source.
* - dnd-drop Optional expression that is invoked when an element is dropped on the
* list. The following variables will be available:
* - event: The original drop event sent by the browser.
* - index: The position in the list at which the element would be dropped.
* - item: The transferred object.
* - type: The dnd-type set on the dnd-draggable, or undefined if unset.
* - external: Whether the element was dragged from an external source.
* The return value determines the further handling of the drop:
* - false: The drop will be canceled and the element won't be inserted.
* - true: Signalises that the drop is allowed, but the dnd-drop
* callback already took care of inserting the element.
* - otherwise: All other return values will be treated as the object to
* insert into the array. In most cases you want to simply return the
* item parameter, but there are no restrictions on what you can return.
* - dnd-inserted Optional expression that is invoked after a drop if the element was
* actually inserted into the list. The same local variables as for
* dnd-drop will be available. Note that for reorderings inside the same
* list the old element will still be in the list due to the fact that
* dnd-moved was not called yet.
* - dnd-external-sources Optional boolean expression. When it evaluates to true, the list accepts
* drops from sources outside of the current browser tab. This allows to
* drag and drop accross different browser tabs. Note that this will allow
* to drop arbitrary text into the list, thus it is highly recommended to
* implement the dnd-drop callback to check the incoming element for
* sanity. Furthermore, the dnd-type of external sources can not be
* determined, therefore do not rely on restrictions of dnd-allowed-type.
*
* CSS classes:
* - dndPlaceholder When an element is dragged over the list, a new placeholder child
* element will be added. This element is of type li and has the class
* dndPlaceholder set. Alternatively, you can define your own placeholder
* by creating a child element with dndPlaceholder class.
* - dndDragover Will be added to the list while an element is dragged over the list.
*/
.directive('dndList', ['$parse', '$timeout', 'dndDropEffectWorkaround', 'dndDragTypeWorkaround',
function($parse, $timeout, dndDropEffectWorkaround, dndDragTypeWorkaround) {
return function(scope, element, attr) {
// While an element is dragged over the list, this placeholder element is inserted
// at the location where the element would be inserted after dropping
var placeholder = getPlaceholderElement();
var placeholderNode = placeholder[0];
var listNode = element[0];
placeholder.remove();
var horizontal = attr.dndHorizontalList && scope.$eval(attr.dndHorizontalList);
var externalSources = attr.dndExternalSources && scope.$eval(attr.dndExternalSources);
/**
* The dragenter event is fired when a dragged element or text selection enters a valid drop
* target. According to the spec, we either need to have a dropzone attribute or listen on
* dragenter events and call preventDefault(). It should be noted though that no browser seems
* to enforce this behaviour.
*/
element.on('dragenter', function (event) {
event = event.originalEvent || event;
if (!isDropAllowed(event)) return true;
event.preventDefault();
});
/**
* The dragover event is triggered "every few hundred milliseconds" while an element
* is being dragged over our list, or over an child element.
*/
element.on('dragover', function(event) {
event = event.originalEvent || event;
if (!isDropAllowed(event)) return true;
// First of all, make sure that the placeholder is shown
// This is especially important if the list is empty
if (placeholderNode.parentNode != listNode) {
element.append(placeholder);
}
if (event.target !== listNode) {
// Try to find the node direct directly below the list node.
var listItemNode = event.target;
while (listItemNode.parentNode !== listNode && listItemNode.parentNode) {
listItemNode = listItemNode.parentNode;
}
if (listItemNode.parentNode === listNode && listItemNode !== placeholderNode) {
// If the mouse pointer is in the upper half of the child element,
// we place it before the child element, otherwise below it.
if (isMouseInFirstHalf(event, listItemNode)) {
listNode.insertBefore(placeholderNode, listItemNode);
} else {
listNode.insertBefore(placeholderNode, listItemNode.nextSibling);
}
}
} else {
// This branch is reached when we are dragging directly over the list element.
// Usually we wouldn't need to do anything here, but the IE does not fire it's
// events for the child element, only for the list directly. Therefore, we repeat
// the positioning algorithm for IE here.
if (isMouseInFirstHalf(event, placeholderNode, true)) {
// Check if we should move the placeholder element one spot towards the top.
// Note that display none elements will have offsetTop and offsetHeight set to
// zero, therefore we need a special check for them.
while (placeholderNode.previousElementSibling
&& (isMouseInFirstHalf(event, placeholderNode.previousElementSibling, true)
|| placeholderNode.previousElementSibling.offsetHeight === 0)) {
listNode.insertBefore(placeholderNode, placeholderNode.previousElementSibling);
}
} else {
// Check if we should move the placeholder element one spot towards the bottom
while (placeholderNode.nextElementSibling &&
!isMouseInFirstHalf(event, placeholderNode.nextElementSibling, true)) {
listNode.insertBefore(placeholderNode,
placeholderNode.nextElementSibling.nextElementSibling);
}
}
}
// At this point we invoke the callback, which still can disallow the drop.
// We can't do this earlier because we want to pass the index of the placeholder.
if (attr.dndDragover && !invokeCallback(attr.dndDragover, event, getPlaceholderIndex())) {
return stopDragover();
}
element.addClass("dndDragover");
event.preventDefault();
event.stopPropagation();
return false;
});
/**
* When the element is dropped, we use the position of the placeholder element as the
* position where we insert the transferred data. This assumes that the list has exactly
* one child element per array element.
*/
element.on('drop', function(event) {
event = event.originalEvent || event;
if (!isDropAllowed(event)) return true;
// The default behavior in Firefox is to interpret the dropped element as URL and
// forward to it. We want to prevent that even if our drop is aborted.
event.preventDefault();
// Unserialize the data that was serialized in dragstart. According to the HTML5 specs,
// the "Text" drag type will be converted to text/plain, but IE does not do that.
var data = event.dataTransfer.getData("Text") || event.dataTransfer.getData("text/plain");
var transferredObject;
try {
transferredObject = JSON.parse(data);
} catch(e) {
return stopDragover();
}
// Invoke the callback, which can transform the transferredObject and even abort the drop.
var index = getPlaceholderIndex();
if (attr.dndDrop) {
transferredObject = invokeCallback(attr.dndDrop, event, index, transferredObject);
if (!transferredObject) {
return stopDragover();
}
}
// Insert the object into the array, unless dnd-drop took care of that (returned true).
if (transferredObject !== true) {
scope.$apply(function() {
scope.$eval(attr.dndList).splice(index, 0, transferredObject);
});
}
invokeCallback(attr.dndInserted, event, index, transferredObject);
// In Chrome on Windows the dropEffect will always be none...
// We have to determine the actual effect manually from the allowed effects
if (event.dataTransfer.dropEffect === "none") {
if (event.dataTransfer.effectAllowed === "copy" ||
event.dataTransfer.effectAllowed === "move") {
dndDropEffectWorkaround.dropEffect = event.dataTransfer.effectAllowed;
} else {
dndDropEffectWorkaround.dropEffect = event.ctrlKey ? "copy" : "move";
}
} else {
dndDropEffectWorkaround.dropEffect = event.dataTransfer.dropEffect;
}
// Clean up
stopDragover();
event.stopPropagation();
return false;
});
/**
* We have to remove the placeholder when the element is no longer dragged over our list. The
* problem is that the dragleave event is not only fired when the element leaves our list,
* but also when it leaves a child element -- so practically it's fired all the time. As a
* workaround we wait a few milliseconds and then check if the dndDragover class was added
* again. If it is there, dragover must have been called in the meantime, i.e. the element
* is still dragging over the list. If you know a better way of doing this, please tell me!
*/
element.on('dragleave', function(event) {
event = event.originalEvent || event;
element.removeClass("dndDragover");
$timeout(function() {
if (!element.hasClass("dndDragover")) {
placeholder.remove();
}
}, 100);
});
/**
* Checks whether the mouse pointer is in the first half of the given target element.
*
* In Chrome we can just use offsetY, but in Firefox we have to use layerY, which only
* works if the child element has position relative. In IE the events are only triggered
* on the listNode instead of the listNodeItem, therefore the mouse positions are
* relative to the parent element of targetNode.
*/
function isMouseInFirstHalf(event, targetNode, relativeToParent) {
var mousePointer = horizontal ? (event.offsetX || event.layerX)
: (event.offsetY || event.layerY);
var targetSize = horizontal ? targetNode.offsetWidth : targetNode.offsetHeight;
var targetPosition = horizontal ? targetNode.offsetLeft : targetNode.offsetTop;
targetPosition = relativeToParent ? targetPosition : 0;
return mousePointer < targetPosition + targetSize / 2;
}
/**
* Tries to find a child element that has the dndPlaceholder class set. If none was found, a
* new li element is created.
*/
function getPlaceholderElement() {
var placeholder;
angular.forEach(element.children(), function(childNode) {
var child = angular.element(childNode);
if (child.hasClass('dndPlaceholder')) {
placeholder = child;
}
});
return placeholder || angular.element("<li class='dndPlaceholder'></li>");
}
/**
* We use the position of the placeholder node to determine at which position of the array the
* object needs to be inserted
*/
function getPlaceholderIndex() {
return Array.prototype.indexOf.call(listNode.children, placeholderNode);
}
/**
* Checks various conditions that must be fulfilled for a drop to be allowed
*/
function isDropAllowed(event) {
// Disallow drop from external source unless it's allowed explicitly.
if (!dndDragTypeWorkaround.isDragging && !externalSources) return false;
// Check mimetype. Usually we would use a custom drag type instead of Text, but IE doesn't
// support that.
if (!hasTextMimetype(event.dataTransfer.types)) return false;
// Now check the dnd-allowed-types against the type of the incoming element. For drops from
// external sources we don't know the type, so it will need to be checked via dnd-drop.
if (attr.dndAllowedTypes && dndDragTypeWorkaround.isDragging) {
var allowed = scope.$eval(attr.dndAllowedTypes);
if (angular.isArray(allowed) && allowed.indexOf(dndDragTypeWorkaround.dragType) === -1) {
return false;
}
}
// Check whether droping is disabled completely
if (attr.dndDisableIf && scope.$eval(attr.dndDisableIf)) return false;
return true;
}
/**
* Small helper function that cleans up if we aborted a drop.
*/
function stopDragover() {
placeholder.remove();
element.removeClass("dndDragover");
return true;
}
/**
* Invokes a callback with some interesting parameters and returns the callbacks return value.
*/
function invokeCallback(expression, event, index, item) {
return $parse(expression)(scope, {
event: event,
index: index,
item: item || undefined,
external: !dndDragTypeWorkaround.isDragging,
type: dndDragTypeWorkaround.isDragging ? dndDragTypeWorkaround.dragType : undefined
});
}
/**
* Check if the dataTransfer object contains a drag type that we can handle. In old versions
* of IE the types collection will not even be there, so we just assume a drop is possible.
*/
function hasTextMimetype(types) {
if (!types) return true;
for (var i = 0; i < types.length; i++) {
if (types[i] === "Text" || types[i] === "text/plain") return true;
}
return false;
}
};
}])
/**
* Use the dnd-nodrag attribute inside of dnd-draggable elements to prevent them from starting
* drag operations. This is especially useful if you want to use input elements inside of
* dnd-draggable elements or create specific handle elements. Note: This directive does not work
* in Internet Explorer 9.
*/
.directive('dndNodrag', function() {
return function(scope, element, attr) {
// Set as draggable so that we can cancel the events explicitly
element.attr("draggable", "true");
/**
* Since the element is draggable, the browser's default operation is to drag it on dragstart.
* We will prevent that and also stop the event from bubbling up.
*/
element.on('dragstart', function(event) {
event = event.originalEvent || event;
if (!event._dndHandle) {
// If a child element already reacted to dragstart and set a dataTransfer object, we will
// allow that. For example, this is the case for user selections inside of input elements.
if (!(event.dataTransfer.types && event.dataTransfer.types.length)) {
event.preventDefault();
}
event.stopPropagation();
}
});
/**
* Stop propagation of dragend events, otherwise dnd-moved might be triggered and the element
* would be removed.
*/
element.on('dragend', function(event) {
event = event.originalEvent || event;
if (!event._dndHandle) {
event.stopPropagation();
}
});
};
})
/**
* Use the dnd-handle directive within a dnd-nodrag element in order to allow dragging with that
* element after all. Therefore, by combining dnd-nodrag and dnd-handle you can allow
* dnd-draggable elements to only be dragged via specific "handle" elements. Note that Internet
* Explorer will show the handle element as drag image instead of the dnd-draggable element. You
* can work around this by styling the handle element differently when it is being dragged. Use
* the CSS selector .dndDragging:not(.dndDraggingSource) [dnd-handle] for that.
*/
.directive('dndHandle', function() {
return function(scope, element, attr) {
element.attr("draggable", "true");
element.on('dragstart dragend', function(event) {
event = event.originalEvent || event;
event._dndHandle = true;
});
};
})
/**
* This workaround handles the fact that Internet Explorer does not support drag types other than
* "Text" and "URL". That means we can not know whether the data comes from one of our elements or
* is just some other data like a text selection. As a workaround we save the isDragging flag in
* here. When a dropover event occurs, we only allow the drop if we are already dragging, because
* that means the element is ours.
*/
.factory('dndDragTypeWorkaround', function(){ return {} })
/**
* Chrome on Windows does not set the dropEffect field, which we need in dragend to determine
* whether a drag operation was successful. Therefore we have to maintain it in this global
* variable. The bug report for that has been open for years:
* https://code.google.com/p/chromium/issues/detail?id=39399
*/
.factory('dndDropEffectWorkaround', function(){ return {} });
|
/*
@license textAngular
Author : Austin Anderson
License : 2013 MIT
Version 1.3.0-17
See README.md or https://github.com/fraywing/textAngular/wiki for requirements and use.
*/
(function(){ // encapsulate all variables so they don't become global vars
"Use Strict";
// IE version detection - http://stackoverflow.com/questions/4169160/javascript-ie-detection-why-not-use-simple-conditional-comments
// We need this as IE sometimes plays funny tricks with the contenteditable.
// ----------------------------------------------------------
// If you're not in IE (or IE version is less than 5) then:
// ie === undefined
// If you're in IE (>=5) then you can determine which version:
// ie === 7; // IE7
// Thus, to detect IE:
// if (ie) {}
// And to detect the version:
// ie === 6 // IE6
// ie > 7 // IE8, IE9, IE10 ...
// ie < 9 // Anything less than IE9
// ----------------------------------------------------------
/* istanbul ignore next: untestable browser check */
var _browserDetect = {
ie: (function(){
var undef,
v = 3,
div = document.createElement('div'),
all = div.getElementsByTagName('i');
while (
div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->',
all[0]
);
return v > 4 ? v : undef;
}()),
webkit: /AppleWebKit\/([\d.]+)/i.test(navigator.userAgent)
};
// fix a webkit bug, see: https://gist.github.com/shimondoodkin/1081133
// this is set true when a blur occurs as the blur of the ta-bind triggers before the click
var globalContentEditableBlur = false;
/* istanbul ignore next: Browser Un-Focus fix for webkit */
if(_browserDetect.webkit) {
document.addEventListener("mousedown", function(_event){
var e = _event || window.event;
var curelement = e.target;
if(globalContentEditableBlur && curelement !== null){
var isEditable = false;
var tempEl = curelement;
while(tempEl !== null && tempEl.tagName.toLowerCase() !== 'html' && !isEditable){
isEditable = tempEl.contentEditable === 'true';
tempEl = tempEl.parentNode;
}
if(!isEditable){
document.getElementById('textAngular-editableFix-010203040506070809').setSelectionRange(0, 0); // set caret focus to an element that handles caret focus correctly.
curelement.focus(); // focus the wanted element.
if (curelement.select) {
curelement.select(); // use select to place cursor for input elements.
}
}
}
globalContentEditableBlur = false;
}, false); // add global click handler
angular.element(document).ready(function () {
angular.element(document.body).append(angular.element('<input id="textAngular-editableFix-010203040506070809" style="width:1px;height:1px;border:none;margin:0;padding:0;position:absolute; top: -10000px; left: -10000px;" unselectable="on" tabIndex="-1">'));
});
}
// Gloabl to textAngular REGEXP vars for block and list elements.
var BLOCKELEMENTS = /^(address|article|aside|audio|blockquote|canvas|dd|div|dl|fieldset|figcaption|figure|footer|form|h1|h2|h3|h4|h5|h6|header|hgroup|hr|noscript|ol|output|p|pre|section|table|tfoot|ul|video)$/ig;
var LISTELEMENTS = /^(ul|li|ol)$/ig;
var VALIDELEMENTS = /^(address|article|aside|audio|blockquote|canvas|dd|div|dl|fieldset|figcaption|figure|footer|form|h1|h2|h3|h4|h5|h6|header|hgroup|hr|noscript|ol|output|p|pre|section|table|tfoot|ul|video|li)$/ig;
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim#Compatibility
/* istanbul ignore next: trim shim for older browsers */
if (!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^\s+|\s+$/g, '');
};
}
// tests against the current jqLite/jquery implementation if this can be an element
function validElementString(string){
try{
return angular.element(string).length !== 0;
}catch(any){
return false;
}
}
/*
Custom stylesheet for the placeholders rules.
Credit to: http://davidwalsh.name/add-rules-stylesheets
*/
var sheet, addCSSRule, removeCSSRule, _addCSSRule, _removeCSSRule;
/* istanbul ignore else: IE <8 test*/
if(_browserDetect.ie > 8 || _browserDetect.ie === undefined){
var _sheets = document.styleSheets;
/* istanbul ignore next: preference for stylesheet loaded externally */
for(var i = 0; i < _sheets.length; i++){
if(_sheets[i].media.length === 0 || _sheets[i].media.mediaText.match(/(all|screen)/ig)){
if(_sheets[i].href){
if(_sheets[i].href.match(/textangular\.(min\.|)css/ig)){
sheet = _sheets[i];
break;
}
}
}
}
/* istanbul ignore next: preference for stylesheet loaded externally */
if(!sheet){
// this sheet is used for the placeholders later on.
sheet = (function() {
// Create the <style> tag
var style = document.createElement("style");
/* istanbul ignore else : WebKit hack :( */
if(_browserDetect.webkit) style.appendChild(document.createTextNode(""));
// Add the <style> element to the page, add as first so the styles can be overridden by custom stylesheets
document.head.appendChild(style);
return style.sheet;
})();
}
// use as: addCSSRule("header", "float: left");
addCSSRule = function(selector, rules) {
return _addCSSRule(sheet, selector, rules);
};
_addCSSRule = function(_sheet, selector, rules){
var insertIndex;
// This order is important as IE 11 has both cssRules and rules but they have different lengths - cssRules is correct, rules gives an error in IE 11
/* istanbul ignore else: firefox catch */
if(_sheet.cssRules) insertIndex = Math.max(_sheet.cssRules.length - 1, 0);
else if(_sheet.rules) insertIndex = Math.max(_sheet.rules.length - 1, 0);
/* istanbul ignore else: untestable IE option */
if(_sheet.insertRule) {
_sheet.insertRule(selector + "{" + rules + "}", insertIndex);
}
else {
_sheet.addRule(selector, rules, insertIndex);
}
// return the index of the stylesheet rule
return insertIndex;
};
removeCSSRule = function(index){
_removeCSSRule(sheet, index);
};
_removeCSSRule = function(sheet, index){
/* istanbul ignore else: untestable IE option */
if(sheet.removeRule){
sheet.removeRule(index);
}else{
sheet.deleteRule(index);
}
};
}
// recursive function that returns an array of angular.elements that have the passed attribute set on them
function getByAttribute(element, attribute){
var resultingElements = [];
var childNodes = element.children();
if(childNodes.length){
angular.forEach(childNodes, function(child){
resultingElements = resultingElements.concat(getByAttribute(angular.element(child), attribute));
});
}
if(element.attr(attribute) !== undefined) resultingElements.push(element);
return resultingElements;
}
angular.module('textAngular.factories', [])
.factory('taBrowserTag', [function(){
return function(tag){
/* istanbul ignore next: ie specific test */
if(!tag) return (_browserDetect.ie <= 8)? 'P' : 'p';
else if(tag === '') return (_browserDetect.ie === undefined)? 'div' : (_browserDetect.ie <= 8)? 'P' : 'p';
else return (_browserDetect.ie <= 8)? tag.toUpperCase() : tag;
};
}]).factory('taApplyCustomRenderers', ['taCustomRenderers', function(taCustomRenderers){
return function(val){
var element = angular.element('<div></div>');
element[0].innerHTML = val;
angular.forEach(taCustomRenderers, function(renderer){
var elements = [];
// get elements based on what is defined. If both defined do secondary filter in the forEach after using selector string
if(renderer.selector && renderer.selector !== '')
elements = element.find(renderer.selector);
/* istanbul ignore else: shouldn't fire, if it does we're ignoring everything */
else if(renderer.customAttribute && renderer.customAttribute !== '')
elements = getByAttribute(element, renderer.customAttribute);
// process elements if any found
angular.forEach(elements, function(_element){
_element = angular.element(_element);
if(renderer.selector && renderer.selector !== '' && renderer.customAttribute && renderer.customAttribute !== ''){
if(_element.attr(renderer.customAttribute) !== undefined) renderer.renderLogic(_element);
} else renderer.renderLogic(_element);
});
});
return element[0].innerHTML;
};
}]).factory('taFixChrome', function(){
// get whaterever rubbish is inserted in chrome
// should be passed an html string, returns an html string
var taFixChrome = function(html){
// default wrapper is a span so find all of them
var $html = angular.element('<div>' + html + '</div>');
var spans = angular.element($html).find('span');
for(var s = 0; s < spans.length; s++){
var span = angular.element(spans[s]);
// chrome specific string that gets inserted into the style attribute, other parts may vary. Second part is specific ONLY to hitting backspace in Headers
if(span.attr('style') && span.attr('style').match(/line-height: 1.428571429;|color: inherit; line-height: 1.1;/i)){
span.attr('style', span.attr('style').replace(/( |)font-family: inherit;|( |)line-height: 1.428571429;|( |)line-height:1.1;|( |)color: inherit;/ig, ''));
if(!span.attr('style') || span.attr('style') === ''){
if(span.next().length > 0 && span.next()[0].tagName === 'BR') span.next().remove();
span.replaceWith(span[0].innerHTML);
}
}
}
// regex to replace ONLY offending styles - these can be inserted into various other tags on delete
var result = $html[0].innerHTML.replace(/style="[^"]*?(line-height: 1.428571429;|color: inherit; line-height: 1.1;)[^"]*"/ig, '');
// only replace when something has changed, else we get focus problems on inserting lists
if(result !== $html[0].innerHTML) $html[0].innerHTML = result;
return $html[0].innerHTML;
};
return taFixChrome;
}).factory('taSanitize', ['$sanitize', function taSanitizeFactory($sanitize){
var convert_infos = [
{
property: 'font-weight',
values: [ 'bold' ],
tag: 'b'
},
{
property: 'font-style',
values: [ 'italic' ],
tag: 'i'
}
];
function fixChildren( jq_elm ) {
var children = jq_elm.children();
if ( !children.length ) {
return;
}
angular.forEach( children, function( child ) {
var jq_child = angular.element(child);
fixElement( jq_child );
fixChildren( jq_child );
});
}
function fixElement( jq_elm ) {
var styleString = jq_elm.attr('style');
if ( !styleString ) {
return;
}
angular.forEach( convert_infos, function( convert_info ) {
var css_key = convert_info.property;
var css_value = jq_elm.css(css_key);
if ( convert_info.values.indexOf(css_value) >= 0 && styleString.toLowerCase().indexOf(css_key) >= 0 ) {
jq_elm.css( css_key, '' );
var inner_html = jq_elm.html();
var tag = convert_info.tag;
inner_html = '<'+tag+'>' + inner_html + '</'+tag+'>';
jq_elm.html( inner_html );
}
});
}
return function taSanitize(unsafe, oldsafe, ignore){
if ( !ignore ) {
try {
var jq_container = angular.element('<div>' + unsafe + '</div>');
fixElement( jq_container );
fixChildren( jq_container );
unsafe = jq_container.html();
} catch (e) {
}
}
// unsafe and oldsafe should be valid HTML strings
// any exceptions (lets say, color for example) should be made here but with great care
// setup unsafe element for modification
var unsafeElement = angular.element('<div>' + unsafe + '</div>');
// replace all align='...' tags with text-align attributes
angular.forEach(getByAttribute(unsafeElement, 'align'), function(element){
element.css('text-align', element.attr('align'));
element.removeAttr('align');
});
// get the html string back
var safe;
unsafe = unsafeElement[0].innerHTML;
try {
safe = $sanitize(unsafe);
// do this afterwards, then the $sanitizer should still throw for bad markup
if(ignore) safe = unsafe;
} catch (e){
safe = oldsafe || '';
}
return safe;
};
}]).factory('taToolExecuteAction', ['$q', '$log', function($q, $log){
// this must be called on a toolScope or instance
return function(editor){
if(editor !== undefined) this.$editor = function(){ return editor; };
var deferred = $q.defer(),
promise = deferred.promise,
_editor = this.$editor();
promise['finally'](function(){
_editor.endAction.call(_editor);
});
// pass into the action the deferred function and also the function to reload the current selection if rangy available
var result;
try{
result = this.action(deferred, _editor.startAction());
}catch(exc){
$log.error(exc);
}
if(result || result === undefined){
// if true or undefined is returned then the action has finished. Otherwise the deferred action will be resolved manually.
deferred.resolve();
}
};
}]);
angular.module('textAngular.DOM', ['textAngular.factories'])
.factory('taExecCommand', ['taSelection', 'taBrowserTag', '$document', function(taSelection, taBrowserTag, $document){
var listToDefault = function(listElement, defaultWrap){
var $target, i;
// if all selected then we should remove the list
// grab all li elements and convert to taDefaultWrap tags
var children = listElement.find('li');
for(i = children.length - 1; i >= 0; i--){
$target = angular.element('<' + defaultWrap + '>' + children[i].innerHTML + '</' + defaultWrap + '>');
listElement.after($target);
}
listElement.remove();
taSelection.setSelectionToElementEnd($target[0]);
};
var selectLi = function(liElement){
if(/(<br(|\/)>)$/i.test(liElement.innerHTML.trim())) taSelection.setSelectionBeforeElement(angular.element(liElement).find("br")[0]);
else taSelection.setSelectionToElementEnd(liElement);
};
var listToList = function(listElement, newListTag){
var $target = angular.element('<' + newListTag + '>' + listElement[0].innerHTML + '</' + newListTag + '>');
listElement.after($target);
listElement.remove();
selectLi($target.find('li')[0]);
};
var childElementsToList = function(elements, listElement, newListTag){
var html = '';
for(var i = 0; i < elements.length; i++){
html += '<' + taBrowserTag('li') + '>' + elements[i].innerHTML + '</' + taBrowserTag('li') + '>';
}
var $target = angular.element('<' + newListTag + '>' + html + '</' + newListTag + '>');
listElement.after($target);
listElement.remove();
selectLi($target.find('li')[0]);
};
return function(taDefaultWrap, topNode){
taDefaultWrap = taBrowserTag(taDefaultWrap);
return function(command, showUI, options){
var i, $target, html, _nodes, next, optionsTagName, selectedElement;
var defaultWrapper = angular.element('<' + taDefaultWrap + '>');
try{
selectedElement = taSelection.getSelectionElement();
}catch(e){}
var $selected = angular.element(selectedElement);
if(selectedElement !== undefined){
var tagName = selectedElement.tagName.toLowerCase();
if(command.toLowerCase() === 'insertorderedlist' || command.toLowerCase() === 'insertunorderedlist'){
var selfTag = taBrowserTag((command.toLowerCase() === 'insertorderedlist')? 'ol' : 'ul');
if(tagName === selfTag){
// if all selected then we should remove the list
// grab all li elements and convert to taDefaultWrap tags
return listToDefault($selected, taDefaultWrap);
}else if(tagName === 'li' && $selected.parent()[0].tagName.toLowerCase() === selfTag && $selected.parent().children().length === 1){
// catch for the previous statement if only one li exists
return listToDefault($selected.parent(), taDefaultWrap);
}else if(tagName === 'li' && $selected.parent()[0].tagName.toLowerCase() !== selfTag && $selected.parent().children().length === 1){
// catch for the previous statement if only one li exists
return listToList($selected.parent(), selfTag);
}else if(tagName.match(BLOCKELEMENTS) && !$selected.hasClass('ta-bind')){
// if it's one of those block elements we have to change the contents
// if it's a ol/ul we are changing from one to the other
if(tagName === 'ol' || tagName === 'ul'){
return listToList($selected, selfTag);
}else{
var childBlockElements = false;
angular.forEach($selected.children(), function(elem){
if(elem.tagName.match(BLOCKELEMENTS)) {
childBlockElements = true;
}
});
if(childBlockElements){
return childElementsToList($selected.children(), $selected, selfTag);
}else{
return childElementsToList([angular.element('<div>' + selectedElement.innerHTML + '</div>')[0]], $selected, selfTag);
}
}
}else if(tagName.match(BLOCKELEMENTS)){
// if we get here then all the contents of the ta-bind are selected
_nodes = taSelection.getOnlySelectedElements();
if(_nodes.length === 0){
// here is if there is only text in ta-bind ie <div ta-bind>test content</div>
$target = angular.element('<' + selfTag + '><li>' + selectedElement.innerHTML + '</li></' + selfTag + '>');
$selected.html('');
$selected.append($target);
}else if(_nodes.length === 1 && (_nodes[0].tagName.toLowerCase() === 'ol' || _nodes[0].tagName.toLowerCase() === 'ul')){
if(_nodes[0].tagName.toLowerCase() === selfTag){
// remove
return listToDefault(angular.element(_nodes[0]), taDefaultWrap);
}else{
return listToList(angular.element(_nodes[0]), selfTag);
}
}else{
html = '';
var $nodes = [];
for(i = 0; i < _nodes.length; i++){
/* istanbul ignore else: catch for real-world can't make it occur in testing */
if(_nodes[i].nodeType !== 3){
var $n = angular.element(_nodes[i]);
/* istanbul ignore if: browser check only, phantomjs doesn't return children nodes but chrome at least does */
if(_nodes[i].tagName.toLowerCase() === 'li') continue;
else if(_nodes[i].tagName.toLowerCase() === 'ol' || _nodes[i].tagName.toLowerCase() === 'ul'){
html += $n[0].innerHTML; // if it's a list, add all it's children
}else if(_nodes[i].tagName.toLowerCase() === 'span' && (_nodes[i].childNodes[0].tagName.toLowerCase() === 'ol' || _nodes[i].childNodes[0].tagName.toLowerCase() === 'ul')){
html += $n[0].childNodes[0].innerHTML; // if it's a list, add all it's children
}else{
html += '<' + taBrowserTag('li') + '>' + $n[0].innerHTML + '</' + taBrowserTag('li') + '>';
}
$nodes.unshift($n);
}
}
$target = angular.element('<' + selfTag + '>' + html + '</' + selfTag + '>');
$nodes.pop().replaceWith($target);
angular.forEach($nodes, function($node){ $node.remove(); });
}
taSelection.setSelectionToElementEnd($target[0]);
return;
}
}else if(command.toLowerCase() === 'formatblock'){
optionsTagName = options.toLowerCase().replace(/[<>]/ig, '');
if(optionsTagName.trim() === 'default') {
optionsTagName = taDefaultWrap;
options = '<' + taDefaultWrap + '>';
}
if(tagName === 'li') $target = $selected.parent();
else $target = $selected;
// find the first blockElement
while(!$target[0].tagName || !$target[0].tagName.match(BLOCKELEMENTS) && !$target.parent().attr('contenteditable')){
$target = $target.parent();
/* istanbul ignore next */
tagName = ($target[0].tagName || '').toLowerCase();
}
if(tagName === optionsTagName){
// $target is wrap element
_nodes = $target.children();
var hasBlock = false;
for(i = 0; i < _nodes.length; i++){
hasBlock = hasBlock || _nodes[i].tagName.match(BLOCKELEMENTS);
}
if(hasBlock){
$target.after(_nodes);
next = $target.next();
$target.remove();
$target = next;
}else{
defaultWrapper.append($target[0].childNodes);
$target.after(defaultWrapper);
$target.remove();
$target = defaultWrapper;
}
}else if($target.parent()[0].tagName.toLowerCase() === optionsTagName && !$target.parent().hasClass('ta-bind')){
//unwrap logic for parent
var blockElement = $target.parent();
var contents = blockElement.contents();
for(i = 0; i < contents.length; i ++){
/* istanbul ignore next: can't test - some wierd thing with how phantomjs works */
if(blockElement.parent().hasClass('ta-bind') && contents[i].nodeType === 3){
defaultWrapper = angular.element('<' + taDefaultWrap + '>');
defaultWrapper[0].innerHTML = contents[i].outerHTML;
contents[i] = defaultWrapper[0];
}
blockElement.parent()[0].insertBefore(contents[i], blockElement[0]);
}
blockElement.remove();
}else if(tagName.match(LISTELEMENTS)){
// wrapping a list element
$target.wrap(options);
}else{
// default wrap behaviour
_nodes = taSelection.getOnlySelectedElements();
if(_nodes.length === 0) _nodes = [$target[0]];
// find the parent block element if any of the nodes are inline or text
for(i = 0; i < _nodes.length; i++){
if(_nodes[i].nodeType === 3 || !_nodes[i].tagName.match(BLOCKELEMENTS)){
while(_nodes[i].nodeType === 3 || !_nodes[i].tagName || !_nodes[i].tagName.match(BLOCKELEMENTS)){
_nodes[i] = _nodes[i].parentNode;
}
}
}
if(angular.element(_nodes[0]).hasClass('ta-bind')){
$target = angular.element(options);
$target[0].innerHTML = _nodes[0].innerHTML;
_nodes[0].innerHTML = $target[0].outerHTML;
}else if(optionsTagName === 'blockquote'){
// blockquotes wrap other block elements
html = '';
for(i = 0; i < _nodes.length; i++){
html += _nodes[i].outerHTML;
}
$target = angular.element(options);
$target[0].innerHTML = html;
_nodes[0].parentNode.insertBefore($target[0],_nodes[0]);
for(i = _nodes.length - 1; i >= 0; i--){
/* istanbul ignore else: */
if(_nodes[i].parentNode) _nodes[i].parentNode.removeChild(_nodes[i]);
}
}
else {
// regular block elements replace other block elements
for(i = 0; i < _nodes.length; i++){
$target = angular.element(options);
$target[0].innerHTML = _nodes[i].innerHTML;
_nodes[i].parentNode.insertBefore($target[0],_nodes[i]);
_nodes[i].parentNode.removeChild(_nodes[i]);
}
}
}
taSelection.setSelectionToElementEnd($target[0]);
return;
}else if(command.toLowerCase() === 'createlink'){
var _selection = taSelection.getSelection();
if(_selection.collapsed){
// insert text at selection, then select then just let normal exec-command run
taSelection.insertHtml('<a href="' + options + '">' + options + '</a>', topNode);
return;
}
}else if(command.toLowerCase() === 'inserthtml'){
taSelection.insertHtml(options, topNode);
return;
}
}
try{
$document[0].execCommand(command, showUI, options);
}catch(e){}
};
};
}]).service('taSelection', ['$window', '$document',
/* istanbul ignore next: all browser specifics and PhantomJS dosen't seem to support half of it */
function($window, $document){
// need to dereference the document else the calls don't work correctly
var _document = $document[0];
var rangy = $window.rangy;
var api = {
getSelection: function(){
var range = rangy.getSelection().getRangeAt(0);
var container = range.commonAncestorContainer;
// Check if the container is a text node and return its parent if so
container = container.nodeType === 3 ? container.parentNode : container;
return {
start: {
element: range.startContainer,
offset: range.startOffset
},
end: {
element: range.endContainer,
offset: range.endOffset
},
container: container,
collapsed: range.collapsed
};
},
getOnlySelectedElements: function(){
var range = rangy.getSelection().getRangeAt(0);
var container = range.commonAncestorContainer;
// Check if the container is a text node and return its parent if so
container = container.nodeType === 3 ? container.parentNode : container;
return range.getNodes([1], function(node){
return node.parentNode === container;
});
},
// Some basic selection functions
getSelectionElement: function () {
return api.getSelection().container;
},
setSelection: function(el, start, end){
var range = rangy.createRange();
range.setStart(el, start);
range.setEnd(el, end);
rangy.getSelection().setSingleRange(range);
},
setSelectionBeforeElement: function (el){
var range = rangy.createRange();
range.selectNode(el);
range.collapse(true);
rangy.getSelection().setSingleRange(range);
},
setSelectionAfterElement: function (el){
var range = rangy.createRange();
range.selectNode(el);
range.collapse(false);
rangy.getSelection().setSingleRange(range);
},
setSelectionToElementStart: function (el){
var range = rangy.createRange();
range.selectNodeContents(el);
range.collapse(true);
rangy.getSelection().setSingleRange(range);
},
setSelectionToElementEnd: function (el){
var range = rangy.createRange();
range.selectNodeContents(el);
range.collapse(false);
rangy.getSelection().setSingleRange(range);
},
// from http://stackoverflow.com/questions/6690752/insert-html-at-caret-in-a-contenteditable-div
// topNode is the contenteditable normally, all manipulation MUST be inside this.
insertHtml: function(html, topNode){
var parent, secondParent, _childI, nodes, startIndex, startNodes, endNodes, i, lastNode;
var element = angular.element("<div>" + html + "</div>");
var range = rangy.getSelection().getRangeAt(0);
var frag = _document.createDocumentFragment();
var children = element[0].childNodes;
var isInline = true;
if(children.length > 0){
// NOTE!! We need to do the following:
// check for blockelements - if they exist then we have to split the current element in half (and all others up to the closest block element) and insert all children in-between.
// If there are no block elements, or there is a mixture we need to create textNodes for the non wrapped text (we don't want them spans messing up the picture).
nodes = [];
for(_childI = 0; _childI < children.length; _childI++){
if(!(
(children[_childI].nodeName.toLowerCase() === 'p' && children[_childI].innerHTML.trim() === '') || // empty p element
(children[_childI].nodeType === 3 && children[_childI].nodeValue.trim() === '') // empty text node
)){
isInline = isInline && !BLOCKELEMENTS.test(children[_childI].nodeName);
nodes.push(children[_childI]);
}
}
for(var _n = 0; _n < nodes.length; _n++) lastNode = frag.appendChild(nodes[_n]);
if(!isInline && range.collapsed && /^(|<br(|\/)>)$/i.test(range.startContainer.innerHTML)) range.selectNode(range.startContainer);
}else{
isInline = true;
// paste text of some sort
lastNode = frag = _document.createTextNode(html);
}
// Other Edge case - selected data spans multiple blocks.
if(isInline){
range.deleteContents();
}else{ // not inline insert
if(range.collapsed && range.startContainer !== topNode && range.startContainer.parentNode !== topNode){
// split element into 2 and insert block element in middle
if(range.startContainer.nodeType === 3){ // if text node
parent = range.startContainer.parentNode;
nodes = parent.childNodes;
// split the nodes into two lists - before and after, splitting the node with the selection into 2 text nodes.
startNodes = [];
endNodes = [];
for(startIndex = 0; startIndex < nodes.length; startIndex++){
startNodes.push(nodes[startIndex]);
if(nodes[startIndex] === range.startContainer) break;
}
endNodes.push(_document.createTextNode(range.startContainer.nodeValue.substring(range.startOffset)));
range.startContainer.nodeValue = range.startContainer.nodeValue.substring(0, range.startOffset);
for(i = startIndex + 1; i < nodes.length; i++) endNodes.push(nodes[i]);
secondParent = parent.cloneNode();
parent.childNodes = startNodes;
secondParent.childNodes = endNodes;
}else{
parent = range.startContainer;
secondParent = parent.cloneNode();
secondParent.innerHTML = parent.innerHTML.substring(range.startOffset);
parent.innerHTML = parent.innerHTML.substring(0, range.startOffset);
}
angular.element(parent).after(secondParent);
// put cursor to end of inserted content
range.setStartAfter(parent);
range.setEndAfter(parent);
if(/^(|<br(|\/)>)$/i.test(parent.innerHTML.trim())){
range.setStartBefore(parent);
range.setEndBefore(parent);
angular.element(parent).remove();
}
if(/^(|<br(|\/)>)$/i.test(secondParent.innerHTML.trim())) angular.element(secondParent).remove();
}else{
range.deleteContents();
}
}
range.insertNode(frag);
if(lastNode){
api.setSelectionToElementEnd(lastNode);
}
}
};
return api;
}]);
angular.module('textAngular.validators', [])
.directive('taMaxText', function(){
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, elem, attrs, ctrl){
var max = parseInt(scope.$eval(attrs.taMaxText));
if (isNaN(max)){
throw('Max text must be an integer');
}
attrs.$observe('taMaxText', function(value){
max = parseInt(value);
if (isNaN(max)){
throw('Max text must be an integer');
}
if (ctrl.$dirty){
ctrl.$setViewValue(ctrl.$viewValue);
}
});
function validator (viewValue){
var source = angular.element('<div/>');
source.html(viewValue);
var length = source.text().length;
if (length <= max){
ctrl.$setValidity('taMaxText', true);
return viewValue;
}
else{
ctrl.$setValidity('taMaxText', false);
return undefined;
}
}
ctrl.$parsers.unshift(validator);
}
};
}).directive('taMinText', function(){
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, elem, attrs, ctrl){
var min = parseInt(scope.$eval(attrs.taMinText));
if (isNaN(min)){
throw('Min text must be an integer');
}
attrs.$observe('taMinText', function(value){
min = parseInt(value);
if (isNaN(min)){
throw('Min text must be an integer');
}
if (ctrl.$dirty){
ctrl.$setViewValue(ctrl.$viewValue);
}
});
function validator (viewValue){
var source = angular.element('<div/>');
source.html(viewValue);
var length = source.text().length;
if (!length || length >= min){
ctrl.$setValidity('taMinText', true);
return viewValue;
}
else{
ctrl.$setValidity('taMinText', false);
return undefined;
}
}
ctrl.$parsers.unshift(validator);
}
};
});
angular.module('textAngular.taBind', ['textAngular.factories', 'textAngular.DOM'])
.directive('taBind', ['taSanitize', '$timeout', '$window', '$document', 'taFixChrome', 'taBrowserTag', 'taSelection', 'taSelectableElements', 'taApplyCustomRenderers', 'taOptions',
function(taSanitize, $timeout, $window, $document, taFixChrome, taBrowserTag, taSelection, taSelectableElements, taApplyCustomRenderers, taOptions){
// Uses for this are textarea or input with ng-model and ta-bind='text'
// OR any non-form element with contenteditable="contenteditable" ta-bind="html|text" ng-model
return {
require: 'ngModel',
link: function(scope, element, attrs, ngModel){
// the option to use taBind on an input or textarea is required as it will sanitize all input into it correctly.
var _isContentEditable = element.attr('contenteditable') !== undefined && element.attr('contenteditable');
var _isInputFriendly = _isContentEditable || element[0].tagName.toLowerCase() === 'textarea' || element[0].tagName.toLowerCase() === 'input';
var _isReadonly = false;
var _focussed = false;
var _disableSanitizer = attrs.taUnsafeSanitizer || taOptions.disableSanitizer;
var _lastKey;
var BLOCKED_KEYS = /^(9|19|20|27|33|34|35|36|37|38|39|40|45|112|113|114|115|116|117|118|119|120|121|122|123|144|145)$/i;
var UNDO_TRIGGER_KEYS = /^(8|13|32|46|59|61|107|109|186|187|188|189|190|191|192|219|220|221|222)$/i; // spaces, enter, delete, backspace, all punctuation
var INLINETAGS_NONBLANK = /<(a|abbr|acronym|bdi|bdo|big|cite|code|del|dfn|img|ins|kbd|label|map|mark|q|ruby|rp|rt|s|samp|time|tt|var)[^>]*>/i;
// defaults to the paragraph element, but we need the line-break or it doesn't allow you to type into the empty element
// non IE is '<p><br/></p>', ie is '<p></p>' as for once IE gets it correct...
var _defaultVal, _defaultTest;
// set the default to be a paragraph value
if(attrs.taDefaultWrap === undefined) attrs.taDefaultWrap = 'p';
/* istanbul ignore next: ie specific test */
if(attrs.taDefaultWrap === ''){
_defaultVal = '';
_defaultTest = (_browserDetect.ie === undefined)? '<div><br></div>' : (_browserDetect.ie >= 11)? '<p><br></p>' : (_browserDetect.ie <= 8)? '<P> </P>' : '<p> </p>';
}else{
_defaultVal = (_browserDetect.ie === undefined || _browserDetect.ie >= 11)?
'<' + attrs.taDefaultWrap + '><br></' + attrs.taDefaultWrap + '>' :
(_browserDetect.ie <= 8)?
'<' + attrs.taDefaultWrap.toUpperCase() + '></' + attrs.taDefaultWrap.toUpperCase() + '>' :
'<' + attrs.taDefaultWrap + '></' + attrs.taDefaultWrap + '>';
_defaultTest = (_browserDetect.ie === undefined || _browserDetect.ie >= 11)?
'<' + attrs.taDefaultWrap + '><br></' + attrs.taDefaultWrap + '>' :
(_browserDetect.ie <= 8)?
'<' + attrs.taDefaultWrap.toUpperCase() + '> </' + attrs.taDefaultWrap.toUpperCase() + '>' :
'<' + attrs.taDefaultWrap + '> </' + attrs.taDefaultWrap + '>';
}
var _blankTest = function(_blankVal){
var _firstTagIndex = _blankVal.indexOf('>');
if(_firstTagIndex === -1) return _blankVal.trim().length === 0;
_blankVal = _blankVal.trim().substring(_firstTagIndex, _firstTagIndex + 100);
// this regex is to match any number of whitespace only between two tags
if (_blankVal.length === 0 || _blankVal === _defaultTest || /^>(\s| )*<\/[^>]+>$/ig.test(_blankVal)) return true;
// this regex tests if there is a tag followed by some optional whitespace and some text after that
else if (/>\s*[^\s<]/i.test(_blankVal) || INLINETAGS_NONBLANK.test(_blankVal)) return false;
else return true;
};
element.addClass('ta-bind');
var _undoKeyupTimeout;
scope['$undoManager' + (attrs.id || '')] = ngModel.$undoManager = {
_stack: [],
_index: 0,
_max: 1000,
push: function(value){
if((typeof value === "undefined" || value === null) ||
((typeof this.current() !== "undefined" && this.current() !== null) && value === this.current())) return value;
if(this._index < this._stack.length - 1){
this._stack = this._stack.slice(0,this._index+1);
}
this._stack.push(value);
if(_undoKeyupTimeout) $timeout.cancel(_undoKeyupTimeout);
if(this._stack.length > this._max) this._stack.shift();
this._index = this._stack.length - 1;
return value;
},
undo: function(){
return this.setToIndex(this._index-1);
},
redo: function(){
return this.setToIndex(this._index+1);
},
setToIndex: function(index){
if(index < 0 || index > this._stack.length - 1){
return undefined;
}
this._index = index;
return this.current();
},
current: function(){
return this._stack[this._index];
}
};
var _undo = scope['$undoTaBind' + (attrs.id || '')] = function(){
/* istanbul ignore else: can't really test it due to all changes being ignored as well in readonly */
if(!_isReadonly && _isContentEditable){
var content = ngModel.$undoManager.undo();
if(typeof content !== "undefined" && content !== null){
_setInnerHTML(content);
_setViewValue(content, false);
/* istanbul ignore else: browser catch */
if(element[0].childNodes.length) taSelection.setSelectionToElementEnd(element[0].childNodes[element[0].childNodes.length-1]);
else taSelection.setSelectionToElementEnd(element[0]);
}
}
};
var _redo = scope['$redoTaBind' + (attrs.id || '')] = function(){
/* istanbul ignore else: can't really test it due to all changes being ignored as well in readonly */
if(!_isReadonly && _isContentEditable){
var content = ngModel.$undoManager.redo();
if(typeof content !== "undefined" && content !== null){
_setInnerHTML(content);
_setViewValue(content, false);
/* istanbul ignore else: browser catch */
if(element[0].childNodes.length) taSelection.setSelectionToElementEnd(element[0].childNodes[element[0].childNodes.length-1]);
else taSelection.setSelectionToElementEnd(element[0]);
}
}
};
// in here we are undoing the converts used elsewhere to prevent the < > and & being displayed when they shouldn't in the code.
var _compileHtml = function(){
if(_isContentEditable) return element[0].innerHTML;
if(_isInputFriendly) return element.val();
throw ('textAngular Error: attempting to update non-editable taBind');
};
var _setViewValue = function(_val, triggerUndo){
if(typeof triggerUndo === "undefined" || triggerUndo === null) triggerUndo = true && _isContentEditable; // if not contentEditable then the native undo/redo is fine
if(typeof _val === "undefined" || _val === null) _val = _compileHtml();
if(_blankTest(_val)){
// this avoids us from tripping the ng-pristine flag if we click in and out with out typing
if(ngModel.$viewValue !== '') ngModel.$setViewValue('');
if(triggerUndo && ngModel.$undoManager.current() !== '') ngModel.$undoManager.push('');
}else{
_reApplyOnSelectorHandlers();
if(ngModel.$viewValue !== _val){
ngModel.$setViewValue(_val);
if(triggerUndo) ngModel.$undoManager.push(_val);
}
}
};
//used for updating when inserting wrapped elements
scope['updateTaBind' + (attrs.id || '')] = function(){
if(!_isReadonly) _setViewValue();
};
//this code is used to update the models when data is entered/deleted
if(_isInputFriendly){
if(!_isContentEditable){
// if a textarea or input just add in change and blur handlers, everything else is done by angulars input directive
element.on('change blur', function(){
if(!_isReadonly) ngModel.$setViewValue(_compileHtml());
});
}else{
// all the code specific to contenteditable divs
var waitforpastedata = function(savedcontent, _savedSelection, cb) {
if (element[0].childNodes && element[0].childNodes.length > 0) {
cb(savedcontent, _savedSelection);
} else {
that = {
s: savedcontent,
_: _savedSelection,
cb: cb
};
that.callself = function () {
waitforpastedata(that.s, that._, that.cb);
};
setTimeout(that.callself, 5);
}
};
var _processingPaste = false;
/* istanbul ignore next: phantom js cannot test this for some reason */
var processpaste = function(savedcontent, _savedSelection) {
text = element[0].innerHTML;
element[0].innerHTML = savedcontent;
// restore selection
$window.rangy.restoreSelection(_savedSelection);
/* istanbul ignore else: don't care if nothing pasted */
if(text.trim().length){
// test paste from word/microsoft product
if(text.match(/class=["']*Mso(Normal|List)/i)){
var textFragment = text.match(/<!--StartFragment-->([\s\S]*?)<!--EndFragment-->/i);
if(!textFragment) textFragment = text;
else textFragment = textFragment[1];
textFragment = textFragment.replace(/<o:p>[\s\S]*?<\/o:p>/ig, '').replace(/class=(["']|)MsoNormal(["']|)/ig, '');
var dom = angular.element("<div>" + textFragment + "</div>");
var targetDom = angular.element("<div></div>");
var _list = {
element: null,
lastIndent: [],
lastLi: null,
isUl: false
};
_list.lastIndent.peek = function(){
var n = this.length;
if (n>0) return this[n-1];
};
var _resetList = function(isUl){
_list.isUl = isUl;
_list.element = angular.element(isUl ? "<ul>" : "<ol>");
_list.lastIndent = [];
_list.lastIndent.peek = function(){
var n = this.length;
if (n>0) return this[n-1];
};
_list.lastLevelMatch = null;
};
for(var i = 0; i <= dom[0].childNodes.length; i++){
if(!dom[0].childNodes[i] || dom[0].childNodes[i].nodeName === "#text" || dom[0].childNodes[i].tagName.toLowerCase() !== "p") continue;
var el = angular.element(dom[0].childNodes[i]);
var _listMatch = (el.attr('class') || '').match(/MsoList(Bullet|Number|Paragraph)(CxSp(First|Middle|Last)|)/i);
if(_listMatch){
if(el[0].childNodes.length < 2 || el[0].childNodes[1].childNodes.length < 1){
continue;
}
var isUl = _listMatch[1].toLowerCase() === "bullet" || (_listMatch[1].toLowerCase() !== "number" && !(/^[^0-9a-z<]*[0-9a-z]+[^0-9a-z<>]</i.test(el[0].childNodes[1].innerHTML) || /^[^0-9a-z<]*[0-9a-z]+[^0-9a-z<>]</i.test(el[0].childNodes[1].childNodes[0].innerHTML)));
var _indentMatch = (el.attr('style') || '').match(/margin-left:([\-\.0-9]*)/i);
var indent = parseFloat((_indentMatch)?_indentMatch[1]:0);
var _levelMatch = (el.attr('style') || '').match(/mso-list:l([0-9]+) level([0-9]+) lfo[0-9+]($|;)/i);
// prefers the mso-list syntax
if(_levelMatch && _levelMatch[2]) indent = parseInt(_levelMatch[2]);
if ((_levelMatch && (!_list.lastLevelMatch || _levelMatch[1] !== _list.lastLevelMatch[1])) || !_listMatch[3] || _listMatch[3].toLowerCase() === "first" || (_list.lastIndent.peek() === null) || (_list.isUl !== isUl && _list.lastIndent.peek() === indent)) {
_resetList(isUl);
targetDom.append(_list.element);
} else if (_list.lastIndent.peek() != null && _list.lastIndent.peek() < indent){
_list.element = angular.element(isUl ? "<ul>" : "<ol>");
_list.lastLi.append(_list.element);
} else if (_list.lastIndent.peek() != null && _list.lastIndent.peek() > indent){
while(_list.lastIndent.peek() != null && _list.lastIndent.peek() > indent){
if(_list.element.parent()[0].tagName.toLowerCase() === 'li'){
_list.element = _list.element.parent();
continue;
}else if(/[uo]l/i.test(_list.element.parent()[0].tagName.toLowerCase())){
_list.element = _list.element.parent();
}else{ // else it's it should be a sibling
break;
}
_list.lastIndent.pop();
}
_list.isUl = _list.element[0].tagName.toLowerCase() === "ul";
if (isUl !== _list.isUl) {
_resetList(isUl);
targetDom.append(_list.element);
}
}
_list.lastLevelMatch = _levelMatch;
if(indent !== _list.lastIndent.peek()) _list.lastIndent.push(indent);
_list.lastLi = angular.element("<li>");
_list.element.append(_list.lastLi);
_list.lastLi.html(el.html().replace(/<!(--|)\[if !supportLists\](--|)>[\s\S]*?<!(--|)\[endif\](--|)>/ig, ''));
el.remove();
}else{
_resetList(false);
targetDom.append(el);
}
}
var _unwrapElement = function(node){
node = angular.element(node);
for(var _n = node[0].childNodes.length - 1; _n >= 0; _n--) node.after(node[0].childNodes[_n]);
node.remove();
};
angular.forEach(targetDom.find('span'), function(node){
node.removeAttribute('lang');
if(node.attributes.length <= 0) _unwrapElement(node);
});
angular.forEach(targetDom.find('font'), _unwrapElement);
text = targetDom.html();
}else{
// remove unnecessary chrome insert
text = text.replace(/<(|\/)meta[^>]*?>/ig, '');
if(text.match(/<[^>]*?(ta-bind)[^>]*?>/)){
// entire text-angular or ta-bind has been pasted, REMOVE AT ONCE!!
if(text.match(/<[^>]*?(text-angular)[^>]*?>/)){
var _el = angular.element("<div>" + text + "</div>");
_el.find('textarea').remove();
var binds = getByAttribute(_el, 'ta-bind');
for(var _b = 0; _b < binds.length; _b++){
var _target = binds[_b][0].parentNode.parentNode;
for(var _c = 0; _c < binds[_b][0].childNodes.length; _c++){
_target.parentNode.insertBefore(binds[_b][0].childNodes[_c], _target);
}
_target.parentNode.removeChild(_target);
}
text = _el.html().replace('<br class="Apple-interchange-newline">', '');
}
}else if(text.match(/^<span/)){
// in case of pasting only a span - chrome paste, remove them. THis is just some wierd formatting
text = text.replace(/<(|\/)span[^>]*?>/ig, '');
}
text = text.replace(/<br class="Apple-interchange-newline"[^>]*?>/ig, '');
}
text = taSanitize(text, '', _disableSanitizer);
taSelection.insertHtml(text, element[0]);
$timeout(function(){
ngModel.$setViewValue(_compileHtml());
_processingPaste = false;
element.removeClass('processing-paste');
}, 0);
}else{
_processingPaste = false;
element.removeClass('processing-paste');
}
};
element.on('paste', function(e, eventData){
/* istanbul ignore else: this is for catching the jqLite testing*/
if(eventData) angular.extend(e, eventData);
if(_isReadonly || _processingPaste){
e.stopPropagation();
e.preventDefault();
return false;
}
// Code adapted from http://stackoverflow.com/questions/2176861/javascript-get-clipboard-data-on-paste-event-cross-browser/6804718#6804718
var _savedSelection = $window.rangy.saveSelection();
_processingPaste = true;
element.addClass('processing-paste');
var savedcontent = element[0].innerHTML;
var clipboardData = (e.originalEvent || e).clipboardData;
if (clipboardData && clipboardData.getData) {// Webkit - get data from clipboard, put into editdiv, cleanup, then cancel event
var _types = "";
for(var _t = 0; _t < clipboardData.types.length; _t++){
_types += " " + clipboardData.types[_t];
}
/* istanbul ignore next: browser tests */
if (/text\/html/i.test(_types)) {
element[0].innerHTML = clipboardData.getData('text/html');
} else if (/text\/plain/i.test(_types)) {
element[0].innerHTML = clipboardData.getData('text/plain');
} else {
element[0].innerHTML = "";
}
waitforpastedata(savedcontent, _savedSelection, processpaste);
e.stopPropagation();
e.preventDefault();
return false;
} else {// Everything else - empty editdiv and allow browser to paste content into it, then cleanup
element[0].innerHTML = "";
waitforpastedata(savedcontent, _savedSelection, processpaste);
return true;
}
});
element.on('cut', function(e){
// timeout to next is needed as otherwise the paste/cut event has not finished actually changing the display
if(!_isReadonly) $timeout(function(){
ngModel.$setViewValue(_compileHtml());
}, 0);
else e.preventDefault();
});
element.on('keydown', function(event, eventData){
/* istanbul ignore else: this is for catching the jqLite testing*/
if(eventData) angular.extend(event, eventData);
/* istanbul ignore else: readonly check */
if(!_isReadonly){
if(event.metaKey || event.ctrlKey){
// covers ctrl/command + z
if((event.keyCode === 90 && !event.shiftKey)){
_undo();
event.preventDefault();
// covers ctrl + y, command + shift + z
}else if((event.keyCode === 90 && event.shiftKey) || (event.keyCode === 89 && !event.shiftKey)){
_redo();
event.preventDefault();
}
/* istanbul ignore next: difficult to test as can't seem to select */
}else if(event.keyCode === 13 && !event.shiftKey){
var selection = taSelection.getSelectionElement();
if(!selection.tagName.match(VALIDELEMENTS)) return;
var _new = angular.element(_defaultVal);
if (/^<br(|\/)>$/i.test(selection.innerHTML.trim()) && selection.parentNode.tagName.toLowerCase() === 'blockquote' && !selection.nextSibling) {
// if last element in blockquote and element is blank, pull element outside of blockquote.
$selection = angular.element(selection);
var _parent = $selection.parent();
_parent.after(_new);
$selection.remove();
if(_parent.children().length === 0) _parent.remove();
taSelection.setSelectionToElementStart(_new[0]);
event.preventDefault();
}else if (/^<[^>]+><br(|\/)><\/[^>]+>$/i.test(selection.innerHTML.trim()) && selection.tagName.toLowerCase() === 'blockquote'){
$selection = angular.element(selection);
$selection.after(_new);
$selection.remove();
taSelection.setSelectionToElementStart(_new[0]);
event.preventDefault();
}
}
}
});
element.on('keyup', function(event, eventData){
/* istanbul ignore else: this is for catching the jqLite testing*/
if(eventData) angular.extend(event, eventData);
if(_undoKeyupTimeout) $timeout.cancel(_undoKeyupTimeout);
if(!_isReadonly && !BLOCKED_KEYS.test(event.keyCode)){
// if enter - insert new taDefaultWrap, if shift+enter insert <br/>
if(_defaultVal !== '' && event.keyCode === 13){
if(!event.shiftKey){
// new paragraph, br should be caught correctly
var selection = taSelection.getSelectionElement();
while(!selection.tagName.match(VALIDELEMENTS) && selection !== element[0]){
selection = selection.parentNode;
}
if(selection.tagName.toLowerCase() !== attrs.taDefaultWrap && selection.tagName.toLowerCase() !== 'li' && (selection.innerHTML.trim() === '' || selection.innerHTML.trim() === '<br>')){
var _new = angular.element(_defaultVal);
angular.element(selection).replaceWith(_new);
taSelection.setSelectionToElementStart(_new[0]);
}
}
}
var val = _compileHtml();
if(_defaultVal !== '' && val.trim() === ''){
_setInnerHTML(_defaultVal);
taSelection.setSelectionToElementStart(element.children()[0]);
}
var triggerUndo = _lastKey !== event.keyCode && UNDO_TRIGGER_KEYS.test(event.keyCode);
_setViewValue(val, triggerUndo);
if(!triggerUndo) _undoKeyupTimeout = $timeout(function(){ ngModel.$undoManager.push(val); }, 250);
_lastKey = event.keyCode;
}
});
element.on('blur', function(){
_focussed = false;
/* istanbul ignore else: if readonly don't update model */
if(!_isReadonly){
_setViewValue();
}
ngModel.$render();
});
// Placeholders not supported on ie 8 and below
if(attrs.placeholder && (_browserDetect.ie > 8 || _browserDetect.ie === undefined)){
var ruleIndex;
if(attrs.id) ruleIndex = addCSSRule('#' + attrs.id + '.placeholder-text:before', 'content: "' + attrs.placeholder + '"');
else throw('textAngular Error: An unique ID is required for placeholders to work');
scope.$on('$destroy', function(){
removeCSSRule(ruleIndex);
});
}
element.on('focus', function(){
_focussed = true;
ngModel.$render();
});
element.on('mouseup', function(){
var _selection = taSelection.getSelection();
if(_selection.start.element === element[0]) taSelection.setSelectionToElementStart(element.children()[0]);
});
// prevent propagation on mousedown in editor, see #206
element.on('mousedown', function(event, eventData){
/* istanbul ignore else: this is for catching the jqLite testing*/
if(eventData) angular.extend(event, eventData);
event.stopPropagation();
});
}
}
// catch DOM XSS via taSanitize
// Sanitizing both ways is identical
var _sanitize = function(unsafe){
return (ngModel.$oldViewValue = taSanitize(taFixChrome(unsafe), ngModel.$oldViewValue, _disableSanitizer));
};
// trigger the validation calls
var _validity = function(value){
if(attrs.required) ngModel.$setValidity('required', !_blankTest(value));
return value;
};
// parsers trigger from the above keyup function or any other time that the viewValue is updated and parses it for storage in the ngModel
ngModel.$parsers.push(_sanitize);
ngModel.$parsers.push(_validity);
// because textAngular is bi-directional (which is awesome) we need to also sanitize values going in from the server
ngModel.$formatters.push(_sanitize);
ngModel.$formatters.push(function(value){
if(_blankTest(value)) return value;
var domTest = angular.element("<div>" + value + "</div>");
if(domTest.children().length === 0){
value = "<" + attrs.taDefaultWrap + ">" + value + "</" + attrs.taDefaultWrap + ">";
}
return value;
});
ngModel.$formatters.push(_validity);
ngModel.$formatters.push(function(value){
return ngModel.$undoManager.push(value || '');
});
var selectorClickHandler = function(event){
// emit the element-select event, pass the element
scope.$emit('ta-element-select', this);
event.preventDefault();
return false;
};
var fileDropHandler = function(event, eventData){
/* istanbul ignore else: this is for catching the jqLite testing*/
if(eventData) angular.extend(event, eventData);
// emit the drop event, pass the element, preventing should be done elsewhere
if(!dropFired && !_isReadonly){
dropFired = true;
var dataTransfer;
if(event.originalEvent) dataTransfer = event.originalEvent.dataTransfer;
else dataTransfer = event.dataTransfer;
scope.$emit('ta-drop-event', this, event, dataTransfer);
$timeout(function(){
dropFired = false;
_setViewValue();
}, 100);
}
};
//used for updating when inserting wrapped elements
var _reApplyOnSelectorHandlers = scope['reApplyOnSelectorHandlers' + (attrs.id || '')] = function(){
/* istanbul ignore else */
if(!_isReadonly) angular.forEach(taSelectableElements, function(selector){
// check we don't apply the handler twice
element.find(selector)
.off('click', selectorClickHandler)
.on('click', selectorClickHandler);
});
};
var _setInnerHTML = function(newval){
element[0].innerHTML = newval;
};
// changes to the model variable from outside the html/text inputs
ngModel.$render = function(){
// catch model being null or undefined
var val = ngModel.$viewValue || '';
// if the editor isn't focused it needs to be updated, otherwise it's receiving user input
if($document[0].activeElement !== element[0]){
// Not focussed
if(_isContentEditable){
// WYSIWYG Mode
if(attrs.placeholder){
if(val === ''){
// blank
if(_focussed) element.removeClass('placeholder-text');
else element.addClass('placeholder-text');
_setInnerHTML(_defaultVal);
}else{
// not-blank
element.removeClass('placeholder-text');
_setInnerHTML(val);
}
}else{
_setInnerHTML((val === '') ? _defaultVal : val);
}
// if in WYSIWYG and readOnly we kill the use of links by clicking
if(!_isReadonly){
_reApplyOnSelectorHandlers();
element.on('drop', fileDropHandler);
}else{
element.off('drop', fileDropHandler);
}
}else if(element[0].tagName.toLowerCase() !== 'textarea' && element[0].tagName.toLowerCase() !== 'input'){
// make sure the end user can SEE the html code as a display. This is a read-only display element
_setInnerHTML(taApplyCustomRenderers(val));
}else{
// only for input and textarea inputs
element.val(val);
}
}else{
/* istanbul ignore else: in other cases we don't care */
if(_isContentEditable){
// element is focussed, test for placeholder
element.removeClass('placeholder-text');
}
}
};
if(attrs.taReadonly){
//set initial value
_isReadonly = scope.$eval(attrs.taReadonly);
if(_isReadonly){
element.addClass('ta-readonly');
// we changed to readOnly mode (taReadonly='true')
if(element[0].tagName.toLowerCase() === 'textarea' || element[0].tagName.toLowerCase() === 'input'){
element.attr('disabled', 'disabled');
}
if(element.attr('contenteditable') !== undefined && element.attr('contenteditable')){
element.removeAttr('contenteditable');
}
}else{
element.removeClass('ta-readonly');
// we changed to NOT readOnly mode (taReadonly='false')
if(element[0].tagName.toLowerCase() === 'textarea' || element[0].tagName.toLowerCase() === 'input'){
element.removeAttr('disabled');
}else if(_isContentEditable){
element.attr('contenteditable', 'true');
}
}
// taReadonly only has an effect if the taBind element is an input or textarea or has contenteditable='true' on it.
// Otherwise it is readonly by default
scope.$watch(attrs.taReadonly, function(newVal, oldVal){
if(oldVal === newVal) return;
if(newVal){
element.addClass('ta-readonly');
// we changed to readOnly mode (taReadonly='true')
if(element[0].tagName.toLowerCase() === 'textarea' || element[0].tagName.toLowerCase() === 'input'){
element.attr('disabled', 'disabled');
}
if(element.attr('contenteditable') !== undefined && element.attr('contenteditable')){
element.removeAttr('contenteditable');
}
// turn ON selector click handlers
angular.forEach(taSelectableElements, function(selector){
element.find(selector).on('click', selectorClickHandler);
});
element.off('drop', fileDropHandler);
}else{
element.removeClass('ta-readonly');
// we changed to NOT readOnly mode (taReadonly='false')
if(element[0].tagName.toLowerCase() === 'textarea' || element[0].tagName.toLowerCase() === 'input'){
element.removeAttr('disabled');
}else if(_isContentEditable){
element.attr('contenteditable', 'true');
}
// remove the selector click handlers
angular.forEach(taSelectableElements, function(selector){
element.find(selector).off('click', selectorClickHandler);
});
element.on('drop', fileDropHandler);
}
_isReadonly = newVal;
});
}
// Initialise the selectableElements
// if in WYSIWYG and readOnly we kill the use of links by clicking
if(_isContentEditable && !_isReadonly){
angular.forEach(taSelectableElements, function(selector){
element.find(selector).on('click', selectorClickHandler);
});
element.on('drop', fileDropHandler);
element.on('blur', function(){
/* istanbul ignore next: webkit fix */
if(_browserDetect.webkit) { // detect webkit
globalContentEditableBlur = true;
}
});
}
}
};
}]);
// this global var is used to prevent multiple fires of the drop event. Needs to be global to the textAngular file.
var dropFired = false;
var textAngular = angular.module("textAngular", ['ngSanitize', 'textAngularSetup', 'textAngular.factories', 'textAngular.DOM', 'textAngular.validators', 'textAngular.taBind']); //This makes ngSanitize required
// setup the global contstant functions for setting up the toolbar
// all tool definitions
var taTools = {};
/*
A tool definition is an object with the following key/value parameters:
action: [function(deferred, restoreSelection)]
a function that is executed on clicking on the button - this will allways be executed using ng-click and will
overwrite any ng-click value in the display attribute.
The function is passed a deferred object ($q.defer()), if this is wanted to be used `return false;` from the action and
manually call `deferred.resolve();` elsewhere to notify the editor that the action has finished.
restoreSelection is only defined if the rangy library is included and it can be called as `restoreSelection()` to restore the users
selection in the WYSIWYG editor.
display: [string]?
Optional, an HTML element to be displayed as the button. The `scope` of the button is the tool definition object with some additional functions
If set this will cause buttontext and iconclass to be ignored
class: [string]?
Optional, if set will override the taOptions.classes.toolbarButton class.
buttontext: [string]?
if this is defined it will replace the contents of the element contained in the `display` element
iconclass: [string]?
if this is defined an icon (<i>) will be appended to the `display` element with this string as it's class
tooltiptext: [string]?
Optional, a plain text description of the action, used for the title attribute of the action button in the toolbar by default.
activestate: [function(commonElement)]?
this function is called on every caret movement, if it returns true then the class taOptions.classes.toolbarButtonActive
will be applied to the `display` element, else the class will be removed
disabled: [function()]?
if this function returns true then the tool will have the class taOptions.classes.disabled applied to it, else it will be removed
Other functions available on the scope are:
name: [string]
the name of the tool, this is the first parameter passed into taRegisterTool
isDisabled: [function()]
returns true if the tool is disabled, false if it isn't
displayActiveToolClass: [function(boolean)]
returns true if the tool is 'active' in the currently focussed toolbar
onElementSelect: [Object]
This object contains the following key/value pairs and is used to trigger the ta-element-select event
element: [String]
an element name, will only trigger the onElementSelect action if the tagName of the element matches this string
filter: [function(element)]?
an optional filter that returns a boolean, if true it will trigger the onElementSelect.
action: [function(event, element, editorScope)]
the action that should be executed if the onElementSelect function runs
*/
// name and toolDefinition to add into the tools available to be added on the toolbar
function registerTextAngularTool(name, toolDefinition){
if(!name || name === '' || taTools.hasOwnProperty(name)) throw('textAngular Error: A unique name is required for a Tool Definition');
if(
(toolDefinition.display && (toolDefinition.display === '' || !validElementString(toolDefinition.display))) ||
(!toolDefinition.display && !toolDefinition.buttontext && !toolDefinition.iconclass)
)
throw('textAngular Error: Tool Definition for "' + name + '" does not have a valid display/iconclass/buttontext value');
taTools[name] = toolDefinition;
}
textAngular.constant('taRegisterTool', registerTextAngularTool);
textAngular.value('taTools', taTools);
textAngular.config([function(){
// clear taTools variable. Just catches testing and any other time that this config may run multiple times...
angular.forEach(taTools, function(value, key){ delete taTools[key]; });
}]);
textAngular.run([function(){
/* istanbul ignore next: not sure how to test this */
// Require Rangy and rangy savedSelection module.
if(!window.rangy){
throw("rangy-core.js and rangy-selectionsaverestore.js are required for textAngular to work correctly, rangy-core is not yet loaded.");
}else{
window.rangy.init();
if(!window.rangy.saveSelection){
throw("rangy-selectionsaverestore.js is required for textAngular to work correctly.");
}
}
}]);
textAngular.directive("textAngular", [
'$compile', '$timeout', 'taOptions', 'taSelection', 'taExecCommand', 'textAngularManager', '$window', '$document', '$animate', '$log', '$q',
function($compile, $timeout, taOptions, taSelection, taExecCommand, textAngularManager, $window, $document, $animate, $log, $q){
return {
require: '?ngModel',
scope: {},
restrict: "EA",
link: function(scope, element, attrs, ngModel){
// all these vars should not be accessable outside this directive
var _keydown, _keyup, _keypress, _mouseup, _focusin, _focusout,
_originalContents, _toolbars,
_serial = (attrs.serial) ? attrs.serial : Math.floor(Math.random() * 10000000000000000),
_taExecCommand;
scope._name = (attrs.name) ? attrs.name : 'textAngularEditor' + _serial;
var oneEvent = function(_element, event, action){
$timeout(function(){
// shim the .one till fixed
var _func = function(){
_element.off(event, _func);
action.apply(this, arguments);
};
_element.on(event, _func);
}, 100);
};
_taExecCommand = taExecCommand(attrs.taDefaultWrap);
// get the settings from the defaults and add our specific functions that need to be on the scope
angular.extend(scope, angular.copy(taOptions), {
// wraps the selection in the provided tag / execCommand function. Should only be called in WYSIWYG mode.
wrapSelection: function(command, opt, isSelectableElementTool){
if(command.toLowerCase() === "undo"){
scope['$undoTaBindtaTextElement' + _serial]();
}else if(command.toLowerCase() === "redo"){
scope['$redoTaBindtaTextElement' + _serial]();
}else{
// catch errors like FF erroring when you try to force an undo with nothing done
_taExecCommand(command, false, opt);
if(isSelectableElementTool){
// re-apply the selectable tool events
scope['reApplyOnSelectorHandlerstaTextElement' + _serial]();
}
// refocus on the shown display element, this fixes a display bug when using :focus styles to outline the box.
// You still have focus on the text/html input it just doesn't show up
scope.displayElements.text[0].focus();
}
},
showHtml: scope.$eval(attrs.taShowHtml) || false
});
// setup the options from the optional attributes
if(attrs.taFocussedClass) scope.classes.focussed = attrs.taFocussedClass;
if(attrs.taTextEditorClass) scope.classes.textEditor = attrs.taTextEditorClass;
if(attrs.taHtmlEditorClass) scope.classes.htmlEditor = attrs.taHtmlEditorClass;
// optional setup functions
if(attrs.taTextEditorSetup) scope.setup.textEditorSetup = scope.$parent.$eval(attrs.taTextEditorSetup);
if(attrs.taHtmlEditorSetup) scope.setup.htmlEditorSetup = scope.$parent.$eval(attrs.taHtmlEditorSetup);
// optional fileDropHandler function
if(attrs.taFileDrop) scope.fileDropHandler = scope.$parent.$eval(attrs.taFileDrop);
else scope.fileDropHandler = scope.defaultFileDropHandler;
_originalContents = element[0].innerHTML;
// clear the original content
element[0].innerHTML = '';
// Setup the HTML elements as variable references for use later
scope.displayElements = {
// we still need the hidden input even with a textarea as the textarea may have invalid/old input in it,
// wheras the input will ALLWAYS have the correct value.
forminput: angular.element("<input type='hidden' tabindex='-1' style='display: none;'>"),
html: angular.element("<textarea></textarea>"),
text: angular.element("<div></div>"),
// other toolbased elements
scrollWindow: angular.element("<div class='ta-scroll-window'></div>"),
popover: angular.element('<div class="popover fade bottom" style="max-width: none; width: 305px;"></div>'),
popoverArrow: angular.element('<div class="arrow"></div>'),
popoverContainer: angular.element('<div class="popover-content"></div>'),
resize: {
overlay: angular.element('<div class="ta-resizer-handle-overlay"></div>'),
background: angular.element('<div class="ta-resizer-handle-background"></div>'),
anchors: [
angular.element('<div class="ta-resizer-handle-corner ta-resizer-handle-corner-tl"></div>'),
angular.element('<div class="ta-resizer-handle-corner ta-resizer-handle-corner-tr"></div>'),
angular.element('<div class="ta-resizer-handle-corner ta-resizer-handle-corner-bl"></div>'),
angular.element('<div class="ta-resizer-handle-corner ta-resizer-handle-corner-br"></div>')
],
info: angular.element('<div class="ta-resizer-handle-info"></div>')
}
};
// Setup the popover
scope.displayElements.popover.append(scope.displayElements.popoverArrow);
scope.displayElements.popover.append(scope.displayElements.popoverContainer);
scope.displayElements.scrollWindow.append(scope.displayElements.popover);
scope.displayElements.popover.on('mousedown', function(e, eventData){
/* istanbul ignore else: this is for catching the jqLite testing*/
if(eventData) angular.extend(e, eventData);
// this prevents focusout from firing on the editor when clicking anything in the popover
e.preventDefault();
return false;
});
// define the popover show and hide functions
scope.showPopover = function(_el){
scope.displayElements.popover.css('display', 'block');
scope.reflowPopover(_el);
$animate.addClass(scope.displayElements.popover, 'in');
oneEvent($document.find('body'), 'click keyup', function(){scope.hidePopover();});
};
scope.reflowPopover = function(_el){
/* istanbul ignore if: catches only if near bottom of editor */
if(scope.displayElements.text[0].offsetHeight - 51 > _el[0].offsetTop){
scope.displayElements.popover.css('top', _el[0].offsetTop + _el[0].offsetHeight + 'px');
scope.displayElements.popover.removeClass('top').addClass('bottom');
}else{
scope.displayElements.popover.css('top', _el[0].offsetTop - 54 + 'px');
scope.displayElements.popover.removeClass('bottom').addClass('top');
}
var _maxLeft = scope.displayElements.text[0].offsetWidth - scope.displayElements.popover[0].offsetWidth;
var _targetLeft = _el[0].offsetLeft + (_el[0].offsetWidth / 2.0) - (scope.displayElements.popover[0].offsetWidth / 2.0);
scope.displayElements.popover.css('left', Math.max(0, Math.min(_maxLeft, _targetLeft)) + 'px');
scope.displayElements.popoverArrow.css('margin-left', (Math.min(_targetLeft, (Math.max(0, _targetLeft - _maxLeft))) - 11) + 'px');
};
scope.hidePopover = function(){
/* istanbul ignore next: dosen't test with mocked animate */
var doneCb = function(){
scope.displayElements.popover.css('display', '');
scope.displayElements.popoverContainer.attr('style', '');
scope.displayElements.popoverContainer.attr('class', 'popover-content');
};
$q.when($animate.removeClass(scope.displayElements.popover, 'in', doneCb)).then(doneCb);
};
// setup the resize overlay
scope.displayElements.resize.overlay.append(scope.displayElements.resize.background);
angular.forEach(scope.displayElements.resize.anchors, function(anchor){ scope.displayElements.resize.overlay.append(anchor);});
scope.displayElements.resize.overlay.append(scope.displayElements.resize.info);
scope.displayElements.scrollWindow.append(scope.displayElements.resize.overlay);
// define the show and hide events
scope.reflowResizeOverlay = function(_el){
_el = angular.element(_el)[0];
scope.displayElements.resize.overlay.css({
'display': 'block',
'left': _el.offsetLeft - 5 + 'px',
'top': _el.offsetTop - 5 + 'px',
'width': _el.offsetWidth + 10 + 'px',
'height': _el.offsetHeight + 10 + 'px'
});
scope.displayElements.resize.info.text(_el.offsetWidth + ' x ' + _el.offsetHeight);
};
/* istanbul ignore next: pretty sure phantomjs won't test this */
scope.showResizeOverlay = function(_el){
var resizeMouseDown = function(event){
var startPosition = {
width: parseInt(_el.attr('width')),
height: parseInt(_el.attr('height')),
x: event.clientX,
y: event.clientY
};
if(startPosition.width === undefined) startPosition.width = _el[0].offsetWidth;
if(startPosition.height === undefined) startPosition.height = _el[0].offsetHeight;
scope.hidePopover();
var ratio = startPosition.height / startPosition.width;
var mousemove = function(event){
// calculate new size
var pos = {
x: Math.max(0, startPosition.width + (event.clientX - startPosition.x)),
y: Math.max(0, startPosition.height + (event.clientY - startPosition.y))
};
if(event.shiftKey){
// keep ratio
var newRatio = pos.y / pos.x;
pos.x = ratio > newRatio ? pos.x : pos.y / ratio;
pos.y = ratio > newRatio ? pos.x * ratio : pos.y;
}
el = angular.element(_el);
el.attr('height', Math.max(0, pos.y));
el.attr('width', Math.max(0, pos.x));
// reflow the popover tooltip
scope.reflowResizeOverlay(_el);
};
$document.find('body').on('mousemove', mousemove);
oneEvent($document.find('body'), 'mouseup', function(event){
event.preventDefault();
event.stopPropagation();
$document.find('body').off('mousemove', mousemove);
scope.showPopover(_el);
});
event.stopPropagation();
event.preventDefault();
};
scope.displayElements.resize.anchors[3].on('mousedown', resizeMouseDown);
scope.reflowResizeOverlay(_el);
oneEvent($document.find('body'), 'click', function(){scope.hideResizeOverlay();});
};
/* istanbul ignore next: pretty sure phantomjs won't test this */
scope.hideResizeOverlay = function(){
scope.displayElements.resize.overlay.css('display', '');
};
// allow for insertion of custom directives on the textarea and div
scope.setup.htmlEditorSetup(scope.displayElements.html);
scope.setup.textEditorSetup(scope.displayElements.text);
scope.displayElements.html.attr({
'id': 'taHtmlElement' + _serial,
'ng-show': 'showHtml',
'ta-bind': 'ta-bind',
'ng-model': 'html'
});
scope.displayElements.text.attr({
'id': 'taTextElement' + _serial,
'contentEditable': 'true',
'ta-bind': 'ta-bind',
'ng-model': 'html'
});
scope.displayElements.scrollWindow.attr({'ng-hide': 'showHtml'});
if(attrs.taDefaultWrap) scope.displayElements.text.attr('ta-default-wrap', attrs.taDefaultWrap);
if(attrs.taUnsafeSanitizer){
scope.displayElements.text.attr('ta-unsafe-sanitizer', attrs.taUnsafeSanitizer);
scope.displayElements.html.attr('ta-unsafe-sanitizer', attrs.taUnsafeSanitizer);
}
// add the main elements to the origional element
scope.displayElements.scrollWindow.append(scope.displayElements.text);
element.append(scope.displayElements.scrollWindow);
element.append(scope.displayElements.html);
scope.displayElements.forminput.attr('name', scope._name);
element.append(scope.displayElements.forminput);
if(attrs.tabindex){
element.removeAttr('tabindex');
scope.displayElements.text.attr('tabindex', attrs.tabindex);
scope.displayElements.html.attr('tabindex', attrs.tabindex);
}
if (attrs.placeholder) {
scope.displayElements.text.attr('placeholder', attrs.placeholder);
scope.displayElements.html.attr('placeholder', attrs.placeholder);
}
if(attrs.taDisabled){
scope.displayElements.text.attr('ta-readonly', 'disabled');
scope.displayElements.html.attr('ta-readonly', 'disabled');
scope.disabled = scope.$parent.$eval(attrs.taDisabled);
scope.$parent.$watch(attrs.taDisabled, function(newVal){
scope.disabled = newVal;
if(scope.disabled){
element.addClass(scope.classes.disabled);
}else{
element.removeClass(scope.classes.disabled);
}
});
}
// compile the scope with the text and html elements only - if we do this with the main element it causes a compile loop
$compile(scope.displayElements.scrollWindow)(scope);
$compile(scope.displayElements.html)(scope);
scope.updateTaBindtaTextElement = scope['updateTaBindtaTextElement' + _serial];
scope.updateTaBindtaHtmlElement = scope['updateTaBindtaHtmlElement' + _serial];
// add the classes manually last
element.addClass("ta-root");
scope.displayElements.scrollWindow.addClass("ta-text ta-editor " + scope.classes.textEditor);
scope.displayElements.html.addClass("ta-html ta-editor " + scope.classes.htmlEditor);
// used in the toolbar actions
scope._actionRunning = false;
var _savedSelection = false;
scope.startAction = function(){
scope._actionRunning = true;
// if rangy library is loaded return a function to reload the current selection
_savedSelection = $window.rangy.saveSelection();
return function(){
if(_savedSelection) $window.rangy.restoreSelection(_savedSelection);
};
};
scope.endAction = function(){
scope._actionRunning = false;
if(_savedSelection) $window.rangy.removeMarkers(_savedSelection);
_savedSelection = false;
scope.updateSelectedStyles();
// only update if in text or WYSIWYG mode
if(!scope.showHtml) scope['updateTaBindtaTextElement' + _serial]();
};
// note that focusout > focusin is called everytime we click a button - except bad support: http://www.quirksmode.org/dom/events/blurfocus.html
// cascades to displayElements.text and displayElements.html automatically.
_focusin = function(){
element.addClass(scope.classes.focussed);
_toolbars.focus();
};
scope.displayElements.html.on('focus', _focusin);
scope.displayElements.text.on('focus', _focusin);
_focusout = function(e){
// if we are NOT runnig an action and have NOT focussed again on the text etc then fire the blur events
if(!scope._actionRunning && $document[0].activeElement !== scope.displayElements.html[0] && $document[0].activeElement !== scope.displayElements.text[0]){
element.removeClass(scope.classes.focussed);
_toolbars.unfocus();
// to prevent multiple apply error defer to next seems to work.
$timeout(function(){ element.triggerHandler('blur'); }, 0);
}
e.preventDefault();
return false;
};
scope.displayElements.html.on('blur', _focusout);
scope.displayElements.text.on('blur', _focusout);
// Setup the default toolbar tools, this way allows the user to add new tools like plugins.
// This is on the editor for future proofing if we find a better way to do this.
scope.queryFormatBlockState = function(command){
// $document[0].queryCommandValue('formatBlock') errors in Firefox if we call this when focussed on the textarea
return !scope.showHtml && command.toLowerCase() === $document[0].queryCommandValue('formatBlock').toLowerCase();
};
scope.queryCommandState = function(command){
// $document[0].queryCommandValue('formatBlock') errors in Firefox if we call this when focussed on the textarea
return (!scope.showHtml) ? $document[0].queryCommandState(command) : '';
};
scope.switchView = function(){
scope.showHtml = !scope.showHtml;
$animate.enabled(false, scope.displayElements.html);
$animate.enabled(false, scope.displayElements.text);
//Show the HTML view
if(scope.showHtml){
//defer until the element is visible
$timeout(function(){
$animate.enabled(true, scope.displayElements.html);
$animate.enabled(true, scope.displayElements.text);
// [0] dereferences the DOM object from the angular.element
return scope.displayElements.html[0].focus();
}, 100);
}else{
//Show the WYSIWYG view
//defer until the element is visible
$timeout(function(){
$animate.enabled(true, scope.displayElements.html);
$animate.enabled(true, scope.displayElements.text);
// [0] dereferences the DOM object from the angular.element
return scope.displayElements.text[0].focus();
}, 100);
}
};
// changes to the model variable from outside the html/text inputs
// if no ngModel, then the only input is from inside text-angular
if(attrs.ngModel){
var _firstRun = true;
ngModel.$render = function(){
if(_firstRun){
// we need this firstRun to set the originalContents otherwise it gets overrided by the setting of ngModel to undefined from NaN
_firstRun = false;
// if view value is null or undefined initially and there was original content, set to the original content
var _initialValue = scope.$parent.$eval(attrs.ngModel);
if((_initialValue === undefined || _initialValue === null) && (_originalContents && _originalContents !== '')){
// on passing through to taBind it will be sanitised
ngModel.$setViewValue(_originalContents);
}
}
scope.displayElements.forminput.val(ngModel.$viewValue);
// if the editors aren't focused they need to be updated, otherwise they are doing the updating
/* istanbul ignore else: don't care */
if(!scope._elementSelectTriggered && $document[0].activeElement !== scope.displayElements.html[0] && $document[0].activeElement !== scope.displayElements.text[0]){
// catch model being null or undefined
scope.html = ngModel.$viewValue || '';
}
};
// trigger the validation calls
var _validity = function(value){
if(attrs.required) ngModel.$setValidity('required', !(!value || value.trim() === ''));
return value;
};
ngModel.$parsers.push(_validity);
ngModel.$formatters.push(_validity);
}else{
// if no ngModel then update from the contents of the origional html.
scope.displayElements.forminput.val(_originalContents);
scope.html = _originalContents;
}
// changes from taBind back up to here
scope.$watch('html', function(newValue, oldValue){
if(newValue !== oldValue){
if(attrs.ngModel && ngModel.$viewValue !== newValue) ngModel.$setViewValue(newValue);
scope.displayElements.forminput.val(newValue);
}
});
if(attrs.taTargetToolbars) _toolbars = textAngularManager.registerEditor(scope._name, scope, attrs.taTargetToolbars.split(','));
else{
var _toolbar = angular.element('<div text-angular-toolbar name="textAngularToolbar' + _serial + '">');
// passthrough init of toolbar options
if(attrs.taToolbar) _toolbar.attr('ta-toolbar', attrs.taToolbar);
if(attrs.taToolbarClass) _toolbar.attr('ta-toolbar-class', attrs.taToolbarClass);
if(attrs.taToolbarGroupClass) _toolbar.attr('ta-toolbar-group-class', attrs.taToolbarGroupClass);
if(attrs.taToolbarButtonClass) _toolbar.attr('ta-toolbar-button-class', attrs.taToolbarButtonClass);
if(attrs.taToolbarActiveButtonClass) _toolbar.attr('ta-toolbar-active-button-class', attrs.taToolbarActiveButtonClass);
if(attrs.taFocussedClass) _toolbar.attr('ta-focussed-class', attrs.taFocussedClass);
element.prepend(_toolbar);
$compile(_toolbar)(scope.$parent);
_toolbars = textAngularManager.registerEditor(scope._name, scope, ['textAngularToolbar' + _serial]);
}
scope.$on('$destroy', function(){
textAngularManager.unregisterEditor(scope._name);
});
// catch element select event and pass to toolbar tools
scope.$on('ta-element-select', function(event, element){
if(_toolbars.triggerElementSelect(event, element)){
scope['reApplyOnSelectorHandlerstaTextElement' + _serial]();
}
});
scope.$on('ta-drop-event', function(event, element, dropEvent, dataTransfer){
scope.displayElements.text[0].focus();
if(dataTransfer && dataTransfer.files && dataTransfer.files.length > 0){
angular.forEach(dataTransfer.files, function(file){
// taking advantage of boolean execution, if the fileDropHandler returns true, nothing else after it is executed
// If it is false then execute the defaultFileDropHandler if the fileDropHandler is NOT the default one
// Once one of these has been executed wrap the result as a promise, if undefined or variable update the taBind, else we should wait for the promise
try{
$q.when(scope.fileDropHandler(file, scope.wrapSelection) ||
(scope.fileDropHandler !== scope.defaultFileDropHandler &&
$q.when(scope.defaultFileDropHandler(file, scope.wrapSelection)))).then(function(){
scope['updateTaBindtaTextElement' + _serial]();
});
}catch(error){
$log.error(error);
}
});
dropEvent.preventDefault();
dropEvent.stopPropagation();
/* istanbul ignore else, the updates if moved text */
}else{
$timeout(function(){
scope['updateTaBindtaTextElement' + _serial]();
}, 0);
}
});
// the following is for applying the active states to the tools that support it
scope._bUpdateSelectedStyles = false;
// loop through all the tools polling their activeState function if it exists
scope.updateSelectedStyles = function(){
var _selection;
// test if the common element ISN'T the root ta-text node
if((_selection = taSelection.getSelectionElement()) !== undefined && _selection.parentNode !== scope.displayElements.text[0]){
_toolbars.updateSelectedStyles(angular.element(_selection));
}else _toolbars.updateSelectedStyles();
// used to update the active state when a key is held down, ie the left arrow
/* istanbul ignore else: browser only check */
if(scope._bUpdateSelectedStyles && $document.hasFocus()) $timeout(scope.updateSelectedStyles, 200);
else scope._bUpdateSelectedStyles = false;
};
// start updating on keydown
_keydown = function(){
/* istanbul ignore else: don't run if already running */
if(!scope._bUpdateSelectedStyles){
scope._bUpdateSelectedStyles = true;
scope.$apply(function(){
scope.updateSelectedStyles();
});
}
};
scope.displayElements.html.on('keydown', _keydown);
scope.displayElements.text.on('keydown', _keydown);
// stop updating on key up and update the display/model
_keyup = function(){
scope._bUpdateSelectedStyles = false;
};
scope.displayElements.html.on('keyup', _keyup);
scope.displayElements.text.on('keyup', _keyup);
// stop updating on key up and update the display/model
_keypress = function(event, eventData){
/* istanbul ignore else: this is for catching the jqLite testing*/
if(eventData) angular.extend(event, eventData);
scope.$apply(function(){
if(_toolbars.sendKeyCommand(event)){
/* istanbul ignore else: don't run if already running */
if(!scope._bUpdateSelectedStyles){
scope.updateSelectedStyles();
}
event.preventDefault();
return false;
}
});
};
scope.displayElements.html.on('keypress', _keypress);
scope.displayElements.text.on('keypress', _keypress);
// update the toolbar active states when we click somewhere in the text/html boxed
_mouseup = function(){
// ensure only one execution of updateSelectedStyles()
scope._bUpdateSelectedStyles = false;
scope.$apply(function(){
scope.updateSelectedStyles();
});
};
scope.displayElements.html.on('mouseup', _mouseup);
scope.displayElements.text.on('mouseup', _mouseup);
}
};
}
]);
textAngular.service('textAngularManager', ['taToolExecuteAction', 'taTools', 'taRegisterTool', function(taToolExecuteAction, taTools, taRegisterTool){
// this service is used to manage all textAngular editors and toolbars.
// All publicly published functions that modify/need to access the toolbar or editor scopes should be in here
// these contain references to all the editors and toolbars that have been initialised in this app
var toolbars = {}, editors = {};
// when we focus into a toolbar, we need to set the TOOLBAR's $parent to be the toolbars it's linked to.
// We also need to set the tools to be updated to be the toolbars...
return {
// register an editor and the toolbars that it is affected by
registerEditor: function(name, scope, targetToolbars){
// targetToolbars are optional, we don't require a toolbar to function
if(!name || name === '') throw('textAngular Error: An editor requires a name');
if(!scope) throw('textAngular Error: An editor requires a scope');
if(editors[name]) throw('textAngular Error: An Editor with name "' + name + '" already exists');
// _toolbars is an ARRAY of toolbar scopes
var _toolbars = [];
angular.forEach(targetToolbars, function(_name){
if(toolbars[_name]) _toolbars.push(toolbars[_name]);
// if it doesn't exist it may not have been compiled yet and it will be added later
});
editors[name] = {
scope: scope,
toolbars: targetToolbars,
_registerToolbar: function(toolbarScope){
// add to the list late
if(this.toolbars.indexOf(toolbarScope.name) >= 0) _toolbars.push(toolbarScope);
},
// this is a suite of functions the editor should use to update all it's linked toolbars
editorFunctions: {
disable: function(){
// disable all linked toolbars
angular.forEach(_toolbars, function(toolbarScope){ toolbarScope.disabled = true; });
},
enable: function(){
// enable all linked toolbars
angular.forEach(_toolbars, function(toolbarScope){ toolbarScope.disabled = false; });
},
focus: function(){
// this should be called when the editor is focussed
angular.forEach(_toolbars, function(toolbarScope){
toolbarScope._parent = scope;
toolbarScope.disabled = false;
toolbarScope.focussed = true;
});
},
unfocus: function(){
// this should be called when the editor becomes unfocussed
angular.forEach(_toolbars, function(toolbarScope){
toolbarScope.disabled = true;
toolbarScope.focussed = false;
});
},
updateSelectedStyles: function(selectedElement){
// update the active state of all buttons on liked toolbars
angular.forEach(_toolbars, function(toolbarScope){
angular.forEach(toolbarScope.tools, function(toolScope){
if(toolScope.activeState){
toolbarScope._parent = scope;
toolScope.active = toolScope.activeState(selectedElement);
}
});
});
},
sendKeyCommand: function(event){
// we return true if we applied an action, false otherwise
var result = false;
if(event.ctrlKey || event.metaKey) angular.forEach(taTools, function(tool, name){
if(tool.commandKeyCode && tool.commandKeyCode === event.which){
for(var _t = 0; _t < _toolbars.length; _t++){
if(_toolbars[_t].tools[name] !== undefined){
taToolExecuteAction.call(_toolbars[_t].tools[name], scope);
result = true;
break;
}
}
}
});
return result;
},
triggerElementSelect: function(event, element){
// search through the taTools to see if a match for the tag is made.
// if there is, see if the tool is on a registered toolbar and not disabled.
// NOTE: This can trigger on MULTIPLE tools simultaneously.
var elementHasAttrs = function(_element, attrs){
var result = true;
for(var i = 0; i < attrs.length; i++) result = result && _element.attr(attrs[i]);
return result;
};
var workerTools = [];
var unfilteredTools = {};
var result = false;
element = angular.element(element);
// get all valid tools by element name, keep track if one matches the
var onlyWithAttrsFilter = false;
angular.forEach(taTools, function(tool, name){
if(
tool.onElementSelect &&
tool.onElementSelect.element &&
tool.onElementSelect.element.toLowerCase() === element[0].tagName.toLowerCase() &&
(!tool.onElementSelect.filter || tool.onElementSelect.filter(element))
){
// this should only end up true if the element matches the only attributes
onlyWithAttrsFilter = onlyWithAttrsFilter ||
(angular.isArray(tool.onElementSelect.onlyWithAttrs) && elementHasAttrs(element, tool.onElementSelect.onlyWithAttrs));
if(!tool.onElementSelect.onlyWithAttrs || elementHasAttrs(element, tool.onElementSelect.onlyWithAttrs)) unfilteredTools[name] = tool;
}
});
// if we matched attributes to filter on, then filter, else continue
if(onlyWithAttrsFilter){
angular.forEach(unfilteredTools, function(tool, name){
if(tool.onElementSelect.onlyWithAttrs && elementHasAttrs(element, tool.onElementSelect.onlyWithAttrs)) workerTools.push({'name': name, 'tool': tool});
});
// sort most specific (most attrs to find) first
workerTools.sort(function(a,b){
return b.tool.onElementSelect.onlyWithAttrs.length - a.tool.onElementSelect.onlyWithAttrs.length;
});
}else{
angular.forEach(unfilteredTools, function(tool, name){
workerTools.push({'name': name, 'tool': tool});
});
}
// Run the actions on the first visible filtered tool only
if(workerTools.length > 0){
for(var _i = 0; _i < workerTools.length; _i++){
var tool = workerTools[_i].tool;
var name = workerTools[_i].name;
for(var _t = 0; _t < _toolbars.length; _t++){
if(_toolbars[_t].tools[name] !== undefined){
tool.onElementSelect.action.call(_toolbars[_t].tools[name], event, element, scope);
result = true;
break;
}
}
if(result) break;
}
}
return result;
}
}
};
return editors[name].editorFunctions;
},
// retrieve editor by name, largely used by testing suites only
retrieveEditor: function(name){
return editors[name];
},
unregisterEditor: function(name){
delete editors[name];
},
// registers a toolbar such that it can be linked to editors
registerToolbar: function(scope){
if(!scope) throw('textAngular Error: A toolbar requires a scope');
if(!scope.name || scope.name === '') throw('textAngular Error: A toolbar requires a name');
if(toolbars[scope.name]) throw('textAngular Error: A toolbar with name "' + scope.name + '" already exists');
toolbars[scope.name] = scope;
angular.forEach(editors, function(_editor){
_editor._registerToolbar(scope);
});
},
// retrieve toolbar by name, largely used by testing suites only
retrieveToolbar: function(name){
return toolbars[name];
},
// retrieve toolbars by editor name, largely used by testing suites only
retrieveToolbarsViaEditor: function(name){
var result = [], _this = this;
angular.forEach(this.retrieveEditor(name).toolbars, function(name){
result.push(_this.retrieveToolbar(name));
});
return result;
},
unregisterToolbar: function(name){
delete toolbars[name];
},
// functions for updating the toolbar buttons display
updateToolsDisplay: function(newTaTools){
// pass a partial struct of the taTools, this allows us to update the tools on the fly, will not change the defaults.
var _this = this;
angular.forEach(newTaTools, function(_newTool, key){
_this.updateToolDisplay(key, _newTool);
});
},
// this function resets all toolbars to their default tool definitions
resetToolsDisplay: function(){
var _this = this;
angular.forEach(taTools, function(_newTool, key){
_this.resetToolDisplay(key);
});
},
// update a tool on all toolbars
updateToolDisplay: function(toolKey, _newTool){
var _this = this;
angular.forEach(toolbars, function(toolbarScope, toolbarKey){
_this.updateToolbarToolDisplay(toolbarKey, toolKey, _newTool);
});
},
// resets a tool to the default/starting state on all toolbars
resetToolDisplay: function(toolKey){
var _this = this;
angular.forEach(toolbars, function(toolbarScope, toolbarKey){
_this.resetToolbarToolDisplay(toolbarKey, toolKey);
});
},
// update a tool on a specific toolbar
updateToolbarToolDisplay: function(toolbarKey, toolKey, _newTool){
if(toolbars[toolbarKey]) toolbars[toolbarKey].updateToolDisplay(toolKey, _newTool);
else throw('textAngular Error: No Toolbar with name "' + toolbarKey + '" exists');
},
// reset a tool on a specific toolbar to it's default starting value
resetToolbarToolDisplay: function(toolbarKey, toolKey){
if(toolbars[toolbarKey]) toolbars[toolbarKey].updateToolDisplay(toolKey, taTools[toolKey], true);
else throw('textAngular Error: No Toolbar with name "' + toolbarKey + '" exists');
},
// removes a tool from all toolbars and it's definition
removeTool: function(toolKey){
delete taTools[toolKey];
angular.forEach(toolbars, function(toolbarScope){
delete toolbarScope.tools[toolKey];
for(var i = 0; i < toolbarScope.toolbar.length; i++){
var toolbarIndex;
for(var j = 0; j < toolbarScope.toolbar[i].length; j++){
if(toolbarScope.toolbar[i][j] === toolKey){
toolbarIndex = {
group: i,
index: j
};
break;
}
if(toolbarIndex !== undefined) break;
}
if(toolbarIndex !== undefined){
toolbarScope.toolbar[toolbarIndex.group].slice(toolbarIndex.index, 1);
toolbarScope._$element.children().eq(toolbarIndex.group).children().eq(toolbarIndex.index).remove();
}
}
});
},
// toolkey, toolDefinition are required. If group is not specified will pick the last group, if index isnt defined will append to group
addTool: function(toolKey, toolDefinition, group, index){
taRegisterTool(toolKey, toolDefinition);
angular.forEach(toolbars, function(toolbarScope){
toolbarScope.addTool(toolKey, toolDefinition, group, index);
});
},
// adds a Tool but only to one toolbar not all
addToolToToolbar: function(toolKey, toolDefinition, toolbarKey, group, index){
taRegisterTool(toolKey, toolDefinition);
toolbars[toolbarKey].addTool(toolKey, toolDefinition, group, index);
},
// this is used when externally the html of an editor has been changed and textAngular needs to be notified to update the model.
// this will call a $digest if not already happening
refreshEditor: function(name){
if(editors[name]){
editors[name].scope.updateTaBindtaTextElement();
/* istanbul ignore else: phase catch */
if(!editors[name].scope.$$phase) editors[name].scope.$digest();
}else throw('textAngular Error: No Editor with name "' + name + '" exists');
}
};
}]);
textAngular.directive('textAngularToolbar', [
'$compile', 'textAngularManager', 'taOptions', 'taTools', 'taToolExecuteAction', '$window',
function($compile, textAngularManager, taOptions, taTools, taToolExecuteAction, $window){
return {
scope: {
name: '@' // a name IS required
},
restrict: "EA",
link: function(scope, element, attrs){
if(!scope.name || scope.name === '') throw('textAngular Error: A toolbar requires a name');
angular.extend(scope, angular.copy(taOptions));
if(attrs.taToolbar) scope.toolbar = scope.$parent.$eval(attrs.taToolbar);
if(attrs.taToolbarClass) scope.classes.toolbar = attrs.taToolbarClass;
if(attrs.taToolbarGroupClass) scope.classes.toolbarGroup = attrs.taToolbarGroupClass;
if(attrs.taToolbarButtonClass) scope.classes.toolbarButton = attrs.taToolbarButtonClass;
if(attrs.taToolbarActiveButtonClass) scope.classes.toolbarButtonActive = attrs.taToolbarActiveButtonClass;
if(attrs.taFocussedClass) scope.classes.focussed = attrs.taFocussedClass;
scope.disabled = true;
scope.focussed = false;
scope._$element = element;
element[0].innerHTML = '';
element.addClass("ta-toolbar " + scope.classes.toolbar);
scope.$watch('focussed', function(){
if(scope.focussed) element.addClass(scope.classes.focussed);
else element.removeClass(scope.classes.focussed);
});
var setupToolElement = function(toolDefinition, toolScope){
var toolElement;
if(toolDefinition && toolDefinition.display){
toolElement = angular.element(toolDefinition.display);
}
else toolElement = angular.element("<button type='button'>");
if(toolDefinition && toolDefinition["class"]) toolElement.addClass(toolDefinition["class"]);
else toolElement.addClass(scope.classes.toolbarButton);
toolElement.attr('name', toolScope.name);
// important to not take focus from the main text/html entry
toolElement.attr('unselectable', 'on');
toolElement.attr('ng-disabled', 'isDisabled()');
toolElement.attr('tabindex', '-1');
toolElement.attr('ng-click', 'executeAction()');
toolElement.attr('ng-class', 'displayActiveToolClass(active)');
if (toolDefinition && toolDefinition.tooltiptext) {
toolElement.attr('title', toolDefinition.tooltiptext);
}
toolElement.on('mousedown', function(e, eventData){
/* istanbul ignore else: this is for catching the jqLite testing*/
if(eventData) angular.extend(e, eventData);
// this prevents focusout from firing on the editor when clicking toolbar buttons
e.preventDefault();
return false;
});
if(toolDefinition && !toolDefinition.display && !toolScope._display){
// first clear out the current contents if any
toolElement[0].innerHTML = '';
// add the buttonText
if(toolDefinition.buttontext) toolElement[0].innerHTML = toolDefinition.buttontext;
// add the icon to the front of the button if there is content
if(toolDefinition.iconclass){
var icon = angular.element('<i>'), content = toolElement[0].innerHTML;
icon.addClass(toolDefinition.iconclass);
toolElement[0].innerHTML = '';
toolElement.append(icon);
if(content && content !== '') toolElement.append(' ' + content);
}
}
toolScope._lastToolDefinition = angular.copy(toolDefinition);
return $compile(toolElement)(toolScope);
};
// Keep a reference for updating the active states later
scope.tools = {};
// create the tools in the toolbar
// default functions and values to prevent errors in testing and on init
scope._parent = {
disabled: true,
showHtml: false,
queryFormatBlockState: function(){ return false; },
queryCommandState: function(){ return false; }
};
var defaultChildScope = {
$window: $window,
$editor: function(){
// dynamically gets the editor as it is set
return scope._parent;
},
isDisabled: function(){
// to set your own disabled logic set a function or boolean on the tool called 'disabled'
return ( // this bracket is important as without it it just returns the first bracket and ignores the rest
// when the button's disabled function/value evaluates to true
(typeof this.$eval('disabled') !== 'function' && this.$eval('disabled')) || this.$eval('disabled()') ||
// all buttons except the HTML Switch button should be disabled in the showHtml (RAW html) mode
(this.name !== 'html' && this.$editor().showHtml) ||
// if the toolbar is disabled
this.$parent.disabled ||
// if the current editor is disabled
this.$editor().disabled
);
},
displayActiveToolClass: function(active){
return (active)? scope.classes.toolbarButtonActive : '';
},
executeAction: taToolExecuteAction
};
angular.forEach(scope.toolbar, function(group){
// setup the toolbar group
var groupElement = angular.element("<div>");
groupElement.addClass(scope.classes.toolbarGroup);
angular.forEach(group, function(tool){
// init and add the tools to the group
// a tool name (key name from taTools struct)
//creates a child scope of the main angularText scope and then extends the childScope with the functions of this particular tool
// reference to the scope and element kept
scope.tools[tool] = angular.extend(scope.$new(true), taTools[tool], defaultChildScope, {name: tool});
scope.tools[tool].$element = setupToolElement(taTools[tool], scope.tools[tool]);
// append the tool compiled with the childScope to the group element
groupElement.append(scope.tools[tool].$element);
});
// append the group to the toolbar
element.append(groupElement);
});
// update a tool
// if a value is set to null, remove from the display
// when forceNew is set to true it will ignore all previous settings, used to reset to taTools definition
// to reset to defaults pass in taTools[key] as _newTool and forceNew as true, ie `updateToolDisplay(key, taTools[key], true);`
scope.updateToolDisplay = function(key, _newTool, forceNew){
var toolInstance = scope.tools[key];
if(toolInstance){
// get the last toolDefinition, then override with the new definition
if(toolInstance._lastToolDefinition && !forceNew) _newTool = angular.extend({}, toolInstance._lastToolDefinition, _newTool);
if(_newTool.buttontext === null && _newTool.iconclass === null && _newTool.display === null)
throw('textAngular Error: Tool Definition for updating "' + key + '" does not have a valid display/iconclass/buttontext value');
// if tool is defined on this toolbar, update/redo the tool
if(_newTool.buttontext === null){
delete _newTool.buttontext;
}
if(_newTool.iconclass === null){
delete _newTool.iconclass;
}
if(_newTool.display === null){
delete _newTool.display;
}
var toolElement = setupToolElement(_newTool, toolInstance);
toolInstance.$element.replaceWith(toolElement);
toolInstance.$element = toolElement;
}
};
// we assume here that all values passed are valid and correct
scope.addTool = function(key, _newTool, groupIndex, index){
scope.tools[key] = angular.extend(scope.$new(true), taTools[key], defaultChildScope, {name: key});
scope.tools[key].$element = setupToolElement(taTools[key], scope.tools[key]);
var group;
if(groupIndex === undefined) groupIndex = scope.toolbar.length - 1;
group = angular.element(element.children()[groupIndex]);
if(index === undefined){
group.append(scope.tools[key].$element);
scope.toolbar[groupIndex][scope.toolbar[groupIndex].length - 1] = key;
}else{
group.children().eq(index).after(scope.tools[key].$element);
scope.toolbar[groupIndex][index] = key;
}
};
textAngularManager.registerToolbar(scope);
scope.$on('$destroy', function(){
textAngularManager.unregisterToolbar(scope.name);
});
}
};
}
]);})(); |
//// Copyright (c) Microsoft Corporation. All rights reserved
(function () {
"use strict";
var sampleTitle = "Adaptive Streaming";
var scenarios = [
{ url: "/html/scenario1.html", title: "Basic HLS/DASH Playback" },
{ url: "/html/scenario2.html", title: "Configuring HLS/DASH Playback" },
{ url: "/html/scenario3.html", title: "Customized Resource Acquisition" },
{ url: "/html/scenario4.html", title: "Playback with PlayReady DRM" }
];
WinJS.Namespace.define("SdkSample", {
sampleTitle: sampleTitle,
scenarios: new WinJS.Binding.List(scenarios)
});
})(); |
export default function isPlainFunction(test) {
return typeof test === 'function' && test.PrototypeMixin === undefined;
}
|
(function() {
var MaxmertkitEvent, MaxmertkitHelpers, MaxmertkitReactor, _eventCallbacks, _globalRotation, _reactorEvents, _version;
_eventCallbacks = [];
_reactorEvents = [];
_globalRotation = {
x: 0,
y: 0,
z: 0
};
_version = "0.0.1";
MaxmertkitEvent = (function() {
function MaxmertkitEvent(name) {
this.name = name;
}
MaxmertkitEvent.prototype.callbacks = _eventCallbacks;
MaxmertkitEvent.prototype.registerCallback = function(callback) {
return this.callbacks.push(callback);
};
return MaxmertkitEvent;
})();
MaxmertkitReactor = (function() {
function MaxmertkitReactor() {}
MaxmertkitReactor.prototype.events = _reactorEvents;
MaxmertkitReactor.prototype.registerEvent = function(eventName) {
var event;
event = new MaxmertkitEvent(eventName);
return this.events[eventName] = event;
};
MaxmertkitReactor.prototype.dispatchEvent = function(eventName, eventArgs) {
var callback, _i, _len, _ref, _results;
_ref = this.events[eventName].callbacks;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
callback = _ref[_i];
_results.push(callback(eventArgs));
}
return _results;
};
MaxmertkitReactor.prototype.addEventListener = function(eventName, callback) {
return this.events[eventName].registerCallback(callback);
};
return MaxmertkitReactor;
})();
MaxmertkitHelpers = (function() {
MaxmertkitHelpers.prototype._id = 0;
MaxmertkitHelpers.prototype._instances = new Array();
function MaxmertkitHelpers($btn, options) {
this.$btn = $btn;
this.options = options;
this._pushInstance();
if (this._afterConstruct != null) {
this._afterConstruct();
}
}
MaxmertkitHelpers.prototype.destroy = function() {
this.$el.off("." + this._name);
return this._popInstance();
};
MaxmertkitHelpers.prototype._extend = function(object, properties) {
var key, val;
for (key in properties) {
val = properties[key];
object[key] = val;
}
return object;
};
MaxmertkitHelpers.prototype._merge = function(options, overrides) {
return this._extend(this._extend({}, options), overrides);
};
MaxmertkitHelpers.prototype._setOptions = function(options) {
return console.warning("Maxmertkit Helpers. There is no standart setOptions function.");
};
MaxmertkitHelpers.prototype._pushInstance = function() {
this._id++;
return this._instances.push(this);
};
MaxmertkitHelpers.prototype._popInstance = function() {
var index, instance, _i, _len, _ref, _results;
_ref = this._instances;
_results = [];
for (index = _i = 0, _len = _ref.length; _i < _len; index = ++_i) {
instance = _ref[index];
if (instance._id === this._id) {
this._instances.splice(index, 1);
}
_results.push(delete this);
}
return _results;
};
MaxmertkitHelpers.prototype._selfish = function() {
var index, instance, _i, _len, _ref, _results;
_ref = this._instances;
_results = [];
for (index = _i = 0, _len = _ref.length; _i < _len; index = ++_i) {
instance = _ref[index];
if (this._id !== instance._id) {
_results.push(instance.close());
} else {
_results.push(void 0);
}
}
return _results;
};
MaxmertkitHelpers.prototype._getVersion = function() {
return _version;
};
MaxmertkitHelpers.prototype.reactor = new MaxmertkitReactor();
MaxmertkitHelpers.prototype._setTransform = function(style, transform) {
style.webkitTransform = transform;
style.MozTransform = transform;
return style.transform = transform;
};
MaxmertkitHelpers.prototype._equalNodes = function(node1, node2) {
return node1.get(0) === node2.get(0);
};
MaxmertkitHelpers.prototype._deviceMobile = function() {
return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
};
MaxmertkitHelpers.prototype._refreshSizes = function() {
this._windowHeight = $(window).height();
this._windowWidth = $(window).width();
this._height = this.$el.height();
this._width = this.$el.width();
if (this.scroll != null) {
if (this.scroll[0].nodeName === 'BODY') {
return this._offset = this.$el.offset();
} else {
return this._offset = this.$el.offset();
}
} else {
return this._offset = this.$el.offset();
}
};
MaxmertkitHelpers.prototype._getContainer = function(el) {
var parent, style;
parent = el[0] || el;
while (parent = parent.parentNode) {
try {
style = getComputedStyle(parent);
} catch (_error) {}
if (style == null) {
return $(parent);
}
if (/(relative)/.test(style['position']) || ((parent != null) && (parent.style != null) && /(relative)/.test(parent.style['position']))) {
return $(parent);
}
}
return $(document);
};
MaxmertkitHelpers.prototype._getScrollParent = function(el) {
var parent, style;
parent = el[0] || el;
while (parent = parent.parentNode) {
try {
style = getComputedStyle(parent);
} catch (_error) {}
if (style == null) {
return $(parent);
}
if (/(auto|scroll)/.test(style['overflow'] + style['overflow-y'] + style['overflow-x']) && $(parent)[0].nodeName !== 'BODY') {
return $(parent);
}
}
return $(document);
};
MaxmertkitHelpers.prototype._isVisible = function() {
return this._offset.top - this._windowHeight <= this.scroll.scrollTop() && this.scroll.scrollTop() <= this._offset.top + this._height;
};
MaxmertkitHelpers.prototype._getVisiblePercent = function() {
var current, max, min;
min = this._offset.top;
current = this.scroll.scrollTop();
max = this._offset.top + this._height;
return (current - min) / (max - min);
};
MaxmertkitHelpers.prototype._scrollVisible = function() {
var current, max, min, percent;
if (this.scroll != null) {
min = this._offset.top - this._windowHeight;
max = this._offset.top + this._height + this._windowHeight;
current = this.scroll.scrollTop() + this._windowHeight;
percent = 1 - current / max;
return (1 > percent && percent > 0);
} else {
return true;
}
};
MaxmertkitHelpers.prototype._setGlobalRotation = function(x, y, z) {
return _globalRotation = {
x: x,
y: y,
z: z
};
};
MaxmertkitHelpers.prototype._getGlobalRotation = function() {
return _globalRotation;
};
return MaxmertkitHelpers;
})();
/*
Adds support for the special browser events 'scrollstart' and 'scrollstop'.
*/
(function() {
var special, uid1, uid2;
special = jQuery.event.special;
uid1 = "D" + (+new Date());
uid2 = "D" + (+new Date() + 1);
special.scrollstart = {
setup: function() {
var handler, timer;
timer = void 0;
handler = function(evt) {
var _args;
_args = arguments;
if (timer) {
clearTimeout(timer);
} else {
evt.type = "scrollstart";
jQuery.event.trigger.apply(this, _args);
}
timer = setTimeout(function() {
timer = null;
}, special.scrollstop.latency);
};
jQuery(this).bind("scroll", handler).data(uid1, handler);
},
teardown: function() {
jQuery(this).unbind("scroll", jQuery(this).data(uid1));
}
};
special.scrollstop = {
latency: 300,
setup: function() {
var handler, timer;
timer = void 0;
handler = function(evt) {
var _args;
_args = arguments;
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(function() {
timer = null;
evt.type = "scrollstop";
jQuery.event.trigger.apply(this, _args);
}, special.scrollstop.latency);
};
jQuery(this).bind("scroll", handler).data(uid2, handler);
},
teardown: function() {
jQuery(this).unbind("scroll", jQuery(this).data(uid2));
}
};
})();
window['MaxmertkitHelpers'] = MaxmertkitHelpers;
}).call(this);
(function() {
var Affix, _beforestart, _beforestop, _id, _instances, _name, _position, _setPosition, _start, _stop,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
_name = "affix";
_instances = [];
_id = 0;
Affix = (function(_super) {
__extends(Affix, _super);
Affix.prototype._name = _name;
Affix.prototype._instances = _instances;
function Affix(el, options) {
var _options;
this.el = el;
this.options = options;
this.$el = $(this.el);
this.$el.parent().append(' ');
this._id = _id++;
_options = {
spy: this.$el.data('spy') || 'affix',
offset: 5,
beforeactive: function() {},
onactive: function() {},
beforeunactive: function() {},
onunactive: function() {}
};
this.options = this._merge(_options, this.options);
this.beforeactive = this.options.beforeactive;
this.onactive = this.options.onactive;
this.beforeunactive = this.options.beforeunactive;
this.onunactive = this.options.onunactive;
this.start();
Affix.__super__.constructor.call(this, this.$btn, this.options);
}
Affix.prototype._setOptions = function(options) {
var key, value;
for (key in options) {
value = options[key];
if (this.options[key] == null) {
return console.error("Maxmertkit Affix. You're trying to set unpropriate option.");
}
this.options[key] = value;
}
};
Affix.prototype.destroy = function() {
return Affix.__super__.destroy.apply(this, arguments);
};
Affix.prototype.start = function() {
return _beforestart.call(this);
};
Affix.prototype.stop = function() {
return _beforestop.call(this);
};
return Affix;
})(MaxmertkitHelpers);
_setPosition = function() {
var $scrollParent, offset;
$scrollParent = this._getContainer(this.$el);
if ($scrollParent[0].firstElementChild.nodeName === "HTML") {
offset = 0;
} else {
offset = $scrollParent.offset().top;
}
if ((this.$el.parent() != null) && this.$el.parent().offset() && !this._deviceMobile() && this._windowWidth > 992) {
if (this.$el.parent().offset().top - this.options.offset <= $(document).scrollTop()) {
if (this.$el.parent().offset().top + $scrollParent.outerHeight() - this.options.offset - this.$el.outerHeight() >= $(document).scrollTop()) {
return this.$el.css({
width: this.$el.width(),
position: 'fixed',
top: "" + this.options.offset + "px",
bottom: 'auto'
});
} else {
return this.$el.css({
position: 'absolute',
top: 'auto',
bottom: "-" + this.options.offset + "px",
width: this.$el.width()
});
}
} else {
this.$el.css('position', 'relative');
return this.$el.css('top', 'inherit');
}
}
};
_position = function() {
$(document).on("scroll." + this._name + "." + this._id, (function(_this) {
return function(event) {
return _setPosition.call(_this);
};
})(this));
return $(window).on("resize." + this._name + "." + this._id, (function(_this) {
return function(event) {
_this._refreshSizes();
if (_this._windowWidth < 992) {
_this.$el.css('position', 'relative');
return _this.$el.css('top', 'inherit');
} else {
return _setPosition.call(_this);
}
};
})(this));
};
_beforestart = function() {
var deferred;
if (this.beforeactive != null) {
try {
deferred = this.beforeactive.call(this.$el);
return deferred.done((function(_this) {
return function() {
return _start.call(_this);
};
})(this)).fail((function(_this) {
return function() {
return _this.$el.trigger("fail." + _this._name);
};
})(this));
} catch (_error) {
return _start.call(this);
}
} else {
return _start.call(this);
}
};
_start = function() {
this._refreshSizes();
_position.call(this);
this.$el.addClass('_active_');
this.$el.trigger("started." + this._name);
if (this.onactive != null) {
try {
return this.onactive.call(this.$el);
} catch (_error) {}
}
};
_beforestop = function() {
var deferred;
if (this.beforeunactive != null) {
try {
deferred = this.beforeunactive.call(this.$el);
return deferred.done((function(_this) {
return function() {
return _stop.call(_this);
};
})(this)).fail((function(_this) {
return function() {
return _this.$el.trigger("fail." + _this._name);
};
})(this));
} catch (_error) {
return _stop.call(this);
}
} else {
return _stop.call(this);
}
};
_stop = function() {
this.$el.removeClass('_active_');
$(document).off("scroll." + this._name + "." + this._id);
this.$el.trigger("stopped." + this._name);
if (this.onunactive != null) {
try {
return this.onunactive.call(this.$el);
} catch (_error) {}
}
};
$.fn[_name] = function(options) {
return this.each(function() {
if (!$.data(this, "kit-" + _name)) {
$.data(this, "kit-" + _name, new Affix(this, options));
} else {
if (typeof options === "object") {
$.data(this, "kit-" + _name)._setOptions(options);
} else {
if (typeof options === "string" && options.charAt(0) !== "_") {
$.data(this, "kit-" + _name)[options];
}
}
}
});
};
}).call(this);
(function() {
var Button, _activate, _beforeactive, _beforeunactive, _deactivate, _id, _instances, _name,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
_name = "button";
_instances = [];
_id = 0;
Button = (function(_super) {
__extends(Button, _super);
Button.prototype._name = _name;
Button.prototype._instances = _instances;
function Button(btn, options) {
var _options;
this.btn = btn;
this.options = options;
this.$btn = $(this.btn);
this._id = _id++;
_options = {
toggle: this.$btn.data('toggle') || 'button',
group: this.$btn.data('group') || null,
type: this.$btn.data('type') || 'button',
event: "click",
beforeactive: function() {},
onactive: function() {},
beforeunactive: function() {},
onunactive: function() {}
};
this.options = this._merge(_options, this.options);
this.beforeactive = this.options.beforeactive;
this.onactive = this.options.onactive;
this.beforeunactive = this.options.beforeunactive;
this.onunactive = this.options.onunactive;
this.$btn.on(this.options.event, (function(_this) {
return function() {
if (!_this.$btn.hasClass('_active_')) {
return _this.activate();
} else {
return _this.deactivate();
}
};
})(this));
this.$btn.on(this.options.eventClose, (function(_this) {
return function() {
if (_this.options.event !== _this.options.eventClose) {
return _this.deactivate();
}
};
})(this));
this.$btn.removeClass('_active_ _disabled_ _loading_');
Button.__super__.constructor.call(this, this.$btn, this.options);
}
Button.prototype._setOptions = function(options) {
var key, value;
for (key in options) {
value = options[key];
if (this.options[key] == null) {
return console.error("Maxmertkit Button. You're trying to set unpropriate option.");
}
switch (key) {
case 'event':
this.$btn.off("" + this.options.event + "." + this._name);
this.options.event = value;
this.$btn.on("" + this.options.event + "." + this._name, (function(_this) {
return function() {
if (_this.$btn.hasClass('_active_')) {
return _this.deactivate();
} else {
return _this.activate();
}
};
})(this));
break;
default:
this.options[key] = value;
if (typeof value === 'function') {
this[key] = this.options[key];
}
}
}
};
Button.prototype.destroy = function() {
this.$btn.off("." + this._name);
return Button.__super__.destroy.apply(this, arguments);
};
Button.prototype.activate = function() {
return _beforeactive.call(this);
};
Button.prototype.deactivate = function() {
if (this.$btn.hasClass('_active_')) {
return _beforeunactive.call(this);
}
};
Button.prototype.disable = function() {
return this.$btn.toggleClass('_disabled_');
};
return Button;
})(MaxmertkitHelpers);
_beforeactive = function() {
var deferred;
if (this.options.selfish) {
this._selfish();
}
if (this.beforeactive != null) {
try {
deferred = this.beforeactive.call(this.$btn);
return deferred.done((function(_this) {
return function() {
return _activate.call(_this);
};
})(this)).fail((function(_this) {
return function() {
return _this.$btn.trigger("fail." + _this._name);
};
})(this));
} catch (_error) {
return _activate.call(this);
}
} else {
return _activate.call(this);
}
};
_activate = function() {
var button, _i, _len, _ref;
if (this.options.type === 'radio') {
_ref = this._instances;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
button = _ref[_i];
if (this._id !== button._id && button.options.type === 'radio' && button.options.group === this.options.group) {
button.deactivate();
}
}
}
this.$btn.addClass('_active_');
this.$btn.trigger("activated." + this._name);
if (this.onactive != null) {
try {
return this.onactive.call(this.$btn);
} catch (_error) {}
}
};
_beforeunactive = function() {
var deferred;
if (this.beforeunactive != null) {
try {
deferred = this.beforeunactive.call(this.$btn);
return deferred.done((function(_this) {
return function() {
return _deactivate.call(_this);
};
})(this)).fail((function(_this) {
return function() {
return _this.$btn.trigger("fail." + _this._name);
};
})(this));
} catch (_error) {
return _deactivate.call(this);
}
} else {
return _deactivate.call(this);
}
};
_deactivate = function() {
this.$btn.removeClass('_active_');
this.$btn.trigger("deactivated." + this._name);
if (this.onunactive != null) {
try {
return this.onunactive.call(this.$btn);
} catch (_error) {}
}
};
$.fn[_name] = function(options) {
return this.each(function() {
if (!$.data(this, "kit-" + _name)) {
$.data(this, "kit-" + _name, new Button(this, options));
} else {
if (typeof options === "object") {
$.data(this, "kit-" + _name)._setOptions(options);
} else {
if (typeof options === "string" && options.charAt(0) !== "_") {
$.data(this, "kit-" + _name)[options];
} else {
console.error("Maxmertkit Button. You passed into the " + _name + " something wrong.\n" + options);
}
}
}
});
};
$(window).on('load', function() {
return $('[data-toggle="button"]').each(function() {
var $btn;
$btn = $(this);
return $btn.button($btn.data());
});
});
}).call(this);
(function() {
var Modal, _beforeclose, _beforeopen, _close, _instances, _name, _open, _pushStart, _pushStop,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
_name = "modal";
_instances = [];
Modal = (function(_super) {
__extends(Modal, _super);
Modal.prototype._name = _name;
Modal.prototype._instances = _instances;
function Modal(btn, options) {
var _options;
this.btn = btn;
this.options = options;
this.$btn = $(this.btn);
_options = {
target: this.$btn.data('target'),
toggle: this.$btn.data('toggle') || 'modal',
event: "click." + this._name,
eventClose: "click." + this._name,
backdrop: this.$btn.data('backdrop') || false,
push: this.$btn.data('push') || false,
beforeactive: function() {},
onactive: function() {},
beforeunactive: function() {},
onunactive: function() {}
};
this.options = this._merge(_options, this.options);
this.$el = $(document).find(this.options.target);
this.$btn.on(this.options.event, (function(_this) {
return function(event) {
event.preventDefault();
return _this.open();
};
})(this));
this._setOptions(this.options);
this.$el.find("*[data-dismiss='modal']").on(this.options.event, (function(_this) {
return function() {
return _this.close();
};
})(this));
Modal.__super__.constructor.call(this, this.$btn, this.options);
}
Modal.prototype._setOptions = function(options) {
var key, push, value;
for (key in options) {
value = options[key];
if (this.options[key] == null) {
return console.error("Maxmertkit Modal. You're trying to set unpropriate option – " + key);
}
switch (key) {
case 'backdrop':
if (value) {
this.$el.on("click." + this._name, (function(_this) {
return function(event) {
if ($(event.target).hasClass('-modal _active_') || $(event.target).hasClass('-carousel')) {
return _this.close();
}
};
})(this));
}
break;
case 'push':
if (value) {
push = $(document).find(value);
if (push.length) {
this.$push = $(document).find(value);
}
}
}
this.options[key] = value;
if (typeof value === 'function') {
this[key] = this.options[key];
}
}
};
Modal.prototype.destroy = function() {
this.$btn.off("." + this._name);
return Modal.__super__.destroy.apply(this, arguments);
};
Modal.prototype.open = function() {
return _beforeopen.call(this);
};
Modal.prototype.close = function() {
return _beforeclose.call(this);
};
return Modal;
})(MaxmertkitHelpers);
_pushStart = function() {
if (this.$push != null) {
this.$push.addClass('-start--');
return this.$push.removeClass('-stop--');
}
};
_pushStop = function() {
if (this.$push != null) {
this.$push.addClass('-stop--');
this.$push.removeClass('-start--');
if ((this.$push[0] != null) && (this.$push[0].style != null) && (this.$push[0].style['-webkit-overflow-scrolling'] != null)) {
return this.$push[0].style['-webkit-overflow-scrolling'] = 'auto';
}
}
};
_beforeopen = function() {
var deferred;
if (this.beforeopen != null) {
try {
deferred = this.beforeopen.call(this.$btn);
return deferred.done((function(_this) {
return function() {
return _open.call(_this);
};
})(this)).fail((function(_this) {
return function() {
return _this.$el.trigger("fail." + _this._name);
};
})(this));
} catch (_error) {
return _open.call(this);
}
} else {
return _open.call(this);
}
};
_open = function() {
if (this.$push != null) {
$('body').addClass('_perspective_');
}
this.$el.css({
display: 'table'
});
setTimeout((function(_this) {
return function() {
_this.$el.addClass('_visible_ -start--');
_this.$el.find('.-dialog').addClass('_visible_ -start--');
return _pushStart.call(_this);
};
})(this), 1);
$('body').addClass('_no-scroll_');
this.$el.trigger("opened." + this._name);
if (this.onopen != null) {
try {
return this.onopen.call(this.$btn);
} catch (_error) {}
}
};
_beforeclose = function() {
var deferred;
if (this.beforeclose != null) {
try {
deferred = this.beforeclose.call(this.$btn);
return deferred.done((function(_this) {
return function() {
return _close.call(_this);
};
})(this)).fail((function(_this) {
return function() {
return _this.$el.trigger("fail." + _this._name);
};
})(this));
} catch (_error) {
return _close.call(this);
}
} else {
return _close.call(this);
}
};
_close = function() {
this.$el.addClass('-stop--');
this.$el.find('.-dialog').addClass('-stop--');
_pushStop.call(this);
setTimeout((function(_this) {
return function() {
_this.$el.removeClass('_visible_ -start-- -stop--');
_this.$el.find('.-dialog').removeClass('_visible_ -start-- -stop--');
$('body').removeClass('_no-scroll_');
if (_this.$push != null) {
$('body').removeClass('_perspective_');
}
return _this.$el.hide();
};
})(this), 1000);
this.$el.trigger("closed." + this._name);
if (this.onclose != null) {
try {
return this.onclose.call(this.$btn);
} catch (_error) {}
}
};
$.fn[_name] = function(options) {
return this.each(function() {
if (!$.data(this, "kit-" + _name)) {
$.data(this, "kit-" + _name, new Modal(this, options));
} else {
if (typeof options === "object") {
$.data(this, "kit-" + _name)._setOptions(options);
} else {
if (typeof options === "string" && options.charAt(0) !== "_") {
$.data(this, "kit-" + _name)[options];
} else {
console.error("Maxmertkit error. You passed into the " + _name + " something wrong.");
}
}
}
});
};
$(window).on('load', function() {
return $('[data-toggle="modal"]').each(function() {
var $modal;
$modal = $(this);
return $modal.modal($modal.data());
});
});
}).call(this);
(function() {
var Popup, _beforeclose, _beforeopen, _close, _id, _instances, _name, _open, _position,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
_name = "popup";
_instances = [];
_id = 0;
Popup = (function(_super) {
__extends(Popup, _super);
Popup.prototype._name = _name;
Popup.prototype._instances = _instances;
function Popup(btn, options) {
var _options;
this.btn = btn;
this.options = options;
this.$btn = $(this.btn);
this._id = _id++;
_options = {
target: this.$btn.data('target'),
toggle: this.$btn.data('toggle') || 'popup',
event: "click",
eventClose: "click",
positionVertical: 'top',
positionHorizontal: 'center',
offset: {
horizontal: 5,
vertical: 5
},
closeUnfocus: false,
selfish: true
};
this.options = this._merge(_options, this.options);
this.beforeopen = this.options.beforeopen;
this.onopen = this.options.onopen;
this.beforeclose = this.options.beforeclose;
this.onclose = this.options.onclose;
this.$el = $(document).find(this.options.target);
this.$btn.on(this.options.event, (function(_this) {
return function() {
if (!_this.$el.is(':visible')) {
return _this.open();
} else {
return _this.close();
}
};
})(this));
this.$btn.on(this.options.eventClose, (function(_this) {
return function() {
if (_this.options.event !== _this.options.eventClose) {
return _this.close();
}
};
})(this));
this.$el.find("*[data-dismiss='popup']").on(this.options.event, (function(_this) {
return function() {
return _this.close();
};
})(this));
if (this.options.closeUnfocus) {
$(document).on('click', (function(_this) {
return function(event) {
var classes;
classes = '.' + _this.$el[0].className.split(' ').join('.');
if (!$(event.target).closest(classes).length && _this.$el.is(':visible') && !_this.$el.is(':animated') && $(event.target)[0] !== _this.$btn[0]) {
return _this.close();
}
};
})(this));
}
this.$el.removeClass('_top_ _bottom_ _left_ _right_');
this.$el.addClass("_" + this.options.positionVertical + "_ _" + this.options.positionHorizontal + "_");
Popup.__super__.constructor.call(this, this.$btn, this.options);
}
Popup.prototype._setOptions = function(options) {
var key, value;
for (key in options) {
value = options[key];
if (this.options[key] == null) {
return console.error("Maxmertkit Popup. You're trying to set unpropriate option.");
}
switch (key) {
case 'target':
this.$el = $(document).find(this.options.target);
this.$el.find("*[data-dismiss='popup']").on(this.options.event, (function(_this) {
return function() {
return _this.close();
};
})(this));
break;
case 'event':
this.$btn.off("" + this.options.event + "." + this._name);
this.options.event = value;
this.$btn.on("" + this.options.event + "." + this._name, (function(_this) {
return function() {
if (!_this.$el.is(':visible')) {
return _this.open();
} else {
return _this.close();
}
};
})(this));
break;
case 'eventClose':
this.$btn.off("" + this.options.eventClose + "." + this._name);
this.options.eventClose = value;
this.$btn.on("" + this.options.eventClose + "." + this._name, (function(_this) {
return function() {
if (_this.options.event !== _this.options.eventClose) {
return _this.close();
}
};
})(this));
break;
case 'closeUnfocus':
this.options.closeUnfocus = value;
$(document).off("click." + this._name);
if (this.options.closeUnfocus) {
$(document).on("click." + this._name, (function(_this) {
return function(event) {
var classes;
classes = '.' + _this.$el[0].className.split(' ').join('.');
if (!$(event.target).closest(classes).length && _this.$el.is(':visible') && !_this.$el.is(':animated') && $(event.target)[0] !== _this.$btn[0]) {
return _this.close();
}
};
})(this));
}
break;
case 'positionVertical':
this.$el.removeClass("_top_ _middle_ _bottom_");
this.options.positionVertical = value;
this.$el.addClass("_" + this.options.positionVertical + "_");
break;
case 'positionHorizontal':
this.$el.removeClass("_left_ _center_ _right_");
this.options.positionHorizontal = value;
this.$el.addClass("_" + this.options.positionHorizontal + "_");
break;
default:
this.options[key] = value;
}
}
};
Popup.prototype.destroy = function() {
this.$btn.off("." + this._name);
return Popup.__super__.destroy.apply(this, arguments);
};
Popup.prototype.open = function() {
return _beforeopen.call(this);
};
Popup.prototype.close = function() {
return _beforeclose.call(this);
};
return Popup;
})(MaxmertkitHelpers);
_position = function() {
var newLeft, newTop, position, positionBtn, scrollParent, scrollParentBtn, size, sizeBtn;
scrollParent = this._getScrollParent(this.$el);
scrollParentBtn = this._getScrollParent(this.$btn);
positionBtn = this.$btn.offset();
position = this.$el.offset();
if ((scrollParent != null) && (scrollParent[0] == null) || scrollParent[0].activeElement.nodeName !== 'BODY') {
positionBtn.top = positionBtn.top - $(scrollParent).offset().top;
positionBtn.left = positionBtn.left - $(scrollParent).offset().left;
}
sizeBtn = {
width: this.$btn.outerWidth(),
height: this.$btn.outerHeight()
};
size = {
width: this.$el.outerWidth(),
height: this.$el.outerHeight()
};
newTop = newLeft = 0;
switch (this.options.positionVertical) {
case 'top':
newTop = positionBtn.top - size.height - this.options.offset.vertical;
break;
case 'bottom':
newTop = positionBtn.top + sizeBtn.height + this.options.offset.vertical;
break;
case 'middle' || 'center':
newTop = positionBtn.top + sizeBtn.height / 2 - size.height / 2;
}
switch (this.options.positionHorizontal) {
case 'center' || 'middle':
newLeft = positionBtn.left + sizeBtn.width / 2 - size.width / 2;
break;
case 'left':
newLeft = positionBtn.left - size.width - this.options.offset.horizontal;
break;
case 'right':
newLeft = positionBtn.left + sizeBtn.width + this.options.offset.horizontal;
}
return this.$el.css({
left: newLeft,
top: newTop
});
};
_beforeopen = function() {
var deferred;
if (this.options.selfish) {
this._selfish();
}
if (this.beforeopen != null) {
try {
deferred = this.beforeopen.call(this.$btn);
return deferred.done((function(_this) {
return function() {
return _open.call(_this);
};
})(this)).fail((function(_this) {
return function() {
return _this.$el.trigger("fail." + _this._name);
};
})(this));
} catch (_error) {
return _open.call(this);
}
} else {
return _open.call(this);
}
};
_open = function() {
_position.call(this);
this.$el.addClass('_active_');
this.$el.trigger("opened." + this._name);
if (this.onopen != null) {
try {
return this.onopen.call(this.$btn);
} catch (_error) {}
}
};
_beforeclose = function() {
var deferred;
if (this.beforeclose != null) {
try {
deferred = this.beforeclose.call(this.$btn);
return deferred.done((function(_this) {
return function() {
return _close.call(_this);
};
})(this)).fail((function(_this) {
return function() {
return _this.$el.trigger("fail." + _this._name);
};
})(this));
} catch (_error) {
return _close.call(this);
}
} else {
return _close.call(this);
}
};
_close = function() {
this.$el.removeClass('_active_');
this.$el.trigger("closed." + this._name);
if (this.onclose != null) {
try {
return this.onclose.call(this.$btn);
} catch (_error) {}
}
};
$.fn[_name] = function(options) {
return this.each(function() {
if (!$.data(this, "kit-" + _name)) {
$.data(this, "kit-" + _name, new Popup(this, options));
} else {
if (typeof options === "object") {
$.data(this, "kit-" + _name)._setOptions(options);
} else {
if (typeof options === "string" && options.charAt(0) !== "_") {
$.data(this, "kit-" + _name)[options];
} else {
console.error("Maxmertkit Popup. You passed into the " + _name + " something wrong.");
}
}
}
});
};
}).call(this);
(function() {
var Scrollspy, _activate, _activateItem, _beforestart, _beforestop, _deactivateItem, _id, _instances, _name, _refresh, _spy, _start, _stop,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
_name = "scrollspy";
_instances = [];
_id = 0;
Scrollspy = (function(_super) {
__extends(Scrollspy, _super);
Scrollspy.prototype._name = _name;
Scrollspy.prototype._instances = _instances;
function Scrollspy(el, options) {
var _options;
this.el = el;
this.options = options;
this.$el = $(this.el);
this._id = _id++;
_options = {
spy: this.$el.data('spy') || 'scroll',
target: this.$el.data('target') || 'body',
offset: 0,
elements: 'li a',
elementsAttr: 'href',
noMobile: this.$el.data("no-mobile") || true,
beforeactive: function() {},
onactive: function() {},
beforeunactive: function() {},
onunactive: function() {}
};
this.options = this._merge(_options, this.options);
this.beforeactive = this.options.beforeactive;
this.onactive = this.options.onactive;
this.beforeunactive = this.options.beforeunactive;
this.onunactive = this.options.onunactive;
this.start();
Scrollspy.__super__.constructor.call(this, this.$btn, this.options);
}
Scrollspy.prototype._setOptions = function(options) {
var key, value;
for (key in options) {
value = options[key];
if (this.options[key] == null) {
return console.error("Maxmertkit Scrollspy. You're trying to set unpropriate option.");
}
this.options[key] = value;
}
};
Scrollspy.prototype.destroy = function() {
return Scrollspy.__super__.destroy.apply(this, arguments);
};
Scrollspy.prototype.refresh = function() {
return _refresh.call(this);
};
Scrollspy.prototype.start = function() {
return _beforestart.call(this);
};
Scrollspy.prototype.stop = function() {
return _beforestop.call(this);
};
return Scrollspy;
})(MaxmertkitHelpers);
_activateItem = function(itemNumber) {
var element, _i, _len, _ref;
_ref = this.elements;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
element = _ref[_i];
element.menu.removeClass('_active_');
}
return this.elements[itemNumber].menu.addClass('_active_').parents('li').addClass('_active_');
};
_deactivateItem = function(itemNumber) {
return this.elements[itemNumber].menu.removeClass('_active_');
};
_refresh = function() {
this.elements = [];
return this.$el.find(this.options.elements).each((function(_this) {
return function(index, el) {
var item, link;
link = $(el).attr(_this.options.elementsAttr);
if (link != null) {
item = $(_this.options.target).find(link);
if (item.length) {
return _this.elements.push({
menu: $(el).parent(),
item: item.parent(),
itemHeight: item.parent().height(),
offsetTop: item.position().top
});
}
}
};
})(this));
};
_spy = function(event) {
var i, _ref, _results;
i = 0;
_results = [];
while (i < this.elements.length) {
if ((this.elements[i].offsetTop <= (_ref = (event.currentTarget.scrollTop || event.currentTarget.scrollY) + this.options.offset) && _ref <= this.elements[i].offsetTop + this.elements[i].itemHeight)) {
if (!this.elements[i].menu.hasClass('_active_')) {
_activateItem.call(this, i);
}
} else {
if (this.elements[i].menu.hasClass('_active_') && (event.currentTarget.scrollTop || event.currentTarget.scrollY) + this.options.offset < this.elements[i].offsetTop + this.elements[i].itemHeight) {
_deactivateItem.call(this, i);
}
}
_results.push(i++);
}
return _results;
};
_activate = function() {
var target;
if (this.options.target === 'body') {
target = window;
} else {
target = this.options.target;
}
return $(target).on("scroll." + this._name + "." + this._id, (function(_this) {
return function(event) {
return _spy.call(_this, event);
};
})(this));
};
_beforestart = function() {
var deferred;
this.refresh();
if (this.beforeactive != null) {
try {
deferred = this.beforeactive.call(this.$el);
return deferred.done((function(_this) {
return function() {
return _start.call(_this);
};
})(this)).fail((function(_this) {
return function() {
return _this.$el.trigger("fail." + _this._name);
};
})(this));
} catch (_error) {
return _start.call(this);
}
} else {
return _start.call(this);
}
};
_start = function() {
_activate.call(this);
this.$el.addClass('_active_');
this.$el.trigger("started." + this._name);
if (this.onactive != null) {
try {
return this.onactive.call(this.$el);
} catch (_error) {}
}
};
_beforestop = function() {
var deferred;
if (this.beforeunactive != null) {
try {
deferred = this.beforeunactive.call(this.$el);
return deferred.done((function(_this) {
return function() {
return _stop.call(_this);
};
})(this)).fail((function(_this) {
return function() {
return _this.$el.trigger("fail." + _this._name);
};
})(this));
} catch (_error) {
return _stop.call(this);
}
} else {
return _stop.call(this);
}
};
_stop = function() {
var target;
if (this.options.target === 'body') {
target = window;
} else {
target = this.options.target;
}
$(target).off("scroll." + this._name + "." + this._id);
this.$el.trigger("stopped." + this._name);
if (this.onunactive != null) {
try {
return this.onunactive.call(this.$el);
} catch (_error) {}
}
};
$.fn[_name] = function(options) {
return this.each(function() {
if (!$.data(this, "kit-" + _name)) {
$.data(this, "kit-" + _name, new Scrollspy(this, options));
} else {
if (typeof options === "object") {
$.data(this, "kit-" + _name)._setOptions(options);
} else {
if (typeof options === "string" && options.charAt(0) !== "_") {
$.data(this, "kit-" + _name)[options];
} else {
console.error("Maxmertkit Affix. You passed into the " + _name + " something wrong.");
}
}
}
});
};
}).call(this);
(function() {
var Tabs, _activate, _beforeactive, _beforeunactive, _deactivate, _id, _instances, _name,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
_name = "tabs";
_instances = [];
_id = 0;
Tabs = (function(_super) {
__extends(Tabs, _super);
Tabs.prototype._name = _name;
Tabs.prototype._instances = _instances;
function Tabs(tab, options) {
var _options;
this.tab = tab;
this.options = options;
this.$tab = $(this.tab);
this._id = _id++;
_options = {
toggle: this.$tab.data('toggle') || 'tabs',
group: this.$tab.data('group') || null,
target: this.$tab.data('target') || null,
event: "click",
active: 0,
beforeactive: function() {},
onactive: function() {},
beforeunactive: function() {},
onunactive: function() {}
};
this.options = this._merge(_options, this.options);
this.beforeactive = this.options.beforeactive;
this.onactive = this.options.onactive;
this.beforeunactive = this.options.beforeunactive;
this.onunactive = this.options.onunactive;
this.$tab.on(this.options.event, (function(_this) {
return function() {
if (!_this.$tab.hasClass('_active_')) {
return _this.activate();
}
};
})(this));
this.$content = $(document).find(this.options.target);
this.$content.hide();
Tabs.__super__.constructor.call(this, this.$tab, this.options);
}
Tabs.prototype._setOptions = function(options) {
var key, value;
for (key in options) {
value = options[key];
if (this.options[key] == null) {
return console.error("Maxmertkit Tabs. You're trying to set unpropriate option.");
}
switch (key) {
case 'event':
this.$tab.off("" + this.options.event + "." + this._name);
this.options.event = value;
this.$tab.on("" + this.options.event + "." + this._name, (function(_this) {
return function() {
if (_this.$tab.hasClass('_active_')) {
return _this.deactivate();
} else {
return _this.activate();
}
};
})(this));
break;
case 'target':
this.options.target = value;
this.$content = $(document).find(this.options.target);
break;
default:
this.options[key] = value;
if (typeof value === 'function') {
this[key] = this.options[key];
}
}
}
};
Tabs.prototype._afterConstruct = function() {
var i;
i = 0;
while (i < this._instances && this._instances[i].group !== this.options.group) {
i++;
}
return this._instances[i].activate();
};
Tabs.prototype.destroy = function() {
this.$tab.off("." + this._name);
return Tabs.__super__.destroy.apply(this, arguments);
};
Tabs.prototype.activate = function() {
return _beforeactive.call(this);
};
Tabs.prototype.deactivate = function() {
if (this.$tab.hasClass('_active_')) {
return _beforeunactive.call(this);
}
};
Tabs.prototype.disable = function() {
return this.$tab.toggleClass('_disabled_');
};
return Tabs;
})(MaxmertkitHelpers);
_beforeactive = function() {
var deferred;
if (this.options.selfish) {
this._selfish();
}
if (this.beforeactive != null) {
try {
deferred = this.beforeactive.call(this.$tab);
return deferred.done((function(_this) {
return function() {
return _activate.call(_this);
};
})(this)).fail((function(_this) {
return function() {
return _this.$tab.trigger("fail." + _this._name);
};
})(this));
} catch (_error) {
return _activate.call(this);
}
} else {
return _activate.call(this);
}
};
_activate = function() {
var tab, _i, _len, _ref;
_ref = this._instances;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
tab = _ref[_i];
if (this._id !== tab._id && tab.options.group === this.options.group) {
tab.deactivate();
}
}
this.$tab.addClass('_active_');
this.$tab.trigger("activated." + this._name);
this.$content.show();
if (this.onactive != null) {
try {
return this.onactive.call(this.$tab);
} catch (_error) {}
}
};
_beforeunactive = function() {
var deferred;
if (this.beforeunactive != null) {
try {
deferred = this.beforeunactive.call(this.$tab);
return deferred.done((function(_this) {
return function() {
return _deactivate.call(_this);
};
})(this)).fail((function(_this) {
return function() {
return _this.$tab.trigger("fail." + _this._name);
};
})(this));
} catch (_error) {
return _deactivate.call(this);
}
} else {
return _deactivate.call(this);
}
};
_deactivate = function() {
this.$tab.removeClass('_active_');
this.$tab.trigger("deactivated." + this._name);
this.$content.hide();
if (this.onunactive != null) {
try {
return this.onunactive.call(this.$tab);
} catch (_error) {}
}
};
$.fn[_name] = function(options) {
return this.each(function() {
if (!$.data(this, "kit-" + _name)) {
$.data(this, "kit-" + _name, new Tabs(this, options));
} else {
if (typeof options === "object") {
$.data(this, "kit-" + _name)._setOptions(options);
} else {
if (typeof options === "string" && options.charAt(0) !== "_") {
$.data(this, "kit-" + _name)[options];
} else {
console.error("Maxmertkit Tabs. You passed into the " + _name + " something wrong.");
}
}
}
});
};
}).call(this);
|
/*! Select2 4.0.0-rc.2 | https://github.com/select2/select2/blob/master/LICENSE.md */
(function(){if(jQuery&&jQuery.fn&&jQuery.fn.select2&&jQuery.fn.select2.amd)var e=jQuery.fn.select2.amd;return e.define("select2/i18n/az",[],function(){return{inputTooLong:function(e){var t=e.input.length-e.maximum;return t+" simvol silin"},inputTooShort:function(e){var t=e.minimum-e.input.length;return t+" simvol daxil edin"},loadingMore:function(){return"Daha çox nəticə yüklənir…"},maximumSelected:function(e){return"Sadəcə "+e.maximum+" element seçə bilərsiniz"},noResults:function(){return"Nəticə tapılmadı"},searching:function(){return"Axtarılır…"}}}),{define:e.define,require:e.require}})(); |
//// Copyright (c) Microsoft Corporation. All rights reserved
(function () {
"use strict";
var page = WinJS.UI.Pages.define("/html/crossfade.html", {
ready: function (element, options) {
runAnimation.addEventListener("click", runCrossfadeAnimation, false);
element2.style.opacity = "0";
}
});
function runCrossfadeAnimation() {
var incoming;
var outgoing;
// Set incoming and outgoing elements
if (element1.style.opacity === "0") {
incoming = element1;
outgoing = element2;
} else {
incoming = element2;
outgoing = element1;
}
// Run crossfade animation
WinJS.UI.Animation.crossFade(incoming, outgoing);
}
})();
|
module.exports = []
|
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"\u13cc\u13be\u13b4",
"\u13d2\u13af\u13f1\u13a2\u13d7\u13e2"
],
"DAY": [
"\u13a4\u13be\u13d9\u13d3\u13c6\u13cd\u13ac",
"\u13a4\u13be\u13d9\u13d3\u13c9\u13c5\u13af",
"\u13d4\u13b5\u13c1\u13a2\u13a6",
"\u13e6\u13a2\u13c1\u13a2\u13a6",
"\u13c5\u13a9\u13c1\u13a2\u13a6",
"\u13e7\u13be\u13a9\u13b6\u13cd\u13d7",
"\u13a4\u13be\u13d9\u13d3\u13c8\u13d5\u13be"
],
"MONTH": [
"\u13a4\u13c3\u13b8\u13d4\u13c5",
"\u13a7\u13a6\u13b5",
"\u13a0\u13c5\u13f1",
"\u13a7\u13ec\u13c2",
"\u13a0\u13c2\u13cd\u13ac\u13d8",
"\u13d5\u13ad\u13b7\u13f1",
"\u13ab\u13f0\u13c9\u13c2",
"\u13a6\u13b6\u13c2",
"\u13da\u13b5\u13cd\u13d7",
"\u13da\u13c2\u13c5\u13d7",
"\u13c5\u13d3\u13d5\u13c6",
"\u13a5\u13cd\u13a9\u13f1"
],
"SHORTDAY": [
"\u13c6\u13cd\u13ac",
"\u13c9\u13c5\u13af",
"\u13d4\u13b5\u13c1",
"\u13e6\u13a2\u13c1",
"\u13c5\u13a9\u13c1",
"\u13e7\u13be\u13a9",
"\u13c8\u13d5\u13be"
],
"SHORTMONTH": [
"\u13a4\u13c3",
"\u13a7\u13a6",
"\u13a0\u13c5",
"\u13a7\u13ec",
"\u13a0\u13c2",
"\u13d5\u13ad",
"\u13ab\u13f0",
"\u13a6\u13b6",
"\u13da\u13b5",
"\u13da\u13c2",
"\u13c5\u13d3",
"\u13a5\u13cd"
],
"fullDate": "EEEE, MMMM d, y",
"longDate": "MMMM d, y",
"medium": "MMM d, y h:mm:ss a",
"mediumDate": "MMM d, y",
"mediumTime": "h:mm:ss a",
"short": "M/d/yy h:mm a",
"shortDate": "M/d/yy",
"shortTime": "h:mm a"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "$",
"DECIMAL_SEP": ".",
"GROUP_SEP": ",",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "\u00a4-",
"negSuf": "",
"posPre": "\u00a4",
"posSuf": ""
}
]
},
"id": "chr-us",
"pluralCat": function(n, opt_precision) { if (n == 1) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]);
|
!function($){$.fn.datepicker.dates["sw"]={days:["Jumapili","Jumatatu","Jumanne","Jumatano","Alhamisi","Ijumaa","Jumamosi","Jumapili"],daysShort:["J2","J3","J4","J5","Alh","Ij","J1","J2"],daysMin:["2","3","4","5","A","I","1","2"],months:["Januari","Februari","Machi","Aprili","Mei","Juni","Julai","Agosti","Septemba","Oktoba","Novemba","Desemba"],monthsShort:["Jan","Feb","Mac","Apr","Mei","Jun","Jul","Ago","Sep","Okt","Nov","Des"],today:"Leo"}}(jQuery); |
YUI.add("lang/datatype-date-format_zh-Hans-CN",function(a){a.Intl.add("datatype-date-format","zh-Hans-CN",{"a":["周日","周一","周二","周三","周四","周五","周六"],"A":["星期日","星期一","星期二","星期三","星期四","星期五","星期六"],"b":["1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"],"B":["1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"],"c":"%Y年%b%d日%a%Z%p%l时%M分%S秒","p":["上午","下午"],"P":["上午","下午"],"x":"%y-%m-%d","X":"%p%l时%M分%S秒"});},"@VERSION@");YUI.add("lang/datatype-date_zh-Hans-CN",function(a){},"@VERSION@",{use:["lang/datatype-date-format_zh-Hans-CN"]});YUI.add("lang/datatype_zh-Hans-CN",function(a){},"@VERSION@",{use:["lang/datatype-date_zh-Hans-CN"]}); |
/**
* angular-strap
* @version v2.2.1 - 2015-05-15
* @link http://mgcrea.github.io/angular-strap
* @author Olivier Louvignes <[email protected]> (https://github.com/mgcrea)
* @license MIT License, http://www.opensource.org/licenses/MIT
*/
'use strict';
angular.module('mgcrea.ngStrap.affix', [ 'mgcrea.ngStrap.helpers.dimensions', 'mgcrea.ngStrap.helpers.debounce' ]).provider('$affix', function() {
var defaults = this.defaults = {
offsetTop: 'auto',
inlineStyles: true
};
this.$get = [ '$window', 'debounce', 'dimensions', function($window, debounce, dimensions) {
var bodyEl = angular.element($window.document.body);
var windowEl = angular.element($window);
function AffixFactory(element, config) {
var $affix = {};
var options = angular.extend({}, defaults, config);
var targetEl = options.target;
var reset = 'affix affix-top affix-bottom', setWidth = false, initialAffixTop = 0, initialOffsetTop = 0, offsetTop = 0, offsetBottom = 0, affixed = null, unpin = null;
var parent = element.parent();
if (options.offsetParent) {
if (options.offsetParent.match(/^\d+$/)) {
for (var i = 0; i < options.offsetParent * 1 - 1; i++) {
parent = parent.parent();
}
} else {
parent = angular.element(options.offsetParent);
}
}
$affix.init = function() {
this.$parseOffsets();
initialOffsetTop = dimensions.offset(element[0]).top + initialAffixTop;
setWidth = !element[0].style.width;
targetEl.on('scroll', this.checkPosition);
targetEl.on('click', this.checkPositionWithEventLoop);
windowEl.on('resize', this.$debouncedOnResize);
this.checkPosition();
this.checkPositionWithEventLoop();
};
$affix.destroy = function() {
targetEl.off('scroll', this.checkPosition);
targetEl.off('click', this.checkPositionWithEventLoop);
windowEl.off('resize', this.$debouncedOnResize);
};
$affix.checkPositionWithEventLoop = function() {
setTimeout($affix.checkPosition, 1);
};
$affix.checkPosition = function() {
var scrollTop = getScrollTop();
var position = dimensions.offset(element[0]);
var elementHeight = dimensions.height(element[0]);
var affix = getRequiredAffixClass(unpin, position, elementHeight);
if (affixed === affix) return;
affixed = affix;
element.removeClass(reset).addClass('affix' + (affix !== 'middle' ? '-' + affix : ''));
if (affix === 'top') {
unpin = null;
if (setWidth) {
element.css('width', '');
}
if (options.inlineStyles) {
element.css('position', options.offsetParent ? '' : 'relative');
element.css('top', '');
}
} else if (affix === 'bottom') {
if (options.offsetUnpin) {
unpin = -(options.offsetUnpin * 1);
} else {
unpin = position.top - scrollTop;
}
if (setWidth) {
element.css('width', '');
}
if (options.inlineStyles) {
element.css('position', options.offsetParent ? '' : 'relative');
element.css('top', options.offsetParent ? '' : bodyEl[0].offsetHeight - offsetBottom - elementHeight - initialOffsetTop + 'px');
}
} else {
unpin = null;
if (setWidth) {
element.css('width', element[0].offsetWidth + 'px');
}
if (options.inlineStyles) {
element.css('position', 'fixed');
element.css('top', initialAffixTop + 'px');
}
}
};
$affix.$onResize = function() {
$affix.$parseOffsets();
$affix.checkPosition();
};
$affix.$debouncedOnResize = debounce($affix.$onResize, 50);
$affix.$parseOffsets = function() {
var initialPosition = element.css('position');
if (options.inlineStyles) {
element.css('position', options.offsetParent ? '' : 'relative');
}
if (options.offsetTop) {
if (options.offsetTop === 'auto') {
options.offsetTop = '+0';
}
if (options.offsetTop.match(/^[-+]\d+$/)) {
initialAffixTop = -options.offsetTop * 1;
if (options.offsetParent) {
offsetTop = dimensions.offset(parent[0]).top + options.offsetTop * 1;
} else {
offsetTop = dimensions.offset(element[0]).top - dimensions.css(element[0], 'marginTop', true) + options.offsetTop * 1;
}
} else {
offsetTop = options.offsetTop * 1;
}
}
if (options.offsetBottom) {
if (options.offsetParent && options.offsetBottom.match(/^[-+]\d+$/)) {
offsetBottom = getScrollHeight() - (dimensions.offset(parent[0]).top + dimensions.height(parent[0])) + options.offsetBottom * 1 + 1;
} else {
offsetBottom = options.offsetBottom * 1;
}
}
if (options.inlineStyles) {
element.css('position', initialPosition);
}
};
function getRequiredAffixClass(unpin, position, elementHeight) {
var scrollTop = getScrollTop();
var scrollHeight = getScrollHeight();
if (scrollTop <= offsetTop) {
return 'top';
} else if (unpin !== null && scrollTop + unpin <= position.top) {
return 'middle';
} else if (offsetBottom !== null && position.top + elementHeight + initialAffixTop >= scrollHeight - offsetBottom) {
return 'bottom';
} else {
return 'middle';
}
}
function getScrollTop() {
return targetEl[0] === $window ? $window.pageYOffset : targetEl[0].scrollTop;
}
function getScrollHeight() {
return targetEl[0] === $window ? $window.document.body.scrollHeight : targetEl[0].scrollHeight;
}
$affix.init();
return $affix;
}
return AffixFactory;
} ];
}).directive('bsAffix', [ '$affix', '$window', function($affix, $window) {
return {
restrict: 'EAC',
require: '^?bsAffixTarget',
link: function postLink(scope, element, attr, affixTarget) {
var options = {
scope: scope,
target: affixTarget ? affixTarget.$element : angular.element($window)
};
angular.forEach([ 'offsetTop', 'offsetBottom', 'offsetParent', 'offsetUnpin', 'inlineStyles' ], function(key) {
if (angular.isDefined(attr[key])) {
var option = attr[key];
if (/true/i.test(option)) option = true;
if (/false/i.test(option)) option = false;
options[key] = option;
}
});
var affix = $affix(element, options);
scope.$on('$destroy', function() {
affix && affix.destroy();
options = null;
affix = null;
});
}
};
} ]).directive('bsAffixTarget', function() {
return {
controller: [ '$element', function($element) {
this.$element = $element;
} ]
};
}); |
YUI.add('swf', function (Y, NAME) {
/**
* Embed a Flash applications in a standard manner and communicate with it
* via External Interface.
* @module swf
*/
var Event = Y.Event,
SWFDetect = Y.SWFDetect,
Lang = Y.Lang,
uA = Y.UA,
Node = Y.Node,
Escape = Y.Escape,
// private
FLASH_CID = "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000",
FLASH_TYPE = "application/x-shockwave-flash",
FLASH_VER = "10.0.22",
EXPRESS_INSTALL_URL = "http://fpdownload.macromedia.com/pub/flashplayer/update/current/swf/autoUpdater.swf?" + Math.random(),
EVENT_HANDLER = "SWF.eventHandler",
possibleAttributes = {align:"", allowFullScreen:"", allowNetworking:"", allowScriptAccess:"", base:"", bgcolor:"", loop:"", menu:"", name:"", play: "", quality:"", salign:"", scale:"", tabindex:"", wmode:""};
/**
* The SWF utility is a tool for embedding Flash applications in HTML pages.
* @module swf
* @title SWF Utility
* @requires event-custom, node, swfdetect
*/
/**
* Creates the SWF instance and keeps the configuration data
*
* @class SWF
* @augments Y.Event.Target
* @constructor
* @param {String|HTMLElement} id The id of the element, or the element itself that the SWF will be inserted into.
* The width and height of the SWF will be set to the width and height of this container element.
* @param {String} swfURL The URL of the SWF to be embedded into the page.
* @param {Object} p_oAttributes (optional) Configuration parameters for the Flash application and values for Flashvars
* to be passed to the SWF. The p_oAttributes object allows the following additional properties:
* <dl>
* <dt>version : String</dt>
* <dd>The minimum version of Flash required on the user's machine.</dd>
* <dt>fixedAttributes : Object</dt>
* <dd>An object literal containing one or more of the following String keys and their values: <code>align,
* allowFullScreen, allowNetworking, allowScriptAccess, base, bgcolor, menu, name, quality, salign, scale,
* tabindex, wmode.</code> event from the thumb</dd>
* </dl>
*/
function SWF (p_oElement /*:String*/, swfURL /*:String*/, p_oAttributes /*:Object*/ ) {
this._id = Y.guid("yuiswf");
var _id = this._id;
var oElement = Node.one(p_oElement);
var p_oAttributes = p_oAttributes || {};
var flashVersion = p_oAttributes.version || FLASH_VER;
var flashVersionSplit = (flashVersion + '').split(".");
var isFlashVersionRight = SWFDetect.isFlashVersionAtLeast(parseInt(flashVersionSplit[0], 10), parseInt(flashVersionSplit[1], 10), parseInt(flashVersionSplit[2], 10));
var canExpressInstall = (SWFDetect.isFlashVersionAtLeast(8,0,0));
var shouldExpressInstall = canExpressInstall && !isFlashVersionRight && p_oAttributes.useExpressInstall;
var flashURL = (shouldExpressInstall)?EXPRESS_INSTALL_URL:swfURL;
var objstring = '<object ';
var w, h;
var flashvarstring = "yId=" + Y.id + "&YUISwfId=" + _id + "&YUIBridgeCallback=" + EVENT_HANDLER + "&allowedDomain=" + document.location.hostname;
Y.SWF._instances[_id] = this;
if (oElement && (isFlashVersionRight || shouldExpressInstall) && flashURL) {
objstring += 'id="' + _id + '" ';
if (uA.ie) {
objstring += 'classid="' + FLASH_CID + '" ';
} else {
objstring += 'type="' + FLASH_TYPE + '" data="' + Escape.html(flashURL) + '" ';
}
w = "100%";
h = "100%";
objstring += 'width="' + w + '" height="' + h + '">';
if (uA.ie) {
objstring += '<param name="movie" value="' + Escape.html(flashURL) + '"/>';
}
for (var attribute in p_oAttributes.fixedAttributes) {
if (possibleAttributes.hasOwnProperty(attribute)) {
objstring += '<param name="' + Escape.html(attribute) + '" value="' + Escape.html(p_oAttributes.fixedAttributes[attribute]) + '"/>';
}
}
for (var flashvar in p_oAttributes.flashVars) {
var fvar = p_oAttributes.flashVars[flashvar];
if (Lang.isString(fvar)) {
flashvarstring += "&" + Escape.html(flashvar) + "=" + Escape.html(encodeURIComponent(fvar));
}
}
if (flashvarstring) {
objstring += '<param name="flashVars" value="' + flashvarstring + '"/>';
}
objstring += "</object>";
//using innerHTML as setHTML/setContent causes some issues with ExternalInterface for IE versions of the player
oElement.set("innerHTML", objstring);
this._swf = Node.one("#" + _id);
} else {
/**
* Fired when the Flash player version on the user's machine is
* below the required value.
*
* @event wrongflashversion
*/
var event = {};
event.type = "wrongflashversion";
this.publish("wrongflashversion", {fireOnce:true});
this.fire("wrongflashversion", event);
}
}
/**
* @private
* The static collection of all instances of the SWFs on the page.
* @property _instances
* @type Object
*/
SWF._instances = SWF._instances || {};
/**
* @private
* Handles an event coming from within the SWF and delegate it
* to a specific instance of SWF.
* @method eventHandler
* @param swfid {String} the id of the SWF dispatching the event
* @param event {Object} the event being transmitted.
*/
SWF.eventHandler = function (swfid, event) {
SWF._instances[swfid]._eventHandler(event);
};
SWF.prototype = {
/**
* @private
* Propagates a specific event from Flash to JS.
* @method _eventHandler
* @param event {Object} The event to be propagated from Flash.
*/
_eventHandler: function(event) {
if (event.type === "swfReady") {
this.publish("swfReady", {fireOnce:true});
this.fire("swfReady", event);
} else if(event.type === "log") {
} else {
this.fire(event.type, event);
}
},
/**
* Calls a specific function exposed by the SWF's
* ExternalInterface.
* @method callSWF
* @param func {String} the name of the function to call
* @param args {Array} the set of arguments to pass to the function.
*/
callSWF: function (func, args)
{
if (!args) {
args= [];
}
if (this._swf._node[func]) {
return(this._swf._node[func].apply(this._swf._node, args));
} else {
return null;
}
},
/**
* Public accessor to the unique name of the SWF instance.
*
* @method toString
* @return {String} Unique name of the SWF instance.
*/
toString: function()
{
return "SWF " + this._id;
}
};
Y.augment(SWF, Y.EventTarget);
Y.SWF = SWF;
}, '@VERSION@', {"requires": ["event-custom", "node", "swfdetect", "escape"]});
|
// FILE H TWO
module.exports = 2
|
/**
* The YUI module contains the components required for building the YUI seed
* file. This includes the script loading mechanism, a simple queue, and
* the core utilities for the library.
* @module yui
* @submodule yui-base
*/
if (typeof YUI != 'undefined') {
YUI._YUI = YUI;
}
/**
The YUI global namespace object. If YUI is already defined, the
existing YUI object will not be overwritten so that defined
namespaces are preserved. It is the constructor for the object
the end user interacts with. As indicated below, each instance
has full custom event support, but only if the event system
is available. This is a self-instantiable factory function. You
can invoke it directly like this:
YUI().use('*', function(Y) {
// ready
});
But it also works like this:
var Y = YUI();
@class YUI
@constructor
@global
@uses EventTarget
@param o* {Object} 0..n optional configuration objects. these values
are store in Y.config. See <a href="config.html">Config</a> for the list of supported
properties.
*/
/*global YUI*/
/*global YUI_config*/
var YUI = function() {
var i = 0,
Y = this,
args = arguments,
l = args.length,
instanceOf = function(o, type) {
return (o && o.hasOwnProperty && (o instanceof type));
},
gconf = (typeof YUI_config !== 'undefined') && YUI_config;
if (!(instanceOf(Y, YUI))) {
Y = new YUI();
} else {
// set up the core environment
Y._init();
/**
YUI.GlobalConfig is a master configuration that might span
multiple contexts in a non-browser environment. It is applied
first to all instances in all contexts.
@property YUI.GlobalConfig
@type {Object}
@global
@example
YUI.GlobalConfig = {
filter: 'debug'
};
YUI().use('node', function(Y) {
//debug files used here
});
YUI({
filter: 'min'
}).use('node', function(Y) {
//min files used here
});
*/
if (YUI.GlobalConfig) {
Y.applyConfig(YUI.GlobalConfig);
}
/**
YUI_config is a page-level config. It is applied to all
instances created on the page. This is applied after
YUI.GlobalConfig, and before the instance level configuration
objects.
@global
@property YUI_config
@type {Object}
@example
//Single global var to include before YUI seed file
YUI_config = {
filter: 'debug'
};
YUI().use('node', function(Y) {
//debug files used here
});
YUI({
filter: 'min'
}).use('node', function(Y) {
//min files used here
});
*/
if (gconf) {
Y.applyConfig(gconf);
}
// bind the specified additional modules for this instance
if (!l) {
Y._setup();
}
}
if (l) {
// Each instance can accept one or more configuration objects.
// These are applied after YUI.GlobalConfig and YUI_Config,
// overriding values set in those config files if there is a '
// matching property.
for (; i < l; i++) {
Y.applyConfig(args[i]);
}
Y._setup();
}
Y.instanceOf = instanceOf;
return Y;
};
(function() {
var proto, prop,
VERSION = '@VERSION@',
PERIOD = '.',
BASE = 'http://yui.yahooapis.com/',
DOC_LABEL = 'yui3-js-enabled',
NOOP = function() {},
SLICE = Array.prototype.slice,
APPLY_TO_AUTH = { 'io.xdrReady': 1, // the functions applyTo
'io.xdrResponse': 1, // can call. this should
'SWF.eventHandler': 1 }, // be done at build time
hasWin = (typeof window != 'undefined'),
win = (hasWin) ? window : null,
doc = (hasWin) ? win.document : null,
docEl = doc && doc.documentElement,
docClass = docEl && docEl.className,
instances = {},
time = new Date().getTime(),
add = function(el, type, fn, capture) {
if (el && el.addEventListener) {
el.addEventListener(type, fn, capture);
} else if (el && el.attachEvent) {
el.attachEvent('on' + type, fn);
}
},
remove = function(el, type, fn, capture) {
if (el && el.removeEventListener) {
// this can throw an uncaught exception in FF
try {
el.removeEventListener(type, fn, capture);
} catch (ex) {}
} else if (el && el.detachEvent) {
el.detachEvent('on' + type, fn);
}
},
handleLoad = function() {
YUI.Env.windowLoaded = true;
YUI.Env.DOMReady = true;
if (hasWin) {
remove(window, 'load', handleLoad);
}
},
getLoader = function(Y, o) {
var loader = Y.Env._loader;
if (loader) {
//loader._config(Y.config);
loader.ignoreRegistered = false;
loader.onEnd = null;
loader.data = null;
loader.required = [];
loader.loadType = null;
} else {
loader = new Y.Loader(Y.config);
Y.Env._loader = loader;
}
return loader;
},
clobber = function(r, s) {
for (var i in s) {
if (s.hasOwnProperty(i)) {
r[i] = s[i];
}
}
},
ALREADY_DONE = { success: true };
// Stamp the documentElement (HTML) with a class of "yui-loaded" to
// enable styles that need to key off of JS being enabled.
if (docEl && docClass.indexOf(DOC_LABEL) == -1) {
if (docClass) {
docClass += ' ';
}
docClass += DOC_LABEL;
docEl.className = docClass;
}
if (VERSION.indexOf('@') > -1) {
VERSION = '3.3.0'; // dev time hack for cdn test
}
proto = {
/**
* Applies a new configuration object to the YUI instance config.
* This will merge new group/module definitions, and will also
* update the loader cache if necessary. Updating Y.config directly
* will not update the cache.
* @method applyConfig
* @param {Object} o the configuration object.
* @since 3.2.0
*/
applyConfig: function(o) {
o = o || NOOP;
var attr,
name,
// detail,
config = this.config,
mods = config.modules,
groups = config.groups,
rls = config.rls,
loader = this.Env._loader;
for (name in o) {
if (o.hasOwnProperty(name)) {
attr = o[name];
if (mods && name == 'modules') {
clobber(mods, attr);
} else if (groups && name == 'groups') {
clobber(groups, attr);
} else if (rls && name == 'rls') {
clobber(rls, attr);
} else if (name == 'win') {
config[name] = attr.contentWindow || attr;
config.doc = config[name].document;
} else if (name == '_yuid') {
// preserve the guid
} else {
config[name] = attr;
}
}
}
if (loader) {
loader._config(o);
}
},
/**
* Old way to apply a config to the instance (calls `applyConfig` under the hood)
* @private
* @method _config
* @param {Object} o The config to apply
*/
_config: function(o) {
this.applyConfig(o);
},
/**
* Initialize this YUI instance
* @private
* @method _init
*/
_init: function() {
var filter,
Y = this,
G_ENV = YUI.Env,
Env = Y.Env,
prop;
/**
* The version number of the YUI instance.
* @property version
* @type string
*/
Y.version = VERSION;
if (!Env) {
Y.Env = {
mods: {}, // flat module map
versions: {}, // version module map
base: BASE,
cdn: BASE + VERSION + '/build/',
// bootstrapped: false,
_idx: 0,
_used: {},
_attached: {},
_missed: [],
_yidx: 0,
_uidx: 0,
_guidp: 'y',
_loaded: {},
// serviced: {},
// Regex in English:
// I'll start at the \b(simpleyui).
// 1. Look in the test string for "simpleyui" or "yui" or
// "yui-base" or "yui-rls" or "yui-foobar" that comes after a word break. That is, it
// can't match "foyui" or "i_heart_simpleyui". This can be anywhere in the string.
// 2. After #1 must come a forward slash followed by the string matched in #1, so
// "yui-base/yui-base" or "simpleyui/simpleyui" or "yui-pants/yui-pants".
// 3. The second occurence of the #1 token can optionally be followed by "-debug" or "-min",
// so "yui/yui-min", "yui/yui-debug", "yui-base/yui-base-debug". NOT "yui/yui-tshirt".
// 4. This is followed by ".js", so "yui/yui.js", "simpleyui/simpleyui-min.js"
// 0. Going back to the beginning, now. If all that stuff in 1-4 comes after a "?" in the string,
// then capture the junk between the LAST "&" and the string in 1-4. So
// "blah?foo/yui/yui.js" will capture "foo/" and "blah?some/thing.js&3.3.0/build/yui-rls/yui-rls.js"
// will capture "3.3.0/build/"
//
// Regex Exploded:
// (?:\? Find a ?
// (?:[^&]*&) followed by 0..n characters followed by an &
// * in fact, find as many sets of characters followed by a & as you can
// ([^&]*) capture the stuff after the last & in \1
// )? but it's ok if all this ?junk&more_junk stuff isn't even there
// \b(simpleyui| after a word break find either the string "simpleyui" or
// yui(?:-\w+)? the string "yui" optionally followed by a -, then more characters
// ) and store the simpleyui or yui-* string in \2
// \/\2 then comes a / followed by the simpleyui or yui-* string in \2
// (?:-(min|debug))? optionally followed by "-min" or "-debug"
// .js and ending in ".js"
_BASE_RE: /(?:\?(?:[^&]*&)*([^&]*))?\b(simpleyui|yui(?:-\w+)?)\/\2(?:-(min|debug))?\.js/,
parseBasePath: function(src, pattern) {
var match = src.match(pattern),
path, filter;
if (match) {
path = RegExp.leftContext || src.slice(0, src.indexOf(match[0]));
// this is to set up the path to the loader. The file
// filter for loader should match the yui include.
filter = match[3];
// extract correct path for mixed combo urls
// http://yuilibrary.com/projects/yui3/ticket/2528423
if (match[1]) {
path += '?' + match[1];
}
path = {
filter: filter,
path: path
}
}
return path;
},
getBase: G_ENV && G_ENV.getBase ||
function(pattern) {
var nodes = (doc && doc.getElementsByTagName('script')) || [],
path = Env.cdn, parsed,
i, len, src;
for (i = 0, len = nodes.length; i < len; ++i) {
src = nodes[i].src;
if (src) {
parsed = Y.Env.parseBasePath(src, pattern);
if (parsed) {
filter = parsed.filter;
path = parsed.path;
break;
}
}
}
// use CDN default
return path;
}
};
Env = Y.Env;
Env._loaded[VERSION] = {};
if (G_ENV && Y !== YUI) {
Env._yidx = ++G_ENV._yidx;
Env._guidp = ('yui_' + VERSION + '_' +
Env._yidx + '_' + time).replace(/\./g, '_');
} else if (YUI._YUI) {
G_ENV = YUI._YUI.Env;
Env._yidx += G_ENV._yidx;
Env._uidx += G_ENV._uidx;
for (prop in G_ENV) {
if (!(prop in Env)) {
Env[prop] = G_ENV[prop];
}
}
delete YUI._YUI;
}
Y.id = Y.stamp(Y);
instances[Y.id] = Y;
}
Y.constructor = YUI;
// configuration defaults
Y.config = Y.config || {
win: win,
doc: doc,
debug: true,
useBrowserConsole: true,
throwFail: true,
bootstrap: true,
cacheUse: true,
fetchCSS: true,
use_rls: true,
rls_timeout: 2000
};
if (YUI.Env.rls_disabled) {
Y.config.use_rls = false;
}
Y.config.lang = Y.config.lang || 'en-US';
Y.config.base = YUI.config.base || Y.Env.getBase(Y.Env._BASE_RE);
if (!filter || (!('mindebug').indexOf(filter))) {
filter = 'min';
}
filter = (filter) ? '-' + filter : filter;
Y.config.loaderPath = YUI.config.loaderPath || 'loader/loader' + filter + '.js';
},
/**
* Finishes the instance setup. Attaches whatever modules were defined
* when the yui modules was registered.
* @method _setup
* @private
*/
_setup: function(o) {
var i, Y = this,
core = [],
mods = YUI.Env.mods,
extras = Y.config.core || ['get','features','intl-base','rls','yui-log','yui-later'];
for (i = 0; i < extras.length; i++) {
if (mods[extras[i]]) {
core.push(extras[i]);
}
}
Y._attach(['yui-base']);
Y._attach(core);
// Y.log(Y.id + ' initialized', 'info', 'yui');
},
/**
* Executes a method on a YUI instance with
* the specified id if the specified method is whitelisted.
* @method applyTo
* @param id {String} the YUI instance id.
* @param method {String} the name of the method to exectute.
* Ex: 'Object.keys'.
* @param args {Array} the arguments to apply to the method.
* @return {Object} the return value from the applied method or null.
*/
applyTo: function(id, method, args) {
if (!(method in APPLY_TO_AUTH)) {
this.log(method + ': applyTo not allowed', 'warn', 'yui');
return null;
}
var instance = instances[id], nest, m, i;
if (instance) {
nest = method.split('.');
m = instance;
for (i = 0; i < nest.length; i = i + 1) {
m = m[nest[i]];
if (!m) {
this.log('applyTo not found: ' + method, 'warn', 'yui');
}
}
return m.apply(instance, args);
}
return null;
},
/**
Registers a module with the YUI global. The easiest way to create a
first-class YUI module is to use the YUI component build tool.
http://yuilibrary.com/projects/builder
The build system will produce the `YUI.add` wrapper for you module, along
with any configuration info required for the module.
@method add
@param name {String} module name.
@param fn {Function} entry point into the module that is used to bind module to the YUI instance.
@param {YUI} fn.Y The YUI instance this module is executed in.
@param {String} fn.name The name of the module
@param version {String} version string.
@param details {Object} optional config data:
@param details.requires {Array} features that must be present before this module can be attached.
@param details.optional {Array} optional features that should be present if loadOptional
is defined. Note: modules are not often loaded this way in YUI 3,
but this field is still useful to inform the user that certain
features in the component will require additional dependencies.
@param details.use {Array} features that are included within this module which need to
be attached automatically when this module is attached. This
supports the YUI 3 rollup system -- a module with submodules
defined will need to have the submodules listed in the 'use'
config. The YUI component build tool does this for you.
@return {YUI} the YUI instance.
@example
YUI.add('davglass', function(Y, name) {
Y.davglass = function() {
alert('Dav was here!');
};
}, '3.4.0', { requires: ['yui-base', 'harley-davidson', 'mt-dew'] });
*/
add: function(name, fn, version, details) {
details = details || {};
var env = YUI.Env,
mod = {
name: name,
fn: fn,
version: version,
details: details
},
loader,
i, versions = env.versions;
env.mods[name] = mod;
versions[version] = versions[version] || {};
versions[version][name] = mod;
for (i in instances) {
if (instances.hasOwnProperty(i)) {
loader = instances[i].Env._loader;
if (loader) {
if (!loader.moduleInfo[name]) {
loader.addModule(details, name);
}
}
}
}
return this;
},
/**
* Executes the function associated with each required
* module, binding the module to the YUI instance.
* @method _attach
* @private
*/
_attach: function(r, moot) {
var i, name, mod, details, req, use, after,
mods = YUI.Env.mods,
aliases = YUI.Env.aliases,
Y = this, j,
done = Y.Env._attached,
len = r.length, loader;
//console.info('attaching: ' + r, 'info', 'yui');
for (i = 0; i < len; i++) {
if (!done[r[i]]) {
name = r[i];
mod = mods[name];
if (aliases && aliases[name]) {
Y._attach(aliases[name]);
continue;
}
if (!mod) {
loader = Y.Env._loader;
if (loader && loader.moduleInfo[name]) {
mod = loader.moduleInfo[name];
if (mod.use) {
moot = true;
}
}
// Y.log('no js def for: ' + name, 'info', 'yui');
//if (!loader || !loader.moduleInfo[name]) {
//if ((!loader || !loader.moduleInfo[name]) && !moot) {
if (!moot) {
if (name.indexOf('skin-') === -1) {
Y.Env._missed.push(name);
Y.message('NOT loaded: ' + name, 'warn', 'yui');
}
}
} else {
done[name] = true;
//Don't like this, but in case a mod was asked for once, then we fetch it
//We need to remove it from the missed list
for (j = 0; j < Y.Env._missed.length; j++) {
if (Y.Env._missed[j] === name) {
Y.message('Found: ' + name + ' (was reported as missing earlier)', 'warn', 'yui');
Y.Env._missed.splice(j, 1);
}
}
details = mod.details;
req = details.requires;
use = details.use;
after = details.after;
if (req) {
for (j = 0; j < req.length; j++) {
if (!done[req[j]]) {
if (!Y._attach(req)) {
return false;
}
break;
}
}
}
if (after) {
for (j = 0; j < after.length; j++) {
if (!done[after[j]]) {
if (!Y._attach(after, true)) {
return false;
}
break;
}
}
}
if (mod.fn) {
try {
mod.fn(Y, name);
} catch (e) {
Y.error('Attach error: ' + name, e, name);
return false;
}
}
if (use) {
for (j = 0; j < use.length; j++) {
if (!done[use[j]]) {
if (!Y._attach(use)) {
return false;
}
break;
}
}
}
}
}
}
return true;
},
/**
* Attaches one or more modules to the YUI instance. When this
* is executed, the requirements are analyzed, and one of
* several things can happen:
*
* * All requirements are available on the page -- The modules
* are attached to the instance. If supplied, the use callback
* is executed synchronously.
*
* * Modules are missing, the Get utility is not available OR
* the 'bootstrap' config is false -- A warning is issued about
* the missing modules and all available modules are attached.
*
* * Modules are missing, the Loader is not available but the Get
* utility is and boostrap is not false -- The loader is bootstrapped
* before doing the following....
*
* * Modules are missing and the Loader is available -- The loader
* expands the dependency tree and fetches missing modules. When
* the loader is finshed the callback supplied to use is executed
* asynchronously.
*
* @method use
* @param modules* {String} 1-n modules to bind (uses arguments array).
* @param *callback {Function} callback function executed when
* the instance has the required functionality. If included, it
* must be the last parameter.
*
* @example
* // loads and attaches dd and its dependencies
* YUI().use('dd', function(Y) {});
*
* // loads and attaches dd and node as well as all of their dependencies (since 3.4.0)
* YUI().use(['dd', 'node'], function(Y) {});
*
* // attaches all modules that are available on the page
* YUI().use('*', function(Y) {});
*
* // intrinsic YUI gallery support (since 3.1.0)
* YUI().use('gallery-yql', function(Y) {});
*
* // intrinsic YUI 2in3 support (since 3.1.0)
* YUI().use('yui2-datatable', function(Y) {});
*
* @return {YUI} the YUI instance.
*/
use: function() {
var args = SLICE.call(arguments, 0),
callback = args[args.length - 1],
Y = this,
i = 0,
name,
Env = Y.Env,
provisioned = true;
// The last argument supplied to use can be a load complete callback
if (Y.Lang.isFunction(callback)) {
args.pop();
} else {
callback = null;
}
if (Y.Lang.isArray(args[0])) {
args = args[0];
}
if (Y.config.cacheUse) {
while ((name = args[i++])) {
if (!Env._attached[name]) {
provisioned = false;
break;
}
}
if (provisioned) {
if (args.length) {
Y.log('already provisioned: ' + args, 'info', 'yui');
}
Y._notify(callback, ALREADY_DONE, args);
return Y;
}
}
if (Y.config.cacheUse) {
while ((name = args[i++])) {
if (!Env._attached[name]) {
provisioned = false;
break;
}
}
if (provisioned) {
if (args.length) {
Y.log('already provisioned: ' + args, 'info', 'yui');
}
Y._notify(callback, ALREADY_DONE, args);
return Y;
}
}
if (Y._loading) {
Y._useQueue = Y._useQueue || new Y.Queue();
Y._useQueue.add([args, callback]);
} else {
Y._use(args, function(Y, response) {
Y._notify(callback, response, args);
});
}
return Y;
},
/**
* Notify handler from Loader for attachment/load errors
* @method _notify
* @param callback {Function} The callback to pass to the `Y.config.loadErrorFn`
* @param response {Object} The response returned from Loader
* @param args {Array} The aruments passed from Loader
* @private
*/
_notify: function(callback, response, args) {
if (!response.success && this.config.loadErrorFn) {
this.config.loadErrorFn.call(this, this, callback, response, args);
} else if (callback) {
try {
callback(this, response);
} catch (e) {
this.error('use callback error', e, args);
}
}
},
/**
* This private method is called from the `use` method queue. To ensure that only one set of loading
* logic is performed at a time.
* @method _use
* @private
* @param args* {String} 1-n modules to bind (uses arguments array).
* @param *callback {Function} callback function executed when
* the instance has the required functionality. If included, it
* must be the last parameter.
*/
_use: function(args, callback) {
if (!this.Array) {
this._attach(['yui-base']);
}
var len, loader, handleBoot, handleRLS,
Y = this,
G_ENV = YUI.Env,
mods = G_ENV.mods,
Env = Y.Env,
used = Env._used,
queue = G_ENV._loaderQueue,
firstArg = args[0],
YArray = Y.Array,
config = Y.config,
boot = config.bootstrap,
missing = [],
r = [],
ret = true,
fetchCSS = config.fetchCSS,
process = function(names, skip) {
if (!names.length) {
return;
}
YArray.each(names, function(name) {
// add this module to full list of things to attach
if (!skip) {
r.push(name);
}
// only attach a module once
if (used[name]) {
return;
}
var m = mods[name], req, use;
if (m) {
used[name] = true;
req = m.details.requires;
use = m.details.use;
} else {
// CSS files don't register themselves, see if it has
// been loaded
if (!G_ENV._loaded[VERSION][name]) {
missing.push(name);
} else {
used[name] = true; // probably css
}
}
// make sure requirements are attached
if (req && req.length) {
process(req);
}
// make sure we grab the submodule dependencies too
if (use && use.length) {
process(use, 1);
}
});
},
handleLoader = function(fromLoader) {
var response = fromLoader || {
success: true,
msg: 'not dynamic'
},
redo, origMissing,
ret = true,
data = response.data;
Y._loading = false;
if (data) {
origMissing = missing;
missing = [];
r = [];
process(data);
redo = missing.length;
if (redo) {
if (missing.sort().join() ==
origMissing.sort().join()) {
redo = false;
}
}
}
if (redo && data) {
Y._loading = false;
Y._use(args, function() {
Y.log('Nested use callback: ' + data, 'info', 'yui');
if (Y._attach(data)) {
Y._notify(callback, response, data);
}
});
} else {
if (data) {
// Y.log('attaching from loader: ' + data, 'info', 'yui');
ret = Y._attach(data);
}
if (ret) {
Y._notify(callback, response, args);
}
}
if (Y._useQueue && Y._useQueue.size() && !Y._loading) {
Y._use.apply(Y, Y._useQueue.next());
}
};
// Y.log(Y.id + ': use called: ' + a + ' :: ' + callback, 'info', 'yui');
// YUI().use('*'); // bind everything available
if (firstArg === '*') {
ret = Y._attach(Y.Object.keys(mods));
if (ret) {
handleLoader();
}
return Y;
}
// Y.log('before loader requirements: ' + args, 'info', 'yui');
// use loader to expand dependencies and sort the
// requirements if it is available.
if (boot && Y.Loader && args.length) {
loader = getLoader(Y);
loader.require(args);
loader.ignoreRegistered = true;
loader.calculate(null, (fetchCSS) ? null : 'js');
args = loader.sorted;
}
// process each requirement and any additional requirements
// the module metadata specifies
process(args);
len = missing.length;
if (len) {
missing = Y.Object.keys(YArray.hash(missing));
len = missing.length;
Y.log('Modules missing: ' + missing + ', ' + missing.length, 'info', 'yui');
}
// dynamic load
if (boot && len && Y.Loader) {
// Y.log('Using loader to fetch missing deps: ' + missing, 'info', 'yui');
Y.log('Using Loader', 'info', 'yui');
Y._loading = true;
loader = getLoader(Y);
loader.onEnd = handleLoader;
loader.context = Y;
loader.data = args;
loader.ignoreRegistered = false;
loader.require(args);
loader.insert(null, (fetchCSS) ? null : 'js');
// loader.partial(missing, (fetchCSS) ? null : 'js');
} else if (len && Y.config.use_rls && !YUI.Env.rls_enabled) {
G_ENV._rls_queue = G_ENV._rls_queue || new Y.Queue();
// server side loader service
handleRLS = function(instance, argz) {
var rls_end = function(o) {
handleLoader(o);
instance.rls_advance();
},
rls_url = instance._rls(argz);
if (rls_url) {
Y.log('Fetching RLS url', 'info', 'rls');
instance.rls_oncomplete(function(o) {
rls_end(o);
});
instance.Get.script(rls_url, {
data: argz,
timeout: instance.config.rls_timeout,
onFailure: instance.rls_handleFailure,
onTimeout: instance.rls_handleTimeout
});
} else {
rls_end({
success: true,
data: argz
});
}
};
G_ENV._rls_queue.add(function() {
Y.log('executing queued rls request', 'info', 'rls');
G_ENV._rls_in_progress = true;
Y.rls_callback = callback;
Y.rls_locals(Y, args, handleRLS);
});
if (!G_ENV._rls_in_progress && G_ENV._rls_queue.size()) {
G_ENV._rls_queue.next()();
}
} else if (boot && len && Y.Get && !Env.bootstrapped) {
Y._loading = true;
handleBoot = function() {
Y._loading = false;
queue.running = false;
Env.bootstrapped = true;
G_ENV._bootstrapping = false;
if (Y._attach(['loader'])) {
Y._use(args, callback);
}
};
if (G_ENV._bootstrapping) {
Y.log('Waiting for loader', 'info', 'yui');
queue.add(handleBoot);
} else {
G_ENV._bootstrapping = true;
Y.log('Fetching loader: ' + config.base + config.loaderPath, 'info', 'yui');
Y.Get.script(config.base + config.loaderPath, {
onEnd: handleBoot
});
}
} else {
Y.log('Attaching available dependencies: ' + args, 'info', 'yui');
ret = Y._attach(args);
if (ret) {
handleLoader();
}
}
return Y;
},
/**
Adds a namespace object onto the YUI global if called statically:
// creates YUI.your.namespace.here as nested objects
YUI.namespace("your.namespace.here");
If called as an instance method on the YUI instance, it creates the
namespace on the instance:
// creates Y.property.package
Y.namespace("property.package");
Dots in the input string cause `namespace` to create nested objects for
each token. If any part of the requested namespace already exists, the
current object will be left in place. This allows multiple calls to
`namespace` to preserve existing namespaced properties.
If the first token in the namespace string is "YAHOO", the token is
discarded.
Be careful when naming packages. Reserved words may work in some browsers
and not others. For instance, the following will fail in some browsers:
Y.namespace("really.long.nested.namespace");
This fails because `long` is a future reserved word in ECMAScript
@method namespace
@param {String[]} namespace* 1-n namespaces to create.
@return {Object} A reference to the last namespace object created.
**/
namespace: function() {
var a = arguments, o = this, i = 0, j, d, arg;
for (; i < a.length; i++) {
// d = ('' + a[i]).split('.');
arg = a[i];
if (arg.indexOf(PERIOD)) {
d = arg.split(PERIOD);
for (j = (d[0] == 'YAHOO') ? 1 : 0; j < d.length; j++) {
o[d[j]] = o[d[j]] || {};
o = o[d[j]];
}
} else {
o[arg] = o[arg] || {};
}
}
return o;
},
// this is replaced if the log module is included
log: NOOP,
message: NOOP,
// this is replaced if the dump module is included
dump: function (o) { return ''+o; },
/**
* Report an error. The reporting mechanism is controled by
* the `throwFail` configuration attribute. If throwFail is
* not specified, the message is written to the Logger, otherwise
* a JS error is thrown
* @method error
* @param msg {String} the error message.
* @param e {Error|String} Optional JS error that was caught, or an error string.
* @param data Optional additional info
* and `throwFail` is specified, this error will be re-thrown.
* @return {YUI} this YUI instance.
*/
error: function(msg, e, data) {
var Y = this, ret;
if (Y.config.errorFn) {
ret = Y.config.errorFn.apply(Y, arguments);
}
if (Y.config.throwFail && !ret) {
throw (e || new Error(msg));
} else {
Y.message(msg, 'error'); // don't scrub this one
}
return Y;
},
/**
* Generate an id that is unique among all YUI instances
* @method guid
* @param pre {String} optional guid prefix.
* @return {String} the guid.
*/
guid: function(pre) {
var id = this.Env._guidp + '_' + (++this.Env._uidx);
return (pre) ? (pre + id) : id;
},
/**
* Returns a `guid` associated with an object. If the object
* does not have one, a new one is created unless `readOnly`
* is specified.
* @method stamp
* @param o {Object} The object to stamp.
* @param readOnly {Boolean} if `true`, a valid guid will only
* be returned if the object has one assigned to it.
* @return {String} The object's guid or null.
*/
stamp: function(o, readOnly) {
var uid;
if (!o) {
return o;
}
// IE generates its own unique ID for dom nodes
// The uniqueID property of a document node returns a new ID
if (o.uniqueID && o.nodeType && o.nodeType !== 9) {
uid = o.uniqueID;
} else {
uid = (typeof o === 'string') ? o : o._yuid;
}
if (!uid) {
uid = this.guid();
if (!readOnly) {
try {
o._yuid = uid;
} catch (e) {
uid = null;
}
}
}
return uid;
},
/**
* Destroys the YUI instance
* @method destroy
* @since 3.3.0
*/
destroy: function() {
var Y = this;
if (Y.Event) {
Y.Event._unload();
}
delete instances[Y.id];
delete Y.Env;
delete Y.config;
}
/**
* instanceof check for objects that works around
* memory leak in IE when the item tested is
* window/document
* @method instanceOf
* @since 3.3.0
*/
};
YUI.prototype = proto;
// inheritance utilities are not available yet
for (prop in proto) {
if (proto.hasOwnProperty(prop)) {
YUI[prop] = proto[prop];
}
}
// set up the environment
YUI._init();
if (hasWin) {
// add a window load event at load time so we can capture
// the case where it fires before dynamic loading is
// complete.
add(window, 'load', handleLoad);
} else {
handleLoad();
}
YUI.Env.add = add;
YUI.Env.remove = remove;
/*global exports*/
// Support the CommonJS method for exporting our single global
if (typeof exports == 'object') {
exports.YUI = YUI;
}
}());
/**
* The config object contains all of the configuration options for
* the `YUI` instance. This object is supplied by the implementer
* when instantiating a `YUI` instance. Some properties have default
* values if they are not supplied by the implementer. This should
* not be updated directly because some values are cached. Use
* `applyConfig()` to update the config object on a YUI instance that
* has already been configured.
*
* @class config
* @static
*/
/**
* Allows the YUI seed file to fetch the loader component and library
* metadata to dynamically load additional dependencies.
*
* @property bootstrap
* @type boolean
* @default true
*/
/**
* Log to the browser console if debug is on and the browser has a
* supported console.
*
* @property useBrowserConsole
* @type boolean
* @default true
*/
/**
* A hash of log sources that should be logged. If specified, only
* log messages from these sources will be logged.
*
* @property logInclude
* @type object
*/
/**
* A hash of log sources that should be not be logged. If specified,
* all sources are logged if not on this list.
*
* @property logExclude
* @type object
*/
/**
* Set to true if the yui seed file was dynamically loaded in
* order to bootstrap components relying on the window load event
* and the `domready` custom event.
*
* @property injected
* @type boolean
* @default false
*/
/**
* If `throwFail` is set, `Y.error` will generate or re-throw a JS Error.
* Otherwise the failure is logged.
*
* @property throwFail
* @type boolean
* @default true
*/
/**
* The window/frame that this instance should operate in.
*
* @property win
* @type Window
* @default the window hosting YUI
*/
/**
* The document associated with the 'win' configuration.
*
* @property doc
* @type Document
* @default the document hosting YUI
*/
/**
* A list of modules that defines the YUI core (overrides the default).
*
* @property core
* @type string[]
*/
/**
* A list of languages in order of preference. This list is matched against
* the list of available languages in modules that the YUI instance uses to
* determine the best possible localization of language sensitive modules.
* Languages are represented using BCP 47 language tags, such as "en-GB" for
* English as used in the United Kingdom, or "zh-Hans-CN" for simplified
* Chinese as used in China. The list can be provided as a comma-separated
* list or as an array.
*
* @property lang
* @type string|string[]
*/
/**
* The default date format
* @property dateFormat
* @type string
* @deprecated use configuration in `DataType.Date.format()` instead.
*/
/**
* The default locale
* @property locale
* @type string
* @deprecated use `config.lang` instead.
*/
/**
* The default interval when polling in milliseconds.
* @property pollInterval
* @type int
* @default 20
*/
/**
* The number of dynamic nodes to insert by default before
* automatically removing them. This applies to script nodes
* because removing the node will not make the evaluated script
* unavailable. Dynamic CSS is not auto purged, because removing
* a linked style sheet will also remove the style definitions.
* @property purgethreshold
* @type int
* @default 20
*/
/**
* The default interval when polling in milliseconds.
* @property windowResizeDelay
* @type int
* @default 40
*/
/**
* Base directory for dynamic loading
* @property base
* @type string
*/
/*
* The secure base dir (not implemented)
* For dynamic loading.
* @property secureBase
* @type string
*/
/**
* The YUI combo service base dir. Ex: `http://yui.yahooapis.com/combo?`
* For dynamic loading.
* @property comboBase
* @type string
*/
/**
* The root path to prepend to module path for the combo service.
* Ex: 3.0.0b1/build/
* For dynamic loading.
* @property root
* @type string
*/
/**
* A filter to apply to result urls. This filter will modify the default
* path for all modules. The default path for the YUI library is the
* minified version of the files (e.g., event-min.js). The filter property
* can be a predefined filter or a custom filter. The valid predefined
* filters are:
* <dl>
* <dt>DEBUG</dt>
* <dd>Selects the debug versions of the library (e.g., event-debug.js).
* This option will automatically include the Logger widget</dd>
* <dt>RAW</dt>
* <dd>Selects the non-minified version of the library (e.g., event.js).</dd>
* </dl>
* You can also define a custom filter, which must be an object literal
* containing a search expression and a replace string:
*
* myFilter: {
* 'searchExp': "-min\\.js",
* 'replaceStr': "-debug.js"
* }
*
* For dynamic loading.
*
* @property filter
* @type string|object
*/
/**
* The `skin` config let's you configure application level skin
* customizations. It contains the following attributes which
* can be specified to override the defaults:
*
* // The default skin, which is automatically applied if not
* // overriden by a component-specific skin definition.
* // Change this in to apply a different skin globally
* defaultSkin: 'sam',
*
* // This is combined with the loader base property to get
* // the default root directory for a skin.
* base: 'assets/skins/',
*
* // Any component-specific overrides can be specified here,
* // making it possible to load different skins for different
* // components. It is possible to load more than one skin
* // for a given component as well.
* overrides: {
* slider: ['capsule', 'round']
* }
*
* For dynamic loading.
*
* @property skin
*/
/**
* Hash of per-component filter specification. If specified for a given
* component, this overrides the filter config.
*
* For dynamic loading.
*
* @property filters
*/
/**
* Use the YUI combo service to reduce the number of http connections
* required to load your dependencies. Turning this off will
* disable combo handling for YUI and all module groups configured
* with a combo service.
*
* For dynamic loading.
*
* @property combine
* @type boolean
* @default true if 'base' is not supplied, false if it is.
*/
/**
* A list of modules that should never be dynamically loaded
*
* @property ignore
* @type string[]
*/
/**
* A list of modules that should always be loaded when required, even if already
* present on the page.
*
* @property force
* @type string[]
*/
/**
* Node or id for a node that should be used as the insertion point for new
* nodes. For dynamic loading.
*
* @property insertBefore
* @type string
*/
/**
* Object literal containing attributes to add to dynamically loaded script
* nodes.
* @property jsAttributes
* @type string
*/
/**
* Object literal containing attributes to add to dynamically loaded link
* nodes.
* @property cssAttributes
* @type string
*/
/**
* Number of milliseconds before a timeout occurs when dynamically
* loading nodes. If not set, there is no timeout.
* @property timeout
* @type int
*/
/**
* Callback for the 'CSSComplete' event. When dynamically loading YUI
* components with CSS, this property fires when the CSS is finished
* loading but script loading is still ongoing. This provides an
* opportunity to enhance the presentation of a loading page a little
* bit before the entire loading process is done.
*
* @property onCSS
* @type function
*/
/**
* A hash of module definitions to add to the list of YUI components.
* These components can then be dynamically loaded side by side with
* YUI via the `use()` method. This is a hash, the key is the module
* name, and the value is an object literal specifying the metdata
* for the module. See `Loader.addModule` for the supported module
* metadata fields. Also see groups, which provides a way to
* configure the base and combo spec for a set of modules.
*
* modules: {
* mymod1: {
* requires: ['node'],
* fullpath: 'http://myserver.mydomain.com/mymod1/mymod1.js'
* },
* mymod2: {
* requires: ['mymod1'],
* fullpath: 'http://myserver.mydomain.com/mymod2/mymod2.js'
* }
* }
*
* @property modules
* @type object
*/
/**
* A hash of module group definitions. It for each group you
* can specify a list of modules and the base path and
* combo spec to use when dynamically loading the modules.
*
* groups: {
* yui2: {
* // specify whether or not this group has a combo service
* combine: true,
*
* // the base path for non-combo paths
* base: 'http://yui.yahooapis.com/2.8.0r4/build/',
*
* // the path to the combo service
* comboBase: 'http://yui.yahooapis.com/combo?',
*
* // a fragment to prepend to the path attribute when
* // when building combo urls
* root: '2.8.0r4/build/',
*
* // the module definitions
* modules: {
* yui2_yde: {
* path: "yahoo-dom-event/yahoo-dom-event.js"
* },
* yui2_anim: {
* path: "animation/animation.js",
* requires: ['yui2_yde']
* }
* }
* }
* }
*
* @property groups
* @type object
*/
/**
* The loader 'path' attribute to the loader itself. This is combined
* with the 'base' attribute to dynamically load the loader component
* when boostrapping with the get utility alone.
*
* @property loaderPath
* @type string
* @default loader/loader-min.js
*/
/**
* Specifies whether or not YUI().use(...) will attempt to load CSS
* resources at all. Any truthy value will cause CSS dependencies
* to load when fetching script. The special value 'force' will
* cause CSS dependencies to be loaded even if no script is needed.
*
* @property fetchCSS
* @type boolean|string
* @default true
*/
/**
* The default gallery version to build gallery module urls
* @property gallery
* @type string
* @since 3.1.0
*/
/**
* The default YUI 2 version to build yui2 module urls. This is for
* intrinsic YUI 2 support via the 2in3 project. Also see the '2in3'
* config for pulling different revisions of the wrapped YUI 2
* modules.
* @since 3.1.0
* @property yui2
* @type string
* @default 2.8.1
*/
/**
* The 2in3 project is a deployment of the various versions of YUI 2
* deployed as first-class YUI 3 modules. Eventually, the wrapper
* for the modules will change (but the underlying YUI 2 code will
* be the same), and you can select a particular version of
* the wrapper modules via this config.
* @since 3.1.0
* @property 2in3
* @type string
* @default 1
*/
/**
* Alternative console log function for use in environments without
* a supported native console. The function is executed in the
* YUI instance context.
* @since 3.1.0
* @property logFn
* @type Function
*/
/**
* A callback to execute when Y.error is called. It receives the
* error message and an javascript error object if Y.error was
* executed because a javascript error was caught. The function
* is executed in the YUI instance context.
*
* @since 3.2.0
* @property errorFn
* @type Function
*/
/**
* A callback to execute when the loader fails to load one or
* more resource. This could be because of a script load
* failure. It can also fail if a javascript module fails
* to register itself, but only when the 'requireRegistration'
* is true. If this function is defined, the use() callback will
* only be called when the loader succeeds, otherwise it always
* executes unless there was a javascript error when attaching
* a module.
*
* @since 3.3.0
* @property loadErrorFn
* @type Function
*/
/**
* When set to true, the YUI loader will expect that all modules
* it is responsible for loading will be first-class YUI modules
* that register themselves with the YUI global. If this is
* set to true, loader will fail if the module registration fails
* to happen after the script is loaded.
*
* @since 3.3.0
* @property requireRegistration
* @type boolean
* @default false
*/
/**
* Cache serviced use() requests.
* @since 3.3.0
* @property cacheUse
* @type boolean
* @default true
* @deprecated no longer used
*/
/**
* The parameter defaults for the remote loader service. **Requires the rls seed file.** The properties that are supported:
*
* * `m`: comma separated list of module requirements. This
* must be the param name even for custom implemetations.
* * `v`: the version of YUI to load. Defaults to the version
* of YUI that is being used.
* * `gv`: the version of the gallery to load (see the gallery config)
* * `env`: comma separated list of modules already on the page.
* this must be the param name even for custom implemetations.
* * `lang`: the languages supported on the page (see the lang config)
* * `'2in3v'`: the version of the 2in3 wrapper to use (see the 2in3 config).
* * `'2v'`: the version of yui2 to use in the yui 2in3 wrappers
* * `filt`: a filter def to apply to the urls (see the filter config).
* * `filts`: a list of custom filters to apply per module
* * `tests`: this is a map of conditional module test function id keys
* with the values of 1 if the test passes, 0 if not. This must be
* the name of the querystring param in custom templates.
*
* @since 3.2.0
* @property rls
* @type {Object}
*/
/**
* The base path to the remote loader service. **Requires the rls seed file.**
*
* @since 3.2.0
* @property rls_base
* @type {String}
*/
/**
* The template to use for building the querystring portion
* of the remote loader service url. The default is determined
* by the rls config -- each property that has a value will be
* represented. **Requires the rls seed file.**
*
* @since 3.2.0
* @property rls_tmpl
* @type {String}
* @example
* m={m}&v={v}&env={env}&lang={lang}&filt={filt}&tests={tests}
*
*/
/**
* Configure the instance to use a remote loader service instead of
* the client loader. **Requires the rls seed file.**
*
* @since 3.2.0
* @property use_rls
* @type {Boolean}
*/
YUI.add('yui-base', function(Y) {
/*
* YUI stub
* @module yui
* @submodule yui-base
*/
/**
* The YUI module contains the components required for building the YUI
* seed file. This includes the script loading mechanism, a simple queue,
* and the core utilities for the library.
* @module yui
* @submodule yui-base
*/
/**
* Provides core language utilites and extensions used throughout YUI.
*
* @class Lang
* @static
*/
var L = Y.Lang || (Y.Lang = {}),
STRING_PROTO = String.prototype,
TOSTRING = Object.prototype.toString,
TYPES = {
'undefined' : 'undefined',
'number' : 'number',
'boolean' : 'boolean',
'string' : 'string',
'[object Function]': 'function',
'[object RegExp]' : 'regexp',
'[object Array]' : 'array',
'[object Date]' : 'date',
'[object Error]' : 'error'
},
SUBREGEX = /\{\s*([^|}]+?)\s*(?:\|([^}]*))?\s*\}/g,
TRIMREGEX = /^\s+|\s+$/g,
// If either MooTools or Prototype is on the page, then there's a chance that we
// can't trust "native" language features to actually be native. When this is
// the case, we take the safe route and fall back to our own non-native
// implementation.
win = Y.config.win,
unsafeNatives = win && !!(win.MooTools || win.Prototype);
/**
* Determines whether or not the provided item is an array.
*
* Returns `false` for array-like collections such as the function `arguments`
* collection or `HTMLElement` collections. Use `Y.Array.test()` if you want to
* test for an array-like collection.
*
* @method isArray
* @param o The object to test.
* @return {boolean} true if o is an array.
* @static
*/
L.isArray = (!unsafeNatives && Array.isArray) || function (o) {
return L.type(o) === 'array';
};
/**
* Determines whether or not the provided item is a boolean.
* @method isBoolean
* @static
* @param o The object to test.
* @return {boolean} true if o is a boolean.
*/
L.isBoolean = function(o) {
return typeof o === 'boolean';
};
/**
* <p>
* Determines whether or not the provided item is a function.
* Note: Internet Explorer thinks certain functions are objects:
* </p>
*
* <pre>
* var obj = document.createElement("object");
* Y.Lang.isFunction(obj.getAttribute) // reports false in IE
*
* var input = document.createElement("input"); // append to body
* Y.Lang.isFunction(input.focus) // reports false in IE
* </pre>
*
* <p>
* You will have to implement additional tests if these functions
* matter to you.
* </p>
*
* @method isFunction
* @static
* @param o The object to test.
* @return {boolean} true if o is a function.
*/
L.isFunction = function(o) {
return L.type(o) === 'function';
};
/**
* Determines whether or not the supplied item is a date instance.
* @method isDate
* @static
* @param o The object to test.
* @return {boolean} true if o is a date.
*/
L.isDate = function(o) {
return L.type(o) === 'date' && o.toString() !== 'Invalid Date' && !isNaN(o);
};
/**
* Determines whether or not the provided item is null.
* @method isNull
* @static
* @param o The object to test.
* @return {boolean} true if o is null.
*/
L.isNull = function(o) {
return o === null;
};
/**
* Determines whether or not the provided item is a legal number.
* @method isNumber
* @static
* @param o The object to test.
* @return {boolean} true if o is a number.
*/
L.isNumber = function(o) {
return typeof o === 'number' && isFinite(o);
};
/**
* Determines whether or not the provided item is of type object
* or function. Note that arrays are also objects, so
* <code>Y.Lang.isObject([]) === true</code>.
* @method isObject
* @static
* @param o The object to test.
* @param failfn {boolean} fail if the input is a function.
* @return {boolean} true if o is an object.
* @see isPlainObject
*/
L.isObject = function(o, failfn) {
var t = typeof o;
return (o && (t === 'object' ||
(!failfn && (t === 'function' || L.isFunction(o))))) || false;
};
/**
* Determines whether or not the provided item is a string.
* @method isString
* @static
* @param o The object to test.
* @return {boolean} true if o is a string.
*/
L.isString = function(o) {
return typeof o === 'string';
};
/**
* Determines whether or not the provided item is undefined.
* @method isUndefined
* @static
* @param o The object to test.
* @return {boolean} true if o is undefined.
*/
L.isUndefined = function(o) {
return typeof o === 'undefined';
};
/**
* Returns a string without any leading or trailing whitespace. If
* the input is not a string, the input will be returned untouched.
* @method trim
* @static
* @param s {string} the string to trim.
* @return {string} the trimmed string.
*/
L.trim = STRING_PROTO.trim ? function(s) {
return s && s.trim ? s.trim() : s;
} : function (s) {
try {
return s.replace(TRIMREGEX, '');
} catch (e) {
return s;
}
};
/**
* Returns a string without any leading whitespace.
* @method trimLeft
* @static
* @param s {string} the string to trim.
* @return {string} the trimmed string.
*/
L.trimLeft = STRING_PROTO.trimLeft ? function (s) {
return s.trimLeft();
} : function (s) {
return s.replace(/^\s+/, '');
};
/**
* Returns a string without any trailing whitespace.
* @method trimRight
* @static
* @param s {string} the string to trim.
* @return {string} the trimmed string.
*/
L.trimRight = STRING_PROTO.trimRight ? function (s) {
return s.trimRight();
} : function (s) {
return s.replace(/\s+$/, '');
};
/**
* A convenience method for detecting a legitimate non-null value.
* Returns false for null/undefined/NaN, true for other values,
* including 0/false/''
* @method isValue
* @static
* @param o The item to test.
* @return {boolean} true if it is not null/undefined/NaN || false.
*/
L.isValue = function(o) {
var t = L.type(o);
switch (t) {
case 'number':
return isFinite(o);
case 'null': // fallthru
case 'undefined':
return false;
default:
return !!t;
}
};
/**
* <p>
* Returns a string representing the type of the item passed in.
* </p>
*
* <p>
* Known issues:
* </p>
*
* <ul>
* <li>
* <code>typeof HTMLElementCollection</code> returns function in Safari, but
* <code>Y.type()</code> reports object, which could be a good thing --
* but it actually caused the logic in <code>Y.Lang.isObject</code> to fail.
* </li>
* </ul>
*
* @method type
* @param o the item to test.
* @return {string} the detected type.
* @static
*/
L.type = function(o) {
return TYPES[typeof o] || TYPES[TOSTRING.call(o)] || (o ? 'object' : 'null');
};
/**
* Lightweight version of <code>Y.substitute</code>. Uses the same template
* structure as <code>Y.substitute</code>, but doesn't support recursion,
* auto-object coersion, or formats.
* @method sub
* @param {string} s String to be modified.
* @param {object} o Object containing replacement values.
* @return {string} the substitute result.
* @static
* @since 3.2.0
*/
L.sub = function(s, o) {
return s.replace ? s.replace(SUBREGEX, function (match, key) {
return L.isUndefined(o[key]) ? match : o[key];
}) : s;
};
/**
* Returns the current time in milliseconds.
*
* @method now
* @return {Number} Current time in milliseconds.
* @static
* @since 3.3.0
*/
L.now = Date.now || function () {
return new Date().getTime();
};
/**
* The YUI module contains the components required for building the YUI seed
* file. This includes the script loading mechanism, a simple queue, and the
* core utilities for the library.
*
* @module yui
* @submodule yui-base
*/
var Lang = Y.Lang,
Native = Array.prototype,
hasOwn = Object.prototype.hasOwnProperty;
/**
Provides utility methods for working with arrays. Additional array helpers can
be found in the `collection` and `array-extras` modules.
`Y.Array(thing)` returns a native array created from _thing_. Depending on
_thing_'s type, one of the following will happen:
* Arrays are returned unmodified unless a non-zero _startIndex_ is
specified.
* Array-like collections (see `Array.test()`) are converted to arrays.
* For everything else, a new array is created with _thing_ as the sole
item.
Note: elements that are also collections, such as `<form>` and `<select>`
elements, are not automatically converted to arrays. To force a conversion,
pass `true` as the value of the _force_ parameter.
@class Array
@constructor
@param {Any} thing The thing to arrayify.
@param {Number} [startIndex=0] If non-zero and _thing_ is an array or array-like
collection, a subset of items starting at the specified index will be
returned.
@param {Boolean} [force=false] If `true`, _thing_ will be treated as an
array-like collection no matter what.
@return {Array} A native array created from _thing_, according to the rules
described above.
**/
function YArray(thing, startIndex, force) {
var len, result;
startIndex || (startIndex = 0);
if (force || YArray.test(thing)) {
// IE throws when trying to slice HTMLElement collections.
try {
return Native.slice.call(thing, startIndex);
} catch (ex) {
result = [];
for (len = thing.length; startIndex < len; ++startIndex) {
result.push(thing[startIndex]);
}
return result;
}
}
return [thing];
}
Y.Array = YArray;
/**
Evaluates _obj_ to determine if it's an array, an array-like collection, or
something else. This is useful when working with the function `arguments`
collection and `HTMLElement` collections.
Note: This implementation doesn't consider elements that are also
collections, such as `<form>` and `<select>`, to be array-like.
@method test
@param {Object} obj Object to test.
@return {Number} A number indicating the results of the test:
* 0: Neither an array nor an array-like collection.
* 1: Real array.
* 2: Array-like collection.
@static
**/
YArray.test = function (obj) {
var result = 0;
if (Lang.isArray(obj)) {
result = 1;
} else if (Lang.isObject(obj)) {
try {
// indexed, but no tagName (element) or alert (window),
// or functions without apply/call (Safari
// HTMLElementCollection bug).
if ('length' in obj && !obj.tagName && !obj.alert && !obj.apply) {
result = 2;
}
} catch (ex) {}
}
return result;
};
/**
Dedupes an array of strings, returning an array that's guaranteed to contain
only one copy of a given string.
This method differs from `Array.unique()` in that it's optimized for use only
with strings, whereas `unique` may be used with other types (but is slower).
Using `dedupe()` with non-string values may result in unexpected behavior.
@method dedupe
@param {String[]} array Array of strings to dedupe.
@return {Array} Deduped copy of _array_.
@static
@since 3.4.0
**/
YArray.dedupe = function (array) {
var hash = {},
results = [],
i, item, len;
for (i = 0, len = array.length; i < len; ++i) {
item = array[i];
if (!hasOwn.call(hash, item)) {
hash[item] = 1;
results.push(item);
}
}
return results;
};
/**
Executes the supplied function on each item in the array. This method wraps
the native ES5 `Array.forEach()` method if available.
@method each
@param {Array} array Array to iterate.
@param {Function} fn Function to execute on each item in the array. The function
will receive the following arguments:
@param {Any} fn.item Current array item.
@param {Number} fn.index Current array index.
@param {Array} fn.array Array being iterated.
@param {Object} [thisObj] `this` object to use when calling _fn_.
@return {YUI} The YUI instance.
@static
**/
YArray.each = YArray.forEach = Native.forEach ? function (array, fn, thisObj) {
Native.forEach.call(array || [], fn, thisObj || Y);
return Y;
} : function (array, fn, thisObj) {
for (var i = 0, len = (array && array.length) || 0; i < len; ++i) {
if (i in array) {
fn.call(thisObj || Y, array[i], i, array);
}
}
return Y;
};
/**
Alias for `each()`.
@method forEach
@static
**/
/**
Returns an object using the first array as keys and the second as values. If
the second array is not provided, or if it doesn't contain the same number of
values as the first array, then `true` will be used in place of the missing
values.
@example
Y.Array.hash(['a', 'b', 'c'], ['foo', 'bar']);
// => {a: 'foo', b: 'bar', c: true}
@method hash
@param {String[]} keys Array of strings to use as keys.
@param {Array} [values] Array to use as values.
@return {Object} Hash using the first array as keys and the second as values.
@static
**/
YArray.hash = function (keys, values) {
var hash = {},
vlen = (values && values.length) || 0,
i, len;
for (i = 0, len = keys.length; i < len; ++i) {
if (i in keys) {
hash[keys[i]] = vlen > i && i in values ? values[i] : true;
}
}
return hash;
};
/**
Returns the index of the first item in the array that's equal (using a strict
equality check) to the specified _value_, or `-1` if the value isn't found.
This method wraps the native ES5 `Array.indexOf()` method if available.
@method indexOf
@param {Array} array Array to search.
@param {Any} value Value to search for.
@return {Number} Index of the item strictly equal to _value_, or `-1` if not
found.
@static
**/
YArray.indexOf = Native.indexOf ? function (array, value) {
// TODO: support fromIndex
return Native.indexOf.call(array, value);
} : function (array, value) {
for (var i = 0, len = array.length; i < len; ++i) {
if (array[i] === value) {
return i;
}
}
return -1;
};
/**
Numeric sort convenience function.
The native `Array.prototype.sort()` function converts values to strings and
sorts them in lexicographic order, which is unsuitable for sorting numeric
values. Provide `Array.numericSort` as a custom sort function when you want
to sort values in numeric order.
@example
[42, 23, 8, 16, 4, 15].sort(Y.Array.numericSort);
// => [4, 8, 15, 16, 23, 42]
@method numericSort
@param {Number} a First value to compare.
@param {Number} b Second value to compare.
@return {Number} Difference between _a_ and _b_.
@static
**/
YArray.numericSort = function (a, b) {
return a - b;
};
/**
Executes the supplied function on each item in the array. Returning a truthy
value from the function will stop the processing of remaining items.
@method some
@param {Array} array Array to iterate over.
@param {Function} fn Function to execute on each item. The function will receive
the following arguments:
@param {Any} fn.value Current array item.
@param {Number} fn.index Current array index.
@param {Array} fn.array Array being iterated over.
@param {Object} [thisObj] `this` object to use when calling _fn_.
@return {Boolean} `true` if the function returns a truthy value on any of the
items in the array; `false` otherwise.
@static
**/
YArray.some = Native.some ? function (array, fn, thisObj) {
return Native.some.call(array, fn, thisObj);
} : function (array, fn, thisObj) {
for (var i = 0, len = array.length; i < len; ++i) {
if (i in array && fn.call(thisObj, array[i], i, array)) {
return true;
}
}
return false;
};
/**
* The YUI module contains the components required for building the YUI
* seed file. This includes the script loading mechanism, a simple queue,
* and the core utilities for the library.
* @module yui
* @submodule yui-base
*/
/**
* A simple FIFO queue. Items are added to the Queue with add(1..n items) and
* removed using next().
*
* @class Queue
* @constructor
* @param {MIXED} item* 0..n items to seed the queue.
*/
function Queue() {
this._init();
this.add.apply(this, arguments);
}
Queue.prototype = {
/**
* Initialize the queue
*
* @method _init
* @protected
*/
_init: function() {
/**
* The collection of enqueued items
*
* @property _q
* @type Array
* @protected
*/
this._q = [];
},
/**
* Get the next item in the queue. FIFO support
*
* @method next
* @return {MIXED} the next item in the queue.
*/
next: function() {
return this._q.shift();
},
/**
* Get the last in the queue. LIFO support.
*
* @method last
* @return {MIXED} the last item in the queue.
*/
last: function() {
return this._q.pop();
},
/**
* Add 0..n items to the end of the queue.
*
* @method add
* @param {MIXED} item* 0..n items.
* @return {object} this queue.
*/
add: function() {
this._q.push.apply(this._q, arguments);
return this;
},
/**
* Returns the current number of queued items.
*
* @method size
* @return {Number} The size.
*/
size: function() {
return this._q.length;
}
};
Y.Queue = Queue;
YUI.Env._loaderQueue = YUI.Env._loaderQueue || new Queue();
/**
The YUI module contains the components required for building the YUI seed file.
This includes the script loading mechanism, a simple queue, and the core
utilities for the library.
@module yui
@submodule yui-base
**/
var CACHED_DELIMITER = '__',
hasOwn = Object.prototype.hasOwnProperty,
isObject = Y.Lang.isObject;
/**
Returns a wrapper for a function which caches the return value of that function,
keyed off of the combined string representation of the argument values provided
when the wrapper is called.
Calling this function again with the same arguments will return the cached value
rather than executing the wrapped function.
Note that since the cache is keyed off of the string representation of arguments
passed to the wrapper function, arguments that aren't strings and don't provide
a meaningful `toString()` method may result in unexpected caching behavior. For
example, the objects `{}` and `{foo: 'bar'}` would both be converted to the
string `[object Object]` when used as a cache key.
@method cached
@param {Function} source The function to memoize.
@param {Object} [cache={}] Object in which to store cached values. You may seed
this object with pre-existing cached values if desired.
@param {any} [refetch] If supplied, this value is compared with the cached value
using a `==` comparison. If the values are equal, the wrapped function is
executed again even though a cached value exists.
@return {Function} Wrapped function.
@for YUI
**/
Y.cached = function (source, cache, refetch) {
cache || (cache = {});
return function (arg) {
var key = arguments.length > 1 ?
Array.prototype.join.call(arguments, CACHED_DELIMITER) :
arg.toString();
if (!(key in cache) || (refetch && cache[key] == refetch)) {
cache[key] = source.apply(source, arguments);
}
return cache[key];
};
};
/**
Returns a new object containing all of the properties of all the supplied
objects. The properties from later objects will overwrite those in earlier
objects.
Passing in a single object will create a shallow copy of it. For a deep copy,
use `clone()`.
@method merge
@param {Object} objects* One or more objects to merge.
@return {Object} A new merged object.
**/
Y.merge = function () {
var args = arguments,
i = 0,
len = args.length,
result = {};
for (; i < len; ++i) {
Y.mix(result, args[i], true);
}
return result;
};
/**
Mixes _supplier_'s properties into _receiver_. Properties will not be
overwritten or merged unless the _overwrite_ or _merge_ parameters are `true`,
respectively.
In the default mode (0), only properties the supplier owns are copied (prototype
properties are not copied). The following copying modes are available:
* `0`: _Default_. Object to object.
* `1`: Prototype to prototype.
* `2`: Prototype to prototype and object to object.
* `3`: Prototype to object.
* `4`: Object to prototype.
@method mix
@param {Function|Object} receiver The object or function to receive the mixed
properties.
@param {Function|Object} supplier The object or function supplying the
properties to be mixed.
@param {Boolean} [overwrite=false] If `true`, properties that already exist
on the receiver will be overwritten with properties from the supplier.
@param {String[]} [whitelist] An array of property names to copy. If
specified, only the whitelisted properties will be copied, and all others
will be ignored.
@param {Int} [mode=0] Mix mode to use. See above for available modes.
@param {Boolean} [merge=false] If `true`, objects and arrays that already
exist on the receiver will have the corresponding object/array from the
supplier merged into them, rather than being skipped or overwritten. When
both _overwrite_ and _merge_ are `true`, _merge_ takes precedence.
@return {Function|Object|YUI} The receiver, or the YUI instance if the
specified receiver is falsy.
**/
Y.mix = function(receiver, supplier, overwrite, whitelist, mode, merge) {
var alwaysOverwrite, exists, from, i, key, len, to;
// If no supplier is given, we return the receiver. If no receiver is given,
// we return Y. Returning Y doesn't make much sense to me, but it's
// grandfathered in for backcompat reasons.
if (!receiver || !supplier) {
return receiver || Y;
}
if (mode) {
// In mode 2 (prototype to prototype and object to object), we recurse
// once to do the proto to proto mix. The object to object mix will be
// handled later on.
if (mode === 2) {
Y.mix(receiver.prototype, supplier.prototype, overwrite,
whitelist, 0, merge);
}
// Depending on which mode is specified, we may be copying from or to
// the prototypes of the supplier and receiver.
from = mode === 1 || mode === 3 ? supplier.prototype : supplier;
to = mode === 1 || mode === 4 ? receiver.prototype : receiver;
// If either the supplier or receiver doesn't actually have a
// prototype property, then we could end up with an undefined `from`
// or `to`. If that happens, we abort and return the receiver.
if (!from || !to) {
return receiver;
}
} else {
from = supplier;
to = receiver;
}
// If `overwrite` is truthy and `merge` is falsy, then we can skip a call
// to `hasOwnProperty` on each iteration and save some time.
alwaysOverwrite = overwrite && !merge;
if (whitelist) {
for (i = 0, len = whitelist.length; i < len; ++i) {
key = whitelist[i];
// We call `Object.prototype.hasOwnProperty` instead of calling
// `hasOwnProperty` on the object itself, since the object's
// `hasOwnProperty` method may have been overridden or removed.
// Also, some native objects don't implement a `hasOwnProperty`
// method.
if (!hasOwn.call(from, key)) {
continue;
}
exists = alwaysOverwrite ? false : hasOwn.call(to, key);
if (merge && exists && isObject(to[key], true)
&& isObject(from[key], true)) {
// If we're in merge mode, and the key is present on both
// objects, and the value on both objects is either an object or
// an array (but not a function), then we recurse to merge the
// `from` value into the `to` value instead of overwriting it.
//
// Note: It's intentional that the whitelist isn't passed to the
// recursive call here. This is legacy behavior that lots of
// code still depends on.
Y.mix(to[key], from[key], overwrite, null, 0, merge);
} else if (overwrite || !exists) {
// We're not in merge mode, so we'll only copy the `from` value
// to the `to` value if we're in overwrite mode or if the
// current key doesn't exist on the `to` object.
to[key] = from[key];
}
}
} else {
for (key in from) {
// The code duplication here is for runtime performance reasons.
// Combining whitelist and non-whitelist operations into a single
// loop or breaking the shared logic out into a function both result
// in worse performance, and Y.mix is critical enough that the byte
// tradeoff is worth it.
if (!hasOwn.call(from, key)) {
continue;
}
exists = alwaysOverwrite ? false : hasOwn.call(to, key);
if (merge && exists && isObject(to[key], true)
&& isObject(from[key], true)) {
Y.mix(to[key], from[key], overwrite, null, 0, merge);
} else if (overwrite || !exists) {
to[key] = from[key];
}
}
// If this is an IE browser with the JScript enumeration bug, force
// enumeration of the buggy properties by making a recursive call with
// the buggy properties as the whitelist.
if (Y.Object._hasEnumBug) {
Y.mix(to, from, overwrite, Y.Object._forceEnum, mode, merge);
}
}
return receiver;
};
/**
* The YUI module contains the components required for building the YUI
* seed file. This includes the script loading mechanism, a simple queue,
* and the core utilities for the library.
* @module yui
* @submodule yui-base
*/
/**
* Adds utilities to the YUI instance for working with objects.
*
* @class Object
*/
var hasOwn = Object.prototype.hasOwnProperty,
// If either MooTools or Prototype is on the page, then there's a chance that we
// can't trust "native" language features to actually be native. When this is
// the case, we take the safe route and fall back to our own non-native
// implementations.
win = Y.config.win,
unsafeNatives = win && !!(win.MooTools || win.Prototype),
UNDEFINED, // <-- Note the comma. We're still declaring vars.
/**
* Returns a new object that uses _obj_ as its prototype. This method wraps the
* native ES5 `Object.create()` method if available, but doesn't currently
* pass through `Object.create()`'s second argument (properties) in order to
* ensure compatibility with older browsers.
*
* @method ()
* @param {Object} obj Prototype object.
* @return {Object} New object using _obj_ as its prototype.
* @static
*/
O = Y.Object = (!unsafeNatives && Object.create) ? function (obj) {
// We currently wrap the native Object.create instead of simply aliasing it
// to ensure consistency with our fallback shim, which currently doesn't
// support Object.create()'s second argument (properties). Once we have a
// safe fallback for the properties arg, we can stop wrapping
// Object.create().
return Object.create(obj);
} : (function () {
// Reusable constructor function for the Object.create() shim.
function F() {}
// The actual shim.
return function (obj) {
F.prototype = obj;
return new F();
};
}()),
/**
* Property names that IE doesn't enumerate in for..in loops, even when they
* should be enumerable. When `_hasEnumBug` is `true`, it's necessary to
* manually enumerate these properties.
*
* @property _forceEnum
* @type String[]
* @protected
* @static
*/
forceEnum = O._forceEnum = [
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'toString',
'toLocaleString',
'valueOf'
],
/**
* `true` if this browser has the JScript enumeration bug that prevents
* enumeration of the properties named in the `_forceEnum` array, `false`
* otherwise.
*
* See:
* - <https://developer.mozilla.org/en/ECMAScript_DontEnum_attribute#JScript_DontEnum_Bug>
* - <http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation>
*
* @property _hasEnumBug
* @type {Boolean}
* @protected
* @static
*/
hasEnumBug = O._hasEnumBug = !{valueOf: 0}.propertyIsEnumerable('valueOf'),
/**
* Returns `true` if _key_ exists on _obj_, `false` if _key_ doesn't exist or
* exists only on _obj_'s prototype. This is essentially a safer version of
* `obj.hasOwnProperty()`.
*
* @method owns
* @param {Object} obj Object to test.
* @param {String} key Property name to look for.
* @return {Boolean} `true` if _key_ exists on _obj_, `false` otherwise.
* @static
*/
owns = O.owns = function (obj, key) {
return !!obj && hasOwn.call(obj, key);
}; // <-- End of var declarations.
/**
* Alias for `owns()`.
*
* @method hasKey
* @param {Object} obj Object to test.
* @param {String} key Property name to look for.
* @return {Boolean} `true` if _key_ exists on _obj_, `false` otherwise.
* @static
*/
O.hasKey = owns;
/**
* Returns an array containing the object's enumerable keys. Does not include
* prototype keys or non-enumerable keys.
*
* Note that keys are returned in enumeration order (that is, in the same order
* that they would be enumerated by a `for-in` loop), which may not be the same
* as the order in which they were defined.
*
* This method is an alias for the native ES5 `Object.keys()` method if
* available.
*
* @example
*
* Y.Object.keys({a: 'foo', b: 'bar', c: 'baz'});
* // => ['a', 'b', 'c']
*
* @method keys
* @param {Object} obj An object.
* @return {String[]} Array of keys.
* @static
*/
O.keys = (!unsafeNatives && Object.keys) || function (obj) {
if (!Y.Lang.isObject(obj)) {
throw new TypeError('Object.keys called on a non-object');
}
var keys = [],
i, key, len;
for (key in obj) {
if (owns(obj, key)) {
keys.push(key);
}
}
if (hasEnumBug) {
for (i = 0, len = forceEnum.length; i < len; ++i) {
key = forceEnum[i];
if (owns(obj, key)) {
keys.push(key);
}
}
}
return keys;
};
/**
* Returns an array containing the values of the object's enumerable keys.
*
* Note that values are returned in enumeration order (that is, in the same
* order that they would be enumerated by a `for-in` loop), which may not be the
* same as the order in which they were defined.
*
* @example
*
* Y.Object.values({a: 'foo', b: 'bar', c: 'baz'});
* // => ['foo', 'bar', 'baz']
*
* @method values
* @param {Object} obj An object.
* @return {Array} Array of values.
* @static
*/
O.values = function (obj) {
var keys = O.keys(obj),
i = 0,
len = keys.length,
values = [];
for (; i < len; ++i) {
values.push(obj[keys[i]]);
}
return values;
};
/**
* Returns the number of enumerable keys owned by an object.
*
* @method size
* @param {Object} obj An object.
* @return {Number} The object's size.
* @static
*/
O.size = function (obj) {
return O.keys(obj).length;
};
/**
* Returns `true` if the object owns an enumerable property with the specified
* value.
*
* @method hasValue
* @param {Object} obj An object.
* @param {any} value The value to search for.
* @return {Boolean} `true` if _obj_ contains _value_, `false` otherwise.
* @static
*/
O.hasValue = function (obj, value) {
return Y.Array.indexOf(O.values(obj), value) > -1;
};
/**
* Executes a function on each enumerable property in _obj_. The function
* receives the value, the key, and the object itself as parameters (in that
* order).
*
* By default, only properties owned by _obj_ are enumerated. To include
* prototype properties, set the _proto_ parameter to `true`.
*
* @method each
* @param {Object} obj Object to enumerate.
* @param {Function} fn Function to execute on each enumerable property.
* @param {mixed} fn.value Value of the current property.
* @param {String} fn.key Key of the current property.
* @param {Object} fn.obj Object being enumerated.
* @param {Object} [thisObj] `this` object to use when calling _fn_.
* @param {Boolean} [proto=false] Include prototype properties.
* @return {YUI} the YUI instance.
* @chainable
* @static
*/
O.each = function (obj, fn, thisObj, proto) {
var key;
for (key in obj) {
if (proto || owns(obj, key)) {
fn.call(thisObj || Y, obj[key], key, obj);
}
}
return Y;
};
/**
* Executes a function on each enumerable property in _obj_, but halts if the
* function returns a truthy value. The function receives the value, the key,
* and the object itself as paramters (in that order).
*
* By default, only properties owned by _obj_ are enumerated. To include
* prototype properties, set the _proto_ parameter to `true`.
*
* @method some
* @param {Object} obj Object to enumerate.
* @param {Function} fn Function to execute on each enumerable property.
* @param {mixed} fn.value Value of the current property.
* @param {String} fn.key Key of the current property.
* @param {Object} fn.obj Object being enumerated.
* @param {Object} [thisObj] `this` object to use when calling _fn_.
* @param {Boolean} [proto=false] Include prototype properties.
* @return {Boolean} `true` if any execution of _fn_ returns a truthy value,
* `false` otherwise.
* @static
*/
O.some = function (obj, fn, thisObj, proto) {
var key;
for (key in obj) {
if (proto || owns(obj, key)) {
if (fn.call(thisObj || Y, obj[key], key, obj)) {
return true;
}
}
}
return false;
};
/**
* Retrieves the sub value at the provided path,
* from the value object provided.
*
* @method getValue
* @static
* @param o The object from which to extract the property value.
* @param path {Array} A path array, specifying the object traversal path
* from which to obtain the sub value.
* @return {Any} The value stored in the path, undefined if not found,
* undefined if the source is not an object. Returns the source object
* if an empty path is provided.
*/
O.getValue = function(o, path) {
if (!Y.Lang.isObject(o)) {
return UNDEFINED;
}
var i,
p = Y.Array(path),
l = p.length;
for (i = 0; o !== UNDEFINED && i < l; i++) {
o = o[p[i]];
}
return o;
};
/**
* Sets the sub-attribute value at the provided path on the
* value object. Returns the modified value object, or
* undefined if the path is invalid.
*
* @method setValue
* @static
* @param o The object on which to set the sub value.
* @param path {Array} A path array, specifying the object traversal path
* at which to set the sub value.
* @param val {Any} The new value for the sub-attribute.
* @return {Object} The modified object, with the new sub value set, or
* undefined, if the path was invalid.
*/
O.setValue = function(o, path, val) {
var i,
p = Y.Array(path),
leafIdx = p.length - 1,
ref = o;
if (leafIdx >= 0) {
for (i = 0; ref !== UNDEFINED && i < leafIdx; i++) {
ref = ref[p[i]];
}
if (ref !== UNDEFINED) {
ref[p[i]] = val;
} else {
return UNDEFINED;
}
}
return o;
};
/**
* Returns `true` if the object has no enumerable properties of its own.
*
* @method isEmpty
* @param {Object} obj An object.
* @return {Boolean} `true` if the object is empty.
* @static
* @since 3.2.0
*/
O.isEmpty = function (obj) {
return !O.keys(obj).length;
};
/**
* The YUI module contains the components required for building the YUI seed
* file. This includes the script loading mechanism, a simple queue, and the
* core utilities for the library.
* @module yui
* @submodule yui-base
*/
/**
* YUI user agent detection.
* Do not fork for a browser if it can be avoided. Use feature detection when
* you can. Use the user agent as a last resort. For all fields listed
* as @type float, UA stores a version number for the browser engine,
* 0 otherwise. This value may or may not map to the version number of
* the browser using the engine. The value is presented as a float so
* that it can easily be used for boolean evaluation as well as for
* looking for a particular range of versions. Because of this,
* some of the granularity of the version info may be lost. The fields that
* are @type string default to null. The API docs list the values that
* these fields can have.
* @class UA
* @static
*/
/**
* Static method for parsing the UA string. Defaults to assigning it's value to Y.UA
* @static
* @method Env.parseUA
* @param {String} subUA Parse this UA string instead of navigator.userAgent
* @returns {Object} The Y.UA object
*/
YUI.Env.parseUA = function(subUA) {
var numberify = function(s) {
var c = 0;
return parseFloat(s.replace(/\./g, function() {
return (c++ == 1) ? '' : '.';
}));
},
win = Y.config.win,
nav = win && win.navigator,
o = {
/**
* Internet Explorer version number or 0. Example: 6
* @property ie
* @type float
* @static
*/
ie: 0,
/**
* Opera version number or 0. Example: 9.2
* @property opera
* @type float
* @static
*/
opera: 0,
/**
* Gecko engine revision number. Will evaluate to 1 if Gecko
* is detected but the revision could not be found. Other browsers
* will be 0. Example: 1.8
* <pre>
* Firefox 1.0.0.4: 1.7.8 <-- Reports 1.7
* Firefox 1.5.0.9: 1.8.0.9 <-- 1.8
* Firefox 2.0.0.3: 1.8.1.3 <-- 1.81
* Firefox 3.0 <-- 1.9
* Firefox 3.5 <-- 1.91
* </pre>
* @property gecko
* @type float
* @static
*/
gecko: 0,
/**
* AppleWebKit version. KHTML browsers that are not WebKit browsers
* will evaluate to 1, other browsers 0. Example: 418.9
* <pre>
* Safari 1.3.2 (312.6): 312.8.1 <-- Reports 312.8 -- currently the
* latest available for Mac OSX 10.3.
* Safari 2.0.2: 416 <-- hasOwnProperty introduced
* Safari 2.0.4: 418 <-- preventDefault fixed
* Safari 2.0.4 (419.3): 418.9.1 <-- One version of Safari may run
* different versions of webkit
* Safari 2.0.4 (419.3): 419 <-- Tiger installations that have been
* updated, but not updated
* to the latest patch.
* Webkit 212 nightly: 522+ <-- Safari 3.0 precursor (with native
* SVG and many major issues fixed).
* Safari 3.0.4 (523.12) 523.12 <-- First Tiger release - automatic
* update from 2.x via the 10.4.11 OS patch.
* Webkit nightly 1/2008:525+ <-- Supports DOMContentLoaded event.
* yahoo.com user agent hack removed.
* </pre>
* http://en.wikipedia.org/wiki/Safari_version_history
* @property webkit
* @type float
* @static
*/
webkit: 0,
/**
* Safari will be detected as webkit, but this property will also
* be populated with the Safari version number
* @property safari
* @type float
* @static
*/
safari: 0,
/**
* Chrome will be detected as webkit, but this property will also
* be populated with the Chrome version number
* @property chrome
* @type float
* @static
*/
chrome: 0,
/**
* The mobile property will be set to a string containing any relevant
* user agent information when a modern mobile browser is detected.
* Currently limited to Safari on the iPhone/iPod Touch, Nokia N-series
* devices with the WebKit-based browser, and Opera Mini.
* @property mobile
* @type string
* @default null
* @static
*/
mobile: null,
/**
* Adobe AIR version number or 0. Only populated if webkit is detected.
* Example: 1.0
* @property air
* @type float
*/
air: 0,
/**
* Detects Apple iPad's OS version
* @property ipad
* @type float
* @static
*/
ipad: 0,
/**
* Detects Apple iPhone's OS version
* @property iphone
* @type float
* @static
*/
iphone: 0,
/**
* Detects Apples iPod's OS version
* @property ipod
* @type float
* @static
*/
ipod: 0,
/**
* General truthy check for iPad, iPhone or iPod
* @property ios
* @type float
* @default null
* @static
*/
ios: null,
/**
* Detects Googles Android OS version
* @property android
* @type float
* @static
*/
android: 0,
/**
* Detects Palms WebOS version
* @property webos
* @type float
* @static
*/
webos: 0,
/**
* Google Caja version number or 0.
* @property caja
* @type float
*/
caja: nav && nav.cajaVersion,
/**
* Set to true if the page appears to be in SSL
* @property secure
* @type boolean
* @static
*/
secure: false,
/**
* The operating system. Currently only detecting windows or macintosh
* @property os
* @type string
* @default null
* @static
*/
os: null
},
ua = subUA || nav && nav.userAgent,
loc = win && win.location,
href = loc && loc.href,
m;
o.secure = href && (href.toLowerCase().indexOf('https') === 0);
if (ua) {
if ((/windows|win32/i).test(ua)) {
o.os = 'windows';
} else if ((/macintosh/i).test(ua)) {
o.os = 'macintosh';
} else if ((/rhino/i).test(ua)) {
o.os = 'rhino';
}
// Modern KHTML browsers should qualify as Safari X-Grade
if ((/KHTML/).test(ua)) {
o.webkit = 1;
}
// Modern WebKit browsers are at least X-Grade
m = ua.match(/AppleWebKit\/([^\s]*)/);
if (m && m[1]) {
o.webkit = numberify(m[1]);
o.safari = o.webkit;
// Mobile browser check
if (/ Mobile\//.test(ua)) {
o.mobile = 'Apple'; // iPhone or iPod Touch
m = ua.match(/OS ([^\s]*)/);
if (m && m[1]) {
m = numberify(m[1].replace('_', '.'));
}
o.ios = m;
o.ipad = o.ipod = o.iphone = 0;
m = ua.match(/iPad|iPod|iPhone/);
if (m && m[0]) {
o[m[0].toLowerCase()] = o.ios;
}
} else {
m = ua.match(/NokiaN[^\/]*|webOS\/\d\.\d/);
if (m) {
// Nokia N-series, webOS, ex: NokiaN95
o.mobile = m[0];
}
if (/webOS/.test(ua)) {
o.mobile = 'WebOS';
m = ua.match(/webOS\/([^\s]*);/);
if (m && m[1]) {
o.webos = numberify(m[1]);
}
}
if (/ Android/.test(ua)) {
if (/Mobile/.test(ua)) {
o.mobile = 'Android';
}
m = ua.match(/Android ([^\s]*);/);
if (m && m[1]) {
o.android = numberify(m[1]);
}
}
}
m = ua.match(/Chrome\/([^\s]*)/);
if (m && m[1]) {
o.chrome = numberify(m[1]); // Chrome
o.safari = 0; //Reset safari back to 0
} else {
m = ua.match(/AdobeAIR\/([^\s]*)/);
if (m) {
o.air = m[0]; // Adobe AIR 1.0 or better
}
}
}
if (!o.webkit) { // not webkit
// @todo check Opera/8.01 (J2ME/MIDP; Opera Mini/2.0.4509/1316; fi; U; ssr)
m = ua.match(/Opera[\s\/]([^\s]*)/);
if (m && m[1]) {
o.opera = numberify(m[1]);
m = ua.match(/Version\/([^\s]*)/);
if (m && m[1]) {
o.opera = numberify(m[1]); // opera 10+
}
m = ua.match(/Opera Mini[^;]*/);
if (m) {
o.mobile = m[0]; // ex: Opera Mini/2.0.4509/1316
}
} else { // not opera or webkit
m = ua.match(/MSIE\s([^;]*)/);
if (m && m[1]) {
o.ie = numberify(m[1]);
} else { // not opera, webkit, or ie
m = ua.match(/Gecko\/([^\s]*)/);
if (m) {
o.gecko = 1; // Gecko detected, look for revision
m = ua.match(/rv:([^\s\)]*)/);
if (m && m[1]) {
o.gecko = numberify(m[1]);
}
}
}
}
}
}
YUI.Env.UA = o;
return o;
};
Y.UA = YUI.Env.UA || YUI.Env.parseUA();
YUI.Env.aliases = {
"anim": ["anim-base","anim-color","anim-curve","anim-easing","anim-node-plugin","anim-scroll","anim-xy"],
"app": ["controller","model","model-list","view"],
"attribute": ["attribute-base","attribute-complex"],
"autocomplete": ["autocomplete-base","autocomplete-sources","autocomplete-list","autocomplete-plugin"],
"base": ["base-base","base-pluginhost","base-build"],
"cache": ["cache-base","cache-offline","cache-plugin"],
"collection": ["array-extras","arraylist","arraylist-add","arraylist-filter","array-invoke"],
"dataschema": ["dataschema-base","dataschema-json","dataschema-xml","dataschema-array","dataschema-text"],
"datasource": ["datasource-local","datasource-io","datasource-get","datasource-function","datasource-cache","datasource-jsonschema","datasource-xmlschema","datasource-arrayschema","datasource-textschema","datasource-polling"],
"datatable": ["datatable-base","datatable-datasource","datatable-sort","datatable-scroll"],
"datatype": ["datatype-number","datatype-date","datatype-xml"],
"datatype-date": ["datatype-date-parse","datatype-date-format"],
"datatype-number": ["datatype-number-parse","datatype-number-format"],
"datatype-xml": ["datatype-xml-parse","datatype-xml-format"],
"dd": ["dd-ddm-base","dd-ddm","dd-ddm-drop","dd-drag","dd-proxy","dd-constrain","dd-drop","dd-scroll","dd-delegate"],
"dom": ["dom-base","dom-screen","dom-style","selector-native","selector"],
"editor": ["frame","selection","exec-command","editor-base","editor-para","editor-br","editor-bidi","editor-tab","createlink-base"],
"event": ["event-base","event-delegate","event-synthetic","event-mousewheel","event-mouseenter","event-key","event-focus","event-resize","event-hover","event-outside"],
"event-custom": ["event-custom-base","event-custom-complex"],
"event-gestures": ["event-flick","event-move"],
"highlight": ["highlight-base","highlight-accentfold"],
"history": ["history-base","history-hash","history-hash-ie","history-html5"],
"io": ["io-base","io-xdr","io-form","io-upload-iframe","io-queue"],
"json": ["json-parse","json-stringify"],
"loader": ["loader-base","loader-rollup","loader-yui3"],
"node": ["node-base","node-event-delegate","node-pluginhost","node-screen","node-style"],
"pluginhost": ["pluginhost-base","pluginhost-config"],
"querystring": ["querystring-parse","querystring-stringify"],
"recordset": ["recordset-base","recordset-sort","recordset-filter","recordset-indexer"],
"resize": ["resize-base","resize-proxy","resize-constrain"],
"slider": ["slider-base","slider-value-range","clickable-rail","range-slider"],
"text": ["text-accentfold","text-wordbreak"],
"widget": ["widget-base","widget-htmlparser","widget-uievents","widget-skin"]
};
}, '@VERSION@' );
YUI.add('get', function(Y) {
/**
* Provides a mechanism to fetch remote resources and
* insert them into a document.
* @module yui
* @submodule get
*/
/**
* Fetches and inserts one or more script or link nodes into the document
* @class Get
* @static
*/
var ua = Y.UA,
L = Y.Lang,
TYPE_JS = 'text/javascript',
TYPE_CSS = 'text/css',
STYLESHEET = 'stylesheet',
SCRIPT = 'script',
AUTOPURGE = 'autopurge',
UTF8 = 'utf-8',
LINK = 'link',
ASYNC = 'async',
ALL = true,
// FireFox does not support the onload event for link nodes, so
// there is no way to make the css requests synchronous. This means
// that the css rules in multiple files could be applied out of order
// in this browser if a later request returns before an earlier one.
// Safari too.
ONLOAD_SUPPORTED = {
script: ALL,
css: !(ua.webkit || ua.gecko)
},
/**
* hash of queues to manage multiple requests
* @property queues
* @private
*/
queues = {},
/**
* queue index used to generate transaction ids
* @property qidx
* @type int
* @private
*/
qidx = 0,
/**
* interal property used to prevent multiple simultaneous purge
* processes
* @property purging
* @type boolean
* @private
*/
purging,
/**
* Clear timeout state
*
* @method _clearTimeout
* @param {Object} q Queue data
* @private
*/
_clearTimeout = function(q) {
var timer = q.timer;
if (timer) {
clearTimeout(timer);
q.timer = null;
}
},
/**
* Generates an HTML element, this is not appended to a document
* @method _node
* @param {string} type the type of element.
* @param {Object} attr the fixed set of attribute for the type.
* @param {Object} custAttrs optional Any custom attributes provided by the user.
* @param {Window} win optional window to create the element in.
* @return {HTMLElement} the generated node.
* @private
*/
_node = function(type, attr, custAttrs, win) {
var w = win || Y.config.win,
d = w.document,
n = d.createElement(type),
i;
if (custAttrs) {
Y.mix(attr, custAttrs);
}
for (i in attr) {
if (attr[i] && attr.hasOwnProperty(i)) {
n.setAttribute(i, attr[i]);
}
}
return n;
},
/**
* Generates a link node
* @method _linkNode
* @param {string} url the url for the css file.
* @param {Window} win optional window to create the node in.
* @param {object} attributes optional attributes collection to apply to the
* new node.
* @return {HTMLElement} the generated node.
* @private
*/
_linkNode = function(url, win, attributes) {
return _node(LINK, {
id: Y.guid(),
type: TYPE_CSS,
rel: STYLESHEET,
href: url
}, attributes, win);
},
/**
* Generates a script node
* @method _scriptNode
* @param {string} url the url for the script file.
* @param {Window} win optional window to create the node in.
* @param {object} attributes optional attributes collection to apply to the
* new node.
* @return {HTMLElement} the generated node.
* @private
*/
_scriptNode = function(url, win, attributes) {
return _node(SCRIPT, {
id: Y.guid(),
type: TYPE_JS,
src: url
}, attributes, win);
},
/**
* Returns the data payload for callback functions.
* @method _returnData
* @param {object} q the queue.
* @param {string} msg the result message.
* @param {string} result the status message from the request.
* @return {object} the state data from the request.
* @private
*/
_returnData = function(q, msg, result) {
return {
tId: q.tId,
win: q.win,
data: q.data,
nodes: q.nodes,
msg: msg,
statusText: result,
purge: function() {
_purge(this.tId);
}
};
},
/**
* The transaction is finished
* @method _end
* @param {string} id the id of the request.
* @param {string} msg the result message.
* @param {string} result the status message from the request.
* @private
*/
_end = function(id, msg, result) {
var q = queues[id],
onEnd = q && q.onEnd;
q.finished = true;
if (onEnd) {
onEnd.call(q.context, _returnData(q, msg, result));
}
},
/**
* The request failed, execute fail handler with whatever
* was accomplished. There isn't a failure case at the
* moment unless you count aborted transactions
* @method _fail
* @param {string} id the id of the request
* @private
*/
_fail = function(id, msg) {
Y.log('get failure: ' + msg, 'warn', 'get');
var q = queues[id],
onFailure = q.onFailure;
_clearTimeout(q);
if (onFailure) {
onFailure.call(q.context, _returnData(q, msg));
}
_end(id, msg, 'failure');
},
/**
* Abort the transaction
*
* @method _abort
* @param {Object} id
* @private
*/
_abort = function(id) {
_fail(id, 'transaction ' + id + ' was aborted');
},
/**
* The request is complete, so executing the requester's callback
* @method _complete
* @param {string} id the id of the request.
* @private
*/
_complete = function(id) {
Y.log("Finishing transaction " + id, "info", "get");
var q = queues[id],
onSuccess = q.onSuccess;
_clearTimeout(q);
if (q.aborted) {
_abort(id);
} else {
if (onSuccess) {
onSuccess.call(q.context, _returnData(q));
}
// 3.3.0 had undefined msg for this path.
_end(id, undefined, 'OK');
}
},
/**
* Get node reference, from string
*
* @method _getNodeRef
* @param {String|HTMLElement} nId The node id to find. If an HTMLElement is passed in, it will be returned.
* @param {String} tId Queue id, used to determine document for queue
* @private
*/
_getNodeRef = function(nId, tId) {
var q = queues[tId],
n = (L.isString(nId)) ? q.win.document.getElementById(nId) : nId;
if (!n) {
_fail(tId, 'target node not found: ' + nId);
}
return n;
},
/**
* Removes the nodes for the specified queue
* @method _purge
* @param {string} tId the transaction id.
* @private
*/
_purge = function(tId) {
var nodes, doc, parent, sibling, node, attr, insertBefore,
i, l,
q = queues[tId];
if (q) {
nodes = q.nodes;
l = nodes.length;
// TODO: Why is node.parentNode undefined? Which forces us to do this...
/*
doc = q.win.document;
parent = doc.getElementsByTagName('head')[0];
insertBefore = q.insertBefore || doc.getElementsByTagName('base')[0];
if (insertBefore) {
sibling = _getNodeRef(insertBefore, tId);
if (sibling) {
parent = sibling.parentNode;
}
}
*/
for (i = 0; i < l; i++) {
node = nodes[i];
parent = node.parentNode;
if (node.clearAttributes) {
node.clearAttributes();
} else {
// This destroys parentNode ref, so we hold onto it above first.
for (attr in node) {
if (node.hasOwnProperty(attr)) {
delete node[attr];
}
}
}
parent.removeChild(node);
}
}
q.nodes = [];
},
/**
* Progress callback
*
* @method _progress
* @param {string} id The id of the request.
* @param {string} The url which just completed.
* @private
*/
_progress = function(id, url) {
var q = queues[id],
onProgress = q.onProgress,
o;
if (onProgress) {
o = _returnData(q);
o.url = url;
onProgress.call(q.context, o);
}
},
/**
* Timeout detected
* @method _timeout
* @param {string} id the id of the request.
* @private
*/
_timeout = function(id) {
Y.log('Timeout ' + id, 'info', 'get');
var q = queues[id],
onTimeout = q.onTimeout;
if (onTimeout) {
onTimeout.call(q.context, _returnData(q));
}
_end(id, 'timeout', 'timeout');
},
/**
* onload callback
* @method _loaded
* @param {string} id the id of the request.
* @return {string} the result.
* @private
*/
_loaded = function(id, url) {
var q = queues[id],
sync = (q && !q.async);
if (!q) {
return;
}
if (sync) {
_clearTimeout(q);
}
_progress(id, url);
// TODO: Cleaning up flow to have a consistent end point
// !q.finished check is for the async case,
// where scripts may still be loading when we've
// already aborted. Ideally there should be a single path
// for this.
if (!q.finished) {
if (q.aborted) {
_abort(id);
} else {
if ((--q.remaining) === 0) {
_complete(id);
} else if (sync) {
_next(id);
}
}
}
},
/**
* Detects when a node has been loaded. In the case of
* script nodes, this does not guarantee that contained
* script is ready to use.
* @method _trackLoad
* @param {string} type the type of node to track.
* @param {HTMLElement} n the node to track.
* @param {string} id the id of the request.
* @param {string} url the url that is being loaded.
* @private
*/
_trackLoad = function(type, n, id, url) {
// TODO: Can we massage this to use ONLOAD_SUPPORTED[type]?
// IE supports the readystatechange event for script and css nodes
// Opera only for script nodes. Opera support onload for script
// nodes, but this doesn't fire when there is a load failure.
// The onreadystatechange appears to be a better way to respond
// to both success and failure.
if (ua.ie) {
n.onreadystatechange = function() {
var rs = this.readyState;
if ('loaded' === rs || 'complete' === rs) {
// Y.log(id + " onreadstatechange " + url, "info", "get");
n.onreadystatechange = null;
_loaded(id, url);
}
};
} else if (ua.webkit) {
// webkit prior to 3.x is no longer supported
if (type === SCRIPT) {
// Safari 3.x supports the load event for script nodes (DOM2)
n.addEventListener('load', function() {
_loaded(id, url);
}, false);
}
} else {
// FireFox and Opera support onload (but not DOM2 in FF) handlers for
// script nodes. Opera, but not FF, supports the onload event for link nodes.
n.onload = function() {
// Y.log(id + " onload " + url, "info", "get");
_loaded(id, url);
};
n.onerror = function(e) {
_fail(id, e + ': ' + url);
};
}
},
_insertInDoc = function(node, id, win) {
// Add it to the head or insert it before 'insertBefore'.
// Work around IE bug if there is a base tag.
var q = queues[id],
doc = win.document,
insertBefore = q.insertBefore || doc.getElementsByTagName('base')[0],
sibling;
if (insertBefore) {
sibling = _getNodeRef(insertBefore, id);
if (sibling) {
Y.log('inserting before: ' + insertBefore, 'info', 'get');
sibling.parentNode.insertBefore(node, sibling);
}
} else {
// 3.3.0 assumed head is always around.
doc.getElementsByTagName('head')[0].appendChild(node);
}
},
/**
* Loads the next item for a given request
* @method _next
* @param {string} id the id of the request.
* @return {string} the result.
* @private
*/
_next = function(id) {
// Assigning out here for readability
var q = queues[id],
type = q.type,
attrs = q.attributes,
win = q.win,
timeout = q.timeout,
node,
url;
if (q.url.length > 0) {
url = q.url.shift();
Y.log('attempting to load ' + url, 'info', 'get');
// !q.timer ensures that this only happens once for async
if (timeout && !q.timer) {
q.timer = setTimeout(function() {
_timeout(id);
}, timeout);
}
if (type === SCRIPT) {
node = _scriptNode(url, win, attrs);
} else {
node = _linkNode(url, win, attrs);
}
// add the node to the queue so we can return it in the callback
q.nodes.push(node);
_trackLoad(type, node, id, url);
_insertInDoc(node, id, win);
if (!ONLOAD_SUPPORTED[type]) {
_loaded(id, url);
}
if (q.async) {
// For sync, the _next call is chained in _loaded
_next(id);
}
}
},
/**
* Removes processed queues and corresponding nodes
* @method _autoPurge
* @private
*/
_autoPurge = function() {
if (purging) {
return;
}
purging = true;
var i, q;
for (i in queues) {
if (queues.hasOwnProperty(i)) {
q = queues[i];
if (q.autopurge && q.finished) {
_purge(q.tId);
delete queues[i];
}
}
}
purging = false;
},
/**
* Saves the state for the request and begins loading
* the requested urls
* @method queue
* @param {string} type the type of node to insert.
* @param {string} url the url to load.
* @param {object} opts the hash of options for this request.
* @return {object} transaction object.
* @private
*/
_queue = function(type, url, opts) {
opts = opts || {};
var id = 'q' + (qidx++),
thresh = opts.purgethreshold || Y.Get.PURGE_THRESH,
q;
if (qidx % thresh === 0) {
_autoPurge();
}
// Merge to protect opts (grandfathered in).
q = queues[id] = Y.merge(opts);
// Avoid mix, merge overhead. Known set of props.
q.tId = id;
q.type = type;
q.url = url;
q.finished = false;
q.nodes = [];
q.win = q.win || Y.config.win;
q.context = q.context || q;
q.autopurge = (AUTOPURGE in q) ? q.autopurge : (type === SCRIPT) ? true : false;
q.attributes = q.attributes || {};
q.attributes.charset = opts.charset || q.attributes.charset || UTF8;
if (ASYNC in q && type === SCRIPT) {
q.attributes.async = q.async;
}
q.url = (L.isString(q.url)) ? [q.url] : q.url;
// TODO: Do we really need to account for this developer error?
// If the url is undefined, this is probably a trailing comma problem in IE.
if (!q.url[0]) {
q.url.shift();
Y.log('skipping empty url');
}
q.remaining = q.url.length;
_next(id);
return {
tId: id
};
};
Y.Get = {
/**
* The number of request required before an automatic purge.
* Can be configured via the 'purgethreshold' config
* @property PURGE_THRESH
* @static
* @type int
* @default 20
* @private
*/
PURGE_THRESH: 20,
/**
* Abort a transaction
* @method abort
* @static
* @param {string|object} o Either the tId or the object returned from
* script() or css().
*/
abort : function(o) {
var id = (L.isString(o)) ? o : o.tId,
q = queues[id];
if (q) {
Y.log('Aborting ' + id, 'info', 'get');
q.aborted = true;
}
},
/**
* Fetches and inserts one or more script nodes into the head
* of the current document or the document in a specified window.
*
* @method script
* @static
* @param {string|string[]} url the url or urls to the script(s).
* @param {object} opts Options:
* <dl>
* <dt>onSuccess</dt>
* <dd>
* callback to execute when the script(s) are finished loading
* The callback receives an object back with the following
* data:
* <dl>
* <dt>win</dt>
* <dd>the window the script(s) were inserted into</dd>
* <dt>data</dt>
* <dd>the data object passed in when the request was made</dd>
* <dt>nodes</dt>
* <dd>An array containing references to the nodes that were
* inserted</dd>
* <dt>purge</dt>
* <dd>A function that, when executed, will remove the nodes
* that were inserted</dd>
* <dt>
* </dl>
* </dd>
* <dt>onTimeout</dt>
* <dd>
* callback to execute when a timeout occurs.
* The callback receives an object back with the following
* data:
* <dl>
* <dt>win</dt>
* <dd>the window the script(s) were inserted into</dd>
* <dt>data</dt>
* <dd>the data object passed in when the request was made</dd>
* <dt>nodes</dt>
* <dd>An array containing references to the nodes that were
* inserted</dd>
* <dt>purge</dt>
* <dd>A function that, when executed, will remove the nodes
* that were inserted</dd>
* <dt>
* </dl>
* </dd>
* <dt>onEnd</dt>
* <dd>a function that executes when the transaction finishes,
* regardless of the exit path</dd>
* <dt>onFailure</dt>
* <dd>
* callback to execute when the script load operation fails
* The callback receives an object back with the following
* data:
* <dl>
* <dt>win</dt>
* <dd>the window the script(s) were inserted into</dd>
* <dt>data</dt>
* <dd>the data object passed in when the request was made</dd>
* <dt>nodes</dt>
* <dd>An array containing references to the nodes that were
* inserted successfully</dd>
* <dt>purge</dt>
* <dd>A function that, when executed, will remove any nodes
* that were inserted</dd>
* <dt>
* </dl>
* </dd>
* <dt>onProgress</dt>
* <dd>callback to execute when each individual file is done loading
* (useful when passing in an array of js files). Receives the same
* payload as onSuccess, with the addition of a <code>url</code>
* property, which identifies the file which was loaded.</dd>
* <dt>async</dt>
* <dd>
* <p>When passing in an array of JS files, setting this flag to true
* will insert them into the document in parallel, as opposed to the
* default behavior, which is to chain load them serially. It will also
* set the async attribute on the script node to true.</p>
* <p>Setting async:true
* will lead to optimal file download performance allowing the browser to
* download multiple scripts in parallel, and execute them as soon as they
* are available.</p>
* <p>Note that async:true does not guarantee execution order of the
* scripts being downloaded. They are executed in whichever order they
* are received.</p>
* </dd>
* <dt>context</dt>
* <dd>the execution context for the callbacks</dd>
* <dt>win</dt>
* <dd>a window other than the one the utility occupies</dd>
* <dt>autopurge</dt>
* <dd>
* setting to true will let the utilities cleanup routine purge
* the script once loaded
* </dd>
* <dt>purgethreshold</dt>
* <dd>
* The number of transaction before autopurge should be initiated
* </dd>
* <dt>data</dt>
* <dd>
* data that is supplied to the callback when the script(s) are
* loaded.
* </dd>
* <dt>insertBefore</dt>
* <dd>node or node id that will become the new node's nextSibling.
* If this is not specified, nodes will be inserted before a base
* tag should it exist. Otherwise, the nodes will be appended to the
* end of the document head.</dd>
* </dl>
* <dt>charset</dt>
* <dd>Node charset, default utf-8 (deprecated, use the attributes
* config)</dd>
* <dt>attributes</dt>
* <dd>An object literal containing additional attributes to add to
* the link tags</dd>
* <dt>timeout</dt>
* <dd>Number of milliseconds to wait before aborting and firing
* the timeout event</dd>
* <pre>
* Y.Get.script(
* ["http://yui.yahooapis.com/2.5.2/build/yahoo/yahoo-min.js",
* "http://yui.yahooapis.com/2.5.2/build/event/event-min.js"],
* {
* onSuccess: function(o) {
* this.log("won't cause error because Y is the context");
* Y.log(o.data); // foo
* Y.log(o.nodes.length === 2) // true
* // o.purge(); // optionally remove the script nodes
* // immediately
* },
* onFailure: function(o) {
* Y.log("transaction failed");
* },
* onTimeout: function(o) {
* Y.log("transaction timed out");
* },
* data: "foo",
* timeout: 10000, // 10 second timeout
* context: Y, // make the YUI instance
* // win: otherframe // target another window/frame
* autopurge: true // allow the utility to choose when to
* // remove the nodes
* purgetheshold: 1 // purge previous transaction before
* // next transaction
* });.
* </pre>
* @return {tId: string} an object containing info about the
* transaction.
*/
script: function(url, opts) {
return _queue(SCRIPT, url, opts);
},
/**
* Fetches and inserts one or more css link nodes into the
* head of the current document or the document in a specified
* window.
* @method css
* @static
* @param {string} url the url or urls to the css file(s).
* @param {object} opts Options:
* <dl>
* <dt>onSuccess</dt>
* <dd>
* callback to execute when the css file(s) are finished loading
* The callback receives an object back with the following
* data:
* <dl>win</dl>
* <dd>the window the link nodes(s) were inserted into</dd>
* <dt>data</dt>
* <dd>the data object passed in when the request was made</dd>
* <dt>nodes</dt>
* <dd>An array containing references to the nodes that were
* inserted</dd>
* <dt>purge</dt>
* <dd>A function that, when executed, will remove the nodes
* that were inserted</dd>
* <dt>
* </dl>
* </dd>
* <dt>onProgress</dt>
* <dd>callback to execute when each individual file is done loading (useful when passing in an array of css files). Receives the same
* payload as onSuccess, with the addition of a <code>url</code> property, which identifies the file which was loaded. Currently only useful for non Webkit/Gecko browsers,
* where onload for css is detected accurately.</dd>
* <dt>async</dt>
* <dd>When passing in an array of css files, setting this flag to true will insert them
* into the document in parallel, as oppposed to the default behavior, which is to chain load them (where possible).
* This flag is more useful for scripts currently, since for css Get only chains if not Webkit/Gecko.</dd>
* <dt>context</dt>
* <dd>the execution context for the callbacks</dd>
* <dt>win</dt>
* <dd>a window other than the one the utility occupies</dd>
* <dt>data</dt>
* <dd>
* data that is supplied to the callbacks when the nodes(s) are
* loaded.
* </dd>
* <dt>insertBefore</dt>
* <dd>node or node id that will become the new node's nextSibling</dd>
* <dt>charset</dt>
* <dd>Node charset, default utf-8 (deprecated, use the attributes
* config)</dd>
* <dt>attributes</dt>
* <dd>An object literal containing additional attributes to add to
* the link tags</dd>
* </dl>
* <pre>
* Y.Get.css("http://localhost/css/menu.css");
* </pre>
* <pre>
* Y.Get.css(
* ["http://localhost/css/menu.css",
* "http://localhost/css/logger.css"], {
* insertBefore: 'custom-styles' // nodes will be inserted
* // before the specified node
* });.
* </pre>
* @return {tId: string} an object containing info about the
* transaction.
*/
css: function(url, opts) {
return _queue('css', url, opts);
}
};
}, '@VERSION@' ,{requires:['yui-base']});
YUI.add('features', function(Y) {
var feature_tests = {};
Y.mix(Y.namespace('Features'), {
tests: feature_tests,
add: function(cat, name, o) {
feature_tests[cat] = feature_tests[cat] || {};
feature_tests[cat][name] = o;
},
all: function(cat, args) {
var cat_o = feature_tests[cat],
// results = {};
result = [];
if (cat_o) {
Y.Object.each(cat_o, function(v, k) {
result.push(k + ':' + (Y.Features.test(cat, k, args) ? 1 : 0));
});
}
return (result.length) ? result.join(';') : '';
},
test: function(cat, name, args) {
args = args || [];
var result, ua, test,
cat_o = feature_tests[cat],
feature = cat_o && cat_o[name];
if (!feature) {
Y.log('Feature test ' + cat + ', ' + name + ' not found');
} else {
result = feature.result;
if (Y.Lang.isUndefined(result)) {
ua = feature.ua;
if (ua) {
result = (Y.UA[ua]);
}
test = feature.test;
if (test && ((!ua) || result)) {
result = test.apply(Y, args);
}
feature.result = result;
}
}
return result;
}
});
// Y.Features.add("load", "1", {});
// Y.Features.test("load", "1");
// caps=1:1;2:0;3:1;
/* This file is auto-generated by src/loader/scripts/meta_join.py */
var add = Y.Features.add;
// graphics-canvas-default
add('load', '0', {
"name": "graphics-canvas-default",
"test": function(Y) {
var DOCUMENT = Y.config.doc,
canvas = DOCUMENT && DOCUMENT.createElement("canvas");
return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (canvas && canvas.getContext && canvas.getContext("2d")));
},
"trigger": "graphics"
});
// autocomplete-list-keys
add('load', '1', {
"name": "autocomplete-list-keys",
"test": function (Y) {
// Only add keyboard support to autocomplete-list if this doesn't appear to
// be an iOS or Android-based mobile device.
//
// There's currently no feasible way to actually detect whether a device has
// a hardware keyboard, so this sniff will have to do. It can easily be
// overridden by manually loading the autocomplete-list-keys module.
//
// Worth noting: even though iOS supports bluetooth keyboards, Mobile Safari
// doesn't fire the keyboard events used by AutoCompleteList, so there's
// no point loading the -keys module even when a bluetooth keyboard may be
// available.
return !(Y.UA.ios || Y.UA.android);
},
"trigger": "autocomplete-list"
});
// graphics-svg
add('load', '2', {
"name": "graphics-svg",
"test": function(Y) {
var DOCUMENT = Y.config.doc;
return (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1"));
},
"trigger": "graphics"
});
// history-hash-ie
add('load', '3', {
"name": "history-hash-ie",
"test": function (Y) {
var docMode = Y.config.doc && Y.config.doc.documentMode;
return Y.UA.ie && (!('onhashchange' in Y.config.win) ||
!docMode || docMode < 8);
},
"trigger": "history-hash"
});
// graphics-vml-default
add('load', '4', {
"name": "graphics-vml-default",
"test": function(Y) {
var DOCUMENT = Y.config.doc,
canvas = DOCUMENT && DOCUMENT.createElement("canvas");
return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (!canvas || !canvas.getContext || !canvas.getContext("2d")));
},
"trigger": "graphics"
});
// graphics-svg-default
add('load', '5', {
"name": "graphics-svg-default",
"test": function(Y) {
var DOCUMENT = Y.config.doc;
return (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1"));
},
"trigger": "graphics"
});
// widget-base-ie
add('load', '6', {
"name": "widget-base-ie",
"trigger": "widget-base",
"ua": "ie"
});
// transition-timer
add('load', '7', {
"name": "transition-timer",
"test": function (Y) {
var DOCUMENT = Y.config.doc,
node = (DOCUMENT) ? DOCUMENT.documentElement: null,
ret = true;
if (node && node.style) {
ret = !('MozTransition' in node.style || 'WebkitTransition' in node.style);
}
return ret;
},
"trigger": "transition"
});
// dom-style-ie
add('load', '8', {
"name": "dom-style-ie",
"test": function (Y) {
var testFeature = Y.Features.test,
addFeature = Y.Features.add,
WINDOW = Y.config.win,
DOCUMENT = Y.config.doc,
DOCUMENT_ELEMENT = 'documentElement',
ret = false;
addFeature('style', 'computedStyle', {
test: function() {
return WINDOW && 'getComputedStyle' in WINDOW;
}
});
addFeature('style', 'opacity', {
test: function() {
return DOCUMENT && 'opacity' in DOCUMENT[DOCUMENT_ELEMENT].style;
}
});
ret = (!testFeature('style', 'opacity') &&
!testFeature('style', 'computedStyle'));
return ret;
},
"trigger": "dom-style"
});
// selector-css2
add('load', '9', {
"name": "selector-css2",
"test": function (Y) {
var DOCUMENT = Y.config.doc,
ret = DOCUMENT && !('querySelectorAll' in DOCUMENT);
return ret;
},
"trigger": "selector"
});
// event-base-ie
add('load', '10', {
"name": "event-base-ie",
"test": function(Y) {
var imp = Y.config.doc && Y.config.doc.implementation;
return (imp && (!imp.hasFeature('Events', '2.0')));
},
"trigger": "node-base"
});
// dd-gestures
add('load', '11', {
"name": "dd-gestures",
"test": function(Y) {
return (Y.config.win && ('ontouchstart' in Y.config.win && !Y.UA.chrome));
},
"trigger": "dd-drag"
});
// scrollview-base-ie
add('load', '12', {
"name": "scrollview-base-ie",
"trigger": "scrollview-base",
"ua": "ie"
});
// graphics-canvas
add('load', '13', {
"name": "graphics-canvas",
"test": function(Y) {
var DOCUMENT = Y.config.doc,
canvas = DOCUMENT && DOCUMENT.createElement("canvas");
return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (canvas && canvas.getContext && canvas.getContext("2d")));
},
"trigger": "graphics"
});
// graphics-vml
add('load', '14', {
"name": "graphics-vml",
"test": function(Y) {
var DOCUMENT = Y.config.doc,
canvas = DOCUMENT && DOCUMENT.createElement("canvas");
return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (!canvas || !canvas.getContext || !canvas.getContext("2d")));
},
"trigger": "graphics"
});
}, '@VERSION@' ,{requires:['yui-base']});
YUI.add('intl-base', function(Y) {
/**
* The Intl utility provides a central location for managing sets of
* localized resources (strings and formatting patterns).
*
* @class Intl
* @uses EventTarget
* @static
*/
var SPLIT_REGEX = /[, ]/;
Y.mix(Y.namespace('Intl'), {
/**
* Returns the language among those available that
* best matches the preferred language list, using the Lookup
* algorithm of BCP 47.
* If none of the available languages meets the user's preferences,
* then "" is returned.
* Extended language ranges are not supported.
*
* @method lookupBestLang
* @param {String[] | String} preferredLanguages The list of preferred
* languages in descending preference order, represented as BCP 47
* language tags. A string array or a comma-separated list.
* @param {String[]} availableLanguages The list of languages
* that the application supports, represented as BCP 47 language
* tags.
*
* @return {String} The available language that best matches the
* preferred language list, or "".
* @since 3.1.0
*/
lookupBestLang: function(preferredLanguages, availableLanguages) {
var i, language, result, index;
// check whether the list of available languages contains language;
// if so return it
function scan(language) {
var i;
for (i = 0; i < availableLanguages.length; i += 1) {
if (language.toLowerCase() ===
availableLanguages[i].toLowerCase()) {
return availableLanguages[i];
}
}
}
if (Y.Lang.isString(preferredLanguages)) {
preferredLanguages = preferredLanguages.split(SPLIT_REGEX);
}
for (i = 0; i < preferredLanguages.length; i += 1) {
language = preferredLanguages[i];
if (!language || language === '*') {
continue;
}
// check the fallback sequence for one language
while (language.length > 0) {
result = scan(language);
if (result) {
return result;
} else {
index = language.lastIndexOf('-');
if (index >= 0) {
language = language.substring(0, index);
// one-character subtags get cut along with the
// following subtag
if (index >= 2 && language.charAt(index - 2) === '-') {
language = language.substring(0, index - 2);
}
} else {
// nothing available for this language
break;
}
}
}
}
return '';
}
});
}, '@VERSION@' ,{requires:['yui-base']});
YUI.add('rls', function(Y) {
/**
* RLS (Remote Loader Service) Support
* @module yui
* @submodule rls
* @class rls
*/
Y.rls_handleTimeout = function(o) {
Y.Get.abort(o.tId);
o.purge();
o.message = 'RLS request timed out, fetching loader';
Y.rls_failure(o);
};
Y.rls_handleFailure = function(o) {
o.message = 'RLS request failed, fetching loader';
Y.rls_failure(o);
};
Y.rls_failure = function(o) {
Y.log(o.message, 'warn', 'rls');
YUI.Env.rls_disabled = true;
Y.config.use_rls = false;
if (o.data) {
o.data.unshift('loader');
Y._use(o.data, function(Y, response) {
Y._notify(Y.rls_callback, response, o.data);
//Call the RLS done method, so it can progress the queue
Y.rls_advance();
});
}
};
/**
* Checks the environment for local modules and deals with them before firing off an RLS request.
* This needs to make sure that all dependencies are calculated before it can make an RLS request in
* order to make sure all remote dependencies are evaluated and their requirements are met.
* @method rls_locals
* @private
* @param {YUI} instance The YUI Instance we are working with.
* @param {Array} argz The requested modules.
* @param {Callback} cb The callback to be executed when we are done
* @param {YUI} cb.instance The instance is passed back to the callback
* @param {Array} cb.argz The modified list or modules needed to require
*/
Y.rls_locals = function(instance, argz, cb) {
if (YUI.Env.rls_disabled) {
var data = {
message: 'RLS is disabled, moving to loader',
data: argz
};
Y.rls_failure(data);
return;
}
if (instance.config.modules) {
var files = [], asked = Y.Array.hash(argz),
PATH = 'fullpath', f,
mods = instance.config.modules;
for (f in mods) {
if (mods[f][PATH]) {
if (asked[f]) {
files.push(mods[f][PATH]);
if (mods[f].requires) {
Y.Array.each(mods[f].requires, function(f) {
if (!YUI.Env.mods[f]) {
if (mods[f]) {
if (mods[f][PATH]) {
files.push(mods[f][PATH]);
argz.push(f);
}
}
}
});
}
}
}
}
if (files.length) {
Y.Get.script(files, {
onEnd: function(o) {
cb(instance, argz);
},
data: argz
});
} else {
cb(instance, argz);
}
} else {
cb(instance, argz);
}
};
/**
* Check the environment and the local config to determine if a module has already been registered.
* @method rls_needs
* @private
* @param {String} mod The module to check
* @param {YUI} instance The instance to check against.
*/
Y.rls_needs = function(mod, instance) {
var self = instance || this,
config = self.config, i,
m = YUI.Env.aliases[mod];
if (m) {
Y.log('We have an alias (' + mod + '), are all the deps available?', 'info', 'rls');
for (i = 0; i < m.length; i++) {
if (Y.rls_needs(m[i])) {
Y.log('Needs (' + mod + ')', 'info', 'rls');
return true;
}
}
Y.log('Does not need (' + mod + ')', 'info', 'rls');
return false;
}
if (!YUI.Env.mods[mod] && !(config.modules && config.modules[mod])) {
Y.log('Needs (' + mod + ')', 'info', 'rls');
return true;
}
Y.log('Does not need (' + mod + ')', 'info', 'rls');
return false;
};
/**
* Implentation for building the remote loader service url.
* @method _rls
* @private
* @param {Array} what the requested modules.
* @since 3.2.0
* @return {string} the url for the remote loader service call, returns false if no modules are required to be fetched (they are in the ENV already).
*/
Y._rls = function(what) {
//what.push('intl');
Y.log('Issuing a new RLS Request', 'info', 'rls');
var config = Y.config,
mods = config.modules,
YArray = Y.Array,
YObject = Y.Object,
// the configuration
rls = config.rls || {
m: 1, // required in the template
v: Y.version,
gv: config.gallery,
env: 1, // required in the template
lang: config.lang,
'2in3v': config['2in3'],
'2v': config.yui2,
filt: config.filter,
filts: config.filters,
ignore: config.ignore,
tests: 1 // required in the template
},
// The rls base path
rls_base = config.rls_base || 'http://l.yimg.com/py/load?httpcache=rls-seed&gzip=1&',
// the template
rls_tmpl = config.rls_tmpl || function() {
var s = [], param;
for (param in rls) {
if (param in rls && rls[param]) {
s.push(param + '={' + param + '}');
}
}
return s.join('&');
}(),
m = [], asked = {}, o, d, mod, a, j,
w = [],
i, len = what.length,
url;
//Explode our aliases..
for (i = 0; i < len; i++) {
a = YUI.Env.aliases[what[i]];
if (a) {
for (j = 0; j < a.length; j++) {
w.push(a[j]);
}
} else {
w.push(what[i]);
}
}
what = w;
len = what.length;
for (i = 0; i < len; i++) {
asked[what[i]] = 1;
if (Y.rls_needs(what[i])) {
Y.log('Did not find ' + what[i] + ' in YUI.Env.mods or config.modules adding to RLS', 'info', 'rls');
m.push(what[i]);
} else {
Y.log(what[i] + ' was skipped from RLS', 'info', 'rls');
}
}
if (mods) {
for (i in mods) {
if (asked[i] && mods[i].requires && !mods[i].noop) {
len = mods[i].requires.length;
for (o = 0; o < len; o++) {
mod = mods[i].requires[o];
if (Y.rls_needs(mod)) {
m.push(mod);
} else {
d = YUI.Env.mods[mod] || mods[mod];
if (d) {
d = d.details || d;
if (!d.noop) {
if (d.requires) {
YArray.each(d.requires, function(o) {
if (Y.rls_needs(o)) {
m.push(o);
}
});
}
}
}
}
}
}
}
}
YObject.each(YUI.Env.mods, function(i) {
if (asked[i.name]) {
if (i.details && i.details.requires) {
if (!i.noop) {
YArray.each(i.details.requires, function(o) {
if (Y.rls_needs(o)) {
m.push(o);
}
});
}
}
}
});
function addIfNeeded(module) {
if (Y.rls_needs(module)) {
m.unshift(module);
}
}
//Add in the debug modules
if (rls.filt === 'debug') {
YArray.each(['dump', 'yui-log'], addIfNeeded);
}
//If they have a groups config, add the loader-base module
if (Y.config.groups) {
addIfNeeded('loader-base');
}
m = YArray.dedupe(m);
//Strip Duplicates
m = YArray.dedupe(m);
what = YArray.dedupe(what);
if (!m.length) {
//Return here if there no modules to load.
Y.log('RLS request terminated, no modules in m', 'warn', 'rls');
return false;
}
// update the request
rls.m = m.sort(); // cache proxy optimization
rls.env = [].concat(YObject.keys(YUI.Env.mods), YArray.dedupe(YUI._rls_skins)).sort();
rls.tests = Y.Features.all('load', [Y]);
url = Y.Lang.sub(rls_base + rls_tmpl, rls);
config.rls = rls;
config.rls_tmpl = rls_tmpl;
YUI._rls_active = {
asked: what,
attach: m,
inst: Y,
url: url
};
return url;
};
/**
*
* @method rls_oncomplete
* @param {Callback} cb The callback to execute when the RLS request is complete
*/
Y.rls_oncomplete = function(cb) {
YUI._rls_active.cb = cb;
};
Y.rls_advance = function() {
var G_ENV = YUI.Env;
G_ENV._rls_in_progress = false;
if (G_ENV._rls_queue.size()) {
G_ENV._rls_queue.next()();
}
};
/**
* Calls the callback registered with Y.rls_oncomplete when the RLS request (and it's dependency requests) is done.
* @method rls_done
* @param {Array} data The modules loaded
*/
Y.rls_done = function(data) {
Y.log('RLS Request complete', 'info', 'rls');
data.success = true;
YUI._rls_active.cb(data);
};
/**
* Hash to hang on to the calling RLS instance so we can deal with the return from the server.
* @property _rls_active
* @private
* @type Object
* @static
*/
if (!YUI._rls_active) {
YUI._rls_active = {};
}
/**
* An array of skins loaded via RLS to populate the ENV with when making future requests.
* @property _rls_skins
* @private
* @type Array
* @static
*/
if (!YUI._rls_skins) {
YUI._rls_skins = [];
}
/**
*
* @method $rls
* @private
* @static
* @param {Object} req The data returned from the RLS server
* @param {String} req.css Does this request need CSS? If so, load the same RLS url with &css=1 attached
* @param {Array} req.module The sorted list of modules to attach to the page.
*/
if (!YUI.$rls) {
YUI.$rls = function(req) {
var rls_active = YUI._rls_active,
Y = rls_active.inst;
if (Y) {
Y.log('RLS request received, processing', 'info', 'rls');
if (req.error) {
Y.rls_failure({
message: req.error,
data: req.modules
});
}
if (YUI.Env && YUI.Env.rls_disabled) {
Y.log('RLS processing on this instance is disabled.', 'warn', 'rls');
return;
}
if (req.css && Y.config.fetchCSS) {
Y.Get.css(rls_active.url + '&css=1');
}
if (req.modules && !req.css) {
if (req.modules.length) {
var loadInt = Y.Array.some(req.modules, function(v) {
return (v.indexOf('lang') === 0);
});
if (loadInt) {
req.modules.unshift('intl');
}
}
Y.Env.bootstrapped = true;
Y.Array.each(req.modules, function(v) {
if (v.indexOf('skin-') > -1) {
Y.log('Found skin (' + v + ') caching module for future requests', 'info', 'rls');
YUI._rls_skins.push(v);
}
});
Y._attach([].concat(req.modules, rls_active.asked));
var additional = req.missing;
if (Y.config.groups) {
if (!additional) {
additional = [];
}
additional = [].concat(additional, rls_active.what);
}
if (additional && Y.Loader) {
Y.log('Making extra Loader request', 'info', 'rls');
var loader = new Y.Loader(rls_active.inst.config);
loader.onEnd = Y.rls_done;
loader.context = Y;
loader.data = additional;
loader.ignoreRegistered = false;
loader.require(additional);
loader.insert(null, (Y.config.fetchCSS) ? null : 'js');
} else {
Y.rls_done({ data: req.modules });
}
}
}
};
}
}, '@VERSION@' ,{requires:['get','features']});
YUI.add('yui-log', function(Y) {
/**
* Provides console log capability and exposes a custom event for
* console implementations. This module is a `core` YUI module, <a href="../classes/YUI.html#method_log">it's documentation is located under the YUI class</a>.
*
* @module yui
* @submodule yui-log
*/
var INSTANCE = Y,
LOGEVENT = 'yui:log',
UNDEFINED = 'undefined',
LEVELS = { debug: 1,
info: 1,
warn: 1,
error: 1 };
/**
* If the 'debug' config is true, a 'yui:log' event will be
* dispatched, which the Console widget and anything else
* can consume. If the 'useBrowserConsole' config is true, it will
* write to the browser console if available. YUI-specific log
* messages will only be present in the -debug versions of the
* JS files. The build system is supposed to remove log statements
* from the raw and minified versions of the files.
*
* @method log
* @for YUI
* @param {String} msg The message to log.
* @param {String} cat The log category for the message. Default
* categories are "info", "warn", "error", time".
* Custom categories can be used as well. (opt).
* @param {String} src The source of the the message (opt).
* @param {boolean} silent If true, the log event won't fire.
* @return {YUI} YUI instance.
*/
INSTANCE.log = function(msg, cat, src, silent) {
var bail, excl, incl, m, f,
Y = INSTANCE,
c = Y.config,
publisher = (Y.fire) ? Y : YUI.Env.globalEvents;
// suppress log message if the config is off or the event stack
// or the event call stack contains a consumer of the yui:log event
if (c.debug) {
// apply source filters
if (src) {
excl = c.logExclude;
incl = c.logInclude;
if (incl && !(src in incl)) {
bail = 1;
} else if (incl && (src in incl)) {
bail = !incl[src];
} else if (excl && (src in excl)) {
bail = excl[src];
}
}
if (!bail) {
if (c.useBrowserConsole) {
m = (src) ? src + ': ' + msg : msg;
if (Y.Lang.isFunction(c.logFn)) {
c.logFn.call(Y, msg, cat, src);
} else if (typeof console != UNDEFINED && console.log) {
f = (cat && console[cat] && (cat in LEVELS)) ? cat : 'log';
console[f](m);
} else if (typeof opera != UNDEFINED) {
opera.postError(m);
}
}
if (publisher && !silent) {
if (publisher == Y && (!publisher.getEvent(LOGEVENT))) {
publisher.publish(LOGEVENT, {
broadcast: 2
});
}
publisher.fire(LOGEVENT, {
msg: msg,
cat: cat,
src: src
});
}
}
}
return Y;
};
/**
* Write a system message. This message will be preserved in the
* minified and raw versions of the YUI files, unlike log statements.
* @method message
* @for YUI
* @param {String} msg The message to log.
* @param {String} cat The log category for the message. Default
* categories are "info", "warn", "error", time".
* Custom categories can be used as well. (opt).
* @param {String} src The source of the the message (opt).
* @param {boolean} silent If true, the log event won't fire.
* @return {YUI} YUI instance.
*/
INSTANCE.message = function() {
return INSTANCE.log.apply(INSTANCE, arguments);
};
}, '@VERSION@' ,{requires:['yui-base']});
YUI.add('yui-later', function(Y) {
/**
* Provides a setTimeout/setInterval wrapper. This module is a `core` YUI module, <a href="../classes/YUI.html#method_later">it's documentation is located under the YUI class</a>.
*
* @module yui
* @submodule yui-later
*/
var NO_ARGS = [];
/**
* Executes the supplied function in the context of the supplied
* object 'when' milliseconds later. Executes the function a
* single time unless periodic is set to true.
* @for YUI
* @method later
* @param when {int} the number of milliseconds to wait until the fn
* is executed.
* @param o the context object.
* @param fn {Function|String} the function to execute or the name of
* the method in the 'o' object to execute.
* @param data [Array] data that is provided to the function. This
* accepts either a single item or an array. If an array is provided,
* the function is executed with one parameter for each array item.
* If you need to pass a single array parameter, it needs to be wrapped
* in an array [myarray].
*
* Note: native methods in IE may not have the call and apply methods.
* In this case, it will work, but you are limited to four arguments.
*
* @param periodic {boolean} if true, executes continuously at supplied
* interval until canceled.
* @return {object} a timer object. Call the cancel() method on this
* object to stop the timer.
*/
Y.later = function(when, o, fn, data, periodic) {
when = when || 0;
data = (!Y.Lang.isUndefined(data)) ? Y.Array(data) : data;
var cancelled = false,
method = (o && Y.Lang.isString(fn)) ? o[fn] : fn,
wrapper = function() {
// IE 8- may execute a setInterval callback one last time
// after clearInterval was called, so in order to preserve
// the cancel() === no more runny-run, we have to jump through
// an extra hoop.
if (!cancelled) {
if (!method.apply) {
method(data[0], data[1], data[2], data[3]);
} else {
method.apply(o, data || NO_ARGS);
}
}
},
id = (periodic) ? setInterval(wrapper, when) : setTimeout(wrapper, when);
return {
id: id,
interval: periodic,
cancel: function() {
cancelled = true;
if (this.interval) {
clearInterval(id);
} else {
clearTimeout(id);
}
}
};
};
Y.Lang.later = Y.later;
}, '@VERSION@' ,{requires:['yui-base']});
YUI.add('yui', function(Y){}, '@VERSION@' ,{use:['yui-base','get','features','intl-base','rls','yui-log','yui-later']});
|
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule PickerIOS
*
* This is a controlled component version of RCTPickerIOS
*/
'use strict';
var NativeMethodsMixin = require('NativeMethodsMixin');
var React = require('React');
var ReactChildren = require('ReactChildren');
var ReactNativeViewAttributes = require('ReactNativeViewAttributes');
var RCTPickerIOSConsts = require('NativeModules').UIManager.RCTPicker.Constants;
var StyleSheet = require('StyleSheet');
var View = require('View');
var requireNativeComponent = require('requireNativeComponent');
var merge = require('merge');
var PICKER = 'picker';
var PickerIOS = React.createClass({
mixins: [NativeMethodsMixin],
propTypes: {
onValueChange: React.PropTypes.func,
selectedValue: React.PropTypes.any, // string or integer basically
},
getInitialState: function() {
return this._stateFromProps(this.props);
},
componentWillReceiveProps: function(nextProps) {
this.setState(this._stateFromProps(nextProps));
},
// Translate PickerIOS prop and children into stuff that RCTPickerIOS understands.
_stateFromProps: function(props) {
var selectedIndex = 0;
var items = [];
ReactChildren.forEach(props.children, function (child, index) {
if (child.props.value === props.selectedValue) {
selectedIndex = index;
}
items.push({value: child.props.value, label: child.props.label});
});
return {selectedIndex, items};
},
render: function() {
return (
<View style={this.props.style}>
<RCTPickerIOS
ref={PICKER}
style={styles.pickerIOS}
items={this.state.items}
selectedIndex={this.state.selectedIndex}
onChange={this._onChange}
/>
</View>
);
},
_onChange: function(event) {
if (this.props.onChange) {
this.props.onChange(event);
}
if (this.props.onValueChange) {
this.props.onValueChange(event.nativeEvent.newValue);
}
// The picker is a controlled component. This means we expect the
// on*Change handlers to be in charge of updating our
// `selectedValue` prop. That way they can also
// disallow/undo/mutate the selection of certain values. In other
// words, the embedder of this component should be the source of
// truth, not the native component.
if (this.state.selectedIndex !== event.nativeEvent.newIndex) {
this.refs[PICKER].setNativeProps({
selectedIndex: this.state.selectedIndex
});
}
},
});
PickerIOS.Item = React.createClass({
propTypes: {
value: React.PropTypes.any, // string or integer basically
label: React.PropTypes.string,
},
render: function() {
// These items don't get rendered directly.
return null;
},
});
var styles = StyleSheet.create({
pickerIOS: {
// The picker will conform to whatever width is given, but we do
// have to set the component's height explicitly on the
// surrounding view to ensure it gets rendered.
height: RCTPickerIOSConsts.ComponentHeight,
},
});
var RCTPickerIOS = requireNativeComponent('RCTPicker', PickerIOS, {
nativeOnly: {
items: true,
onChange: true,
selectedIndex: true,
},
});
module.exports = PickerIOS;
|
/**
* Form Validation
* @module Ink.UI.FormValidator_2
* @version 2
*/
Ink.createModule('Ink.UI.FormValidator', '2', [ 'Ink.UI.Common_1','Ink.Dom.Element_1','Ink.Dom.Event_1','Ink.Dom.Selector_1','Ink.Dom.Css_1','Ink.Util.Array_1','Ink.Util.I18n_1','Ink.Util.Validator_1'], function( Common, Element, Event, Selector, Css, InkArray, I18n, InkValidator ) {
'use strict';
/**
* Validation Functions to be used
* Some functions are a port from PHP, others are the 'best' solutions available
*
* @private
* @static
*/
var validationFunctions = {
/**
* Checks if a value is defined and not empty
* @method required
* @param {String} value Value to be checked
* @return {Boolean} True case is defined, false if it's empty or not defined.
*/
'required': function( value ){
return ( (typeof value !== 'undefined') && ( !(/^\s*$/).test(value) ) );
},
/**
* Checks if a value has a minimum length
*
* @method min_length
* @param {String} value Value to be checked.
* @param {String|Number} minSize Minimum number of characters.
* @return {Boolean} True if the length of value is equal or bigger than the minimum chars defined. False if not.
*/
'min_length': function( value, minSize ){
return ( (typeof value === 'string') && ( value.length >= parseInt(minSize,10) ) );
},
/**
* Checks if a value has a maximum length
*
* @method max_length
* @param {String} value Value to be checked.
* @param {String|Number} maxSize Maximum number of characters.
* @return {Boolean} True if the length of value is equal or smaller than the maximum chars defined. False if not.
*/
'max_length': function( value, maxSize ){
return ( (typeof value === 'string') && ( value.length <= parseInt(maxSize,10) ) );
},
/**
* Checks if a value has an exact length
*
* @method exact_length
* @param {String} value Value to be checked
* @param {String|Number} exactSize Exact number of characters.
* @return {Boolean} True if the length of value is equal to the size defined. False if not.
*/
'exact_length': function( value, exactSize ){
return ( (typeof value === 'string') && ( value.length === parseInt(exactSize,10) ) );
},
/**
* Checks if a value is a valid email address
*
* @method email
* @param {String} value Value to be checked
* @return {Boolean} True if the value is a valid email address. False if not.
*/
'email': function( value ){
return ( ( typeof value === 'string' ) && InkValidator.mail( value ) );
},
/**
* Checks if a value has a valid URL
*
* @method url
* @param {String} value Value to be checked
* @param {Boolean} fullCheck Flag to validate a full url (with the protocol).
* @return {Boolean} True if the URL is considered valid. False if not.
*/
'url': function( value, fullCheck ){
fullCheck = fullCheck || false;
return ( (typeof value === 'string') && InkValidator.url( value, fullCheck ) );
},
/**
* Checks if a value is a valid IP. Supports ipv4 and ipv6
*
* @method ip
* @param {String} value Value to be checked
* @param {String} ipType Type of IP to be validated. The values are: ipv4, ipv6. By default is ipv4.
* @return {Boolean} True if the value is a valid IP address. False if not.
*/
'ip': function( value, ipType ){
if( typeof value !== 'string' ){
return false;
}
return InkValidator.isIP(value, ipType);
},
/**
* Checks if a value is a valid phone number.
* Supports several countries, based in the Ink.Util.Validator class.
*
* @method phone
* @param {String} value Value to be checked
* @param {String} phoneType Country's initials to specify the type of phone number to be validated. Ex: 'AO'.
* @return {Boolean} True if it's a valid phone number. False if not.
*/
'phone': function( value, phoneType ){
if( typeof value !== 'string' ){
return false;
}
var countryCode = phoneType ? phoneType.toUpperCase() : '';
return InkValidator['is' + countryCode + 'Phone'](value);
},
/**
* Checks if a value is a valid credit card.
*
* @method credit_card
* @param {String} value Value to be checked
* @param {String} cardType Type of credit card to be validated. The card types available are in the Ink.Util.Validator class.
* @return {Boolean} True if the value is a valid credit card number. False if not.
*/
'credit_card': function( value, cardType ){
if( typeof value !== 'string' ){
return false;
}
return InkValidator.isCreditCard( value, cardType || 'default' );
},
/**
* Checks if a value is a valid date.
*
* @method date
* @param {String} value Value to be checked
* @param {String} format Specific format of the date.
* @return {Boolean} True if the value is a valid date. False if not.
*/
'date': function( value, format ){
return ( (typeof value === 'string' ) && InkValidator.isDate(format, value) );
},
/**
* Checks if a value only contains alphabetical values.
*
* @method alpha
* @param {String} value Value to be checked
* @param {Boolean} supportSpaces Allow whitespace
* @return {Boolean} True if the value is alphabetical-only. False if not.
*/
'alpha': function( value, supportSpaces ){
return InkValidator.ascii(value, {singleLineWhitespace: supportSpaces});
},
/*
* Checks if a value contains only printable BMP unicode characters
* Optionally allow punctuation and whitespace
*
* @method text
* @param {String} value Value to be checked
* @return {Boolean} Whether the value only contains printable text characters
**/
'text': function (value, whitespace, punctuation) {
return InkValidator.unicode(value, {
singleLineWhitespace: whitespace,
unicodePunctuation: punctuation});
},
/*
* Checks if a value contains only printable latin-1 text characters.
* Optionally allow punctuation and whitespace.
*
* @method text
* @param {String} value Value to be checked
* @return {Boolean} Whether the value only contains printable text characters
**/
'latin': function (value, punctuation, whitespace) {
if ( typeof value !== 'string') { return false; }
return InkValidator.latin1(value, {latin1Punctuation: punctuation, singleLineWhitespace: whitespace});
},
/**
* Checks if a value contains only alphabetical or numerical characters.
*
* @method alpha_numeric
* @param {String} value Value to be checked
* @return {Boolean} True if the value is a valid alphanumerical. False if not.
*/
'alpha_numeric': function( value ){
return InkValidator.ascii(value, {numbers: true});
},
/**
* Checks if a value contains only alphabetical, dash or underscore characteres.
*
* @method alpha_dashes
* @param {String} value Value to be checked
* @return {Boolean} True if the value is a valid. False if not.
*/
'alpha_dash': function( value ){
return InkValidator.ascii(value, {dash: true, underscore: true});
},
/**
* Checks if a value is a single digit.
*
* @method digit
* @param {String} value Value to be checked
* @return {Boolean} True if the value is a valid digit. False if not.
*/
'digit': function( value ){
return ((typeof value === 'string') && /^[0-9]{1}$/.test(value));
},
/**
* Checks if a value is a valid integer.
*
* @method integer
* @param {String} value Value to be checked
* @param {String} positive Flag that specifies if the integer is must be positive (unsigned).
* @return {Boolean} True if the value is a valid integer. False if not.
*/
'integer': function( value, positive ){
return InkValidator.number(value, {
negative: !positive,
decimalPlaces: 0
});
},
/**
* Checks if a value is a valid decimal number.
*
* @method decimal
* @param {String} value Value to be checked
* @param {String} decimalSeparator Character that splits the integer part from the decimal one. By default is '.'.
* @param {String} [decimalPlaces] Maximum number of digits that the decimal part must have.
* @param {String} [leftDigits] Maximum number of digits that the integer part must have, when provided.
* @return {Boolean} True if the value is a valid decimal number. False if not.
*/
'decimal': function( value, decimalSeparator, decimalPlaces, leftDigits ){
return InkValidator.number(value, {
decimalSep: decimalSeparator || '.',
decimalPlaces: +decimalPlaces || null,
maxDigits: +leftDigits
});
},
/**
* Checks if a value is a numeric value.
*
* @method numeric
* @param {String} value Value to be checked
* @param {String} decimalSeparator Checks if it's a valid decimal. Otherwise checks if it's a valid integer.
* @param {String} [decimalPlaces] Maximum number of digits the decimal part must have.
* @param {String} [leftDigits] Maximum number of digits the integer part must have, when provided.
* @return {Boolean} True if the value is numeric. False if not.
*/
'numeric': function( value, decimalSeparator, decimalPlaces, leftDigits ){
decimalSeparator = decimalSeparator || '.';
if( value.indexOf(decimalSeparator) !== -1 ){
return validationFunctions.decimal( value, decimalSeparator, decimalPlaces, leftDigits );
} else {
return validationFunctions.integer( value );
}
},
/**
* Checks if a value is in a specific range of values.
* The parameters after the first one are used to specify the range, and are similar in function to python's range() function.
*
* @method range
* @param {String} value Value to be checked
* @param {String} minValue Left limit of the range.
* @param {String} maxValue Right limit of the range.
* @param {String} [multipleOf] In case you want numbers that are only multiples of another number.
* @return {Boolean} True if the value is within the range. False if not.
*/
'range': function( value, minValue, maxValue, multipleOf ){
value = +value;
minValue = +minValue;
maxValue = +maxValue;
if (isNaN(value) || isNaN(minValue) || isNaN(maxValue)) {
return false;
}
if( value < minValue || value > maxValue ){
return false;
}
if (multipleOf) {
return (value - minValue) % multipleOf === 0;
} else {
return true;
}
},
/**
* Checks if a value is a valid color.
*
* @method color
* @param {String} value Value to be checked
* @return {Boolean} True if the value is a valid color. False if not.
*/
'color': function( value ){
return InkValidator.isColor(value);
},
/**
* Checks if a value matches the value of a different field.
*
* @method matches
* @param {String} value Value to be checked
* @param {String} fieldToCompare Name or ID of the field to compare.
* @return {Boolean} True if the values match. False if not.
*/
'matches': function( value, fieldToCompare ){
return ( value === this.getFormElements()[fieldToCompare][0].getValue() );
}
};
/**
* Error messages for the validation functions above
* @private
* @static
*/
var validationMessages = new I18n({
en_US: {
'formvalidator.required' : 'The {field} filling is mandatory',
'formvalidator.min_length': 'The {field} must have a minimum size of {param1} characters',
'formvalidator.max_length': 'The {field} must have a maximum size of {param1} characters',
'formvalidator.exact_length': 'The {field} must have an exact size of {param1} characters',
'formvalidator.email': 'The {field} must have a valid e-mail address',
'formvalidator.url': 'The {field} must have a valid URL',
'formvalidator.ip': 'The {field} does not contain a valid {param1} IP address',
'formvalidator.phone': 'The {field} does not contain a valid {param1} phone number',
'formvalidator.credit_card': 'The {field} does not contain a valid {param1} credit card',
'formvalidator.date': 'The {field} should contain a date in the {param1} format',
'formvalidator.alpha': 'The {field} should only contain letters',
'formvalidator.text': 'The {field} should only contain alphabetic characters',
'formvalidator.latin': 'The {field} should only contain alphabetic characters',
'formvalidator.alpha_numeric': 'The {field} should only contain letters or numbers',
'formvalidator.alpha_dashes': 'The {field} should only contain letters or dashes',
'formvalidator.digit': 'The {field} should only contain a digit',
'formvalidator.integer': 'The {field} should only contain an integer',
'formvalidator.decimal': 'The {field} should contain a valid decimal number',
'formvalidator.numeric': 'The {field} should contain a number',
'formvalidator.range': 'The {field} should contain a number between {param1} and {param2}',
'formvalidator.color': 'The {field} should contain a valid color',
'formvalidator.matches': 'The {field} should match the field {param1}',
'formvalidator.validation_function_not_found': 'The rule {rule} has not been defined'
},
pt_PT: {
'formvalidator.required' : 'Preencher {field} é obrigatório',
'formvalidator.min_length': '{field} deve ter no mínimo {param1} caracteres',
'formvalidator.max_length': '{field} tem um tamanho máximo de {param1} caracteres',
'formvalidator.exact_length': '{field} devia ter exactamente {param1} caracteres',
'formvalidator.email': '{field} deve ser um e-mail válido',
'formvalidator.url': 'O {field} deve ser um URL válido',
'formvalidator.ip': '{field} não tem um endereço IP {param1} válido',
'formvalidator.phone': '{field} deve ser preenchido com um número de telefone {param1} válido.',
'formvalidator.credit_card': '{field} não tem um cartão de crédito {param1} válido',
'formvalidator.date': '{field} deve conter uma data no formato {param1}',
'formvalidator.alpha': 'O campo {field} deve conter apenas caracteres alfabéticos',
'formvalidator.text': 'O campo {field} deve conter apenas caracteres alfabéticos',
'formvalidator.latin': 'O campo {field} deve conter apenas caracteres alfabéticos',
'formvalidator.alpha_numeric': '{field} deve conter apenas letras e números',
'formvalidator.alpha_dashes': '{field} deve conter apenas letras e traços',
'formvalidator.digit': '{field} destina-se a ser preenchido com apenas um dígito',
'formvalidator.integer': '{field} deve conter um número inteiro',
'formvalidator.decimal': '{field} deve conter um número válido',
'formvalidator.numeric': '{field} deve conter um número válido',
'formvalidator.range': '{field} deve conter um número entre {param1} e {param2}',
'formvalidator.color': '{field} deve conter uma cor válida',
'formvalidator.matches': '{field} deve corresponder ao campo {param1}',
'formvalidator.validation_function_not_found': '[A regra {rule} não foi definida]'
}
}, 'en_US');
/**
* Constructor of a FormElement.
* This type of object has particular methods to parse rules and validate them in a specific DOM Element.
*
* @param {DOMElement} element DOM Element
* @param {Object} options Object with configuration options
* @return {FormElement} FormElement object
*/
var FormElement = function( element, options ){
this._element = Common.elOrSelector( element, 'Invalid FormElement' );
this._errors = {};
this._rules = {};
this._value = null;
this._options = Ink.extendObj( {
label: this._getLabel()
}, Element.data(this._element) );
this._options = Ink.extendObj( this._options, options || {} );
};
/**
* FormElement's prototype
*/
FormElement.prototype = {
/**
* Function to get the label that identifies the field.
* If it can't find one, it will use the name or the id
* (depending on what is defined)
*
* @method _getLabel
* @return {String} Label to be used in the error messages
* @private
*/
_getLabel: function(){
var controlGroup = Element.findUpwardsByClass(this._element,'control-group');
var label = Ink.s('label',controlGroup);
if( label ){
label = Element.textContent(label);
} else {
label = this._element.name || this._element.id || '';
}
return label;
},
/**
* Function to parse a rules' string.
* Ex: required|number|max_length[30]
*
* @method _parseRules
* @param {String} rules String with the rules
* @private
*/
_parseRules: function( rules ){
this._rules = {};
rules = rules.split("|");
var i, rulesLength = rules.length, rule, params, paramStartPos ;
if( rulesLength > 0 ){
for( i = 0; i < rulesLength; i++ ){
rule = rules[i];
if( !rule ){
continue;
}
if( ( paramStartPos = rule.indexOf('[') ) !== -1 ){
params = rule.substr( paramStartPos+1 );
params = params.split(']');
params = params[0];
params = params.split(',');
for (var p = 0, len = params.length; p < len; p++) {
params[p] =
params[p] === 'true' ? true :
params[p] === 'false' ? false :
params[p];
}
params.splice(0,0,this.getValue());
rule = rule.substr(0,paramStartPos);
this._rules[rule] = params;
} else {
this._rules[rule] = [this.getValue()];
}
}
}
},
/**
* Function to add an error to the FormElement's 'errors' object.
* It basically receives the rule where the error occurred, the parameters passed to it (if any)
* and the error message.
* Then it replaces some tokens in the message for a more 'custom' reading
*
* @method _addError
* @param {String|null} rule Rule that failed, or null if no rule was found.
* @private
* @static
*/
_addError: function(rule){
var params = this._rules[rule] || [];
var paramObj = {
field: this._options.label,
value: this.getValue()
};
for( var i = 1; i < params.length; i++ ){
paramObj['param' + i] = params[i];
}
var i18nKey = 'formvalidator.' + rule;
this._errors[rule] = validationMessages.text(i18nKey, paramObj);
if (this._errors[rule] === i18nKey) {
this._errors[rule] = 'Validation message not found';
}
},
/**
* Gets an element's value
*
* @method getValue
* @return {mixed} The DOM Element's value
* @public
*/
getValue: function(){
switch(this._element.nodeName.toLowerCase()){
case 'select':
return Ink.s('option:selected',this._element).value;
case 'textarea':
return this._element.value;
case 'input':
if( "type" in this._element ){
if( (this._element.type === 'radio') || (this._element.type === 'checkbox') ){
if( this._element.checked ){
return this._element.value;
}
} else if( this._element.type !== 'file' ){
return this._element.value;
}
} else {
return this._element.value;
}
return;
default:
return this._element.innerHTML;
}
},
/**
* Gets the constructed errors' object.
*
* @method getErrors
* @return {Object} Errors' object
* @public
*/
getErrors: function(){
return this._errors;
},
/**
* Gets the DOM element related to the instance.
*
* @method getElement
* @return {Object} DOM Element
* @public
*/
getElement: function(){
return this._element;
},
/**
* Gets other elements in the same form.
*
* @method getFormElements
* @return {Object} A mapping of keys to other elements in this form.
* @public
*/
getFormElements: function () {
return this._options.form._formElements;
},
/**
* Validates the element based on the rules defined.
* It parses the rules defined in the _options.rules property.
*
* @method validate
* @return {Boolean} True if every rule was valid. False if one fails.
* @public
*/
validate: function(){
this._errors = {};
if( "rules" in this._options || 1){
this._parseRules( this._options.rules );
}
if( ("required" in this._rules) || (this.getValue() !== '') ){
for(var rule in this._rules) {
if (this._rules.hasOwnProperty(rule)) {
if( (typeof validationFunctions[rule] === 'function') ){
if( validationFunctions[rule].apply(this, this._rules[rule] ) === false ){
this._addError( rule );
return false;
}
} else {
Ink.warn('Rule "' + rule + '" not found. Used in element:', this._element);
this._addError( null );
return false;
}
}
}
}
return true;
}
};
/**
* @class Ink.UI.FormValidator_2
* @version 2
* @constructor
* @param {String|DOMElement} selector Either a CSS Selector string, or the form's DOMElement
* @param {Object} [options] Options object, containing the following options:
* @param {String} [options.eventTrigger] Event that will trigger the validation. Defaults to 'submit'.
* @param {Boolean} [options.neverSubmit] Flag to cancel the submit event. Use this to avoid submitting the form.
* @param {Selector} [options.searchFor] Selector containing the validation data-attributes. Defaults to 'input, select, textarea, .control-group'.
* @param {Function} [options.beforeValidation] Callback to be executed before validating the form
* @param {Function} [options.onError] Validation error callback
* @param {Function} [options.onSuccess] Validation success callback
*
* @sample Ink_UI_FormValidator_2.html
*/
var FormValidator = function( selector, options ){
/**
* DOMElement of the form being validated
*
* @property _rootElement
* @type {DOMElement}
*/
this._rootElement = Common.elOrSelector( selector );
/**
* Object that will gather the form elements by name
*
* @property _formElements
* @type {Object}
*/
this._formElements = {};
/**
* Error message DOMElements
*
* @property _errorMessages
*/
this._errorMessages = [];
/**
* Array of elements marked with validation errors
*
* @property _markedErrorElements
*/
this._markedErrorElements = [];
/**
* Configuration options. Fetches the data attributes first, then the ones passed when executing the constructor.
* By doing that, the latter will be the one with highest priority.
*
* @property _options
* @type {Object}
*/
this._options = Ink.extendObj({
eventTrigger: 'submit',
neverSubmit: 'false',
searchFor: 'input, select, textarea, .control-group',
beforeValidation: undefined,
onError: undefined,
onSuccess: undefined
},Element.data(this._rootElement));
this._options = Ink.extendObj( this._options, options || {} );
// Sets an event listener for a specific event in the form, if defined.
// By default is the 'submit' event.
if( typeof this._options.eventTrigger === 'string' ){
Event.observe( this._rootElement,this._options.eventTrigger, Ink.bindEvent(this.validate,this) );
}
Common.registerInstance(this, this._rootElement);
this._init();
};
/**
* Sets or modifies validation functions
*
* @method setRule
* @param {String} name Name of the function. E.g. 'required'
* @param {String} errorMessage Error message to be displayed in case of returning false. E.g. 'Oops, you passed {param1} as parameter1, lorem ipsum dolor...'
* @param {Function} cb Function to be executed when calling this rule
* @public
* @static
*/
FormValidator.setRule = function( name, errorMessage, cb ){
validationFunctions[ name ] = cb;
if (validationMessages.getKey('formvalidator.' + name) !== errorMessage) {
var langObj = {}; langObj['formvalidator.' + name] = errorMessage;
var dictObj = {}; dictObj[validationMessages.lang()] = langObj;
validationMessages.append(dictObj);
}
};
/**
* Gets the i18n object in charge of the error messages
*
* @method getI18n
* @return {Ink.Util.I18n} The i18n object the FormValidator is using.
*/
FormValidator.getI18n = function () {
return validationMessages;
};
/**
* Sets the I18n object for validation error messages
*
* @method setI18n
* @param {Ink.Util.I18n} i18n The I18n object.
*/
FormValidator.setI18n = function (i18n) {
validationMessages = i18n;
};
/**
* Add to the I18n dictionary.
* See `Ink.Util.I18n.append()` documentation.
*
* @method AppendI18n
*/
FormValidator.appendI18n = function () {
validationMessages.append.apply(validationMessages, [].slice.call(arguments));
};
/**
* Sets the language of the error messages.
* pt_PT and en_US are available, but you can add new languages by using append()
*
* See the `Ink.Util.I18n.lang()` setter
*
* @method setLanguage
* @param language The language to set i18n to.
*/
FormValidator.setLanguage = function (language) {
validationMessages.lang(language);
};
/**
* Method used to get the existing defined validation functions
*
* @method getRules
* @return {Object} Object with the rules defined
* @public
* @static
*/
FormValidator.getRules = function(){
return validationFunctions;
};
FormValidator.prototype = {
_init: function(){
},
/**
* Searches for the elements in the form.
* This method is based in the this._options.searchFor configuration.
*
* @method getElements
* @return {Object} An object with the elements in the form, indexed by name/id
* @public
*/
getElements: function(){
this._formElements = {};
var formElements = Selector.select( this._options.searchFor, this._rootElement );
if( formElements.length ){
var i, element;
for( i=0; i<formElements.length; i+=1 ){
element = formElements[i];
var dataAttrs = Element.data( element );
if( !("rules" in dataAttrs) ){
continue;
}
var options = {
form: this
};
var key;
if( ("name" in element) && element.name ){
key = element.name;
} else if( ("id" in element) && element.id ){
key = element.id;
} else {
key = 'element_' + Math.floor(Math.random()*100);
element.id = key;
}
if( !(key in this._formElements) ){
this._formElements[key] = [ new FormElement( element, options ) ];
} else {
this._formElements[key].push( new FormElement( element, options ) );
}
}
}
return this._formElements;
},
/**
* Validates every registered FormElement
* This method looks inside the this._formElements object for validation targets.
* Also, based on the this._options.beforeValidation, this._options.onError, and this._options.onSuccess, this callbacks are executed when defined.
*
* @method validate
* @param {Event} event Window.event object
* @return {Boolean}
* @public
*/
validate: function( event ) {
if(this._options.neverSubmit+'' === 'true' && event) {
Event.stopDefault(event);
}
if( typeof this._options.beforeValidation === 'function' ){
this._options.beforeValidation();
}
InkArray.each( this._markedErrorElements, function (errorElement) {
Css.removeClassName(errorElement, ['validation', 'error']);
});
InkArray.each( this._errorMessages, Element.remove);
this.getElements();
var errorElements = [];
for( var key in this._formElements ){
if( this._formElements.hasOwnProperty(key) ){
for( var counter = 0; counter < this._formElements[key].length; counter+=1 ){
if( !this._formElements[key][counter].validate() ) {
errorElements.push(this._formElements[key][counter]);
}
}
}
}
if( errorElements.length === 0 ){
if( typeof this._options.onSuccess === 'function' ){
this._options.onSuccess();
}
// [3.0.0] remove this, it's a little backwards compat quirk
if(event && this._options.cancelEventOnSuccess + '' === 'true') {
Event.stopDefault(event);
return false;
}
return true;
} else {
if(event) {
Event.stopDefault(event);
}
if( typeof this._options.onError === 'function' ){
this._options.onError( errorElements );
}
this._errorMessages = [];
this._markedErrorElements = [];
InkArray.each( errorElements, Ink.bind(function( formElement ){
var controlGroupElement;
var controlElement;
if( Css.hasClassName(formElement.getElement(),'control-group') ){
controlGroupElement = formElement.getElement();
controlElement = Ink.s('.control',formElement.getElement());
} else {
controlGroupElement = Element.findUpwardsByClass(formElement.getElement(),'control-group');
controlElement = Element.findUpwardsByClass(formElement.getElement(),'control');
}
if(controlGroupElement) {
Css.addClassName( controlGroupElement, ['validation', 'error'] );
this._markedErrorElements.push(controlGroupElement);
}
var paragraph = document.createElement('p');
Css.addClassName(paragraph,'tip');
if (controlElement || controlGroupElement) {
(controlElement || controlGroupElement).appendChild(paragraph);
} else {
Element.insertAfter(paragraph, formElement.getElement());
}
var errors = formElement.getErrors();
var errorArr = [];
for (var k in errors) {
if (errors.hasOwnProperty(k)) {
errorArr.push(errors[k]);
}
}
paragraph.innerHTML = errorArr.join('<br/>');
this._errorMessages.push(paragraph);
}, this));
return false;
}
}
};
/**
* Returns the FormValidator's Object
*/
return FormValidator;
});
|
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
/**
* <%= model.pascalCaseSingular %> Schema
*/
var <%= model.pascalCaseSingular %>Schema = new Schema({<% model.elements.forEach(function(element) { %>
<% if ( ['Schema.Types.ObjectId', 'File'].indexOf(element.elementtype)>-1 ) { %>
<%= element.elementname %>: <% if (element.isarray === true){%>[<% }%>{type: Schema.Types.ObjectId, ref: '<%= element.schemaobjref %>'}<% if (element.isarray === true){%>]<% } %>,
<% } else if (element.elementtype === 'Nested') { %>
<%= element.elementname %>: <% if (element.isarray === true){%>[<% } %>{
<% element.elements.forEach(function(nestedelement) { %>
<% if ( nestedelement.elementtype === 'Schema.Types.ObjectId' ) { %>
<%= nestedelement.elementname %>:{type: <%= nestedelement.elementtype %>, ref: '<%= nestedelement.schemaobjref %>'},
<% } else { %>
<%= nestedelement.elementname %>: <%= nestedelement.elementtype %>,
<% } %>
<% }); %>
}<% if (element.isarray === true){%>]<% } %>,
<% } else { %>
<%= element.elementname %>: <%= element.elementtype %>,
<% } %><% }); %>
created: {type: Date, default: Date.now},
user: {type: Schema.ObjectId, ref: 'User'}
});
mongoose.model('<%= model.pascalCaseSingular %>', <%= model.pascalCaseSingular %>Schema); |
import {
Card,
} from '@card-game/core';
class Suits extends Enum {}
Suits.initEnum(['RED', 'GREEN', 'BLUE', 'YELLOW']);
class Ranks extends Enum {}
Ranks.initEnum(['ZERO', 'ONE', 'TWO', 'THREE', 'FOUR', 'FIVE', 'SIX', 'SEVEN', 'EIGHT', 'NINE', 'SKIP', 'DRAW_TWO', 'REVERSE']);
class Wilds extends Enum {}
Wilds.initEnum(['WILD', 'DRAW_FOUR']);
export default class UNOCard extends Card {
static get SUITS() {
return Suits;
}
static get RANKS() {
return Ranks;
}
static get WILDS() {
return Wilds;
}
constructor(suit, rank, owner) {
super({ suit, rank }, owner);
}
} |
var jfs = require('json-schema-faker');
var mout = require('mout');
var Joi = require('joi');
var bluebird = require('bluebird');
var HapiFaker = function(options) {
if (!(this instanceof HapiFaker))
return new HapiFaker(options);
var result = Joi.validate(options, Joi.object({
schemas: Joi.array().items(Joi.object({
id: Joi.string().required(),
type: Joi.string().required()
}).unknown(true)).optional().default([]),
attachAt: Joi.string().only(['onRequest', 'onPreAuth', 'onPostAuth',
'onPreHandler', 'onPostHandler', 'onPreResponse'
]).default('onPostAuth'),
hooks: Joi.object({
request: Joi.func().optional()
}).optional().default({}),
jfs: Joi.func().optional().default(undefined)
}).optional().default({}));
if (result.error)
throw result.error;
this._options = mout.lang.deepClone(result.value);
if (!this._options.jfs)
this._options.jfs = jfs;
};
HapiFaker.prototype.attach = function(server) {
this._server = server;
// Capture requests to do the default job
server.ext(this._options.attachAt, this._hook, {
bind: this
});
// Add a new handler in case the user want's to
server.handler('faker', this._handler.bind(this));
// Add a new method in the reply interface
server.decorate('reply', 'faker', this._decorator(this));
// Expose our options server wide
server.expose('options', mout.lang.deepClone(this._options));
};
HapiFaker.prototype._hook = function(request, reply) {
var settings = request.route.settings.plugins;
var that = this;
// If this route isn't configured for faker, just ignore
if (!settings || !settings.faker)
return reply.continue();
var req = this._options.hooks.request;
bluebird
.resolve()
.then(req ? req.bind(this, request, reply) : function() {
return true;
})
.then(function(enable) {
if (!enable)
return reply.continue();
return bluebird
.resolve(that._genData(settings.faker))
.then(function(data) {
reply(data);
});
}).catch(function(err) {
// Enable Hapi to handle our errors
process.nextTick(function() {
throw err;
});
});
};
HapiFaker.prototype._handler = function(route, options) {
var that = this;
return function(request, reply) {
reply(that._genData(options));
};
};
HapiFaker.prototype._decorator = function(ctx) {
var that = ctx;
return function(input) {
this(that._genData(input));
};
};
HapiFaker.prototype._genData = function(input) {
var schema = null;
if (typeof input === 'string')
schema = this._options.schemas.filter(function(s) {
return s.id === input;
})[0];
else
schema = input;
if (!schema)
throw new Error('Unknown faker schema with ID ' + input);
// Do not modify the original schema
schema = mout.lang.deepClone(schema);
return this._options.jfs(schema, this._options.schemas);
};
module.exports = HapiFaker;
|
/**
* Created by Guoliang Cui on 2015/5/5.
*/
var utility=require('../lib/utility');
var ConfigInfo=require("../../config/baseConfig")
exports.getVersion=function(req,res){
var params=utility.parseParams(req).query;
var resultObj;
resultObj=utility.jsonResult(false,"OK",{version:ConfigInfo.basicSettings[params.key]});
res.send(resultObj);
} |
/* eslint-env mocha */
import path from 'path';
import fs from 'fs';
import assert from 'assert';
import {transformFileSync} from 'babel-core';
function trim(str) {
return str.replace(/^\s+|\s+$/, '');
}
describe('Transpile ES7 async/await to vanilla ES6 Promise chains -', function () {
// sometimes 2000 isn't enough when starting up in coverage mode.
this.timeout(5000);
const fixturesDir = path.join(__dirname, 'fixtures');
fs.readdirSync(fixturesDir).forEach(caseName => {
const fixtureDir = path.join(fixturesDir, caseName);
const actualPath = path.join(fixtureDir, 'actual.js');
if (!fs.statSync(fixtureDir).isDirectory()) {
return;
}
it(caseName.split('-').join(' '), () => {
const actual = transformFileSync(actualPath).code;
const expected = fs.readFileSync(
path.join(fixtureDir, 'expected.js')
).toString();
assert.equal(trim(actual), trim(expected));
});
});
});
|
#!/usr/bin/env node
"use strict";
var setupThrobber = require("../../throbber")
, throbber = setupThrobber(process.stdout.write.bind(process.stdout), 200);
process.stdout.write("START");
throbber.start();
setTimeout(throbber.stop, 1100);
|
import { Constants, Feature } from 'alpheios-data-models'
import Morpheme from '@lib/morpheme.js'
import Form from '@lib/form.js'
import Table from '@views/lib/table.js'
import GreekView from '../greek-view.js'
import GroupFeatureType from '../../../lib/group-feature-type.js'
export default class GreekNumeralView extends GreekView {
constructor (homonym, inflectionData) {
super(homonym, inflectionData)
this.id = 'numeralDeclension'
this.name = 'numeral declension'
this.title = 'Numeral declension'
this.partOfSpeech = this.constructor.mainPartOfSpeech
this.lemmaTypeFeature = new Feature(Feature.types.hdwd, this.constructor.dataset.getNumeralGroupingLemmas(), GreekNumeralView.languageID)
this.features.lemmas = new GroupFeatureType(Feature.types.hdwd, this.constructor.languageID, 'Lemma',
this.constructor.dataset.getNumeralGroupingLemmaFeatures())
this.features.genders.getOrderedFeatures = this.constructor.getOrderedGenders
this.features.genders.getTitle = this.constructor.getGenderTitle
this.features.genders.filter = this.constructor.genderFilter
this.features.genders.comparisonType = Morpheme.comparisonTypes.PARTIAL
if (this.isImplemented) {
this.createTable()
}
}
static get viewID () {
return 'greek_numeral_view'
}
static get partsOfSpeech () {
return [Constants.POFS_NUMERAL]
}
static get inflectionType () {
return Form
}
createTable () {
this.table = new Table([this.features.lemmas, this.features.genders, this.features.types, this.features.numbers, this.features.cases])
let features = this.table.features // eslint-disable-line prefer-const
features.columns = [
this.lemmaTypeFeature,
this.constructor.model.typeFeature(Feature.types.gender),
this.constructor.model.typeFeature(Feature.types.type)
]
features.rows = [
this.constructor.model.typeFeature(Feature.types.number),
this.constructor.model.typeFeature(Feature.types.grmCase)
]
features.columnRowTitles = [
this.constructor.model.typeFeature(Feature.types.grmCase)
]
features.fullWidthRowTitles = [this.constructor.model.typeFeature(Feature.types.number)]
}
static getOrderedGenders (ancestorFeatures) {
const lemmaValues = GreekView.dataset.getNumeralGroupingLemmas()
// Items below are lemmas
const ancestorValue = ancestorFeatures[ancestorFeatures.length - 1].value
if (ancestorValue === lemmaValues[1]) {
return [
this.featureMap.get(GreekView.datasetConsts.GEND_MASCULINE_FEMININE_NEUTER)
]
} else if ([lemmaValues[2], lemmaValues[3]].includes(ancestorValue)) {
return [
this.featureMap.get(GreekView.datasetConsts.GEND_MASCULINE_FEMININE),
this.featureMap.get(Constants.GEND_NEUTER)
]
} else {
return [
this.featureMap.get(Constants.GEND_FEMININE),
this.featureMap.get(Constants.GEND_MASCULINE),
this.featureMap.get(Constants.GEND_NEUTER)
]
}
}
static genderFilter (featureValues, suffix) {
// If not an array, convert it to array for uniformity
if (!Array.isArray(featureValues)) {
featureValues = [featureValues]
}
for (const value of featureValues) {
if (suffix.features[this.type] === value) {
return true
}
}
return false
}
static getGenderTitle (featureValue) {
if (featureValue === Constants.GEND_MASCULINE) { return 'm.' }
if (featureValue === Constants.GEND_FEMININE) { return 'f.' }
if (featureValue === Constants.GEND_NEUTER) { return 'n.' }
if (featureValue === GreekView.datasetConsts.GEND_MASCULINE_FEMININE) { return 'f./m.' }
if (featureValue === GreekView.datasetConsts.GEND_MASCULINE_FEMININE_NEUTER) { return 'f./m./n.' }
return featureValue
}
}
|
const Packages = [
{
id: 'book',
title: 'The Book',
price: 1000,
desc: `
- The Book
- 14 chapters
- 100s of examples
- Access to GitHub Repo + Source
`
},
{
id: 'bookAndVideos',
title: 'The Book and Videos',
price: 1000,
desc: `
- The book
- Screencasts on
- Building this site
- Building a TODOMVC React app
- And more!
*Note*: May not be available until launch.
`
},
{
id: 'all',
title: 'All the things!',
price: 1000,
desc: `
- The Book + videos
- Bonus Chapters
- React Native Intro
- Building a Chat App
- Building a Static Blog Site
*Note*: May not be available until launch.
`
}
];
export default Packages;
|
var socket = io()
var app = angular.module('alcohol', ['ui.router', 'ui.router.grant', 'ngStorage'])
app.run(['grant', 'authService', function (grant, authService) {
grant.addTest('auth', function () {
console.log(authService.isLoggedIn())
return authService.isLoggedIn()
})
}])
app.config(['$stateProvider', '$urlRouterProvider', '$locationProvider', function ($stateProvider, $urlRouterProvider, $locationProvider) {
$stateProvider
.state('home', {
url: '/',
controller: 'homeController',
templateUrl: 'templates/home.html'
})
.state('about', {
url: '/about',
templateUrl: 'templates/about.html'
})
.state('profile', {
url: '/profile',
controller: 'profileController',
templateUrl: 'templates/profile.html',
resolve: {
auth: function(grant) {
return grant.only({test: 'auth', state: 'nope'});
}
}
})
.state('party', {
url: '/:id',
controller: 'partyController',
templateUrl: 'templates/party.html',
resolve: {
auth: function(grant) {
return grant.only({test: 'auth', state: 'nope'});
}
}
})
.state('nope', {
url: '/nope',
templateUrl: 'templates/nope.html'
})
.state('invalid', {
url: '/404',
templateUrl: 'templates/404.html'
})
$locationProvider.html5Mode(true)
$urlRouterProvider.otherwise('/404')
}])
app.factory('authService', ['$http', '$window', '$localStorage', function ($http, $window, $localStorage) {
var service = {},
user = {},
isLoggedIn = $localStorage.isLoggedIn || false
$http
.get('http://localhost:8080/api/profile')
.then(function (response) {
user.name = response.data.name
user.email = response.data.email
user.id = response.data.facebookId
})
return {
login: function () {
$localStorage.isLoggedIn = true
$window.location.href = 'http://localhost:8080/auth/facebook'
},
getUser: function () {
return user
},
getId: function () {
return user.id
},
isLoggedIn: function () {
return isLoggedIn
},
logout: function () {
$localStorage.isLoggedIn = false
$window.location.href = 'http://localhost:8080/logout'
}
}
}])
app.factory('streamService', ['$http', 'authService', function ($http, authService) {
var partyId
return {
start: function () {
return new Promise(function (resolve, reject) {
$http
.get('/api/start')
.then(function (response) {
partyId = response.data
resolve(response.data)
}, function () {
reject()
})
})
},
join: function (partyId) {
},
getPartyId: function () {
return partyId
}
}
}])
app.controller('homeController', ['$scope', 'authService', function ($scope, authService) {
$scope.pageName = 'Home'
$scope.login = authService.login
}])
app.controller('partyController', ['$scope', 'streamService', function ($scope, streamService) {
$scope.partyId = streamService.getPartyId()
}])
app.controller('profileController', ['$scope', '$state', 'authService', 'streamService', function($scope, $state, authService, streamService) {
$scope.user = authService.getUser()
$scope.logout = authService.logout
$scope.start = function () {
streamService
.start()
.then(function (partyId) {
$state.transitionTo('party', {
id: partyId
})
})
}
$scope.join = streamService.join
}])
|
version https://git-lfs.github.com/spec/v1
oid sha256:0f37b0ed995928892d2a7c5d05dbecd85b0d4d248931074f5f228f0c14bf5909
size 11378
|
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* @name: S15.10.2.15_A1_T23;
* @section: 15.10.2.15;
* @assertion: The internal helper function CharacterRange takes two CharSet parameters A and B and performs the
* following:
* If A does not contain exactly one character or B does not contain exactly one character then throw
* a SyntaxError exception;
* @description: Checking if execution of "/[b-G\d]/.exec("a")" leads to throwing the correct exception;
*/
//CHECK#1
try {
$ERROR('#1.1: /[b-G\\d]/.exec("a") throw SyntaxError. Actual: ' + (/[b-G\d]/.exec("a")));
} catch (e) {
if((e instanceof SyntaxError) !== true){
$ERROR('#1.2: /[b-G\\d]/.exec("a") throw SyntaxError. Actual: ' + (e));
}
}
|
/* jshint -W030 */
'use strict';
describe('Controller: MainMenuController', function () {
// load the controller's module
beforeEach(module('ftiApp.mainMenu'));
var controller;
var menuEntry = {name: 'test', state: 'test.main'};
var mainMenuMock = {
getMenu: function () {
return [menuEntry]
}
};
var $mdSidenavMock = function () {
return {
open: function () {},
close: function () {}
}
}
// Initialize the controller and a mock scope
beforeEach(inject(function ($controller, $rootScope) {
controller = $controller('MainMenuController', {
mainMenu: mainMenuMock,
$mdSidenav: $mdSidenavMock
});
}));
it('object should exist', function () {
Should.exist(controller);
controller.should.be.an.Object;
});
it('should have an items property', function () {
Should.exist(controller.items);
controller.items.should.be.an.Array;
controller.items.should.eql([menuEntry]);
});
});
|
'use strict';
/* lib/encode.js
* Encode WebSocket message frames.
* * */
|
// Avoid `console` errors in browsers that lack a console.
(function() {
var method;
var noop = function () {};
var methods = [
'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
'timeStamp', 'trace', 'warn'
];
var length = methods.length;
var console = (window.console = window.console || {});
while (length--) {
method = methods[length];
// Only stub undefined methods.
if (!console[method]) {
console[method] = noop;
}
}
}());
// Place any jQuery/helper plugins in here.
$(function(){
//Code for menu collapse button
$('#search_btn').click(function(event){
event.preventDefault();
$('#search_bar').submit();
});
//Code for menu collapse button
$('.collapse-button').click(function(event){
event.preventDefault();
$('.nav-bar').toggleClass('show');
});
//slider functions and operations
var slideCount = $('#slider ul li').length; //count the number of slides in the slider
var sliderVisorWidth = $('#slider').width();
var sliderUlWidth = slideCount * sliderVisorWidth; //total sliders list width.
$('#slider ul li').css({ width: sliderVisorWidth});
$('#slider ul').css({ width: sliderUlWidth, marginLeft: - sliderVisorWidth });
$('#slider ul li:last-child').prependTo('#slider ul');
function moveLeft() {
$('#slider ul').animate({
left: + sliderVisorWidth
}, 200, function () {
$('#slider ul li:last-child').prependTo('#slider ul');
$('#slider ul').css('left', '');
});
};
function moveRight() {
$('#slider ul').animate({
left: - sliderVisorWidth
}, 200, function () {
$('#slider ul li:first-child').appendTo('#slider ul');
$('#slider ul').css('left', '');
});
};
$('a.control_prev').click(function(event) {
event.preventDefault();
moveLeft();
});
$('a.control_next').click(function(event) {
event.preventDefault();
moveRight();
});
//click interactions for menu bar submenus
function hideMenus(){
$(".subMenu1").removeClass('show');
$(".subMenu2").removeClass('show');
$(".subMenu3").removeClass('show');
$(".subMenu4").removeClass('show');
$(".subMenu5").removeClass('show');
$(".subMenu6").removeClass('show');
$(".innerMenu1").removeClass('gray');
$(".innerMenu2").removeClass('gray');
$(".innerMenu3").removeClass('gray');
$(".innerMenu4").removeClass('gray');
$(".innerMenu5").removeClass('gray');
$(".innerMenu6").removeClass('gray');
}
//var menu;
//var sub_menu;
function show_menu(menu, sub_menu){
if ($(sub_menu).css('height') == "0px") {
hideMenus();
$(menu).addClass('gray');
$(sub_menu).addClass('show');
} else{
$(sub_menu).removeClass('show');
$(menu).removeClass('gray');
}
}
$('.innerMenu1').click(function(event){
event.preventDefault();
show_menu(".innerMenu1", ".subMenu1");
});
$('.innerMenu2').click(function(event){
event.preventDefault();
show_menu(".innerMenu2", ".subMenu2");
});
$('.innerMenu3').click(function(event){
event.preventDefault();
show_menu(".innerMenu3", ".subMenu3");
});
$('.innerMenu4').click(function(event){
event.preventDefault();
show_menu(".innerMenu4", ".subMenu4");
});
$('.innerMenu5').click(function(event){
event.preventDefault();
show_menu(".innerMenu5", ".subMenu5");
});
$('.innerMenu6').click(function(event){
event.preventDefault();
show_menu(".innerMenu6", ".subMenu6");
});
//slider autoscrolling
$(document).ready(function() {
setInterval(function() {
moveRight()
}, 5000);
$( window ).resize(function() {
sliderVisorWidth = $('#slider').width();
$('#slider ul li').css({ width: sliderVisorWidth});
sliderUlWidth = slideCount * sliderVisorWidth;
$('#slider ul').css({ width: sliderUlWidth, marginLeft: - sliderVisorWidth });
});
});
}); |
var twilio = require('twilio'),
Player = require('../models/Player'),
Question = require('../models/Question');
// Handle inbound SMS and process commands
module.exports = function(request, response) {
var twiml = new twilio.TwimlResponse();
var body = request.param('Body').trim(),
playerPhone = request.param('From'),
player = null,
question = null;
// Emit a response with the given message
function respond(str) {
twiml.message(str);
response.send(twiml);
}
// Process the "nick" command
function nick(input) {
if (was('help', input)) {
respond('Set your nickname, as you want it to appear on the leaderboard. Example: "nick Mrs. Awesomepants"');
} else {
if (input === '') {
respond('A nickname is required. Text "nick help" for command help.');
} else {
player.nick = input;
player.save(function(err) {
if (err) {
respond('There was a problem updating your nickname, or that nickname is already in use. Please try another nickname.');
} else {
respond('Your nickname has been changed!');
}
});
}
}
}
// Process the "stop" command
function stop(input) {
if (was('help', input)) {
respond('Unsubscribe from all messages. Example: "stop"');
} else {
player.remove(function(err, model) {
if (err) {
respond('There was a problem unsubscribing. Please try again later.');
} else {
respond('You have been unsubscribed.');
}
});
}
}
// Process the "question" command
function questionCommand(input) {
if (was('help', input)) {
respond('Print out the current question. Example: "question"');
} else {
Question.findOne({}, function(err, q) {
question = err ? {question:'Error, no question found.'} : q;
respond('Current question: '+question.question);
});
}
}
// Once the current question is found, determine if we have an eligible
// answer
function processAnswer(input) {
if (!question.answered) {
question.answered = [];
}
if (question.answered.indexOf(player.phone) > -1) {
respond('You have already answered this question!');
} else {
var answerLower = question.answer.toLowerCase(),
inputLower = input.toLowerCase().trim();
if (inputLower !== '' && answerLower.indexOf(inputLower) > -1) {
var points = 5 - question.answered.length;
if (points < 1) {
points = 1;
}
// DOUBLE POINTS
// points = points*2;
// Update the question, then the player score
question.answered.push(player.phone);
question.save(function(err) {
player.points = player.points+points;
player.save(function(err2) {
respond('Woop woop! You got it! Your score is now: '+player.points);
});
});
} else {
respond('Sorry! That answer was incorrect. Guess again...');
}
}
}
// Process the "answer" command
function answer(input) {
if (was('help', input)) {
respond('Answer the current question - spelling is important, capitalization is not. If you don\'t know the current question, text "question". Example: "answer frodo baggins"');
} else {
Question.findOne({}, function(err, q) {
question = err ? {question:'Error, no question found.'} : q;
processAnswer(input);
});
}
}
// Process the "score" command
function score(input) {
if (was('help', input)) {
respond('Print out your current score. Example: "score"');
} else {
respond('Your current score is: '+player.points);
}
}
// Helper to see if the command was a given string
function was(command, input) {
var lowered = input.toLowerCase();
return lowered ? lowered.indexOf(command) === 0 : false;
}
// Helper to chop off the command string for further processing
function chop(input) {
var idx = input.indexOf(' ');
return idx > 0 ? input.substring(idx).trim() : '';
}
// Parse their input command
function processInput() {
var input = body||'help';
var chopped = chop(input);
if (was('nick', input)) {
nick(chopped);
} else if (was('stop', input)) {
stop(chopped);
} else if (was('answer', input)) {
answer(chopped);
} else if (was('question', input)) {
questionCommand(chopped);
} else if (was('score', input)) {
score(chopped);
} else {
respond('Welcome to Twilio Trivia '+player.nick+'! Commands are "answer", "question", "nick", "score", help", and "stop". Text "<command name> help" for usage. View the current leaderboard and question at http://build-trivia.azurewebsites.net/');
}
}
// Create a new player
function createPlayer() {
Player.create({
phone:playerPhone,
nick:'Mysterious Stranger '+playerPhone.substring(7),
points:0
}, function(err, model) {
if (err) {
respond('There was an error signing you up, try again later.');
} else {
player = model;
respond('Welcome to Twilio Trivia! You are now signed up. Text "help" for instructions.');
}
});
}
// Deal with the found player, if it exists
function playerFound(err, model) {
if (err) {
respond('There was an error recording your answer.');
} else {
if (model) {
player = model;
processInput();
} else {
createPlayer();
}
}
}
// Kick off the db access by finding the player for this phone number
Player.findOne({
phone:playerPhone
}, playerFound);
}; |
(function () {
'use strict';
angular.module('openSnap')
.constant('CONFIG', {
menuItems: [{
state: 'home',
icon: 'home'
},
{
state: 'codes',
icon: 'code'
},
{
state: 'create',
icon: 'create'
},
{
state: 'info',
icon: 'info'
}
],
backendUrl: ''
})
})();
|
define(function (require) {
'use strict';
/**
* Module dependencies
*/
var defineComponent = require('flight/lib/component');
/**
* Module exports
*/
return defineComponent(switcher);
/**
* Module function
*/
function switcher() {
this.defaultAttrs({
onClass: 'btn-primary'
});
this.turnOn = function() {
// 1) add class `this.attr.onClass`
// 2) trigger 'buttonOn' event
};
this.turnOff = function() {
// 3) remove class `this.attr.onClass`
// 4) trigger 'buttonOff' event
};
this.toggle = function() {
// 5) if `this.attr.onClass` is present call `turnOff` otherwise call `turnOn`
}
this.after('initialize', function () {
// 6) listen for 'click' event and call `this.toggle`
});
}
});
|
const other = {
something: 'here'
};
const other$1 = {
somethingElse: 'here'
};
|
var mongoose = require('mongoose');
var u = require('../utils');
var autorizadaSchema = new mongoose.Schema({
nome: String,
cpf: { type: String, unique: true },
celular: String,
dtInicial: Date,
dtFinal: Date,
autorizador: String,
apto: Number,
bloco: String,
contato: String
});
var A = mongoose.model('Autorizada', autorizadaSchema);
[{
nome: 'Mickey',
cpf: '99933366600',
celular: '11 9 9633-3366',
dtInicial: new Date(2013, 11, 1),
dtFinal: new Date(2015, 0, 1),
autorizador: 'Pateta',
apto: 432,
bloco: 'D',
contato: '11 9 9833-3388'
}].forEach(function(f) {
var model = new A();
u.objetoExtends(model, f);
model.save();
});
module.exports = A;
|
'use strict';
// MODULES //
var ctor = require( './ctor.js' );
// VARIABLES //
var CACHE = require( './cache.js' ).CTORS;
// GET CTOR //
/**
* FUNCTION: getCtor( dtype, ndims )
* Returns an ndarray constructor.
*
* @param {String} dtype - underlying ndarray data type
* @param {Number} ndims - view dimensions
* @returns {ndarray} ndarray constructor
*/
function getCtor( dtype, ndims ) {
var ctors,
len,
i;
ctors = CACHE[ dtype ];
len = ctors.length;
// If the constructor has not already been created, use the opportunity to create it, as well as any lower dimensional constructors of the same data type....
for ( i = len+1; i <= ndims; i++ ) {
ctors.push( ctor( dtype, i ) );
}
return ctors[ ndims-1 ];
} // end FUNCTION getCtor()
// EXPORTS //
module.exports = getCtor;
|
var elt;
var canvas;
var gl;
var program;
var NumVertices = 36;
var pointsArray = [];
var normalsArray = [];
var colorsArray = [];
var framebuffer;
var flag = true;
var color = new Uint8Array(4);
var vertices = [
vec4( -0.5, -0.5, 0.5, 1.0 ),
vec4( -0.5, 0.5, 0.5, 1.0 ),
vec4( 0.5, 0.5, 0.5, 1.0 ),
vec4( 0.5, -0.5, 0.5, 1.0 ),
vec4( -0.5, -0.5, -0.5, 1.0 ),
vec4( -0.5, 0.5, -0.5, 1.0 ),
vec4( 0.5, 0.5, -0.5, 1.0 ),
vec4( 0.5, -0.5, -0.5, 1.0 ),
];
var vertexColors = [
vec4( 0.0, 0.0, 0.0, 1.0 ), // black
vec4( 1.0, 0.0, 0.0, 1.0 ), // red
vec4( 1.0, 1.0, 0.0, 1.0 ), // yellow
vec4( 0.0, 1.0, 0.0, 1.0 ), // green
vec4( 0.0, 0.0, 1.0, 1.0 ), // blue
vec4( 1.0, 0.0, 1.0, 1.0 ), // magenta
vec4( 0.0, 1.0, 1.0, 1.0 ), // cyan
vec4( 1.0, 1.0, 1.0, 1.0 ), // white
];
var lightPosition = vec4(1.0, 1.0, 1.0, 0.0 );
var lightAmbient = vec4(0.2, 0.2, 0.2, 1.0 );
var lightDiffuse = vec4( 1.0, 1.0, 1.0, 1.0 );
var lightSpecular = vec4( 1.0, 1.0, 1.0, 1.0 );
//var materialAmbient = vec4( 1.0, 0.0, 1.0, 1.0 );
var materialAmbient = vec4( 1.0, 1.0, 1.0, 1.0 );
//var materialDiffuse = vec4( 1.0, 0.8, 0.0, 1.0);
var materialDiffuse = vec4( 0.5, 0.5, 0.5, 1.0);
var materialSpecular = vec4( 1.0, 0.8, 0.0, 1.0 );
var materialShininess = 10.0;
var ctm;
var ambientColor, diffuseColor, specularColor;
var modelView, projection;
var viewerPos;
var program;
var xAxis = 0;
var yAxis = 1;
var zAxis = 2;
var axis = xAxis;
var theta = [45.0, 45.0, 45.0];
var thetaLoc;
var Index = 0;
function quad(a, b, c, d) {
var t1 = subtract(vertices[b], vertices[a]);
var t2 = subtract(vertices[c], vertices[b]);
var normal = cross(t1, t2);
var normal = vec3(normal);
normal = normalize(normal);
pointsArray.push(vertices[a]);
normalsArray.push(normal);
colorsArray.push(vertexColors[a]);
pointsArray.push(vertices[b]);
normalsArray.push(normal);
colorsArray.push(vertexColors[a]);
pointsArray.push(vertices[c]);
normalsArray.push(normal);
colorsArray.push(vertexColors[a]);
pointsArray.push(vertices[a]);
normalsArray.push(normal);
colorsArray.push(vertexColors[a]);
pointsArray.push(vertices[c]);
normalsArray.push(normal);
colorsArray.push(vertexColors[a]);
pointsArray.push(vertices[d]);
normalsArray.push(normal);
colorsArray.push(vertexColors[a]);
}
function colorCube()
{
quad( 1, 0, 3, 2 );
quad( 2, 3, 7, 6 );
quad( 3, 0, 4, 7 );
quad( 6, 5, 1, 2 );
quad( 4, 5, 6, 7 );
quad( 5, 4, 0, 1 );
}
window.onload = function init() {
canvas = document.getElementById( "gl-canvas" );
var ctx = canvas.getContext("experimental-webgl", {preserveDrawingBuffer: true});
gl = WebGLUtils.setupWebGL( canvas );
if ( !gl ) { alert( "WebGL isn't available" ); }
elt = document.getElementById("test");
gl.viewport( 0, 0, canvas.width, canvas.height );
gl.clearColor( 0.5, 0.5, 0.5, 1.0 );
gl.enable(gl.CULL_FACE);
var texture = gl.createTexture();
gl.bindTexture( gl.TEXTURE_2D, texture );
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 512, 512, 0,
gl.RGBA, gl.UNSIGNED_BYTE, null);
gl.generateMipmap(gl.TEXTURE_2D);
// Allocate a frame buffer object
framebuffer = gl.createFramebuffer();
gl.bindFramebuffer( gl.FRAMEBUFFER, framebuffer);
// Attach color buffer
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
// check for completeness
//var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
//if(status != gl.FRAMEBUFFER_COMPLETE) alert('Frame Buffer Not Complete');
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
//
// Load shaders and initialize attribute buffers
//
program = initShaders( gl, "vertex-shader", "fragment-shader" );
gl.useProgram( program );
colorCube();
var cBuffer = gl.createBuffer();
gl.bindBuffer( gl.ARRAY_BUFFER, cBuffer );
gl.bufferData( gl.ARRAY_BUFFER, flatten(colorsArray), gl.STATIC_DRAW );
var vColor = gl.getAttribLocation( program, "vColor" );
gl.vertexAttribPointer( vColor, 4, gl.FLOAT, false, 0, 0 );
gl.enableVertexAttribArray( vColor );
var nBuffer = gl.createBuffer();
gl.bindBuffer( gl.ARRAY_BUFFER, nBuffer );
gl.bufferData( gl.ARRAY_BUFFER, flatten(normalsArray), gl.STATIC_DRAW );
var vNormal = gl.getAttribLocation( program, "vNormal" );
gl.vertexAttribPointer( vNormal, 3, gl.FLOAT, false, 0, 0 );
gl.enableVertexAttribArray( vNormal );
var vBuffer = gl.createBuffer();
gl.bindBuffer( gl.ARRAY_BUFFER, vBuffer );
gl.bufferData( gl.ARRAY_BUFFER, flatten(pointsArray), gl.STATIC_DRAW );
var vPosition = gl.getAttribLocation(program, "vPosition");
gl.vertexAttribPointer(vPosition, 4, gl.FLOAT, false, 0, 0);
gl.enableVertexAttribArray(vPosition);
thetaLoc = gl.getUniformLocation(program, "theta");
viewerPos = vec3(0.0, 0.0, -20.0 );
projection = ortho(-1, 1, -1, 1, -100, 100);
ambientProduct = mult(lightAmbient, materialAmbient);
diffuseProduct = mult(lightDiffuse, materialDiffuse);
specularProduct = mult(lightSpecular, materialSpecular);
document.getElementById("ButtonX").onclick = function(){axis = xAxis;};
document.getElementById("ButtonY").onclick = function(){axis = yAxis;};
document.getElementById("ButtonZ").onclick = function(){axis = zAxis;};
document.getElementById("ButtonT").onclick = function(){flag = !flag};
gl.uniform4fv(gl.getUniformLocation(program, "ambientProduct"),
flatten(ambientProduct));
gl.uniform4fv(gl.getUniformLocation(program, "diffuseProduct"),
flatten(diffuseProduct) );
gl.uniform4fv(gl.getUniformLocation(program, "specularProduct"),
flatten(specularProduct) );
gl.uniform4fv(gl.getUniformLocation(program, "lightPosition"),
flatten(lightPosition) );
gl.uniform1f(gl.getUniformLocation(program,
"shininess"),materialShininess);
gl.uniformMatrix4fv( gl.getUniformLocation(program, "projectionMatrix"),
false, flatten(projection));
canvas.addEventListener("mousedown", function(event){
gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
gl.clear( gl.COLOR_BUFFER_BIT);
gl.uniform3fv(thetaLoc, theta);
for(var i=0; i<6; i++) {
gl.uniform1i(gl.getUniformLocation(program, "i"), i+1);
gl.drawArrays( gl.TRIANGLES, 6*i, 6 );
}
var x = event.clientX;
var y = canvas.height -event.clientY;
gl.readPixels(x, y, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, color);
if(color[0]==255)
if(color[1]==255) elt.innerHTML = "<div> cyan </div>";
else if(color[2]==255) elt.innerHTML = "<div> magenta </div>";
else elt.innerHTML = "<div> red </div>";
else if(color[1]==255)
if(color[2]==255) elt.innerHTML = "<div> blue </div>";
else elt.innerHTML = "<div> yellow </div>";
else if(color[2]==255) elt.innerHTML = "<div> green </div>";
else elt.innerHTML = "<div> background </div>";
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
gl.uniform1i(gl.getUniformLocation(program, "i"), 0);
gl.clear( gl.COLOR_BUFFER_BIT );
gl.uniform3fv(thetaLoc, theta);
gl.drawArrays(gl.TRIANGLES, 0, 36);
});
render();
}
var render = function(){
gl.clear( gl.COLOR_BUFFER_BIT );
if(flag) theta[axis] += 2.0;
modelView = mat4();
modelView = mult(modelView, rotate(theta[xAxis], [1, 0, 0] ));
modelView = mult(modelView, rotate(theta[yAxis], [0, 1, 0] ));
modelView = mult(modelView, rotate(theta[zAxis], [0, 0, 1] ));
gl.uniformMatrix4fv( gl.getUniformLocation(program,
"modelViewMatrix"), false, flatten(modelView) );
gl.uniform1i(gl.getUniformLocation(program, "i"),0);
gl.drawArrays( gl.TRIANGLES, 0, 36 );
requestAnimFrame(render);
}
|
import classnames from 'classnames';
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import telephonyStatuses from 'ringcentral-integration/enums/telephonyStatus';
import callDirections from 'ringcentral-integration/enums/callDirections';
import CloseIcon from '../../assets/images/CloseIcon.svg';
import { Button } from '../Button';
import LogNotification from '../LogNotificationV2';
import styles from './styles.scss';
import i18n from './i18n';
export default class NotificationSection extends Component {
componentWillUpdate(nextProps) {
const {
logNotification,
onCloseNotification,
currentNotificationIdentify,
} = nextProps;
if (currentNotificationIdentify) {
const { call = {} } = logNotification;
const { result } = call;
if (result) {
onCloseNotification();
}
}
}
renderLogSection() {
const {
formatPhone,
currentLocale,
logNotification,
showNotiLogButton,
onCloseNotification,
onSaveNotification,
onExpandNotification,
onDiscardNotification,
currentNotificationIdentify,
currentSession,
onReject,
onHangup,
shrinkNotification,
} = this.props;
const { call } = logNotification;
const { result, telephonyStatus } = call;
const status = result || telephonyStatus;
let statusI18n = null;
const isIncomingCall =
status === telephonyStatuses.ringing &&
call.direction === callDirections.inbound;
if (isIncomingCall) {
statusI18n = i18n.getString('ringing', currentLocale);
} else {
statusI18n = i18n.getString('callConnected', currentLocale);
}
return (
<div className={classnames(styles.root)}>
<div className={styles.notificationModal}>
<div className={styles.modalHeader}>
<div className={styles.modalTitle}>{statusI18n}</div>
<div className={styles.modalCloseBtn}>
<Button dataSign="closeButton" onClick={onCloseNotification}>
<CloseIcon />
</Button>
</div>
</div>
<LogNotification
showEndButton
showLogButton={showNotiLogButton}
currentLocale={currentLocale}
formatPhone={formatPhone}
currentLog={logNotification}
isExpand={logNotification.notificationIsExpand}
onSave={onSaveNotification}
onExpand={onExpandNotification}
onDiscard={onDiscardNotification}
onReject={() => onReject(currentNotificationIdentify)}
onHangup={() => onHangup(currentNotificationIdentify)}
currentSession={currentSession}
shrinkNotification={shrinkNotification}
/>
</div>
</div>
);
}
render() {
return this.renderLogSection();
}
}
NotificationSection.propTypes = {
currentLocale: PropTypes.string.isRequired,
formatPhone: PropTypes.func.isRequired,
// - Notification
logNotification: PropTypes.object,
onCloseNotification: PropTypes.func,
onDiscardNotification: PropTypes.func,
onSaveNotification: PropTypes.func,
onExpandNotification: PropTypes.func,
showNotiLogButton: PropTypes.bool,
currentNotificationIdentify: PropTypes.string,
currentSession: PropTypes.object,
onReject: PropTypes.func.isRequired,
onHangup: PropTypes.func.isRequired,
shrinkNotification: PropTypes.func,
};
NotificationSection.defaultProps = {
// Notification
logNotification: undefined,
onCloseNotification: undefined,
onDiscardNotification: undefined,
onSaveNotification: undefined,
onExpandNotification: undefined,
showNotiLogButton: true,
currentNotificationIdentify: '',
currentSession: undefined,
shrinkNotification: undefined,
};
|
/************************************************************************************************************
JS Calendar
Copyright (C) September 2006 DTHMLGoodies.com, Alf Magne Kalleland
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Dhtmlgoodies.com., hereby disclaims all copyright interest in this script
written by Alf Magne Kalleland.
Alf Magne Kalleland, 2006
Owner of DHTMLgoodies.com
************************************************************************************************************/
/* Update log:
(C) www.dhtmlgoodies.com, September 2005
Version 1.2, November 8th - 2005 - Added <iframe> background in IE
Version 1.3, November 12th - 2005 - Fixed top bar position in Opera 7
Version 1.4, December 28th - 2005 - Support for Spanish and Portuguese
Version 1.5, January 18th - 2006 - Fixed problem with next-previous buttons after a month has been selected from dropdown
Version 1.6, February 22nd - 2006 - Added variable which holds the path to images.
Format todays date at the bottom by use of the todayStringFormat variable
Pick todays date by clicking on todays date at the bottom of the calendar
Version 2.0 May, 25th - 2006 - Added support for time(hour and minutes) and changing year and hour when holding mouse over + and - options. (i.e. instead of click)
Version 2.1 July, 2nd - 2006 - Added support for more date formats(example: d.m.yyyy, i.e. one letter day and month).
*/
var languageCode = 'en'; // Possible values: en,ge,no,nl,es,pt-br,fr
// en = english, ge = german, no = norwegian,nl = dutch, es = spanish, pt-br = portuguese, fr = french, da = danish, hu = hungarian(Use UTF-8 doctype for hungarian)
var calendar_display_time = true;
// Format of current day at the bottom of the calendar
// [todayString] = the value of todayString
// [dayString] = day of week (examle: mon, tue, wed...)
// [UCFdayString] = day of week (examle: Mon, Tue, Wed...) ( First letter in uppercase)
// [day] = Day of month, 1..31
// [monthString] = Name of current month
// [year] = Current year
var todayStringFormat = '[todayString] [UCFdayString]. [day]. [monthString] [year]';
//var pathToCalImages = '../images/calendar/'; // Relative to your HTML file
var speedOfSelectBoxSliding = 200; // Milliseconds between changing year and hour when holding mouse over "-" and "+" - lower value = faster
var intervalSelectBox_minutes = 5; // Minute select box - interval between each option (5 = default)
var calendar_offsetTop = 0; // Offset - calendar placement - You probably have to modify this value if you're not using a strict doctype
var calendar_offsetLeft = 0; // Offset - calendar placement - You probably have to modify this value if you're not using a strict doctype
var calendarDiv = false;
var MSIE = false;
var Opera = false;
if(navigator.userAgent.indexOf('MSIE')>=0 && navigator.userAgent.indexOf('Opera')<0)MSIE=true;
if(navigator.userAgent.indexOf('Opera')>=0)Opera=true;
switch(languageCode){
case "en": /* English */
var monthArray = ['January','February','March','April','May','June','July','August','September','October','November','December'];
var monthArrayShort = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
var dayArray = ['Mon','Tue','Wed','Thu','Fri','Sat','Sun'];
var weekString = 'Week';
var todayString = '';
break;
case "ge": /* German */
var monthArray = ['Januar','Februar','März','April','Mai','Juni','Juli','August','September','Oktober','November','Dezember'];
var monthArrayShort = ['Jan','Feb','Mar','Apr','Mai','Jun','Jul','Aug','Sep','Okt','Nov','Dez'];
var dayArray = ['Mon','Die','Mit','Don','Fre','Sam','Son'];
var weekString = 'Woche';
var todayString = 'Heute';
break;
case "no": /* Norwegian */
var monthArray = ['Januar','Februar','Mars','April','Mai','Juni','Juli','August','September','Oktober','November','Desember'];
var monthArrayShort = ['Jan','Feb','Mar','Apr','Mai','Jun','Jul','Aug','Sep','Okt','Nov','Des'];
var dayArray = ['Man','Tir','Ons','Tor','Fre','Lør','Søn'];
var weekString = 'Uke';
var todayString = 'Dagen i dag er';
break;
case "nl": /* Dutch */
var monthArray = ['Januari','Februari','Maart','April','Mei','Juni','Juli','Augustus','September','Oktober','November','December'];
var monthArrayShort = ['Jan','Feb','Mar','Apr','Mei','Jun','Jul','Aug','Sep','Okt','Nov','Dec'];
var dayArray = ['Ma','Di','Wo','Do','Vr','Za','Zo'];
var weekString = 'Week';
var todayString = 'Vandaag';
break;
case "es": /* Spanish */
var monthArray = ['Enero','Febrero','Marzo','April','Mayo','Junio','Julio','Agosto','Septiembre','Octubre','Noviembre','Diciembre'];
var monthArrayShort =['Ene','Feb','Mar','Abr','May','Jun','Jul','Ago','Sep','Oct','Nov','Dic'];
var dayArray = ['Lun','Mar','Mie','Jue','Vie','Sab','Dom'];
var weekString = 'Semana';
var todayString = 'Hoy es';
break;
case "pt-br": /* Brazilian portuguese (pt-br) */
var monthArray = ['Janeiro','Fevereiro','Março','Abril','Maio','Junho','Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'];
var monthArrayShort = ['Jan','Fev','Mar','Abr','Mai','Jun','Jul','Ago','Set','Out','Nov','Dez'];
var dayArray = ['Seg','Ter','Qua','Qui','Sex','Sáb','Dom'];
var weekString = 'Sem.';
var todayString = 'Hoje é';
break;
case "fr": /* French */
var monthArray = ['Janvier','Février','Mars','Avril','Mai','Juin','Juillet','Août','Septembre','Octobre','Novembre','Décembre'];
var monthArrayShort = ['Jan','Fev','Mar','Avr','Mai','Jun','Jul','Aou','Sep','Oct','Nov','Dec'];
var dayArray = ['Lun','Mar','Mer','Jeu','Ven','Sam','Dim'];
var weekString = 'Sem';
var todayString = "Aujourd'hui";
break;
case "da": /*Danish*/
var monthArray = ['januar','februar','marts','april','maj','juni','juli','august','september','oktober','november','december'];
var monthArrayShort = ['jan','feb','mar','apr','maj','jun','jul','aug','sep','okt','nov','dec'];
var dayArray = ['man','tirs','ons','tors','fre','lør','søn'];
var weekString = 'Uge';
var todayString = 'I dag er den';
break;
case "hu": /* Hungarian - Remember to use UTF-8 encoding, i.e. the <meta> tag */
var monthArray = ['Január','Február','Március','�prilis','Május','Június','Július','Augusztus','Szeptember','Október','November','December'];
var monthArrayShort = ['Jan','Feb','Márc','�pr','Máj','Jún','Júl','Aug','Szep','Okt','Nov','Dec'];
var dayArray = ['Hé','Ke','Sze','Cs','Pé','Szo','Vas'];
var weekString = 'Hét';
var todayString = 'Mai nap';
break;
case "it": /* Italian*/
var monthArray = ['Gennaio','Febbraio','Marzo','Aprile','Maggio','Giugno','Luglio','Agosto','Settembre','Ottobre','Novembre','Dicembre'];
var monthArrayShort = ['Gen','Feb','Mar','Apr','Mag','Giu','Lugl','Ago','Set','Ott','Nov','Dic'];
var dayArray = ['Lun',';Mar','Mer','Gio','Ven','Sab','Dom'];
var weekString = 'Settimana';
var todayString = 'Oggi è il';
break;
case "sv": /* Swedish */
var monthArray = ['Januari','Februari','Mars','April','Maj','Juni','Juli','Augusti','September','Oktober','November','December'];
var monthArrayShort = ['Jan','Feb','Mar','Apr','Maj','Jun','Jul','Aug','Sep','Okt','Nov','Dec'];
var dayArray = ['Mån','Tis','Ons','Tor','Fre','Lör','Sön'];
var weekString = 'Vecka';
var todayString = 'Idag är det den';
break;
}
var daysInMonthArray = [31,28,31,30,31,30,31,31,30,31,30,31];
var currentMonth;
var currentYear;
var currentHour;
var currentMinute;
var calendarContentDiv;
var returnDateTo;
var returnFormat;
var activeSelectBoxMonth;
var activeSelectBoxYear;
var activeSelectBoxHour;
var activeSelectBoxMinute;
var iframeObj = false;
//// fix for EI frame problem on time dropdowns 09/30/2006
var iframeObj2 =false;
function EIS_FIX_EI1(where2fixit)
{
if(!iframeObj2)return;
iframeObj2.style.display = 'block';
iframeObj2.style.height =document.getElementById(where2fixit).offsetHeight+1;
iframeObj2.style.width=document.getElementById(where2fixit).offsetWidth;
iframeObj2.style.left=getleftPos(document.getElementById(where2fixit))+1-calendar_offsetLeft;
iframeObj2.style.top=getTopPos(document.getElementById(where2fixit))-document.getElementById(where2fixit).offsetHeight-calendar_offsetTop;
}
function EIS_Hide_Frame()
{ if(iframeObj2)iframeObj2.style.display = 'none';}
//// fix for EI frame problem on time dropdowns 09/30/2006
var returnDateToYear;
var returnDateToMonth;
var returnDateToDay;
var returnDateToHour;
var returnDateToMinute;
var inputYear;
var inputMonth;
var inputDay;
var inputHour;
var inputMinute;
var calendarDisplayTime = false;
var selectBoxHighlightColor = '#D60808'; // Highlight color of select boxes
var selectBoxRolloverBgColor = '#E2EBED'; // Background color on drop down lists(rollover)
var selectBoxMovementInProgress = false;
var activeSelectBox = false;
function cancelCalendarEvent()
{
return false;
}
function isLeapYear(inputYear)
{
if(inputYear%400==0||(inputYear%4==0&&inputYear%100!=0)) return true;
return false;
}
var activeSelectBoxMonth = false;
var activeSelectBoxDirection = false;
function highlightMonthYear()
{
if(activeSelectBoxMonth)activeSelectBoxMonth.className='';
activeSelectBox = this;
if(this.className=='monthYearActive'){
this.className='';
}else{
this.className = 'monthYearActive';
activeSelectBoxMonth = this;
}
if(this.innerHTML.indexOf('-')>=0 || this.innerHTML.indexOf('+')>=0){
if(this.className=='monthYearActive')
selectBoxMovementInProgress = true;
else
selectBoxMovementInProgress = false;
if(this.innerHTML.indexOf('-')>=0)activeSelectBoxDirection = -1; else activeSelectBoxDirection = 1;
}else selectBoxMovementInProgress = false;
}
function showMonthDropDown()
{
if(document.getElementById('monthDropDown').style.display=='block'){
document.getElementById('monthDropDown').style.display='none';
//// fix for EI frame problem on time dropdowns 09/30/2006
EIS_Hide_Frame();
}else{
document.getElementById('monthDropDown').style.display='block';
document.getElementById('yearDropDown').style.display='none';
document.getElementById('hourDropDown').style.display='none';
document.getElementById('minuteDropDown').style.display='none';
if (MSIE)
{ EIS_FIX_EI1('monthDropDown')}
//// fix for EI frame problem on time dropdowns 09/30/2006
}
}
function showYearDropDown()
{
if(document.getElementById('yearDropDown').style.display=='block'){
document.getElementById('yearDropDown').style.display='none';
//// fix for EI frame problem on time dropdowns 09/30/2006
EIS_Hide_Frame();
}else{
document.getElementById('yearDropDown').style.display='block';
document.getElementById('monthDropDown').style.display='none';
document.getElementById('hourDropDown').style.display='none';
document.getElementById('minuteDropDown').style.display='none';
if (MSIE)
{ EIS_FIX_EI1('yearDropDown')}
//// fix for EI frame problem on time dropdowns 09/30/2006
}
}
function showHourDropDown()
{
if(document.getElementById('hourDropDown').style.display=='block'){
document.getElementById('hourDropDown').style.display='none';
//// fix for EI frame problem on time dropdowns 09/30/2006
EIS_Hide_Frame();
}else{
document.getElementById('hourDropDown').style.display='block';
document.getElementById('monthDropDown').style.display='none';
document.getElementById('yearDropDown').style.display='none';
document.getElementById('minuteDropDown').style.display='none';
if (MSIE)
{ EIS_FIX_EI1('hourDropDown')}
//// fix for EI frame problem on time dropdowns 09/30/2006
}
}
function showMinuteDropDown()
{
if(document.getElementById('minuteDropDown').style.display=='block'){
document.getElementById('minuteDropDown').style.display='none';
//// fix for EI frame problem on time dropdowns 09/30/2006
EIS_Hide_Frame();
}else{
document.getElementById('minuteDropDown').style.display='block';
document.getElementById('monthDropDown').style.display='none';
document.getElementById('yearDropDown').style.display='none';
document.getElementById('hourDropDown').style.display='none';
if (MSIE)
{ EIS_FIX_EI1('minuteDropDown')}
//// fix for EI frame problem on time dropdowns 09/30/2006
}
}
function selectMonth()
{
document.getElementById('calendar_month_txt').innerHTML = this.innerHTML
currentMonth = this.id.replace(/[^\d]/g,'');
document.getElementById('monthDropDown').style.display='none';
//// fix for EI frame problem on time dropdowns 09/30/2006
EIS_Hide_Frame();
for(var no=0;no<monthArray.length;no++){
document.getElementById('monthDiv_'+no).style.color='';
}
this.style.color = selectBoxHighlightColor;
activeSelectBoxMonth = this;
writeCalendarContent();
}
function selectHour()
{
document.getElementById('calendar_hour_txt').innerHTML = this.innerHTML
currentHour = this.innerHTML.replace(/[^\d]/g,'');
document.getElementById('hourDropDown').style.display='none';
//// fix for EI frame problem on time dropdowns 09/30/2006
EIS_Hide_Frame();
if(activeSelectBoxHour){
activeSelectBoxHour.style.color='';
}
activeSelectBoxHour=this;
this.style.color = selectBoxHighlightColor;
}
function selectMinute()
{
document.getElementById('calendar_minute_txt').innerHTML = this.innerHTML
currentMinute = this.innerHTML.replace(/[^\d]/g,'');
document.getElementById('minuteDropDown').style.display='none';
//// fix for EI frame problem on time dropdowns 09/30/2006
EIS_Hide_Frame();
if(activeSelectBoxMinute){
activeSelectBoxMinute.style.color='';
}
activeSelectBoxMinute=this;
this.style.color = selectBoxHighlightColor;
}
function selectYear()
{
document.getElementById('calendar_year_txt').innerHTML = this.innerHTML
currentYear = this.innerHTML.replace(/[^\d]/g,'');
document.getElementById('yearDropDown').style.display='none';
//// fix for EI frame problem on time dropdowns 09/30/2006
EIS_Hide_Frame();
if(activeSelectBoxYear){
activeSelectBoxYear.style.color='';
}
activeSelectBoxYear=this;
this.style.color = selectBoxHighlightColor;
writeCalendarContent();
}
function switchMonth()
{
if(this.src.indexOf('left')>=0){
currentMonth=currentMonth-1;;
if(currentMonth<0){
currentMonth=11;
currentYear=currentYear-1;
}
}else{
currentMonth=currentMonth+1;;
if(currentMonth>11){
currentMonth=0;
currentYear=currentYear/1+1;
}
}
writeCalendarContent();
}
function createMonthDiv(){
var div = document.createElement('DIV');
div.className='monthYearPicker';
div.id = 'monthPicker';
for(var no=0;no<monthArray.length;no++){
var subDiv = document.createElement('DIV');
subDiv.innerHTML = monthArray[no];
subDiv.onmouseover = highlightMonthYear;
subDiv.onmouseout = highlightMonthYear;
subDiv.onclick = selectMonth;
subDiv.id = 'monthDiv_' + no;
subDiv.style.width = '56px';
subDiv.onselectstart = cancelCalendarEvent;
div.appendChild(subDiv);
if(currentMonth && currentMonth==no){
subDiv.style.color = selectBoxHighlightColor;
activeSelectBoxMonth = subDiv;
}
}
return div;
}
function changeSelectBoxYear(e,inputObj)
{
if(!inputObj)inputObj =this;
var yearItems = inputObj.parentNode.getElementsByTagName('DIV');
if(inputObj.innerHTML.indexOf('-')>=0){
var startYear = yearItems[1].innerHTML/1 -1;
if(activeSelectBoxYear){
activeSelectBoxYear.style.color='';
}
}else{
var startYear = yearItems[1].innerHTML/1 +1;
if(activeSelectBoxYear){
activeSelectBoxYear.style.color='';
}
}
for(var no=1;no<yearItems.length-1;no++){
yearItems[no].innerHTML = startYear+no-1;
yearItems[no].id = 'yearDiv' + (startYear/1+no/1-1);
}
if(activeSelectBoxYear){
activeSelectBoxYear.style.color='';
if(document.getElementById('yearDiv'+currentYear)){
activeSelectBoxYear = document.getElementById('yearDiv'+currentYear);
activeSelectBoxYear.style.color=selectBoxHighlightColor;;
}
}
}
function changeSelectBoxHour(e,inputObj)
{
if(!inputObj)inputObj = this;
var hourItems = inputObj.parentNode.getElementsByTagName('DIV');
if(inputObj.innerHTML.indexOf('-')>=0){
var startHour = hourItems[1].innerHTML/1 -1;
if(startHour<0)startHour=0;
if(activeSelectBoxHour){
activeSelectBoxHour.style.color='';
}
}else{
var startHour = hourItems[1].innerHTML/1 +1;
if(startHour>14)startHour = 14;
if(activeSelectBoxHour){
activeSelectBoxHour.style.color='';
}
}
var prefix = '';
for(var no=1;no<hourItems.length-1;no++){
if((startHour/1 + no/1) < 11)prefix = '0'; else prefix = '';
hourItems[no].innerHTML = prefix + (startHour+no-1);
hourItems[no].id = 'hourDiv' + (startHour/1+no/1-1);
}
if(activeSelectBoxHour){
activeSelectBoxHour.style.color='';
if(document.getElementById('hourDiv'+currentHour)){
activeSelectBoxHour = document.getElementById('hourDiv'+currentHour);
activeSelectBoxHour.style.color=selectBoxHighlightColor;;
}
}
}
function updateYearDiv()
{
var div = document.getElementById('yearDropDown');
var yearItems = div.getElementsByTagName('DIV');
for(var no=1;no<yearItems.length-1;no++){
yearItems[no].innerHTML = currentYear/1 -6 + no;
if(currentYear==(currentYear/1 -6 + no)){
yearItems[no].style.color = selectBoxHighlightColor;
activeSelectBoxYear = yearItems[no];
}else{
yearItems[no].style.color = '';
}
}
}
function updateMonthDiv()
{
for(no=0;no<12;no++){
document.getElementById('monthDiv_' + no).style.color = '';
}
document.getElementById('monthDiv_' + currentMonth).style.color = selectBoxHighlightColor;
activeSelectBoxMonth = document.getElementById('monthDiv_' + currentMonth);
}
function updateHourDiv()
{
var div = document.getElementById('hourDropDown');
var hourItems = div.getElementsByTagName('DIV');
var addHours = 0;
if((currentHour/1 -6 + 1)<0){
addHours = (currentHour/1 -6 + 1)*-1;
}
for(var no=1;no<hourItems.length-1;no++){
var prefix='';
if((currentHour/1 -6 + no + addHours) < 10)prefix='0';
hourItems[no].innerHTML = prefix + (currentHour/1 -6 + no + addHours);
if(currentHour==(currentHour/1 -6 + no)){
hourItems[no].style.color = selectBoxHighlightColor;
activeSelectBoxHour = hourItems[no];
}else{
hourItems[no].style.color = '';
}
}
}
function updateMinuteDiv()
{
for(no=0;no<60;no+=intervalSelectBox_minutes){
var prefix = '';
if(no<10)prefix = '0';
document.getElementById('minuteDiv_' + prefix + no).style.color = '';
}
if(document.getElementById('minuteDiv_' + currentMinute)){
document.getElementById('minuteDiv_' + currentMinute).style.color = selectBoxHighlightColor;
activeSelectBoxMinute = document.getElementById('minuteDiv_' + currentMinute);
}
}
function createYearDiv()
{
if(!document.getElementById('yearDropDown')){
var div = document.createElement('DIV');
div.className='monthYearPicker';
}else{
var div = document.getElementById('yearDropDown');
var subDivs = div.getElementsByTagName('DIV');
for(var no=0;no<subDivs.length;no++){
subDivs[no].parentNode.removeChild(subDivs[no]);
}
}
var d = new Date();
if(currentYear){
d.setFullYear(currentYear);
}
var startYear = d.getFullYear()/1 - 5;
var subDiv = document.createElement('DIV');
subDiv.innerHTML = ' - ';
subDiv.onclick = changeSelectBoxYear;
subDiv.onmouseover = highlightMonthYear;
subDiv.onmouseout = function(){ selectBoxMovementInProgress = false;};
subDiv.onselectstart = cancelCalendarEvent;
div.appendChild(subDiv);
for(var no=startYear;no<(startYear+10);no++){
var subDiv = document.createElement('DIV');
subDiv.innerHTML = no;
subDiv.onmouseover = highlightMonthYear;
subDiv.onmouseout = highlightMonthYear;
subDiv.onclick = selectYear;
subDiv.id = 'yearDiv' + no;
subDiv.onselectstart = cancelCalendarEvent;
div.appendChild(subDiv);
if(currentYear && currentYear==no){
subDiv.style.color = selectBoxHighlightColor;
activeSelectBoxYear = subDiv;
}
}
var subDiv = document.createElement('DIV');
subDiv.innerHTML = ' + ';
subDiv.onclick = changeSelectBoxYear;
subDiv.onmouseover = highlightMonthYear;
subDiv.onmouseout = function(){ selectBoxMovementInProgress = false;};
subDiv.onselectstart = cancelCalendarEvent;
div.appendChild(subDiv);
return div;
}
/* This function creates the hour div at the bottom bar */
function slideCalendarSelectBox()
{
if(selectBoxMovementInProgress){
if(activeSelectBox.parentNode.id=='hourDropDown'){
changeSelectBoxHour(false,activeSelectBox);
}
if(activeSelectBox.parentNode.id=='yearDropDown'){
changeSelectBoxYear(false,activeSelectBox);
}
}
setTimeout('slideCalendarSelectBox()',speedOfSelectBoxSliding);
}
function createHourDiv()
{
if(!document.getElementById('hourDropDown')){
var div = document.createElement('DIV');
div.className='monthYearPicker';
}else{
var div = document.getElementById('hourDropDown');
var subDivs = div.getElementsByTagName('DIV');
for(var no=0;no<subDivs.length;no++){
subDivs[no].parentNode.removeChild(subDivs[no]);
}
}
if(!currentHour)currentHour=0;
var startHour = currentHour/1;
if(startHour>14)startHour=14;
var subDiv = document.createElement('DIV');
subDiv.innerHTML = ' - ';
subDiv.onclick = changeSelectBoxHour;
subDiv.onmouseover = highlightMonthYear;
subDiv.onmouseout = function(){ selectBoxMovementInProgress = false;};
subDiv.onselectstart = cancelCalendarEvent;
div.appendChild(subDiv);
for(var no=startHour;no<startHour+10;no++){
var prefix = '';
if(no/1<10)prefix='0';
var subDiv = document.createElement('DIV');
subDiv.innerHTML = prefix + no;
subDiv.onmouseover = highlightMonthYear;
subDiv.onmouseout = highlightMonthYear;
subDiv.onclick = selectHour;
subDiv.id = 'hourDiv' + no;
subDiv.onselectstart = cancelCalendarEvent;
div.appendChild(subDiv);
if(currentYear && currentYear==no){
subDiv.style.color = selectBoxHighlightColor;
activeSelectBoxYear = subDiv;
}
}
var subDiv = document.createElement('DIV');
subDiv.innerHTML = ' + ';
subDiv.onclick = changeSelectBoxHour;
subDiv.onmouseover = highlightMonthYear;
subDiv.onmouseout = function(){ selectBoxMovementInProgress = false;};
subDiv.onselectstart = cancelCalendarEvent;
div.appendChild(subDiv);
return div;
}
/* This function creates the minute div at the bottom bar */
function createMinuteDiv()
{
if(!document.getElementById('minuteDropDown')){
var div = document.createElement('DIV');
div.className='monthYearPicker';
}else{
var div = document.getElementById('minuteDropDown');
var subDivs = div.getElementsByTagName('DIV');
for(var no=0;no<subDivs.length;no++){
subDivs[no].parentNode.removeChild(subDivs[no]);
}
}
var startMinute = 0;
var prefix = '';
for(var no=startMinute;no<60;no+=intervalSelectBox_minutes){
if(no<10)prefix='0'; else prefix = '';
var subDiv = document.createElement('DIV');
subDiv.innerHTML = prefix + no;
subDiv.onmouseover = highlightMonthYear;
subDiv.onmouseout = highlightMonthYear;
subDiv.onclick = selectMinute;
subDiv.id = 'minuteDiv_' + prefix + no;
subDiv.onselectstart = cancelCalendarEvent;
div.appendChild(subDiv);
if(currentYear && currentYear==no){
subDiv.style.color = selectBoxHighlightColor;
activeSelectBoxYear = subDiv;
}
}
return div;
}
function highlightSelect()
{
if(this.className=='selectBoxTime'){
this.className = 'selectBoxTimeOver';
this.getElementsByTagName('IMG')[0].src = pathToCalImages + 'down_time_over.gif';
}else if(this.className=='selectBoxTimeOver'){
this.className = 'selectBoxTime';
this.getElementsByTagName('IMG')[0].src = pathToCalImages + 'down_time.gif';
}
if(this.className=='selectBox'){
this.className = 'selectBoxOver';
this.getElementsByTagName('IMG')[0].src = pathToCalImages + 'down_over.gif';
}else if(this.className=='selectBoxOver'){
this.className = 'selectBox';
this.getElementsByTagName('IMG')[0].src = pathToCalImages + 'down.gif';
}
}
function highlightArrow()
{
if(this.src.indexOf('over')>=0){
if(this.src.indexOf('left')>=0)this.src = pathToCalImages + 'left.gif';
if(this.src.indexOf('right')>=0)this.src = pathToCalImages + 'right.gif';
}else{
if(this.src.indexOf('left')>=0)this.src = pathToCalImages + 'left_over.gif';
if(this.src.indexOf('right')>=0)this.src = pathToCalImages + 'right_over.gif';
}
}
function highlightClose()
{
if(this.src.indexOf('over')>=0){
this.src = pathToCalImages + 'close.gif';
}else{
this.src = pathToCalImages + 'close_over.gif';
}
}
function closeCalendar(){
document.getElementById('yearDropDown').style.display='none';
document.getElementById('monthDropDown').style.display='none';
document.getElementById('hourDropDown').style.display='none';
document.getElementById('minuteDropDown').style.display='none';
calendarDiv.style.display='none';
if(iframeObj){
iframeObj.style.display='none';
//// //// fix for EI frame problem on time dropdowns 09/30/2006
EIS_Hide_Frame();}
if(activeSelectBoxMonth)activeSelectBoxMonth.className='';
if(activeSelectBoxYear)activeSelectBoxYear.className='';
}
function writeTopBar()
{
var topBar = document.createElement('DIV');
topBar.className = 'topBar';
topBar.id = 'topBar';
calendarDiv.appendChild(topBar);
// Left arrow
var leftDiv = document.createElement('DIV');
leftDiv.style.marginRight = '1px';
var img = document.createElement('IMG');
img.src = pathToCalImages + 'left.gif';
img.onmouseover = highlightArrow;
img.onclick = switchMonth;
img.onmouseout = highlightArrow;
leftDiv.appendChild(img);
topBar.appendChild(leftDiv);
if(Opera)leftDiv.style.width = '16px';
// Right arrow
var rightDiv = document.createElement('DIV');
rightDiv.style.marginRight = '1px';
var img = document.createElement('IMG');
img.src = pathToCalImages + 'right.gif';
img.onclick = switchMonth;
img.onmouseover = highlightArrow;
img.onmouseout = highlightArrow;
rightDiv.appendChild(img);
if(Opera)rightDiv.style.width = '16px';
topBar.appendChild(rightDiv);
// Month selector
var monthDiv = document.createElement('DIV');
monthDiv.id = 'monthSelect';
monthDiv.onmouseover = highlightSelect;
monthDiv.onmouseout = highlightSelect;
monthDiv.onclick = showMonthDropDown;
var span = document.createElement('SPAN');
span.innerHTML = monthArray[currentMonth];
span.id = 'calendar_month_txt';
monthDiv.appendChild(span);
var img = document.createElement('IMG');
img.src = pathToCalImages + 'down.gif';
img.style.position = 'absolute';
img.style.right = '0px';
monthDiv.appendChild(img);
monthDiv.className = 'selectBox';
if(Opera){
img.style.cssText = 'float:right;position:relative';
img.style.position = 'relative';
img.style.styleFloat = 'right';
}
topBar.appendChild(monthDiv);
var monthPicker = createMonthDiv();
monthPicker.style.left = '37px';
monthPicker.style.top = monthDiv.offsetTop + monthDiv.offsetHeight + 1 + 'px';
monthPicker.style.width ='60px';
monthPicker.id = 'monthDropDown';
calendarDiv.appendChild(monthPicker);
// Year selector
var yearDiv = document.createElement('DIV');
yearDiv.onmouseover = highlightSelect;
yearDiv.onmouseout = highlightSelect;
yearDiv.onclick = showYearDropDown;
var span = document.createElement('SPAN');
span.innerHTML = currentYear;
span.id = 'calendar_year_txt';
yearDiv.appendChild(span);
topBar.appendChild(yearDiv);
var img = document.createElement('IMG');
img.src = pathToCalImages + 'down.gif';
yearDiv.appendChild(img);
yearDiv.className = 'selectBox';
if(Opera){
yearDiv.style.width = '50px';
img.style.cssText = 'float:right';
img.style.position = 'relative';
img.style.styleFloat = 'right';
}
var yearPicker = createYearDiv();
yearPicker.style.left = '113px';
yearPicker.style.top = monthDiv.offsetTop + monthDiv.offsetHeight + 1 + 'px';
yearPicker.style.width = '35px';
yearPicker.id = 'yearDropDown';
calendarDiv.appendChild(yearPicker);
var img = document.createElement('IMG');
img.src = pathToCalImages + 'close.gif';
img.style.styleFloat = 'right';
img.onmouseover = highlightClose;
img.onmouseout = highlightClose;
img.onclick = closeCalendar;
topBar.appendChild(img);
if(!document.all){
img.style.position = 'absolute';
img.style.right = '2px';
}
}
function writeCalendarContent()
{
var calendarContentDivExists = true;
if(!calendarContentDiv){
calendarContentDiv = document.createElement('DIV');
calendarDiv.appendChild(calendarContentDiv);
calendarContentDivExists = false;
}
currentMonth = currentMonth/1;
var d = new Date();
d.setFullYear(currentYear);
d.setDate(1);
d.setMonth(currentMonth);
var dayStartOfMonth = d.getDay();
if(dayStartOfMonth==0)dayStartOfMonth=7;
dayStartOfMonth--;
document.getElementById('calendar_year_txt').innerHTML = currentYear;
document.getElementById('calendar_month_txt').innerHTML = monthArray[currentMonth];
document.getElementById('calendar_hour_txt').innerHTML = currentHour;
document.getElementById('calendar_minute_txt').innerHTML = currentMinute;
var existingTable = calendarContentDiv.getElementsByTagName('TABLE');
if(existingTable.length>0){
calendarContentDiv.removeChild(existingTable[0]);
}
var calTable = document.createElement('TABLE');
calTable.width = '100%';
calTable.cellSpacing = '0';
calendarContentDiv.appendChild(calTable);
var calTBody = document.createElement('TBODY');
calTable.appendChild(calTBody);
var row = calTBody.insertRow(-1);
row.className = 'calendar_week_row';
var cell = row.insertCell(-1);
cell.innerHTML = weekString;
cell.className = 'calendar_week_column';
cell.style.backgroundColor = selectBoxRolloverBgColor;
for(var no=0;no<dayArray.length;no++){
var cell = row.insertCell(-1);
cell.innerHTML = dayArray[no];
}
var row = calTBody.insertRow(-1);
var cell = row.insertCell(-1);
cell.className = 'calendar_week_column';
cell.style.backgroundColor = selectBoxRolloverBgColor;
var week = getWeek(currentYear,currentMonth,1);
cell.innerHTML = week; // Week
for(var no=0;no<dayStartOfMonth;no++){
var cell = row.insertCell(-1);
cell.innerHTML = ' ';
}
var colCounter = dayStartOfMonth;
var daysInMonth = daysInMonthArray[currentMonth];
if(daysInMonth==28){
if(isLeapYear(currentYear))daysInMonth=29;
}
for(var no=1;no<=daysInMonth;no++){
d.setDate(no-1);
if(colCounter>0 && colCounter%7==0){
var row = calTBody.insertRow(-1);
var cell = row.insertCell(-1);
cell.className = 'calendar_week_column';
var week = getWeek(currentYear,currentMonth,no);
cell.innerHTML = week; // Week
cell.style.backgroundColor = selectBoxRolloverBgColor;
}
var cell = row.insertCell(-1);
if(currentYear==inputYear && currentMonth == inputMonth && no==inputDay){
cell.className='activeDay';
}
cell.innerHTML = no;
cell.onclick = pickDate;
colCounter++;
}
if(!document.all){
if(calendarContentDiv.offsetHeight)
document.getElementById('topBar').style.top = calendarContentDiv.offsetHeight + document.getElementById('timeBar').offsetHeight + document.getElementById('topBar').offsetHeight -1 + 'px';
else{
document.getElementById('topBar').style.top = '';
document.getElementById('topBar').style.bottom = '0px';
}
}
if(iframeObj){
if(!calendarContentDivExists)setTimeout('resizeIframe()',350);else setTimeout('resizeIframe()',10);
}
}
function resizeIframe()
{
iframeObj.style.width = calendarDiv.offsetWidth + 'px';
iframeObj.style.height = calendarDiv.offsetHeight + 'px' ;
}
function pickTodaysDate()
{
var d = new Date();
currentMonth = d.getMonth();
currentYear = d.getFullYear();
pickDate(false,d.getDate());
}
function pickDate(e,inputDay)
{
var month = currentMonth/1 +1;
if(month<10)month = '0' + month;
var day;
if(!inputDay && this)day = this.innerHTML; else day = inputDay;
if(day/1<10)day = '0' + day;
if(returnFormat){
returnFormat = returnFormat.replace('dd',day);
returnFormat = returnFormat.replace('mm',month);
returnFormat = returnFormat.replace('yyyy',currentYear);
returnFormat = returnFormat.replace('hh',currentHour);
returnFormat = returnFormat.replace('ii',currentMinute);
returnFormat = returnFormat.replace('d',day/1);
returnFormat = returnFormat.replace('m',month/1);
returnDateTo.value = returnFormat;
try{
returnDateTo.onchange();
}catch(e){
}
}else{
for(var no=0;no<returnDateToYear.options.length;no++){
if(returnDateToYear.options[no].value==currentYear){
returnDateToYear.selectedIndex=no;
break;
}
}
for(var no=0;no<returnDateToMonth.options.length;no++){
if(returnDateToMonth.options[no].value==parseInt(month,10)){
returnDateToMonth.selectedIndex=no;
break;
}
}
for(var no=0;no<returnDateToDay.options.length;no++){
if(returnDateToDay.options[no].value==parseInt(day,10)){
returnDateToDay.selectedIndex=no;
break;
}
}
if(calendarDisplayTime){
for(var no=0;no<returnDateToHour.options.length;no++){
if(returnDateToHour.options[no].value==parseInt(currentHour,10)){
returnDateToHour.selectedIndex=no;
break;
}
}
for(var no=0;no<returnDateToMinute.options.length;no++){
if(returnDateToMinute.options[no].value==parseInt(currentMinute,10)){
returnDateToMinute.selectedIndex=no;
break;
}
}
}
}
closeCalendar();
}
// This function is from http://www.codeproject.com/csharp/gregorianwknum.asp
// Only changed the month add
function getWeek(year,month,day){
day = day/1;
year = year /1;
month = month/1 + 1; //use 1-12
var a = Math.floor((14-(month))/12);
var y = year+4800-a;
var m = (month)+(12*a)-3;
var jd = day + Math.floor(((153*m)+2)/5) +
(365*y) + Math.floor(y/4) - Math.floor(y/100) +
Math.floor(y/400) - 32045; // (gregorian calendar)
var d4 = (jd+31741-(jd%7))%146097%36524%1461;
var L = Math.floor(d4/1460);
var d1 = ((d4-L)%365)+L;
NumberOfWeek = Math.floor(d1/7) + 1;
return NumberOfWeek;
}
function writeTimeBar()
{
var timeBar = document.createElement('DIV');
timeBar.id = 'timeBar';
timeBar.className = 'timeBar';
var subDiv = document.createElement('DIV');
subDiv.innerHTML = 'Time:';
//timeBar.appendChild(subDiv);
// Year selector
var hourDiv = document.createElement('DIV');
hourDiv.onmouseover = highlightSelect;
hourDiv.onmouseout = highlightSelect;
hourDiv.onclick = showHourDropDown;
hourDiv.style.width = '30px';
var span = document.createElement('SPAN');
span.innerHTML = currentHour;
span.id = 'calendar_hour_txt';
hourDiv.appendChild(span);
timeBar.appendChild(hourDiv);
var img = document.createElement('IMG');
img.src = pathToCalImages + 'down_time.gif';
hourDiv.appendChild(img);
hourDiv.className = 'selectBoxTime';
if(Opera){
hourDiv.style.width = '30px';
img.style.cssText = 'float:right';
img.style.position = 'relative';
img.style.styleFloat = 'right';
}
var hourPicker = createHourDiv();
hourPicker.style.left = '130px';
//hourPicker.style.top = monthDiv.offsetTop + monthDiv.offsetHeight + 1 + 'px';
hourPicker.style.width = '35px';
hourPicker.id = 'hourDropDown';
calendarDiv.appendChild(hourPicker);
// Add Minute picker
// Year selector
var minuteDiv = document.createElement('DIV');
minuteDiv.onmouseover = highlightSelect;
minuteDiv.onmouseout = highlightSelect;
minuteDiv.onclick = showMinuteDropDown;
minuteDiv.style.width = '30px';
var span = document.createElement('SPAN');
span.innerHTML = currentMinute;
span.id = 'calendar_minute_txt';
minuteDiv.appendChild(span);
timeBar.appendChild(minuteDiv);
var img = document.createElement('IMG');
img.src = pathToCalImages + 'down_time.gif';
minuteDiv.appendChild(img);
minuteDiv.className = 'selectBoxTime';
if(Opera){
minuteDiv.style.width = '30px';
img.style.cssText = 'float:right';
img.style.position = 'relative';
img.style.styleFloat = 'right';
}
var minutePicker = createMinuteDiv();
minutePicker.style.left = '167px';
//minutePicker.style.top = monthDiv.offsetTop + monthDiv.offsetHeight + 1 + 'px';
minutePicker.style.width = '35px';
minutePicker.id = 'minuteDropDown';
calendarDiv.appendChild(minutePicker);
return timeBar;
}
function writeBottomBar()
{
var d = new Date();
var bottomBar = document.createElement('DIV');
bottomBar.id = 'bottomBar';
bottomBar.style.cursor = 'pointer';
bottomBar.className = 'todaysDate';
// var todayStringFormat = '[todayString] [dayString] [day] [monthString] [year]'; ;;
var subDiv = document.createElement('DIV');
subDiv.onclick = pickTodaysDate;
subDiv.id = 'todaysDateString';
subDiv.style.width = (calendarDiv.offsetWidth - 95) + 'px';
var day = d.getDay();
if(day==0)day = 7;
day--;
var bottomString = todayStringFormat;
bottomString = bottomString.replace('[monthString]',monthArrayShort[d.getMonth()]);
bottomString = bottomString.replace('[day]',d.getDate());
bottomString = bottomString.replace('[year]',d.getFullYear());
bottomString = bottomString.replace('[dayString]',dayArray[day].toLowerCase());
bottomString = bottomString.replace('[UCFdayString]',dayArray[day]);
bottomString = bottomString.replace('[todayString]',todayString);
subDiv.innerHTML = todayString + ': ' + d.getDate() + '. ' + monthArrayShort[d.getMonth()] + ', ' + d.getFullYear() ;
subDiv.innerHTML = bottomString ;
bottomBar.appendChild(subDiv);
var timeDiv = writeTimeBar();
bottomBar.appendChild(timeDiv);
calendarDiv.appendChild(bottomBar);
}
function getTopPos(inputObj)
{
var returnValue = inputObj.offsetTop + inputObj.offsetHeight;
while((inputObj = inputObj.offsetParent) != null)returnValue += inputObj.offsetTop;
return returnValue + calendar_offsetTop;
}
function getleftPos(inputObj)
{
var returnValue = inputObj.offsetLeft;
while((inputObj = inputObj.offsetParent) != null)returnValue += inputObj.offsetLeft;
return returnValue + calendar_offsetLeft;
}
function positionCalendar(inputObj)
{
calendarDiv.style.left = getleftPos(inputObj) + 'px';
calendarDiv.style.top = getTopPos(inputObj) + 'px';
if(iframeObj){
iframeObj.style.left = calendarDiv.style.left;
iframeObj.style.top = calendarDiv.style.top;
//// fix for EI frame problem on time dropdowns 09/30/2006
iframeObj2.style.left = calendarDiv.style.left;
iframeObj2.style.top = calendarDiv.style.top;
}
}
function initCalendar()
{
if(MSIE){
iframeObj = document.createElement('IFRAME');
iframeObj.style.filter = 'alpha(opacity=0)';
iframeObj.style.position = 'absolute';
iframeObj.border='0px';
iframeObj.style.border = '0px';
iframeObj.style.backgroundColor = '#FF0000';
//// fix for EI frame problem on time dropdowns 09/30/2006
iframeObj2 = document.createElement('IFRAME');
iframeObj2.style.position = 'absolute';
iframeObj2.border='0px';
iframeObj2.style.border = '0px';
iframeObj2.style.height = '1px';
iframeObj2.style.width = '1px';
document.body.appendChild(iframeObj2);
//// fix for EI frame problem on time dropdowns 09/30/2006
// Added fixed for HTTPS
iframeObj2.src = 'blank.html';
iframeObj.src = 'blank.html';
document.body.appendChild(iframeObj);
}
calendarDiv = document.createElement('DIV');
calendarDiv.id = 'calendarDiv';
calendarDiv.style.zIndex = 1000;
slideCalendarSelectBox();
document.body.appendChild(calendarDiv);
writeBottomBar();
writeTopBar();
if(!currentYear){
var d = new Date();
currentMonth = d.getMonth();
currentYear = d.getFullYear();
}
writeCalendarContent();
}
function setTimeProperties()
{
if(!calendarDisplayTime){
document.getElementById('timeBar').style.display='none';
document.getElementById('timeBar').style.visibility='hidden';
document.getElementById('todaysDateString').style.width = '100%';
}else{
document.getElementById('timeBar').style.display='block';
document.getElementById('timeBar').style.visibility='visible';
document.getElementById('hourDropDown').style.top = document.getElementById('calendar_minute_txt').parentNode.offsetHeight + calendarContentDiv.offsetHeight + document.getElementById('topBar').offsetHeight + 'px';
document.getElementById('minuteDropDown').style.top = document.getElementById('calendar_minute_txt').parentNode.offsetHeight + calendarContentDiv.offsetHeight + document.getElementById('topBar').offsetHeight + 'px';
document.getElementById('minuteDropDown').style.right = '50px';
document.getElementById('hourDropDown').style.right = '50px';
document.getElementById('todaysDateString').style.width = '115px';
}
}
function calendarSortItems(a,b)
{
return a/1 - b/1;
}
function displayCalendar(inputField,format,buttonObj,displayTime,timeInput)
{
if(displayTime)calendarDisplayTime=true; else calendarDisplayTime = false;
if(inputField.value.length>0){
if(!format.match(/^[0-9]*?$/gi)){
var items = inputField.value.split(/[^0-9]/gi);
var positionArray = new Array();
positionArray['m'] = format.indexOf('mm');
if(positionArray['m']==-1)positionArray['m'] = format.indexOf('m');
positionArray['d'] = format.indexOf('dd');
if(positionArray['d']==-1)positionArray['d'] = format.indexOf('d');
positionArray['y'] = format.indexOf('yyyy');
positionArray['h'] = format.indexOf('hh');
positionArray['i'] = format.indexOf('ii');
var positionArrayNumeric = Array();
positionArrayNumeric[0] = positionArray['m'];
positionArrayNumeric[1] = positionArray['d'];
positionArrayNumeric[2] = positionArray['y'];
positionArrayNumeric[3] = positionArray['h'];
positionArrayNumeric[4] = positionArray['i'];
positionArrayNumeric = positionArrayNumeric.sort(calendarSortItems);
var itemIndex = -1;
currentHour = '00';
currentMinute = '00';
for(var no=0;no<positionArrayNumeric.length;no++){
if(positionArrayNumeric[no]==-1)continue;
itemIndex++;
if(positionArrayNumeric[no]==positionArray['m']){
currentMonth = items[itemIndex]-1;
continue;
}
if(positionArrayNumeric[no]==positionArray['y']){
currentYear = items[itemIndex];
continue;
}
if(positionArrayNumeric[no]==positionArray['d']){
tmpDay = items[itemIndex];
continue;
}
if(positionArrayNumeric[no]==positionArray['h']){
currentHour = items[itemIndex];
continue;
}
if(positionArrayNumeric[no]==positionArray['i']){
currentMinute = items[itemIndex];
continue;
}
}
currentMonth = currentMonth / 1;
tmpDay = tmpDay / 1;
}else{
var monthPos = format.indexOf('mm');
currentMonth = inputField.value.substr(monthPos,2)/1 -1;
var yearPos = format.indexOf('yyyy');
currentYear = inputField.value.substr(yearPos,4);
var dayPos = format.indexOf('dd');
tmpDay = inputField.value.substr(dayPos,2);
var hourPos = format.indexOf('hh');
if(hourPos>=0){
tmpHour = inputField.value.substr(hourPos,2);
currentHour = tmpHour;
}else{
currentHour = '00';
}
var minutePos = format.indexOf('ii');
if(minutePos>=0){
tmpMinute = inputField.value.substr(minutePos,2);
currentMinute = tmpMinute;
}else{
currentMinute = '00';
}
}
}else{
var d = new Date();
currentMonth = d.getMonth();
currentYear = d.getFullYear();
currentHour = '08';
currentMinute = '00';
tmpDay = d.getDate();
}
inputYear = currentYear;
inputMonth = currentMonth;
inputDay = tmpDay/1;
if(!calendarDiv){
initCalendar();
}else{
if(calendarDiv.style.display=='block'){
closeCalendar();
return false;
}
writeCalendarContent();
}
returnFormat = format;
returnDateTo = inputField;
positionCalendar(buttonObj);
calendarDiv.style.visibility = 'visible';
calendarDiv.style.display = 'block';
if(iframeObj){
iframeObj.style.display = '';
iframeObj.style.height = '140px';
iframeObj.style.width = '195px';
iframeObj2.style.display = '';
iframeObj2.style.height = '140px';
iframeObj2.style.width = '195px';
}
setTimeProperties();
updateYearDiv();
updateMonthDiv();
updateMinuteDiv();
updateHourDiv();
}
function displayCalendarSelectBox(yearInput,monthInput,dayInput,hourInput,minuteInput,buttonObj)
{
if(!hourInput)calendarDisplayTime=false; else calendarDisplayTime = true;
//alert(dayInput);
currentMonth = monthInput.options[monthInput.selectedIndex].value/1-1;
currentYear = yearInput.options[yearInput.selectedIndex].value;
var d = new Date();
if (currentMonth==-1) currentMonth = d.getMonth();
if (currentYear==0) currentYear = d.getFullYear();
if(hourInput){
currentHour = hourInput.options[hourInput.selectedIndex].value;
inputHour = currentHour/1;
}
if(minuteInput){
currentMinute = minuteInput.options[minuteInput.selectedIndex].value;
inputMinute = currentMinute/1;
}
inputYear = yearInput.options[yearInput.selectedIndex].value;
inputMonth = monthInput.options[monthInput.selectedIndex].value/1 - 1;
inputDay = dayInput.options[dayInput.selectedIndex].value/1;
if (inputDay==0) inputDay = 1;
if(!calendarDiv){
initCalendar();
}else{
writeCalendarContent();
}
returnDateToYear = yearInput;
returnDateToMonth = monthInput;
returnDateToDay = dayInput;
returnDateToHour = hourInput;
returnDateToMinute = minuteInput;
returnFormat = false;
returnDateTo = false;
positionCalendar(buttonObj);
calendarDiv.style.visibility = 'visible';
calendarDiv.style.display = 'block';
if(iframeObj){
iframeObj.style.display = '';
iframeObj.style.height = calendarDiv.offsetHeight + 'px';
iframeObj.style.width = calendarDiv.offsetWidth + 'px';
//// fix for EI frame problem on time dropdowns 09/30/2006
iframeObj2.style.display = '';
iframeObj2.style.height = calendarDiv.offsetHeight + 'px';
iframeObj2.style.width = calendarDiv.offsetWidth + 'px'
}
setTimeProperties();
updateYearDiv();
updateMonthDiv();
updateHourDiv();
updateMinuteDiv();
}
|
import Resolver from 'ember/resolver';
var resolver = Resolver.create();
resolver.namespace = {
modulePrefix: 'map-app'
};
export default resolver;
|
'use strict';
module.exports = function (t, a) {
var foo = 'raz',
bar = 'dwa',
fn = function fn(a, b) {
return this + a + b + foo + bar;
},
result;
result = t(fn, 3);
a(result.call('marko', 'el', 'fe'), 'markoelferazdwa', "Content");
a(result.length, 3, "Length");
a(result.prototype, fn.prototype, "Prototype");
};
//# sourceMappingURL=_define-length-compiled.js.map |
var tag, tag_text;
var name, name_jp;
var labeltags = document.getElementsByTagName("label");
for (var i = 0; i < labeltags.length; i++) {
tag = labeltags[i];
tag_text = tag.innerText;
for (var j=0; j<skill_replace_list.length; j++) {
name = skill_replace_list[j]["name"];
name_jp = skill_replace_list[j]["name_jp"];
// replace on exact match only
if (tag_text == name_jp) {
tag.innerText = name;
tag.setAttribute("title", name_jp);
matched = true;
break;
}
}
}
|
(function () {
'use strict';
// Uploadfiles controller
angular
.module('uploadfiles')
.controller('UploadfilesController', UploadfilesController);
UploadfilesController.$inject = ['$scope', '$state', '$window', 'Authentication', 'uploadfileResolve'];
function UploadfilesController ($scope, $state, $window, Authentication, uploadfile) {
var vm = this;
vm.authentication = Authentication;
vm.uploadfile = uploadfile;
vm.error = null;
vm.form = {};
vm.remove = remove;
vm.save = save;
// Remove existing Uploadfile
function remove() {
if ($window.confirm('Are you sure you want to delete?')) {
vm.uploadfile.$remove($state.go('uploadfiles.list'));
}
}
// Save Uploadfile
function save(isValid) {
if (!isValid) {
$scope.$broadcast('show-errors-check-validity', 'vm.form.uploadfileForm');
return false;
}
// TODO: move create/update logic to service
if (vm.uploadfile._id) {
vm.uploadfile.$update(successCallback, errorCallback);
} else {
vm.uploadfile.$save(successCallback, errorCallback);
}
function successCallback(res) {
$state.go('uploadfiles.view', {
uploadfileId: res._id
});
}
function errorCallback(res) {
vm.error = res.data.message;
}
}
}
}());
|
'use strict';
const common = require('../common');
const assert = require('assert');
const URLSearchParams = require('url').URLSearchParams;
const { test, assert_false, assert_true } = require('../common/wpt');
/* The following tests are copied from WPT. Modifications to them should be
upstreamed first. Refs:
https://github.com/w3c/web-platform-tests/blob/8791bed/url/urlsearchparams-has.html
License: http://www.w3.org/Consortium/Legal/2008/04-testsuite-copyright.html
*/
/* eslint-disable */
test(function() {
var params = new URLSearchParams('a=b&c=d');
assert_true(params.has('a'));
assert_true(params.has('c'));
assert_false(params.has('e'));
params = new URLSearchParams('a=b&c=d&a=e');
assert_true(params.has('a'));
params = new URLSearchParams('=b&c=d');
assert_true(params.has(''));
params = new URLSearchParams('null=a');
assert_true(params.has(null));
}, 'Has basics');
test(function() {
var params = new URLSearchParams('a=b&c=d&&');
params.append('first', 1);
params.append('first', 2);
assert_true(params.has('a'), 'Search params object has name "a"');
assert_true(params.has('c'), 'Search params object has name "c"');
assert_true(params.has('first'), 'Search params object has name "first"');
assert_false(params.has('d'), 'Search params object has no name "d"');
params.delete('first');
assert_false(params.has('first'), 'Search params object has no name "first"');
}, 'has() following delete()');
/* eslint-enable */
// Tests below are not from WPT.
{
const params = new URLSearchParams();
common.expectsError(() => {
params.has.call(undefined);
}, {
code: 'ERR_INVALID_THIS',
type: TypeError,
message: 'Value of "this" must be of type URLSearchParams'
});
common.expectsError(() => {
params.has();
}, {
code: 'ERR_MISSING_ARGS',
type: TypeError,
message: 'The "name" argument must be specified'
});
const obj = {
toString() { throw new Error('toString'); },
valueOf() { throw new Error('valueOf'); }
};
const sym = Symbol();
assert.throws(() => params.has(obj), /^Error: toString$/);
assert.throws(() => params.has(sym),
/^TypeError: Cannot convert a Symbol value to a string$/);
}
|
//-----------------------------------------------------------------------------
/**
* The sprite which covers the entire game screen.
*
* @class ScreenSprite
* @constructor
*/
function ScreenSprite() {
this.initialize.apply(this, arguments);
}
ScreenSprite.prototype = Object.create(PIXI.Container.prototype);
ScreenSprite.prototype.constructor = ScreenSprite;
ScreenSprite.prototype.initialize = function () {
PIXI.Container.call(this);
this._graphics = new PIXI.Graphics();
this.addChild(this._graphics);
this.opacity = 0;
this._red = -1;
this._green = -1;
this._blue = -1;
this._colorText = '';
this.setBlack();
};
/**
* The opacity of the sprite (0 to 255).
*
* @property opacity
* @type Number
*/
Object.defineProperty(ScreenSprite.prototype, 'opacity', {
get: function () {
return this.alpha * 255;
},
set: function (value) {
this.alpha = value.clamp(0, 255) / 255;
},
configurable: true
});
ScreenSprite.YEPWarned = false;
ScreenSprite.warnYep = function () {
if (!ScreenSprite.YEPWarned) {
console.log("Deprecation warning. Please update YEP_CoreEngine. ScreenSprite is not a sprite, it has graphics inside.");
ScreenSprite.YEPWarned = true;
}
};
Object.defineProperty(ScreenSprite.prototype, 'anchor', {
get: function () {
ScreenSprite.warnYep();
this.scale.x = 1;
this.scale.y = 1;
return {x: 0, y: 0};
},
set: function (value) {
this.alpha = value.clamp(0, 255) / 255;
},
configurable: true
});
Object.defineProperty(ScreenSprite.prototype, 'blendMode', {
get: function () {
return this._graphics.blendMode;
},
set: function (value) {
this._graphics.blendMode = value;
},
configurable: true
});
/**
* Sets black to the color of the screen sprite.
*
* @method setBlack
*/
ScreenSprite.prototype.setBlack = function () {
this.setColor(0, 0, 0);
};
/**
* Sets white to the color of the screen sprite.
*
* @method setWhite
*/
ScreenSprite.prototype.setWhite = function () {
this.setColor(255, 255, 255);
};
/**
* Sets the color of the screen sprite by values.
*
* @method setColor
* @param {Number} r The red value in the range (0, 255)
* @param {Number} g The green value in the range (0, 255)
* @param {Number} b The blue value in the range (0, 255)
*/
ScreenSprite.prototype.setColor = function (r, g, b) {
if (this._red !== r || this._green !== g || this._blue !== b) {
r = Math.round(r || 0).clamp(0, 255);
g = Math.round(g || 0).clamp(0, 255);
b = Math.round(b || 0).clamp(0, 255);
this._red = r;
this._green = g;
this._blue = b;
this._colorText = Utils.rgbToCssColor(r, g, b);
var graphics = this._graphics;
graphics.clear();
var intColor = (r << 16) | (g << 8) | b;
graphics.beginFill(intColor, 1);
//whole screen with zoom. BWAHAHAHAHA
graphics.drawRect(-Graphics.width * 5, -Graphics.height * 5, Graphics.width * 10, Graphics.height * 10);
}
};
|
var sum_pairs = function (ints, s) {
// your code here
};
module.exports = sum_pairs;
|
window.Rendxx = window.Rendxx || {};
window.Rendxx.Game = window.Rendxx.Game || {};
window.Rendxx.Game.Ghost = window.Rendxx.Game.Ghost || {};
window.Rendxx.Game.Ghost.Renderer2D = window.Rendxx.Game.Ghost.Renderer2D || {};
(function (RENDERER) {
var Data = RENDERER.Data;
var GridSize = Data.grid.size;
var _Data = {
size: 3,
tileSize: 128,
tileDispDuration: 50,
Name: {
'Blood': 0,
'Electric': 1
}
};
var Effort = function (entity) {
// data ----------------------------------------------------------
var that = this,
tex = {},
_scene = entity.env.scene['effort'];
// callback ------------------------------------------------------
// public method -------------------------------------------------
this.update = function (newEffort) {
if (newEffort == null || newEffort.length === 0) return;
for (var i = 0, l = newEffort.length; i < l;i++){
createEffort(newEffort[i]);
}
};
this.render = function (delta) {
};
// private method -------------------------------------------------
var createEffort = function (effort) {
if (effort==null) return;
var effortName = effort[0];
var x = effort[1];
var y = effort[2];
if (!tex.hasOwnProperty(effortName)) return;
var item = new PIXI.extras.MovieClip(tex[effortName]);
item.loop = false;
item.anchor.set(0.5, 0.5);
item.animationSpeed = 0.5;
item.position.set(x * GridSize, y * GridSize);
item.scale.set(_Data.size * GridSize / _Data.tileSize, _Data.size * GridSize / _Data.tileSize);
item.onComplete = function () { _scene.removeChild(this) };
_scene.addChild(item);
item.play();
};
// setup -----------------------------------------------
var _setupTex = function () {
tex = {};
var path = entity.root + Data.files.path[Data.categoryName.sprite];
// texture loader -------------------------------------------------------------------------------------------
PIXI.loader
.add(path + 'effort.blood.json')
.add(path + 'effort.electric.json')
.load(function (loader, resources) {
// blood
var frames = [];
var name = path + 'effort.blood.json';
var _f = resources[name].data.frames;
var i = 0;
while (true) {
var val = i < 10 ? '0' + i : i;
if (!_f.hasOwnProperty('animation00' + val)) break;
frames.push(loader.resources[name].textures['animation00' + val]);
i++;
}
tex[_Data.Name.Blood] = frames;
// electric
var frames = [];
var name = path + 'effort.electric.json';
var _f = resources[name].data.frames;
var i = 0;
while (true) {
var val = i < 10 ? '0' + i : i;
if (!_f.hasOwnProperty('animation00' + val)) break;
frames.push(loader.resources[name].textures['animation00' + val]);
i++;
}
tex[_Data.Name.Electric] = frames;
});
};
var _init = function () {
_setupTex();
};
_init();
};
RENDERER.Effort = Effort;
RENDERER.Effort.Data = _Data;
})(window.Rendxx.Game.Ghost.Renderer2D); |
'use strict';
angular.module('applicant-test').controller('ApplicantTestController', ['$scope', '$stateParams', '$location', 'Authentication', 'Questions', '$http',
function($scope, $stateParams, $location, Authentication, Questions, $http ) {
$scope.authentication =Authentication;
$scope.find = function(){
var url = '/test/';
$http.get(url).success(function(response) {
$scope.questions = response;
console.log('Questions init');
console.log($scope.questions);
});
};
// $scope.findOne = function() {
// var url = '/test/' + $stateParams.testId;
// console.log('Getting stateParams');
// console.log($stateParams);
// $http.get(url).success(function(response) {
// $scope.questions = response;
// console.log('Questions init');
// console.log($scope.questions);
// });
// // $scope.test = Questions.get({
// // testId: $stateParams.testId
// // });
// };
}]); |
/**
* Copyright (c) 2015-present, Parse, LLC.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @flow
*/
import CoreManager from './CoreManager';
import encode from './encode';
import ParseError from './ParseError';
import ParseGeoPoint from './ParseGeoPoint';
import ParseObject from './ParseObject';
import ParsePromise from './ParsePromise';
import type { RequestOptions, FullOptions } from './RESTController';
export type WhereClause = {
[attr: string]: mixed;
};
export type QueryJSON = {
where: WhereClause;
include?: string;
keys?: string;
limit?: number;
skip?: number;
order?: string;
className?: string;
count?: number;
};
/**
* Converts a string into a regex that matches it.
* Surrounding with \Q .. \E does this, we just need to escape any \E's in
* the text separately.
*/
function quote(s: string) {
return '\\Q' + s.replace('\\E', '\\E\\\\E\\Q') + '\\E';
}
/**
* Creates a new parse Parse.Query for the given Parse.Object subclass.
* @class Parse.Query
* @constructor
* @param {} objectClass An instance of a subclass of Parse.Object, or a Parse className string.
*
* <p>Parse.Query defines a query that is used to fetch Parse.Objects. The
* most common use case is finding all objects that match a query through the
* <code>find</code> method. For example, this sample code fetches all objects
* of class <code>MyClass</code>. It calls a different function depending on
* whether the fetch succeeded or not.
*
* <pre>
* var query = new Parse.Query(MyClass);
* query.find({
* success: function(results) {
* // results is an array of Parse.Object.
* },
*
* error: function(error) {
* // error is an instance of Parse.Error.
* }
* });</pre></p>
*
* <p>A Parse.Query can also be used to retrieve a single object whose id is
* known, through the get method. For example, this sample code fetches an
* object of class <code>MyClass</code> and id <code>myId</code>. It calls a
* different function depending on whether the fetch succeeded or not.
*
* <pre>
* var query = new Parse.Query(MyClass);
* query.get(myId, {
* success: function(object) {
* // object is an instance of Parse.Object.
* },
*
* error: function(object, error) {
* // error is an instance of Parse.Error.
* }
* });</pre></p>
*
* <p>A Parse.Query can also be used to count the number of objects that match
* the query without retrieving all of those objects. For example, this
* sample code counts the number of objects of the class <code>MyClass</code>
* <pre>
* var query = new Parse.Query(MyClass);
* query.count({
* success: function(number) {
* // There are number instances of MyClass.
* },
*
* error: function(error) {
* // error is an instance of Parse.Error.
* }
* });</pre></p>
*/
export default class ParseQuery {
className: string;
_where: any;
_include: Array<string>;
_select: Array<string>;
_limit: number;
_skip: number;
_order: Array<string>;
_extraOptions: { [key: string]: mixed };
constructor(objectClass: string | ParseObject) {
if (typeof objectClass === 'string') {
if (objectClass === 'User' && CoreManager.get('PERFORM_USER_REWRITE')) {
this.className = '_User';
} else {
this.className = objectClass;
}
} else if (objectClass instanceof ParseObject) {
this.className = objectClass.className;
} else if (typeof objectClass === 'function') {
if (typeof objectClass.className === 'string') {
this.className = objectClass.className;
} else {
var obj = new objectClass();
this.className = obj.className;
}
} else {
throw new TypeError(
'A ParseQuery must be constructed with a ParseObject or class name.'
);
}
this._where = {};
this._include = [];
this._limit = -1; // negative limit is not sent in the server request
this._skip = 0;
this._extraOptions = {};
}
/**
* Adds constraint that at least one of the passed in queries matches.
* @method _orQuery
* @param {Array} queries
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
_orQuery(queries: Array<ParseQuery>): ParseQuery {
var queryJSON = queries.map((q) => {
return q.toJSON().where;
});
this._where.$or = queryJSON;
return this;
}
/**
* Helper for condition queries
*/
_addCondition(key: string, condition: string, value: mixed): ParseQuery {
if (!this._where[key] || typeof this._where[key] === 'string') {
this._where[key] = {};
}
this._where[key][condition] = encode(value, false, true);
return this;
}
/**
* Returns a JSON representation of this query.
* @method toJSON
* @return {Object} The JSON representation of the query.
*/
toJSON(): QueryJSON {
var params: QueryJSON = {
where: this._where
};
if (this._include.length) {
params.include = this._include.join(',');
}
if (this._select) {
params.keys = this._select.join(',');
}
if (this._limit >= 0) {
params.limit = this._limit;
}
if (this._skip > 0) {
params.skip = this._skip;
}
if (this._order) {
params.order = this._order.join(',');
}
for (var key in this._extraOptions) {
params[key] = this._extraOptions[key];
}
return params;
}
/**
* Constructs a Parse.Object whose id is already known by fetching data from
* the server. Either options.success or options.error is called when the
* find completes.
*
* @method get
* @param {String} objectId The id of the object to be fetched.
* @param {Object} options A Backbone-style options object.
* Valid options are:<ul>
* <li>success: A Backbone-style success callback
* <li>error: An Backbone-style error callback.
* <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
* be used for this request.
* <li>sessionToken: A valid session token, used for making a request on
* behalf of a specific user.
* </ul>
*
* @return {Parse.Promise} A promise that is resolved with the result when
* the query completes.
*/
get(objectId: string, options?: FullOptions): ParsePromise {
this.equalTo('objectId', objectId);
var firstOptions = {};
if (options && options.hasOwnProperty('useMasterKey')) {
firstOptions.useMasterKey = options.useMasterKey;
}
if (options && options.hasOwnProperty('sessionToken')) {
firstOptions.sessionToken = options.sessionToken;
}
return this.first(firstOptions).then((response) => {
if (response) {
return response;
}
var errorObject = new ParseError(
ParseError.OBJECT_NOT_FOUND,
'Object not found.'
);
return ParsePromise.error(errorObject);
})._thenRunCallbacks(options, null);
}
/**
* Retrieves a list of ParseObjects that satisfy this query.
* Either options.success or options.error is called when the find
* completes.
*
* @method find
* @param {Object} options A Backbone-style options object. Valid options
* are:<ul>
* <li>success: Function to call when the find completes successfully.
* <li>error: Function to call when the find fails.
* <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
* be used for this request.
* <li>sessionToken: A valid session token, used for making a request on
* behalf of a specific user.
* </ul>
*
* @return {Parse.Promise} A promise that is resolved with the results when
* the query completes.
*/
find(options?: FullOptions): ParsePromise {
options = options || {};
let findOptions = {};
if (options.hasOwnProperty('useMasterKey')) {
findOptions.useMasterKey = options.useMasterKey;
}
if (options.hasOwnProperty('sessionToken')) {
findOptions.sessionToken = options.sessionToken;
}
let controller = CoreManager.getQueryController();
return controller.find(
this.className,
this.toJSON(),
findOptions
).then((response) => {
return response.results.map((data) => {
// In cases of relations, the server may send back a className
// on the top level of the payload
let override = response.className || this.className;
if (!data.className) {
data.className = override;
}
return ParseObject.fromJSON(data, true);
});
})._thenRunCallbacks(options);
}
/**
* Counts the number of objects that match this query.
* Either options.success or options.error is called when the count
* completes.
*
* @method count
* @param {Object} options A Backbone-style options object. Valid options
* are:<ul>
* <li>success: Function to call when the count completes successfully.
* <li>error: Function to call when the find fails.
* <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
* be used for this request.
* <li>sessionToken: A valid session token, used for making a request on
* behalf of a specific user.
* </ul>
*
* @return {Parse.Promise} A promise that is resolved with the count when
* the query completes.
*/
count(options?: FullOptions): ParsePromise {
options = options || {};
var findOptions = {};
if (options.hasOwnProperty('useMasterKey')) {
findOptions.useMasterKey = options.useMasterKey;
}
if (options.hasOwnProperty('sessionToken')) {
findOptions.sessionToken = options.sessionToken;
}
var controller = CoreManager.getQueryController();
var params = this.toJSON();
params.limit = 0;
params.count = 1;
return controller.find(
this.className,
params,
findOptions
).then((result) => {
return result.count;
})._thenRunCallbacks(options);
}
/**
* Retrieves at most one Parse.Object that satisfies this query.
*
* Either options.success or options.error is called when it completes.
* success is passed the object if there is one. otherwise, undefined.
*
* @method first
* @param {Object} options A Backbone-style options object. Valid options
* are:<ul>
* <li>success: Function to call when the find completes successfully.
* <li>error: Function to call when the find fails.
* <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
* be used for this request.
* <li>sessionToken: A valid session token, used for making a request on
* behalf of a specific user.
* </ul>
*
* @return {Parse.Promise} A promise that is resolved with the object when
* the query completes.
*/
first(options?: FullOptions): ParsePromise {
options = options || {};
var findOptions = {};
if (options.hasOwnProperty('useMasterKey')) {
findOptions.useMasterKey = options.useMasterKey;
}
if (options.hasOwnProperty('sessionToken')) {
findOptions.sessionToken = options.sessionToken;
}
var controller = CoreManager.getQueryController();
var params = this.toJSON();
params.limit = 1;
return controller.find(
this.className,
params,
findOptions
).then((response) => {
var objects = response.results;
if (!objects[0]) {
return undefined;
}
if (!objects[0].className) {
objects[0].className = this.className;
}
return ParseObject.fromJSON(objects[0], true);
})._thenRunCallbacks(options);
}
/**
* Iterates over each result of a query, calling a callback for each one. If
* the callback returns a promise, the iteration will not continue until
* that promise has been fulfilled. If the callback returns a rejected
* promise, then iteration will stop with that error. The items are
* processed in an unspecified order. The query may not have any sort order,
* and may not use limit or skip.
* @method each
* @param {Function} callback Callback that will be called with each result
* of the query.
* @param {Object} options An optional Backbone-like options object with
* success and error callbacks that will be invoked once the iteration
* has finished.
* @return {Parse.Promise} A promise that will be fulfilled once the
* iteration has completed.
*/
each(callback: (obj: ParseObject) => any, options?: FullOptions): ParsePromise {
options = options || {};
if (this._order || this._skip || (this._limit >= 0)) {
var error = 'Cannot iterate on a query with sort, skip, or limit.';
return ParsePromise.error(error)._thenRunCallbacks(options);
}
var promise = new ParsePromise();
var query = new ParseQuery(this.className);
// We can override the batch size from the options.
// This is undocumented, but useful for testing.
query._limit = options.batchSize || 100;
query._include = this._include.map((i) => {
return i;
});
if (this._select) {
query._select = this._select.map((s) => {
return s;
});
}
query._where = {};
for (var attr in this._where) {
var val = this._where[attr];
if (Array.isArray(val)) {
query._where[attr] = val.map((v) => {
return v;
});
} else if (val && typeof val === 'object') {
var conditionMap = {};
query._where[attr] = conditionMap;
for (var cond in val) {
conditionMap[cond] = val[cond];
}
} else {
query._where[attr] = val;
}
}
query.ascending('objectId');
var findOptions = {};
if (options.hasOwnProperty('useMasterKey')) {
findOptions.useMasterKey = options.useMasterKey;
}
if (options.hasOwnProperty('sessionToken')) {
findOptions.sessionToken = options.sessionToken;
}
var finished = false;
return ParsePromise._continueWhile(() => {
return !finished;
}, () => {
return query.find(findOptions).then((results) => {
var callbacksDone = ParsePromise.as();
results.forEach((result) => {
callbacksDone = callbacksDone.then(() => {
return callback(result);
});
});
return callbacksDone.then(() => {
if (results.length >= query._limit) {
query.greaterThan('objectId', results[results.length - 1].id);
} else {
finished = true;
}
});
});
})._thenRunCallbacks(options);
}
/** Query Conditions **/
/**
* Adds a constraint to the query that requires a particular key's value to
* be equal to the provided value.
* @method equalTo
* @param {String} key The key to check.
* @param value The value that the Parse.Object must contain.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
equalTo(key: string, value: mixed): ParseQuery {
if (typeof value === 'undefined') {
return this.doesNotExist(key);
}
this._where[key] = encode(value, false, true);
return this;
}
/**
* Adds a constraint to the query that requires a particular key's value to
* be not equal to the provided value.
* @method notEqualTo
* @param {String} key The key to check.
* @param value The value that must not be equalled.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
notEqualTo(key: string, value: mixed): ParseQuery {
return this._addCondition(key, '$ne', value);
}
/**
* Adds a constraint to the query that requires a particular key's value to
* be less than the provided value.
* @method lessThan
* @param {String} key The key to check.
* @param value The value that provides an upper bound.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
lessThan(key: string, value: mixed): ParseQuery {
return this._addCondition(key, '$lt', value);
}
/**
* Adds a constraint to the query that requires a particular key's value to
* be greater than the provided value.
* @method greaterThan
* @param {String} key The key to check.
* @param value The value that provides an lower bound.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
greaterThan(key: string, value: mixed): ParseQuery {
return this._addCondition(key, '$gt', value);
}
/**
* Adds a constraint to the query that requires a particular key's value to
* be less than or equal to the provided value.
* @method lessThanOrEqualTo
* @param {String} key The key to check.
* @param value The value that provides an upper bound.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
lessThanOrEqualTo(key: string, value: mixed): ParseQuery {
return this._addCondition(key, '$lte', value);
}
/**
* Adds a constraint to the query that requires a particular key's value to
* be greater than or equal to the provided value.
* @method greaterThanOrEqualTo
* @param {String} key The key to check.
* @param value The value that provides an lower bound.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
greaterThanOrEqualTo(key: string, value: mixed): ParseQuery {
return this._addCondition(key, '$gte', value);
}
/**
* Adds a constraint to the query that requires a particular key's value to
* be contained in the provided list of values.
* @method containedIn
* @param {String} key The key to check.
* @param {Array} values The values that will match.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
containedIn(key: string, value: mixed): ParseQuery {
return this._addCondition(key, '$in', value);
}
/**
* Adds a constraint to the query that requires a particular key's value to
* not be contained in the provided list of values.
* @method notContainedIn
* @param {String} key The key to check.
* @param {Array} values The values that will not match.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
notContainedIn(key: string, value: mixed): ParseQuery {
return this._addCondition(key, '$nin', value);
}
/**
* Adds a constraint to the query that requires a particular key's value to
* contain each one of the provided list of values.
* @method containsAll
* @param {String} key The key to check. This key's value must be an array.
* @param {Array} values The values that will match.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
containsAll(key: string, values: Array<mixed>): ParseQuery {
return this._addCondition(key, '$all', values);
}
/**
* Adds a constraint for finding objects that contain the given key.
* @method exists
* @param {String} key The key that should exist.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
exists(key: string): ParseQuery {
return this._addCondition(key, '$exists', true);
}
/**
* Adds a constraint for finding objects that do not contain a given key.
* @method doesNotExist
* @param {String} key The key that should not exist
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
doesNotExist(key: string): ParseQuery {
return this._addCondition(key, '$exists', false);
}
/**
* Adds a regular expression constraint for finding string values that match
* the provided regular expression.
* This may be slow for large datasets.
* @method matches
* @param {String} key The key that the string to match is stored in.
* @param {RegExp} regex The regular expression pattern to match.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
matches(key: string, regex: RegExp, modifiers: string): ParseQuery {
this._addCondition(key, '$regex', regex);
if (!modifiers) {
modifiers = '';
}
if (regex.ignoreCase) {
modifiers += 'i';
}
if (regex.multiline) {
modifiers += 'm';
}
if (modifiers.length) {
this._addCondition(key, '$options', modifiers);
}
return this;
}
/**
* Adds a constraint that requires that a key's value matches a Parse.Query
* constraint.
* @method matchesQuery
* @param {String} key The key that the contains the object to match the
* query.
* @param {Parse.Query} query The query that should match.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
matchesQuery(key: string, query: ParseQuery): ParseQuery {
var queryJSON = query.toJSON();
queryJSON.className = query.className;
return this._addCondition(key, '$inQuery', queryJSON);
}
/**
* Adds a constraint that requires that a key's value not matches a
* Parse.Query constraint.
* @method doesNotMatchQuery
* @param {String} key The key that the contains the object to match the
* query.
* @param {Parse.Query} query The query that should not match.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
doesNotMatchQuery(key: string, query: ParseQuery): ParseQuery {
var queryJSON = query.toJSON();
queryJSON.className = query.className;
return this._addCondition(key, '$notInQuery', queryJSON);
}
/**
* Adds a constraint that requires that a key's value matches a value in
* an object returned by a different Parse.Query.
* @method matchesKeyInQuery
* @param {String} key The key that contains the value that is being
* matched.
* @param {String} queryKey The key in the objects returned by the query to
* match against.
* @param {Parse.Query} query The query to run.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
matchesKeyInQuery(key: string, queryKey: string, query: ParseQuery): ParseQuery {
var queryJSON = query.toJSON();
queryJSON.className = query.className;
return this._addCondition(key, '$select', {
key: queryKey,
query: queryJSON
});
}
/**
* Adds a constraint that requires that a key's value not match a value in
* an object returned by a different Parse.Query.
* @method doesNotMatchKeyInQuery
* @param {String} key The key that contains the value that is being
* excluded.
* @param {String} queryKey The key in the objects returned by the query to
* match against.
* @param {Parse.Query} query The query to run.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
doesNotMatchKeyInQuery(key: string, queryKey: string, query: ParseQuery): ParseQuery {
var queryJSON = query.toJSON();
queryJSON.className = query.className;
return this._addCondition(key, '$dontSelect', {
key: queryKey,
query: queryJSON
});
}
/**
* Adds a constraint for finding string values that contain a provided
* string. This may be slow for large datasets.
* @method contains
* @param {String} key The key that the string to match is stored in.
* @param {String} substring The substring that the value must contain.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
contains(key: string, value: string): ParseQuery {
if (typeof value !== 'string') {
throw new Error('The value being searched for must be a string.');
}
return this._addCondition(key, '$regex', quote(value));
}
/**
* Adds a constraint for finding string values that start with a provided
* string. This query will use the backend index, so it will be fast even
* for large datasets.
* @method startsWith
* @param {String} key The key that the string to match is stored in.
* @param {String} prefix The substring that the value must start with.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
startsWith(key: string, value: string): ParseQuery {
if (typeof value !== 'string') {
throw new Error('The value being searched for must be a string.');
}
return this._addCondition(key, '$regex', '^' + quote(value));
}
/**
* Adds a constraint for finding string values that end with a provided
* string. This will be slow for large datasets.
* @method endsWith
* @param {String} key The key that the string to match is stored in.
* @param {String} suffix The substring that the value must end with.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
endsWith(key: string, value: string): ParseQuery {
if (typeof value !== 'string') {
throw new Error('The value being searched for must be a string.');
}
return this._addCondition(key, '$regex', quote(value) + '$');
}
/**
* Adds a proximity based constraint for finding objects with key point
* values near the point given.
* @method near
* @param {String} key The key that the Parse.GeoPoint is stored in.
* @param {Parse.GeoPoint} point The reference Parse.GeoPoint that is used.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
near(key: string, point: ParseGeoPoint): ParseQuery {
if (!(point instanceof ParseGeoPoint)) {
// Try to cast it as a GeoPoint
point = new ParseGeoPoint(point);
}
return this._addCondition(key, '$nearSphere', point);
}
/**
* Adds a proximity based constraint for finding objects with key point
* values near the point given and within the maximum distance given.
* @method withinRadians
* @param {String} key The key that the Parse.GeoPoint is stored in.
* @param {Parse.GeoPoint} point The reference Parse.GeoPoint that is used.
* @param {Number} maxDistance Maximum distance (in radians) of results to
* return.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
withinRadians(key: string, point: ParseGeoPoint, distance: number): ParseQuery {
this.near(key, point);
return this._addCondition(key, '$maxDistance', distance);
}
/**
* Adds a proximity based constraint for finding objects with key point
* values near the point given and within the maximum distance given.
* Radius of earth used is 3958.8 miles.
* @method withinMiles
* @param {String} key The key that the Parse.GeoPoint is stored in.
* @param {Parse.GeoPoint} point The reference Parse.GeoPoint that is used.
* @param {Number} maxDistance Maximum distance (in miles) of results to
* return.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
withinMiles(key: string, point: ParseGeoPoint, distance: number): ParseQuery {
return this.withinRadians(key, point, distance / 3958.8);
}
/**
* Adds a proximity based constraint for finding objects with key point
* values near the point given and within the maximum distance given.
* Radius of earth used is 6371.0 kilometers.
* @method withinKilometers
* @param {String} key The key that the Parse.GeoPoint is stored in.
* @param {Parse.GeoPoint} point The reference Parse.GeoPoint that is used.
* @param {Number} maxDistance Maximum distance (in kilometers) of results
* to return.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
withinKilometers(key: string, point: ParseGeoPoint, distance: number): ParseQuery {
return this.withinRadians(key, point, distance / 6371.0);
}
/**
* Adds a constraint to the query that requires a particular key's
* coordinates be contained within a given rectangular geographic bounding
* box.
* @method withinGeoBox
* @param {String} key The key to be constrained.
* @param {Parse.GeoPoint} southwest
* The lower-left inclusive corner of the box.
* @param {Parse.GeoPoint} northeast
* The upper-right inclusive corner of the box.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
withinGeoBox(key: string, southwest: ParseGeoPoint, northeast: ParseGeoPoint): ParseQuery {
if (!(southwest instanceof ParseGeoPoint)) {
southwest = new ParseGeoPoint(southwest);
}
if (!(northeast instanceof ParseGeoPoint)) {
northeast = new ParseGeoPoint(northeast);
}
this._addCondition(key, '$within', { '$box': [ southwest, northeast ] });
return this;
}
/** Query Orderings **/
/**
* Sorts the results in ascending order by the given key.
*
* @method ascending
* @param {(String|String[]|...String} key The key to order by, which is a
* string of comma separated values, or an Array of keys, or multiple keys.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
ascending(...keys: Array<string>): ParseQuery {
this._order = [];
return this.addAscending.apply(this, keys);
}
/**
* Sorts the results in ascending order by the given key,
* but can also add secondary sort descriptors without overwriting _order.
*
* @method addAscending
* @param {(String|String[]|...String} key The key to order by, which is a
* string of comma separated values, or an Array of keys, or multiple keys.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
addAscending(...keys: Array<string>): ParseQuery {
if (!this._order) {
this._order = [];
}
keys.forEach((key) => {
if (Array.isArray(key)) {
key = key.join();
}
this._order = this._order.concat(key.replace(/\s/g, '').split(','));
});
return this;
}
/**
* Sorts the results in descending order by the given key.
*
* @method descending
* @param {(String|String[]|...String} key The key to order by, which is a
* string of comma separated values, or an Array of keys, or multiple keys.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
descending(...keys: Array<string>): ParseQuery {
this._order = [];
return this.addDescending.apply(this, keys);
}
/**
* Sorts the results in descending order by the given key,
* but can also add secondary sort descriptors without overwriting _order.
*
* @method addDescending
* @param {(String|String[]|...String} key The key to order by, which is a
* string of comma separated values, or an Array of keys, or multiple keys.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
addDescending(...keys: Array<string>): ParseQuery {
if (!this._order) {
this._order = [];
}
keys.forEach((key) => {
if (Array.isArray(key)) {
key = key.join();
}
this._order = this._order.concat(
key.replace(/\s/g, '').split(',').map((k) => {
return '-' + k;
})
);
});
return this;
}
/** Query Options **/
/**
* Sets the number of results to skip before returning any results.
* This is useful for pagination.
* Default is to skip zero results.
* @method skip
* @param {Number} n the number of results to skip.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
skip(n: number): ParseQuery {
if (typeof n !== 'number' || n < 0) {
throw new Error('You can only skip by a positive number');
}
this._skip = n;
return this;
}
/**
* Sets the limit of the number of results to return. The default limit is
* 100, with a maximum of 1000 results being returned at a time.
* @method limit
* @param {Number} n the number of results to limit to.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
limit(n: number): ParseQuery {
if (typeof n !== 'number') {
throw new Error('You can only set the limit to a numeric value');
}
this._limit = n;
return this;
}
/**
* Includes nested Parse.Objects for the provided key. You can use dot
* notation to specify which fields in the included object are also fetched.
* @method include
* @param {String} key The name of the key to include.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
include(...keys: Array<string>): ParseQuery {
keys.forEach((key) => {
if (Array.isArray(key)) {
this._include = this._include.concat(key);
} else {
this._include.push(key);
}
});
return this;
}
/**
* Restricts the fields of the returned Parse.Objects to include only the
* provided keys. If this is called multiple times, then all of the keys
* specified in each of the calls will be included.
* @method select
* @param {Array} keys The names of the keys to include.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
select(...keys: Array<string>): ParseQuery {
if (!this._select) {
this._select = [];
}
keys.forEach((key) => {
if (Array.isArray(key)) {
this._select = this._select.concat(key);
} else {
this._select.push(key);
}
});
return this;
}
/**
* Subscribe this query to get liveQuery updates
* @method subscribe
* @return {LiveQuerySubscription} Returns the liveQuerySubscription, it's an event emitter
* which can be used to get liveQuery updates.
*/
subscribe(): any {
let controller = CoreManager.getLiveQueryController();
return controller.subscribe(this);
}
/**
* Constructs a Parse.Query that is the OR of the passed in queries. For
* example:
* <pre>var compoundQuery = Parse.Query.or(query1, query2, query3);</pre>
*
* will create a compoundQuery that is an or of the query1, query2, and
* query3.
* @method or
* @param {...Parse.Query} var_args The list of queries to OR.
* @static
* @return {Parse.Query} The query that is the OR of the passed in queries.
*/
static or(...queries: Array<ParseQuery>): ParseQuery {
var className = null;
queries.forEach((q) => {
if (!className) {
className = q.className;
}
if (className !== q.className) {
throw new Error('All queries must be for the same class.');
}
});
var query = new ParseQuery(className);
query._orQuery(queries);
return query;
}
}
var DefaultController = {
find(className: string, params: QueryJSON, options: RequestOptions): ParsePromise {
var RESTController = CoreManager.getRESTController();
return RESTController.request(
'GET',
'classes/' + className,
params,
options
);
}
};
CoreManager.setQueryController(DefaultController);
|
/*!
Material Components for the web
Copyright (c) 2017 Google Inc.
License: Apache-2.0
*/
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define([], factory);
else if(typeof exports === 'object')
exports["checkbox"] = factory();
else
root["mdc"] = root["mdc"] || {}, root["mdc"]["checkbox"] = factory();
})(this, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "/assets/";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 27);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
* Copyright 2016 Google Inc.
*
* 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.
*/
/**
* @template A
*/
var MDCFoundation = function () {
_createClass(MDCFoundation, null, [{
key: "cssClasses",
/** @return enum{cssClasses} */
get: function get() {
// Classes extending MDCFoundation should implement this method to return an object which exports every
// CSS class the foundation class needs as a property. e.g. {ACTIVE: 'mdc-component--active'}
return {};
}
/** @return enum{strings} */
}, {
key: "strings",
get: function get() {
// Classes extending MDCFoundation should implement this method to return an object which exports all
// semantic strings as constants. e.g. {ARIA_ROLE: 'tablist'}
return {};
}
/** @return enum{numbers} */
}, {
key: "numbers",
get: function get() {
// Classes extending MDCFoundation should implement this method to return an object which exports all
// of its semantic numbers as constants. e.g. {ANIMATION_DELAY_MS: 350}
return {};
}
/** @return {!Object} */
}, {
key: "defaultAdapter",
get: function get() {
// Classes extending MDCFoundation may choose to implement this getter in order to provide a convenient
// way of viewing the necessary methods of an adapter. In the future, this could also be used for adapter
// validation.
return {};
}
/**
* @param {A=} adapter
*/
}]);
function MDCFoundation() {
var adapter = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
_classCallCheck(this, MDCFoundation);
/** @protected {!A} */
this.adapter_ = adapter;
}
_createClass(MDCFoundation, [{
key: "init",
value: function init() {
// Subclasses should override this method to perform initialization routines (registering events, etc.)
}
}, {
key: "destroy",
value: function destroy() {
// Subclasses should override this method to perform de-initialization routines (de-registering events, etc.)
}
}]);
return MDCFoundation;
}();
/* harmony default export */ __webpack_exports__["a"] = (MDCFoundation);
/***/ }),
/* 1 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__foundation__ = __webpack_require__(0);
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
* Copyright 2016 Google Inc.
*
* 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.
*/
/**
* @template F
*/
var MDCComponent = function () {
_createClass(MDCComponent, null, [{
key: 'attachTo',
/**
* @param {!Element} root
* @return {!MDCComponent}
*/
value: function attachTo(root) {
// Subclasses which extend MDCBase should provide an attachTo() method that takes a root element and
// returns an instantiated component with its root set to that element. Also note that in the cases of
// subclasses, an explicit foundation class will not have to be passed in; it will simply be initialized
// from getDefaultFoundation().
return new MDCComponent(root, new __WEBPACK_IMPORTED_MODULE_0__foundation__["a" /* default */]());
}
/**
* @param {!Element} root
* @param {F=} foundation
* @param {...?} args
*/
}]);
function MDCComponent(root) {
var foundation = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined;
_classCallCheck(this, MDCComponent);
/** @protected {!Element} */
this.root_ = root;
for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
args[_key - 2] = arguments[_key];
}
this.initialize.apply(this, args);
// Note that we initialize foundation here and not within the constructor's default param so that
// this.root_ is defined and can be used within the foundation class.
/** @protected {!F} */
this.foundation_ = foundation === undefined ? this.getDefaultFoundation() : foundation;
this.foundation_.init();
this.initialSyncWithDOM();
}
_createClass(MDCComponent, [{
key: 'initialize',
value: function initialize() /* ...args */{}
// Subclasses can override this to do any additional setup work that would be considered part of a
// "constructor". Essentially, it is a hook into the parent constructor before the foundation is
// initialized. Any additional arguments besides root and foundation will be passed in here.
/**
* @return {!F} foundation
*/
}, {
key: 'getDefaultFoundation',
value: function getDefaultFoundation() {
// Subclasses must override this method to return a properly configured foundation class for the
// component.
throw new Error('Subclasses must override getDefaultFoundation to return a properly configured ' + 'foundation class');
}
}, {
key: 'initialSyncWithDOM',
value: function initialSyncWithDOM() {
// Subclasses should override this method if they need to perform work to synchronize with a host DOM
// object. An example of this would be a form control wrapper that needs to synchronize its internal state
// to some property or attribute of the host DOM. Please note: this is *not* the place to perform DOM
// reads/writes that would cause layout / paint, as this is called synchronously from within the constructor.
}
}, {
key: 'destroy',
value: function destroy() {
// Subclasses may implement this method to release any resources / deregister any listeners they have
// attached. An example of this might be deregistering a resize event from the window object.
this.foundation_.destroy();
}
/**
* Wrapper method to add an event listener to the component's root element. This is most useful when
* listening for custom events.
* @param {string} evtType
* @param {!Function} handler
*/
}, {
key: 'listen',
value: function listen(evtType, handler) {
this.root_.addEventListener(evtType, handler);
}
/**
* Wrapper method to remove an event listener to the component's root element. This is most useful when
* unlistening for custom events.
* @param {string} evtType
* @param {!Function} handler
*/
}, {
key: 'unlisten',
value: function unlisten(evtType, handler) {
this.root_.removeEventListener(evtType, handler);
}
/**
* Fires a cross-browser-compatible custom event from the component root of the given type,
* with the given data.
* @param {string} evtType
* @param {!Object} evtData
* @param {boolean=} shouldBubble
*/
}, {
key: 'emit',
value: function emit(evtType, evtData) {
var shouldBubble = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
var evt = void 0;
if (typeof CustomEvent === 'function') {
evt = new CustomEvent(evtType, {
detail: evtData,
bubbles: shouldBubble
});
} else {
evt = document.createEvent('CustomEvent');
evt.initCustomEvent(evtType, shouldBubble, false, evtData);
}
this.root_.dispatchEvent(evt);
}
}]);
return MDCComponent;
}();
/* harmony default export */ __webpack_exports__["a"] = (MDCComponent);
/***/ }),
/* 2 */,
/* 3 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
/* harmony export (immutable) */ __webpack_exports__["supportsCssVariables"] = supportsCssVariables;
/* harmony export (immutable) */ __webpack_exports__["applyPassive"] = applyPassive;
/* harmony export (immutable) */ __webpack_exports__["getMatchesProperty"] = getMatchesProperty;
/* harmony export (immutable) */ __webpack_exports__["getNormalizedEventCoords"] = getNormalizedEventCoords;
/**
* Copyright 2016 Google Inc. 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.
*/
/** @private {boolean|undefined} */
var supportsPassive_ = void 0;
/**
* @param {!Window} windowObj
* @return {boolean|undefined}
*/
function supportsCssVariables(windowObj) {
var supportsFunctionPresent = windowObj.CSS && typeof windowObj.CSS.supports === 'function';
if (!supportsFunctionPresent) {
return;
}
var explicitlySupportsCssVars = windowObj.CSS.supports('--css-vars', 'yes');
// See: https://bugs.webkit.org/show_bug.cgi?id=154669
// See: README section on Safari
var weAreFeatureDetectingSafari10plus = windowObj.CSS.supports('(--css-vars: yes)') && windowObj.CSS.supports('color', '#00000000');
return explicitlySupportsCssVars || weAreFeatureDetectingSafari10plus;
}
//
/**
* Determine whether the current browser supports passive event listeners, and if so, use them.
* @param {!Window=} globalObj
* @param {boolean=} forceRefresh
* @return {boolean|{passive: boolean}}
*/
function applyPassive() {
var globalObj = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : window;
var forceRefresh = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
if (supportsPassive_ === undefined || forceRefresh) {
var isSupported = false;
try {
globalObj.document.addEventListener('test', null, { get passive() {
isSupported = true;
} });
} catch (e) {}
supportsPassive_ = isSupported;
}
return supportsPassive_ ? { passive: true } : false;
}
/**
* @param {!Object} HTMLElementPrototype
* @return {!Array<string>}
*/
function getMatchesProperty(HTMLElementPrototype) {
return ['webkitMatchesSelector', 'msMatchesSelector', 'matches'].filter(function (p) {
return p in HTMLElementPrototype;
}).pop();
}
/**
* @param {!Event} ev
* @param {!{x: number, y: number}} pageOffset
* @param {!ClientRect} clientRect
* @return {!{x: number, y: number}}
*/
function getNormalizedEventCoords(ev, pageOffset, clientRect) {
var x = pageOffset.x,
y = pageOffset.y;
var documentX = x + clientRect.left;
var documentY = y + clientRect.top;
var normalizedX = void 0;
var normalizedY = void 0;
// Determine touch point relative to the ripple container.
if (ev.type === 'touchstart') {
normalizedX = ev.changedTouches[0].pageX - documentX;
normalizedY = ev.changedTouches[0].pageY - documentY;
} else {
normalizedX = ev.pageX - documentX;
normalizedY = ev.pageY - documentY;
}
return { x: normalizedX, y: normalizedY };
}
/***/ }),
/* 4 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
* Copyright 2016 Google Inc. 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.
*/
/* eslint no-unused-vars: [2, {"args": "none"}] */
/**
* Adapter for MDC Ripple. Provides an interface for managing
* - classes
* - dom
* - CSS variables
* - position
* - dimensions
* - scroll position
* - event handlers
* - unbounded, active and disabled states
*
* Additionally, provides type information for the adapter to the Closure
* compiler.
*
* Implement this adapter for your framework of choice to delegate updates to
* the component in your framework of choice. See architecture documentation
* for more details.
* https://github.com/material-components/material-components-web/blob/master/docs/architecture.md
*
* @record
*/
var MDCRippleAdapter = function () {
function MDCRippleAdapter() {
_classCallCheck(this, MDCRippleAdapter);
}
_createClass(MDCRippleAdapter, [{
key: "browserSupportsCssVars",
/** @return {boolean} */
value: function browserSupportsCssVars() {}
/** @return {boolean} */
}, {
key: "isUnbounded",
value: function isUnbounded() {}
/** @return {boolean} */
}, {
key: "isSurfaceActive",
value: function isSurfaceActive() {}
/** @return {boolean} */
}, {
key: "isSurfaceDisabled",
value: function isSurfaceDisabled() {}
/** @param {string} className */
}, {
key: "addClass",
value: function addClass(className) {}
/** @param {string} className */
}, {
key: "removeClass",
value: function removeClass(className) {}
/**
* @param {string} evtType
* @param {!Function} handler
*/
}, {
key: "registerInteractionHandler",
value: function registerInteractionHandler(evtType, handler) {}
/**
* @param {string} evtType
* @param {!Function} handler
*/
}, {
key: "deregisterInteractionHandler",
value: function deregisterInteractionHandler(evtType, handler) {}
/**
* @param {!Function} handler
*/
}, {
key: "registerResizeHandler",
value: function registerResizeHandler(handler) {}
/**
* @param {!Function} handler
*/
}, {
key: "deregisterResizeHandler",
value: function deregisterResizeHandler(handler) {}
/**
* @param {string} varName
* @param {?number|string} value
*/
}, {
key: "updateCssVariable",
value: function updateCssVariable(varName, value) {}
/** @return {!ClientRect} */
}, {
key: "computeBoundingRect",
value: function computeBoundingRect() {}
/** @return {{x: number, y: number}} */
}, {
key: "getWindowPageOffset",
value: function getWindowPageOffset() {}
}]);
return MDCRippleAdapter;
}();
/* unused harmony default export */ var _unused_webpack_default_export = (MDCRippleAdapter);
/***/ }),
/* 5 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MDCRipple", function() { return MDCRipple; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__material_base_component__ = __webpack_require__(1);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__adapter__ = __webpack_require__(4);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__foundation__ = __webpack_require__(6);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__util__ = __webpack_require__(3);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "MDCRippleFoundation", function() { return __WEBPACK_IMPORTED_MODULE_2__foundation__["a"]; });
/* harmony reexport (module object) */ __webpack_require__.d(__webpack_exports__, "util", function() { return __WEBPACK_IMPORTED_MODULE_3__util__; });
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
/**
* Copyright 2016 Google Inc. 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.
*/
/**
* @extends MDCComponent<!MDCRippleFoundation>
*/
var MDCRipple = function (_MDCComponent) {
_inherits(MDCRipple, _MDCComponent);
/** @param {...?} args */
function MDCRipple() {
var _ref;
_classCallCheck(this, MDCRipple);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
/** @type {boolean} */
var _this = _possibleConstructorReturn(this, (_ref = MDCRipple.__proto__ || Object.getPrototypeOf(MDCRipple)).call.apply(_ref, [this].concat(args)));
_this.disabled = false;
/** @private {boolean} */
_this.unbounded_;
return _this;
}
/**
* @param {!Element} root
* @param {{isUnbounded: (boolean|undefined)}=} options
* @return {!MDCRipple}
*/
_createClass(MDCRipple, [{
key: 'activate',
value: function activate() {
this.foundation_.activate();
}
}, {
key: 'deactivate',
value: function deactivate() {
this.foundation_.deactivate();
}
}, {
key: 'layout',
value: function layout() {
this.foundation_.layout();
}
/** @return {!MDCRippleFoundation} */
}, {
key: 'getDefaultFoundation',
value: function getDefaultFoundation() {
return new __WEBPACK_IMPORTED_MODULE_2__foundation__["a" /* default */](MDCRipple.createAdapter(this));
}
}, {
key: 'initialSyncWithDOM',
value: function initialSyncWithDOM() {
this.unbounded = 'mdcRippleIsUnbounded' in this.root_.dataset;
}
}, {
key: 'unbounded',
/** @return {boolean} */
get: function get() {
return this.unbounded_;
}
/** @param {boolean} unbounded */
,
set: function set(unbounded) {
var UNBOUNDED = __WEBPACK_IMPORTED_MODULE_2__foundation__["a" /* default */].cssClasses.UNBOUNDED;
this.unbounded_ = Boolean(unbounded);
if (this.unbounded_) {
this.root_.classList.add(UNBOUNDED);
} else {
this.root_.classList.remove(UNBOUNDED);
}
}
}], [{
key: 'attachTo',
value: function attachTo(root) {
var _ref2 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
_ref2$isUnbounded = _ref2.isUnbounded,
isUnbounded = _ref2$isUnbounded === undefined ? undefined : _ref2$isUnbounded;
var ripple = new MDCRipple(root);
// Only override unbounded behavior if option is explicitly specified
if (isUnbounded !== undefined) {
ripple.unbounded = /** @type {boolean} */isUnbounded;
}
return ripple;
}
/**
* @param {!RippleCapableSurface} instance
* @return {!MDCRippleAdapter}
*/
}, {
key: 'createAdapter',
value: function createAdapter(instance) {
var MATCHES = __WEBPACK_IMPORTED_MODULE_3__util__["getMatchesProperty"](HTMLElement.prototype);
return {
browserSupportsCssVars: function browserSupportsCssVars() {
return __WEBPACK_IMPORTED_MODULE_3__util__["supportsCssVariables"](window);
},
isUnbounded: function isUnbounded() {
return instance.unbounded;
},
isSurfaceActive: function isSurfaceActive() {
return instance.root_[MATCHES](':active');
},
isSurfaceDisabled: function isSurfaceDisabled() {
return instance.disabled;
},
addClass: function addClass(className) {
return instance.root_.classList.add(className);
},
removeClass: function removeClass(className) {
return instance.root_.classList.remove(className);
},
registerInteractionHandler: function registerInteractionHandler(evtType, handler) {
return instance.root_.addEventListener(evtType, handler, __WEBPACK_IMPORTED_MODULE_3__util__["applyPassive"]());
},
deregisterInteractionHandler: function deregisterInteractionHandler(evtType, handler) {
return instance.root_.removeEventListener(evtType, handler, __WEBPACK_IMPORTED_MODULE_3__util__["applyPassive"]());
},
registerResizeHandler: function registerResizeHandler(handler) {
return window.addEventListener('resize', handler);
},
deregisterResizeHandler: function deregisterResizeHandler(handler) {
return window.removeEventListener('resize', handler);
},
updateCssVariable: function updateCssVariable(varName, value) {
return instance.root_.style.setProperty(varName, value);
},
computeBoundingRect: function computeBoundingRect() {
return instance.root_.getBoundingClientRect();
},
getWindowPageOffset: function getWindowPageOffset() {
return { x: window.pageXOffset, y: window.pageYOffset };
}
};
}
}]);
return MDCRipple;
}(__WEBPACK_IMPORTED_MODULE_0__material_base_component__["a" /* default */]);
/**
* See Material Design spec for more details on when to use ripples.
* https://material.io/guidelines/motion/choreography.html#choreography-creation
* @record
*/
var RippleCapableSurface = function RippleCapableSurface() {
_classCallCheck(this, RippleCapableSurface);
};
/** @protected {!Element} */
RippleCapableSurface.prototype.root_;
/**
* Whether or not the ripple bleeds out of the bounds of the element.
* @type {boolean|undefined}
*/
RippleCapableSurface.prototype.unbounded;
/**
* Whether or not the ripple is attached to a disabled component.
* @type {boolean|undefined}
*/
RippleCapableSurface.prototype.disabled;
/***/ }),
/* 6 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__material_base_foundation__ = __webpack_require__(0);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__adapter__ = __webpack_require__(4);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__constants__ = __webpack_require__(7);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__util__ = __webpack_require__(3);
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
/**
* Copyright 2016 Google Inc. 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.
*/
/**
* @typedef {!{
* isActivated: (boolean|undefined),
* hasDeactivationUXRun: (boolean|undefined),
* wasActivatedByPointer: (boolean|undefined),
* wasElementMadeActive: (boolean|undefined),
* activationStartTime: (number|undefined),
* activationEvent: Event,
* isProgrammatic: (boolean|undefined)
* }}
*/
var ActivationStateType = void 0;
/**
* @typedef {!{
* activate: (string|undefined),
* deactivate: (string|undefined),
* focus: (string|undefined),
* blur: (string|undefined)
* }}
*/
var ListenerInfoType = void 0;
/**
* @typedef {!{
* activate: function(!Event),
* deactivate: function(!Event),
* focus: function(),
* blur: function()
* }}
*/
var ListenersType = void 0;
/**
* @typedef {!{
* x: number,
* y: number
* }}
*/
var PointType = void 0;
/**
* @enum {string}
*/
var DEACTIVATION_ACTIVATION_PAIRS = {
mouseup: 'mousedown',
pointerup: 'pointerdown',
touchend: 'touchstart',
keyup: 'keydown',
blur: 'focus'
};
/**
* @extends {MDCFoundation<!MDCRippleAdapter>}
*/
var MDCRippleFoundation = function (_MDCFoundation) {
_inherits(MDCRippleFoundation, _MDCFoundation);
_createClass(MDCRippleFoundation, [{
key: 'isSupported_',
/**
* We compute this property so that we are not querying information about the client
* until the point in time where the foundation requests it. This prevents scenarios where
* client-side feature-detection may happen too early, such as when components are rendered on the server
* and then initialized at mount time on the client.
* @return {boolean}
*/
get: function get() {
return this.adapter_.browserSupportsCssVars();
}
}], [{
key: 'cssClasses',
get: function get() {
return __WEBPACK_IMPORTED_MODULE_2__constants__["a" /* cssClasses */];
}
}, {
key: 'strings',
get: function get() {
return __WEBPACK_IMPORTED_MODULE_2__constants__["c" /* strings */];
}
}, {
key: 'numbers',
get: function get() {
return __WEBPACK_IMPORTED_MODULE_2__constants__["b" /* numbers */];
}
}, {
key: 'defaultAdapter',
get: function get() {
return {
browserSupportsCssVars: function browserSupportsCssVars() /* boolean - cached */{},
isUnbounded: function isUnbounded() /* boolean */{},
isSurfaceActive: function isSurfaceActive() /* boolean */{},
isSurfaceDisabled: function isSurfaceDisabled() /* boolean */{},
addClass: function addClass() /* className: string */{},
removeClass: function removeClass() /* className: string */{},
registerInteractionHandler: function registerInteractionHandler() /* evtType: string, handler: EventListener */{},
deregisterInteractionHandler: function deregisterInteractionHandler() /* evtType: string, handler: EventListener */{},
registerResizeHandler: function registerResizeHandler() /* handler: EventListener */{},
deregisterResizeHandler: function deregisterResizeHandler() /* handler: EventListener */{},
updateCssVariable: function updateCssVariable() /* varName: string, value: string */{},
computeBoundingRect: function computeBoundingRect() /* ClientRect */{},
getWindowPageOffset: function getWindowPageOffset() /* {x: number, y: number} */{}
};
}
}]);
function MDCRippleFoundation(adapter) {
_classCallCheck(this, MDCRippleFoundation);
/** @private {number} */
var _this = _possibleConstructorReturn(this, (MDCRippleFoundation.__proto__ || Object.getPrototypeOf(MDCRippleFoundation)).call(this, _extends(MDCRippleFoundation.defaultAdapter, adapter)));
_this.layoutFrame_ = 0;
/** @private {!ClientRect} */
_this.frame_ = /** @type {!ClientRect} */{ width: 0, height: 0 };
/** @private {!ActivationStateType} */
_this.activationState_ = _this.defaultActivationState_();
/** @private {number} */
_this.xfDuration_ = 0;
/** @private {number} */
_this.initialSize_ = 0;
/** @private {number} */
_this.maxRadius_ = 0;
/** @private {!Array<{ListenerInfoType}>} */
_this.listenerInfos_ = [{ activate: 'touchstart', deactivate: 'touchend' }, { activate: 'pointerdown', deactivate: 'pointerup' }, { activate: 'mousedown', deactivate: 'mouseup' }, { activate: 'keydown', deactivate: 'keyup' }, { focus: 'focus', blur: 'blur' }];
/** @private {!ListenersType} */
_this.listeners_ = {
activate: function activate(e) {
return _this.activate_(e);
},
deactivate: function deactivate(e) {
return _this.deactivate_(e);
},
focus: function focus() {
return requestAnimationFrame(function () {
return _this.adapter_.addClass(MDCRippleFoundation.cssClasses.BG_FOCUSED);
});
},
blur: function blur() {
return requestAnimationFrame(function () {
return _this.adapter_.removeClass(MDCRippleFoundation.cssClasses.BG_FOCUSED);
});
}
};
/** @private {!Function} */
_this.resizeHandler_ = function () {
return _this.layout();
};
/** @private {!{left: number, top:number}} */
_this.unboundedCoords_ = {
left: 0,
top: 0
};
/** @private {number} */
_this.fgScale_ = 0;
/** @private {number} */
_this.activationTimer_ = 0;
/** @private {number} */
_this.fgDeactivationRemovalTimer_ = 0;
/** @private {boolean} */
_this.activationAnimationHasEnded_ = false;
/** @private {!Function} */
_this.activationTimerCallback_ = function () {
_this.activationAnimationHasEnded_ = true;
_this.runDeactivationUXLogicIfReady_();
};
return _this;
}
/**
* @return {!ActivationStateType}
*/
_createClass(MDCRippleFoundation, [{
key: 'defaultActivationState_',
value: function defaultActivationState_() {
return {
isActivated: false,
hasDeactivationUXRun: false,
wasActivatedByPointer: false,
wasElementMadeActive: false,
activationStartTime: 0,
activationEvent: null,
isProgrammatic: false
};
}
}, {
key: 'init',
value: function init() {
var _this2 = this;
if (!this.isSupported_) {
return;
}
this.addEventListeners_();
var _MDCRippleFoundation$ = MDCRippleFoundation.cssClasses,
ROOT = _MDCRippleFoundation$.ROOT,
UNBOUNDED = _MDCRippleFoundation$.UNBOUNDED;
requestAnimationFrame(function () {
_this2.adapter_.addClass(ROOT);
if (_this2.adapter_.isUnbounded()) {
_this2.adapter_.addClass(UNBOUNDED);
}
_this2.layoutInternal_();
});
}
/** @private */
}, {
key: 'addEventListeners_',
value: function addEventListeners_() {
var _this3 = this;
this.listenerInfos_.forEach(function (info) {
Object.keys(info).forEach(function (k) {
_this3.adapter_.registerInteractionHandler(info[k], _this3.listeners_[k]);
});
});
this.adapter_.registerResizeHandler(this.resizeHandler_);
}
/**
* @param {Event} e
* @private
*/
}, {
key: 'activate_',
value: function activate_(e) {
var _this4 = this;
if (this.adapter_.isSurfaceDisabled()) {
return;
}
var activationState = this.activationState_;
if (activationState.isActivated) {
return;
}
activationState.isActivated = true;
activationState.isProgrammatic = e === null;
activationState.activationEvent = e;
activationState.wasActivatedByPointer = activationState.isProgrammatic ? false : e.type === 'mousedown' || e.type === 'touchstart' || e.type === 'pointerdown';
activationState.activationStartTime = Date.now();
requestAnimationFrame(function () {
// This needs to be wrapped in an rAF call b/c web browsers
// report active states inconsistently when they're called within
// event handling code:
// - https://bugs.chromium.org/p/chromium/issues/detail?id=635971
// - https://bugzilla.mozilla.org/show_bug.cgi?id=1293741
activationState.wasElementMadeActive = e && e.type === 'keydown' ? _this4.adapter_.isSurfaceActive() : true;
if (activationState.wasElementMadeActive) {
_this4.animateActivation_();
} else {
// Reset activation state immediately if element was not made active.
_this4.activationState_ = _this4.defaultActivationState_();
}
});
}
}, {
key: 'activate',
value: function activate() {
this.activate_(null);
}
/** @private */
}, {
key: 'animateActivation_',
value: function animateActivation_() {
var _this5 = this;
var _MDCRippleFoundation$2 = MDCRippleFoundation.strings,
VAR_FG_TRANSLATE_START = _MDCRippleFoundation$2.VAR_FG_TRANSLATE_START,
VAR_FG_TRANSLATE_END = _MDCRippleFoundation$2.VAR_FG_TRANSLATE_END;
var _MDCRippleFoundation$3 = MDCRippleFoundation.cssClasses,
BG_ACTIVE_FILL = _MDCRippleFoundation$3.BG_ACTIVE_FILL,
FG_DEACTIVATION = _MDCRippleFoundation$3.FG_DEACTIVATION,
FG_ACTIVATION = _MDCRippleFoundation$3.FG_ACTIVATION;
var DEACTIVATION_TIMEOUT_MS = MDCRippleFoundation.numbers.DEACTIVATION_TIMEOUT_MS;
var translateStart = '';
var translateEnd = '';
if (!this.adapter_.isUnbounded()) {
var _getFgTranslationCoor = this.getFgTranslationCoordinates_(),
startPoint = _getFgTranslationCoor.startPoint,
endPoint = _getFgTranslationCoor.endPoint;
translateStart = startPoint.x + 'px, ' + startPoint.y + 'px';
translateEnd = endPoint.x + 'px, ' + endPoint.y + 'px';
}
this.adapter_.updateCssVariable(VAR_FG_TRANSLATE_START, translateStart);
this.adapter_.updateCssVariable(VAR_FG_TRANSLATE_END, translateEnd);
// Cancel any ongoing activation/deactivation animations
clearTimeout(this.activationTimer_);
clearTimeout(this.fgDeactivationRemovalTimer_);
this.rmBoundedActivationClasses_();
this.adapter_.removeClass(FG_DEACTIVATION);
// Force layout in order to re-trigger the animation.
this.adapter_.computeBoundingRect();
this.adapter_.addClass(BG_ACTIVE_FILL);
this.adapter_.addClass(FG_ACTIVATION);
this.activationTimer_ = setTimeout(function () {
return _this5.activationTimerCallback_();
}, DEACTIVATION_TIMEOUT_MS);
}
/**
* @private
* @return {{startPoint: PointType, endPoint: PointType}}
*/
}, {
key: 'getFgTranslationCoordinates_',
value: function getFgTranslationCoordinates_() {
var activationState = this.activationState_;
var activationEvent = activationState.activationEvent,
wasActivatedByPointer = activationState.wasActivatedByPointer;
var startPoint = void 0;
if (wasActivatedByPointer) {
startPoint = __WEBPACK_IMPORTED_MODULE_3__util__["getNormalizedEventCoords"](
/** @type {!Event} */activationEvent, this.adapter_.getWindowPageOffset(), this.adapter_.computeBoundingRect());
} else {
startPoint = {
x: this.frame_.width / 2,
y: this.frame_.height / 2
};
}
// Center the element around the start point.
startPoint = {
x: startPoint.x - this.initialSize_ / 2,
y: startPoint.y - this.initialSize_ / 2
};
var endPoint = {
x: this.frame_.width / 2 - this.initialSize_ / 2,
y: this.frame_.height / 2 - this.initialSize_ / 2
};
return { startPoint: startPoint, endPoint: endPoint };
}
/** @private */
}, {
key: 'runDeactivationUXLogicIfReady_',
value: function runDeactivationUXLogicIfReady_() {
var _this6 = this;
var FG_DEACTIVATION = MDCRippleFoundation.cssClasses.FG_DEACTIVATION;
var _activationState_ = this.activationState_,
hasDeactivationUXRun = _activationState_.hasDeactivationUXRun,
isActivated = _activationState_.isActivated;
var activationHasEnded = hasDeactivationUXRun || !isActivated;
if (activationHasEnded && this.activationAnimationHasEnded_) {
this.rmBoundedActivationClasses_();
this.adapter_.addClass(FG_DEACTIVATION);
this.fgDeactivationRemovalTimer_ = setTimeout(function () {
_this6.adapter_.removeClass(FG_DEACTIVATION);
}, __WEBPACK_IMPORTED_MODULE_2__constants__["b" /* numbers */].FG_DEACTIVATION_MS);
}
}
/** @private */
}, {
key: 'rmBoundedActivationClasses_',
value: function rmBoundedActivationClasses_() {
var _MDCRippleFoundation$4 = MDCRippleFoundation.cssClasses,
BG_ACTIVE_FILL = _MDCRippleFoundation$4.BG_ACTIVE_FILL,
FG_ACTIVATION = _MDCRippleFoundation$4.FG_ACTIVATION;
this.adapter_.removeClass(BG_ACTIVE_FILL);
this.adapter_.removeClass(FG_ACTIVATION);
this.activationAnimationHasEnded_ = false;
this.adapter_.computeBoundingRect();
}
/**
* @param {Event} e
* @private
*/
}, {
key: 'deactivate_',
value: function deactivate_(e) {
var _this7 = this;
var activationState = this.activationState_;
// This can happen in scenarios such as when you have a keyup event that blurs the element.
if (!activationState.isActivated) {
return;
}
// Programmatic deactivation.
if (activationState.isProgrammatic) {
var evtObject = null;
var _state = /** @type {!ActivationStateType} */_extends({}, activationState);
requestAnimationFrame(function () {
return _this7.animateDeactivation_(evtObject, _state);
});
this.activationState_ = this.defaultActivationState_();
return;
}
var actualActivationType = DEACTIVATION_ACTIVATION_PAIRS[e.type];
var expectedActivationType = activationState.activationEvent.type;
// NOTE: Pointer events are tricky - https://patrickhlauke.github.io/touch/tests/results/
// Essentially, what we need to do here is decouple the deactivation UX from the actual
// deactivation state itself. This way, touch/pointer events in sequence do not trample one
// another.
var needsDeactivationUX = actualActivationType === expectedActivationType;
var needsActualDeactivation = needsDeactivationUX;
if (activationState.wasActivatedByPointer) {
needsActualDeactivation = e.type === 'mouseup';
}
var state = /** @type {!ActivationStateType} */_extends({}, activationState);
requestAnimationFrame(function () {
if (needsDeactivationUX) {
_this7.activationState_.hasDeactivationUXRun = true;
_this7.animateDeactivation_(e, state);
}
if (needsActualDeactivation) {
_this7.activationState_ = _this7.defaultActivationState_();
}
});
}
}, {
key: 'deactivate',
value: function deactivate() {
this.deactivate_(null);
}
/**
* @param {Event} e
* @param {!ActivationStateType} options
* @private
*/
}, {
key: 'animateDeactivation_',
value: function animateDeactivation_(e, _ref) {
var wasActivatedByPointer = _ref.wasActivatedByPointer,
wasElementMadeActive = _ref.wasElementMadeActive;
var BG_FOCUSED = MDCRippleFoundation.cssClasses.BG_FOCUSED;
if (wasActivatedByPointer || wasElementMadeActive) {
// Remove class left over by element being focused
this.adapter_.removeClass(BG_FOCUSED);
this.runDeactivationUXLogicIfReady_();
}
}
}, {
key: 'destroy',
value: function destroy() {
var _this8 = this;
if (!this.isSupported_) {
return;
}
this.removeEventListeners_();
var _MDCRippleFoundation$5 = MDCRippleFoundation.cssClasses,
ROOT = _MDCRippleFoundation$5.ROOT,
UNBOUNDED = _MDCRippleFoundation$5.UNBOUNDED;
requestAnimationFrame(function () {
_this8.adapter_.removeClass(ROOT);
_this8.adapter_.removeClass(UNBOUNDED);
_this8.removeCssVars_();
});
}
/** @private */
}, {
key: 'removeEventListeners_',
value: function removeEventListeners_() {
var _this9 = this;
this.listenerInfos_.forEach(function (info) {
Object.keys(info).forEach(function (k) {
_this9.adapter_.deregisterInteractionHandler(info[k], _this9.listeners_[k]);
});
});
this.adapter_.deregisterResizeHandler(this.resizeHandler_);
}
/** @private */
}, {
key: 'removeCssVars_',
value: function removeCssVars_() {
var _this10 = this;
var strings = MDCRippleFoundation.strings;
Object.keys(strings).forEach(function (k) {
if (k.indexOf('VAR_') === 0) {
_this10.adapter_.updateCssVariable(strings[k], null);
}
});
}
}, {
key: 'layout',
value: function layout() {
var _this11 = this;
if (this.layoutFrame_) {
cancelAnimationFrame(this.layoutFrame_);
}
this.layoutFrame_ = requestAnimationFrame(function () {
_this11.layoutInternal_();
_this11.layoutFrame_ = 0;
});
}
/** @private */
}, {
key: 'layoutInternal_',
value: function layoutInternal_() {
this.frame_ = this.adapter_.computeBoundingRect();
var maxDim = Math.max(this.frame_.height, this.frame_.width);
var surfaceDiameter = Math.sqrt(Math.pow(this.frame_.width, 2) + Math.pow(this.frame_.height, 2));
// 60% of the largest dimension of the surface
this.initialSize_ = maxDim * MDCRippleFoundation.numbers.INITIAL_ORIGIN_SCALE;
// Diameter of the surface + 10px
this.maxRadius_ = surfaceDiameter + MDCRippleFoundation.numbers.PADDING;
this.fgScale_ = this.maxRadius_ / this.initialSize_;
this.xfDuration_ = 1000 * Math.sqrt(this.maxRadius_ / 1024);
this.updateLayoutCssVars_();
}
/** @private */
}, {
key: 'updateLayoutCssVars_',
value: function updateLayoutCssVars_() {
var _MDCRippleFoundation$6 = MDCRippleFoundation.strings,
VAR_SURFACE_WIDTH = _MDCRippleFoundation$6.VAR_SURFACE_WIDTH,
VAR_SURFACE_HEIGHT = _MDCRippleFoundation$6.VAR_SURFACE_HEIGHT,
VAR_FG_SIZE = _MDCRippleFoundation$6.VAR_FG_SIZE,
VAR_LEFT = _MDCRippleFoundation$6.VAR_LEFT,
VAR_TOP = _MDCRippleFoundation$6.VAR_TOP,
VAR_FG_SCALE = _MDCRippleFoundation$6.VAR_FG_SCALE;
this.adapter_.updateCssVariable(VAR_SURFACE_WIDTH, this.frame_.width + 'px');
this.adapter_.updateCssVariable(VAR_SURFACE_HEIGHT, this.frame_.height + 'px');
this.adapter_.updateCssVariable(VAR_FG_SIZE, this.initialSize_ + 'px');
this.adapter_.updateCssVariable(VAR_FG_SCALE, this.fgScale_);
if (this.adapter_.isUnbounded()) {
this.unboundedCoords_ = {
left: Math.round(this.frame_.width / 2 - this.initialSize_ / 2),
top: Math.round(this.frame_.height / 2 - this.initialSize_ / 2)
};
this.adapter_.updateCssVariable(VAR_LEFT, this.unboundedCoords_.left + 'px');
this.adapter_.updateCssVariable(VAR_TOP, this.unboundedCoords_.top + 'px');
}
}
}]);
return MDCRippleFoundation;
}(__WEBPACK_IMPORTED_MODULE_0__material_base_foundation__["a" /* default */]);
/* harmony default export */ __webpack_exports__["a"] = (MDCRippleFoundation);
/***/ }),
/* 7 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return cssClasses; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return strings; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return numbers; });
/**
* Copyright 2016 Google Inc. 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.
*/
var cssClasses = {
// Ripple is a special case where the "root" component is really a "mixin" of sorts,
// given that it's an 'upgrade' to an existing component. That being said it is the root
// CSS class that all other CSS classes derive from.
ROOT: 'mdc-ripple-upgraded',
UNBOUNDED: 'mdc-ripple-upgraded--unbounded',
BG_FOCUSED: 'mdc-ripple-upgraded--background-focused',
BG_ACTIVE_FILL: 'mdc-ripple-upgraded--background-active-fill',
FG_ACTIVATION: 'mdc-ripple-upgraded--foreground-activation',
FG_DEACTIVATION: 'mdc-ripple-upgraded--foreground-deactivation'
};
var strings = {
VAR_SURFACE_WIDTH: '--mdc-ripple-surface-width',
VAR_SURFACE_HEIGHT: '--mdc-ripple-surface-height',
VAR_FG_SIZE: '--mdc-ripple-fg-size',
VAR_LEFT: '--mdc-ripple-left',
VAR_TOP: '--mdc-ripple-top',
VAR_FG_SCALE: '--mdc-ripple-fg-scale',
VAR_FG_TRANSLATE_START: '--mdc-ripple-fg-translate-start',
VAR_FG_TRANSLATE_END: '--mdc-ripple-fg-translate-end'
};
var numbers = {
PADDING: 10,
INITIAL_ORIGIN_SCALE: 0.6,
DEACTIVATION_TIMEOUT_MS: 300,
FG_DEACTIVATION_MS: 83
};
/***/ }),
/* 8 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "transformStyleProperties", function() { return transformStyleProperties; });
/* harmony export (immutable) */ __webpack_exports__["getCorrectEventName"] = getCorrectEventName;
/* harmony export (immutable) */ __webpack_exports__["getCorrectPropertyName"] = getCorrectPropertyName;
/**
* Copyright 2016 Google Inc. 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.
*/
/**
* @typedef {{
* noPrefix: string,
* webkitPrefix: string
* }}
*/
var VendorPropertyMapType = void 0;
/** @const {Object<string, !VendorPropertyMapType>} */
var eventTypeMap = {
'animationstart': {
noPrefix: 'animationstart',
webkitPrefix: 'webkitAnimationStart',
styleProperty: 'animation'
},
'animationend': {
noPrefix: 'animationend',
webkitPrefix: 'webkitAnimationEnd',
styleProperty: 'animation'
},
'animationiteration': {
noPrefix: 'animationiteration',
webkitPrefix: 'webkitAnimationIteration',
styleProperty: 'animation'
},
'transitionend': {
noPrefix: 'transitionend',
webkitPrefix: 'webkitTransitionEnd',
styleProperty: 'transition'
}
};
/** @const {Object<string, !VendorPropertyMapType>} */
var cssPropertyMap = {
'animation': {
noPrefix: 'animation',
webkitPrefix: '-webkit-animation'
},
'transform': {
noPrefix: 'transform',
webkitPrefix: '-webkit-transform'
},
'transition': {
noPrefix: 'transition',
webkitPrefix: '-webkit-transition'
}
};
/**
* @param {!Object} windowObj
* @return {boolean}
*/
function hasProperShape(windowObj) {
return windowObj['document'] !== undefined && typeof windowObj['document']['createElement'] === 'function';
}
/**
* @param {string} eventType
* @return {boolean}
*/
function eventFoundInMaps(eventType) {
return eventType in eventTypeMap || eventType in cssPropertyMap;
}
/**
* @param {string} eventType
* @param {!Object<string, !VendorPropertyMapType>} map
* @param {!Element} el
* @return {string}
*/
function getJavaScriptEventName(eventType, map, el) {
return map[eventType].styleProperty in el.style ? map[eventType].noPrefix : map[eventType].webkitPrefix;
}
/**
* Helper function to determine browser prefix for CSS3 animation events
* and property names.
* @param {!Object} windowObj
* @param {string} eventType
* @return {string}
*/
function getAnimationName(windowObj, eventType) {
if (!hasProperShape(windowObj) || !eventFoundInMaps(eventType)) {
return eventType;
}
var map = /** @type {!Object<string, !VendorPropertyMapType>} */eventType in eventTypeMap ? eventTypeMap : cssPropertyMap;
var el = windowObj['document']['createElement']('div');
var eventName = '';
if (map === eventTypeMap) {
eventName = getJavaScriptEventName(eventType, map, el);
} else {
eventName = map[eventType].noPrefix in el.style ? map[eventType].noPrefix : map[eventType].webkitPrefix;
}
return eventName;
}
// Public functions to access getAnimationName() for JavaScript events or CSS
// property names.
var transformStyleProperties = ['transform', 'WebkitTransform', 'MozTransform', 'OTransform', 'MSTransform'];
/**
* @param {!Object} windowObj
* @param {string} eventType
* @return {string}
*/
function getCorrectEventName(windowObj, eventType) {
return getAnimationName(windowObj, eventType);
}
/**
* @param {!Object} windowObj
* @param {string} eventType
* @return {string}
*/
function getCorrectPropertyName(windowObj, eventType) {
return getAnimationName(windowObj, eventType);
}
/***/ }),
/* 9 */,
/* 10 */,
/* 11 */,
/* 12 */,
/* 13 */,
/* 14 */,
/* 15 */,
/* 16 */,
/* 17 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* unused harmony export InputElementState */
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
* Copyright 2016 Google Inc. 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.
*/
/* eslint no-unused-vars: [2, {"args": "none"}] */
/**
* Adapter for MDC Checkbox. Provides an interface for managing
* - classes
* - dom
* - event handlers
*
* Additionally, provides type information for the adapter to the Closure
* compiler.
*
* Implement this adapter for your framework of choice to delegate updates to
* the component in your framework of choice. See architecture documentation
* for more details.
* https://github.com/material-components/material-components-web/blob/master/docs/architecture.md
*
* @record
*/
var MDCCheckboxAdapter = function () {
function MDCCheckboxAdapter() {
_classCallCheck(this, MDCCheckboxAdapter);
}
_createClass(MDCCheckboxAdapter, [{
key: "addClass",
/** @param {string} className */
value: function addClass(className) {}
/** @param {string} className */
}, {
key: "removeClass",
value: function removeClass(className) {}
/** @param {!EventListener} handler */
}, {
key: "registerAnimationEndHandler",
value: function registerAnimationEndHandler(handler) {}
/** @param {!EventListener} handler */
}, {
key: "deregisterAnimationEndHandler",
value: function deregisterAnimationEndHandler(handler) {}
/** @param {!EventListener} handler */
}, {
key: "registerChangeHandler",
value: function registerChangeHandler(handler) {}
/** @param {!EventListener} handler */
}, {
key: "deregisterChangeHandler",
value: function deregisterChangeHandler(handler) {}
/** @return {InputElementState} */
}, {
key: "getNativeControl",
value: function getNativeControl() {}
}, {
key: "forceLayout",
value: function forceLayout() {}
/** @return {boolean} */
}, {
key: "isAttachedToDOM",
value: function isAttachedToDOM() {}
}]);
return MDCCheckboxAdapter;
}();
/**
* @typedef {!{
* checked: boolean,
* indeterminate: boolean,
* disabled: boolean,
* value: ?string
* }}
*/
/* unused harmony default export */ var _unused_webpack_default_export = (MDCCheckboxAdapter);
var InputElementState = void 0;
/***/ }),
/* 18 */,
/* 19 */,
/* 20 */,
/* 21 */,
/* 22 */,
/* 23 */,
/* 24 */,
/* 25 */,
/* 26 */,
/* 27 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(28);
/***/ }),
/* 28 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MDCCheckbox", function() { return MDCCheckbox; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__material_animation__ = __webpack_require__(8);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__material_base_component__ = __webpack_require__(1);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__adapter__ = __webpack_require__(17);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__foundation__ = __webpack_require__(29);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__material_ripple__ = __webpack_require__(5);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__material_ripple_util__ = __webpack_require__(3);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "MDCCheckboxFoundation", function() { return __WEBPACK_IMPORTED_MODULE_3__foundation__["a"]; });
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
/**
* Copyright 2016 Google Inc. 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.
*/
/* eslint-disable no-unused-vars */
/* eslint-enable no-unused-vars */
/**
* @extends MDCComponent<!MDCCheckboxFoundation>
*/
var MDCCheckbox = function (_MDCComponent) {
_inherits(MDCCheckbox, _MDCComponent);
_createClass(MDCCheckbox, [{
key: 'nativeCb_',
/**
* @return {InputElementState|undefined}
* @private
*/
get: function get() {
var NATIVE_CONTROL_SELECTOR = __WEBPACK_IMPORTED_MODULE_3__foundation__["a" /* default */].strings.NATIVE_CONTROL_SELECTOR;
var cbEl = /** @type {InputElementState|undefined} */this.root_.querySelector(NATIVE_CONTROL_SELECTOR);
return cbEl;
}
}], [{
key: 'attachTo',
value: function attachTo(root) {
return new MDCCheckbox(root);
}
}]);
function MDCCheckbox() {
var _ref;
_classCallCheck(this, MDCCheckbox);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
/** @private {!MDCRipple} */
var _this = _possibleConstructorReturn(this, (_ref = MDCCheckbox.__proto__ || Object.getPrototypeOf(MDCCheckbox)).call.apply(_ref, [this].concat(args)));
_this.ripple_ = _this.initRipple_();
return _this;
}
/**
* @return {!MDCRipple}
* @private
*/
_createClass(MDCCheckbox, [{
key: 'initRipple_',
value: function initRipple_() {
var _this2 = this;
var MATCHES = __WEBPACK_IMPORTED_MODULE_5__material_ripple_util__["getMatchesProperty"](HTMLElement.prototype);
var adapter = _extends(__WEBPACK_IMPORTED_MODULE_4__material_ripple__["MDCRipple"].createAdapter(this), {
isUnbounded: function isUnbounded() {
return true;
},
isSurfaceActive: function isSurfaceActive() {
return _this2.nativeCb_[MATCHES](':active');
},
registerInteractionHandler: function registerInteractionHandler(type, handler) {
return _this2.nativeCb_.addEventListener(type, handler);
},
deregisterInteractionHandler: function deregisterInteractionHandler(type, handler) {
return _this2.nativeCb_.removeEventListener(type, handler);
},
computeBoundingRect: function computeBoundingRect() {
var _root_$getBoundingCli = _this2.root_.getBoundingClientRect(),
left = _root_$getBoundingCli.left,
top = _root_$getBoundingCli.top;
var DIM = 40;
return {
top: top,
left: left,
right: left + DIM,
bottom: top + DIM,
width: DIM,
height: DIM
};
}
});
var foundation = new __WEBPACK_IMPORTED_MODULE_4__material_ripple__["MDCRippleFoundation"](adapter);
return new __WEBPACK_IMPORTED_MODULE_4__material_ripple__["MDCRipple"](this.root_, foundation);
}
/** @return {!MDCCheckboxFoundation} */
}, {
key: 'getDefaultFoundation',
value: function getDefaultFoundation() {
var _this3 = this;
return new __WEBPACK_IMPORTED_MODULE_3__foundation__["a" /* default */]({
addClass: function addClass(className) {
return _this3.root_.classList.add(className);
},
removeClass: function removeClass(className) {
return _this3.root_.classList.remove(className);
},
registerAnimationEndHandler: function registerAnimationEndHandler(handler) {
return _this3.root_.addEventListener(__WEBPACK_IMPORTED_MODULE_0__material_animation__["getCorrectEventName"](window, 'animationend'), handler);
},
deregisterAnimationEndHandler: function deregisterAnimationEndHandler(handler) {
return _this3.root_.removeEventListener(__WEBPACK_IMPORTED_MODULE_0__material_animation__["getCorrectEventName"](window, 'animationend'), handler);
},
registerChangeHandler: function registerChangeHandler(handler) {
return _this3.nativeCb_.addEventListener('change', handler);
},
deregisterChangeHandler: function deregisterChangeHandler(handler) {
return _this3.nativeCb_.removeEventListener('change', handler);
},
getNativeControl: function getNativeControl() {
return _this3.nativeCb_;
},
forceLayout: function forceLayout() {
return _this3.root_.offsetWidth;
},
isAttachedToDOM: function isAttachedToDOM() {
return Boolean(_this3.root_.parentNode);
}
});
}
/** @return {!MDCRipple} */
}, {
key: 'destroy',
value: function destroy() {
this.ripple_.destroy();
_get(MDCCheckbox.prototype.__proto__ || Object.getPrototypeOf(MDCCheckbox.prototype), 'destroy', this).call(this);
}
}, {
key: 'ripple',
get: function get() {
return this.ripple_;
}
/** @return {boolean} */
}, {
key: 'checked',
get: function get() {
return this.foundation_.isChecked();
}
/** @param {boolean} checked */
,
set: function set(checked) {
this.foundation_.setChecked(checked);
}
/** @return {boolean} */
}, {
key: 'indeterminate',
get: function get() {
return this.foundation_.isIndeterminate();
}
/** @param {boolean} indeterminate */
,
set: function set(indeterminate) {
this.foundation_.setIndeterminate(indeterminate);
}
/** @return {boolean} */
}, {
key: 'disabled',
get: function get() {
return this.foundation_.isDisabled();
}
/** @param {boolean} disabled */
,
set: function set(disabled) {
this.foundation_.setDisabled(disabled);
}
/** @return {?string} */
}, {
key: 'value',
get: function get() {
return this.foundation_.getValue();
}
/** @param {?string} value */
,
set: function set(value) {
this.foundation_.setValue(value);
}
}]);
return MDCCheckbox;
}(__WEBPACK_IMPORTED_MODULE_1__material_base_component__["a" /* default */]);
/***/ }),
/* 29 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__material_base_foundation__ = __webpack_require__(0);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__adapter__ = __webpack_require__(17);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__constants__ = __webpack_require__(30);
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
/**
* Copyright 2016 Google Inc. 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.
*/
/* eslint-disable no-unused-vars */
/* eslint-enable no-unused-vars */
/** @const {!Array<string>} */
var CB_PROTO_PROPS = ['checked', 'indeterminate'];
/**
* @extends {MDCFoundation<!MDCCheckboxAdapter>}
*/
var MDCCheckboxFoundation = function (_MDCFoundation) {
_inherits(MDCCheckboxFoundation, _MDCFoundation);
_createClass(MDCCheckboxFoundation, null, [{
key: 'cssClasses',
get: function get() {
return __WEBPACK_IMPORTED_MODULE_2__constants__["a" /* cssClasses */];
}
}, {
key: 'strings',
get: function get() {
return __WEBPACK_IMPORTED_MODULE_2__constants__["c" /* strings */];
}
}, {
key: 'numbers',
get: function get() {
return __WEBPACK_IMPORTED_MODULE_2__constants__["b" /* numbers */];
}
}, {
key: 'defaultAdapter',
get: function get() {
return {
addClass: function addClass() /* className: string */{},
removeClass: function removeClass() /* className: string */{},
registerAnimationEndHandler: function registerAnimationEndHandler() /* handler: EventListener */{},
deregisterAnimationEndHandler: function deregisterAnimationEndHandler() /* handler: EventListener */{},
registerChangeHandler: function registerChangeHandler() /* handler: EventListener */{},
deregisterChangeHandler: function deregisterChangeHandler() /* handler: EventListener */{},
getNativeControl: function getNativeControl() /* InputElementState */{},
forceLayout: function forceLayout() {},
isAttachedToDOM: function isAttachedToDOM() /* boolean */{}
};
}
}]);
function MDCCheckboxFoundation(adapter) {
_classCallCheck(this, MDCCheckboxFoundation);
/** @private {string} */
var _this = _possibleConstructorReturn(this, (MDCCheckboxFoundation.__proto__ || Object.getPrototypeOf(MDCCheckboxFoundation)).call(this, _extends(MDCCheckboxFoundation.defaultAdapter, adapter)));
_this.currentCheckState_ = __WEBPACK_IMPORTED_MODULE_2__constants__["c" /* strings */].TRANSITION_STATE_INIT;
/** @private {string} */
_this.currentAnimationClass_ = '';
/** @private {number} */
_this.animEndLatchTimer_ = 0;
_this.animEndHandler_ = /** @private {!EventListener} */function () {
clearTimeout(_this.animEndLatchTimer_);
_this.animEndLatchTimer_ = setTimeout(function () {
_this.adapter_.removeClass(_this.currentAnimationClass_);
_this.adapter_.deregisterAnimationEndHandler(_this.animEndHandler_);
}, __WEBPACK_IMPORTED_MODULE_2__constants__["b" /* numbers */].ANIM_END_LATCH_MS);
};
_this.changeHandler_ = /** @private {!EventListener} */function () {
return _this.transitionCheckState_();
};
return _this;
}
_createClass(MDCCheckboxFoundation, [{
key: 'init',
value: function init() {
this.adapter_.addClass(__WEBPACK_IMPORTED_MODULE_2__constants__["a" /* cssClasses */].UPGRADED);
this.adapter_.registerChangeHandler(this.changeHandler_);
this.installPropertyChangeHooks_();
}
}, {
key: 'destroy',
value: function destroy() {
this.adapter_.deregisterChangeHandler(this.changeHandler_);
this.uninstallPropertyChangeHooks_();
}
/** @return {boolean} */
}, {
key: 'isChecked',
value: function isChecked() {
return this.getNativeControl_().checked;
}
/** @param {boolean} checked */
}, {
key: 'setChecked',
value: function setChecked(checked) {
this.getNativeControl_().checked = checked;
}
/** @return {boolean} */
}, {
key: 'isIndeterminate',
value: function isIndeterminate() {
return this.getNativeControl_().indeterminate;
}
/** @param {boolean} indeterminate */
}, {
key: 'setIndeterminate',
value: function setIndeterminate(indeterminate) {
this.getNativeControl_().indeterminate = indeterminate;
}
/** @return {boolean} */
}, {
key: 'isDisabled',
value: function isDisabled() {
return this.getNativeControl_().disabled;
}
/** @param {boolean} disabled */
}, {
key: 'setDisabled',
value: function setDisabled(disabled) {
this.getNativeControl_().disabled = disabled;
if (disabled) {
this.adapter_.addClass(__WEBPACK_IMPORTED_MODULE_2__constants__["a" /* cssClasses */].DISABLED);
} else {
this.adapter_.removeClass(__WEBPACK_IMPORTED_MODULE_2__constants__["a" /* cssClasses */].DISABLED);
}
}
/** @return {?string} */
}, {
key: 'getValue',
value: function getValue() {
return this.getNativeControl_().value;
}
/** @param {?string} value */
}, {
key: 'setValue',
value: function setValue(value) {
this.getNativeControl_().value = value;
}
/** @private */
}, {
key: 'installPropertyChangeHooks_',
value: function installPropertyChangeHooks_() {
var _this2 = this;
var nativeCb = this.getNativeControl_();
var cbProto = Object.getPrototypeOf(nativeCb);
CB_PROTO_PROPS.forEach(function (controlState) {
var desc = Object.getOwnPropertyDescriptor(cbProto, controlState);
// We have to check for this descriptor, since some browsers (Safari) don't support its return.
// See: https://bugs.webkit.org/show_bug.cgi?id=49739
if (validDescriptor(desc)) {
var nativeCbDesc = /** @type {!ObjectPropertyDescriptor} */{
get: desc.get,
set: function set(state) {
desc.set.call(nativeCb, state);
_this2.transitionCheckState_();
},
configurable: desc.configurable,
enumerable: desc.enumerable
};
Object.defineProperty(nativeCb, controlState, nativeCbDesc);
}
});
}
/** @private */
}, {
key: 'uninstallPropertyChangeHooks_',
value: function uninstallPropertyChangeHooks_() {
var nativeCb = this.getNativeControl_();
var cbProto = Object.getPrototypeOf(nativeCb);
CB_PROTO_PROPS.forEach(function (controlState) {
var desc = /** @type {!ObjectPropertyDescriptor} */Object.getOwnPropertyDescriptor(cbProto, controlState);
if (validDescriptor(desc)) {
Object.defineProperty(nativeCb, controlState, desc);
}
});
}
/** @private */
}, {
key: 'transitionCheckState_',
value: function transitionCheckState_() {
var nativeCb = this.adapter_.getNativeControl();
if (!nativeCb) {
return;
}
var oldState = this.currentCheckState_;
var newState = this.determineCheckState_(nativeCb);
if (oldState === newState) {
return;
}
// Check to ensure that there isn't a previously existing animation class, in case for example
// the user interacted with the checkbox before the animation was finished.
if (this.currentAnimationClass_.length > 0) {
clearTimeout(this.animEndLatchTimer_);
this.adapter_.forceLayout();
this.adapter_.removeClass(this.currentAnimationClass_);
}
this.currentAnimationClass_ = this.getTransitionAnimationClass_(oldState, newState);
this.currentCheckState_ = newState;
// Check for parentNode so that animations are only run when the element is attached
// to the DOM.
if (this.adapter_.isAttachedToDOM() && this.currentAnimationClass_.length > 0) {
this.adapter_.addClass(this.currentAnimationClass_);
this.adapter_.registerAnimationEndHandler(this.animEndHandler_);
}
}
/**
* @param {!InputElementState} nativeCb
* @return {string}
* @private
*/
}, {
key: 'determineCheckState_',
value: function determineCheckState_(nativeCb) {
var TRANSITION_STATE_INDETERMINATE = __WEBPACK_IMPORTED_MODULE_2__constants__["c" /* strings */].TRANSITION_STATE_INDETERMINATE,
TRANSITION_STATE_CHECKED = __WEBPACK_IMPORTED_MODULE_2__constants__["c" /* strings */].TRANSITION_STATE_CHECKED,
TRANSITION_STATE_UNCHECKED = __WEBPACK_IMPORTED_MODULE_2__constants__["c" /* strings */].TRANSITION_STATE_UNCHECKED;
if (nativeCb.indeterminate) {
return TRANSITION_STATE_INDETERMINATE;
}
return nativeCb.checked ? TRANSITION_STATE_CHECKED : TRANSITION_STATE_UNCHECKED;
}
/**
* @param {string} oldState
* @param {string} newState
* @return {string}
*/
}, {
key: 'getTransitionAnimationClass_',
value: function getTransitionAnimationClass_(oldState, newState) {
var TRANSITION_STATE_INIT = __WEBPACK_IMPORTED_MODULE_2__constants__["c" /* strings */].TRANSITION_STATE_INIT,
TRANSITION_STATE_CHECKED = __WEBPACK_IMPORTED_MODULE_2__constants__["c" /* strings */].TRANSITION_STATE_CHECKED,
TRANSITION_STATE_UNCHECKED = __WEBPACK_IMPORTED_MODULE_2__constants__["c" /* strings */].TRANSITION_STATE_UNCHECKED;
var _MDCCheckboxFoundatio = MDCCheckboxFoundation.cssClasses,
ANIM_UNCHECKED_CHECKED = _MDCCheckboxFoundatio.ANIM_UNCHECKED_CHECKED,
ANIM_UNCHECKED_INDETERMINATE = _MDCCheckboxFoundatio.ANIM_UNCHECKED_INDETERMINATE,
ANIM_CHECKED_UNCHECKED = _MDCCheckboxFoundatio.ANIM_CHECKED_UNCHECKED,
ANIM_CHECKED_INDETERMINATE = _MDCCheckboxFoundatio.ANIM_CHECKED_INDETERMINATE,
ANIM_INDETERMINATE_CHECKED = _MDCCheckboxFoundatio.ANIM_INDETERMINATE_CHECKED,
ANIM_INDETERMINATE_UNCHECKED = _MDCCheckboxFoundatio.ANIM_INDETERMINATE_UNCHECKED;
switch (oldState) {
case TRANSITION_STATE_INIT:
if (newState === TRANSITION_STATE_UNCHECKED) {
return '';
}
// fallthrough
case TRANSITION_STATE_UNCHECKED:
return newState === TRANSITION_STATE_CHECKED ? ANIM_UNCHECKED_CHECKED : ANIM_UNCHECKED_INDETERMINATE;
case TRANSITION_STATE_CHECKED:
return newState === TRANSITION_STATE_UNCHECKED ? ANIM_CHECKED_UNCHECKED : ANIM_CHECKED_INDETERMINATE;
// TRANSITION_STATE_INDETERMINATE
default:
return newState === TRANSITION_STATE_CHECKED ? ANIM_INDETERMINATE_CHECKED : ANIM_INDETERMINATE_UNCHECKED;
}
}
/**
* @return {!InputElementState}
* @private
*/
}, {
key: 'getNativeControl_',
value: function getNativeControl_() {
return this.adapter_.getNativeControl() || {
checked: false,
indeterminate: false,
disabled: false,
value: null
};
}
}]);
return MDCCheckboxFoundation;
}(__WEBPACK_IMPORTED_MODULE_0__material_base_foundation__["a" /* default */]);
/**
* @param {ObjectPropertyDescriptor|undefined} inputPropDesc
* @return {boolean}
*/
/* harmony default export */ __webpack_exports__["a"] = (MDCCheckboxFoundation);
function validDescriptor(inputPropDesc) {
return !!inputPropDesc && typeof inputPropDesc.set === 'function';
}
/***/ }),
/* 30 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return cssClasses; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return strings; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return numbers; });
/**
* Copyright 2016 Google Inc. 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.
*/
/** @const {string} */
var ROOT = 'mdc-checkbox';
/** @enum {string} */
var cssClasses = {
UPGRADED: 'mdc-checkbox--upgraded',
CHECKED: 'mdc-checkbox--checked',
INDETERMINATE: 'mdc-checkbox--indeterminate',
DISABLED: 'mdc-checkbox--disabled',
ANIM_UNCHECKED_CHECKED: 'mdc-checkbox--anim-unchecked-checked',
ANIM_UNCHECKED_INDETERMINATE: 'mdc-checkbox--anim-unchecked-indeterminate',
ANIM_CHECKED_UNCHECKED: 'mdc-checkbox--anim-checked-unchecked',
ANIM_CHECKED_INDETERMINATE: 'mdc-checkbox--anim-checked-indeterminate',
ANIM_INDETERMINATE_CHECKED: 'mdc-checkbox--anim-indeterminate-checked',
ANIM_INDETERMINATE_UNCHECKED: 'mdc-checkbox--anim-indeterminate-unchecked'
};
/** @enum {string} */
var strings = {
NATIVE_CONTROL_SELECTOR: '.' + ROOT + '__native-control',
TRANSITION_STATE_INIT: 'init',
TRANSITION_STATE_CHECKED: 'checked',
TRANSITION_STATE_UNCHECKED: 'unchecked',
TRANSITION_STATE_INDETERMINATE: 'indeterminate'
};
/** @enum {number} */
var numbers = {
ANIM_END_LATCH_MS: 100
};
/***/ })
/******/ ]);
}); |
import SocialShare from './SocialShare'
export default SocialShare
|
module.exports = require('react-native').NativeModules.SuperIDRN;
|
version https://git-lfs.github.com/spec/v1
oid sha256:54bbb07ae1a9f895764c118915dd17af16bf383083de7e4f867c71d1da32c925
size 972
|
!function(e){"use strict";e.redux=e.redux||{},e(document).ready(function(){e.redux.table()}),e.redux.table=function(){var l=e(".wpglobus_flag_table_wrapper").html(),a=e(".wpglobus_flag_table_wrapper").parents("table");a.wrap('<div style="overflow:hidden;" class="wpglobus_flag_table"></div>'),a.remove(),e(".wpglobus_flag_table").html(l)}}(jQuery); |
/**
Loading progress view
@class LoadingView
@constructor
@return {object} instantiated LoadingView
**/
define(['jquery', 'backbone'], function ($, Backbone) {
var LoadingView = Backbone.View.extend({
/**
Constructor
@method initialize
**/
initialize: function () {
var self = this;
BB.comBroker.setService(BB.SERVICES.LOADING_VIEW,self);
self.collection.on('add', function(){
BB.comBroker.getService(BB.EVENTS.APP_STACK_VIEW).selectView(BB.Elements.DIGG_CONTAINER);
self.collection.off('add');
});
}
});
return LoadingView;
}); |
// *****************************************************************
// Ox - A modular framework for developing templated, responsive, grid-based projects.
//
// *****************************************************************
// Project configuration
var project = 'ox' // Directory name for your project.
, src = './src/' // The raw files for your project.
, build = './build/' // The temporary files of your development build.
, dist = './dist/' // The production package that you'll upload to your server.
, assets = 'assets/' // The assets folder.
, bower = './bower_components/' // Bower packages.
, modules = './node_modules/' // npm packages.
;
// Project settings
module.exports = {
browsersync: {
files: [build+'/**', '!'+build+'/**.map'] // Watch all files, except map files
, notify: false // In-line notifications
, open: false // Stops the browser window opening automatically
, port: 1337 // Port number for the live version of the site; default: 1377
, server: { baseDir: build }
//, proxy: project+'.dev' // Proxy defined to work with Virtual Hosts
, watchOptions: {
debounceDelay: 2000 // Avoid triggering too many reloads
}
},
images: {
build: { // Copies images from `src` to `build`; does not optimise
src: src+'**/*.+(png|jpg|jpeg|gif|svg)'
, dest: build
}
, dist: { // Optimises images in the `dist` folder
src: [dist+'**/*.+(png|jpg|jpeg|gif|svg)']
, imagemin: {
optimizationLevel: 7
, progressive: true
, interlaced: true
}
, dest: dist
}
},
scripts: {
bundles: { // Bundles are defined by a name and an array of chunks (below) to concatenate.
core: ['core']
, vendor: ['vendor']
, jquery: ['jquery']
, modernizr: ['modernizr']
}
, chunks: { // Chunks are arrays of paths or globs matching a set of source files
core: src+assets+'js/core/*.js'
, vendor: src+assets+'js/vendor/*.js'
, modernizr: src+assets+'js/modernizr/*.js'
, jquery: bower+'jquery/dist/jquery.js'
}
, dest: build+assets+'js/'
, lint: {
src: [src+assets+'js/**/*.js', '!'+src+assets+'js/vendor/*.js', '!'+src+assets+'js/modernizr/*.js']
}
, minify: {
src: build+assets+'js/**/*.js'
, uglify: {} // Default options
, dest: build+assets+'js/'
}
},
styles: {
build: {
src: src+assets+'scss/**/*.scss'
, dest: build+assets+'/styles'
}
, autoprefixer: {
browsers: ['> 1%', 'last 2 versions', 'ie 11', 'ios >= 6', 'android >= 4', 'safari >= 8']
, grid: true
}
, stylelint: {"rules": {
"color-no-invalid-hex": true,
"number-leading-zero": "always",
"number-no-trailing-zeros": true,
"length-zero-no-unit": true,
"string-quotes": "double",
"value-no-vendor-prefix": true,
"declaration-colon-space-before": "never",
"declaration-bang-space-before": "always",
"declaration-bang-space-after": "never",
"declaration-block-semicolon-newline-after": "always-multi-line",
"selector-list-comma-space-before": "never",
"selector-pseudo-element-colon-notation": "double",
"max-empty-lines": 5
}}
, minify: {
safe: true,
autoprefixer: false
}
, libsass: { // Requires the libsass implementation of Sass
includePaths: [src+assets+'scss', bower, modules]
, precision: 6
}
},
theme: {
beautify: {
"indent_size": 4,
"indent_with_tabs": true,
"max_preserve_newlines": 1
}
, njk: {
src: src+'app/pages/**/*.+(html|njk|json)'
, path: [src+'app/templates']
, dest: build
}
, html: {
src: src+'**/*.html'
, dest: build
}
, favicon: {
src: src+assets+'images/favicon/*.+(ico|jpg|json)'
, dest: build+assets+'images'
}
, font: {
src: src+assets+'fonts/**/*.+(eot|svg|ttf|woff|woff2)'
, dest: build+assets+'fonts'
}
},
utils: {
clean: [build+'**/.DS_Store']
, wipe: [dist]
, dist: {
src: [build+'**/*', '!'+build+'**/*.map']
, dest: dist
}
},
watch: {
src: {
styles: src+assets+'scss/**/*.scss'
, scripts: src+assets+'js/**/*.js'
, images: src+'**/*.+(png|jpg|jpeg|gif|svg)'
, theme: src+'**/*.+(html|njk|json)'
, themeassets: [src+assets+'images/favicon/*.+(ico|jpg|json)', src+assets+'fonts/**/*.+(eot|svg|ttf|woff|woff2)']
}
, watcher: 'browsersync'
}
}
|
import { app, router, store } from './app'
const isDev = process.env.NODE_ENV !== 'production'
export default context => {
const s = isDev && Date.now()
router.push(context.url)
const matchedComponents = router.getMatchedComponents()
if (!matchedComponents.length) {
return Promise.reject({ code: 404 })
}
return Promise.all(matchedComponents.map(component => {
if (component.preFetch) {
return component.preFetch(store)
}
})).then(() => {
isDev && console.log(`data pre-fetch: ${Date.now() - s}ms`)
context.initialState = store.state
return app
})
} |
/// <reference path="_reference.js" />
"use strict";
var svgNameSpace = "http://www.w3.org/2000/svg";
function createSVG(id, width, height) {
var svg = document.createElementNS(svgNameSpace, "svg");
if (id) {
svg.setAttribute("id", id);
}
svg.setAttribute("width", width );
svg.setAttribute("height", height );
return svg;
}
function createPath(points, stroke, fill, strokeWidth) {
var path;
path = document.createElementNS(svgNameSpace, 'path');
path.setAttribute('d', points);
path.setAttribute('stroke', stroke);
path.setAttribute('fill', fill);
path.setAttribute('stroke-width', strokeWidth);
return path;
}
function createCircle(x, y, r, fill) {
var circle;
circle = document.createElementNS(svgNameSpace, 'circle');
circle.setAttribute('cx', x);
circle.setAttribute('cy', y);
circle.setAttribute('r', r);
circle.setAttribute('fill', fill);
return circle;
}
function createImage(x, y, width, height, href) {
var image;
image = document.createElementNS(svgNameSpace, 'image');
image.setAttribute('x', x);
image.setAttribute('y', y);
image.setAttribute('width', width);
image.setAttribute('height', height);
image.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', href);
return image;
}
function createText(x, y, fontSize, fontWeight, fontFamily, fill, value) {
var text;
text = document.createElementNS(svgNameSpace, 'text');
text.setAttribute('x', x);
text.setAttribute('y', y);
text.setAttribute('font-size', fontSize);
text.setAttribute('font-weight', fontWeight);
text.setAttribute('font-family', fontFamily);
text.setAttribute('fill', fill);
text.textContent = value;
return text;
}
function createRect(x, y, width, height, fill, stroke) {
var rect;
rect = document.createElementNS(svgNameSpace, 'rect');
rect.setAttribute('x', x);
rect.setAttribute('y', y);
rect.setAttribute('width', width);
rect.setAttribute('height', height);
rect.setAttribute('fill', fill);
rect.setAttribute('stroke', stroke);
return rect;
} |
define(["require", "exports", "./selection", "./collection", "./utils/arrayUtils"], function (require, exports, selection_1, collection_1, arrayUtils_1) {
Object.defineProperty(exports, "__esModule", { value: true });
var DataSource = (function () {
function DataSource(selection, config) {
this.selection = selection || new selection_1.Selection('single');
this.selectionEventID = this.selection.addEventListener(this.selectionEventCallback.bind(this));
this.selection.overrideGetRowKey(this.getRowKey.bind(this));
this.selection.overrideGetRowKeys(this.getRowKeys.bind(this));
this.arrayUtils = new arrayUtils_1.ArrayUtils();
this.key = null;
this.mainArray = null;
this.config = config;
if (this.config) {
this.key = config.key || '__avgKey';
this.rowHeight = config.rowHeight || 25;
this.groupHeight = config.groupHeight || 25;
this.rowHeightCallback = config.rowHeightCallback || function () { return null; };
}
else {
this.key = '__avgKey';
this.rowHeight = 25;
this.groupHeight = 25;
this.rowHeightCallback = function () { return null; };
}
this.eventIdCount = -1;
this.eventCallBacks = [];
this.entity = null;
this.collection = new collection_1.Collection(this);
}
DataSource.prototype.getSelection = function () {
return this.selection;
};
DataSource.prototype.getKey = function () {
return this.key;
};
DataSource.prototype.length = function () {
return this.collection.length;
};
DataSource.prototype.triggerEvent = function (event) {
var _this = this;
this.eventCallBacks.forEach(function (FN, i) {
if (FN !== null) {
var alive = FN(event);
if (!alive) {
_this.eventCallBacks[i] = null;
}
}
});
};
DataSource.prototype.addEventListener = function (callback) {
this.eventIdCount++;
this.eventCallBacks.push(callback);
return this.eventIdCount;
};
DataSource.prototype.removeEventListener = function (id) {
this.eventCallBacks.splice(id, 1);
};
DataSource.prototype.setArray = function (array) {
this.collection = new collection_1.Collection(this);
this.selection.reset();
this.arrayUtils.resetGrouping();
this.arrayUtils.resetSort(this.key);
this.entity = null;
this.collection.setData(array);
this.mainArray = this.collection.getEntities();
this.triggerEvent('collection_changed');
};
DataSource.prototype.push = function (array) {
if (Array.isArray(array)) {
var grouping = this.arrayUtils.getGrouping();
var collection = this.collection.getEntities();
collection = collection.concat(array);
this.collection.setData(collection);
this.mainArray = this.collection.getEntities();
this.arrayUtils.runOrderbyOn(this.collection.getEntities());
var untouchedgrouped = this.collection.getEntities();
if (grouping.length > 0) {
var groupedArray = this.arrayUtils.group(untouchedgrouped, grouping, true);
this.collection.setData(groupedArray, untouchedgrouped);
}
this.triggerEvent('collection_updated');
}
};
DataSource.prototype.refresh = function (data) {
if (data) {
this.collection = new collection_1.Collection(this);
this.collection.setData(data);
this.mainArray = this.collection.getEntities();
this.entity = null;
}
var grouping = this.arrayUtils.getGrouping();
this.arrayUtils.runOrderbyOn(this.collection.getEntities());
if (grouping.length > 0) {
var unGroupedArray = this.collection.getEntities();
var groupedArray = this.arrayUtils.group(unGroupedArray, grouping, true);
this.collection.setData(groupedArray, unGroupedArray);
}
this.triggerEvent('collection_updated');
};
DataSource.prototype.select = function (row) {
this.entity = this.collection.getRow(row);
};
DataSource.prototype.query = function (options) {
if (options) {
var newArray = this.arrayUtils.query(this.mainArray, options);
this.collection.setData(newArray);
}
else {
this.collection.setData(this.mainArray);
}
this.orderBy(null, true);
this.triggerEvent('collection_filtered');
};
DataSource.prototype.orderBy = function (attribute, addToCurrentSort) {
var collection = this.collection.getEntities();
var result = this.arrayUtils.orderBy(collection, attribute, addToCurrentSort);
this.collection.setData(result.fixed, result.full);
this.triggerEvent('collection_sorted');
};
DataSource.prototype.getCurrentOrderBy = function () {
return this.arrayUtils.getOrderBy();
};
DataSource.prototype.getCurrentFilter = function () {
return this.arrayUtils.getCurrentFilter();
};
DataSource.prototype.getElement = function (row) {
if (row === undefined || row === null) {
throw new Error('row missing');
}
else {
return this.collection.getRow(row);
}
};
DataSource.prototype.updateRowData = function (attribute, data, rows) {
var entities = this.collection.getCurrentEntities();
rows.forEach(function (x) {
entities[x][attribute] = data;
});
};
DataSource.prototype.group = function (grouping, keepExpanded) {
var _this = this;
this.arrayUtils.resetSort();
grouping.forEach(function (group) {
_this.arrayUtils.setOrderBy(group.field, true);
});
this.arrayUtils.runOrderbyOn(this.collection.getEntities());
var ungroupedArray = this.collection.getEntities();
var groupedArray = this.arrayUtils.group(ungroupedArray, grouping, keepExpanded);
this.collection.setData(groupedArray, ungroupedArray);
this.triggerEvent('collection_grouped');
};
DataSource.prototype.groupCollapse = function (id) {
var groupedArray = this.arrayUtils.groupCollapse(id);
var ungroupedArray = this.collection.getEntities();
this.collection.setData(groupedArray, ungroupedArray);
if (id) {
this.triggerEvent('collection_collapsed');
}
else {
this.triggerEvent('collection_collapsed_all');
}
};
DataSource.prototype.groupExpand = function (id) {
var groupedArray = this.arrayUtils.groupExpand(id);
var ungroupedArray = this.collection.getEntities();
this.collection.setData(groupedArray, ungroupedArray);
if (id) {
this.triggerEvent('collection_expanded');
}
else {
this.triggerEvent('collection_expanded_all');
}
};
DataSource.prototype.getGrouping = function () {
return this.arrayUtils.getGrouping();
};
DataSource.prototype.addBlankRow = function () {
var newElement = {};
this.mainArray.unshift(newElement);
var collectionUngrouped = this.collection.getEntities();
var displayedCollection = this.collection.getCurrentEntities();
var index = collectionUngrouped.indexOf(newElement);
if (index === -1) {
collectionUngrouped.unshift(newElement);
}
displayedCollection.unshift(newElement);
this.collection.setData(displayedCollection, collectionUngrouped);
this.entity = newElement;
this.triggerEvent('collection_filtered');
};
DataSource.prototype.unshift = function (data) {
if (data) {
this.mainArray.unshift(data);
var displayedCollection = this.collection.getEntities();
var ungroupedCollection = this.collection.getCurrentEntities();
var index = displayedCollection.indexOf(data);
if (index === -1) {
displayedCollection.unshift(data);
}
ungroupedCollection.unshift(data);
this.collection.setData(ungroupedCollection, displayedCollection);
this.entity = data;
this.triggerEvent('collection_filtered');
}
};
DataSource.prototype.remove = function (rows) {
var _this = this;
var keysToDelete = new Set();
var returnArray = [];
if (Array.isArray(rows)) {
rows.forEach(function (row) {
keysToDelete.add(_this.getRowKey(row));
});
}
else {
if (this.entity && Number.isInteger(rows)) {
keysToDelete.add(this.getRowKey(rows));
}
}
if (keysToDelete.size > 0) {
var oldArray = this.collection.getEntities();
for (var i = 0; i < oldArray.length; i++) {
if (keysToDelete.has(oldArray[i][this.key]) === true) {
returnArray.push(oldArray.splice(i, 1)[0]);
i--;
}
}
this.collection.setData(oldArray);
this.refresh();
}
return returnArray;
};
DataSource.prototype.getCollectionStatus = function () {
var status = {
collectionLength: this.mainArray ? this.mainArray.length : 0,
filteredCollectionLength: this.collection.getEntities().length,
selectionLength: this.selection.getLength()
};
return status;
};
DataSource.prototype.setLocaleCompare = function (code, options) {
this.arrayUtils.setLocaleCompare(code, options);
};
DataSource.prototype.getRowHeightState = function () {
return this.collection.getRowHeightState();
};
DataSource.prototype.getRowKey = function (row) {
if (this.collection) {
return this.collection.getRowKey(row);
}
else {
return null;
}
};
DataSource.prototype.getRowKeys = function () {
if (this.collection) {
return this.collection.getRowKeys();
}
else {
return [];
}
};
DataSource.prototype.selectionEventCallback = function (e) {
this.triggerEvent(e);
return true;
};
return DataSource;
}());
exports.DataSource = DataSource;
});
//# sourceMappingURL=dataSource.js.map |
function TableSort(id) {
this.tbl = document.getElementById(id);
this.lastSortedTh = null;
if (this.tbl && this.tbl.nodeName == "TABLE") {
var headings = this.tbl.tHead.rows[0].cells;
for (var i=0; headings[i]; i++) {
if (headings[i].className.match(/asc|dsc/)) {
this.lastSortedTh = headings[i];
}
}
this.makeSortable();
}
}
TableSort.prototype.makeSortable = function () {
var headings = this.tbl.tHead.rows[0].cells;
for (var i=0; headings[i]; i++) {
if(!headings[i].className.match(/notSortable/)) {
headings[i].cIdx = i;
var a = document.createElement("a");
a.href = "#";
a.innerHTML = headings[i].innerHTML;
a.onclick = function (that) {
return function () {
that.sortCol(this);
return false;
}
}(this);
headings[i].innerHTML = "";
headings[i].appendChild(a);
}
}
}
TableSort.prototype.sortCol = function (el) {
/*
* Get cell data for column that is to be sorted from HTML table
*/
var rows = this.tbl.rows;
var alpha = [], numeric = [];
var aIdx = 0, nIdx = 0;
var th = el.parentNode;
var cellIndex = th.cIdx;
for (var i=1; rows[i]; i++) {
var cell = rows[i].cells[cellIndex];
var content = cell.textContent ? cell.textContent : cell.innerText;
/*
* Split data into two separate arrays, one for numeric content and
* one for everything else (alphabetic). Store both the actual data
* that will be used for comparison by the sort algorithm (thus the need
* to parseFloat() the numeric data) as well as a reference to the
* element's parent row. The row reference will be used after the new
* order of content is determined in order to actually reorder the HTML
* table's rows.
*/
if(content && String(content).length >= 0) {
var num = content.replace(/(\$|\,|\s)/g, "");
if (parseFloat(num) == num) {
numeric[nIdx++] = {
value: Number(num),
row: rows[i]
}
} else {
alpha[aIdx++] = {
value: content,
row: rows[i]
}
}
} else {
alpha[aIdx++] = {
value: "",
row: rows[i]
}
}
}
/*
* Sort according to direction (ascending or descending)
*/
var col = [], top, bottom;
if (th.className.match("asc")) {
top = bubbleSort(alpha, -1);
bottom = bubbleSort(numeric, -1);
th.className = th.className.replace(/asc/, "dsc");
} else {
top = bubbleSort(numeric, 1);
bottom = bubbleSort(alpha, 1);
if (th.className.match("dsc")) {
th.className = th.className.replace(/dsc/, "asc");
} else {
th.className += "asc";
}
}
/*
* Clear asc/dsc class names from the last sorted column's th if it isnt the
* same as the one that was just clicked
*/
if (this.lastSortedTh && th != this.lastSortedTh) {
this.lastSortedTh.className = this.lastSortedTh.className.replace(/dsc|asc/g, "");
}
this.lastSortedTh = th;
/*
* Reorder HTML table based on new order of data found in the col array
*/
col = top.concat(bottom);
var tBody = this.tbl.tBodies[0];
for (var i=0; col[i]; i++) {
tBody.appendChild(col[i].row);
}
}
function bubbleSort(arr, dir) {
// Pre-calculate directional information
var start, end;
if (dir === 1) {
start = 0;
end = arr.length;
} else if (dir === -1) {
start = arr.length-1;
end = -1;
}
// Bubble sort: http://en.wikipedia.org/wiki/Bubble_sort
var unsorted = true;
while (unsorted) {
unsorted = false;
for (var i=start; i!=end; i=i+dir) {
if (arr[i+dir] && arr[i].value > arr[i+dir].value) {
var a = arr[i];
var b = arr[i+dir];
var c = a;
arr[i] = b;
arr[i+dir] = c;
unsorted = true;
}
}
}
return arr;
} |
const gulp = require('gulp');
const HubRegistry = require('gulp-hub');
const browserSync = require('browser-sync');
const conf = require('./conf/gulp.conf');
// Load some files into the registry
const hub = new HubRegistry([conf.path.tasks('*.js')]);
// Tell gulp to use the tasks just loaded
gulp.registry(hub);
<% if (modules === 'inject') { -%>
gulp.task('inject', gulp.series(gulp.parallel('styles', 'scripts'), 'inject'));
<% } -%>
gulp.task('build', <%- buildTask %>);
gulp.task('test', <%- testTask %>);
gulp.task('test:auto', <%- testAutoTask %>);
gulp.task('serve', <%- serveTask %>);
gulp.task('serve:dist', gulp.series('default', 'browsersync:dist'));
gulp.task('default', gulp.series('clean', 'build'));
gulp.task('watch', watch);
function reloadBrowserSync(cb) {
browserSync.reload();
cb();
}
function watch(done) {
<% if (modules === 'inject') { -%>
gulp.watch([
conf.path.src('index.html'),
'bower.json'
], gulp.parallel('inject'));
<% } -%>
<% if (framework !== 'react' && modules !== 'webpack') { -%>
<% if (modules !== 'systemjs') { -%>
gulp.watch(conf.path.src('app/**/*.html'), gulp.series('partials', reloadBrowserSync));
<% } else { -%>
gulp.watch(conf.path.src('**/*.html'), reloadBrowserSync);
<% } -%>
<% } else if (modules === 'webpack') {-%>
gulp.watch(conf.path.tmp('index.html'), reloadBrowserSync);
<% } else { -%>
gulp.watch(conf.path.src('index.html'), reloadBrowserSync);
<% } -%>
<% if (modules !== 'webpack') { -%>
gulp.watch([
<% if (css !== 'css') { -%>
conf.path.src('**/*.<%- css %>'),
<% } -%>
conf.path.src('**/*.css')
], gulp.series('styles'));
<% } -%>
<% if (modules === 'inject') { -%>
gulp.watch(conf.path.src('**/*.<%- extensions.js %>'), gulp.series('inject'));
<% } else if (modules === 'systemjs') { -%>
gulp.watch(conf.path.src('**/*.<%- extensions.js %>'), gulp.series('scripts'));
<% } -%>
done();
}
|
// All symbols in the Unified Canadian Aboriginal Syllabics block as per Unicode v5.1.0:
[
'\u1400',
'\u1401',
'\u1402',
'\u1403',
'\u1404',
'\u1405',
'\u1406',
'\u1407',
'\u1408',
'\u1409',
'\u140A',
'\u140B',
'\u140C',
'\u140D',
'\u140E',
'\u140F',
'\u1410',
'\u1411',
'\u1412',
'\u1413',
'\u1414',
'\u1415',
'\u1416',
'\u1417',
'\u1418',
'\u1419',
'\u141A',
'\u141B',
'\u141C',
'\u141D',
'\u141E',
'\u141F',
'\u1420',
'\u1421',
'\u1422',
'\u1423',
'\u1424',
'\u1425',
'\u1426',
'\u1427',
'\u1428',
'\u1429',
'\u142A',
'\u142B',
'\u142C',
'\u142D',
'\u142E',
'\u142F',
'\u1430',
'\u1431',
'\u1432',
'\u1433',
'\u1434',
'\u1435',
'\u1436',
'\u1437',
'\u1438',
'\u1439',
'\u143A',
'\u143B',
'\u143C',
'\u143D',
'\u143E',
'\u143F',
'\u1440',
'\u1441',
'\u1442',
'\u1443',
'\u1444',
'\u1445',
'\u1446',
'\u1447',
'\u1448',
'\u1449',
'\u144A',
'\u144B',
'\u144C',
'\u144D',
'\u144E',
'\u144F',
'\u1450',
'\u1451',
'\u1452',
'\u1453',
'\u1454',
'\u1455',
'\u1456',
'\u1457',
'\u1458',
'\u1459',
'\u145A',
'\u145B',
'\u145C',
'\u145D',
'\u145E',
'\u145F',
'\u1460',
'\u1461',
'\u1462',
'\u1463',
'\u1464',
'\u1465',
'\u1466',
'\u1467',
'\u1468',
'\u1469',
'\u146A',
'\u146B',
'\u146C',
'\u146D',
'\u146E',
'\u146F',
'\u1470',
'\u1471',
'\u1472',
'\u1473',
'\u1474',
'\u1475',
'\u1476',
'\u1477',
'\u1478',
'\u1479',
'\u147A',
'\u147B',
'\u147C',
'\u147D',
'\u147E',
'\u147F',
'\u1480',
'\u1481',
'\u1482',
'\u1483',
'\u1484',
'\u1485',
'\u1486',
'\u1487',
'\u1488',
'\u1489',
'\u148A',
'\u148B',
'\u148C',
'\u148D',
'\u148E',
'\u148F',
'\u1490',
'\u1491',
'\u1492',
'\u1493',
'\u1494',
'\u1495',
'\u1496',
'\u1497',
'\u1498',
'\u1499',
'\u149A',
'\u149B',
'\u149C',
'\u149D',
'\u149E',
'\u149F',
'\u14A0',
'\u14A1',
'\u14A2',
'\u14A3',
'\u14A4',
'\u14A5',
'\u14A6',
'\u14A7',
'\u14A8',
'\u14A9',
'\u14AA',
'\u14AB',
'\u14AC',
'\u14AD',
'\u14AE',
'\u14AF',
'\u14B0',
'\u14B1',
'\u14B2',
'\u14B3',
'\u14B4',
'\u14B5',
'\u14B6',
'\u14B7',
'\u14B8',
'\u14B9',
'\u14BA',
'\u14BB',
'\u14BC',
'\u14BD',
'\u14BE',
'\u14BF',
'\u14C0',
'\u14C1',
'\u14C2',
'\u14C3',
'\u14C4',
'\u14C5',
'\u14C6',
'\u14C7',
'\u14C8',
'\u14C9',
'\u14CA',
'\u14CB',
'\u14CC',
'\u14CD',
'\u14CE',
'\u14CF',
'\u14D0',
'\u14D1',
'\u14D2',
'\u14D3',
'\u14D4',
'\u14D5',
'\u14D6',
'\u14D7',
'\u14D8',
'\u14D9',
'\u14DA',
'\u14DB',
'\u14DC',
'\u14DD',
'\u14DE',
'\u14DF',
'\u14E0',
'\u14E1',
'\u14E2',
'\u14E3',
'\u14E4',
'\u14E5',
'\u14E6',
'\u14E7',
'\u14E8',
'\u14E9',
'\u14EA',
'\u14EB',
'\u14EC',
'\u14ED',
'\u14EE',
'\u14EF',
'\u14F0',
'\u14F1',
'\u14F2',
'\u14F3',
'\u14F4',
'\u14F5',
'\u14F6',
'\u14F7',
'\u14F8',
'\u14F9',
'\u14FA',
'\u14FB',
'\u14FC',
'\u14FD',
'\u14FE',
'\u14FF',
'\u1500',
'\u1501',
'\u1502',
'\u1503',
'\u1504',
'\u1505',
'\u1506',
'\u1507',
'\u1508',
'\u1509',
'\u150A',
'\u150B',
'\u150C',
'\u150D',
'\u150E',
'\u150F',
'\u1510',
'\u1511',
'\u1512',
'\u1513',
'\u1514',
'\u1515',
'\u1516',
'\u1517',
'\u1518',
'\u1519',
'\u151A',
'\u151B',
'\u151C',
'\u151D',
'\u151E',
'\u151F',
'\u1520',
'\u1521',
'\u1522',
'\u1523',
'\u1524',
'\u1525',
'\u1526',
'\u1527',
'\u1528',
'\u1529',
'\u152A',
'\u152B',
'\u152C',
'\u152D',
'\u152E',
'\u152F',
'\u1530',
'\u1531',
'\u1532',
'\u1533',
'\u1534',
'\u1535',
'\u1536',
'\u1537',
'\u1538',
'\u1539',
'\u153A',
'\u153B',
'\u153C',
'\u153D',
'\u153E',
'\u153F',
'\u1540',
'\u1541',
'\u1542',
'\u1543',
'\u1544',
'\u1545',
'\u1546',
'\u1547',
'\u1548',
'\u1549',
'\u154A',
'\u154B',
'\u154C',
'\u154D',
'\u154E',
'\u154F',
'\u1550',
'\u1551',
'\u1552',
'\u1553',
'\u1554',
'\u1555',
'\u1556',
'\u1557',
'\u1558',
'\u1559',
'\u155A',
'\u155B',
'\u155C',
'\u155D',
'\u155E',
'\u155F',
'\u1560',
'\u1561',
'\u1562',
'\u1563',
'\u1564',
'\u1565',
'\u1566',
'\u1567',
'\u1568',
'\u1569',
'\u156A',
'\u156B',
'\u156C',
'\u156D',
'\u156E',
'\u156F',
'\u1570',
'\u1571',
'\u1572',
'\u1573',
'\u1574',
'\u1575',
'\u1576',
'\u1577',
'\u1578',
'\u1579',
'\u157A',
'\u157B',
'\u157C',
'\u157D',
'\u157E',
'\u157F',
'\u1580',
'\u1581',
'\u1582',
'\u1583',
'\u1584',
'\u1585',
'\u1586',
'\u1587',
'\u1588',
'\u1589',
'\u158A',
'\u158B',
'\u158C',
'\u158D',
'\u158E',
'\u158F',
'\u1590',
'\u1591',
'\u1592',
'\u1593',
'\u1594',
'\u1595',
'\u1596',
'\u1597',
'\u1598',
'\u1599',
'\u159A',
'\u159B',
'\u159C',
'\u159D',
'\u159E',
'\u159F',
'\u15A0',
'\u15A1',
'\u15A2',
'\u15A3',
'\u15A4',
'\u15A5',
'\u15A6',
'\u15A7',
'\u15A8',
'\u15A9',
'\u15AA',
'\u15AB',
'\u15AC',
'\u15AD',
'\u15AE',
'\u15AF',
'\u15B0',
'\u15B1',
'\u15B2',
'\u15B3',
'\u15B4',
'\u15B5',
'\u15B6',
'\u15B7',
'\u15B8',
'\u15B9',
'\u15BA',
'\u15BB',
'\u15BC',
'\u15BD',
'\u15BE',
'\u15BF',
'\u15C0',
'\u15C1',
'\u15C2',
'\u15C3',
'\u15C4',
'\u15C5',
'\u15C6',
'\u15C7',
'\u15C8',
'\u15C9',
'\u15CA',
'\u15CB',
'\u15CC',
'\u15CD',
'\u15CE',
'\u15CF',
'\u15D0',
'\u15D1',
'\u15D2',
'\u15D3',
'\u15D4',
'\u15D5',
'\u15D6',
'\u15D7',
'\u15D8',
'\u15D9',
'\u15DA',
'\u15DB',
'\u15DC',
'\u15DD',
'\u15DE',
'\u15DF',
'\u15E0',
'\u15E1',
'\u15E2',
'\u15E3',
'\u15E4',
'\u15E5',
'\u15E6',
'\u15E7',
'\u15E8',
'\u15E9',
'\u15EA',
'\u15EB',
'\u15EC',
'\u15ED',
'\u15EE',
'\u15EF',
'\u15F0',
'\u15F1',
'\u15F2',
'\u15F3',
'\u15F4',
'\u15F5',
'\u15F6',
'\u15F7',
'\u15F8',
'\u15F9',
'\u15FA',
'\u15FB',
'\u15FC',
'\u15FD',
'\u15FE',
'\u15FF',
'\u1600',
'\u1601',
'\u1602',
'\u1603',
'\u1604',
'\u1605',
'\u1606',
'\u1607',
'\u1608',
'\u1609',
'\u160A',
'\u160B',
'\u160C',
'\u160D',
'\u160E',
'\u160F',
'\u1610',
'\u1611',
'\u1612',
'\u1613',
'\u1614',
'\u1615',
'\u1616',
'\u1617',
'\u1618',
'\u1619',
'\u161A',
'\u161B',
'\u161C',
'\u161D',
'\u161E',
'\u161F',
'\u1620',
'\u1621',
'\u1622',
'\u1623',
'\u1624',
'\u1625',
'\u1626',
'\u1627',
'\u1628',
'\u1629',
'\u162A',
'\u162B',
'\u162C',
'\u162D',
'\u162E',
'\u162F',
'\u1630',
'\u1631',
'\u1632',
'\u1633',
'\u1634',
'\u1635',
'\u1636',
'\u1637',
'\u1638',
'\u1639',
'\u163A',
'\u163B',
'\u163C',
'\u163D',
'\u163E',
'\u163F',
'\u1640',
'\u1641',
'\u1642',
'\u1643',
'\u1644',
'\u1645',
'\u1646',
'\u1647',
'\u1648',
'\u1649',
'\u164A',
'\u164B',
'\u164C',
'\u164D',
'\u164E',
'\u164F',
'\u1650',
'\u1651',
'\u1652',
'\u1653',
'\u1654',
'\u1655',
'\u1656',
'\u1657',
'\u1658',
'\u1659',
'\u165A',
'\u165B',
'\u165C',
'\u165D',
'\u165E',
'\u165F',
'\u1660',
'\u1661',
'\u1662',
'\u1663',
'\u1664',
'\u1665',
'\u1666',
'\u1667',
'\u1668',
'\u1669',
'\u166A',
'\u166B',
'\u166C',
'\u166D',
'\u166E',
'\u166F',
'\u1670',
'\u1671',
'\u1672',
'\u1673',
'\u1674',
'\u1675',
'\u1676',
'\u1677',
'\u1678',
'\u1679',
'\u167A',
'\u167B',
'\u167C',
'\u167D',
'\u167E',
'\u167F'
]; |
// All code points with the `Sentence_Terminal` property as per Unicode v9.0.0:
[
0x21,
0x2E,
0x3F,
0x589,
0x61F,
0x6D4,
0x700,
0x701,
0x702,
0x7F9,
0x964,
0x965,
0x104A,
0x104B,
0x1362,
0x1367,
0x1368,
0x166E,
0x1735,
0x1736,
0x1803,
0x1809,
0x1944,
0x1945,
0x1AA8,
0x1AA9,
0x1AAA,
0x1AAB,
0x1B5A,
0x1B5B,
0x1B5E,
0x1B5F,
0x1C3B,
0x1C3C,
0x1C7E,
0x1C7F,
0x203C,
0x203D,
0x2047,
0x2048,
0x2049,
0x2E2E,
0x2E3C,
0x3002,
0xA4FF,
0xA60E,
0xA60F,
0xA6F3,
0xA6F7,
0xA876,
0xA877,
0xA8CE,
0xA8CF,
0xA92F,
0xA9C8,
0xA9C9,
0xAA5D,
0xAA5E,
0xAA5F,
0xAAF0,
0xAAF1,
0xABEB,
0xFE52,
0xFE56,
0xFE57,
0xFF01,
0xFF0E,
0xFF1F,
0xFF61,
0x10A56,
0x10A57,
0x11047,
0x11048,
0x110BE,
0x110BF,
0x110C0,
0x110C1,
0x11141,
0x11142,
0x11143,
0x111C5,
0x111C6,
0x111CD,
0x111DE,
0x111DF,
0x11238,
0x11239,
0x1123B,
0x1123C,
0x112A9,
0x1144B,
0x1144C,
0x115C2,
0x115C3,
0x115C9,
0x115CA,
0x115CB,
0x115CC,
0x115CD,
0x115CE,
0x115CF,
0x115D0,
0x115D1,
0x115D2,
0x115D3,
0x115D4,
0x115D5,
0x115D6,
0x115D7,
0x11641,
0x11642,
0x1173C,
0x1173D,
0x1173E,
0x11C41,
0x11C42,
0x16A6E,
0x16A6F,
0x16AF5,
0x16B37,
0x16B38,
0x16B44,
0x1BC9F,
0x1DA88
]; |
import { expect } from 'chai';
import Draft, { EditorState, SelectionState } from 'draft-js';
import handleBlockType from '../handleBlockType';
describe('handleBlockType', () => {
describe('no markup', () => {
const rawContentState = {
entityMap: {},
blocks: [
{
key: 'item1',
text: '[ ]',
type: 'unstyled',
depth: 0,
inlineStyleRanges: [],
entityRanges: [],
data: {},
},
],
};
const contentState = Draft.convertFromRaw(rawContentState);
const selection = new SelectionState({
anchorKey: 'item1',
anchorOffset: 3,
focusKey: 'item1',
focusOffset: 3,
isBackward: false,
hasFocus: true,
});
const editorState = EditorState.forceSelection(EditorState.createWithContent(contentState), selection);
it('does not convert block type', () => {
const newEditorState = handleBlockType(editorState, ' ');
expect(newEditorState).to.equal(editorState);
expect(Draft.convertToRaw(newEditorState.getCurrentContent())).to.deep.equal(rawContentState);
});
});
const testCases = {
'converts from unstyled to header-one': {
before: {
entityMap: {},
blocks: [
{
key: 'item1',
text: '# Test',
type: 'unstyled',
depth: 0,
inlineStyleRanges: [],
entityRanges: [],
data: {},
},
],
},
after: {
entityMap: {},
blocks: [
{
key: 'item1',
text: 'Test ',
type: 'header-one',
depth: 0,
inlineStyleRanges: [],
entityRanges: [],
data: {},
},
],
},
selection: new SelectionState({
anchorKey: 'item1',
anchorOffset: 6,
focusKey: 'item1',
focusOffset: 6,
isBackward: false,
hasFocus: true,
}),
},
'converts from unstyled to header-two': {
before: {
entityMap: {},
blocks: [
{
key: 'item1',
text: '## Test',
type: 'unstyled',
depth: 0,
inlineStyleRanges: [],
entityRanges: [],
data: {},
},
],
},
after: {
entityMap: {},
blocks: [
{
key: 'item1',
text: 'Test ',
type: 'header-two',
depth: 0,
inlineStyleRanges: [],
entityRanges: [],
data: {},
},
],
},
selection: new SelectionState({
anchorKey: 'item1',
anchorOffset: 7,
focusKey: 'item1',
focusOffset: 7,
isBackward: false,
hasFocus: true,
}),
},
'converts from unstyled to header-three': {
before: {
entityMap: {},
blocks: [
{
key: 'item1',
text: '### Test',
type: 'unstyled',
depth: 0,
inlineStyleRanges: [],
entityRanges: [],
data: {},
},
],
},
after: {
entityMap: {},
blocks: [
{
key: 'item1',
text: 'Test ',
type: 'header-three',
depth: 0,
inlineStyleRanges: [],
entityRanges: [],
data: {},
},
],
},
selection: new SelectionState({
anchorKey: 'item1',
anchorOffset: 8,
focusKey: 'item1',
focusOffset: 8,
isBackward: false,
hasFocus: true,
}),
},
'converts from unstyled to header-four': {
before: {
entityMap: {},
blocks: [
{
key: 'item1',
text: '#### Test',
type: 'unstyled',
depth: 0,
inlineStyleRanges: [],
entityRanges: [],
data: {},
},
],
},
after: {
entityMap: {},
blocks: [
{
key: 'item1',
text: 'Test ',
type: 'header-four',
depth: 0,
inlineStyleRanges: [],
entityRanges: [],
data: {},
},
],
},
selection: new SelectionState({
anchorKey: 'item1',
anchorOffset: 9,
focusKey: 'item1',
focusOffset: 9,
isBackward: false,
hasFocus: true,
}),
},
'converts from unstyled to header-five': {
before: {
entityMap: {},
blocks: [
{
key: 'item1',
text: '##### Test',
type: 'unstyled',
depth: 0,
inlineStyleRanges: [],
entityRanges: [],
data: {},
},
],
},
after: {
entityMap: {},
blocks: [
{
key: 'item1',
text: 'Test ',
type: 'header-five',
depth: 0,
inlineStyleRanges: [],
entityRanges: [],
data: {},
},
],
},
selection: new SelectionState({
anchorKey: 'item1',
anchorOffset: 10,
focusKey: 'item1',
focusOffset: 10,
isBackward: false,
hasFocus: true,
}),
},
'converts from unstyled to header-six': {
before: {
entityMap: {},
blocks: [
{
key: 'item1',
text: '###### Test',
type: 'unstyled',
depth: 0,
inlineStyleRanges: [],
entityRanges: [],
data: {},
},
],
},
after: {
entityMap: {},
blocks: [
{
key: 'item1',
text: 'Test ',
type: 'header-six',
depth: 0,
inlineStyleRanges: [],
entityRanges: [],
data: {},
},
],
},
selection: new SelectionState({
anchorKey: 'item1',
anchorOffset: 11,
focusKey: 'item1',
focusOffset: 11,
isBackward: false,
hasFocus: true,
}),
},
'converts from unstyled to unordered-list-item with hyphen': {
before: {
entityMap: {},
blocks: [
{
key: 'item1',
text: '- Test',
type: 'unstyled',
depth: 0,
inlineStyleRanges: [],
entityRanges: [],
data: {},
},
],
},
after: {
entityMap: {},
blocks: [
{
key: 'item1',
text: 'Test ',
type: 'unordered-list-item',
depth: 0,
inlineStyleRanges: [],
entityRanges: [],
data: {},
},
],
},
selection: new SelectionState({
anchorKey: 'item1',
anchorOffset: 6,
focusKey: 'item1',
focusOffset: 6,
isBackward: false,
hasFocus: true,
}),
},
'converts from unstyled to unordered-list-item with astarisk': {
before: {
entityMap: {},
blocks: [
{
key: 'item1',
text: '* Test',
type: 'unstyled',
depth: 0,
inlineStyleRanges: [],
entityRanges: [],
data: {},
},
],
},
after: {
entityMap: {},
blocks: [
{
key: 'item1',
text: 'Test ',
type: 'unordered-list-item',
depth: 0,
inlineStyleRanges: [],
entityRanges: [],
data: {},
},
],
},
selection: new SelectionState({
anchorKey: 'item1',
anchorOffset: 6,
focusKey: 'item1',
focusOffset: 6,
isBackward: false,
hasFocus: true,
}),
},
'converts from unstyled to ordered-list-item': {
before: {
entityMap: {},
blocks: [
{
key: 'item1',
text: '2. Test',
type: 'unstyled',
depth: 0,
inlineStyleRanges: [],
entityRanges: [],
data: {},
},
],
},
after: {
entityMap: {},
blocks: [
{
key: 'item1',
text: 'Test ',
type: 'ordered-list-item',
depth: 0,
inlineStyleRanges: [],
entityRanges: [],
data: {},
},
],
},
selection: new SelectionState({
anchorKey: 'item1',
anchorOffset: 7,
focusKey: 'item1',
focusOffset: 7,
isBackward: false,
hasFocus: true,
}),
},
'converts from unordered-list-item to unchecked checkable-list-item': {
before: {
entityMap: {},
blocks: [
{
key: 'item1',
text: '[] Test',
type: 'unordered-list-item',
depth: 0,
inlineStyleRanges: [],
entityRanges: [],
data: {},
},
],
},
after: {
entityMap: {},
blocks: [
{
key: 'item1',
text: 'Test',
type: 'checkable-list-item',
depth: 0,
inlineStyleRanges: [],
entityRanges: [],
data: {
checked: false,
},
},
],
},
selection: new SelectionState({
anchorKey: 'item1',
anchorOffset: 1,
focusKey: 'item1',
focusOffset: 1,
isBackward: false,
hasFocus: true,
}),
},
'converts from unordered-list-item to checked checkable-list-item': {
before: {
entityMap: {},
blocks: [
{
key: 'item1',
text: '[x]Test',
type: 'unordered-list-item',
depth: 0,
inlineStyleRanges: [],
entityRanges: [],
data: {},
},
],
},
after: {
entityMap: {},
blocks: [
{
key: 'item1',
text: 'Test',
type: 'checkable-list-item',
depth: 0,
inlineStyleRanges: [],
entityRanges: [],
data: {
checked: true,
},
},
],
},
selection: new SelectionState({
anchorKey: 'item1',
anchorOffset: 3,
focusKey: 'item1',
focusOffset: 3,
isBackward: false,
hasFocus: true,
}),
},
'converts from unstyled to blockquote': {
before: {
entityMap: {},
blocks: [
{
key: 'item1',
text: '> Test',
type: 'unstyled',
depth: 0,
inlineStyleRanges: [],
entityRanges: [],
data: {},
},
],
},
after: {
entityMap: {},
blocks: [
{
key: 'item1',
text: 'Test ',
type: 'blockquote',
depth: 0,
inlineStyleRanges: [],
entityRanges: [],
data: {},
},
],
},
selection: new SelectionState({
anchorKey: 'item1',
anchorOffset: 6,
focusKey: 'item1',
focusOffset: 6,
isBackward: false,
hasFocus: true,
}),
},
};
Object.keys(testCases).forEach(k => {
describe(k, () => {
const testCase = testCases[k];
const { before, after, selection, character = ' ' } = testCase;
const contentState = Draft.convertFromRaw(before);
const editorState = EditorState.forceSelection(EditorState.createWithContent(contentState), selection);
it('converts block type', () => {
const newEditorState = handleBlockType(editorState, character);
expect(newEditorState).not.to.equal(editorState);
expect(Draft.convertToRaw(newEditorState.getCurrentContent())).to.deep.equal(after);
});
});
});
});
|
var searchData=
[
['text',['text',['../class_politechnikon_1_1game__elements_1_1_text.html#aa18ff5a85e90a5d19b62976a65863932',1,'Politechnikon::game_elements::Text']]],
['textbuffor',['TextBuffor',['../class_politechnikon_1_1game__elements_1_1_field.html#a35f9c0081c0928be00204ca03ca56f1e',1,'Politechnikon::game_elements::Field']]],
['texture',['Texture',['../class_politechnikon_1_1engine_1_1_initialized_object_texture.html#a01631ef3363a7c274d3b89d5032a4407',1,'Politechnikon::engine::InitializedObjectTexture']]],
['texturepath',['TexturePath',['../class_politechnikon_1_1engine_1_1_initialized_object_texture.html#af22f9450a1f0be442485364e2ad9a77f',1,'Politechnikon::engine::InitializedObjectTexture']]],
['thisgame',['ThisGame',['../struct_politechnikon_1_1game__logic_1_1_score.html#a50c9999f319885c723ff6026c25f44b4',1,'Politechnikon::game_logic::Score']]]
];
|
//================================================================
// RS_HUD_OptimizedMobile.js
// ---------------------------------------------------------------
// The MIT License
// Copyright (c) 2015 biud436
// ---------------------------------------------------------------
// Free for commercial and non commercial use.
//================================================================
/*:
* RS_HUD_OptimizedMobile.js
* @plugindesc (v1.0.1) This plugin draws the HUD, which displays the hp and mp and exp and level of each party members.
*
* @author biud436
*
* @param --- Image Name
*
* @param Texture Atlas
* @parent --- Image Name
* @desc import texture atlas.
* @default config
* @require 1
* @dir img/rs_hud/
* @type file
*
* @param EXP Gauge
* @parent --- Image Name
* @desc Specifies to import file in the path named 'exr'
* @default exr
*
* @param Empty Gauge
* @parent --- Image Name
* @desc Specifies to import file in the path named 'gauge'
* @default gauge
*
* @param HP Gauge
* @parent --- Image Name
* @desc Specifies to import file in the path named 'hp'
* @default hp
*
* @param MP Gauge
* @parent --- Image Name
* @desc Specifies to import file in the path named 'mp'
* @default mp
*
* @param HUD Background
* @parent --- Image Name
* @desc Specifies to import file in the path named 'hud_window_empty'
* @default hud_window_empty
*
* @param Masking
* @parent --- Image Name
* @desc Specifies to import file in the path named 'masking'
* @default masking
*
* @param --- Image Custom Position
*
* @param Face Position
* @parent --- Image Custom Position
* @desc Specifies the properties of the face sprite by x, y, visible
* (Draw it at changing position relative to a background sprite)
* @default 0, 0, true
*
* @param HP Position
* @parent --- Image Custom Position
* @desc Specifies the properties of the hp sprite by x, y, visible
* (Draw it at changing position relative to a background sprite)
* @default 160, 41, true
*
* @param MP Position
* @parent --- Image Custom Position
* @desc Specifies the properties of the mp sprite by x, y, visible
* (Draw it at changing position relative to a background sprite)
* @default 160, 67, true
*
* @param EXP Position
* @parent --- Image Custom Position
* @desc Specifies the properties of the exp sprite by x, y, visible
* (Draw it at changing position relative to a background sprite)
* @default 83, 89, true
*
* @param HP Text Position
* @parent --- Image Custom Position
* @desc Specifies the properties of the hp text sprite by x, y, visible
* (Draw it at changing position relative to a background sprite)
* @default 160, 51, true
*
* @param MP Text Position
* @parent --- Image Custom Position
* @desc Specifies the properties of the mp text sprite by x, y, visible
* (Draw it at changing position relative to a background sprite)
* @default 160, 77, true
*
* @param Level Text Position
* @parent --- Image Custom Position
* @desc Specifies the properties of the level text sprite by x, y, visible
* (Draw it at changing position relative to a background sprite)
* @default 60, 78, true
*
* @param EXP Text Position
* @parent --- Image Custom Position
* @desc Specifies the properties of the exp text sprite by x, y, visible
* (Draw it at changing position relative to a background sprite)
* @default 120.5, 91, true
*
* @param Name Text Position
* @parent --- Image Custom Position
* @desc Specifies the properties of the name text sprite by x, y, visible
* (Draw it at changing position relative to a background sprite)
* @default 54, 51, false
*
* @param --- Noraml
*
* @param Width
* @parent --- Noraml
* @desc Do not change this when you are using the default sprite batch.
* (default : 317)
* @default 317
*
* @param Height
* @parent --- Noraml
* @desc Do not change this when you are using the default sprite batch.
* (default : 101)
* @default 101
*
* @param Margin
* @parent --- Noraml
* @type number
* @min 0
* @desc Sets the margin to the HUD borders.
* @default 0
*
* @param Gaussian Blur
* @parent --- Noraml
* @type boolean
* @desc Sets the Gaussian Blur.
* @default true
*
* @param Show
* @parent --- Noraml
* @type boolean
* @desc Sets the visible status. (default : true)
* @default true
*
* @param Opacity
* @parent --- Noraml
* @type number
* @min 0
* @max 255
* @desc Sets the opacity.
* @default 255
*
* @param Arrangement
* @parent --- Noraml
* @type string[]
* @desc Create an array to set the anchor of each HUD.
* @default ["LeftTop", "LeftBottom", "RightTop", "RightBottom"]
*
* @param Anchor
* @parent --- Noraml
* @desc If anchor is not found, HUD would set to this anchor.
* @default LeftTop
*
* @param preloadImportantFaces
* @parent --- Noraml
* @type string[]
* @desc Allow you to pre-load the base face chips.
* (If you do not set this parameter, It can cause errors in the game.)
* @default ["Actor1", "Actor2", "Actor3"]
*
* @param Battle Only
* @parent --- Noraml
* @type boolean
* @desc If you want to use the HUD only in battles.
* (default : false)
* @default false
*
* @param Show Comma
* @parent --- Noraml
* @type boolean
* @desc Sets the value that indicates whether this parameter displays
* the values with commas every three digits.
* @default false
*
* @param Max Exp Text
* @parent --- Noraml
* @desc
* @default ------/------
*
* @param Max Members
* @parent --- Noraml
* @type number
* @min 1
* @desc Specifies the maximum number of party members that displays within the game screen.
* @default 4
*
* @param --- Font
*
* @param Chinese Font
* @parent --- Font
* @desc Specifies the desired fonts
* @default SimHei, Heiti TC, sans-serif
*
* @param Korean Font
* @parent --- Font
* @desc Specifies the desired fonts
* @default NanumGothic, Dotum, AppleGothic, sans-serif
*
* @param Standard Font
* @parent --- Font
* @desc Specifies to import a css for the font file from ./fonts folder.
* @default GameFont
*
* @param Level Text Size
* @parent --- Font
* @desc Specify the text size for levels.
* @default 24
*
* @param HP Text Size
* @parent --- Font
* @desc Specify the text size for HP.
* @default 12
*
* @param MP Text Size
* @parent --- Font
* @desc Specify the text size for MP.
* @default 12
*
* @param EXP Text Size
* @parent --- Font
* @desc Specify the text size for EXP.
* @default 12
*
* @param Name Text Size
* @parent --- Font
* @desc Specify the text size for names.
* @default 12
*
* @param --- Text Color
*
* @param HP Color
* @parent --- Text Color
* @desc Specify the text color for HP.
* @default #ffffff
*
* @param MP Color
* @parent --- Text Color
* @desc Specify the text color for MP.
* @default #ffffff
*
* @param EXP Color
* @parent --- Text Color
* @desc Specify the text color for EXP.
* @default #ffffff
*
* @param Level Color
* @parent --- Text Color
* @desc Specify the text color for levels.
* @default #ffffff
*
* @param Name Color
* @parent --- Text Color
* @desc Specify the text color for names.
* @default #ffffff
*
* @param --- Text Outline Color
*
* @param HP Outline Color
* @parent --- Text Outline Color
* @desc Specify the text outline color for HP.
* @default rgba(0, 0, 0, 0.5)
*
* @param MP Outline Color
* @parent --- Text Outline Color
* @desc Specify the text outline color for MP.
* @default rgba(0, 0, 0, 0.5)
*
* @param EXP Outline Color
* @parent --- Text Outline Color
* @desc Specify the text outline color for EXP.
* @default rgba(0, 0, 0, 0.5)
*
* @param Level Outline Color
* @parent --- Text Outline Color
* @desc Specify the text outline color for levels.
* @default rgba(0, 0, 0, 0.5)
*
* @param Name Outline Color
* @parent --- Text Outline Color
* @desc Specify the text outline color for names.
* @default rgba(0, 0, 0, 0.5)
*
* @param --- Text Outline Width
*
* @param HP Outline Width
* @parent --- Text Outline Width
* @desc Specify the maximum width of a text border line for HP.
* @default 4
*
* @param MP Outline Width
* @parent --- Text Outline Width
* @desc Specify the maximum width of a text border line for MP.
* @default 4
*
* @param EXP Outline Width
* @parent --- Text Outline Width
* @desc Specify the maximum width of a text border line for EXP.
* @default 4
*
* @param Level Outline Width
* @parent --- Text Outline Width
* @desc Specify the maximum width of a text border line for levels.
* @default 4
*
* @param Name Outline Width
* @parent --- Text Outline Width
* @desc Specify the maximum width of a text border line for names.
* @default 4
*
* @param --- Custom Font
*
* @param Using Custom Font
* @parent --- Custom Font
* @type boolean
* @desc Specify whether the custom font shows (default : false)
* YES - true / NO - false
* @default false
*
* @param Custom Font Name
* @parent --- Custom Font
* @desc Specify the name of the custom font
* @default NanumBrush
*
* @param Custom Font Src
* @parent --- Custom Font
* @desc Specify the path of the font file from a game project folder
* @default fonts/NanumBrush.ttf
*
* @param --- Custom HUD Anchor
*
* @param Custom Pos 1
* @parent --- Custom HUD Anchor
* @desc Predefined Variables : W, H, PD, BW, BH
* (Please refer to a custom position of the help section)
* @default 0, (H * 0) + PD
*
* @param Custom Pos 2
* @parent --- Custom HUD Anchor
* @desc Predefined Variables : W, H, PD, BW, BH
* (Please refer to the help section)
* @default 0, (H * 1) + PD
*
* @param Custom Pos 3
* @parent --- Custom HUD Anchor
* @desc Predefined Variables : W, H, PD, BW, BH
* (Please refer to the help section)
* @default 0, (H * 2) + PD
*
* @param Custom Pos 4
* @parent --- Custom HUD Anchor
* @desc Predefined Variables : W, H, PD, BW, BH
* (Please refer to the help section)
* @default 0, (H * 3) + PD
*
* @param Custom Pos 5
* @parent --- Custom HUD Anchor
* @desc Predefined Variables : W, H, PD, BW, BH
* (Please refer to the help section)
* @default 0, (H * 4) + PD
*
* @param Custom Pos 6
* @parent --- Custom HUD Anchor
* @desc Predefined Variables : W, H, PD, BW, BH
* (Please refer to the help section)
* @default W + PD, (H * 0) + PD
*
* @param Custom Pos 7
* @parent --- Custom HUD Anchor
* @desc Predefined Variables : W, H, PD, BW, BH
* (Please refer to the help section)
* @default W + PD, (H * 1) + PD
*
* @param Custom Pos 8
* @parent --- Custom HUD Anchor
* @desc Predefined Variables : W, H, PD, BW, BH
* (Please refer to the help section)
* @default W + PD, (H * 2) + PD
*
* @param Custom Pos 9
* @parent --- Custom HUD Anchor
* @desc Predefined Variables : W, H, PD, BW, BH
* (Please refer to the help section)
* @default W + PD, (H * 3) + PD
*
* @param Custom Pos 10
* @parent --- Custom HUD Anchor
* @desc Predefined Variables : W, H, PD, BW, BH
* (Please refer to the help section)
* @default W + PD, (H * 4) + PD
*
* @help
* =============================================================================
* Installations
* =============================================================================
*
* Download the resources and place them in your img/rs_hud folder.
* All the resources can download in the following link.
* img/rs_hud/config.json : https://github.com/biud436/MV/raw/master/HUD/config.json
* img/rs_hud/config.png : https://github.com/biud436/MV/raw/master/HUD/config.png
*
* Github Link : https://github.com/biud436/MV/blob/master/HUD/RS_HUD_OptimizedMobile.js
*
* =============================================================================
* Custom Positions
* =============================================================================
*
* To display in correct place, you need to know which predefined variables are currently available.
* You can be available predefined variables as belows when specifying the parameter
* named 'Custom Pos'. So you can quickly set up positions for a hud itself.
*
* Predefined Variables :
* W - 'W' is the same as a parameter named 'Width' in Plugin Manager.
* H - 'H' is the same as a parameter named 'Height' in Plugin Manager
* PD - 'PD' is the same as a parameter named 'Margin' in Plugin Manager
* BW - 'BW' is the same as a maximum width of the game canvas.
* BH - 'BH' is the same as a maximum height of the game canvas.
*
* Each sprites draw at changing position relative to the background sprite.
* Therefore, this custom position is pretty important values.
*
* =============================================================================
* Notetags
* =============================================================================
*
* Insert the following the notetag into the map property window as below.
* <DISABLE_HUD> : A notetag can use in the map that does not wish create each huds.
*
* =============================================================================
* Script Calls
* =============================================================================
*
* -----------------------------------------------------------------------------
* Set Opacity
* -----------------------------------------------------------------------------
* Sets the opacity of the HUD to x.
*
* $gameHud.opacity = x;
*
* That is a number between 0 and 255.
*
* For example :
* $gameHud.opacity = 128;
*
* -----------------------------------------------------------------------------
* Set visibility
* -----------------------------------------------------------------------------
* This variable will change the visible option of the HUD.
*
* $gameHud.show = true/false;
*
* For example :
* $gameHud.show = false;
*
* -----------------------------------------------------------------------------
* Refresh Texts
* -----------------------------------------------------------------------------
* In general, text and gauge sprites refresh when requesting a refresh so this one is not
* updated on every frame. Therefore if you need to immediately refresh
* all texts for themselves, you will use as belows.
*
* $gameTemp.notifyHudTextRefresh();
*
* -----------------------------------------------------------------------------
* Clear and create all huds
* -----------------------------------------------------------------------------
* if you need to immediately recreate for all Huds, you will use as belows.
*
* $gameTemp.notifyHudRefresh();
* =============================================================================
* Plugin Commands
* =============================================================================
*
* RS_HUD Opacity x : This command sets up the opacity for all hud elements.
* 'x' is a number value between 0 and 255.
*
* RS_HUD Visible true/false : This command sets up whether it displays all containers for HUD.
* 'RS_HUD Visible true' sets its visibility to true.
* 'RS_HUD Visible false' sets its visibility to false.
*
* RS_HUD import file_name : This command imports the parameter as the json file from your data folder.
* RS_HUD export file_name : This command exports the parameter as the json file to your data folder.
*
* =============================================================================
* Change Log
* =============================================================================
* 2018.03.16 (v1.0.0) - First Release (forked in RS_HUD_4m)
* 2018.05.09 (v1.0.1) - Supported a face image that is made using SumRndmDde's CharacterCreatorEX plugin.
*/
var Imported = Imported || {};
Imported.RS_HUD_OptimizedMobile = '1.0.1';
var $gameHud = null;
var RS = RS || {};
RS.HUD = RS.HUD || {};
RS.HUD.param = RS.HUD.param || {};
(function() {
if(Utils.RPGMAKER_VERSION < '1.5.0') {
console.warn('Note that RS_HUD_4m plugin can use only in RMMV v1.5.0 or above.');
return;
}
var parameters = PluginManager.parameters('RS_HUD_OptimizedMobile');
// Image Settings
RS.HUD.param.imgEXP = String(parameters['EXP Gauge'] || 'exr');
RS.HUD.param.imgEmptyGauge = String(parameters['Empty Gauge'] || 'gauge');
RS.HUD.param.imgHP = String(parameters['HP Gauge'] || 'hp');
RS.HUD.param.imgMP = String(parameters['MP Gauge'] || 'mp');
RS.HUD.param.imgEmptyHUD = String(parameters['HUD Background'] || 'hud_window_empty');
RS.HUD.param.imgMasking = String(parameters['Masking'] || 'masking');
// Image Position
RS.HUD.loadImagePosition = function (szRE) {
var target = szRE.match(/(.*),(.*),(.*)/i);
var x = parseFloat(RegExp.$1);
var y = parseFloat(RegExp.$2);
var visible = Boolean(String(RegExp.$3).contains('true'));
return {'x': x, 'y': y, 'visible': visible};
};
RS.HUD.loadRealNumber = function (paramName, val) {
var value = Number(parameters[paramName]);
switch (typeof(value)) {
case 'object': case 'undefined':
value = val;
break;
}
return value;
};
RS.HUD.param.ptFace = RS.HUD.loadImagePosition(parameters['Face Position'] || '0, 0, true');
RS.HUD.param.ptHP = RS.HUD.loadImagePosition(parameters['HP Position'] || '160, 43, true');
RS.HUD.param.ptMP = RS.HUD.loadImagePosition(parameters['MP Position'] || '160, 69, true');
RS.HUD.param.ptEXP = RS.HUD.loadImagePosition(parameters['EXP Position'] || '83, 91, true');
RS.HUD.param.ptHPText = RS.HUD.loadImagePosition(parameters['HP Text Position'] || '160, 53, true');
RS.HUD.param.ptMPText = RS.HUD.loadImagePosition(parameters['MP Text Position'] || '160, 79, true');
RS.HUD.param.ptLevelText = RS.HUD.loadImagePosition(parameters['Level Text Position'] || '60, 80, true');
RS.HUD.param.ptEXPText = RS.HUD.loadImagePosition(parameters['EXP Text Position'] || '120.5, 93, true');
RS.HUD.param.ptNameText = RS.HUD.loadImagePosition(parameters['Name Text Position'] || '54, 53, true');
// Normal Settings
RS.HUD.param.nWidth = RS.HUD.loadRealNumber('Width', 317);
RS.HUD.param.nHeight = RS.HUD.loadRealNumber('Height', 101);
RS.HUD.param.nPD = RS.HUD.loadRealNumber('Margin', 0);
RS.HUD.param.blurProcessing = Boolean(parameters['Gaussian Blur'] === "true");
RS.HUD.param.bShow = Boolean(parameters['Show'] ==="true");
RS.HUD.param.nOpacity = RS.HUD.loadRealNumber('Opacity', 255);
RS.HUD.param.szAnchor = String(parameters['Anchor'] || "LeftTop");
RS.HUD.param.arrangement = eval(parameters['Arrangement']);
RS.HUD.param.preloadImportantFaces = eval(parameters['preloadImportantFaces'] || 'Actor1');
RS.HUD.param.battleOnly = Boolean(parameters['Battle Only'] === "true");
RS.HUD.param.showComma = Boolean(parameters['Show Comma'] === 'true');
RS.HUD.param.maxExpText = String(parameters['Max Exp Text'] || "------/------");
RS.HUD.param.nMaxMembers = parseInt(parameters["Max Members"] || 4);
RS.HUD.getDefaultHUDAnchor = function () {
var anchor = {
"LeftTop": {x: RS.HUD.param.nPD, y: RS.HUD.param.nPD},
"LeftBottom": {x: RS.HUD.param.nPD, y: Graphics.boxHeight - RS.HUD.param.nHeight - RS.HUD.param.nPD},
"RightTop": {x: Graphics.boxWidth - RS.HUD.param.nWidth - RS.HUD.param.nPD, y: RS.HUD.param.nPD},
"RightBottom": {x: Graphics.boxWidth - RS.HUD.param.nWidth - RS.HUD.param.nPD, y: Graphics.boxHeight - RS.HUD.param.nHeight - RS.HUD.param.nPD}
};
return anchor;
};
// Font Settings
RS.HUD.param.chineseFont = String(parameters['Chinese Font'] || 'SimHei, Heiti TC, sans-serif');
RS.HUD.param.koreanFont = String(parameters['Korean Font'] || 'NanumGothic, Dotum, AppleGothic, sans-serif');
RS.HUD.param.standardFont = String(parameters['Standard Font'] || 'GameFont');
// Text Size
RS.HUD.param.levelTextSize = RS.HUD.loadRealNumber('Level Text Size', 12);
RS.HUD.param.hpTextSize = RS.HUD.loadRealNumber('HP Text Size', 12);
RS.HUD.param.mpTextSize = RS.HUD.loadRealNumber('MP Text Size', 12);
RS.HUD.param.expTextSize = RS.HUD.loadRealNumber('EXP Text Size', 12);
RS.HUD.param.nameTextSize = RS.HUD.loadRealNumber('Name Text Size', 12);
// Text Color
RS.HUD.param.szHpColor = String(parameters['HP Color'] || '#ffffff');
RS.HUD.param.szMpColor = String(parameters['MP Color'] || '#ffffff');
RS.HUD.param.szExpColor = String(parameters['EXP Color'] || '#ffffff');
RS.HUD.param.szLevelColor = String(parameters['Level Color'] || '#ffffff');
RS.HUD.param.szNameColor = String(parameters['Name Color'] || '#ffffff');
// Text Outline Color
RS.HUD.param.szHpOutlineColor = String(parameters['HP Outline Color'] || 'rgba(0, 0, 0, 0.5)');
RS.HUD.param.szMpOutlineColor = String(parameters['MP Outline Color'] || 'rgba(0, 0, 0, 0.5)');
RS.HUD.param.szExpOutlineColor = String(parameters['EXP Outline Color'] || 'rgba(0, 0, 0, 0.5)');
RS.HUD.param.szLevelOutlineColor = String(parameters['Level Outline Color'] || 'rgba(0, 0, 0, 0.5)');
RS.HUD.param.szNameOutlineColor = String(parameters['Name Outline Color'] || 'rgba(0, 0, 0, 0.5)');
// Text Outline Width
RS.HUD.param.szHpOutlineWidth = RS.HUD.loadRealNumber('HP Outline Width', 4);
RS.HUD.param.szMpOutlineWidth = RS.HUD.loadRealNumber('MP Outline Width', 4);
RS.HUD.param.szExpOutlineWidth = RS.HUD.loadRealNumber('EXP Outline Width', 4);
RS.HUD.param.szLevelOutlineWidth = RS.HUD.loadRealNumber('Level Outline Width', 4);
RS.HUD.param.szNameOutlineWidth = RS.HUD.loadRealNumber('Name Outline Width', 4);
// Custom Font
RS.HUD.param.bUseCustomFont = Boolean(parameters['Using Custom Font'] === 'true');
RS.HUD.param.szCustomFontName = String(parameters['Custom Font Name'] || 'GameFont' );
RS.HUD.param.szCustomFontSrc = String(parameters['Custom Font Src'] || 'fonts/mplus-1m-regular.ttf');
// Custom HUD Anchor
RS.HUD.param.ptCustormAnchor = [];
RS.HUD.param.isCurrentBattleShowUp = false;
RS.HUD.param.isPreviousShowUp = false;
RS.HUD.param.init = false;
PIXI.loader
.add("config", "img/rs_hud/config.json")
.load(onAssetsLoaded);
function onAssetsLoaded() {
RS.HUD.param.init = true;
};
RS.HUD.loadCustomPosition = function (szRE) {
var W = RS.HUD.param.nWidth;
var H = RS.HUD.param.nHeight;
var PD = RS.HUD.param.nPD;
var BW = Graphics.boxWidth || 816;
var BH = Graphics.boxHeight || 624;
var x = eval('[' + szRE + ']');
if(x instanceof Array) return new Point(x[0], x[1]);
return new Point(0, 0);
};
// Opacity and Tone Glitter Settings
var nOpacityEps = 5;
var nOpacityMin = 64;
var nFaceDiameter = 96;
var nHPGlitter = 0.4;
var nMPGlitter = 0.4;
var nEXPGlitter = 0.7;
var defaultTemplate = 'hud_default_template.json';
//----------------------------------------------------------------------------
// Data Imports & Exports
//
//
RS.HUD.localFilePath = function (fileName) {
if(!Utils.isNwjs()) return '';
var path, base;
path = require('path');
base = path.dirname(process.mainModule.filename);
return path.join(base, 'data/') + (fileName || defaultTemplate);
};
RS.HUD.exportData = function (fileName) {
var fs, data, filePath;
if(!Utils.isNwjs()) return false;
if(!RS.HUD.param) return false;
fs = require('fs');
data = JSON.stringify(RS.HUD.param);
filePath = RS.HUD.localFilePath(fileName);
fs.writeFile(filePath, data, 'utf8', function (err) {
if (err) throw err;
});
};
RS.HUD.loadData = function (data) {
var params = Object.keys(RS.HUD.param);
data = JSON.parse(data);
params.forEach(function (name) {
RS.HUD.param[name] = data[name];
}, this);
setTimeout(function () {
$gameTemp.notifyHudRefresh();
}, 0);
};
RS.HUD.importData = function (fileName) {
if(!Utils.isNwjs()) return false;
var fs = require('fs');
var filePath = RS.HUD.localFilePath(fileName);
var data = fs.readFileSync(filePath, { encoding: 'utf8' });
RS.HUD.loadData(data);
};
RS.HUD.importDataWithAjax = function (fileName) {
var xhr = new XMLHttpRequest();
var self = RS.HUD;
var url = './data/' + (fileName || defaultTemplate);
xhr.open('GET', url);
xhr.onload = function() {
if(xhr.status < 400) {
RS.HUD.loadData(xhr.responseText.slice(0));
}
}
xhr.send();
};
RS.HUD.loadPicture = function (filename) {
var bitmap = ImageManager.reservePicture(filename);
return bitmap;
};
RS.HUD.loadFace = function (filename) {
var bitmap = ImageManager.reserveFace(filename);
return bitmap;
};
//----------------------------------------------------------------------------
// Bitmap
//
//
Bitmap.prototype.drawClippingImage = function(bitmap, maskImage , _x, _y, _sx, _sy) {
var context = this._context;
context.save();
context.drawImage(maskImage._canvas, _x, _y, nFaceDiameter, nFaceDiameter);
context.globalCompositeOperation = 'source-atop';
context.drawImage(bitmap._canvas, _sx, _sy, 144, 144, 0, 0, nFaceDiameter, nFaceDiameter);
context.restore();
this._setDirty();
};
Bitmap.prototype.drawClippingImageNonBlur = function(bitmap, _x, _y, _sx, _sy) {
var context = this._context;
context.save();
context.beginPath();
context.arc(_x + 45, _y + 45 , 45, 0, Math.PI * 2, false);
context.clip();
context.drawImage(bitmap._canvas, _sx, _sy, 144, 144, 0, 0, nFaceDiameter, nFaceDiameter);
context.restore();
this._setDirty();
};
//----------------------------------------------------------------------------
// Game_Temp
//
//
Game_Temp.prototype.notifyHudTextRefresh = function() {
if($gameHud) $gameHud.updateText();
};
Game_Temp.prototype.notifyHudRefresh = function() {
if($gameHud) $gameHud.refresh();
};
//----------------------------------------------------------------------------
// Game_System ($gameSystem)
//
//
var _alias_Game_System_initialize = Game_System.prototype.initialize;
Game_System.prototype.initialize = function() {
_alias_Game_System_initialize.call(this);
this._rs_hud = this._rs_hud || {};
this._rs_hud.show = this._rs_hud.show || RS.HUD.param.bShow;
this._rs_hud.opacity = this._rs_hud.opacity || RS.HUD.param.nOpacity;
};
//----------------------------------------------------------------------------
// Game_Battler
//
//
var alias_Game_Battler_refresh = Game_Battler.prototype.refresh;
Game_Battler.prototype.refresh = function() {
alias_Game_Battler_refresh.call(this);
$gameTemp.notifyHudTextRefresh();
};
//----------------------------------------------------------------------------
// Game_Actor
//
//
Game_Actor.prototype.relativeExp = function () {
if(this.isMaxLevel()) {
return this.expForLevel(this.maxLevel());
} else {
return this.currentExp() - this.currentLevelExp();
}
};
Game_Actor.prototype.relativeMaxExp = function () {
if(!this.isMaxLevel()) {
return this.nextLevelExp() - this.currentLevelExp();
} else {
return this.expForLevel(this.maxLevel());
}
};
//----------------------------------------------------------------------------
// Game_Party
//
//
var alias_Game_Party_swapOrder = Game_Party.prototype.swapOrder;
Game_Party.prototype.swapOrder = function(index1, index2) {
alias_Game_Party_swapOrder.call(this, index1, index2);
$gameTemp.notifyHudRefresh();
};
//----------------------------------------------------------------------------
// TextData
//
//
function TextData() {
this.initialize.apply(this, arguments);
}
TextData.prototype = Object.create(Sprite.prototype);
TextData.prototype.constructor = TextData;
TextData.prototype.initialize = function(bitmap, func, params) {
Sprite.prototype.initialize.call(this, bitmap);
this.setCallbackFunction(func);
this.updateTextLog();
this._params = params;
this.requestUpdate();
};
TextData.prototype.setCallbackFunction = function (cbFunc) {
this._callbackFunction = cbFunc;
};
TextData.prototype.updateTextLog = function () {
this._log = this._callbackFunction.call();
};
TextData.prototype.startCallbackFunction = function () {
this._callbackFunction.call(this);
};
TextData.prototype.getTextProperties = function (n) {
return this._params[n];
};
TextData.prototype.drawDisplayText = function () {
this.defaultFontSettings();
this.bitmap.drawText(this._callbackFunction(this), 0, 0, 120, this._params[0] + 8, 'center');
};
TextData.prototype.isRefresh = function () {
var currentText = this._callbackFunction();
return currentText.localeCompare(this._log) !== 0;
};
TextData.prototype.clearTextData = function () {
this.bitmap.clear();
};
TextData.prototype.requestUpdate = function () {
this.clearTextData();
this.drawDisplayText();
this.updateTextLog();
};
TextData.prototype.standardFontFace = function() {
if(RS.HUD.param.bUseCustomFont) {
return RS.HUD.param.szCustomFontName;
} else {
if (navigator.language.match(/^zh/)) {
return RS.HUD.param.chineseFont;
} else if (navigator.language.match(/^ko/)) {
return RS.HUD.param.koreanFont;
} else {
return RS.HUD.param.standardFont;
}
}
};
TextData.prototype.defaultFontSettings = function() {
var param = this._params;
this.bitmap.fontFace = this.standardFontFace();
this.bitmap.fontSize = param[0];
this.bitmap.textColor = param[1];
this.bitmap.outlineColor = param[2];
this.bitmap.outlineWidth = param[3];
};
//----------------------------------------------------------------------------
// HUD
//
//
function HUD() {
this.initialize.apply(this, arguments);
};
//----------------------------------------------------------------------------
// RS_HudLayer
//
//
function RS_HudLayer() {
this.initialize.apply(this, arguments);
};
RS_HudLayer.prototype = Object.create(Sprite.prototype);
RS_HudLayer.prototype.constructor = RS_HudLayer;
RS_HudLayer.prototype.initialize = function(bitmap) {
Sprite.prototype.initialize.call(this, bitmap);
this.alpha = 0;
this.createItemLayer();
};
RS_HudLayer.prototype.createItemLayer = function () {
this._items = new Sprite();
this._items.setFrame(0, 0, Graphics.boxWidth, Graphics.boxHeight);
this.addChild(this._items);
};
RS_HudLayer.prototype.drawAllHud = function() {
var allHud = this._items;
var items = RS.HUD.param.arrangement;
// This removes any drawing objects that have already been created.
if(allHud.children.length > 0) {
allHud.removeChildren(0, allHud.children.length);
}
items.forEach(function(item, index){
// This code runs only when there is a party member at a specific index.
if(!!$gameParty.members()[index]) {
if(item !== null) allHud.addChild(new HUD({szAnchor: item, nIndex: index}));
}
}, this);
// It sorts objects by party number.
this.sort();
this.show = $gameSystem._rs_hud.show;
this.opacity = $gameSystem._rs_hud.opacity;
};
RS_HudLayer.prototype.update = function () {
var members = $gameParty.members();
this.children.forEach(function(child, idx) {
if (child.update && members[idx]) {
child.update();
}
});
};
RS_HudLayer.prototype.sort = function() {
var allHud = this._items;
var array = allHud.children;
allHud.children = array.sort(function(a, b) {
return a._memberIndex - b._memberIndex;
});
}
RS_HudLayer.prototype.refresh = function() {
var allHud = this._items;
allHud.children.forEach(function(i) {
allHud.removeChild(i);
}, this);
this.drawAllHud();
this.show = $gameSystem._rs_hud.show;
};
RS_HudLayer.prototype.updateText = function() {
var allHud = this._items;
allHud.children.forEach(function(i) {
i.updateText();
}, this);
};
RS_HudLayer.prototype.updateFrame = function () {
var allHud = this._items;
allHud.children.forEach(function(i) {
i.paramUpdate();
}, this);
};
RS_HudLayer.prototype.remove = function(index) {
var self = this;
setTimeout(function() {
while($gameParty.size() !== self._items.children.length) {
self.drawAllHud();
}
}, 0);
};
Object.defineProperty(RS_HudLayer.prototype, 'show', {
get: function() {
return this.visible;
},
set: function(value) {
this.visible = value;
$gameSystem._rs_hud.show = value;
},
});
Object.defineProperty(RS_HudLayer.prototype, 'opacity', {
get: function() {
return Math.floor(this.alpha * 255);
},
set: function(value) {
this.alpha = value * 0.00392156862745098;
$gameSystem._rs_hud.opacity = value.clamp(0, 255);
},
});
//----------------------------------------------------------------------------
// RS_EmptyHudLayer
//
//
function RS_EmptyHudLayer() {
this.initialize.apply(this, arguments);
}
RS_EmptyHudLayer.prototype = Object.create(Sprite.prototype);
RS_EmptyHudLayer.prototype.constructor = RS_EmptyHudLayer;
RS_EmptyHudLayer.prototype.initialize = function(bitmap) {
Sprite.prototype.initialize.call(this, bitmap);
this.alpha = 0;
};
RS_EmptyHudLayer.prototype.constructor = RS_EmptyHudLayer;
Object.defineProperty(RS_EmptyHudLayer.prototype, 'show', {
get: function() {
return $gameSystem._rs_hud.show;
},
set: function(value) {
$gameSystem._rs_hud.show = value;
}
});
Object.defineProperty(RS_EmptyHudLayer.prototype, 'opacity', {
get: function() {
return $gameSystem._rs_hud.opacity;
},
set: function(value) {
$gameSystem._rs_hud.opacity = value.clamp(0, 255);
}
});
//----------------------------------------------------------------------------
// HUD
//
//
HUD.prototype = Object.create(Stage.prototype);
HUD.prototype.constructor = HUD;
HUD.prototype.initialize = function(config) {
Stage.prototype.initialize.call(this);
this.createHud();
this.setAnchor(config.szAnchor || "LeftBottom");
this.setMemberIndex(parseInt(config.nIndex) || 0);
this.createFace();
this.createHp();
this.createMp();
this.createExp();
this.createText();
this.setPosition();
this.paramUpdate();
};
HUD.prototype.getAnchor = function(magnet) {
var anchor = RS.HUD.getDefaultHUDAnchor();
// Add Custom Anchor
for(var i = 0; i < RS.HUD.param.nMaxMembers; i++) {
var idx = parseInt(i + 1);
anchor['Custom Pos ' + idx] = RS.HUD.param.ptCustormAnchor[i];
}
return anchor[magnet];
};
HUD.prototype.setAnchor = function(anchor) {
var pos = this.getAnchor(anchor);
if(typeof(pos) === 'object') {
this._hud.x = pos.x;
this._hud.y = pos.y;
} else {
this.setAnchor(RS.HUD.param.szAnchor);
}
};
HUD.prototype.setMemberIndex = function(index) {
this._memberIndex = index;
};
HUD.prototype.fromImage = function(textureName) {
var texture = PIXI.utils.TextureCache[textureName + ".png"];
var sprite = new PIXI.Sprite(texture);
return sprite;
};
HUD.prototype.createHud = function() {
this._hud = this.fromImage(RS.HUD.param.imgEmptyHUD);
this.addChild(this._hud);
};
HUD.prototype.createFace = function() {
var player = this.getPlayer();
if(Imported["SumRndmDde Character Creator EX"]) {
if(player.hasSetImage()) {
this._faceBitmap = player.getCreatorBitmapFace();
} else {
this._faceBitmap = RS.HUD.loadFace(player.faceName());
}
} else {
this._faceBitmap = RS.HUD.loadFace(player.faceName());
}
this._maskBitmap = RS.HUD.loadPicture(RS.HUD.param.imgMasking);
this._maskBitmap.addLoadListener(function() {
this._faceBitmap.addLoadListener(this.circleClippingMask.bind(this, player.faceIndex()));
}.bind(this));
};
HUD.prototype.circleClippingMask = function(faceIndex) {
this._face = new Sprite();
var fw = Window_Base._faceWidth;
var fh = Window_Base._faceHeight;
var sx = (faceIndex % 4) * fw;
var sy = Math.floor(faceIndex / 4) * fh;
this._face.bitmap = new Bitmap(nFaceDiameter, nFaceDiameter);
if (RS.HUD.param.blurProcessing) {
this._face.bitmap.drawClippingImage(this._faceBitmap, this._maskBitmap, 0, 0, sx, sy);
} else {
this._face.bitmap.drawClippingImageNonBlur(this._faceBitmap, 0, 0, sx, sy);
}
this.addChild(this._face);
this.setCoord(this._face, RS.HUD.param.ptFace);
};
HUD.prototype.createMask = function (parent) {
var mask = new PIXI.Graphics();
mask.beginFill(0x0000ff, 1.0);
mask.drawRect(0,0, parent.width, parent.height);
mask.endFill();
parent.mask = mask;
return mask;
};
HUD.prototype.createHp = function() {
this._hp = this.fromImage(RS.HUD.param.imgHP);
this._hpMask = this.createMask(this._hp);
this.addChild(this._hpMask, this._hp);
};
HUD.prototype.createMp = function() {
this._mp = this.fromImage(RS.HUD.param.imgMP);
this._mpMask = this.createMask(this._mp);
this.addChild(this._mpMask, this._mp);
};
HUD.prototype.createExp = function() {
this._exp = this.fromImage(RS.HUD.param.imgEXP);
this._expMask = this.createMask(this._exp);
this.addChild(this._expMask, this._exp);
};
HUD.prototype.getTextParams = function(src) {
var param = RS.HUD.param;
var textProperties = {
'HP': [param.hpTextSize, param.szHpColor, param.szHpOutlineColor, param.szHpOutlineWidth],
'MP': [param.mpTextSize, param.szMpColor, param.szMpOutlineColor, param.szMpOutlineWidth],
'EXP': [param.expTextSize, param.szExpColor, param.szExpOutlineColor, param.szExpOutlineWidth],
'LEVEL': [param.levelTextSize, param.szLevelColor, param.szLevelOutlineColor, param.szLevelOutlineWidth],
'NAME': [param.nameTextSize, param.szNameColor, param.szNameOutlineColor, param.szNameOutlineWidth]
};
return textProperties[src];
};
HUD.prototype.createText = function() {
this._hpText = this.addText(this.getHp.bind(this), this.getTextParams('HP'));
this._mpText = this.addText(this.getMp.bind(this), this.getTextParams('MP'));
this._expText = this.addText(this.getExp.bind(this), this.getTextParams('EXP'));
this._levelText = this.addText(this.getLevel.bind(this), this.getTextParams('LEVEL'));
this._nameText = this.addText(this.getName.bind(this), this.getTextParams('NAME'));
};
HUD.prototype.setPosition = function() {
var param = RS.HUD.param;
if(this._face) this.setCoord(this._face, param.ptFace);
this.setCoord(this._hpMask, param.ptHP);
this.setCoord(this._hp, param.ptHP);
this.setCoord(this._mpMask, param.ptMP);
this.setCoord(this._mp, param.ptMP);
this.setCoord(this._expMask, param.ptEXP);
this.setCoord(this._exp, param.ptEXP);
this.setCoord(this._hpText, param.ptHPText);
this.setCoord(this._mpText, param.ptMPText);
this.setCoord(this._levelText, param.ptLevelText);
this.setCoord(this._expText, param.ptEXPText);
this.setCoord(this._nameText, param.ptNameText);
};
HUD.prototype.addText = function(strFunc, params) {
var bitmap = new Bitmap(120, params[0] + 8);
var text = new TextData(bitmap, strFunc, params);
var length = this.children.length;
this.addChildAt(text, length);
text.drawDisplayText();
return text;
};
HUD.prototype.getPlayer = function() {
return $gameParty.members()[this._memberIndex];
};
HUD.prototype.getHp = function() {
var player = this.getPlayer();
if(!player) return "0 / 0";
if(RS.HUD.param.showComma) {
return "%1 / %2".appendComma(player.hp, player.mhp);
} else {
return "%1 / %2".format(player.hp, player.mhp);
}
};
HUD.prototype.getMp = function() {
var player = this.getPlayer();
if(!player) return "0 / 0";
if(RS.HUD.param.showComma) {
return "%1 / %2".appendComma(player.mp, player.mmp);
} else {
return "%1 / %2".format(player.mp, player.mmp);
}
};
HUD.prototype.getExp = function() {
var player = this.getPlayer();
if(!player) return "0 / 0";
if(player.isMaxLevel()) return RS.HUD.param.maxExpText;
if(RS.HUD.param.showComma) {
return "%1 / %2".appendComma(player.relativeExp(), player.relativeMaxExp());
} else {
return "%1 / %2".format(player.relativeExp(), player.relativeMaxExp());
}
};
HUD.prototype.getLevel = function() {
var player = this.getPlayer();
if(!player) return "0";
if(RS.HUD.param.showComma) {
return "%1".appendComma(player.level);
} else {
return "%1".format(player.level);
}
};
HUD.prototype.getName = function() {
var player = this.getPlayer();
if(!player) return "";
var name = player && player.name();
if(name) {
return name;
} else {
return ' ';
}
};
HUD.prototype.getHpRate = function() {
var player = this.getPlayer();
if(!player) return 0;
return this._hp.width * (player.hp / player.mhp);
};
HUD.prototype.getMpRate = function() {
var player = this.getPlayer();
if(!player) return 0;
return this._mp.width * (player.mp / player.mmp);
};
HUD.prototype.getExpRate = function() {
var player = this.getPlayer();
if(!player) return 0;
return this._exp.width * (player.relativeExp() / player.relativeMaxExp());
};
HUD.prototype.getRealExpRate = function () {
var player = this.getPlayer();
if(!player) return 0;
if(this.inBattle() && $dataSystem.optDisplayTp) {
return ( player.tp / player.maxTp() );
} else {
return ( player.relativeExp() / player.relativeMaxExp() );
}
};
HUD.prototype.setCoord = function(s,obj) {
var oy = (s._callbackFunction instanceof Function) ? (s.bitmap.height / 2) : 0;
s.x = this._hud.x + obj.x;
s.y = this._hud.y + obj.y - oy;
s.visible = obj.visible;
};
HUD.prototype.update = function() {
this.paramUpdate();
};
HUD.prototype.updateText = function() {
this._hpText.requestUpdate();
this._mpText.requestUpdate();
this._expText.requestUpdate();
this._levelText.requestUpdate();
this._nameText.requestUpdate();
};
HUD.prototype.updateGuage = function (mask, w, h) {
if(!mask) return;
mask.clear();
mask.beginFill(0x0000ff, 1.0);
mask.drawRect(0,0, w, h);
mask.endFill();
};
HUD.prototype.paramUpdate = function() {
this.updateGuage(this._hpMask, this.getHpRate(), this._hp.height);
this.updateGuage(this._mpMask, this.getMpRate(), this._mp.height);
this.updateGuage(this._expMask, this.getExpRate(), this._exp.height);
};
HUD.prototype.inBattle = function() {
return (SceneManager._scene instanceof Scene_Battle ||
$gameParty.inBattle() ||
DataManager.isBattleTest());
};
Object.defineProperty(HUD.prototype, 'show', {
get: function() {
return $gameSystem._rs_hud.show;
},
set: function(value) {
this.children.forEach( function(i) {
i.visible = value;
}, this);
$gameSystem._rs_hud.show = value;
if(value === true) {
this.setPosition();
}
},
});
Object.defineProperty(HUD.prototype, 'opacity', {
get: function() {
return $gameSystem._rs_hud.opacity;
},
set: function(value) {
this.children.forEach( function(i) {
i.opacity = value.clamp(0, 255);
}, this);
$gameSystem._rs_hud.opacity = value.clamp(0, 255);
},
});
//----------------------------------------------------------------------------
// Scene_Map
//
//
var alias_Scene_Map_createDisplayObjects = Scene_Map.prototype.createDisplayObjects;
Scene_Map.prototype.createDisplayObjects = function() {
alias_Scene_Map_createDisplayObjects.call(this);
if(RS.HUD.param.battleOnly || ($dataMap && $dataMap.meta.DISABLE_HUD) ) {
$gameHud = new RS_EmptyHudLayer();
} else {
this._hudLayer = new RS_HudLayer();
this._hudLayer.setFrame(0, 0, Graphics.boxWidth, Graphics.boxHeight);
$gameHud = this._hudLayer;
this._hudLayer.drawAllHud();
this.addChild(this._hudLayer);
this.swapChildren(this._windowLayer, this._hudLayer);
}
};
var alias_Scene_Map_start = Scene_Map.prototype.start;
Scene_Map.prototype.start = function () {
alias_Scene_Map_start.call(this);
$gameTemp.notifyHudTextRefresh();
};
var alias_Scene_Map_terminate = Scene_Map.prototype.terminate;
Scene_Map.prototype.terminate = function() {
this.removeChild(this._hudLayer);
$gameHud = null;
alias_Scene_Map_terminate.call(this);
};
//----------------------------------------------------------------------------
// Game_Party
//
//
var alias_Game_Party_addActor = Game_Party.prototype.addActor;
Game_Party.prototype.addActor = function(actorId) {
alias_Game_Party_addActor.call(this, actorId);
$gameTemp.notifyHudRefresh();
};
var alias_Game_Party_removeActor = Game_Party.prototype.removeActor;
Game_Party.prototype.removeActor = function(actorId) {
alias_Game_Party_removeActor.call(this, actorId);
$gameTemp.notifyHudRefresh();
};
//----------------------------------------------------------------------------
// Scene_Boot
//
//
var alias_Scene_Boot_loadSystemWindowImage = Scene_Boot.prototype.loadSystemWindowImage;
Scene_Boot.prototype.loadSystemWindowImage = function() {
alias_Scene_Boot_loadSystemWindowImage.call(this);
// Load Face
RS.HUD.param.preloadImportantFaces.forEach(function(i) {
if(Utils.RPGMAKER_VERSION >= '1.5.0') {
ImageManager.reserveFace(i)
} else {
ImageManager.loadFace(i);
}
}, this);
if(Utils.RPGMAKER_VERSION >= '1.5.0') {
ImageManager.reservePicture(RS.HUD.param.imgHP);
ImageManager.reservePicture(RS.HUD.param.imgMP);
ImageManager.reservePicture(RS.HUD.param.imgEXP);
}
};
var alias_Scene_Boot_start = Scene_Boot.prototype.start;
Scene_Boot.prototype.start = function() {
alias_Scene_Boot_start.call(this);
// Load Custom Anchor
for(var i = 0; i < RS.HUD.param.nMaxMembers; i++) {
RS.HUD.param.ptCustormAnchor.push( RS.HUD.loadCustomPosition(parameters[String('Custom Pos ' + (i + 1))] || '0, 0') );
}
// Load Custom Font
if(RS.HUD.param.bUseCustomFont) {
Graphics.loadFont(RS.HUD.param.szCustomFontName, RS.HUD.param.szCustomFontSrc);
}
};
//----------------------------------------------------------------------------
// Scene_Map
//
//
var alias_Scene_Map_snapForBattleBackground = Scene_Map.prototype.snapForBattleBackground;
Scene_Map.prototype.snapForBattleBackground = function() {
var temp = $gameHud.show;
if($gameHud && $gameHud.show) $gameHud.show = false;
alias_Scene_Map_snapForBattleBackground.call(this);
if($gameHud && !$gameHud.show) {
RS.HUD.param.isPreviousShowUp = temp;
$gameHud.show = temp;
}
};
var alias_Scene_Map_updateFade = Scene_Map.prototype.updateFade;
Scene_Map.prototype.updateFade = function() {
alias_Scene_Map_updateFade.call(this);
if(this._fadeDuration == 0 && RS.HUD.param.isCurrentBattleShowUp) {
if($gameHud) $gameHud.show = RS.HUD.param.isPreviousShowUp;
RS.HUD.param.isCurrentBattleShowUp = false;
}
};
var alias_Scene_Battle_updateFade = Scene_Battle.prototype.updateFade;
Scene_Battle.prototype.updateFade = function() {
alias_Scene_Battle_updateFade.call(this);
if(this._fadeDuration == 0 && !RS.HUD.param.isCurrentBattleShowUp) {
if($gameHud) $gameHud.show = true;
RS.HUD.param.isCurrentBattleShowUp = true;
}
};
//----------------------------------------------------------------------------
// Game_Interpreter
//
//
var alias_Game_Interpreter_pluginCommand = Game_Interpreter.prototype.pluginCommand;
Game_Interpreter.prototype.pluginCommand = function(command, args) {
alias_Game_Interpreter_pluginCommand.call(this, command, args);
if(command === "RS_HUD") {
switch (args[0].toLowerCase()) {
case 'opacity':
$gameHud.opacity = Number(args[1]);
break;
case 'visible':
$gameHud.show = Boolean(args[1] === "true");
break;
case 'import':
RS.HUD.importDataWithAjax(args[1] + '.json');
break;
case 'export':
RS.HUD.exportData(args[1] + '.json');
break;
}
}
};
//----------------------------------------------------------------------------
// String Utils
//
//
/**
* String.prototype.toArray
*/
String.prototype.toArray = function(){
return this.split("");
}
/**
* String.prototype.reverse
*/
String.prototype.reverse = function(){
return this.toArray().reverse().join("");
}
/**
* String.prototype.toComma
*/
String.prototype.toComma = function(){
return this.reverse().match(/.{1,3}/g).join(",").reverse();
}
/**
* Replaces %1, %2 and so on in the string to the arguments.
*
* @method String.prototype.format
* @param {Any} ...args The objects to format
* @return {String} A formatted string
*/
String.prototype.appendComma = function() {
var args = arguments;
return this.replace(/%([0-9]+)/g, function(s, n) {
return (args[Number(n) - 1] + '').toComma();
});
};
//============================================================================
// Scene_Boot
//============================================================================
var alias_Scene_Boot_isReady = Scene_Boot.prototype.isReady;
Scene_Boot.prototype.isReady = function() {
if(alias_Scene_Boot_isReady.call(this)) {
return RS.HUD.param.init;
} else {
return false;
}
};
//----------------------------------------------------------------------------
// Output Objects
//
//
window.HUD = HUD;
window.RS_HudLayer = RS_HudLayer;
})();
|
var fs = require('fs');
var path = require('path');
var gulp = require('gulp');
var sass = require('gulp-sass');
// Load all gulp plugins automatically
// and attach them to the `plugins` object
var plugins = require('gulp-load-plugins')();
// Temporary solution until gulp 4
// https://github.com/gulpjs/gulp/issues/355
var runSequence = require('run-sequence');
var pkg = require('./package.json');
var dirs = pkg['h5bp-configs'].directories;
// ---------------------------------------------------------------------
// | Helper tasks |
// ---------------------------------------------------------------------
gulp.task('archive:create_archive_dir', function () {
fs.mkdirSync(path.resolve(dirs.archive), '0755');
});
gulp.task('archive:zip', function (done) {
var archiveName = path.resolve(dirs.archive, pkg.name + '_v' + pkg.version + '.zip');
var archiver = require('archiver')('zip');
var files = require('glob').sync('**/*.*', {
'cwd': dirs.dist,
'dot': true // include hidden files
});
var output = fs.createWriteStream(archiveName);
archiver.on('error', function (error) {
done();
throw error;
});
output.on('close', done);
files.forEach(function (file) {
var filePath = path.resolve(dirs.dist, file);
// `archiver.bulk` does not maintain the file
// permissions, so we need to add files individually
archiver.append(fs.createReadStream(filePath), {
'name': file,
'mode': fs.statSync(filePath)
});
});
archiver.pipe(output);
archiver.finalize();
});
gulp.task('clean', function (done) {
require('del')([
dirs.archive,
dirs.dist
], done);
});
gulp.task('copy', [
'copy:.htaccess',
'copy:index.html',
'copy:jquery',
'copy:license',
'copy:main.css',
'copy:misc',
'copy:normalize'
]);
gulp.task('copy:.htaccess', function () {
return gulp.src('node_modules/apache-server-configs/dist/.htaccess')
.pipe(plugins.replace(/# ErrorDocument/g, 'ErrorDocument'))
.pipe(gulp.dest(dirs.dist));
});
gulp.task('copy:index.html', function () {
return gulp.src(dirs.src + '/index.html')
.pipe(plugins.replace(/{{JQUERY_VERSION}}/g, pkg.devDependencies.jquery))
.pipe(gulp.dest(dirs.dist));
});
gulp.task('copy:jquery', function () {
return gulp.src(['node_modules/jquery/dist/jquery.min.js'])
.pipe(plugins.rename('jquery-' + pkg.devDependencies.jquery + '.min.js'))
.pipe(gulp.dest(dirs.dist + '/js/vendor'));
});
gulp.task('copy:license', function () {
return gulp.src('LICENSE.txt')
.pipe(gulp.dest(dirs.dist));
});
gulp.task('copy:main.css', function () {
var banner = '/*! HTML5 Boilerplate v' + pkg.version +
' | ' + pkg.license.type + ' License' +
' | ' + pkg.homepage + ' */\n\n';
return gulp.src(dirs.src + '/css/main.css')
.pipe(plugins.header(banner))
.pipe(plugins.autoprefixer({
browsers: ['last 2 versions', 'ie >= 8', '> 1%'],
cascade: false
}))
.pipe(gulp.dest(dirs.dist + '/css'));
});
gulp.task('copy:misc', function () {
return gulp.src([
// Copy all files
dirs.src + '/**/*',
// Exclude the following files
// (other tasks will handle the copying of these files)
'!' + dirs.src + '/css/main.css',
'!' + dirs.src + '/css/*.css.map',
'!' + dirs.src + '/index.html',
'!' + dirs.src + '/styles/**/*',
'!' + dirs.src + '/js/util/**/*',
'!' + dirs.src + '/js/.DS_Store',
'!' + dirs.src + '/js/util',
'!' + dirs.src + '/styles'
], {
// Include hidden files by default
dot: true
}).pipe(gulp.dest(dirs.dist));
});
gulp.task('copy:normalize', function () {
return gulp.src('node_modules/normalize.css/normalize.css')
.pipe(gulp.dest(dirs.dist + '/css'));
});
gulp.task('lint:js', function () {
return gulp.src([
'gulpfile.js',
dirs.src + '/js/*.js',
dirs.test + '/*.js'
])//.pipe(plugins.jscs())
//.pipe(plugins.jshint())
.pipe(plugins.jshint.reporter('jshint-stylish'))
.pipe(plugins.jshint.reporter('fail'));
});
gulp.task('sass', function () {
return gulp.src('./styles/scss/*.scss')
.pipe(sass())
.pipe(gulp.dest('./css'));
});
/*gulp.task('scripts', function(){
gulp.src('./js/!*.js')
.pipe(concat('all.js'))
.pipe(gulp.dest('./dist'))
.pipe(rename('all.min.js'))
.pipe(uglify())
.pipe(gulp.dest('./dist'));
});*/
// ---------------------------------------------------------------------
// | Main tasks |
// ---------------------------------------------------------------------
gulp.task('archive', function (done) {
runSequence(
'build',
'archive:create_archive_dir',
'archive:zip',
done);
});
gulp.task('build', function (done) {
runSequence(
['clean', 'lint:js'],
'copy',
done);
});
gulp.task('default', ['archive']);
gulp.task('default', function () {
gulp.run('archive');
gulp.watch(['./styles/scss/!*.scss'], function () {
gulp.run('sass');
});
});
|
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
define([], factory);
} else if (typeof module === 'object' && module.exports) {
module.exports = factory();
} else {
root.C = factory();
}
}(this, function () {
function runAndWaitOn(func) {
return function (value) {
var handlerRes = func(value);
if (handlerRes && typeof handlerRes.then === 'function') {
return handlerRes.then(function() {
return value;
});
}
return value;
};
}
function C (handler, optionalPromise, onFulfilled, onRejected){
var promise = optionalPromise ? optionalPromise.then(wrap(onFulfilled), wrap(onRejected)) : new Promise(handler);
var _u = this;
function wrap(func){
return typeof func === 'function' ? function() {
var res = func.apply(undefined, arguments);
if (res === _u) {
throw new TypeError('promise resolution value can`t be promise itself')
}
return res;
} : undefined;
}
function _catch(){
var handler;
var constructor;
switch (arguments.length) {
case 2:
constructor = arguments[0];
handler = arguments[1];
break;
case 1:
handler = arguments[0];
break;
default:
throw new TypeError('Usage: .catch(constructor, handler) or .catch(handler)');
}
return new C(null, promise, null, function (val) {
var shouldBeCaught = typeof constructor === 'undefined' || val instanceof constructor;
if (shouldBeCaught) {
return handler.apply(this, arguments);
}
throw val;
});
}
function _finally(func) {
return new C(null, promise, runAndWaitOn(func), runAndWaitOn(func));
}
function _spread(func) {
return new C(null, promise, function (arr) {
if (!Array.isArray(arr)) {
return func.call(null, arr);
}
return func.apply(null, arr);
});
}
function _then(onFulfilled, onRejected) {
return new C(null, promise, onFulfilled, onRejected);
}
function tap(func) {
return new C(null, promise, runAndWaitOn(func));
}
Object.defineProperties(this, {
catch: {
value: _catch
},
finally: {
value: _finally
},
spread: {
value: _spread
},
tap: {
value: tap
},
then: {
value: _then
}
});
}
C.resolve = function resolve(value) {
return new C(function (resolve) {
resolve(value);
});
}
C.reject = function reject(value) {
return new C(function (resolve, reject) {
reject(value);
});
}
C.all = function all(arr) {
return C.resolve(Promise.all(arr));
}
return C;
}));
|
'use strict';
var expect = require('chai').expect;
var ember = require('ember-cli/tests/helpers/ember');
var MockUI = require('ember-cli/tests/helpers/mock-ui');
var MockAnalytics = require('ember-cli/tests/helpers/mock-analytics');
var Command = require('ember-cli/lib/models/command');
var Task = require('ember-cli/lib/models/task');
var Promise = require('ember-cli/lib/ext/promise');
var RSVP = require('rsvp');
var fs = require('fs-extra');
var path = require('path');
var exec = Promise.denodeify(require('child_process').exec);
var remove = Promise.denodeify(fs.remove);
var ensureFile = Promise.denodeify(fs.ensureFile);
var root = process.cwd();
var tmp = require('tmp-sync');
var tmproot = path.join(root, 'tmp');
var MoveCommandBase = require('../../../lib/commands/move');
describe('move command', function() {
var ui;
var tasks;
var analytics;
var project;
var fakeSpawn;
var CommandUnderTest;
var buildTaskCalled;
var buildTaskReceivedProject;
var tmpdir;
before(function() {
CommandUnderTest = Command.extend(MoveCommandBase);
});
beforeEach(function() {
buildTaskCalled = false;
ui = new MockUI();
analytics = new MockAnalytics();
tasks = {
Build: Task.extend({
run: function() {
buildTaskCalled = true;
buildTaskReceivedProject = !!this.project;
return RSVP.resolve();
}
})
};
project = {
isEmberCLIProject: function() {
return true;
}
};
});
function setupGit() {
return exec('git --version')
.then(function(){
return exec('git rev-parse --is-inside-work-tree', { encoding: 'utf8' })
.then(function(result) {
console.log('result',result)
return;
// return exec('git init');
})
.catch(function(e){
return exec('git init');
});
});
}
function generateFile(path) {
return ensureFile(path);
}
function addFileToGit(path) {
return ensureFile(path)
.then(function() {
return exec('git add .');
});
}
function addFilesToGit(files) {
var filesToAdd = files.map(addFileToGit);
return RSVP.all(filesToAdd);
}
function setupForMove() {
return setupTmpDir()
// .then(setupGit)
.then(addFilesToGit.bind(null,['foo.js','bar.js']));
}
function setupTmpDir() {
return Promise.resolve()
.then(function(){
tmpdir = tmp.in(tmproot);
process.chdir(tmpdir);
return tmpdir;
});
}
function cleanupTmpDir() {
return Promise.resolve()
.then(function(){
process.chdir(root);
return remove(tmproot);
});
}
/*
afterEach(function() {
process.chdir(root);
return remove(tmproot);
});
*/
/*
//TODO: fix so this isn't moving the fixtures
it('smoke test', function() {
return new CommandUnderTest({
ui: ui,
analytics: analytics,
project: project,
environment: { },
tasks: tasks,
settings: {},
runCommand: function(command, args) {
expect.deepEqual(args, ['./tests/fixtures/smoke-test/foo.js', './tests/fixtures/smoke-test/bar.js']);
}
}).validateAndRun(['./tests/fixtures/smoke-test/foo.js', './tests/fixtures/smoke-test/bar.js']);
});
*/
it('exits for unversioned file', function() {
return setupTmpDir()
.then(function(){
fs.writeFileSync('foo.js','foo');
return new CommandUnderTest({
ui: ui,
analytics: analytics,
project: project,
environment: { },
tasks: tasks,
settings: {},
runCommand: function(command, args) {
expect.deepEqual(args, ['nope.js']);
}
}).validateAndRun(['nope.js']).then(function() {
expect(ui.output).to.include('nope.js');
expect(ui.output).to.include('The source path: nope.js does not exist.');
});
})
.then(cleanupTmpDir);
});
it('can move a file', function() {
return setupForMove().
then(function(result) {
console.log('result',result);
return new CommandUnderTest({
ui: ui,
analytics: analytics,
project: project,
environment: { },
tasks: tasks,
settings: {},
runCommand: function(command, args) {
expect.deepEqual(args, ['foo.js', 'foo-bar.js']);
}
}).validateAndRun(['foo.js', 'foo-bar.js']).then(function() {
expect(ui.output).to.include('foo.js');
// expect(ui.output).to.include('The source path: nope.js does not exist.');
});
})
.then(cleanupTmpDir);
});
}); |
/*!
* Jade - Parser
* Copyright(c) 2010 TJ Holowaychuk <[email protected]>
* MIT Licensed
*/
/**
* Module dependencies.
*/
var Lexer = require('./lexer')
, nodes = require('./nodes');
/**
* Initialize `Parser` with the given input `str` and `filename`.
*
* @param {String} str
* @param {String} filename
* @param {Object} options
* @api public
*/
var Parser = exports = module.exports = function Parser(str, filename, options){
this.input = str;
this.lexer = new Lexer(str, options);
this.filename = filename;
};
/**
* Tags that may not contain tags.
*/
var textOnly = exports.textOnly = ['code', 'script', 'textarea', 'style', 'title'];
/**
* Parser prototype.
*/
Parser.prototype = {
/**
* Return the next token object.
*
* @return {Object}
* @api private
*/
advance: function(){
return this.lexer.advance();
},
/**
* Skip `n` tokens.
*
* @param {Number} n
* @api private
*/
skip: function(n){
while (n--) this.advance();
},
/**
* Single token lookahead.
*
* @return {Object}
* @api private
*/
peek: function() {
return this.lookahead(1);
},
/**
* Return lexer lineno.
*
* @return {Number}
* @api private
*/
line: function() {
return this.lexer.lineno;
},
/**
* `n` token lookahead.
*
* @param {Number} n
* @return {Object}
* @api private
*/
lookahead: function(n){
return this.lexer.lookahead(n);
},
/**
* Parse input returning a string of js for evaluation.
*
* @return {String}
* @api public
*/
parse: function(){
var block = new nodes.Block;
block.line = this.line();
while ('eos' != this.peek().type) {
if ('newline' == this.peek().type) {
this.advance();
} else {
block.push(this.parseExpr());
}
}
return block;
},
/**
* Expect the given type, or throw an exception.
*
* @param {String} type
* @api private
*/
expect: function(type){
if (this.peek().type === type) {
return this.advance();
} else {
throw new Error('expected "' + type + '", but got "' + this.peek().type + '"');
}
},
/**
* Accept the given `type`.
*
* @param {String} type
* @api private
*/
accept: function(type){
if (this.peek().type === type) {
return this.advance();
}
},
/**
* tag
* | doctype
* | mixin
* | include
* | filter
* | comment
* | text
* | each
* | code
* | id
* | class
*/
parseExpr: function(){
switch (this.peek().type) {
case 'tag':
return this.parseTag();
case 'mixin':
return this.parseMixin();
case 'include':
return this.parseInclude();
case 'doctype':
return this.parseDoctype();
case 'filter':
return this.parseFilter();
case 'comment':
return this.parseComment();
case 'text':
return this.parseText();
case 'each':
return this.parseEach();
case 'code':
return this.parseCode();
case 'id':
case 'class':
var tok = this.advance();
this.lexer.defer(this.lexer.tok('tag', 'div'));
this.lexer.defer(tok);
return this.parseExpr();
default:
throw new Error('unexpected token "' + this.peek().type + '"');
}
},
/**
* Text
*/
parseText: function(){
var tok = this.expect('text')
, node = new nodes.Text(tok.val);
node.line = this.line();
return node;
},
/**
* code
*/
parseCode: function(){
var tok = this.expect('code')
, node = new nodes.Code(tok.val, tok.buffer, tok.escape)
, block
, i = 1;
node.line = this.line();
while (this.lookahead(i) && 'newline' == this.lookahead(i).type) ++i;
block = 'indent' == this.lookahead(i).type;
if (block) {
this.skip(i-1);
node.block = this.parseBlock();
}
return node;
},
/**
* comment
*/
parseComment: function(){
var tok = this.expect('comment')
, node;
if ('indent' == this.peek().type) {
node = new nodes.BlockComment(tok.val, this.parseBlock(), tok.buffer);
} else {
node = new nodes.Comment(tok.val, tok.buffer);
}
node.line = this.line();
return node;
},
/**
* doctype
*/
parseDoctype: function(){
var tok = this.expect('doctype')
, node = new nodes.Doctype(tok.val);
node.line = this.line();
return node;
},
/**
* filter attrs? text-block
*/
parseFilter: function(){
var block
, tok = this.expect('filter')
, attrs = this.accept('attrs');
this.lexer.pipeless = true;
block = this.parseTextBlock();
this.lexer.pipeless = false;
var node = new nodes.Filter(tok.val, block, attrs && attrs.attrs);
node.line = this.line();
return node;
},
/**
* tag ':' attrs? block
*/
parseASTFilter: function(){
var block
, tok = this.expect('tag')
, attrs = this.accept('attrs');
this.expect(':');
block = this.parseBlock();
var node = new nodes.Filter(tok.val, block, attrs && attrs.attrs);
node.line = this.line();
return node;
},
/**
* each block
*/
parseEach: function(){
var tok = this.expect('each')
, node = new nodes.Each(tok.code, tok.val, tok.key, this.parseBlock());
node.line = this.line();
return node;
},
/**
* include
*/
parseInclude: function(){
var path = require('path')
, fs = require('fs')
, dirname = path.dirname
, basename = path.basename
, join = path.join;
if (!this.filename)
throw new Error('the "filename" option is required to use includes');
var path = name = this.expect('include').val.trim()
, dir = dirname(this.filename);
// non-jade
if (~basename(path).indexOf('.')) {
var path = join(dir, path)
, str = fs.readFileSync(path, 'utf8');
return new nodes.Literal(str);
}
var path = join(dir, path + '.jade')
, str = fs.readFileSync(path, 'utf8')
, parser = new Parser(str, path)
, ast = parser.parse();
return ast;
},
/**
* mixin block
*/
parseMixin: function(){
var tok = this.expect('mixin')
, name = tok.val
, args = tok.args;
var block = 'indent' == this.peek().type
? this.parseBlock()
: null;
return new nodes.Mixin(name, args, block);
},
/**
* indent (text | newline)* outdent
*/
parseTextBlock: function(){
var text = new nodes.Text;
text.line = this.line();
var spaces = this.expect('indent').val;
if (null == this._spaces) this._spaces = spaces;
var indent = Array(spaces - this._spaces + 1).join(' ');
while ('outdent' != this.peek().type) {
switch (this.peek().type) {
case 'newline':
text.push('\\n');
this.advance();
break;
case 'indent':
text.push('\\n');
this.parseTextBlock().nodes.forEach(function(node){
text.push(node);
});
text.push('\\n');
break;
default:
text.push(indent + this.advance().val);
}
}
if (spaces == this._spaces) this._spaces = null;
this.expect('outdent');
return text;
},
/**
* indent expr* outdent
*/
parseBlock: function(){
var block = new nodes.Block;
block.line = this.line();
this.expect('indent');
while ('outdent' != this.peek().type) {
if ('newline' == this.peek().type) {
this.advance();
} else {
block.push(this.parseExpr());
}
}
this.expect('outdent');
return block;
},
/**
* tag (attrs | class | id)* (text | code | ':')? newline* block?
*/
parseTag: function(){
// ast-filter look-ahead
var i = 2;
if ('attrs' == this.lookahead(i).type) ++i;
if (':' == this.lookahead(i).type) {
if ('indent' == this.lookahead(++i).type) {
return this.parseASTFilter();
}
}
var name = this.advance().val
, tag = new nodes.Tag(name);
tag.line = this.line();
// (attrs | class | id)*
out:
while (true) {
switch (this.peek().type) {
case 'id':
case 'class':
var tok = this.advance();
tag.setAttribute(tok.type, "'" + tok.val + "'");
continue;
case 'attrs':
var obj = this.advance().attrs
, names = Object.keys(obj);
for (var i = 0, len = names.length; i < len; ++i) {
var name = names[i]
, val = obj[name];
tag.setAttribute(name, val);
}
continue;
default:
break out;
}
}
// check immediate '.'
if ('.' == this.peek().val) {
tag.textOnly = true;
this.advance();
}
// (text | code | ':')?
switch (this.peek().type) {
case 'text':
tag.text = this.parseText();
break;
case 'code':
tag.code = this.parseCode();
break;
case ':':
this.advance();
tag.block = new nodes.Block;
tag.block.push(this.parseTag());
break;
}
// newline*
while ('newline' == this.peek().type) this.advance();
tag.textOnly = tag.textOnly || ~textOnly.indexOf(tag.name);
// script special-case
if ('script' == tag.name) {
var type = tag.getAttribute('type');
if (type && 'text/javascript' != type.replace(/^['"]|['"]$/g, '')) {
tag.textOnly = false;
}
}
// block?
if ('indent' == this.peek().type) {
if (tag.textOnly) {
this.lexer.pipeless = true;
tag.block = this.parseTextBlock();
this.lexer.pipeless = false;
} else {
var block = this.parseBlock();
if (tag.block) {
for (var i = 0, len = block.nodes.length; i < len; ++i) {
tag.block.push(block.nodes[i]);
}
} else {
tag.block = block;
}
}
}
return tag;
}
};
|
'use strict';
var IoTServer = require("../iot");
var inquirer = require("inquirer");
var chalk = require('chalk');
inquirer.prompt([{
type: "input",
name: "iotBaseURL",
message: "Enter the URL to the IoT Server",
default: "http://iotserver:7101"
}], function(answers) {
var iot = new IoTServer(answers.iotBaseURL);
iot.setPrincipal('iot', 'welcome1');
console.log(chalk.bold("Initial IoT Version: ") + chalk.cyan(iot.getVersion()));
var d = null;
iot.checkVersion()
.then(function (version) {
console.log(chalk.bold("IoT Version: ") + chalk.cyan(version), "[getVersion =", iot.getVersion(), "]");
return iot.createDevice("sharedSecret");
})
.then(function (device) {
d = device;
console.log(chalk.bold("Device created: ") + chalk.cyan(device.getID()));
return device.activate();
})
.then(function (device) {
console.log(chalk.bold("Device Activated: ") + chalk.cyan(device.getState()));
var data = [{temp: 182}, {temp: 213}, {temp: 16}, {temp: 11}];
return device.sendDataMessages("jsclient:temperature", data);
})
.then(function (response) {
console.log(chalk.bold("Messages sent. Response: "), response.body);
return d.delete();
})
.then(function (gateway) {
console.log(chalk.bold("Device deleted."));
})
.catch(function (error) {
console.log(chalk.bold.red("*** Error ***"));
console.log(error.body || error);
if (d) d.delete();
});
});
|
///////////////////////////////////////////////////////////////////////////
// Copyright © Esri. 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.
///////////////////////////////////////////////////////////////////////////
define({
"configText": "Ustaw tekst konfiguracyjny:",
"generalSettings": {
"tabTitle": "Ustawienia ogólne",
"measurementUnitLabel": "Jednostka miary",
"currencyLabel": "Symbol miary",
"roundCostLabel": "Zaokrąglaj koszt",
"projectOutputSettings": "Ustawienia wynikowe projektu",
"typeOfProjectAreaLabel": "Typ obszaru projektu",
"bufferDistanceLabel": "Odległość buforowania",
"csvReportExportLabel": "Zezwól użytkownikowi na eksportowanie raportu projektu",
"editReportSettingsBtnTooltip": "Edytuj ustawienia raportu",
"roundCostValues": {
"twoDecimalPoint": "Dwa miejsca po przecinku",
"nearestWholeNumber": "Najbliższa liczba całkowita",
"nearestTen": "Najbliższa dziesiątka",
"nearestHundred": "Najbliższa setka",
"nearestThousand": "Najbliższe tysiące",
"nearestTenThousands": "Najbliższe dziesiątki tysięcy"
},
"reportSettings": {
"reportSettingsPopupTitle": "Ustawienia raportu",
"reportNameLabel": "Nazwa raportu (opcjonalnie):",
"checkboxLabel": "Pokaż",
"layerTitle": "Tytuł",
"columnLabel": "Etykieta",
"duplicateMsg": "Duplikuj etykietę"
},
"projectAreaType": {
"outline": "Obrys",
"buffer": "Bufor"
},
"errorMessages": {
"currency": "Nieprawidłowa jednostka waluty",
"bufferDistance": "Nieprawidłowa odległość buforowania",
"outOfRangebufferDistance": "Wartość powinna być większa niż 0 i mniejsza niż lub równa 100"
}
},
"projectSettings": {
"tabTitle": "Ustawienia projektu",
"costingGeometrySectionTitle": "Zdefiniuj obszar geograficzny na potrzeby kalkulacji kosztów (opcjonalnie)",
"costingGeometrySectionNote": "Uwaga: skonfigurowanie tej warstwy umożliwi użytkownikowi konfigurowanie równań kosztów szablonów obiektów na podstawie obszarów geograficznych.",
"projectTableSectionTitle": "Możliwość zapisania/wczytania ustawień projektu (opcjonalnie)",
"projectTableSectionNote": "Uwaga: skonfigurowanie wszystkich tabel i warstw umożliwi użytkownikowi zapisanie/wczytanie projektu w celu ponownego wykorzystania.",
"costingGeometryLayerLabel": "Warstwa geometrii kalkulacji kosztów",
"fieldLabelGeography": "Pole do oznaczenia etykietą obszaru geograficznego",
"projectAssetsTableLabel": "Tabela zasobów projektu",
"projectMultiplierTableLabel": "Tabela kosztów dodatkowych mnożnika projektu",
"projectLayerLabel": "Warstwa projektu",
"configureFieldsLabel": "Skonfiguruj pola",
"fieldDescriptionHeaderTitle": "Opis pola",
"layerFieldsHeaderTitle": "Pole warstwy",
"selectLabel": "Zaznacz",
"errorMessages": {
"duplicateLayerSelection": "Warstwa ${layerName} jest już wybrana",
"invalidConfiguration": "Należy wybrać wartość ${fieldsString}"
},
"costingGeometryHelp": "<p>Zostaną wyświetlone warstwy poligonowe z następującymi warunkami: <br/> <li>\tWarstwa musi mieć możliwość wykonywania zapytania</li><li>\tWarstwa musi zawierać pole GlobalID</li></p>",
"fieldToLabelGeographyHelp": "<p>Pola znakowe i liczbowe wybranej warstwy geometrii kalkulacji kosztów zostaną wyświetlone w menu rozwijanym Pole do oznaczenia etykietą obszaru geograficznego.</p>",
"projectAssetsTableHelp": "<p>Zostaną wyświetlone tabele z następującymi warunkami: <br/> <li>Tabela musi mieć możliwości edycji, czyli tworzenia, usuwania i aktualizacji</li> <li>Tabela musi zawierać sześć pól o dokładnie takich nazwach i typach danych:</li><ul><li>\tAssetGUID (pole typu GUID)</li><li>\tCostEquation (pole typu String)</li><li>\tScenario (pole typu String)</li><li>\tTemplateName (pole typu String)</li><li> GeographyGUID (pole typu GUID)</li><li>\tProjectGUID (pole typu GUID)</li></ul> </p>",
"projectMultiplierTableHelp": "<p>Zostaną wyświetlone tabele z następującymi warunkami: <br/> <li>Tabela musi mieć możliwości edycji, czyli tworzenia, usuwania i aktualizacji</li> <li>Tabela musi zawierać pięć pól o dokładnie takich nazwach i typach danych:</li><ul><li>\tDescription (pole typu String)</li><li>\tType (pole typu String)</li><li>\tValue (pole typu Float/Double)</li><li>\tCostindex (pole typu Integer)</li><li> \tProjectGUID (pole typu GUID))</li></ul> </p>",
"projectLayerHelp": "<p>Zostaną wyświetlone warstwy poligonowe z następującymi warunkami: <br/> <li>Warstwa musi mieć możliwości edycji, czyli tworzenia, usuwania i aktualizacji</li> <li>Warstwa musi zawierać pięć pól o dokładnie takich nazwach i typach danych:</li><ul><li>ProjectName (pole typu String)</li><li>Description (pole typu String)</li><li>Totalassetcost (pole typu Float/Double)</li><li>Grossprojectcost (pole typu Float/Double)</li><li>GlobalID (pole typu GlobalID)</li></ul> </p>",
"pointLayerCentroidLabel": "Centroid warstwy punktowej",
"selectRelatedPointLayerDefaultOption": "Zaznacz",
"pointLayerHintText": "<p>Zostaną wyświetlone warstwy punktowe z następującymi warunkami: <br/> <li>\tWarstwa musi mieć pole 'Projectid' (typ GUID)</li><li>\tWarstwa musi mieć możliwość edycji, a więc atrybut 'Tworzenie', 'Usuwanie' i 'Aktualizacja'</li></p>"
},
"layerSettings": {
"tabTitle": "Ustawienia warstwy",
"layerNameHeaderTitle": "Nazwa warstwy",
"layerNameHeaderTooltip": "Lista warstw na mapie",
"EditableLayerHeaderTitle": "Edytowalne",
"EditableLayerHeaderTooltip": "Dołącz warstwę i jej szablony w widżecie kalkulacji kosztów",
"SelectableLayerHeaderTitle": "Podlegające selekcji",
"SelectableLayerHeaderTooltip": "Geometria z obiektu może zostać użyta do wygenerowania nowego elementu kosztu",
"fieldPickerHeaderTitle": "ID projektu (opcjonalnie)",
"fieldPickerHeaderTooltip": "Pole opcjonalne (typu znakowego), w którym będzie przechowywany identyfikator projektu",
"selectLabel": "Zaznacz",
"noAssetLayersAvailable": "Nie znaleziono warstwy zasobów na wybranej mapie internetowej",
"disableEditableCheckboxTooltip": "Ta warstwa nie ma możliwości edycji",
"missingCapabilitiesMsg": "Dla tej warstwy brak następujących funkcji:",
"missingGlobalIdMsg": "Ta warstwa nie ma pola GlobalId",
"create": "Tworzenie",
"update": "Aktualizuj",
"deleteColumnLabel": "Usuń",
"attributeSettingHeaderTitle": "Ustawienia atrybutów",
"addFieldLabelTitle": "Dodaj atrybuty",
"layerAttributesHeaderTitle": "Atrybuty warstwy",
"projectLayerAttributesHeaderTitle": "Atrybuty warstwy projektu",
"attributeSettingsPopupTitle": "Ustawienia atrybutów warstwy"
},
"costingInfo": {
"tabTitle": "Informacje o kalkulacji kosztów",
"proposedMainsLabel": "Proponowane elementy główne",
"addCostingTemplateLabel": "Dodaj szablon kalkulacji kosztów",
"manageScenariosTitle": "Zarządzaj scenariuszami",
"featureTemplateTitle": "Szablon obiektu",
"costEquationTitle": "Równanie kosztów",
"geographyTitle": "Obszar geograficzny",
"scenarioTitle": "Scenariusz",
"actionTitle": "Działania",
"scenarioNameLabel": "Nazwa scenariusza",
"addBtnLabel": "Dodaj",
"srNoLabel": "Nie.",
"deleteLabel": "Usuwanie",
"duplicateScenarioName": "Duplikuj nazwę scenariusza",
"hintText": "<div>Wskazówka: użyj następujących słów kluczowych</div><ul><li><b>{TOTALCOUNT}</b>: używa łącznej liczby zasobów tego samego typu w obszarze geograficznym</li><li><b>{MEASURE}</b>: używa długości dla zasobu liniowego i pola powierzchni dla zasobu poligonowego</li><li><b>{TOTALMEASURE}</b>: używa łącznej długości dla zasobu liniowego i łącznego pola powierzchni dla zasobu poligonowego tego samego typu w obszarze geograficznym</li></ul> Możesz użyć funkcji, takich jak:<ul><li>Math.abs(-100)</li><li>Math.floor({TOTALMEASURE})</li></ul>Należy zmodyfikować równanie kosztów zgodnie z wymaganiami projektu.",
"noneValue": "Brak",
"requiredCostEquation": "Niepoprawne równanie kosztów dla warstwy ${layerName} : ${templateName}",
"duplicateTemplateMessage": "Istnieje podwójny wpis szablonu dla warstwy ${layerName} : ${templateName}",
"defaultEquationRequired": "Wymagane jest domyślne równanie dla warstwy ${layerName} : ${templateName}",
"validCostEquationMessage": "Wprowadź prawidłowe równanie kosztów",
"costEquationHelpText": "Edytuj równanie kosztów zgodnie z wymaganiami projektu",
"scenarioHelpText": "Wybierz scenariusz zgodnie z wymaganiami projektu",
"copyRowTitle": "Kopiuj wiersz",
"noTemplateAvailable": "Dodaj co najmniej jeden szablon dla warstwy ${layerName}",
"manageScenarioLabel": "Zarządzaj scenariuszem",
"noLayerMessage": "Wprowadź co najmniej jedną warstwę w ${tabName}",
"noEditableLayersAvailable": "Warstwy, które należy oznaczyć jako możliwe do edycji na karcie ustawień warstwy",
"updateProjectCostCheckboxLabel": "Aktualizuj równania projektu",
"updateProjectCostEquationHint": "Wskazówka: Umożliwia użytkownikowi aktualizowanie równań kosztów zasobów, które zostały już dodane do istniejących projektów, za pomocą nowych równań zdefiniowanych niżej na podstawie szablonu obiektu, geografii i scenariusza. Jeśli brak określonej kombinacji, zostanie przyjęty koszt domyślny, tzn. geografia i scenariusz ma wartość 'None' (brak). W przypadku usunięcia szablonu obiektu ustawiony zostanie koszt równy 0."
},
"statisticsSettings": {
"tabTitle": "Dodatkowe ustawienia",
"addStatisticsLabel": "Dodaj statystykę",
"fieldNameTitle": "Pole",
"statisticsTitle": "Etykieta",
"addNewStatisticsText": "Dodaj nową statystykę",
"deleteStatisticsText": "Usuń statystykę",
"moveStatisticsUpText": "Przesuń statystykę w górę",
"moveStatisticsDownText": "Przesuń statystykę w dół",
"selectDeselectAllTitle": "Zaznacz wszystkie"
},
"projectCostSettings": {
"addProjectCostLabel": "Dodaj koszt dodatkowy projektu",
"additionalCostValueColumnHeader": "Wartość",
"invalidProjectCostMessage": "Nieprawidłowa wartość kosztu projektu",
"additionalCostLabelColumnHeader": "Etykieta",
"additionalCostTypeColumnHeader": "Typ"
},
"statisticsType": {
"countLabel": "Liczba",
"averageLabel": "Średnia",
"maxLabel": "Maksimum",
"minLabel": "Minimum",
"summationLabel": "Zsumowanie",
"areaLabel": "Pole powierzchni",
"lengthLabel": "Długość"
}
}); |
/* eslint-disable class-methods-use-this */
import Relay from 'react-relay';
class DeletePermissionMutation extends Relay.Mutation {
getMutation() {
return Relay.QL`
mutation {
deletePermission(input: $input)
}
`;
}
getVariables() {
return {
projectId: this.props.project.id,
userId: this.props.userId,
};
}
getFatQuery() {
return Relay.QL`
fragment on DeletePermissionPayload {
deletedPermissionId
viewer {
id
project(name: "${this.props.project.name}") {
users(first: 10) {
edges {
node {
id
fullname
}
}
}
}
allUsers {
id
fullname
}
}
}
`;
}
getConfigs() {
return [{
type: 'NODE_DELETE',
parentName: 'viewer',
parentID: this.props.viewer.id,
connectionName: 'users',
deletedIDFieldName: 'deletedPermissionId',
}];
}
}
export default DeletePermissionMutation;
|
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
errorHandler = require('./errors.server.controller'),
Exame = mongoose.model('Exame'),
_ = require('lodash');
/**
* Create a Exame
*/
exports.create = function(req, res) {
var exame = new Exame(req.body);
exame.user = req.user;
exame.save(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(exame);
}
});
};
exports.addPergunta= function(exameId,perguntaId){
Exame.findById(exameId).exec(function(err,exame){
if(err){
console.log('erro finding exam first');
return;
}
else{
if(!exame){
// console.log('exam not found'+exameId);
return;
}
var exame1=exame.toObject();
exame1._perguntas.push(perguntaId);
exame = _.extend(exame , exame1);
exame.save(function(err) {
if (err) {
//console.log('erro ao salvar');
return;
} else {
//console.log('sucesso');
}
});
}
});
};
exports.listar = function(req, res) {
Exame.find().select('id ano').exec(function (err,exames) {
// body...
if(err){
return res.status(400).send({message:errorHandler.getErrorMessage(err)});
}
else{
res.jsonp(exames);
}
});
};
/**
* Show the current Exame
*/
exports.read = function(req, res) {
Exame.findById(req.params.exameId).populate({path:'_perguntas',model:'Pergunta'}).populate('disciplina').exec(function(err,exame){
if(err){
return res.status(400).send({message:errorHandler.getErrorMessage(err)});
}
else{
if(!exame){
return res.status(404).send({message:'Exame nao encontrado'});
}
Exame.populate(exame._perguntas,{
path:'_ajuda',
model:'Ajuda'},
function(err,docs){
if(err){
return res.status(400).send({message:errorHandler.getErrorMessage(err)});
}
exame._ajuda=docs;
});
Exame.populate(exame._perguntas,{
path:'_alternativas',
model:'Alternativa'},
function(err,docs){
if(err){
return res.status(400).send({message:errorHandler.getErrorMessage(err)});
}
// console.log(docs.toObject());
// exame._perguntas=docs;
res.jsonp(exame); //exame=docs;
});
//res.jsonp(exame);
}
});
};
/**
* Exame middleware
*/
// exports.exameByID = function(req, res, next, id) {
// Exame.findById(id).populate('_perguntas').exec(function(err, exame) {
// //Exame.findById(id).deepPopulate('_perguntas.alternativas').exec(function(err, exame) {
// if (err) return next(err);
// if (! exame) return next(new Error('Failed to load Exame ' + id));
// req.exame = exame ;
// next();
// });
// };
/**
* Update a Exame
*/
exports.update = function(req, res) {
var exame = req.exame ;
exame = _.extend(exame , req.body);
exame.save(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(exame);
}
});
};
/**
* Delete an Exame
*/
exports.delete = function(req, res) {
var exame = req.exame ;
exame.remove(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(exame);
}
});
};
/**
* List of Exames
*/
exports.list = function(req, res) {
Exame.find().select('id ano disciplina').populate('disciplina','name').sort({ano:-1}).exec(function(err, exames) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(exames);
}
});
};
/**
* Exame authorization middleware
*/
exports.hasAuthorization = function(req, res, next) {
if (req.exame.user.id !== req.user.id) {
return res.status(403).send('User is not authorized');
}
next();
};
|
goog.module('test_files.use_closure_externs.use_closure_externs');var module = module || {id: 'test_files/use_closure_externs/use_closure_externs.js'};/**
* @fileoverview A source file that uses types that are used in .d.ts files, but
* that are not available or use different names in Closure's externs.
* @suppress {checkTypes} checked by tsc
*/
console.log('work around TS dropping consecutive comments');
let /** @type {!NodeListOf<!HTMLParagraphElement>} */ x = document.getElementsByTagName('p');
console.log(x);
const /** @type {(null|!RegExpExecArray)} */ res = ((/asd/.exec('asd asd')));
console.log(res);
|
/**
* Created with JetBrains WebStorm.
* User: yujilong
* Date: 14-2-11
* Time: 上午11:08
* To change this template use File | Settings | File Templates.
*/
define(['jquery', 'util', 'post/PostContent'], function ($, util, PostContent) {
var Post = function (_id, categoryId, boardId, title, createTime, taobaoUrl, lastUpdateTime , fontCoverPic , status, price) {
this._id = _id;
this.categoryId = categoryId;
this.boardId = boardId;
this.title = title;
this.createTime = createTime;
this.taobaoUrl = taobaoUrl;
this.lastUpdateTime = lastUpdateTime;
this.postContents = [];
this.fontCoverPic = fontCoverPic;
this.status = status;
this.price = price;
};
Post.prototype = {
createContent: function (_id) {
var content = new PostContent(_id);
this.postContents.push(content);
return content;
},
createContentKey: function (fn) {
util.sendAjax('/burning/cms/createPostContentKey', {
}, 'json', fn, 'post');
},
save : function(){
var title = $('#createBox').find('input[name="postTitle"]').val();
var url = encodeURI($('#createBox').find('input[name="taobaoUrl"]').val());
this.title = title;
this.taobaoUrl = url;
},
pullContents : function(_id){
var tThis = this;
for(var i = 0, len = this.postContents.length; i < len ; i++){
var content = this.postContents[i];
if(content._id.trim() === _id.trim()){
(function(index){
var tmp = tThis.postContents.splice(index,1);
})(i);
break;
}
}
},
updateContent : function(_id,info,type,sort){
var content = this.findContent(_id);
content.info = info;
content.type = type;
},
findContent : function (_id){
for(var i = 0, len = this.postContents.length; i < len ; i++){
if(this.postContents[i]._id === _id){
return this.postContents[i];
}
}
},
submit:function(){
this.initVals();
var tThis = this;
var obj = this.validatePost();
if(obj.flag){
(function(){
util.sendAjax('/burning/cms/createPost',{
post :
{
categoryId : tThis.categoryId,
boardId : tThis.boardId,
title : tThis.title,
taobaoUrl : tThis.taobaoUrl,
postContents : tThis.postContents,
status : tThis.status,
price : tThis.price
}
}, 'json', function(data){
if(data.rs == 1){
location.reload(true);
} else {
alert('error');
}
}, 'post');
})();
}else{
return obj;
}
},
initVals : function(){
this.title = $('#createBox').find('input[name="postTitle"]').val();
this.taobaoUrl = encodeURI($('#createBox').find('input[name="taobaoUrl"]').val());
this.status = $('#createBox').find('select[name="status"]').val();
this.price = $('#createBox').find('input[name="price"]').val();
for(var i = 0 , len = this.postContents.length; i<len; i++){
if(this.postContents[i].type == 1){
this.initTextContent(this.postContents[i]);
}
}
},
initTextContent : function(content){
var text = $('#' + content._id).find('textarea').val();
content.info.text = text;
},
initDefaultText : function(content){
content.type = 1;
content.info = {
text:''
};
},
validatePost : function(){
var error_msg = '';
var tThis = this;
if(!/^[0-9]+(.[0-9]+)?$/.test(tThis.price)){
error_msg = '请输入正确的数字,如12.30或12!';
return {
flag : false,
error : error_msg
};
}
if(this.postContents.length === 0){
error_msg = '请添加图片或文章内容';
return {
flag : false,
error : error_msg
};
}
if(!/^http:\/\//.test(tThis.taobaoUrl)){
return {
flag: false,
error : '请输入正确的URL,如:http://www.baidu.com'
}
}
if(!this.title){
error_msg = '请填写标题';
return {
flag : false,
error : error_msg
};
}
for(var i = 0, len = this.postContents.length; i < len ; i ++) {
var content = this.postContents[i];
if(content.type == 1 && !content.info.text){
return {
flag : false,
error : '有部分段落未填写数据'
};
}else if(content.type != 1 && !content.info){
return {
flag : false,
error : '有部分图片尚未上传'
}
}
}
return {
flag : true
};
},
delByPostId : function(fn){
var tThis = this;
util.sendAjax('/burning/cms/delPostById', {
_id : tThis._id
}, 'json', fn, 'delete');
},
getPostById : function(fn){
var tThis = this;
util.sendAjax('/burning/cms/getPostById',{
_id : tThis._id
},'json',fn,'get');
},
updatePostById : function(fn){
var tThis = this;
util.sendAjax('/burning/cms/updatePostById',{
_id: tThis._id,
taobaoUrl : tThis.taobaoUrl,
price : tThis.price,
title : tThis.title
},'json',fn,'put');
},
updatePostStatus : function(fn){
var tThis = this;
util.sendAjax('/burning/cms/updatePostStatus',{
_id:tThis._id,
status : tThis.status
},'json',fn,'put');
},
multUpdatePostStatus : function(ids,status,fn){
console.log(ids);
var tThis = this;
util.sendAjax('/burning/cms/multUpdatePostStatus',{
ids:ids,
status : status
},'json',fn,'put');
},
multdelPostStatus : function(ids,fn){
console.log(ids);
var tThis = this;
util.sendAjax('/burning/cms/multDelPost',{
ids:ids
},'json',fn,'delete');
}
};
return Post;
}); |
'use strict'
module.exports = (gulp) => {
require('./build/node')(gulp)
require('./build/browser')(gulp)
require('./clean')(gulp)
gulp.task('build', ['build:browser'])
}
|
import React from 'react'
import PropTypes from 'prop-types'
import A from 'components/A'
const Arasaac = ({ link }) =>
link ? (
<A href={'http://www.arasaac.org'} target='_blank' alt='Arasaac'>
ARASAAC (http://www.arasaac.org)
</A>
) : (
<A href={'http://www.arasaac.org'} target='_blank' alt='Arasaac'>
ARASAAC
</A>
)
Arasaac.propTypes = {
link: PropTypes.bool
}
export default Arasaac
|
/**
* Simple wrapper for lang.hitch to make it into an easy function
*/
define(['dojo/_base/lang'], function (lang) {
var l = {
_mixin: function(dest, source, copyFunc){
// summary:
// Copies/adds all properties of source to dest; returns dest.
// dest: Object
// The object to which to copy/add all properties contained in source.
// source: Object
// The object from which to draw all properties to copy into dest.
// copyFunc: Function?
// The process used to copy/add a property in source; defaults to the Javascript assignment operator.
// returns:
// dest, as modified
// description:
// All properties, including functions (sometimes termed "methods"), excluding any non-standard extensions
// found in Object.prototype, are copied/added to dest. Copying/adding each particular property is
// delegated to copyFunc (if any); copyFunc defaults to the Javascript assignment operator if not provided.
// Notice that by default, _mixin executes a so-called "shallow copy" and aggregate types are copied/added by reference.
var name, s, i, empty = {};
for(name in source){
// the (!(name in empty) || empty[name] !== s) condition avoids copying properties in "source"
// inherited from Object.prototype. For example, if dest has a custom toString() method,
// don't overwrite it with the toString() method that source inherited from Object.prototype
s = source[name];
if(!(name in dest) || (dest[name] !== s && (!(name in empty) || empty[name] !== s))){
dest[name] = copyFunc ? copyFunc(s) : s;
}
}
// if(has("bug-for-in-skips-shadowed")){
// if(source){
// for(i = 0; i < _extraLen; ++i){
// name = _extraNames[i];
// s = source[name];
// if(!(name in dest) || (dest[name] !== s && (!(name in empty) || empty[name] !== s))){
// dest[name] = copyFunc ? copyFunc(s) : s;
// }
// }
// }
// }
return dest; // Object
},
mixin: function(dest, sources){
// summary:
// Copies/adds all properties of one or more sources to dest; returns dest.
// dest: Object
// The object to which to copy/add all properties contained in source. If dest is falsy, then
// a new object is manufactured before copying/adding properties begins.
// sources: Object...
// One of more objects from which to draw all properties to copy into dest. sources are processed
// left-to-right and if more than one of these objects contain the same property name, the right-most
// value "wins".
// returns: Object
// dest, as modified
// description:
// All properties, including functions (sometimes termed "methods"), excluding any non-standard extensions
// found in Object.prototype, are copied/added from sources to dest. sources are processed left to right.
// The Javascript assignment operator is used to copy/add each property; therefore, by default, mixin
// executes a so-called "shallow copy" and aggregate types are copied/added by reference.
// example:
// make a shallow copy of an object
// | var copy = lang.mixin({}, source);
// example:
// many class constructors often take an object which specifies
// values to be configured on the object. In this case, it is
// often simplest to call `lang.mixin` on the `this` object:
// | declare("acme.Base", null, {
// | constructor: function(properties){
// | // property configuration:
// | lang.mixin(this, properties);
// |
// | console.log(this.quip);
// | // ...
// | },
// | quip: "I wasn't born yesterday, you know - I've seen movies.",
// | // ...
// | });
// |
// | // create an instance of the class and configure it
// | var b = new acme.Base({quip: "That's what it does!" });
// example:
// copy in properties from multiple objects
// | var flattened = lang.mixin(
// | {
// | name: "Frylock",
// | braces: true
// | },
// | {
// | name: "Carl Brutanananadilewski"
// | }
// | );
// |
// | // will print "Carl Brutanananadilewski"
// | console.log(flattened.name);
// | // will print "true"
// | console.log(flattened.braces);
if(!dest){ dest = {}; }
for(var i = 1, l = arguments.length; i < l; i++){
this._mixin(dest, arguments[i]);
}
return dest; // Object
}
}
return lang.hitch(l, function () {
var arr = {},
args = Array.prototype.slice.call(arguments, 0);
args.unshift(arr);
this.mixin.apply(this, args);
return arr;
});
});
|
$(function () {
'use strict';
QUnit.module('popover plugin')
QUnit.test('should be defined on jquery object', function (assert) {
assert.expect(1)
assert.ok($(document.body).popover, 'popover method is defined')
})
QUnit.module('popover', {
beforeEach: function () {
// Run all tests in noConflict mode -- it's the only way to ensure that the plugin works in noConflict mode
$.fn.bootstrapPopover = $.fn.popover.noConflict()
},
afterEach: function () {
$.fn.popover = $.fn.bootstrapPopover
delete $.fn.bootstrapPopover
}
})
QUnit.test('should provide no conflict', function (assert) {
assert.expect(1)
assert.strictEqual($.fn.popover, undefined, 'popover was set back to undefined (org value)')
})
QUnit.test('should return jquery collection containing the element', function (assert) {
assert.expect(2)
var $el = $('<div/>')
var $popover = $el.bootstrapPopover()
assert.ok($popover instanceof $, 'returns jquery collection')
assert.strictEqual($popover[0], $el[0], 'collection contains element')
})
QUnit.test('should render popover element', function (assert) {
assert.expect(2)
var $popover = $('<a href="#" title="mdo" data-content="https://twitter.com/mdo">@mdo</a>')
.appendTo('#qunit-fixture')
.bootstrapPopover('show')
assert.notEqual($('.popover').length, 0, 'popover was inserted')
$popover.bootstrapPopover('hide')
assert.strictEqual($('.popover').length, 0, 'popover removed')
})
QUnit.test('should store popover instance in popover data object', function (assert) {
assert.expect(1)
var $popover = $('<a href="#" title="mdo" data-content="https://twitter.com/mdo">@mdo</a>').bootstrapPopover()
assert.ok($popover.data('bs.popover'), 'popover instance exists')
})
QUnit.test('should store popover trigger in popover instance data object', function (assert) {
assert.expect(1)
var $popover = $('<a href="#" title="ResentedHook">@ResentedHook</a>')
.appendTo('#qunit-fixture')
.bootstrapPopover()
$popover.bootstrapPopover('show')
assert.ok($('.popover').data('bs.popover'), 'popover trigger stored in instance data')
})
QUnit.test('should get title and content from options', function (assert) {
assert.expect(4)
var $popover = $('<a href="#">@fat</a>')
.appendTo('#qunit-fixture')
.bootstrapPopover({
title: function () {
return '@fat'
},
content: function () {
return 'loves writing tests (╯°□°)╯︵ ┻━┻'
}
})
$popover.bootstrapPopover('show')
assert.notEqual($('.popover').length, 0, 'popover was inserted')
assert.strictEqual($('.popover .popover-title').text(), '@fat', 'title correctly inserted')
assert.strictEqual($('.popover .popover-content').text(), 'loves writing tests (╯°□°)╯︵ ┻━┻', 'content correctly inserted')
$popover.bootstrapPopover('hide')
assert.strictEqual($('.popover').length, 0, 'popover was removed')
})
QUnit.test('should not duplicate HTML object', function (assert) {
assert.expect(6)
var $div = $('<div/>').html('loves writing tests (╯°□°)╯︵ ┻━┻')
var $popover = $('<a href="#">@fat</a>')
.appendTo('#qunit-fixture')
.bootstrapPopover({
content: function () {
return $div
}
})
$popover.bootstrapPopover('show')
assert.notEqual($('.popover').length, 0, 'popover was inserted')
assert.equal($('.popover .popover-content').html(), $div, 'content correctly inserted')
$popover.bootstrapPopover('hide')
assert.strictEqual($('.popover').length, 0, 'popover was removed')
$popover.bootstrapPopover('show')
assert.notEqual($('.popover').length, 0, 'popover was inserted')
assert.equal($('.popover .popover-content').html(), $div, 'content correctly inserted')
$popover.bootstrapPopover('hide')
assert.strictEqual($('.popover').length, 0, 'popover was removed')
})
QUnit.test('should get title and content from attributes', function (assert) {
assert.expect(4)
var $popover = $('<a href="#" title="@mdo" data-content="loves data attributes (づ。◕‿‿◕。)づ ︵ ┻━┻" >@mdo</a>')
.appendTo('#qunit-fixture')
.bootstrapPopover()
.bootstrapPopover('show')
assert.notEqual($('.popover').length, 0, 'popover was inserted')
assert.strictEqual($('.popover .popover-title').text(), '@mdo', 'title correctly inserted')
assert.strictEqual($('.popover .popover-content').text(), 'loves data attributes (づ。◕‿‿◕。)づ ︵ ┻━┻', 'content correctly inserted')
$popover.bootstrapPopover('hide')
assert.strictEqual($('.popover').length, 0, 'popover was removed')
})
QUnit.test('should get title and content from attributes ignoring options passed via js', function (assert) {
assert.expect(4)
var $popover = $('<a href="#" title="@mdo" data-content="loves data attributes (づ。◕‿‿◕。)づ ︵ ┻━┻" >@mdo</a>')
.appendTo('#qunit-fixture')
.bootstrapPopover({
title: 'ignored title option',
content: 'ignored content option'
})
.bootstrapPopover('show')
assert.notEqual($('.popover').length, 0, 'popover was inserted')
assert.strictEqual($('.popover .popover-title').text(), '@mdo', 'title correctly inserted')
assert.strictEqual($('.popover .popover-content').text(), 'loves data attributes (づ。◕‿‿◕。)づ ︵ ┻━┻', 'content correctly inserted')
$popover.bootstrapPopover('hide')
assert.strictEqual($('.popover').length, 0, 'popover was removed')
})
QUnit.test('should respect custom template', function (assert) {
assert.expect(3)
var $popover = $('<a href="#">@fat</a>')
.appendTo('#qunit-fixture')
.bootstrapPopover({
title: 'Test',
content: 'Test',
template: '<div class="popover foobar"><div class="arrow"></div><div class="inner"><h3 class="title"/><div class="content"><p/></div></div></div>'
})
$popover.bootstrapPopover('show')
assert.notEqual($('.popover').length, 0, 'popover was inserted')
assert.ok($('.popover').hasClass('foobar'), 'custom class is present')
$popover.bootstrapPopover('hide')
assert.strictEqual($('.popover').length, 0, 'popover was removed')
})
QUnit.test('should destroy popover', function (assert) {
assert.expect(7)
var $popover = $('<div/>')
.bootstrapPopover({
trigger: 'hover'
})
.on('click.foo', $.noop)
assert.ok($popover.data('bs.popover'), 'popover has data')
assert.ok($._data($popover[0], 'events').mouseover && $._data($popover[0], 'events').mouseout, 'popover has hover event')
assert.strictEqual($._data($popover[0], 'events').click[0].namespace, 'foo', 'popover has extra click.foo event')
$popover.bootstrapPopover('show')
$popover.bootstrapPopover('destroy')
assert.ok(!$popover.hasClass('in'), 'popover is hidden')
assert.ok(!$popover.data('popover'), 'popover does not have data')
assert.strictEqual($._data($popover[0], 'events').click[0].namespace, 'foo', 'popover still has click.foo')
assert.ok(!$._data($popover[0], 'events').mouseover && !$._data($popover[0], 'events').mouseout, 'popover does not have any events')
})
QUnit.test('should render popover element using delegated selector', function (assert) {
assert.expect(2)
var $div = $('<div><a href="#" title="mdo" data-content="https://twitter.com/mdo">@mdo</a></div>')
.appendTo('#qunit-fixture')
.bootstrapPopover({
selector: 'a',
trigger: 'click'
})
$div.find('a').trigger('click')
assert.notEqual($('.popover').length, 0, 'popover was inserted')
$div.find('a').trigger('click')
assert.strictEqual($('.popover').length, 0, 'popover was removed')
})
QUnit.test('should detach popover content rather than removing it so that event handlers are left intact', function (assert) {
assert.expect(1)
var $content = $('<div class="content-with-handler"><a class="btn btn-warning">Button with event handler</a></div>').appendTo('#qunit-fixture')
var handlerCalled = false
$('.content-with-handler .btn').on('click', function () {
handlerCalled = true
})
var $div = $('<div><a href="#">Show popover</a></div>')
.appendTo('#qunit-fixture')
.bootstrapPopover({
html: true,
trigger: 'manual',
container: 'body',
content: function () {
return $content
}
})
var done = assert.async()
$div
.one('shown.bs.popover', function () {
$div
.one('hidden.bs.popover', function () {
$div
.one('shown.bs.popover', function () {
$('.content-with-handler .btn').trigger('click')
$div.bootstrapPopover('destroy')
assert.ok(handlerCalled, 'content\'s event handler still present')
done()
})
.bootstrapPopover('show')
})
.bootstrapPopover('hide')
})
.bootstrapPopover('show')
})
QUnit.test('should throw an error when initializing popover on the document object without specifying a delegation selector', function (assert) {
assert.expect(1)
assert.throws(function () {
$(document).bootstrapPopover({title: 'What am I on?', content: 'My selector is missing'})
}, new Error('`selector` option must be specified when initializing popover on the window.document object!'))
})
QUnit.test('should do nothing when an attempt is made to hide an uninitialized popover', function (assert) {
assert.expect(1)
var $popover = $('<span data-toggle="popover" data-title="some title" data-content="some content">some text</span>')
.appendTo('#qunit-fixture')
.on('hidden.bs.popover shown.bs.popover', function () {
assert.ok(false, 'should not fire any popover events')
})
.bootstrapPopover('hide')
assert.strictEqual($popover.data('bs.popover'), undefined, 'should not initialize the popover')
})
QUnit.test('should throw an error when template contains multiple top-level elements', function (assert) {
assert.expect(1)
assert.throws(function () {
$('<span data-toggle="popover" data-title="some title" data-content="some content">some text</span>')
.appendTo('#qunit-fixture')
.bootstrapPopover({template: '<div>Foo</div><div>Bar</div>'})
.bootstrapPopover('show')
}, new Error('popover `template` option must consist of exactly 1 top-level element!'))
})
QUnit.test('should fire inserted event', function (assert) {
assert.expect(2)
var done = assert.async()
$('<a href="#">@Johann-S</a>')
.appendTo('#qunit-fixture')
.on('inserted.bs.popover', function () {
assert.notEqual($('.popover').length, 0, 'popover was inserted')
assert.ok(true, 'inserted event fired')
done()
})
.bootstrapPopover({
title: 'Test',
content: 'Test'
})
.bootstrapPopover('show')
})
})
|
import internalQuerySelector from '../src/query-selector';
import { querySelector } from '../src';
describe('exports', () => {
it('exports `querySelector`', () => {
expect(querySelector).toEqual(internalQuerySelector);
});
});
|
'use strict';
module.exports = class Account
{
constructor(name, password, email)
{
var load = typeof name === 'object';
this._username = load ? name._username : name;
this._password = load ? name._password : password;
this._email = load ? name._email : email;
this._userType = load ? name._userType : 1; // 1 is a basic user, 2 is an admin
this._userGames = load ? name._userGames : [];
this._numWin = load ? name._numWin : 0;
this._numLoss = load ? name._numLoss : 0;
this._overallRatio = load ? name._overallRatio : 0;
this._userSkillLevel = load ? name._userSkillLevel : 0;
}
get username()
{
return this._username;
}
set username(username)
{
this._username = username;
}
get password()
{
return this._password;
}
set password(password)
{
this._password = password;
}
get email()
{
return this._email;
}
set email(email)
{
this._email = email;
}
get userType()
{
return this._userType;
}
set userType(type)
{
this._userType = type;
}
get userGames()
{
return this._userGames;
}
get userWins()
{
return this._numWin;
}
get userLoss()
{
return this._numLoss;
}
updateFromPlayer(player)
{
if (player.result === 1) {
this._numWin++;
} else {
this._numLoss++;
}
this._overallRatio = (this._numWin / this._numLoss).toFixed(2);
this._userSkillLevel = player.skill;
// We would also add the game ID to the games array, but we aren't saving games atm
}
get overallRatio()
{
return this._overallRatio;
}
get userSkillLevel()
{
return this._userSkillLevel;
}
/**
* Updates user best game by looking for the game the user
* scored the highest skill in.
*/
calculateBestGame()
{
var Skill=0;
this._userSkillLevel=0;
for(var i= 0; i< this._userGames.length; i++)
{
this._userSkillLevel += this._userGames[i].gameSkill;
if(this._userGames[i].gameResult == 0)
i++;
else if(Skill < this._userGames[i].gameSkill){
Skill= this._userGames[i].gameSkill;
this._userBestGame= i;
}
}
}
};
|
"use strict";
var _ = require('lodash');
_.mixin({
pickObjectParams: function (data, params) {
params = Array.prototype.slice.call(arguments, 1);
return _.map(data, function (item) {
return _.pick.apply(_, [item].concat(params));
});
},
omitObjectParams: function (datam, params) {
params = Array.prototype.slice.call(arguments, 1);
return _.map(data, function (item) {
return _.omit.apply(_, [item].concat(params));
});
},
stripHtml: function (str) {
return str.replace(/<(?:.|\n)*?>/gm, '');
},
timeAgoDate: function (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)
return;
return day_diff == 0 && (
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 < 7 && day_diff + " days ago" ||
day_diff < 31 && Math.ceil(day_diff / 7) + " weeks ago" ||
day_diff < 365 && Math.ceil(day_diff / 30) + " mounts ago" ||
day_diff > 365 && Math.floor(day_diff / 365) + " years ago";
},
getImageFromContent: function (str) {
var image = str.match(/<img.+?src=["'](.+?)["'].+?>/)
return image ? image[1] : "";
},
addhttp: function (url) {
if (!/^(f|ht)tps?:\/\//i.test(url)) {
url = "http://" + url;
}
return url;
},
truncate: function(str, length, truncateStr){
if (str == null) return '';
str = String(str); truncateStr = truncateStr || '...';
length = ~~length;
return str.length > length ? str.slice(0, length) + truncateStr : str;
},
getFunctionArgs:function(func){
var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m,
text = func.toString(),
args = text.match(FN_ARGS)[1].replace(/ /g,'').split(',');
_.remove(args,function(arg){
return (arg == "" || arg == undefined || arg == null)
});
return args;
},
deepExtend: function (obj) { //https://gist.github.com/kurtmilam/1868955
var parentRE = /#{\s*?_\s*?}/,
slice = Array.prototype.slice,
hasOwnProperty = Object.prototype.hasOwnProperty;
_.each(slice.call(arguments, 1), function(source) {
for (var prop in source) {
if (hasOwnProperty.call(source, prop)) {
if (_.isUndefined(obj[prop]) || _.isFunction(obj[prop]) || _.isNull(source[prop]) || _.isDate(source[prop])) {
obj[prop] = source[prop];
}
else if (_.isString(source[prop]) && parentRE.test(source[prop])) {
if (_.isString(obj[prop])) {
obj[prop] = source[prop].replace(parentRE, obj[prop]);
}
}
else if (_.isArray(obj[prop]) || _.isArray(source[prop])){
if (!_.isArray(obj[prop]) || !_.isArray(source[prop])){
throw 'Error: Trying to combine an array with a non-array (' + prop + ')';
} else {
obj[prop] = _.reject(_.deepExtend(obj[prop], source[prop]), function (item) { return _.isNull(item);});
}
}
else if (_.isObject(obj[prop]) || _.isObject(source[prop])){
if (!_.isObject(obj[prop]) || !_.isObject(source[prop])){
throw 'Error: Trying to combine an object with a non-object (' + prop + ')';
} else {
obj[prop] = _.deepExtend(obj[prop], source[prop]);
}
} else {
obj[prop] = source[prop];
}
}
}
});
return obj;
}
});
if (!String.prototype.format) {
String.prototype.format = function () {
var args = arguments;
return this.replace(/{(\d+)}/g, function (match, number) {
return typeof args[number] != 'undefined'
? args[number]
: match
;
});
};
}
|
/**
* @namespace
* @description All general ABC methods and functionality should be placed within this namespace.
* @version 0.0.5 Jul 2014
* @author ABC Innovation
*
*/
var ABC = function() {
var includeLocations = [];
var onLoadFunctions = [getSubMenus, clearSearchField];
var lastNav = null;
var navTimer = null;
loadIncludes(includeLocations);
loadEvents(onLoadFunctions);
/**
* Iterate through an array of functions and call them onLoad
*
* @param {array} functionArray All functions to be called on load
*/
function loadEvents(functionArray) {
for (var i=0;i < functionArray.length;i++) {
addLoadEvent(functionArray[i]);
}
}
/**
* Run a specified function on load
*
* @param {function} func Function to be called
*/
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
oldonload();
func();
};
}
}
/**
* Iterate through an array of file locations and write out an HTML script
* tag for each one.
*
* @param {array} includeArray Array of file locations
*/
function loadIncludes(includeArray) {
for (var i=0;i < includeArray.length;i++) {
document.write('<scr' + 'ipt type="text/javascript" src="' + includeArray[i] + '"></scr' + 'ipt>');
}
}
/**
* GLOBAL NAVIGATION SPECIFIC FUNCTIONS
*/
/**
* Perform a HTTP request to retrieve the submenu html for the global nav
* and attach it to the appropriate element.
*
* @return void
*/
function getSubMenus() {
// need to check active stylesheet!
// don't get sub menus if handheld or iphone css
var xmlhttp;
var baseURL = 'http://' + location.host;
var subMenus = baseURL + '/res/abc/submenus.htm';
// find width of nav
var navX = document.getElementById("abcNavWrapper");
var navWidth;
// quit if navX is null or undefined
if (navX == null) { return; }
if (navX.currentStyle) {
navWidth = parseInt(navX.currentStyle["width"]);
//alert('currentStyle: width=' + navWidth);
} else if (window.getComputedStyle) {
navWidth = parseInt(document.defaultView.getComputedStyle(navX,null).getPropertyValue("width"));
//alert('getComputedStyle: width=' + navWidth);
}
// could use instead:
//var navWidth = document.getElementById("abcNavWrapper").offsetWidth;
// download submenus for full-size screens
if (navWidth >= 940) {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); // IE5, IE6
} else {
//alert("Your browser does not support XMLHTTP!");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && (xmlhttp.status == 200 || xmlhttp.status == 304)) {
document.getElementById('abcNavMenu').innerHTML = xmlhttp.responseText;
// after loading submenus
addNavEvents();
addLinkTracking();
}
};
xmlhttp.open("GET",subMenus,true);
xmlhttp.send(null);
}
}
/**
* Adds onmouseover and onmouseout events to top-level navs
*
* @return void
*/
function addNavEvents() {
var topNavs = document.getElementById('abcNavMenu').childNodes;
for (var nodeN in topNavs) {
if (topNavs[nodeN].nodeType == 1) {
topNavs[nodeN].onmouseover = function() {
showSubMenu(this);
};
topNavs[nodeN].onmouseout = function() {
hideSubMenu(this);
};
}
}
}
/**
* show submenus of a top-level nav
*
* @return void
*/
function showSubMenu(obj) {
// show submenu if it exists
if (obj && obj.firstChild && obj.firstChild.nextSibling) {
if (obj.firstChild.nextSibling.nodeType == 1) {
obj.firstChild.nextSibling.style.display = 'block'; // IE
} else {
obj.firstChild.nextSibling.nextSibling.style.display = 'block'; // DOM
}
}
// clear timeout
clearTimeout(navTimer);
// hide last Nav immediately (if not same as current nav)
if (ABC.lastNav != obj) {
hideNav();
}
}
/**
* hide submenus of a top-level nav - after a 500 millisecond delay
*
* @return void
*/
function hideSubMenu(obj) {
ABC.lastNav = obj;
navTimer = setTimeout('ABC.hideNav()',500);
}
/**
* Hide submenus of a top-level nav - called by hideSubMenu after a delay
*
* @return void
*/
function hideNav() {
var obj = ABC.lastNav;
// hide last submenu if it exists
if (obj && obj.firstChild && obj.firstChild.nextSibling) {
if (obj.firstChild.nextSibling.nodeType == 1) {
obj.firstChild.nextSibling.style.display = 'none'; // IE
} else {
obj.firstChild.nextSibling.nextSibling.style.display = 'none'; // DOM
}
}
}
/**
* Adds Webtrends link tracking to abcNav
*
* @return void
*/
function addLinkTracking() {
//if (document.getElementsByTagName('body')[0].className.indexOf('abcHomepage') != -1) {
var navLinks = document.getElementById("abcNav").getElementsByTagName('A');
var link;
for (var i=0, j=navLinks.length; i<j; i++) {
link = navLinks[i];
link.onmouseup = function(){
var parent = this.parentNode;
var parentId = parent.id;
// climb up tree until you find a parent with an id
while (parentId === '') {
parent = parent.parentNode;
parentId = parent.id;
}
// find the current site profile
var profile = 'other';
if (typeof abcContentProfile != 'undefined') {
profile = abcContentProfile;
} else if (ABC.Stats && ABC.Stats.getProfile()) {
profile = ABC.Stats.getProfile();
}
// add the webtrends query string
if ((this.search.indexOf('WT.z_navMenu') == -1)) {
this.search += (this.search == '') ? '?' : '&';
this.search += 'WT.z_navMenu=' + parentId;
this.search += '&WT.z_srcSite=' + profile;
this.search += '&WT.z_linkName=' + (this.textContent || this.innerText || this.title || '').replace(/(?: & )|\s/gi, '_');
}
};
}
//}
}
/**
* Toggle the search field in the top navigation to contain the holding
* text of 'Keyword' unless in focus or filled with a value.
*
* @return void
*/
function clearSearchField() {
var searchBox = document.getElementById('abcNavQuery');
var defaultText = 'Keywords';
if (searchBox != null) {
searchBox.onfocus = function() {
if (this.value == defaultText) { this.value = ''; }
};
searchBox.onblur = function() {
if (!this.value) { this.value = defaultText; }
};
searchBox.parentNode.onsubmit = function() {
if ((searchBox.value == defaultText) || (searchBox.value == '')) {
document.location.href = "http://search.abc.net.au/search/search.cgi?collection=abcall_meta";
return false;
}
};
}
}
return {
hideNav : function() {
hideNav();
},
addLoadEvents : function(functionArray) {
loadEvents(functionArray);
}
};
}(); |
// Get the modal
var modal = document.getElementById('myModal');
// Get the image and insert it inside the modal - use its "alt" text as a caption
var img = document.getElementById('myImg');
var modalImg = document.getElementById("img01");
var captionText = document.getElementById("caption");
img.onclick = function(){
modal.style.display = "block";
modalImg.src = this.src;
modalImg.alt = this.alt;
captionText.innerHTML = this.alt;
}
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
|
import { Selector } from 'testcafe'
const host = process.env.HOST || 'localhost'
const port = process.env.PORT || '3000'
const MAIN_PAGE = `http://${host}:${port}`
// eslint-disable-next-line no-unused-expressions, no-undef
fixture`Hello, world!`.beforeEach(async (t) => {
await t.setNativeDialogHandler(() => true)
await t.navigateTo(MAIN_PAGE)
})
test('home page', async (t) => {
await t
.expect(
await Selector('section').withText(
'Hello World, this is my first styled component!'
).exists
)
.eql(true)
})
|
var React = require('react');
module.exports = React.createClass({
render: function () {
return (
<html lang="sv">
<head>
<meta charSet="utf-8" />
<title>{this.props.title}</title>
</head>
<body style={{ width: 300 + 'px', margin: '0 auto'}}>
<h1>{this.props.title}</h1>
<p>Det finns ingen sida med addressen <b>{this.props.url}</b>. Kontrollera addressen igen eller gå till <a href="/">skissaochgissa.se</a>.</p>
</body>
</html>
);
}
});
|
var http = require('http')
, https = require('https')
, url = require('url')
, vm = require('vm')
, cluster = require('cluster')
, util = require('util')
, haikuConsole = require('./haikuConsole.js')
, sandbox = require('./sandbox.js')
var shutdown
, shutdownInProgress = false
, requestCount = 0
, argv
process.on('message', function (msg) {
process.send({ response: msg.challange });
})
.on('uncaughtException', function (err) {
log('Entering shutdown mode after an uncaught exception: '
+ (err.message || err) + (err.stack ? '\n' + err.stack : ''));
initiateShutdown();
});
function log(thing) {
console.log(process.pid + ': ' + thing);
}
function shutdownNext() {
if (shutdown) {
clearTimeout(shutdown);
shutdown = undefined;
}
process.nextTick(function() {
log('Recycling self. Active connections: TCP: ' + httpServer.connections + ', TLS: ' + httpsServer.connections);
process.exit();
});
}
// raised by HTTP or HTTPS server when one of the client connections closes
function onConnectionClose() {
if (shutdownInProgress && 0 === (httpServer.connections + httpsServer.connections))
shutdownNext()
}
function initiateShutdown() {
if (!shutdownInProgress) {
// stop accepting new requests
httpServer.close();
httpsServer.close();
shutdownInProgress = true;
if (0 === (httpServer.connections + httpsServer.connections)) {
// there are no active connections - shut down now
shutdownNext();
}
else {
// Shut down when all active connections close (see onConnectionClose above)
// or when the graceful shutdown timeout expires, whichever comes first.
// Graceful shutdown timeout is twice the handler processing timeout.
shutdown = setTimeout(shutdownNext, argv.t * 2);
}
}
}
function onRequestFinished(context) {
if (!context.finished) {
context.finished = true;
context.req.socket.end(); // force buffers to be be flushed
}
}
function haikuError(context, status, error) {
log(new Date() + ' Status: ' + status + ', Request URL: ' + context.req.url + ', Error: ' + error);
try {
context.req.resume();
context.res.writeHead(status);
if (error && 'HEAD' !== context.req.method)
context.res.end((typeof error === 'string' ? error : JSON.stringify(error)) + '\n');
else
context.res.end();
}
catch (e) {
// empty
}
onRequestFinished(context);
}
function limitExecutionTime(context) {
// setup timeout for request processing
context.timeout = setTimeout(function () {
delete context.timeout;
haikuError(context, 500, 'Handler ' + context.handlerName + ' did not complete within the time limit of ' + argv.t + 'ms');
onRequestFinished(context);
}, argv.t); // handler processing timeout
// intercept end of response to cancel the timeout timer and
// speed up shutdown if one is in progress
context.res.end = sandbox.wrapFunction(context.res, 'end', function () {
var result = arguments[--arguments.length].apply(this, arguments);
if (context.timeout) {
clearTimeout(context.timeout);
delete context.timeout;
onRequestFinished(context);
}
return result;
});
}
function executeHandler(context) {
log(new Date() + ' executing ' + context.handlerName);
// limit execution time of the handler to the preconfigured value
limitExecutionTime(context);
// expose rigged console through sandbox
var sandboxAddons = {
console: haikuConsole.createConsole(context, argv.l, argv.d)
}
// evaluate handler code in strict mode to prevent stack walking from untrusted code
context.handler = "'use strict';" + context.handler;
context.req.resume();
try {
vm.runInNewContext(context.handler, sandbox.createSandbox(context, sandboxAddons), context.handlerName);
}
catch (e) {
haikuError(context, 500, 'Handler ' + context.handlerName + ' generated an exception at runtime: '
+ (e.message || e) + (e.stack ? '\n' + e.stack : ''));
}
}
function resolveHandler(context) {
if (!context.handlerName)
return haikuError(context, 400,
'The x-haiku-handler HTTP request header or query paramater must specify the URL of the scriptlet to run.');
try {
context.handlerUrl = url.parse(context.handlerName);
}
catch (e) {
return haikuError(context, 400, 'The x-haiku-handler parameter must be a valid URL that resolves to a JavaScript scriptlet.');
}
var engine;
if (context.handlerUrl.protocol === 'http:') {
engine = http;
context.handlerUrl.port = context.handlerUrl.port || 80;
}
else if (context.handlerUrl.protocol === 'https:') {
engine = https;
context.handlerUrl.port = context.handlerUrl.port || 443;
}
else
return haikuError(context, 400, 'The x-haiku-handler parameter specifies unsupported protocol. Only http and https are supported.');
var handlerRequest;
var processResponse = function(res) {
context.handler = '';
var length = 0;
res.on('data', function(chunk) {
length += chunk.length;
if (length > argv.i) {
handlerRequest.abort();
return haikuError(context, 400, 'The size of the handler exceeded the quota of ' + argv.i + ' bytes.');
}
context.handler += chunk;
})
.on('end', function() {
if (res.statusCode === 200)
executeHandler(context);
else if (res.statusCode === 302 && context.redirect < 3) {
context.handlerName = res.headers['location'];
context.redirect++;
resolveHandler(context);
}
else
return haikuError(context, 400, 'HTTP error when obtaining handler code from ' + context.handlerName + ': ' + res.statusCode);
});
}
var processError = function(error) {
haikuError(context, 400, 'Unable to obtain HTTP handler code from ' + context.handlerName + ': ' + error);
}
if (argv.proxyHost) {
// HTTPS or HTTP request through HTTP proxy
http.request({ // establishing a tunnel
host: argv.proxyHost,
port: argv.proxyPort,
method: 'CONNECT',
path: context.handlerUrl.hostname + ':' + context.handlerUrl.port
}).on('connect', function(pres, socket, head) {
if (pres.statusCode !== 200)
return haikuError(context, 400, 'Unable to connect to the host ' + context.host);
else
handlerRequest = engine.get({
host: context.handlerUrl.hostname,
port: context.handlerUrl.port,
path: context.handlerUrl.path,
socket: socket, // using a tunnel
agent: false // cannot use a default agent
}, processResponse).on('error', processError);
}).on('error', processError).end();
}
else // no proxy
handlerRequest = engine.get({
host: context.handlerUrl.hostname,
port: context.handlerUrl.port,
path: context.handlerUrl.path
}, processResponse).on('error', processError);
}
function getHaikuParam(context, name, defaultValue) {
return context.req.headers[name] || context.reqUrl.query[name] || defaultValue;
}
function processRequest(req, res) {
if (req.url === '/favicon.ico')
return haikuError({ req: req, res: res}, 404);
if (!shutdownInProgress && argv.r > 0 && ++requestCount >= argv.r) {
log('Entering shutdown mode after reaching request quota. Current active connections: TCP: '
+ httpServer.connections + ', TLS: ' + httpsServer.connections);
initiateShutdown();
}
req.pause();
var context = {
req: req,
res: res,
redirect: 0,
reqUrl: url.parse(req.url, true)
}
context.handlerName = getHaikuParam(context, 'x-haiku-handler');
context.console = getHaikuParam(context, 'x-haiku-console', 'none');
resolveHandler(context);
}
exports.main = function(args) {
argv = args;
// enter module sanbox - from now on all module reustes in this process will
// be subject to sandboxing
sandbox.enterModuleSandbox();
httpServer = http.createServer(processRequest)
.on('connection', function(socket) {
socket.on('close', onConnectionClose)
})
.listen(argv.p);
httpsServer = https.createServer({ cert: argv.cert, key: argv.key }, processRequest)
.on('connection', function(socket) {
socket.on('close', onConnectionClose)
})
.listen(argv.s);
}
|
import * as API from '../utils/Api'
export const SET_CATEGORIES = "SET_CATEGORIES"
export function setCategories(categories) {
return {
type: SET_CATEGORIES,
categories
}
}
export const fetchGetCategories = () => dispatch => (
API.getCategories().then(data => {
dispatch(setCategories(data.categories))
})
);
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _toast = require('./toast.container');
Object.defineProperty(exports, 'default', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_toast).default;
}
});
var _redux = require('./redux');
Object.keys(_redux).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function get() {
return _redux[key];
}
});
});
Object.defineProperty(exports, 'reducer', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_redux).default;
}
});
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } |
define({
"configText": "아래의 필터 그룹 정의",
"labels": {
"groupName": "필터 설정 이름:",
"groupNameTip": "사용자가 선택할 필터의 이름입니다.",
"groupDesc": "설명:",
"groupDescTip": "필터 설정의 설명입니다.",
"groupOperator": "프리셋 연산자:",
"groupOperatorTip": "필터의 연산자를 미리 정의하는 옵션입니다. 프리셋 연산자가 선택되지 않으면 필터가 동일한 연산자를 사용하게 됩니다.",
"groupDefault": "프리셋 값:",
"groupDefaultTip": "기존 레이어에서 값을 선택하는 옵션입니다.",
"sameLayerAppend": "레이어가 두 번 이상 나열된 경우:",
"sameLayerConjunc": "다음을 사용하여 추가:",
"caseSearch": "대소문자 구분 검색 수행: ",
"headerTextHelp": "필터 선택 위에 표시할 텍스트 제공"
},
"buttons": {
"addNewGroup": "새 그룹 추가",
"addNewGroupTip": "새 필터 설정을 추가합니다.",
"addLayer": "레이어 추가",
"addLayerTip": "레이어를 필터 설정에 추가합니다."
},
"inputs": {
"groupName": "그룹에 이름 지정",
"groupDesc": "그룹 설명",
"groupDefault": "사전 정의된 값 입력",
"sameLayerAny": "임의 일치 식",
"sameLayerAll": "모두 일치 식",
"simpleMode": "간단한 뷰에서 시작",
"simpleModeTip": "구성된 위젯 인터페이스를 단순화하는 옵션입니다. 옵션을 선택한 경우 연산자 드롭다운 목록과 기준 추가 버튼이 인터페이스에서 제거됩니다.",
"webmapAppendModeAny": "기존 맵 필터에 임의 식 추가",
"webmapAppendModeAll": "기존 맵 필터에 모든 식 추가",
"webmapAppendModeTip": "기존 웹 맵 필터에 필터 집합을 추가하는 옵션입니다.",
"persistOnClose": "위젯이 닫힌 후 유지",
"selectGroup": "필터링할 그룹 선택",
"hideDropDown": "하나의 그룹만 구성된 경우 헤더 및 필터 선택 항목을 숨깁니다",
"optionsMode": "위젯 옵션 숨기기",
"optionsModeTip": "추가 위젯 설정을 표시하는 옵션입니다. 옵션을 선택한 경우 정의된 필터를 저장 및 불러오고 위젯이 닫힌 후에 필터를 유지하는 기능이 인터페이스에서 제거됩니다.",
"optionOR": "OR",
"optionAND": "AND",
"optionEQUAL": "EQUALS",
"optionNOTEQUAL": "NOT EQUAL",
"optionGREATERTHAN": "GREATER THAN",
"optionGREATERTHANEQUAL": "GREATER THAN OR EQUAL",
"optionLESSTHAN": "LESS THAN",
"optionLESSTHANEQUAL": "LESS THAN OR EQUAL",
"optionSTART": "BEGINS WITH",
"optionEND": "ENDS WITH",
"optionLIKE": "CONTAINS",
"optionNOTLIKE": "DOES NOT CONTAIN",
"optionONORBEFORE": "다음 시간 또는 그 이전",
"optionONORAFTER": "다음 시간 또는 그 이후",
"optionNONE": "NONE"
},
"tables": {
"layer": "레이어",
"layerTip": "맵에 정의된 레이어 이름입니다.",
"field": "필드",
"fieldTip": "레이어가 필터링될 필드입니다.",
"value": "값 사용",
"valueTip": "레이어에서 드롭다운 목록 값을 사용하는 옵션입니다. 레이어를 이 매개변수에 사용하지 않는 경우 기본 텍스트 상자가 사용자에게 표시됩니다.",
"zoom": "확대",
"zoomTip": "필터가 적용된 후에 피처의 범위를 확대하는 옵션입니다. 하나의 레이어만 확대하는 데 선택할 수 있습니다.",
"action": "삭제",
"actionTip": "필터 설정에서 레이어를 제거합니다."
},
"popup": {
"label": "값 선택"
},
"errors": {
"noGroups": "최소 하나 이상의 그룹이 필요합니다.",
"noGroupName": "하나 이상의 그룹 이름이 없습니다.",
"noDuplicates": "하나 이상의 그룹 이름이 중복되었습니다.",
"noRows": "테이블에 최소 하나의 행이 필요합니다.",
"noLayers": "맵에 레이어가 없습니다."
},
"picker": {
"description": "이 그룹에 대한 프리셋 값을 찾으려면 이 양식을 사용합니다.",
"layer": "레이어 선택",
"layerTip": "웹 맵에 정의된 레이어 이름입니다.",
"field": "필드 선택",
"fieldTip": "프리셋 값이 설정될 필드입니다.",
"value": "값 선택",
"valueTip": "위젯의 기본값이 될 값입니다."
}
}); |
define('dummy/tests/app.jshint', ['exports'], function (exports) {
'use strict';
QUnit.module('JSHint - .');
QUnit.test('app.js should pass jshint', function (assert) {
assert.ok(true, 'app.js should pass jshint.');
});
});
define('dummy/tests/helpers/destroy-app', ['exports', 'ember'], function (exports, _ember) {
exports['default'] = destroyApp;
function destroyApp(application) {
_ember['default'].run(application, 'destroy');
}
});
define('dummy/tests/helpers/destroy-app.jshint', ['exports'], function (exports) {
'use strict';
QUnit.module('JSHint - helpers');
QUnit.test('helpers/destroy-app.js should pass jshint', function (assert) {
assert.ok(true, 'helpers/destroy-app.js should pass jshint.');
});
});
define('dummy/tests/helpers/module-for-acceptance', ['exports', 'qunit', 'dummy/tests/helpers/start-app', 'dummy/tests/helpers/destroy-app'], function (exports, _qunit, _dummyTestsHelpersStartApp, _dummyTestsHelpersDestroyApp) {
exports['default'] = function (name) {
var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
(0, _qunit.module)(name, {
beforeEach: function beforeEach() {
this.application = (0, _dummyTestsHelpersStartApp['default'])();
if (options.beforeEach) {
options.beforeEach.apply(this, arguments);
}
},
afterEach: function afterEach() {
(0, _dummyTestsHelpersDestroyApp['default'])(this.application);
if (options.afterEach) {
options.afterEach.apply(this, arguments);
}
}
});
};
});
define('dummy/tests/helpers/module-for-acceptance.jshint', ['exports'], function (exports) {
'use strict';
QUnit.module('JSHint - helpers');
QUnit.test('helpers/module-for-acceptance.js should pass jshint', function (assert) {
assert.ok(true, 'helpers/module-for-acceptance.js should pass jshint.');
});
});
define('dummy/tests/helpers/resolver', ['exports', 'ember/resolver', 'dummy/config/environment'], function (exports, _emberResolver, _dummyConfigEnvironment) {
var resolver = _emberResolver['default'].create();
resolver.namespace = {
modulePrefix: _dummyConfigEnvironment['default'].modulePrefix,
podModulePrefix: _dummyConfigEnvironment['default'].podModulePrefix
};
exports['default'] = resolver;
});
define('dummy/tests/helpers/resolver.jshint', ['exports'], function (exports) {
'use strict';
QUnit.module('JSHint - helpers');
QUnit.test('helpers/resolver.js should pass jshint', function (assert) {
assert.ok(true, 'helpers/resolver.js should pass jshint.');
});
});
define('dummy/tests/helpers/start-app', ['exports', 'ember', 'dummy/app', 'dummy/config/environment'], function (exports, _ember, _dummyApp, _dummyConfigEnvironment) {
exports['default'] = startApp;
function startApp(attrs) {
var application = undefined;
var attributes = _ember['default'].merge({}, _dummyConfigEnvironment['default'].APP);
attributes = _ember['default'].merge(attributes, attrs); // use defaults, but you can override;
_ember['default'].run(function () {
application = _dummyApp['default'].create(attributes);
application.setupForTesting();
application.injectTestHelpers();
});
return application;
}
});
define('dummy/tests/helpers/start-app.jshint', ['exports'], function (exports) {
'use strict';
QUnit.module('JSHint - helpers');
QUnit.test('helpers/start-app.js should pass jshint', function (assert) {
assert.ok(true, 'helpers/start-app.js should pass jshint.');
});
});
define('dummy/tests/router.jshint', ['exports'], function (exports) {
'use strict';
QUnit.module('JSHint - .');
QUnit.test('router.js should pass jshint', function (assert) {
assert.ok(true, 'router.js should pass jshint.');
});
});
define('dummy/tests/test-helper', ['exports', 'dummy/tests/helpers/resolver', 'ember-qunit'], function (exports, _dummyTestsHelpersResolver, _emberQunit) {
(0, _emberQunit.setResolver)(_dummyTestsHelpersResolver['default']);
});
define('dummy/tests/test-helper.jshint', ['exports'], function (exports) {
'use strict';
QUnit.module('JSHint - .');
QUnit.test('test-helper.js should pass jshint', function (assert) {
assert.ok(true, 'test-helper.js should pass jshint.');
});
});
/* jshint ignore:start */
require('dummy/tests/test-helper');
EmberENV.TESTS_FILE_LOADED = true;
/* jshint ignore:end */
//# sourceMappingURL=tests.map |
'use strict';
var app = angular.module('testReport.project.settings', [
'ngRoute',
]);
app.config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/project/:projectId/settings', {
templateUrl: '/static/app/partials/project/settings/settings.html',
controller: 'ProjectSettingsCtrl'
});
}]);
app.controller('ProjectSettingsCtrl', ['$rootScope', '$scope', '$routeParams', '$q', '$filter', '$location', 'Auth', 'Project',
function ($rootScope, $scope, $routeParams, $q, $filter, $location, Auth, Project) {
$rootScope.isMainDashboard = false;
$scope.formErrors = null;
var admin_settings = ['chart_type', 'results_view', 'weight', 'current_build'];
if(!$rootScope.getActiveProject()) {
$rootScope.selectProject($routeParams.projectId);
}
$scope.activeProjectId = $rootScope.getActiveProject();
function reloadSettings() {
$rootScope.getProjectSettings($routeParams.projectId, '').then(function(result) {
_.each(result, function(item) {
item.$save = true;
});
$scope.settings = _.sortBy(_.filter(result, function(item) {
return !_.contains(admin_settings, item.key);
}), 'key');
});
}
reloadSettings();
$scope.addSettingsItem = function() {
$scope.settings.push({ key: '', value: '' , $edit: true, $save: false });
};
$scope.cancelSettingsItem = function(item, index) {
$scope.formErrors = null;
if (!item.$save) {
$scope.settings.splice(index, 1);
}
item.$edit = false;
};
$scope.updateSettings = function (item) {
$scope.formErrors = null;
if (!item.$save && checkKeyExistent(item.key)) {
$scope.formErrors = 'Key "' + item.key + '" already exists.';
return;
}
if (item.key === '') {
return;
}
item.$edit = false;
Project.save_settings({ projectId: $scope.activeProjectId }, item, function(result) {
if (result.message === 'ok') {
item.$save = true;
}
}, function(result) {
$scope.formErrors = result.data.detail;
});
};
$scope.deleteSettings = function (item) {
var modal = $('#ConfirmationModal');
$scope.modalTitle = 'Attention';
$scope.modalBody = 'Are you sure you want to delete key "' + item.key + '" with value "' + item.value + '"?';
$scope.modalCallBack = function () {
Project.delete_settings({ projectId: $scope.activeProjectId }, item, function(result) {
if (result.message === 'ok') {
reloadSettings();
}
}, function(result) {
$scope.formErrors = result.data.detail;
});
};
modal.modal('show');
};
function checkKeyExistent(key) {
var saved_settings_keys = [];
_.each($scope.settings, function(item) {
if (item.$save) {
saved_settings_keys.push(item.key);
}
});
return _.contains(saved_settings_keys, key);
}
}
]);
|
define( [ 'angular',
'ngRoute',
'config/config',
'tmdb/services/TMDBAPIService'],
function( angular, $routeParams, config, TMDBAPIService ) {
"use strict";
var MovieTileController = function($scope, TMDBAPIService, $routeParams ) {
$scope.view = {
images: config.apiImg
};
$scope.clickOne = function(){
console.log("en el click one");
};
$scope.clickTwo = function(){
console.log("en el click two");
};
};
MovieTileController.$inject = [ '$scope', 'TMDBAPIService', '$routeParams' ];
return MovieTileController;
}
); |
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const React = require("react");
const vgraph_1 = require("./vgraph");
const vrootgraph_list_1 = require("../../components/graph/vrootgraph.list");
const cabeiri_lang_1 = require("cabeiri-lang");
class RootGraphesState {
constructor() {
this.selectedRootGraph = cabeiri_lang_1.CID.CID_NONE;
}
}
exports.RootGraphesState = RootGraphesState;
class VRootGraphes extends React.Component {
constructor(props) {
super(props);
this.onRootGraphSelected = (selectedRootGraph) => {
var graphState = new RootGraphesState();
graphState.selectedRootGraph = selectedRootGraph;
this.setState(graphState);
};
this.state = new RootGraphesState();
}
componentDidMount() {
}
render() {
return React.createElement("div", { className: "container-fluid" },
React.createElement("div", { className: "row" },
React.createElement("div", { className: "col-xs-4 col-md-3" },
React.createElement(vrootgraph_list_1.VRootGraphList, { onItemSelected: this.onRootGraphSelected, searchLabel: "Graphes" })),
React.createElement("div", { className: "col-xs-10 col-md-9" },
React.createElement(vgraph_1.VGraph, { rootGraphCID: this.state.selectedRootGraph }))));
}
;
}
exports.VRootGraphes = VRootGraphes;
;
React.createFactory(VRootGraphes);
//# sourceMappingURL=vrootgraphes.js.map |
const fs = require('fs');
const p = require('path');
// walk $PATH to find bin
const which = (bin) => {
const path = process.env.PATH.split(p.delimiter);
let file = '';
path.find((v) => {
const testPath = v + p.sep + bin;
if (fs.existsSync(testPath)) {
file = testPath;
return true;
}
return false;
});
return file;
};
const config = {
removeInfected: false, // don't change
quarantineInfected: `${__dirname}/infected`, // required for testing
// scanLog: `${__dirname}/clamscan-log`, // not required
clamscan: {
path: which('clamscan'), // required for testing
},
clamdscan: {
socket: '/var/run/clamd.scan/clamd.sock', // - can be set to null
host: '127.0.0.1', // required for testing (change for your system) - can be set to null
port: 3310, // required for testing (change for your system) - can be set to null
path: which('clamdscan'), // required for testing
timeout: 1000,
localFallback: false,
// configFile: '/etc/clamd.d/scan.conf' // set if required
},
// preference: 'clamdscan', // not used if socket/host+port is provided
debugMode: false,
};
// Force specific socket when on GitHub Actions
if (process.env.CI) config.clamdscan.socket = '/var/run/clamav/clamd.ctl';
module.exports = config;
|
module.exports = client => { //eslint-disable-line no-unused-vars
console.log(`Reconnecting... [at ${new Date()}]`);
};
|
import React from 'react';
import { FlexRow, FlexCell } from '../common';
import CharacterName from './CharacterName';
import InfoBlock from './InfoBlock';
const PersonalInfo = ({ character }) => (
<FlexRow>
<FlexCell columns={3}>
<CharacterName character={character} />
</FlexCell>
<FlexCell columns={9}>
<InfoBlock character={character} />
</FlexCell>
</FlexRow>
);
export default PersonalInfo;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.