code
stringlengths
2
1.05M
repo_name
stringlengths
5
114
path
stringlengths
4
991
language
stringclasses
1 value
license
stringclasses
15 values
size
int32
2
1.05M
/*! angular-deckgrid (v0.1.1) - Copyright: 2013, André König (andre.koenig@posteo.de) - MIT */ /* * angular-deckgrid * * Copyright(c) 2013 Andre Koenig <akoenig@posteo.de> * MIT Licensed * */ /** * @author André König (akoenig@posteo.de) * */ angular.module('akoenig.deckgrid', []); angular.module('akoenig.deckgrid').directive('deckgrid', [ 'DeckgridDescriptor', function initialize (DeckgridDescriptor) { 'use strict'; return DeckgridDescriptor.create(); } ]); /* * angular-deckgrid * * Copyright(c) 2013 Andre Koenig <akoenig@posteo.de> * MIT Licensed * */ /** * @author André König (akoenig@posteo.de) * */ angular.module('akoenig.deckgrid').factory('DeckgridDescriptor', [ 'Deckgrid', function initialize (Deckgrid) { 'use strict'; /** * This is a wrapper around the AngularJS * directive description object. * */ function Descriptor () { this.restrict = 'AE'; this.template = '<div data-ng-repeat="column in columns" class="{{layout.classList}}">' + '<div data-ng-repeat="card in column" data-ng-include="cardTemplate"></div>' + '</div>'; this.scope = { 'model': '=source' }; // // Will be created in the linking function. // this.$$deckgrid = null; this.link = this.$$link.bind(this); } /** * @private * * Cleanup method. Will be called when the * deckgrid directive should be destroyed. * */ Descriptor.prototype.$$destroy = function $$destroy () { this.$$deckgrid.destroy(); }; /** * @private * * The deckgrid link method. Will instantiate the deckgrid. * */ Descriptor.prototype.$$link = function $$link (scope, elem, attrs) { scope.$on('$destroy', this.$$destroy.bind(this)); scope.cardTemplate = attrs.cardtemplate; this.$$deckgrid = Deckgrid.create(scope, elem[0]); }; return { create : function create () { return new Descriptor(); } }; } ]); /* * angular-deckgrid * * Copyright(c) 2013 Andre Koenig <akoenig@posteo.de> * MIT Licensed * */ /** * @author André König (akoenig@posteo.de) * */ angular.module('akoenig.deckgrid').factory('Deckgrid', [ '$window', '$log', function initialize ($window, $log) { 'use strict'; /** * The deckgrid directive. * */ function Deckgrid (scope, element) { var self = this, watcher; this.$$elem = element; this.$$watchers = []; this.$$scope = scope; this.$$scope.columns = []; // // The layout configuration will be parsed from // the pseudo "before element." There you have to save all // the column configurations. // this.$$scope.layout = this.$$getLayout(); this.$$createColumns(); // // Register model change. // watcher = this.$$scope.$watch('model', this.$$onModelChange.bind(this), true); this.$$watchers.push(watcher); // // Register window resize change event. // watcher = angular.element($window).on('resize', self.$$onWindowResize.bind(self)); this.$$watchers.push(watcher); } /** * @private * * Creates the column segmentation. With other words: * This method creates the internal data structure from the * passed "source" attribute. Every card within this "source" * model will be passed into this internal column structure by * reference. So if you modify the data within your controller * this directive will reflect these changes immediately. * * NOTE that calling this method will trigger a complete template "redraw". * */ Deckgrid.prototype.$$createColumns = function $$createColumns () { var self = this; if (!this.$$scope.layout) { return $log.error('angular-deckgrid: No CSS configuration found (see ' + 'https://github.com/akoenig/angular-deckgrid#the-grid-configuration)'); } this.$$scope.columns = []; angular.forEach(this.$$scope.model, function onIteration (card, index) { var column = (index % self.$$scope.layout.columns) | 0; if (!self.$$scope.columns[column]) { self.$$scope.columns[column] = []; } self.$$scope.columns[column].push(card); }); }; /** * @private * * Parses the configuration out of the configured CSS styles. * * Example: * * .deckgrid::before { * content: '3 .column.size-1-3'; * } * * Will result in a three column grid where each column will have the * classes: "column size-1-3". * * You are responsible for defining the respective styles within your CSS. * */ Deckgrid.prototype.$$getLayout = function $$getLayout () { var content = $window.getComputedStyle(this.$$elem, ':before').content, layout; if (content) { content = content.replace(/'/g, ''); // before e.g. '3 .column.size-1of3' content = content.replace(/"/g, ''); // before e.g. "3 .column.size-1of3" content = content.split(' '); if (2 === content.length) { layout = {}; layout.columns = (content[0] | 0); layout.classList = content[1].replace(/\./g, ' ').trim(); } } return layout; }; /** * @private * * Event that will be triggered on "window resize". * */ Deckgrid.prototype.$$onWindowResize = function $$onWindowResize () { var self = this, layout = this.$$getLayout(); // // Okay, the layout has changed. // Creating a new column structure is not avoidable. // if (layout.columns !== this.$$scope.layout.columns) { self.$$scope.layout = layout; self.$$scope.$apply(function onApply () { self.$$createColumns(); }); } }; /** * @private * * Event that will be triggered when the source model has changed. * */ Deckgrid.prototype.$$onModelChange = function $$onModelChange (oldModel, newModel) { var self = this; if (oldModel.length !== newModel.length) { self.$$createColumns(); } }; /** * Destroys the directive. Takes care of cleaning all * watchers and event handlers. * */ Deckgrid.prototype.destroy = function destroy () { var i = this.$$watchers.length - 1; for (i; i >= 0; i = i - 1) { this.$$watchers[i](); } }; return { create : function create (scope, element) { return new Deckgrid(scope, element); } }; } ]);
maruilian11/cdnjs
ajax/libs/angular-deckgrid/0.1.1/angular-deckgrid.js
JavaScript
mit
7,829
/** * fullpage.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ (function() { tinyMCEPopup.requireLangPack(); var defaultDocTypes = 'XHTML 1.0 Transitional=<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">,' + 'XHTML 1.0 Frameset=<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">,' + 'XHTML 1.0 Strict=<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">,' + 'XHTML 1.1=<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">,' + 'HTML 4.01 Transitional=<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">,' + 'HTML 4.01 Strict=<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">,' + 'HTML 4.01 Frameset=<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'; var defaultEncodings = 'Western european (iso-8859-1)=iso-8859-1,' + 'Central European (iso-8859-2)=iso-8859-2,' + 'Unicode (UTF-8)=utf-8,' + 'Chinese traditional (Big5)=big5,' + 'Cyrillic (iso-8859-5)=iso-8859-5,' + 'Japanese (iso-2022-jp)=iso-2022-jp,' + 'Greek (iso-8859-7)=iso-8859-7,' + 'Korean (iso-2022-kr)=iso-2022-kr,' + 'ASCII (us-ascii)=us-ascii'; var defaultFontNames = 'Arial=arial,helvetica,sans-serif;Courier New=courier new,courier,monospace;Georgia=georgia,times new roman,times,serif;Tahoma=tahoma,arial,helvetica,sans-serif;Times New Roman=times new roman,times,serif;Verdana=verdana,arial,helvetica,sans-serif;Impact=impact;WingDings=wingdings'; var defaultFontSizes = '10px,11px,12px,13px,14px,15px,16px'; function setVal(id, value) { var elm = document.getElementById(id); if (elm) { value = value || ''; if (elm.nodeName == "SELECT") selectByValue(document.forms[0], id, value); else if (elm.type == "checkbox") elm.checked = !!value; else elm.value = value; } }; function getVal(id) { var elm = document.getElementById(id); if (elm.nodeName == "SELECT") return elm.options[elm.selectedIndex].value; if (elm.type == "checkbox") return elm.checked; return elm.value; }; window.FullPageDialog = { changedStyle : function() { var val, styles = tinyMCEPopup.editor.dom.parseStyle(getVal('style')); setVal('fontface', styles['font-face']); setVal('fontsize', styles['font-size']); setVal('textcolor', styles['color']); if (val = styles['background-image']) setVal('bgimage', val.replace(new RegExp("url\\('?([^']*)'?\\)", 'gi'), "$1")); else setVal('bgimage', ''); setVal('bgcolor', styles['background-color']); // Reset margin form elements setVal('topmargin', ''); setVal('rightmargin', ''); setVal('bottommargin', ''); setVal('leftmargin', ''); // Expand margin if (val = styles['margin']) { val = val.split(' '); styles['margin-top'] = val[0] || ''; styles['margin-right'] = val[1] || val[0] || ''; styles['margin-bottom'] = val[2] || val[0] || ''; styles['margin-left'] = val[3] || val[0] || ''; } if (val = styles['margin-top']) setVal('topmargin', val.replace(/px/, '')); if (val = styles['margin-right']) setVal('rightmargin', val.replace(/px/, '')); if (val = styles['margin-bottom']) setVal('bottommargin', val.replace(/px/, '')); if (val = styles['margin-left']) setVal('leftmargin', val.replace(/px/, '')); updateColor('bgcolor_pick', 'bgcolor'); updateColor('textcolor_pick', 'textcolor'); }, changedStyleProp : function() { var val, dom = tinyMCEPopup.editor.dom, styles = dom.parseStyle(getVal('style')); styles['font-face'] = getVal('fontface'); styles['font-size'] = getVal('fontsize'); styles['color'] = getVal('textcolor'); styles['background-color'] = getVal('bgcolor'); if (val = getVal('bgimage')) styles['background-image'] = "url('" + val + "')"; else styles['background-image'] = ''; delete styles['margin']; if (val = getVal('topmargin')) styles['margin-top'] = val + "px"; else styles['margin-top'] = ''; if (val = getVal('rightmargin')) styles['margin-right'] = val + "px"; else styles['margin-right'] = ''; if (val = getVal('bottommargin')) styles['margin-bottom'] = val + "px"; else styles['margin-bottom'] = ''; if (val = getVal('leftmargin')) styles['margin-left'] = val + "px"; else styles['margin-left'] = ''; // Serialize, parse and reserialize this will compress redundant styles setVal('style', dom.serializeStyle(dom.parseStyle(dom.serializeStyle(styles)))); this.changedStyle(); }, update : function() { var data = {}; tinymce.each(tinyMCEPopup.dom.select('select,input,textarea'), function(node) { data[node.id] = getVal(node.id); }); tinyMCEPopup.editor.plugins.fullpage._dataToHtml(data); tinyMCEPopup.close(); } }; function init() { var form = document.forms[0], i, item, list, editor = tinyMCEPopup.editor; // Setup doctype select box list = editor.getParam("fullpage_doctypes", defaultDocTypes).split(','); for (i = 0; i < list.length; i++) { item = list[i].split('='); if (item.length > 1) addSelectValue(form, 'doctype', item[0], item[1]); } // Setup fonts select box list = editor.getParam("fullpage_fonts", defaultFontNames).split(';'); for (i = 0; i < list.length; i++) { item = list[i].split('='); if (item.length > 1) addSelectValue(form, 'fontface', item[0], item[1]); } // Setup fontsize select box list = editor.getParam("fullpage_fontsizes", defaultFontSizes).split(','); for (i = 0; i < list.length; i++) addSelectValue(form, 'fontsize', list[i], list[i]); // Setup encodings select box list = editor.getParam("fullpage_encodings", defaultEncodings).split(','); for (i = 0; i < list.length; i++) { item = list[i].split('='); if (item.length > 1) addSelectValue(form, 'docencoding', item[0], item[1]); } // Setup color pickers document.getElementById('bgcolor_pickcontainer').innerHTML = getColorPickerHTML('bgcolor_pick','bgcolor'); document.getElementById('link_color_pickcontainer').innerHTML = getColorPickerHTML('link_color_pick','link_color'); document.getElementById('visited_color_pickcontainer').innerHTML = getColorPickerHTML('visited_color_pick','visited_color'); document.getElementById('active_color_pickcontainer').innerHTML = getColorPickerHTML('active_color_pick','active_color'); document.getElementById('textcolor_pickcontainer').innerHTML = getColorPickerHTML('textcolor_pick','textcolor'); document.getElementById('stylesheet_browsercontainer').innerHTML = getBrowserHTML('stylesheetbrowser','stylesheet','file','fullpage'); document.getElementById('bgimage_pickcontainer').innerHTML = getBrowserHTML('bgimage_browser','bgimage','image','fullpage'); // Resize some elements if (isVisible('stylesheetbrowser')) document.getElementById('stylesheet').style.width = '220px'; if (isVisible('link_href_browser')) document.getElementById('element_link_href').style.width = '230px'; if (isVisible('bgimage_browser')) document.getElementById('bgimage').style.width = '210px'; // Update form tinymce.each(tinyMCEPopup.getWindowArg('data'), function(value, key) { setVal(key, value); }); FullPageDialog.changedStyle(); // Update colors updateColor('textcolor_pick', 'textcolor'); updateColor('bgcolor_pick', 'bgcolor'); updateColor('visited_color_pick', 'visited_color'); updateColor('active_color_pick', 'active_color'); updateColor('link_color_pick', 'link_color'); }; tinyMCEPopup.onInit.add(init); })();
Timathom/timathom.github.io
xsltforms/scripts/tinymce_3.4.6/plugins/fullpage/js/fullpage.js
JavaScript
gpl-3.0
8,164
/*! /support/test/element/video/mp4 1.0.5 | http://nucleus.qoopido.com | (c) 2016 Dirk Lueth */ !function(e){"use strict";function c(c,n){var t=c.defer();return n.then(function(){var c=e.createElement("video");c.canPlayType('video/mp4; codecs="avc1.42E01E, mp4a.40.2"')?t.resolve():t.reject()},t.reject),t.pledge}provide(["/demand/pledge","../video"],c)}(document); //# sourceMappingURL=mp4.js.map
vvo/jsdelivr
files/qoopido.nucleus/1.0.5/support/test/element/video/mp4.js
JavaScript
mit
398
'use strict'; angular.module("ngLocale", [], ["$provide", function($provide) { var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; function getDecimals(n) { n = n + ''; var i = n.indexOf('.'); return (i == -1) ? 0 : n.length - i - 1; } function getVF(n, opt_precision) { var v = opt_precision; if (undefined === v) { v = Math.min(getDecimals(n), 3); } var base = Math.pow(10, v); var f = ((n * base) | 0) % base; return {v: v, f: f}; } $provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": [ "am", "pm" ], "DAY": [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ], "MONTH": [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ], "SHORTDAY": [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ], "SHORTMONTH": [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ], "fullDate": "EEEE, d MMMM y", "longDate": "d MMMM y", "medium": "d MMM y HH:mm:ss", "mediumDate": "d MMM y", "mediumTime": "HH:mm:ss", "short": "dd/MM/y HH:mm", "shortDate": "dd/MM/y", "shortTime": "HH:mm" }, "NUMBER_FORMATS": { "CURRENCY_SYM": "\u00a3", "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": "en-fk", "pluralCat": function(n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;} }); }]);
marcoR80/simple-app-mobile
www/vendor/angular-1.3.9/i18n/angular-locale_en-fk.js
JavaScript
mit
2,280
// add new post notification callback on post submit postAfterSubmitMethodCallbacks.push(function (post) { var adminIds = _.pluck(Meteor.users.find({'isAdmin': true}, {fields: {_id:1}}).fetch(), '_id'); var notifiedUserIds = _.pluck(Meteor.users.find({'profile.notifications.posts': 1}, {fields: {_id:1}}).fetch(), '_id'); // remove post author ID from arrays var adminIds = _.without(adminIds, post.userId); var notifiedUserIds = _.without(notifiedUserIds, post.userId); if (post.status === STATUS_PENDING && !!adminIds.length) { // if post is pending, only notify admins Herald.createNotification(adminIds, {courier: 'newPendingPost', data: post}); } else if (!!notifiedUserIds.length) { // if post is approved, notify everybody Herald.createNotification(notifiedUserIds, {courier: 'newPost', data: post}); } return post; }); // notify users that their pending post has been approved postApproveCallbacks.push(function (post) { Herald.createNotification(post.userId, {courier: 'postApproved', data: post}); return post; }); // add new comment notification callback on comment submit commentAfterSubmitMethodCallbacks.push(function (comment) { if(Meteor.isServer && !comment.disableNotifications){ var post = Posts.findOne(comment.postId), notificationData = { comment: _.pick(comment, '_id', 'userId', 'author', 'body'), post: _.pick(post, '_id', 'userId', 'title', 'url') }, userIdsNotified = []; // 1. Notify author of post // do not notify author of post if they're the ones posting the comment if (comment.userId !== post.userId) { Herald.createNotification(post.userId, {courier: 'newComment', data: notificationData}); userIdsNotified.push(post.userId); } // 2. Notify author of comment being replied to if (!!comment.parentCommentId) { var parentComment = Comments.findOne(comment.parentCommentId); // do not notify author of parent comment if they're also post author or comment author // (someone could be replying to their own comment) if (parentComment.userId !== post.userId && parentComment.userId !== comment.userId) { // add parent comment to notification data notificationData.parentComment = _.pick(parentComment, '_id', 'userId', 'author'); Herald.createNotification(parentComment.userId, {courier: 'newReply', data: notificationData}); userIdsNotified.push(parentComment.userId); } } // 3. Notify users subscribed to the thread // TODO: ideally this would be injected from the telescope-subscribe-to-posts package if (!!post.subscribers) { // remove userIds of users that have already been notified // and of comment author (they could be replying in a thread they're subscribed to) var subscriberIdsToNotify = _.difference(post.subscribers, userIdsNotified, [comment.userId]); Herald.createNotification(subscriberIdsToNotify, {courier: 'newCommentSubscribed', data: notificationData}); userIdsNotified = userIdsNotified.concat(subscriberIdsToNotify); } } return comment; }); var emailNotifications = { propertyName: 'emailNotifications', propertySchema: { type: Boolean, optional: true, defaultValue: true, autoform: { group: 'notifications_fieldset', instructions: 'Enable email notifications for new posts and new comments (requires restart).' } } }; addToSettingsSchema.push(emailNotifications); // make it possible to disable notifications on a per-comment basis addToCommentsSchema.push( { propertyName: 'disableNotifications', propertySchema: { type: Boolean, optional: true, autoform: { omit: true } } } ); function setNotificationDefaults (user) { // set notifications default preferences user.profile.notifications = { users: false, posts: false, comments: true, replies: true }; return user; } userCreatedCallbacks.push(setNotificationDefaults);
Accentax/betanyheter
packages/telescope-notifications/lib/notifications.js
JavaScript
mit
4,092
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _pure = require('recompose/pure'); var _pure2 = _interopRequireDefault(_pure); var _SvgIcon = require('../../SvgIcon'); var _SvgIcon2 = _interopRequireDefault(_SvgIcon); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var CommunicationPresentToAll = function CommunicationPresentToAll(props) { return _react2.default.createElement( _SvgIcon2.default, props, _react2.default.createElement('path', { d: 'M21 3H3c-1.11 0-2 .89-2 2v14c0 1.11.89 2 2 2h18c1.11 0 2-.89 2-2V5c0-1.11-.89-2-2-2zm0 16.02H3V4.98h18v14.04zM10 12H8l4-4 4 4h-2v4h-4v-4z' }) ); }; CommunicationPresentToAll = (0, _pure2.default)(CommunicationPresentToAll); CommunicationPresentToAll.displayName = 'CommunicationPresentToAll'; CommunicationPresentToAll.muiName = 'SvgIcon'; exports.default = CommunicationPresentToAll;
Jorginho211/TFG
web/node_modules/material-ui/svg-icons/communication/present-to-all.js
JavaScript
gpl-3.0
1,020
var cssbeautify = require('gulp-cssbeautify'); var gulp = require('gulp'); var imagemin = require('gulp-imagemin'); var jsprettify = require('gulp-jsbeautifier'); var path = require('path'); var pngcrush = require('imagemin-pngcrush'); var ROOT = path.join(__dirname, '..'); gulp.task('format-css', function() { var files = [ 'src/**/*.css', '!src/aui-css/css/*.css' ]; return gulp.src(files, { cwd: ROOT }) .pipe(cssbeautify()) .pipe(gulp.dest(path.join(ROOT, 'src/'))); }); gulp.task('format-js', function() { var configFile = path.join(ROOT, '.jsbeautifyrc'); var files = [ 'src/**/*.js', '!build/**/*.js', '!src/aui-base/js/aui-aliases.js', '!src/aui-base/js/aui-loader.js', '!src/yui/js/*.js' ]; return gulp.src(files, { cwd: ROOT }) .pipe(jsprettify({ config: configFile })) .pipe(gulp.dest(path.join(ROOT, 'src/'))); }); gulp.task('format-img', function() { return gulp.src('src/**/*.png', { cwd: ROOT }) .pipe(imagemin({ progressive: true, svgoPlugins: [{ removeViewBox: false }], use: [pngcrush()] })) .pipe(gulp.dest(path.join(ROOT, 'src/'))); }); gulp.task('format', ['format-css', 'format-js', 'format-img']);
dsanz/alloy-ui
tasks/format.js
JavaScript
bsd-3-clause
1,356
/** * @license Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.md or http://ckeditor.com/license */ /** * This file was added automatically by CKEditor builder. * You may re-use it at any time to build CKEditor again. * * If you would like to build CKEditor online again * (for example to upgrade), visit one the following links: * * (1) http://ckeditor.com/builder * Visit online builder to build CKEditor from scratch. * * (2) http://ckeditor.com/builder/e41bccb8290b6d530f8478ddafe95c48 * Visit online builder to build CKEditor, starting with the same setup as before. * * (3) http://ckeditor.com/builder/download/e41bccb8290b6d530f8478ddafe95c48 * Straight download link to the latest version of CKEditor (Optimized) with the same setup as before. * * NOTE: * This file is not used by CKEditor, you may remove it. * Changing this file will not change your CKEditor configuration. */ var CKBUILDER_CONFIG = { skin: 'moono', preset: 'standard', ignore: [ 'dev', '.gitignore', '.gitattributes', 'README.md', '.mailmap' ], plugins : { 'a11yhelp' : 1, 'about' : 1, 'basicstyles' : 1, 'blockquote' : 1, 'clipboard' : 1, 'contextmenu' : 1, 'elementspath' : 1, 'enterkey' : 1, 'entities' : 1, 'filebrowser' : 1, 'floatingspace' : 1, 'format' : 1, 'horizontalrule' : 1, 'htmlwriter' : 1, 'image' : 1, 'indentlist' : 1, 'link' : 1, 'list' : 1, 'magicline' : 1, 'maximize' : 1, 'pastefromword' : 1, 'pastetext' : 1, 'removeformat' : 1, 'resize' : 1, 'scayt' : 1, 'showborders' : 1, 'sourcearea' : 1, 'specialchar' : 1, 'stylescombo' : 1, 'tab' : 1, 'table' : 1, 'tabletools' : 1, 'toolbar' : 1, 'undo' : 1, 'wsc' : 1, 'wysiwygarea' : 1 }, languages : { 'af' : 1, 'ar' : 1, 'bg' : 1, 'bn' : 1, 'bs' : 1, 'ca' : 1, 'cs' : 1, 'cy' : 1, 'da' : 1, 'de' : 1, 'el' : 1, 'en' : 1, 'en-au' : 1, 'en-ca' : 1, 'en-gb' : 1, 'eo' : 1, 'es' : 1, 'et' : 1, 'eu' : 1, 'fa' : 1, 'fi' : 1, 'fo' : 1, 'fr' : 1, 'fr-ca' : 1, 'gl' : 1, 'gu' : 1, 'he' : 1, 'hi' : 1, 'hr' : 1, 'hu' : 1, 'id' : 1, 'is' : 1, 'it' : 1, 'ja' : 1, 'ka' : 1, 'km' : 1, 'ko' : 1, 'ku' : 1, 'lt' : 1, 'lv' : 1, 'mk' : 1, 'mn' : 1, 'ms' : 1, 'nb' : 1, 'nl' : 1, 'no' : 1, 'pl' : 1, 'pt' : 1, 'pt-br' : 1, 'ro' : 1, 'ru' : 1, 'si' : 1, 'sk' : 1, 'sl' : 1, 'sq' : 1, 'sr' : 1, 'sr-latn' : 1, 'sv' : 1, 'th' : 1, 'tr' : 1, 'tt' : 1, 'ug' : 1, 'uk' : 1, 'vi' : 1, 'zh' : 1, 'zh-cn' : 1 } };
pipedot/pipecode
www/lib/ckeditor/build-config.js
JavaScript
agpl-3.0
2,692
/** * 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. */ 'use strict'; var COLLECTION_PERIOD = 1000; var _endedEvents = Object.create(null); var _eventStarts = Object.create(null); var _queuedActions = []; var _scheduledCollectionTimer = null; var _uuid = 1; var _enabled = true; function endEvent(eventId) { var eventEndTime = Date.now(); if (!_eventStarts[eventId]) { _throw('event(' + eventId + ') is not a valid event id!'); } if (_endedEvents[eventId]) { _throw('event(' + eventId + ') has already ended!'); } _scheduleAction({ action: 'endEvent', eventId: eventId, tstamp: eventEndTime }); _endedEvents[eventId] = true; } function signal(eventName, data) { var signalTime = Date.now(); if (eventName == null) { _throw('No event name specified'); } if (data == null) { data = null; } _scheduleAction({ action: 'signal', data: data, eventName: eventName, tstamp: signalTime }); } function startEvent(eventName, data) { var eventStartTime = Date.now(); if (eventName == null) { _throw('No event name specified'); } if (data == null) { data = null; } var eventId = _uuid++; var action = { action: 'startEvent', data: data, eventId: eventId, eventName: eventName, tstamp: eventStartTime, }; _scheduleAction(action); _eventStarts[eventId] = action; return eventId; } function disable() { _enabled = false; } function _runCollection() { /* jshint -W084 */ var action; while ((action = _queuedActions.shift())) { _writeAction(action); } _scheduledCollectionTimer = null; } function _scheduleAction(action) { _queuedActions.push(action); if (_scheduledCollectionTimer === null) { _scheduledCollectionTimer = setTimeout(_runCollection, COLLECTION_PERIOD); } } /** * This a utility function that throws an error message. * * The only purpose of this utility is to make APIs like * startEvent/endEvent/signal inlineable in the JIT. * * (V8 can't inline functions that statically contain a `throw`, and probably * won't be adding such a non-trivial optimization anytime soon) */ function _throw(msg) { var err = new Error(msg); // Strip off the call to _throw() var stack = err.stack.split('\n'); stack.splice(1, 1); err.stack = stack.join('\n'); throw err; } function _writeAction(action) { if (!_enabled) { return; } var data = action.data ? ': ' + JSON.stringify(action.data) : ''; var fmtTime = new Date(action.tstamp).toLocaleTimeString(); switch (action.action) { case 'startEvent': console.log( '[' + fmtTime + '] ' + '<START> ' + action.eventName + data ); break; case 'endEvent': var startAction = _eventStarts[action.eventId]; var startData = startAction.data ? ': ' + JSON.stringify(startAction.data) : ''; console.log( '[' + fmtTime + '] ' + '<END> ' + startAction.eventName + '(' + (action.tstamp - startAction.tstamp) + 'ms)' + startData ); delete _eventStarts[action.eventId]; break; case 'signal': console.log( '[' + fmtTime + '] ' + ' ' + action.eventName + '' + data ); break; default: _throw('Unexpected scheduled action type: ' + action.action); } } exports.endEvent = endEvent; exports.signal = signal; exports.startEvent = startEvent; exports.disable = disable;
WPDreamMelody/react-native
packager/react-packager/src/Activity/index.js
JavaScript
bsd-3-clause
3,730
(function( factory ) { if ( typeof define === "function" && define.amd ) { define( ["jquery", "../jquery.validate"], factory ); } else if (typeof module === "object" && module.exports) { module.exports = factory( require( "jquery" ) ); } else { factory( jQuery ); } }(function( $ ) { /* * Translated default messages for the jQuery validation plugin. * Locale: ZH (Chinese, 中文 (Zhōngwén), 汉语, 漢語) */ $.extend( $.validator.messages, { required: "这是必填字段", remote: "请修正此字段", email: "请输入有效的电子邮件地址", url: "请输入有效的网址", date: "请输入有效的日期", dateISO: "请输入有效的日期 (YYYY-MM-DD)", number: "请输入有效的数字", digits: "只能输入数字", creditcard: "请输入有效的信用卡号码", equalTo: "你的输入不相同", extension: "请输入有效的后缀", maxlength: $.validator.format( "最多可以输入 {0} 个字符" ), minlength: $.validator.format( "最少要输入 {0} 个字符" ), rangelength: $.validator.format( "请输入长度在 {0} 到 {1} 之间的字符串" ), range: $.validator.format( "请输入范围在 {0} 到 {1} 之间的数值" ), step: $.validator.format( "请输入 {0} 的整数倍值" ), max: $.validator.format( "请输入不大于 {0} 的数值" ), min: $.validator.format( "请输入不小于 {0} 的数值" ) } ); return $; }));
danryan/jquery-validation-rails
vendor/assets/javascripts/jquery.validate.localization/messages_zh.js
JavaScript
mit
1,401
/*! * Ext JS Library 3.4.0 * Copyright(c) 2006-2011 Sencha Inc. * licensing@sencha.com * http://www.sencha.com/license */ (function() { Ext.override(Ext.list.Column, { init : function() { var types = Ext.data.Types, st = this.sortType; if(this.type){ if(Ext.isString(this.type)){ this.type = Ext.data.Types[this.type.toUpperCase()] || types.AUTO; } }else{ this.type = types.AUTO; } // named sortTypes are supported, here we look them up if(Ext.isString(st)){ this.sortType = Ext.data.SortTypes[st]; }else if(Ext.isEmpty(st)){ this.sortType = this.type.sortType; } } }); Ext.tree.Column = Ext.extend(Ext.list.Column, {}); Ext.tree.NumberColumn = Ext.extend(Ext.list.NumberColumn, {}); Ext.tree.DateColumn = Ext.extend(Ext.list.DateColumn, {}); Ext.tree.BooleanColumn = Ext.extend(Ext.list.BooleanColumn, {}); Ext.reg('tgcolumn', Ext.tree.Column); Ext.reg('tgnumbercolumn', Ext.tree.NumberColumn); Ext.reg('tgdatecolumn', Ext.tree.DateColumn); Ext.reg('tgbooleancolumn', Ext.tree.BooleanColumn); })();
x-meta/xworker
xworker_web_extjs/webroot/js/extjs/ux/treegrid/TreeGridColumns.js
JavaScript
apache-2.0
1,301
'use strict'; module.exports.definition = { set: function (v) { this._setProperty('position', v); }, get: function () { return this.getPropertyValue('position'); }, enumerable: true, configurable: true };
ElvisLouis/code
work/js/node_modules/jsdom/node_modules/cssstyle/lib/properties/position.js
JavaScript
gpl-2.0
246
/* babelfish 1.0.2 nodeca/babelfish */!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.Babelfish=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){ module.exports = _dereq_('./lib/babelfish'); },{"./lib/babelfish":2}],2:[function(_dereq_,module,exports){ /** * class BabelFish * * Internalization and localization library that makes i18n and l10n fun again. * * ##### Example * * ```javascript * var BabelFish = require('babelfish'), * i18n = new BabelFish(); * ``` * * or * * ```javascript * var babelfish = require('babelfish'), * i18n = babelfish(); * ``` **/ 'use strict'; var parser = _dereq_('./babelfish/parser'); var pluralizer = _dereq_('./babelfish/pluralizer'); function _class(obj) { return Object.prototype.toString.call(obj); } function isString(obj) { return _class(obj) === '[object String]'; } function isNumber(obj) { return !isNaN(obj) && isFinite(obj); } function isBoolean(obj) { return obj === true || obj === false; } function isFunction(obj) { return _class(obj) === '[object Function]'; } function isObject(obj) { return _class(obj) === '[object Object]'; } var isArray = Array.isArray || function _isArray(obj) { return _class(obj) === '[object Array]'; }; //////////////////////////////////////////////////////////////////////////////// // The following two utilities (forEach and extend) are modified from Underscore // // http://underscorejs.org // // (c) 2009-2013 Jeremy Ashkenas, DocumentCloud Inc. // // Underscore may be freely distributed under the MIT license //////////////////////////////////////////////////////////////////////////////// var nativeForEach = Array.prototype.forEach; // The cornerstone, an `each` implementation, aka `forEach`. // Handles objects with the built-in `forEach`, arrays, and raw objects. // Delegates to **ECMAScript 5**'s native `forEach` if available. function forEach(obj, iterator, context) { if (obj === null) { return; } if (nativeForEach && obj.forEach === nativeForEach) { obj.forEach(iterator, context); } else if (obj.length === +obj.length) { for (var i = 0, l = obj.length; i < l; i += 1) { iterator.call(context, obj[i], i, obj); } } else { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { iterator.call(context, obj[key], key, obj); } } } } var formatRegExp = /%[sdj%]/g; function format(f) { var i = 1; var args = arguments; var len = args.length; var str = String(f).replace(formatRegExp, function(x) { if (x === '%%') { return '%'; } if (i >= len) { return x; } switch (x) { case '%s': return String(args[i++]); case '%d': return Number(args[i++]); case '%j': return JSON.stringify(args[i++]); default: return x; } }); return str; } // helpers //////////////////////////////////////////////////////////////////////////////// // Last resort locale, that exists for sure var GENERIC_LOCALE = 'en'; // flatten(obj) -> Object // // Flattens object into one-level dictionary. // // ##### Example // // var obj = { // abc: { def: 'foo' }, // hij: 'bar' // }; // // flatten(obj); // // -> { 'abc.def': 'foo', 'hij': 'bar' }; // function flatten(obj) { var params = {}; forEach(obj || {}, function (val, key) { if (val && 'object' === typeof val) { forEach(flatten(val), function (sub_val, sub_key) { params[key + '.' + sub_key] = sub_val; }); return; } params[key] = val; }); return params; } var keySeparator = '#@$'; function makePhraseKey(locale, phrase) { return locale + keySeparator + phrase; } function searchPhraseKey(self, locale, phrase) { var key = makePhraseKey(locale, phrase); var storage = self._storage; // direct search first if (storage.hasOwnProperty(key)) { return key; } // don't try follbacks for default locale if (locale === self._defaultLocale) { return null; } // search via fallback map cache var fb_cache = self._fallbacks_cache; if (fb_cache.hasOwnProperty(key)) { return fb_cache[key]; } // scan fallbacks & cache result var fb = self._fallbacks[locale] || [self._defaultLocale]; var fb_key; for (var i=0, l=fb.length; i<l; i++) { fb_key = makePhraseKey(fb[i], phrase); if (storage.hasOwnProperty(fb_key)) { // found - update cache and return result fb_cache[key] = fb_key; return fb_cache[key]; } } // mark fb_cache entry empty for fast lookup on next request fb_cache[key] = null; return null; } // public api (module) //////////////////////////////////////////////////////////////////////////////// /** * new BabelFish([defaultLocale = 'en']) * * Initiates new instance of BabelFish. * * __Note!__ you can omit `new` for convenience, direct call will return * new instance too. **/ function BabelFish(defaultLocale) { if (!(this instanceof BabelFish)) { return new BabelFish(defaultLocale); } this._defaultLocale = defaultLocale ? String(defaultLocale) : GENERIC_LOCALE; // hash of locale => [ fallback1, fallback2, ... ] pairs this._fallbacks = {}; // fallback cache for each phrase // // { // locale_key: fallback_key // } // // fallback_key can be null if search failed // this._fallbacks_cache = {}; // storage of compiled translations // // { // locale + @#$ + phrase_key: { // locale: locale name - can be different for fallbacks // translation: original translation phrase or data variable/object // raw: true/false - does translation contain plain data or // string to compile // compiled: copiled translation fn or plain string // } // ... // } // this._storage = {}; // cache for complex plural parts (with params) // // { // language: new BabelFish(language) // } // this._plurals_cache = {}; } // public api (instance) //////////////////////////////////////////////////////////////////////////////// /** * BabelFish#addPhrase(locale, phrase, translation [, flattenLevel]) -> BabelFish * - locale (String): Locale of translation * - phrase (String|Null): Phrase ID, e.g. `apps.forum` * - translation (String|Object|Array|Number|Boolean): Translation or an object * with nested phrases, or a pure object. * - flattenLevel (Number|Boolean): Optional, 0..infinity. `Infinity` by default. * Define "flatten" deepness for loaded object. You can also use * `true` as `0` or `false` as `Infinity`. * * * ##### Flatten & using JS objects * * By default all nested properties are normalized to strings like "foo.bar.baz", * and if value is string, it will be compiled with babelfish notation. * If deepness is above `flattenLevel` OR value is not object and not string, * it will be used "as is". Note, only JSON stringifiable data should be used. * * In short: you can safely pass `Array`, `Number` or `Boolean`. For objects you * should define flatten level or disable it compleetely, to work with pure data. * * Pure objects can be useful to prepare bulk data for external libraries, like * calendars, time/date generators and so on. * * ##### Example * * ```javascript * i18n.addPhrase('ru-RU', * 'apps.forums.replies_count', * '#{count} %{ответ|ответа|ответов}:count в теме'); * * // equals to: * i18n.addPhrase('ru-RU', * 'apps.forums', * { replies_count: '#{count} %{ответ|ответа|ответов}:count в теме' }); * ``` **/ BabelFish.prototype.addPhrase = function _addPhrase(locale, phrase, translation, flattenLevel) { var self = this, fl; // Calculate flatten level. Infinity by default if (isBoolean(flattenLevel)) { fl = flattenLevel ? Infinity : 0; } else if (isNumber(flattenLevel)) { fl = Math.floor(flattenLevel); fl = (fl < 0) ? 0 : fl; } else { fl = Infinity; } if (isObject(translation) && (fl > 0)) { // recursive object walk, until flattenLevel allows forEach(translation, function (val, key) { self.addPhrase(locale, phrase + '.' + key, val, fl-1); }); return; } if (isString(translation)) { this._storage[makePhraseKey(locale, phrase)] = { translation: translation, locale: locale, raw: false }; } else if (isArray(translation) || isNumber(translation) || isBoolean(translation) || (fl === 0 && isObject(translation))) { // Pure objects are stored without compilation // Limit allowed types. this._storage[makePhraseKey(locale, phrase)] = { translation: translation, locale: locale, raw: true }; } else { // `Regex`, `Date`, `Uint8Array` and others types will // fuckup `stringify()`. Don't allow here. // `undefined` also means wrong param in real life. // `null` can be allowed when examples from real life available. throw new TypeError('Invalid translation - [String|Object|Array|Number|Boolean] expected.'); } self._fallbacks_cache = {}; }; /** * BabelFish#setFallback(locale, fallbacks) -> BabelFish * - locale (String): Target locale * - fallbacks (Array): List of fallback locales * * Set fallbacks for given locale. * * When `locale` has no translation for the phrase, `fallbacks[0]` will be * tried, if translation still not found, then `fallbacks[1]` will be tried * and so on. If none of fallbacks have translation, * default locale will be tried as last resort. * * ##### Errors * * - throws `Error`, when `locale` equals default locale * * ##### Example * * ```javascript * i18n.setFallback('ua-UK', ['ua', 'ru']); * ``` **/ BabelFish.prototype.setFallback = function _setFallback(locale, fallbacks) { var def = this._defaultLocale; if (def === locale) { throw new Error('Default locale can\'t have fallbacks'); } var fb = isArray(fallbacks) ? fallbacks.slice() : [fallbacks]; if (fb[fb.length-1] !== def) { fb.push(def); } this._fallbacks[locale] = fb; this._fallbacks_cache = {}; }; // Compiles given string into function. Used to compile phrases, // which contains `plurals`, `variables`, etc. function compile(self, str, locale) { var nodes, buf, key, strict_exec, forms_exec, plurals_cache; // Quick check to avoid parse in most cases :) if (str.indexOf('#{') === -1 && str.indexOf('((') === -1 && str.indexOf('\\') === -1) { return str; } nodes = parser.parse(str); if (1 === nodes.length && 'literal' === nodes[0].type) { return nodes[0].text; } // init cache instance for plural parts, if not exists yet. if (!self._plurals_cache[locale]) { self._plurals_cache[locale] = new BabelFish(locale); } plurals_cache = self._plurals_cache[locale]; buf = []; buf.push(['var str = "", strict, strict_exec, forms, forms_exec, plrl, cache, loc, loc_plzr, anchor;']); buf.push('params = flatten(params);'); forEach(nodes, function (node) { if ('literal' === node.type) { buf.push(format('str += %j;', node.text)); return; } if ('variable' === node.type) { key = node.anchor; buf.push(format( 'str += ("undefined" === typeof (params[%j])) ? "[missed variable: %s]" : params[%j];', key, key, key )); return; } if ('plural' === node.type) { key = node.anchor; // check if plural parts are plain strings or executable, // and add executable to "cache" instance of babelfish // plural part text will be used as translation key strict_exec = {}; forEach(node.strict, function (text, key) { if (text === '') { strict_exec[key] = false; return; } var parsed = parser.parse(text); if (1 === parsed.length && 'literal' === parsed[0].type) { strict_exec[key] = false; // patch with unescaped value for direct extract node.strict[key] = parsed[0].text; return; } strict_exec[key] = true; if (!plurals_cache.hasPhrase(locale, text, true)) { plurals_cache.addPhrase(locale, text, text); } }); forms_exec = {}; forEach(node.forms, function (text, idx) { if (text === '') { forms_exec[''] = false; return; } var parsed = parser.parse(text), unescaped; if (1 === parsed.length && 'literal' === parsed[0].type) { // patch with unescaped value for direct extract unescaped = parsed[0].text; node.forms[idx] = unescaped; forms_exec[unescaped] = false; return; } forms_exec[text] = true; if (!plurals_cache.hasPhrase(locale, text, true)) { plurals_cache.addPhrase(locale, text, text); } }); buf.push(format('loc = %j;', locale)); buf.push(format('loc_plzr = %j;', locale.split(/[-_]/)[0])); buf.push(format('anchor = params[%j];', key)); buf.push(format('cache = this._plurals_cache[loc];')); buf.push(format('strict = %j;', node.strict)); buf.push(format('strict_exec = %j;', strict_exec)); buf.push(format('forms = %j;', node.forms)); buf.push(format('forms_exec = %j;', forms_exec)); buf.push( 'if (+(anchor) != anchor) {'); buf.push(format(' str += "[invalid plurals amount: %s(" + anchor + ")]";', key)); buf.push( '} else {'); buf.push( ' if (strict[anchor] !== undefined) {'); buf.push( ' plrl = strict[anchor];'); buf.push( ' str += strict_exec[anchor] ? cache.t(loc, plrl, params) : plrl;'); buf.push( ' } else {'); buf.push( ' plrl = pluralizer(loc_plzr, +anchor, forms);'); buf.push( ' str += forms_exec[plrl] ? cache.t(loc, plrl, params) : plrl;'); buf.push( ' }'); buf.push( '}'); return; } // should never happen throw new Error('Unknown node type'); }); buf.push('return str;'); /*jslint evil:true*/ return new Function('params', 'flatten', 'pluralizer', buf.join('\n')); } /** * BabelFish#translate(locale, phrase[, params]) -> String * - locale (String): Locale of translation * - phrase (String): Phrase ID, e.g. `app.forums.replies_count` * - params (Object|Number|String): Params for translation. `Number` & `String` * will be coerced to `{ count: X, value: X }` * * ##### Example * * ```javascript * i18n.addPhrase('ru-RU', * 'apps.forums.replies_count', * '#{count} ((ответ|ответа|ответов)) в теме'); * * // ... * * i18n.translate('ru-RU', 'app.forums.replies_count', { count: 1 }); * i18n.translate('ru-RU', 'app.forums.replies_count', 1}); * // -> '1 ответ' * * i18n.translate('ru-RU', 'app.forums.replies_count', { count: 2 }); * i18n.translate('ru-RU', 'app.forums.replies_count', 2); * // -> '2 ответa' * ``` **/ BabelFish.prototype.translate = function _translate(locale, phrase, params) { var key = searchPhraseKey(this, locale, phrase); var data; if (!key) { return locale + ': No translation for [' + phrase + ']'; } data = this._storage[key]; // simple string or other pure object if (data.raw) { return data.translation; } // compile data if not done yet if (!data.hasOwnProperty('compiled')) { // We should use locale from phrase, because of possible fallback, // to keep plural locales in sync. data.compiled = compile(this, data.translation, data.locale); } // return simple string immediately if (!isFunction(data.compiled)) { return data.compiled; } // // Generate "complex" phrase // // Sugar: coerce numbers & strings to { count: X, value: X } if (isNumber(params) || isString (params)) { params = { count: params, value: params }; } return data.compiled.call(this, params, flatten, pluralizer); }; /** * BabelFish#hasPhrase(locale, phrase) -> Boolean * - locale (String): Locale of translation * - phrase (String): Phrase ID, e.g. `app.forums.replies_count` * - noFallback (Boolean): Disable search in fallbacks * * Returns whenever or not there's a translation of a `phrase`. **/ BabelFish.prototype.hasPhrase = function _hasPhrase(locale, phrase, noFallback) { return noFallback ? this._storage.hasOwnProperty(makePhraseKey(locale, phrase)) : searchPhraseKey(this, locale, phrase) ? true : false; }; /** alias of: BabelFish#translate * BabelFish#t(locale, phrase[, params]) -> String **/ BabelFish.prototype.t = BabelFish.prototype.translate; /** * BabelFish#stringify(locale) -> String * - locale (String): Locale of translation * * Returns serialized locale data, uncluding fallbacks. * It can be loaded back via `load()` method. **/ BabelFish.prototype.stringify = function _stringify(locale) { var self = this; // Collect unique keys var unique = {}; forEach(this._storage, function (val, key) { unique[key.split(keySeparator)[1]] = true; }); // Collect phrases (with fallbacks) var result = {}; forEach(unique, function(val, key) { var k = searchPhraseKey(self, locale, key); // if key was just a garbage from another // and doesn't fit into fallback chain for current locale - skip it if (!k) { return; } // create namespace if not exists var l = self._storage[k].locale; if (!result[l]) { result[l] = {}; } result[l][key] = self._storage[k].translation; }); // Get fallback rule. Cut auto-added fallback to default locale var fallback = (self._fallbacks[locale] || []).pop(); return JSON.stringify({ fallback: { locale: fallback }, locales: result }); }; /** * BabelFish#load(data) * - data (Object|String) - data from `stringify()` method, as object or string. * * Batch load phrases data, prepared with `stringify()` method. * Useful at browser side. **/ BabelFish.prototype.load = function _load(data) { var self = this; if (isString(data)) { data = JSON.parse(data); } forEach(data.locales, function (phrases, locale) { forEach(phrases, function(translation, key) { self.addPhrase(locale, key, translation, 0); }); }); forEach(data.fallback, function (rule, locale) { if (rule.length) { self.setFallback(locale, rule); } }); }; // export module module.exports = BabelFish; },{"./babelfish/parser":3,"./babelfish/pluralizer":4}],3:[function(_dereq_,module,exports){ module.exports = (function() { /* * Generated by PEG.js 0.8.0. * * http://pegjs.majda.cz/ */ function peg$subclass(child, parent) { function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); } function SyntaxError(message, expected, found, offset, line, column) { this.message = message; this.expected = expected; this.found = found; this.offset = offset; this.line = line; this.column = column; this.name = "SyntaxError"; } peg$subclass(SyntaxError, Error); function parse(input) { var options = arguments.length > 1 ? arguments[1] : {}, peg$FAILED = {}, peg$startRuleIndices = { start: 0 }, peg$startRuleIndex = 0, peg$consts = [ [], peg$FAILED, "((", { type: "literal", value: "((", description: "\"((\"" }, "))", { type: "literal", value: "))", description: "\"))\"" }, null, function(forms, anchor) { return { type: 'plural', forms: regularForms(forms), strict: strictForms(forms), anchor: anchor || 'count' }; }, "|", { type: "literal", value: "|", description: "\"|\"" }, function(part, more) { return [part].concat(more); }, function(part) { return [part]; }, "=", { type: "literal", value: "=", description: "\"=\"" }, /^[0-9]/, { type: "class", value: "[0-9]", description: "[0-9]" }, " ", { type: "literal", value: " ", description: "\" \"" }, function(strict, form) { return { strict: strict.join(''), text: form.join('') } }, function() { return { text: text() }; }, "\\", { type: "literal", value: "\\", description: "\"\\\\\"" }, /^[\\|)(]/, { type: "class", value: "[\\\\|)(]", description: "[\\\\|)(]" }, function(char) { return char; }, void 0, { type: "any", description: "any character" }, function() { return text(); }, ":", { type: "literal", value: ":", description: "\":\"" }, function(name) { return name; }, "#{", { type: "literal", value: "#{", description: "\"#{\"" }, "}", { type: "literal", value: "}", description: "\"}\"" }, function(anchor) { return { type: 'variable', anchor: anchor }; }, ".", { type: "literal", value: ".", description: "\".\"" }, function() { return text() }, /^[a-zA-Z_$]/, { type: "class", value: "[a-zA-Z_$]", description: "[a-zA-Z_$]" }, /^[a-zA-Z0-9_$]/, { type: "class", value: "[a-zA-Z0-9_$]", description: "[a-zA-Z0-9_$]" }, function(lc) { return lc; }, function(literal_chars) { return { type: 'literal', text: literal_chars.join('') }; }, /^[\\#()]/, { type: "class", value: "[\\\\#()]", description: "[\\\\#()]" } ], peg$bytecode = [ peg$decode(" 7)*) \"7!*# \"7&,/&7)*) \"7!*# \"7&\""), peg$decode("!.\"\"\"2\"3#+S$7\"+I%.$\"\"2$3%+9%7%*# \" &+)%4$6'$\"\" %$$# !$## !$\"# !\"# !"), peg$decode("!7#+C$.(\"\"2(3)+3%7\"+)%4#6*#\"\" %$## !$\"# !\"# !*/ \"!7#+' 4!6+!! %"), peg$decode("!.,\"\"2,3-+}$ 0.\"\"1!3/+,$,)&0.\"\"1!3/\"\"\" !+X%.0\"\"2031*# \" &+B% 7$+&$,#&7$\"\"\" !+)%4$62$\"\" %$$# !$## !$\"# !\"# !*= \"! 7$+&$,#&7$\"\"\" !+& 4!63! %"), peg$decode("!.4\"\"2435+8$06\"\"1!37+(%4\"68\"! %$\"# !\"# !*a \"!!8.(\"\"2(3)*) \".$\"\"2$3%9*$$\"\" 9\"# !+6$-\"\"1!3:+'%4\"6;\" %$\"# !\"# !"), peg$decode("!.<\"\"2<3=+2$7'+(%4\"6>\"! %$\"# !\"# !"), peg$decode("!.?\"\"2?3@+B$7'+8%.A\"\"2A3B+(%4#6C#!!%$## !$\"# !\"# !"), peg$decode("!7(+P$.D\"\"2D3E+@% 7'+&$,#&7'\"\"\" !+'%4#6F# %$## !$\"# !\"# !*# \"7("), peg$decode("!0G\"\"1!3H+E$ 0I\"\"1!3J,)&0I\"\"1!3J\"+'%4\"6;\" %$\"# !\"# !"), peg$decode("! !!87!*# \"7&9*$$\"\" 9\"# !+2$7*+(%4\"6K\"! %$\"# !\"# !+T$,Q&!!87!*# \"7&9*$$\"\" 9\"# !+2$7*+(%4\"6K\"! %$\"# !\"# !\"\"\" !+' 4!6L!! %"), peg$decode("!.4\"\"2435+8$0M\"\"1!3N+(%4\"68\"! %$\"# !\"# !*( \"-\"\"1!3:") ], peg$currPos = 0, peg$reportedPos = 0, peg$cachedPos = 0, peg$cachedPosDetails = { line: 1, column: 1, seenCR: false }, peg$maxFailPos = 0, peg$maxFailExpected = [], peg$silentFails = 0, peg$result; if ("startRule" in options) { if (!(options.startRule in peg$startRuleIndices)) { throw new Error("Can't start parsing from rule \"" + options.startRule + "\"."); } peg$startRuleIndex = peg$startRuleIndices[options.startRule]; } function text() { return input.substring(peg$reportedPos, peg$currPos); } function offset() { return peg$reportedPos; } function line() { return peg$computePosDetails(peg$reportedPos).line; } function column() { return peg$computePosDetails(peg$reportedPos).column; } function expected(description) { throw peg$buildException( null, [{ type: "other", description: description }], peg$reportedPos ); } function error(message) { throw peg$buildException(message, null, peg$reportedPos); } function peg$computePosDetails(pos) { function advance(details, startPos, endPos) { var p, ch; for (p = startPos; p < endPos; p++) { ch = input.charAt(p); if (ch === "\n") { if (!details.seenCR) { details.line++; } details.column = 1; details.seenCR = false; } else if (ch === "\r" || ch === "\u2028" || ch === "\u2029") { details.line++; details.column = 1; details.seenCR = true; } else { details.column++; details.seenCR = false; } } } if (peg$cachedPos !== pos) { if (peg$cachedPos > pos) { peg$cachedPos = 0; peg$cachedPosDetails = { line: 1, column: 1, seenCR: false }; } advance(peg$cachedPosDetails, peg$cachedPos, pos); peg$cachedPos = pos; } return peg$cachedPosDetails; } function peg$fail(expected) { if (peg$currPos < peg$maxFailPos) { return; } if (peg$currPos > peg$maxFailPos) { peg$maxFailPos = peg$currPos; peg$maxFailExpected = []; } peg$maxFailExpected.push(expected); } function peg$buildException(message, expected, pos) { function cleanupExpected(expected) { var i = 1; expected.sort(function(a, b) { if (a.description < b.description) { return -1; } else if (a.description > b.description) { return 1; } else { return 0; } }); while (i < expected.length) { if (expected[i - 1] === expected[i]) { expected.splice(i, 1); } else { i++; } } } function buildMessage(expected, found) { function stringEscape(s) { function hex(ch) { return ch.charCodeAt(0).toString(16).toUpperCase(); } return s .replace(/\\/g, '\\\\') .replace(/"/g, '\\"') .replace(/\x08/g, '\\b') .replace(/\t/g, '\\t') .replace(/\n/g, '\\n') .replace(/\f/g, '\\f') .replace(/\r/g, '\\r') .replace(/[\x00-\x07\x0B\x0E\x0F]/g, function(ch) { return '\\x0' + hex(ch); }) .replace(/[\x10-\x1F\x80-\xFF]/g, function(ch) { return '\\x' + hex(ch); }) .replace(/[\u0180-\u0FFF]/g, function(ch) { return '\\u0' + hex(ch); }) .replace(/[\u1080-\uFFFF]/g, function(ch) { return '\\u' + hex(ch); }); } var expectedDescs = new Array(expected.length), expectedDesc, foundDesc, i; for (i = 0; i < expected.length; i++) { expectedDescs[i] = expected[i].description; } expectedDesc = expected.length > 1 ? expectedDescs.slice(0, -1).join(", ") + " or " + expectedDescs[expected.length - 1] : expectedDescs[0]; foundDesc = found ? "\"" + stringEscape(found) + "\"" : "end of input"; return "Expected " + expectedDesc + " but " + foundDesc + " found."; } var posDetails = peg$computePosDetails(pos), found = pos < input.length ? input.charAt(pos) : null; if (expected !== null) { cleanupExpected(expected); } return new SyntaxError( message !== null ? message : buildMessage(expected, found), expected, found, pos, posDetails.line, posDetails.column ); } function peg$decode(s) { var bc = new Array(s.length), i; for (i = 0; i < s.length; i++) { bc[i] = s.charCodeAt(i) - 32; } return bc; } function peg$parseRule(index) { var bc = peg$bytecode[index], ip = 0, ips = [], end = bc.length, ends = [], stack = [], params, i; function protect(object) { return Object.prototype.toString.apply(object) === "[object Array]" ? [] : object; } while (true) { while (ip < end) { switch (bc[ip]) { case 0: stack.push(protect(peg$consts[bc[ip + 1]])); ip += 2; break; case 1: stack.push(peg$currPos); ip++; break; case 2: stack.pop(); ip++; break; case 3: peg$currPos = stack.pop(); ip++; break; case 4: stack.length -= bc[ip + 1]; ip += 2; break; case 5: stack.splice(-2, 1); ip++; break; case 6: stack[stack.length - 2].push(stack.pop()); ip++; break; case 7: stack.push(stack.splice(stack.length - bc[ip + 1], bc[ip + 1])); ip += 2; break; case 8: stack.pop(); stack.push(input.substring(stack[stack.length - 1], peg$currPos)); ip++; break; case 9: ends.push(end); ips.push(ip + 3 + bc[ip + 1] + bc[ip + 2]); if (stack[stack.length - 1]) { end = ip + 3 + bc[ip + 1]; ip += 3; } else { end = ip + 3 + bc[ip + 1] + bc[ip + 2]; ip += 3 + bc[ip + 1]; } break; case 10: ends.push(end); ips.push(ip + 3 + bc[ip + 1] + bc[ip + 2]); if (stack[stack.length - 1] === peg$FAILED) { end = ip + 3 + bc[ip + 1]; ip += 3; } else { end = ip + 3 + bc[ip + 1] + bc[ip + 2]; ip += 3 + bc[ip + 1]; } break; case 11: ends.push(end); ips.push(ip + 3 + bc[ip + 1] + bc[ip + 2]); if (stack[stack.length - 1] !== peg$FAILED) { end = ip + 3 + bc[ip + 1]; ip += 3; } else { end = ip + 3 + bc[ip + 1] + bc[ip + 2]; ip += 3 + bc[ip + 1]; } break; case 12: if (stack[stack.length - 1] !== peg$FAILED) { ends.push(end); ips.push(ip); end = ip + 2 + bc[ip + 1]; ip += 2; } else { ip += 2 + bc[ip + 1]; } break; case 13: ends.push(end); ips.push(ip + 3 + bc[ip + 1] + bc[ip + 2]); if (input.length > peg$currPos) { end = ip + 3 + bc[ip + 1]; ip += 3; } else { end = ip + 3 + bc[ip + 1] + bc[ip + 2]; ip += 3 + bc[ip + 1]; } break; case 14: ends.push(end); ips.push(ip + 4 + bc[ip + 2] + bc[ip + 3]); if (input.substr(peg$currPos, peg$consts[bc[ip + 1]].length) === peg$consts[bc[ip + 1]]) { end = ip + 4 + bc[ip + 2]; ip += 4; } else { end = ip + 4 + bc[ip + 2] + bc[ip + 3]; ip += 4 + bc[ip + 2]; } break; case 15: ends.push(end); ips.push(ip + 4 + bc[ip + 2] + bc[ip + 3]); if (input.substr(peg$currPos, peg$consts[bc[ip + 1]].length).toLowerCase() === peg$consts[bc[ip + 1]]) { end = ip + 4 + bc[ip + 2]; ip += 4; } else { end = ip + 4 + bc[ip + 2] + bc[ip + 3]; ip += 4 + bc[ip + 2]; } break; case 16: ends.push(end); ips.push(ip + 4 + bc[ip + 2] + bc[ip + 3]); if (peg$consts[bc[ip + 1]].test(input.charAt(peg$currPos))) { end = ip + 4 + bc[ip + 2]; ip += 4; } else { end = ip + 4 + bc[ip + 2] + bc[ip + 3]; ip += 4 + bc[ip + 2]; } break; case 17: stack.push(input.substr(peg$currPos, bc[ip + 1])); peg$currPos += bc[ip + 1]; ip += 2; break; case 18: stack.push(peg$consts[bc[ip + 1]]); peg$currPos += peg$consts[bc[ip + 1]].length; ip += 2; break; case 19: stack.push(peg$FAILED); if (peg$silentFails === 0) { peg$fail(peg$consts[bc[ip + 1]]); } ip += 2; break; case 20: peg$reportedPos = stack[stack.length - 1 - bc[ip + 1]]; ip += 2; break; case 21: peg$reportedPos = peg$currPos; ip++; break; case 22: params = bc.slice(ip + 4, ip + 4 + bc[ip + 3]); for (i = 0; i < bc[ip + 3]; i++) { params[i] = stack[stack.length - 1 - params[i]]; } stack.splice( stack.length - bc[ip + 2], bc[ip + 2], peg$consts[bc[ip + 1]].apply(null, params) ); ip += 4 + bc[ip + 3]; break; case 23: stack.push(peg$parseRule(bc[ip + 1])); ip += 2; break; case 24: peg$silentFails++; ip++; break; case 25: peg$silentFails--; ip++; break; default: throw new Error("Invalid opcode: " + bc[ip] + "."); } } if (ends.length > 0) { end = ends.pop(); ip = ips.pop(); } else { break; } } return stack[0]; } function regularForms(forms) { var result = []; for (var i=0; i<forms.length; i++) { if (forms[i].strict === undefined) { result.push(forms[i].text); } } return result; } function strictForms(forms) { var result = {}; for (var i=0; i<forms.length; i++) { if (forms[i].strict !== undefined) { result[forms[i].strict] = forms[i].text; } } return result; } peg$result = peg$parseRule(peg$startRuleIndex); if (peg$result !== peg$FAILED && peg$currPos === input.length) { return peg$result; } else { if (peg$result !== peg$FAILED && peg$currPos < input.length) { peg$fail({ type: "end", description: "end of input" }); } throw peg$buildException(null, peg$maxFailExpected, peg$maxFailPos); } } return { SyntaxError: SyntaxError, parse: parse }; })(); },{}],4:[function(_dereq_,module,exports){ // // CLDR Version 21 // http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html // // Charts: http://cldr.unicode.org/index/charts // Latest: http://www.unicode.org/cldr/charts/latest/supplemental/language_plural_rules.html // // TODO: update to latest // 'use strict'; // pluralizers cache var PLURALIZERS = {}; module.exports = function pluralize(lang, count, forms) { var idx; if (!PLURALIZERS[lang]) { return '[pluralizer for (' + lang + ') not exists]'; } idx = PLURALIZERS[lang](count); if (undefined === forms[idx]) { return '[plural form N' + idx + ' not found in translation]'; } return forms[idx]; }; // HELPERS //////////////////////////////////////////////////////////////////////////////// // adds given `rule` pluralizer for given `locales` into `storage` function add(locales, rule) { var i; for (i = 0; i < locales.length; i += 1) { PLURALIZERS[locales[i]] = rule; } } // check if number is int or float function is_int(input) { return (0 === input % 1); } // PLURALIZATION RULES //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // Azerbaijani, Bambara, Burmese, Chinese, Dzongkha, Georgian, Hungarian, Igbo, // Indonesian, Japanese, Javanese, Kabuverdianu, Kannada, Khmer, Korean, // Koyraboro Senni, Lao, Makonde, Malay, Persian, Root, Sakha, Sango, // Sichuan Yi, Thai, Tibetan, Tonga, Turkish, Vietnamese, Wolof, Yoruba add(['az', 'bm', 'my', 'zh', 'dz', 'ka', 'hu', 'ig', 'id', 'ja', 'jv', 'kea', 'kn', 'km', 'ko', 'ses', 'lo', 'kde', 'ms', 'fa', 'root', 'sah', 'sg', 'ii', 'th', 'bo', 'to', 'tr', 'vi', 'wo', 'yo'], function () { return 0; }); // Manx add(['gv'], function (n) { var m10 = n % 10, m20 = n % 20; if ((m10 === 1 || m10 === 2 || m20 === 0) && is_int(n)) { return 0; } return 1; }); // Central Morocco Tamazight add(['tzm'], function (n) { if (n === 0 || n === 1 || (11 <= n && n <= 99 && is_int(n))) { return 0; } return 1; }); // Macedonian add(['mk'], function (n) { if ((n % 10 === 1) && (n !== 11) && is_int(n)) { return 0; } return 1; }); // Akan, Amharic, Bihari, Filipino, Gun, Hindi, // Lingala, Malagasy, Northern Sotho, Tagalog, Tigrinya, Walloon add(['ak', 'am', 'bh', 'fil', 'guw', 'hi', 'ln', 'mg', 'nso', 'tl', 'ti', 'wa'], function (n) { return (n === 0 || n === 1) ? 0 : 1; }); // Afrikaans, Albanian, Basque, Bemba, Bengali, Bodo, Bulgarian, Catalan, // Cherokee, Chiga, Danish, Divehi, Dutch, English, Esperanto, Estonian, Ewe, // Faroese, Finnish, Friulian, Galician, Ganda, German, Greek, Gujarati, Hausa, // Hawaiian, Hebrew, Icelandic, Italian, Kalaallisut, Kazakh, Kurdish, // Luxembourgish, Malayalam, Marathi, Masai, Mongolian, Nahuatl, Nepali, // Norwegian, Norwegian Bokmål, Norwegian Nynorsk, Nyankole, Oriya, Oromo, // Papiamento, Pashto, Portuguese, Punjabi, Romansh, Saho, Samburu, Soga, // Somali, Spanish, Swahili, Swedish, Swiss German, Syriac, Tamil, Telugu, // Turkmen, Urdu, Walser, Western Frisian, Zulu add(['af', 'sq', 'eu', 'bem', 'bn', 'brx', 'bg', 'ca', 'chr', 'cgg', 'da', 'dv', 'nl', 'en', 'eo', 'et', 'ee', 'fo', 'fi', 'fur', 'gl', 'lg', 'de', 'el', 'gu', 'ha', 'haw', 'he', 'is', 'it', 'kl', 'kk', 'ku', 'lb', 'ml', 'mr', 'mas', 'mn', 'nah', 'ne', 'no', 'nb', 'nn', 'nyn', 'or', 'om', 'pap', 'ps', 'pt', 'pa', 'rm', 'ssy', 'saq', 'xog', 'so', 'es', 'sw', 'sv', 'gsw', 'syr', 'ta', 'te', 'tk', 'ur', 'wae', 'fy', 'zu'], function (n) { return (1 === n) ? 0 : 1; }); // Latvian add(['lv'], function (n) { if (n === 0) { return 0; } if ((n % 10 === 1) && (n % 100 !== 11) && is_int(n)) { return 1; } return 2; }); // Colognian add(['ksh'], function (n) { return (n === 0) ? 0 : ((n === 1) ? 1 : 2); }); // Cornish, Inari Sami, Inuktitut, Irish, Lule Sami, Northern Sami, // Sami Language, Skolt Sami, Southern Sami add(['kw', 'smn', 'iu', 'ga', 'smj', 'se', 'smi', 'sms', 'sma'], function (n) { return (n === 1) ? 0 : ((n === 2) ? 1 : 2); }); // Belarusian, Bosnian, Croatian, Russian, Serbian, Serbo-Croatian, Ukrainian add(['be', 'bs', 'hr', 'ru', 'sr', 'sh', 'uk'], function (n) { var m10 = n % 10, m100 = n % 100; if (!is_int(n)) { return 3; } // one → n mod 10 is 1 and n mod 100 is not 11; if (1 === m10 && 11 !== m100) { return 0; } // few → n mod 10 in 2..4 and n mod 100 not in 12..14; if (2 <= m10 && m10 <= 4 && !(12 <= m100 && m100 <= 14)) { return 1; } // many → n mod 10 is 0 or n mod 10 in 5..9 or n mod 100 in 11..14; /* if (0 === m10 || (5 <= m10 && m10 <= 9) || (11 <= m100 && m100 <= 14)) { return 2; } // other return 3;*/ return 2; }); // Polish add(['pl'], function (n) { var m10 = n % 10, m100 = n % 100; if (!is_int(n)) { return 3; } // one → n is 1; if (n === 1) { return 0; } // few → n mod 10 in 2..4 and n mod 100 not in 12..14; if (2 <= m10 && m10 <= 4 && !(12 <= m100 && m100 <= 14)) { return 1; } // many → n is not 1 and n mod 10 in 0..1 or // n mod 10 in 5..9 or n mod 100 in 12..14 // (all other except partials) return 2; }); // Lithuanian add(['lt'], function (n) { var m10 = n % 10, m100 = n % 100; if (!is_int(n)) { return 2; } // one → n mod 10 is 1 and n mod 100 not in 11..19 if (m10 === 1 && !(11 <= m100 && m100 <= 19)) { return 0; } // few → n mod 10 in 2..9 and n mod 100 not in 11..19 if (2 <= m10 && m10 <= 9 && !(11 <= m100 && m100 <= 19)) { return 1; } // other return 2; }); // Tachelhit add(['shi'], function (n) { return (0 <= n && n <= 1) ? 0 : ((is_int(n) && 2 <= n && n <= 10) ? 1 : 2); }); // Moldavian, Romanian add(['mo', 'ro'], function (n) { var m100 = n % 100; if (!is_int(n)) { return 2; } // one → n is 1 if (n === 1) { return 0; } // few → n is 0 OR n is not 1 AND n mod 100 in 1..19 if (n === 0 || (1 <= m100 && m100 <= 19)) { return 1; } // other return 2; }); // Czech, Slovak add(['cs', 'sk'], function (n) { // one → n is 1 if (n === 1) { return 0; } // few → n in 2..4 if (n === 2 || n === 3 || n === 4) { return 1; } // other return 2; }); // Slovenian add(['sl'], function (n) { var m100 = n % 100; if (!is_int(n)) { return 3; } // one → n mod 100 is 1 if (m100 === 1) { return 0; } // one → n mod 100 is 2 if (m100 === 2) { return 1; } // one → n mod 100 in 3..4 if (m100 === 3 || m100 === 4) { return 2; } // other return 3; }); // Maltese add(['mt'], function (n) { var m100 = n % 100; if (!is_int(n)) { return 3; } // one → n is 1 if (n === 1) { return 0; } // few → n is 0 or n mod 100 in 2..10 if (n === 0 || (2 <= m100 && m100 <= 10)) { return 1; } // many → n mod 100 in 11..19 if (11 <= m100 && m100 <= 19) { return 2; } // other return 3; }); // Arabic add(['ar'], function (n) { var m100 = n % 100; if (!is_int(n)) { return 5; } if (n === 0) { return 0; } if (n === 1) { return 1; } if (n === 2) { return 2; } // few → n mod 100 in 3..10 if (3 <= m100 && m100 <= 10) { return 3; } // many → n mod 100 in 11..99 if (11 <= m100 && m100 <= 99) { return 4; } // other return 5; }); // Breton, Welsh add(['br', 'cy'], function (n) { if (n === 0) { return 0; } if (n === 1) { return 1; } if (n === 2) { return 2; } if (n === 3) { return 3; } if (n === 6) { return 4; } return 5; }); // FRACTIONAL PARTS - SPECIAL CASES //////////////////////////////////////////////////////////////////////////////// // French, Fulah, Kabyle add(['fr', 'ff', 'kab'], function (n) { return (0 <= n && n < 2) ? 0 : 1; }); // Langi add(['lag'], function (n) { return (n === 0) ? 0 : ((0 < n && n < 2) ? 1 : 2); }); },{}]},{},[1]) (1) });
maruilian11/cdnjs
ajax/libs/babelfish/1.0.2/babelfish.js
JavaScript
mit
44,580
openerp.gamification = function(instance) { var QWeb = instance.web.qweb; instance.gamification.Sidebar = instance.web.Widget.extend({ template: 'gamification.UserWallSidebar', init: function (parent, action) { var self = this; this._super(parent, action); this.deferred = $.Deferred(); this.goals_info = {}; this.challenge_suggestions = {}; $(document).off('keydown.klistener'); }, events: { // update a challenge and related goals 'click a.oe_update_challenge': function(event) { var self = this; var challenge_id = parseInt(event.currentTarget.id, 10); var goals_updated = new instance.web.Model('gamification.challenge').call('quick_update', [challenge_id]); $.when(goals_updated).done(function() { self.get_goal_todo_info(); }); }, // action to modify a goal 'click a.oe_goal_action': function(event) { var self = this; var goal_id = parseInt(event.currentTarget.id, 10); var goal_action = new instance.web.Model('gamification.goal').call('get_action', [goal_id]).then(function(res) { goal_action['action'] = res; }); $.when(goal_action).done(function() { var action = self.do_action(goal_action.action); $.when(action).done(function () { new instance.web.Model('gamification.goal').call('update', [[goal_id]]).then(function(res) { self.get_goal_todo_info(); }); }); }); }, // get more info about a challenge request 'click a.oe_challenge_reply': function(event) { var self = this; var challenge_id = parseInt(event.currentTarget.id, 10); var challenge_action = new instance.web.Model('gamification.challenge').call('reply_challenge_wizard', [challenge_id]).then(function(res) { challenge_action['action'] = res; }); $.when(challenge_action).done(function() { self.do_action(challenge_action.action).done(function () { self.get_goal_todo_info(); }); }); } }, start: function() { var self = this; this._super.apply(this, arguments); self.get_goal_todo_info(); self.get_challenge_suggestions(); }, get_goal_todo_info: function() { var self = this; var challenges = new instance.web.Model('res.users').call('get_serialised_gamification_summary', []).then(function(result) { if (result.length === 0) { self.$el.find(".oe_gamification_challenge_list").hide(); } else { self.$el.find(".oe_gamification_challenge_list").empty(); _.each(result, function(item){ var $item = $(QWeb.render("gamification.ChallengeSummary", {challenge: item})); self.render_money_fields($item); self.render_user_avatars($item); self.$el.find('.oe_gamification_challenge_list').append($item); }); } }); }, get_challenge_suggestions: function() { var self = this; var challenge_suggestions = new instance.web.Model('res.users').call('get_challenge_suggestions', []).then(function(result) { if (result.length === 0) { self.$el.find(".oe_gamification_suggestion").hide(); } else { var $item = $(QWeb.render("gamification.ChallengeSuggestion", {challenges: result})); self.$el.find('.oe_gamification_suggestion').append($item); } }); }, render_money_fields: function(item) { var self = this; self.dfm = new instance.web.form.DefaultFieldManager(self); // Generate a FieldMonetary for each .oe_goal_field_monetary item.find(".oe_goal_field_monetary").each(function() { var currency_id = parseInt( $(this).attr('data-id'), 10); money_field = new instance.web.form.FieldMonetary(self.dfm, { attrs: { modifiers: '{"readonly": true}' } }); money_field.set('currency', currency_id); money_field.get_currency_info(); money_field.set('value', parseInt($(this).text(), 10)); money_field.replace($(this)); }); }, render_user_avatars: function(item) { var self = this; item.find(".oe_user_avatar").each(function() { var user_id = parseInt( $(this).attr('data-id'), 10); var url = instance.session.url('/web/binary/image', {model: 'res.users', field: 'image_small', id: user_id}); $(this).attr("src", url); }); } }); instance.web.WebClient.include({ to_kitten: function() { this._super(); new instance.web.Model('gamification.badge').call('check_progress', []); } }); instance.mail.Wall.include({ start: function() { this._super(); var sidebar = new instance.gamification.Sidebar(this); sidebar.appendTo($('.oe_mail_wall_aside')); }, }); };
diogocs1/comps
web/addons/gamification/static/src/js/gamification.js
JavaScript
apache-2.0
5,832
/*syn@0.1.4#typeable*/ var syn = require('./synthetic.js'); var typeables = []; var __indexOf = [].indexOf || function (item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) { return i; } } return -1; }; syn.typeable = function (fn) { if (__indexOf.call(typeables, fn) === -1) { typeables.push(fn); } }; syn.typeable.test = function (el) { for (var i = 0, len = typeables.length; i < len; i++) { if (typeables[i](el)) { return true; } } return false; }; var type = syn.typeable; var typeableExp = /input|textarea/i; type(function (el) { return typeableExp.test(el.nodeName); }); type(function (el) { return __indexOf.call([ '', 'true' ], el.getAttribute('contenteditable')) !== -1; });
ahocevar/cdnjs
ajax/libs/syn/0.2.0/cjs/typeable.js
JavaScript
mit
845
description("This tests from-by-animations adding to previous underlying values"); embedSVGTestCase("resources/svglength-additive-from-by-1.svg"); // Setup animation test function sample1() { shouldBeCloseEnough("rect.width.animVal.value", "10"); shouldBe("rect.width.baseVal.value", "10"); } function sample2() { shouldBeCloseEnough("rect.width.animVal.value", "30"); shouldBe("rect.width.baseVal.value", "10"); } function sample3() { shouldBeCloseEnough("rect.width.animVal.value", "50"); shouldBe("rect.width.baseVal.value", "10"); } function sample4() { shouldBeCloseEnough("rect.width.animVal.value", "75"); shouldBe("rect.width.baseVal.value", "10"); } function sample5() { shouldBeCloseEnough("rect.width.animVal.value", "100"); shouldBe("rect.width.baseVal.value", "10"); } function executeTest() { rect = rootSVGElement.ownerDocument.getElementsByTagName("rect")[0]; const expectedValues = [ // [animationId, time, sampleCallback] ["an1", 0.0, sample1], ["an1", 2.0, sample2], ["an1", 4.0, sample3], ["an1", 7.0, sample4], ["an1", 9.0, sample5], ["an1", 60.0, sample5] ]; runAnimationTest(expectedValues); } window.animationStartsImmediately = true; var successfullyParsed = true;
js0701/chromium-crosswalk
third_party/WebKit/LayoutTests/svg/animations/script-tests/svglength-additive-from-by-1.js
JavaScript
bsd-3-clause
1,316
/* * Globalize Culture zh-HK * * http://github.com/jquery/globalize * * Copyright Software Freedom Conservancy, Inc. * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * This file was generated by the Globalize Culture Generator * Translation: bugs found in this file need to be fixed in the generator */ (function( window, undefined ) { var Globalize; if ( typeof require !== "undefined" && typeof exports !== "undefined" && typeof module !== "undefined" ) { // Assume CommonJS Globalize = require( "globalize" ); } else { // Global variable Globalize = window.Globalize; } Globalize.addCultureInfo( "zh-HK", "default", { name: "zh-HK", englishName: "Chinese (Traditional, Hong Kong S.A.R.)", nativeName: "中文(香港特別行政區)", language: "zh-CHT", numberFormat: { NaN: "非數字", negativeInfinity: "負無窮大", positiveInfinity: "正無窮大", percent: { pattern: ["-n%","n%"] }, currency: { symbol: "HK$" } }, calendars: { standard: { days: { names: ["星期日","星期一","星期二","星期三","星期四","星期五","星期六"], namesAbbr: ["週日","週一","週二","週三","週四","週五","週六"], namesShort: ["日","一","二","三","四","五","六"] }, months: { names: ["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月",""], namesAbbr: ["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月",""] }, AM: ["上午","上午","上午"], PM: ["下午","下午","下午"], eras: [{"name":"公元","start":null,"offset":0}], patterns: { d: "d/M/yyyy", D: "yyyy'年'M'月'd'日'", t: "H:mm", T: "H:mm:ss", f: "yyyy'年'M'月'd'日' H:mm", F: "yyyy'年'M'月'd'日' H:mm:ss", M: "M'月'd'日'", Y: "yyyy'年'M'月'" } } } }); }( this ));
sneakers3/listener
tizen-web-ui-fw/latest/js/cultures/globalize.culture.zh-HK.js
JavaScript
mit
1,960
function diff( now, props ) { //noinspection FallthroughInSwitchStatementJS switch ( util.ntype( now ) ) { case 'number' : case 'string' : if ( valid( new Type( now ) ) ) now = new Type( now ); else { if ( !props ) props = now; now = Type.now(); break; } // allow [specific] fall-through case 'array' : case 'object' : props = now; now = Type.now(); break; case 'date' : if ( valid( new Type( +now ) ) ) break; // allow [conditional] fall-through if not a valid date default : now = Type.now(); } var diff, ms = +now - +this, tense = ms < 0 ? 1 : ms > 0 ? -1 : 0; if ( !tense ) { diff = util.obj(); diff.value = 0; } else diff = diff_get( Math.abs( ms ), diff_get_exclusions( props ) ); diff.tense = tense; return diff; } function diff_eval( diff, calc, i, calcs ) { var time; if ( diff.__ms__ ) { if ( !diff.excl[calc[0]] ) { if ( diff.__ms__ >= calc[1] ) { time = diff.__ms__ / calc[1]; if ( !( calc[0] in diff.val ) ) { diff.__ms__ = ( time % 1 ) * calc[1]; diff.val[calc[0]] = Math.floor( time ); } else { time = Math.floor( time ); diff.__ms__ -= time * calc[1]; diff.val[calc[0]] += time; } } return diff; } // round up or down depending on what's available if ( ( !calcs[i + 1] || diff.excl[calcs[i + 1][0]] ) && ( calc = calcs[i - 1] ) ) { time = diff.__ms__ / calc[1]; diff.__ms__ = ( Math.round( time ) * calc[1] ) + ( ( ( diff.__ms__ / calcs[i][1] ) % 1 ) * calcs[i][1] ); return diff_eval( diff, calc, i - 1, [] ); } return diff; } return diff; } function diff_get( ms, excl ) { var diff = time_map.reduce( diff_eval, { __ms__ : ms, excl : excl, val : util.obj() } ).val; diff.value = ms; return diff; } function diff_get_exclusions( props ) { var excl = util.obj(), incl_remaining = true; if ( props ) { //noinspection FallthroughInSwitchStatementJS switch ( util.ntype( props ) ) { case 'object' : incl_remaining = false; break; case 'string' : props = props.split( ' ' ); // allow fall-through case 'array' : props = props.reduce( diff_excl, excl ); incl_remaining = !!util.len( excl ); } } time_props.map( function( prop ) { if ( !( prop in this ) ) this[prop] = !incl_remaining; }, excl ); return excl; } function diff_excl( excl, val ) { var prop = ( val = String( val ).toLowerCase() ).substring( 1 ); switch ( val.charAt( 0 ) ) { case '-' : excl[prop] = true; break; case '+' : excl[prop] = false; break; case '>' : time_map.map( diff_excl_iter, { excl : excl, prop : prop, val : true } ); break; case '<' : time_map.slice().reverse().map( diff_excl_iter, { excl : excl, prop : prop, val : false } ); break; default : excl[val] = false; } return excl; } function diff_excl_iter( calc ) { if ( calc[0] === this.prop ) this.SET_VALID = true; if ( this.SET_VALID ) this.excl[calc[0]] = this.val; } // this ensures a diff's keys are always in descending order of // number of milliseconds per unit of time, i.e. year, ..., millisecond function diff_keys( diff ) { diff = util.copy( diff ); util.remove( diff, 'tense', 'value' ); // while this may seem like overkill, only having to run `indexOf` once for each sort item means that // the overall performance is dramatically improved return Object.keys( diff ).map( function( k ) { return [time_props.indexOf( k ), k]; } ).sort( function( a, b ) { a = a[0]; b = b[0]; return a > b ? 1 : -1; // skipping `===` check as we know all indexes are unique } ).pluck( 1 ); }
zendey/Zendey
zendey/platforms/browser/cordova/node_modules/cordova-serve/node_modules/d8/src/diff.js
JavaScript
gpl-3.0
3,814
/* * jQuery UI Progressbar 1.8.2 * * Copyright (c) 2010 AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT (MIT-LICENSE.txt) * and GPL (GPL-LICENSE.txt) licenses. * * http://docs.jquery.com/UI/Progressbar * * Depends: * jquery.ui.core.js * jquery.ui.widget.js */ (function( $ ) { $.widget( "ui.progressbar", { options: { value: 0 }, _create: function() { this.element .addClass( "ui-progressbar ui-widget ui-widget-content ui-corner-all" ) .attr({ role: "progressbar", "aria-valuemin": this._valueMin(), "aria-valuemax": this._valueMax(), "aria-valuenow": this._value() }); this.valueDiv = $( "<div class='ui-progressbar-value ui-widget-header ui-corner-left'></div>" ) .appendTo( this.element ); this._refreshValue(); }, destroy: function() { this.element .removeClass( "ui-progressbar ui-widget ui-widget-content ui-corner-all" ) .removeAttr( "role" ) .removeAttr( "aria-valuemin" ) .removeAttr( "aria-valuemax" ) .removeAttr( "aria-valuenow" ); this.valueDiv.remove(); $.Widget.prototype.destroy.apply( this, arguments ); }, value: function( newValue ) { if ( newValue === undefined ) { return this._value(); } this._setOption( "value", newValue ); return this; }, _setOption: function( key, value ) { switch ( key ) { case "value": this.options.value = value; this._refreshValue(); this._trigger( "change" ); break; } $.Widget.prototype._setOption.apply( this, arguments ); }, _value: function() { var val = this.options.value; // normalize invalid value if ( typeof val !== "number" ) { val = 0; } if ( val < this._valueMin() ) { val = this._valueMin(); } if ( val > this._valueMax() ) { val = this._valueMax(); } return val; }, _valueMin: function() { return 0; }, _valueMax: function() { return 100; }, _refreshValue: function() { var value = this.value(); this.valueDiv [ value === this._valueMax() ? "addClass" : "removeClass"]( "ui-corner-right" ) .width( value + "%" ); this.element.attr( "aria-valuenow", value ); } }); $.extend( $.ui.progressbar, { version: "1.8.2" }); })( jQuery );
delfernan/CLEiM
web/js/ui/jquery.ui.progressbar.js
JavaScript
gpl-3.0
2,204
Meteor.methods({ 'livechat:removeCustomField'(_id) { if (!Meteor.userId() || !RocketChat.authz.hasPermission(Meteor.userId(), 'view-livechat-manager')) { throw new Meteor.Error('error-not-allowed', 'Not allowed', { method: 'livechat:removeCustomField' }); } check(_id, String); var customField = RocketChat.models.LivechatCustomField.findOneById(_id, { fields: { _id: 1 } }); if (!customField) { throw new Meteor.Error('error-invalid-custom-field', 'Custom field not found', { method: 'livechat:removeCustomField' }); } return RocketChat.models.LivechatCustomField.removeById(_id); } });
abduljanjua/TheHub
packages/rocketchat-livechat/server/methods/removeCustomField.js
JavaScript
mit
614
/*-------------------------------------------------------------------------- * linq-vsdoc.js - LINQ for JavaScript * ver 2.2.0.2 (Jan. 21th, 2011) * * created and maintained by neuecc <ils@neue.cc> * licensed under Microsoft Public License(Ms-PL) * http://neue.cc/ * http://linqjs.codeplex.com/ *--------------------------------------------------------------------------*/ Enumerable = (function () { var Enumerable = function (getEnumerator) { this.GetEnumerator = getEnumerator; } Enumerable.Choice = function (Params_Contents) { /// <summary>Random choice from arguments. /// Ex: Choice(1,2,3) - 1,3,2,3,3,2,1...</summary> /// <param type="T" name="Params_Contents" parameterArray="true">Array or Params Contents</param> /// <returns type="Enumerable"></returns> } Enumerable.Cycle = function (Params_Contents) { /// <summary>Cycle Repeat from arguments. /// Ex: Cycle(1,2,3) - 1,2,3,1,2,3,1,2,3...</summary> /// <param type="T" name="Params_Contents" parameterArray="true">Array or Params Contents</param> /// <returns type="Enumerable"></returns> } Enumerable.Empty = function () { /// <summary>Returns an empty Enumerable.</summary> /// <returns type="Enumerable"></returns> } Enumerable.From = function (obj) { /// <summary> /// Make Enumerable from obj. /// 1. null = Enumerable.Empty(). /// 2. Enumerable = Enumerable. /// 3. Number/Boolean = Enumerable.Repeat(obj, 1). /// 4. String = to CharArray.(Ex:"abc" => "a","b","c"). /// 5. Object/Function = to KeyValuePair(except function) Ex:"{a:0}" => (.Key=a, .Value=0). /// 6. Array or ArrayLikeObject(has length) = to Enumerable. /// 7. JScript's IEnumerable = to Enumerable(using Enumerator). /// </summary> /// <param name="obj">object</param> /// <returns type="Enumerable"></returns> } Enumerable.Return = function (element) { /// <summary>Make one sequence. This equals Repeat(element, 1)</summary> /// <param name="element">element</param> /// <returns type="Enumerable"></returns> } Enumerable.Matches = function (input, pattern, flags) { /// <summary>Global regex match and send regexp object. /// Ex: Matches((.)z,"0z1z2z") - $[1] => 0,1,2</summary> /// <param type="String" name="input">input string</param> /// <param type="RegExp/String" name="pattern">RegExp or Pattern string</param> /// <param type="Optional:String" name="flags" optional="true">If pattern is String then can use regexp flags "i" or "m" or "im"</param> /// <returns type="Enumerable"></returns> } Enumerable.Range = function (start, count, step) { /// <summary>Generates a sequence of integral numbers within a specified range. /// Ex: Range(1,5) - 1,2,3,4,5</summary> /// <param type="Number" integer="true" name="start">The value of the first integer in the sequence.</param> /// <param type="Number" integer="true" name="count">The number of sequential integers to generate.</param> /// <param type="Optional:Number" integer="true" name="step" optional="true">Step of generate number.(Ex:Range(0,3,5) - 0,5,10)</param> /// <returns type="Enumerable"></returns> } Enumerable.RangeDown = function (start, count, step) { /// <summary>Generates a sequence of integral numbers within a specified range. /// Ex: RangeDown(5,5) - 5,4,3,2,1</summary> /// <param type="Number" integer="true" name="start">The value of the first integer in the sequence.</param> /// <param type="Number" integer="true" name="count">The number of sequential integers to generate.</param> /// <param type="Optional:Number" integer="true" name="step" optional="true">Step of generate number.(Ex:RangeDown(0,3,5) - 0,-5,-10)</param> /// <returns type="Enumerable"></returns> } Enumerable.RangeTo = function (start, to, step) { /// <summary>Generates a sequence of integral numbers. /// Ex: RangeTo(10,12) - 10,11,12 RangeTo(0,-2) - 0, -1, -2</summary> /// <param type="Number" integer="true" name="start">start integer</param> /// <param type="Number" integer="true" name="to">to integer</param> /// <param type="Optional:Number" integer="true" name="step" optional="true">Step of generate number.(Ex:RangeTo(0,7,3) - 0,3,6)</param> /// <returns type="Enumerable"></returns> } Enumerable.Repeat = function (obj, count) { /// <summary>Generates a sequence that contains one repeated value. /// If omit count then generate to infinity. /// Ex: Repeat("foo",3) - "foo","foo","foo"</summary> /// <param type="TResult" name="obj">The value to be repeated.</param> /// <param type="Optional:Number" integer="true" name="count" optional="true">The number of times to repeat the value in the generated sequence.</param> /// <returns type="Enumerable"></returns> } Enumerable.RepeatWithFinalize = function (initializer, finalizer) { /// <summary>Lazy Generates one value by initializer's result and do finalize when enumerate end</summary> /// <param type="Func&lt;T>" name="initializer">value factory.</param> /// <param type="Action&lt;T>" name="finalizer">execute when finalize.</param> /// <returns type="Enumerable"></returns> } Enumerable.Generate = function (func, count) { /// <summary>Generates a sequence that execute func value. /// If omit count then generate to infinity. /// Ex: Generate("Math.random()", 5) - 0.131341,0.95425252,...</summary> /// <param type="Func&lt;T>" name="func">The value of execute func to be repeated.</param> /// <param type="Optional:Number" integer="true" name="count" optional="true">The number of times to repeat the value in the generated sequence.</param> /// <returns type="Enumerable"></returns> } Enumerable.ToInfinity = function (start, step) { /// <summary>Generates a sequence of integral numbers to infinity. /// Ex: ToInfinity() - 0,1,2,3...</summary> /// <param type="Optional:Number" integer="true" name="start" optional="true">start integer</param> /// <param type="Optional:Number" integer="true" name="step" optional="true">Step of generate number.(Ex:ToInfinity(10,3) - 10,13,16,19,...)</param> /// <returns type="Enumerable"></returns> } Enumerable.ToNegativeInfinity = function (start, step) { /// <summary>Generates a sequence of integral numbers to negative infinity. /// Ex: ToNegativeInfinity() - 0,-1,-2,-3...</summary> /// <param type="Optional:Number" integer="true" name="start" optional="true">start integer</param> /// <param type="Optional:Number" integer="true" name="step" optional="true">Step of generate number.(Ex:ToNegativeInfinity(10,3) - 10,7,4,1,...)</param> /// <returns type="Enumerable"></returns> } Enumerable.Unfold = function (seed, func) { /// <summary>Applies function and generates a infinity sequence. /// Ex: Unfold(3,"$+10") - 3,13,23,...</summary> /// <param type="T" name="seed">The initial accumulator value.</param> /// <param type="Func&lt;T,T>" name="func">An accumulator function to be invoked on each element.</param> /// <returns type="Enumerable"></returns> } Enumerable.prototype = { /* Projection and Filtering Methods */ CascadeBreadthFirst: function (func, resultSelector) { /// <summary>Projects each element of sequence and flattens the resulting sequences into one sequence use breadth first search.</summary> /// <param name="func" type="Func&lt;T,T[]>">Select child sequence.</param> /// <param name="resultSelector" type="Optional:Func&lt;T>_or_Func&lt;T,int>" optional="true">Optional:the second parameter of the function represents the nestlevel of the source sequence.</param> /// <returns type="Enumerable"></returns> }, CascadeDepthFirst: function (func, resultSelector) { /// <summary>Projects each element of sequence and flattens the resulting sequences into one sequence use depth first search.</summary> /// <param name="func" type="Func&lt;T,T[]>">Select child sequence.</param> /// <param name="resultSelector" type="Optional:Func&lt;T>_or_Func&lt;T,int>" optional="true">Optional:the second parameter of the function represents the nestlevel of the source sequence.</param> /// <returns type="Enumerable"></returns> }, Flatten: function () { /// <summary>Flatten sequences into one sequence.</summary> /// <returns type="Enumerable"></returns> }, Pairwise: function (selector) { /// <summary>Projects current and next element of a sequence into a new form.</summary> /// <param type="Func&lt;TSource,TSource,TResult>" name="selector">A transform function to apply to current and next element.</param> /// <returns type="Enumerable"></returns> }, Scan: function (func_or_seed, func, resultSelector) { /// <summary>Applies an accumulator function over a sequence.</summary> /// <param name="func_or_seed" type="Func&lt;T,T,T>_or_TAccumulate">Func is an accumulator function to be invoked on each element. Seed is the initial accumulator value.</param> /// <param name="func" type="Optional:Func&lt;TAccumulate,T,TAccumulate>" optional="true">An accumulator function to be invoked on each element.</param> /// <param name="resultSelector" type="Optional:Func&lt;TAccumulate,TResult>" optional="true">A function to transform the final accumulator value into the result value.</param> /// <returns type="Enumerable"></returns> }, Select: function (selector) { /// <summary>Projects each element of a sequence into a new form.</summary> /// <param name="selector" type="Func&lt;T,T>_or_Func&lt;T,int,T>">A transform function to apply to each source element; Optional:the second parameter of the function represents the index of the source element.</param> /// <returns type="Enumerable"></returns> }, SelectMany: function (collectionSelector, resultSelector) { /// <summary>Projects each element of a sequence and flattens the resulting sequences into one sequence.</summary> /// <param name="collectionSelector" type="Func&lt;T,TCollection[]>_or_Func&lt;T,int,TCollection[]>">A transform function to apply to each source element; Optional:the second parameter of the function represents the index of the source element.</param> /// <param name="resultSelector" type="Optional:Func&lt;T,TCollection,TResult>" optional="true">Optional:A transform function to apply to each element of the intermediate sequence.</param> /// <returns type="Enumerable"></returns> }, Where: function (predicate) { /// <summary>Filters a sequence of values based on a predicate.</summary> /// <param name="predicate" type="Func&lt;T,bool>_or_Func&lt;T,int,bool>">A function to test each source element for a condition; Optional:the second parameter of the function represents the index of the source element.</param> /// <returns type="Enumerable"></returns> }, OfType: function (type) { /// <summary>Filters the elements based on a specified type.</summary> /// <param name="type" type="T">The type to filter the elements of the sequence on.</param> /// <returns type="Enumerable"></returns> }, Zip: function (second, selector) { /// <summary>Merges two sequences by using the specified predicate function.</summary> /// <param name="second" type="T[]">The second sequence to merge.</param> /// <param name="selector" type="Func&lt;TFirst,TSecond,TResult>_or_Func&lt;TFirst,TSecond,int,TResult>">A function that specifies how to merge the elements from the two sequences. Optional:the third parameter of the function represents the index of the source element.</param> /// <returns type="Enumerable"></returns> }, /* Join Methods */ Join: function (inner, outerKeySelector, innerKeySelector, resultSelector, compareSelector) { /// <summary>Correlates the elements of two sequences based on matching keys.</summary> /// <param name="inner" type="T[]">The sequence to join to the first sequence.</param> /// <param name="outerKeySelector" type="Func&lt;TOuter,TKey>">A function to extract the join key from each element of the first sequence.</param> /// <param name="innerKeySelector" type="Func&lt;TInner,TKey>">A function to extract the join key from each element of the second sequence.</param> /// <param name="resultSelector" type="Func&lt;TOuter,TInner,TResult>">A function to create a result element from two matching elements.</param> /// <param name="compareSelector" type="Optional:Func&lt;TKey,TCompare>" optional="true">An equality comparer to compare values.</param> /// <returns type="Enumerable"></returns> }, GroupJoin: function (inner, outerKeySelector, innerKeySelector, resultSelector, compareSelector) { /// <summary>Correlates the elements of two sequences based on equality of keys and groups the results.</summary> /// <param name="inner" type="T[]">The sequence to join to the first sequence.</param> /// <param name="outerKeySelector" type="Func&lt;TOuter>">A function to extract the join key from each element of the first sequence.</param> /// <param name="innerKeySelector" type="Func&lt;TInner>">A function to extract the join key from each element of the second sequence.</param> /// <param name="resultSelector" type="Func&lt;TOuter,Enumerable&lt;TInner>,TResult">A function to create a result element from an element from the first sequence and a collection of matching elements from the second sequence.</param> /// <param name="compareSelector" type="Optional:Func&lt;TKey,TCompare>" optional="true">An equality comparer to compare values.</param> /// <returns type="Enumerable"></returns> }, /* Set Methods */ All: function (predicate) { /// <summary>Determines whether all elements of a sequence satisfy a condition.</summary> /// <param type="Func&lt;T,bool>" name="predicate">A function to test each element for a condition.</param> /// <returns type="Boolean"></returns> }, Any: function (predicate) { /// <summary>Determines whether a sequence contains any elements or any element of a sequence satisfies a condition.</summary> /// <param name="predicate" type="Optional:Func&lt;T,bool>" optional="true">A function to test each element for a condition.</param> /// <returns type="Boolean"></returns> }, Concat: function (second) { /// <summary>Concatenates two sequences.</summary> /// <param name="second" type="T[]">The sequence to concatenate to the first sequence.</param> /// <returns type="Enumerable"></returns> }, Insert: function (index, second) { /// <summary>Merge two sequences.</summary> /// <param name="index" type="Number" integer="true">The index of insert start position.</param> /// <param name="second" type="T[]">The sequence to concatenate to the first sequence.</param> /// <returns type="Enumerable"></returns> }, Alternate: function (value) { /// <summary>Insert value to between sequence.</summary> /// <param name="value" type="T">The value of insert.</param> /// <returns type="Enumerable"></returns> }, // Overload:function(value) // Overload:function(value, compareSelector) Contains: function (value, compareSelector) { /// <summary>Determines whether a sequence contains a specified element.</summary> /// <param name="value" type="T">The value to locate in the sequence.</param> /// <param name="compareSelector" type="Optional:Func&lt;T,TKey>" optional="true">An equality comparer to compare values.</param> /// <returns type="Boolean"></returns> }, DefaultIfEmpty: function (defaultValue) { /// <summary>Returns the elements of the specified sequence or the specified value in a singleton collection if the sequence is empty.</summary> /// <param name="defaultValue" type="T">The value to return if the sequence is empty.</param> /// <returns type="Enumerable"></returns> }, Distinct: function (compareSelector) { /// <summary>Returns distinct elements from a sequence.</summary> /// <param name="compareSelector" type="Optional:Func&lt;T,TKey>" optional="true">An equality comparer to compare values.</param> /// <returns type="Enumerable"></returns> }, Except: function (second, compareSelector) { /// <summary>Produces the set difference of two sequences.</summary> /// <param name="second" type="T[]">An T[] whose Elements that also occur in the first sequence will cause those elements to be removed from the returned sequence.</param> /// <param name="compareSelector" type="Optional:Func&lt;T,TKey>" optional="true">An equality comparer to compare values.</param> /// <returns type="Enumerable"></returns> }, Intersect: function (second, compareSelector) { /// <summary>Produces the set difference of two sequences.</summary> /// <param name="second" type="T[]">An T[] whose distinct elements that also appear in the first sequence will be returned.</param> /// <param name="compareSelector" type="Optional:Func&lt;T,TKey>" optional="true">An equality comparer to compare values.</param> /// <returns type="Enumerable"></returns> }, SequenceEqual: function (second, compareSelector) { /// <summary>Determines whether two sequences are equal by comparing the elements.</summary> /// <param name="second" type="T[]">An T[] to compare to the first sequence.</param> /// <param name="compareSelector" type="Optional:Func&lt;T,TKey>" optional="true">An equality comparer to compare values.</param> /// <returns type="Enumerable"></returns> }, Union: function (second, compareSelector) { /// <summary>Produces the union of two sequences.</summary> /// <param name="second" type="T[]">An T[] whose distinct elements form the second set for the union.</param> /// <param name="compareSelector" type="Optional:Func&lt;T,TKey>" optional="true">An equality comparer to compare values.</param> /// <returns type="Enumerable"></returns> }, /* Ordering Methods */ OrderBy: function (keySelector) { /// <summary>Sorts the elements of a sequence in ascending order according to a key.</summary> /// <param name="keySelector" type="Optional:Func&lt;T,TKey>">A function to extract a key from an element.</param> return new OrderedEnumerable(); }, OrderByDescending: function (keySelector) { /// <summary>Sorts the elements of a sequence in descending order according to a key.</summary> /// <param name="keySelector" type="Optional:Func&lt;T,TKey>">A function to extract a key from an element.</param> return new OrderedEnumerable(); }, Reverse: function () { /// <summary>Inverts the order of the elements in a sequence.</summary> /// <returns type="Enumerable"></returns> }, Shuffle: function () { /// <summary>Shuffle sequence.</summary> /// <returns type="Enumerable"></returns> }, /* Grouping Methods */ GroupBy: function (keySelector, elementSelector, resultSelector, compareSelector) { /// <summary>Groups the elements of a sequence according to a specified key selector function.</summary> /// <param name="keySelector" type="Func&lt;T,TKey>">A function to extract the key for each element.</param> /// <param name="elementSelector" type="Optional:Func&lt;T,TElement>">A function to map each source element to an element in an Grouping&lt;TKey, TElement>.</param> /// <param name="resultSelector" type="Optional:Func&lt;TKey,Enumerable&lt;TElement>,TResult>">A function to create a result value from each group.</param> /// <param name="compareSelector" type="Optional:Func&lt;TKey,TCompare>" optional="true">An equality comparer to compare values.</param> /// <returns type="Enumerable"></returns> }, PartitionBy: function (keySelector, elementSelector, resultSelector, compareSelector) { /// <summary>Create Group by continuation key.</summary> /// <param name="keySelector" type="Func&lt;T,TKey>">A function to extract the key for each element.</param> /// <param name="elementSelector" type="Optional:Func&lt;T,TElement>">A function to map each source element to an element in an Grouping&lt;TKey, TElement>.</param> /// <param name="resultSelector" type="Optional:Func&lt;TKey,Enumerable&lt;TElement>,TResult>">A function to create a result value from each group.</param> /// <param name="compareSelector" type="Optional:Func&lt;TKey,TCompare>" optional="true">An equality comparer to compare values.</param> /// <returns type="Enumerable"></returns> }, BufferWithCount: function (count) { /// <summary>Divide by count</summary> /// <param name="count" type="Number" integer="true">integer</param> /// <returns type="Enumerable"></returns> }, /* Aggregate Methods */ Aggregate: function (func_or_seed, func, resultSelector) { /// <summary>Applies an accumulator function over a sequence.</summary> /// <param name="func_or_seed" type="Func&lt;T,T,T>_or_TAccumulate">Func is an accumulator function to be invoked on each element. Seed is the initial accumulator value.</param> /// <param name="func" type="Optional:Func&lt;TAccumulate,T,TAccumulate>" optional="true">An accumulator function to be invoked on each element.</param> /// <param name="resultSelector" type="Optional:Func&lt;TAccumulate,TResult>" optional="true">A function to transform the final accumulator value into the result value.</param> /// <returns type="TResult"></returns> }, Average: function (selector) { /// <summary>Computes the average of a sequence.</summary> /// <param name="selector" type="Optional:Func&lt;T,Number>" optional="true">A transform function to apply to each element.</param> /// <returns type="Number"></returns> }, Count: function (predicate) { /// <summary>Returns the number of elements in a sequence.</summary> /// <param name="predicate" type="Optional:Func&lt;T,Boolean>" optional="true">A function to test each element for a condition.</param> /// <returns type="Number"></returns> }, Max: function (selector) { /// <summary>Returns the maximum value in a sequence</summary> /// <param name="selector" type="Optional:Func&lt;T,TKey>" optional="true">A transform function to apply to each element.</param> /// <returns type="Number"></returns> }, Min: function (selector) { /// <summary>Returns the minimum value in a sequence</summary> /// <param name="selector" type="Optional:Func&lt;T,TKey>" optional="true">A transform function to apply to each element.</param> /// <returns type="Number"></returns> }, MaxBy: function (keySelector) { /// <summary>Returns the maximum value in a sequence by keySelector</summary> /// <param name="keySelector" type="Func&lt;T,TKey>">A compare selector of element.</param> /// <returns type="T"></returns> }, MinBy: function (keySelector) { /// <summary>Returns the minimum value in a sequence by keySelector</summary> /// <param name="keySelector" type="Func&lt;T,TKey>">A compare selector of element.</param> /// <returns type="T"></returns> }, Sum: function (selector) { /// <summary>Computes the sum of a sequence of values.</summary> /// <param name="selector" type="Optional:Func&lt;T,TKey>" optional="true">A transform function to apply to each element.</param> /// <returns type="Number"></returns> }, /* Paging Methods */ ElementAt: function (index) { /// <summary>Returns the element at a specified index in a sequence.</summary> /// <param name="index" type="Number" integer="true">The zero-based index of the element to retrieve.</param> /// <returns type="T"></returns> }, ElementAtOrDefault: function (index, defaultValue) { /// <summary>Returns the element at a specified index in a sequence or a default value if the index is out of range.</summary> /// <param name="index" type="Number" integer="true">The zero-based index of the element to retrieve.</param> /// <param name="defaultValue" type="T">The value if the index is outside the bounds then send.</param> /// <returns type="T"></returns> }, First: function (predicate) { /// <summary>Returns the first element of a sequence.</summary> /// <param name="predicate" type="Optional:Func&lt;T,Boolean>">A function to test each element for a condition.</param> /// <returns type="T"></returns> }, FirstOrDefault: function (defaultValue, predicate) { /// <summary>Returns the first element of a sequence, or a default value.</summary> /// <param name="defaultValue" type="T">The value if not found then send.</param> /// <param name="predicate" type="Optional:Func&lt;T,Boolean>">A function to test each element for a condition.</param> /// <returns type="T"></returns> }, Last: function (predicate) { /// <summary>Returns the last element of a sequence.</summary> /// <param name="predicate" type="Optional:Func&lt;T,Boolean>">A function to test each element for a condition.</param> /// <returns type="T"></returns> }, LastOrDefault: function (defaultValue, predicate) { /// <summary>Returns the last element of a sequence, or a default value.</summary> /// <param name="defaultValue" type="T">The value if not found then send.</param> /// <param name="predicate" type="Optional:Func&lt;T,Boolean>">A function to test each element for a condition.</param> /// <returns type="T"></returns> }, Single: function (predicate) { /// <summary>Returns the only element of a sequence that satisfies a specified condition, and throws an exception if more than one such element exists.</summary> /// <param name="predicate" type="Optional:Func&lt;T,Boolean>">A function to test each element for a condition.</param> /// <returns type="T"></returns> }, SingleOrDefault: function (defaultValue, predicate) { /// <summary>Returns a single, specific element of a sequence of values, or a default value if no such element is found.</summary> /// <param name="defaultValue" type="T">The value if not found then send.</param> /// <param name="predicate" type="Optional:Func&lt;T,Boolean>">A function to test each element for a condition.</param> /// <returns type="T"></returns> }, Skip: function (count) { /// <summary>Bypasses a specified number of elements in a sequence and then returns the remaining elements.</summary> /// <param name="count" type="Number" integer="true">The number of elements to skip before returning the remaining elements.</param> /// <returns type="Enumerable"></returns> }, SkipWhile: function (predicate) { /// <summary>Bypasses elements in a sequence as long as a specified condition is true and then returns the remaining elements.</summary> /// <param name="predicate" type="Func&lt;T,Boolean>_or_Func&lt;T,int,Boolean>">A function to test each source element for a condition; Optional:the second parameter of the function represents the index of the source element.</param> /// <returns type="Enumerable"></returns> }, Take: function (count) { /// <summary>Returns a specified number of contiguous elements from the start of a sequence.</summary> /// <param name="count" type="Number" integer="true">The number of elements to return.</param> /// <returns type="Enumerable"></returns> }, TakeWhile: function (predicate) { /// <summary>Returns elements from a sequence as long as a specified condition is true, and then skips the remaining elements.</summary> /// <param name="predicate" type="Func&lt;T,Boolean>_or_Func&lt;T,int,Boolean>">A function to test each source element for a condition; Optional:the second parameter of the function represents the index of the source element.</param> /// <returns type="Enumerable"></returns> }, TakeExceptLast: function (count) { /// <summary>Take a sequence except last count.</summary> /// <param name="count" type="Optional:Number" integer="true">The number of skip count.</param> /// <returns type="Enumerable"></returns> }, TakeFromLast: function (count) { /// <summary>Take a sequence from last count.</summary> /// <param name="count" type="Number" integer="true">The number of take count.</param> /// <returns type="Enumerable"></returns> }, IndexOf: function (item) { /// <summary>Returns the zero-based index of the flrst occurrence of a value.</summary> /// <param name="item" type="T">The zero-based starting index of the search.</param> /// <returns type="Number" integer="true"></returns> }, LastIndexOf: function (item) { /// <summary>Returns the zero-based index of the last occurrence of a value.</summary> /// <param name="item" type="T">The zero-based starting index of the search.</param> /// <returns type="Number" integer="true"></returns> }, /* Convert Methods */ ToArray: function () { /// <summary>Creates an array from this sequence.</summary> /// <returns type="Array"></returns> }, ToLookup: function (keySelector, elementSelector, compareSelector) { /// <summary>Creates a Lookup from this sequence.</summary> /// <param name="keySelector" type="Func&lt;T,TKey>">A function to extract a key from each element.</param> /// <param name="elementSelector" type="Optional:Func&lt;T,TElement>">A transform function to produce a result element value from each element.</param> /// <param name="compareSelector" type="Optional:Func&lt;TKey,TCompare>" optional="true">An equality comparer to compare values.</param> return new Lookup(); }, ToObject: function (keySelector, elementSelector) { /// <summary>Creates a Object from this sequence.</summary> /// <param name="keySelector" type="Func&lt;T,String>">A function to extract a key from each element.</param> /// <param name="elementSelector" type="Func&lt;T,TElement>">A transform function to produce a result element value from each element.</param> /// <returns type="Object"></returns> }, ToDictionary: function (keySelector, elementSelector, compareSelector) { /// <summary>Creates a Dictionary from this sequence.</summary> /// <param name="keySelector" type="Func&lt;T,TKey>">A function to extract a key from each element.</param> /// <param name="elementSelector" type="Func&lt;T,TElement>">A transform function to produce a result element value from each element.</param> /// <param name="compareSelector" type="Optional:Func&lt;TKey,TCompare>" optional="true">An equality comparer to compare values.</param> return new Dictionary(); }, // Overload:function() // Overload:function(replacer) // Overload:function(replacer, space) ToJSON: function (replacer, space) { /// <summary>Creates a JSON String from sequence, performed only native JSON support browser or included json2.js.</summary> /// <param name="replacer" type="Optional:Func">a replacer.</param> /// <param name="space" type="Optional:Number">indent spaces.</param> /// <returns type="String"></returns> }, // Overload:function() // Overload:function(separator) // Overload:function(separator,selector) ToString: function (separator, selector) { /// <summary>Creates Joined string from this sequence.</summary> /// <param name="separator" type="Optional:String">A String.</param> /// <param name="selector" type="Optional:Func&lt;T,String>">A transform function to apply to each source element.</param> /// <returns type="String"></returns> }, /* Action Methods */ Do: function (action) { /// <summary>Performs the specified action on each element of the sequence.</summary> /// <param name="action" type="Action&lt;T>_or_Action&lt;T,int>">Optional:the second parameter of the function represents the index of the source element.</param> /// <returns type="Enumerable"></returns> }, ForEach: function (action) { /// <summary>Performs the specified action on each element of the sequence.</summary> /// <param name="action" type="Action&lt;T>_or_Action&lt;T,int>">[return true;]continue iteration.[return false;]break iteration. Optional:the second parameter of the function represents the index of the source element.</param> /// <returns type="void"></returns> }, Write: function (separator, selector) { /// <summary>Do document.write.</summary> /// <param name="separator" type="Optional:String">A String.</param> /// <param name="selector" type="Optional:Func&lt;T,String>">A transform function to apply to each source element.</param> /// <returns type="void"></returns> }, WriteLine: function (selector) { /// <summary>Do document.write + &lt;br />.</summary> /// <param name="selector" type="Optional:Func&lt;T,String>">A transform function to apply to each source element.</param> /// <returns type="void"></returns> }, Force: function () { /// <summary>Execute enumerate.</summary> /// <returns type="void"></returns> }, /* Functional Methods */ Let: function (func) { /// <summary>Bind the source to the parameter so that it can be used multiple times.</summary> /// <param name="func" type="Func&lt;Enumerable&lt;T>,Enumerable&lt;TR>>">apply function.</param> /// <returns type="Enumerable"></returns> }, Share: function () { /// <summary>Shares cursor of all enumerators to the sequence.</summary> /// <returns type="Enumerable"></returns> }, MemoizeAll: function () { /// <summary>Creates an enumerable that enumerates the original enumerable only once and caches its results.</summary> /// <returns type="Enumerable"></returns> }, /* Error Handling Methods */ Catch: function (handler) { /// <summary>catch error and do handler.</summary> /// <param name="handler" type="Action&lt;Error>">execute if error occured.</param> /// <returns type="Enumerable"></returns> }, Finally: function (finallyAction) { /// <summary>do action if enumerate end or disposed or error occured.</summary> /// <param name="handler" type="Action">finally execute.</param> /// <returns type="Enumerable"></returns> }, /* For Debug Methods */ Trace: function (message, selector) { /// <summary>Trace object use console.log.</summary> /// <param name="message" type="Optional:String">Default is 'Trace:'.</param> /// <param name="selector" type="Optional:Func&lt;T,String>">A transform function to apply to each source element.</param> /// <returns type="Enumerable"></returns> } } // vsdoc-dummy Enumerable.prototype.GetEnumerator = function () { /// <summary>Returns an enumerator that iterates through the collection.</summary> return new IEnumerator(); } var IEnumerator = function () { } IEnumerator.prototype.Current = function () { /// <summary>Gets the element in the collection at the current position of the enumerator.</summary> /// <returns type="T"></returns> } IEnumerator.prototype.MoveNext = function () { /// <summary>Advances the enumerator to the next element of the collection.</summary> /// <returns type="Boolean"></returns> } IEnumerator.prototype.Dispose = function () { /// <summary>Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.</summary> /// <returns type="Void"></returns> } var Dictionary = function () { } Dictionary.prototype = { Add: function (key, value) { /// <summary>add new pair. if duplicate key then overwrite new value.</summary> /// <returns type="Void"></returns> }, Get: function (key) { /// <summary>get value. if not find key then return undefined.</summary> /// <returns type="T"></returns> }, Set: function (key, value) { /// <summary>set value. if complete set value then return true, not find key then return false.</summary> /// <returns type="Boolean"></returns> }, Contains: function (key) { /// <summary>check contains key.</summary> /// <returns type="Boolean"></returns> }, Clear: function () { /// <summary>clear dictionary.</summary> /// <returns type="Void"></returns> }, Remove: function (key) { /// <summary>remove key and value.</summary> /// <returns type="Void"></returns> }, Count: function () { /// <summary>contains value's count.</summary> /// <returns type="Number"></returns> }, ToEnumerable: function () { /// <summary>Convert to Enumerable&lt;{Key:, Value:}&gt;.</summary> /// <returns type="Enumerable"></returns> } } var Lookup = function () { } Lookup.prototype = { Count: function () { /// <summary>contains value's count.</summary> /// <returns type="Number"></returns> }, Get: function (key) { /// <summary>get grouped enumerable.</summary> /// <returns type="Enumerable"></returns> }, Contains: function (key) { /// <summary>check contains key.</summary> /// <returns type="Boolean"></returns> }, ToEnumerable: function () { /// <summary>Convert to Enumerable&lt;Grouping&gt;.</summary> /// <returns type="Enumerable"></returns> } } var Grouping = function () { } Grouping.prototype = new Enumerable(); Grouping.prototype.Key = function () { /// <summary>get grouping key.</summary> /// <returns type="T"></returns> } var OrderedEnumerable = function () { } OrderedEnumerable.prototype = new Enumerable(); OrderedEnumerable.prototype.ThenBy = function (keySelector) { /// <summary>Performs a subsequent ordering of the elements in a sequence in ascending order according to a key.</summary> /// <param name="keySelector" type="Func&lt;T,TKey>">A function to extract a key from each element.</param> return Enumerable.Empty().OrderBy(); } OrderedEnumerable.prototype.ThenByDescending = function (keySelector) { /// <summary>Performs a subsequent ordering of the elements in a sequence in descending order, according to a key.</summary> /// <param name="keySelector" type="Func&lt;T,TKey>">A function to extract a key from each element.</param> return Enumerable.Empty().OrderBy(); } return Enumerable; })()
HackerDom/qctf-starter-2015
tasks/transl/src/scripts/linq-vsdoc.js
JavaScript
mit
42,857
Object.is(1, 1); Object.is(1, 2); Object.is(1, {}); Object.is(1, NaN); Object.is(0, 0); Object.is(0, -0); Object.is(NaN, NaN); Object.is({}, {}); var emptyObject = {}; var emptyArray = []; Object.is(emptyObject, emptyObject); Object.is(emptyArray, emptyArray); Object.is(emptyObject, emptyArray); var squared = x => x * x; Object.is(squared, squared); var a: boolean = Object.is('a', 'a'); var b: string = Object.is('a', 'a'); var c: boolean = Object.is('a'); var d: boolean = Object.is('a', 'b', 'c');
kidaa/kythe
third_party/flow/tests/object_is/object_is.js
JavaScript
apache-2.0
506
'use strict' /* global * describe, it, beforeEach, afterEach, expect, spyOn, * loadFixtures, Waypoint */ describe('Waypoints debug script', function() { var waypoint, element beforeEach(function() { loadFixtures('standard.html') }) afterEach(function() { waypoint.destroy() }) describe('display none detection', function() { beforeEach(function() { element = document.getElementById('same1') waypoint = new Waypoint({ element: element, handler: function() {} }) element.style.display = 'none' }) it('logs a console error', function() { spyOn(console, 'error') waypoint.context.refresh() expect(console.error).toHaveBeenCalled() }) }) describe('display fixed positioning detection', function() { beforeEach(function() { element = document.getElementById('same1') waypoint = new Waypoint({ element: element, handler: function() {} }) element.style.position = 'fixed' }) it('logs a console error', function() { spyOn(console, 'error') waypoint.context.refresh() expect(console.error).toHaveBeenCalled() }) }) describe('fixed position detection', function() { }) describe('respect waypoint disabling', function() { beforeEach(function() { element = document.getElementById('same1') waypoint = new Waypoint({ element: element, handler: function() {} }) element.style.display = 'none' waypoint.disable() }) it('does not log a console error', function() { spyOn(console, 'error') waypoint.context.refresh() expect(console.error.calls.length).toEqual(0) }) }) })
marcoprolog/marcoprolog.github.io
wedding/node_modules/waypoints/test/debug-spec.js
JavaScript
apache-2.0
1,733
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){ var Core = _dereq_('../lib/Core'), CollectionGroup = _dereq_('../lib/CollectionGroup'), View = _dereq_('../lib/View'), Highchart = _dereq_('../lib/Highchart'), Persist = _dereq_('../lib/Persist'), Document = _dereq_('../lib/Document'), Overview = _dereq_('../lib/Overview'), OldView = _dereq_('../lib/OldView'), OldViewBind = _dereq_('../lib/OldView.Bind'); if (typeof window !== 'undefined') { window.ForerunnerDB = Core; } module.exports = Core; },{"../lib/CollectionGroup":4,"../lib/Core":5,"../lib/Document":7,"../lib/Highchart":8,"../lib/OldView":22,"../lib/OldView.Bind":21,"../lib/Overview":25,"../lib/Persist":27,"../lib/View":30}],2:[function(_dereq_,module,exports){ "use strict"; /** * Creates an always-sorted multi-key bucket that allows ForerunnerDB to * know the index that a document will occupy in an array with minimal * processing, speeding up things like sorted views. */ var Shared = _dereq_('./Shared'); /** * The active bucket class. * @param {object} orderBy An order object. * @constructor */ var ActiveBucket = function (orderBy) { var sortKey; this._primaryKey = '_id'; this._keyArr = []; this._data = []; this._objLookup = {}; this._count = 0; for (sortKey in orderBy) { if (orderBy.hasOwnProperty(sortKey)) { this._keyArr.push({ key: sortKey, dir: orderBy[sortKey] }); } } }; Shared.addModule('ActiveBucket', ActiveBucket); Shared.synthesize(ActiveBucket.prototype, 'primaryKey'); Shared.mixin(ActiveBucket.prototype, 'Mixin.Sorting'); /** * Quicksorts a single document into the passed array and * returns the index that the document should occupy. * @param {object} obj The document to calculate index for. * @param {array} arr The array the document index will be * calculated for. * @param {string} item The string key representation of the * document whose index is being calculated. * @param {function} fn The comparison function that is used * to determine if a document is sorted below or above the * document we are calculating the index for. * @returns {number} The index the document should occupy. */ ActiveBucket.prototype.qs = function (obj, arr, item, fn) { // If the array is empty then return index zero if (!arr.length) { return 0; } var lastMidwayIndex = -1, midwayIndex, lookupItem, result, start = 0, end = arr.length - 1; // Loop the data until our range overlaps while (end >= start) { // Calculate the midway point (divide and conquer) midwayIndex = Math.floor((start + end) / 2); if (lastMidwayIndex === midwayIndex) { // No more items to scan break; } // Get the item to compare against lookupItem = arr[midwayIndex]; if (lookupItem !== undefined) { // Compare items result = fn(this, obj, item, lookupItem); if (result > 0) { start = midwayIndex + 1; } if (result < 0) { end = midwayIndex - 1; } } lastMidwayIndex = midwayIndex; } if (result > 0) { return midwayIndex + 1; } else { return midwayIndex; } }; /** * Calculates the sort position of an item against another item. * @param {object} sorter An object or instance that contains * sortAsc and sortDesc methods. * @param {object} obj The document to compare. * @param {string} a The first key to compare. * @param {string} b The second key to compare. * @returns {number} Either 1 for sort a after b or -1 to sort * a before b. * @private */ ActiveBucket.prototype._sortFunc = function (sorter, obj, a, b) { var aVals = a.split('.:.'), bVals = b.split('.:.'), arr = sorter._keyArr, count = arr.length, index, sortType, castType; for (index = 0; index < count; index++) { sortType = arr[index]; castType = typeof obj[sortType.key]; if (castType === 'number') { aVals[index] = Number(aVals[index]); bVals[index] = Number(bVals[index]); } // Check for non-equal items if (aVals[index] !== bVals[index]) { // Return the sorted items if (sortType.dir === 1) { return sorter.sortAsc(aVals[index], bVals[index]); } if (sortType.dir === -1) { return sorter.sortDesc(aVals[index], bVals[index]); } } } }; /** * Inserts a document into the active bucket. * @param {object} obj The document to insert. * @returns {number} The index the document now occupies. */ ActiveBucket.prototype.insert = function (obj) { var key, keyIndex; key = this.documentKey(obj); keyIndex = this._data.indexOf(key); if (keyIndex === -1) { // Insert key keyIndex = this.qs(obj, this._data, key, this._sortFunc); this._data.splice(keyIndex, 0, key); } else { this._data.splice(keyIndex, 0, key); } this._objLookup[obj[this._primaryKey]] = key; this._count++; return keyIndex; }; /** * Removes a document from the active bucket. * @param {object} obj The document to remove. * @returns {boolean} True if the document was removed * successfully or false if it wasn't found in the active * bucket. */ ActiveBucket.prototype.remove = function (obj) { var key, keyIndex; key = this._objLookup[obj[this._primaryKey]]; if (key) { keyIndex = this._data.indexOf(key); if (keyIndex > -1) { this._data.splice(keyIndex, 1); delete this._objLookup[obj[this._primaryKey]]; this._count--; return true; } else { return false; } } return false; }; /** * Get the index that the passed document currently occupies * or the index it will occupy if added to the active bucket. * @param {object} obj The document to get the index for. * @returns {number} The index. */ ActiveBucket.prototype.index = function (obj) { var key, keyIndex; key = this.documentKey(obj); keyIndex = this._data.indexOf(key); if (keyIndex === -1) { // Get key index keyIndex = this.qs(obj, this._data, key, this._sortFunc); } return keyIndex; }; /** * The key that represents the passed document. * @param {object} obj The document to get the key for. * @returns {string} The document key. */ ActiveBucket.prototype.documentKey = function (obj) { var key = '', arr = this._keyArr, count = arr.length, index, sortType; for (index = 0; index < count; index++) { sortType = arr[index]; if (key) { key += '.:.'; } key += obj[sortType.key]; } // Add the unique identifier on the end of the key key += '.:.' + obj[this._primaryKey]; return key; }; /** * Get the number of documents currently indexed in the active * bucket instance. * @returns {number} The number of documents. */ ActiveBucket.prototype.count = function () { return this._count; }; Shared.finishModule('ActiveBucket'); module.exports = ActiveBucket; },{"./Shared":29}],3:[function(_dereq_,module,exports){ "use strict"; /** * The main collection class. Collections store multiple documents and * can operate on them using the query language to insert, read, update * and delete. */ var Shared, Core, Metrics, KeyValueStore, Path, IndexHashMap, IndexBinaryTree, Crc, Overload, ReactorIO; Shared = _dereq_('./Shared'); /** * Collection object used to store data. * @constructor */ var Collection = function (name) { this.init.apply(this, arguments); }; Collection.prototype.init = function (name) { this._primaryKey = '_id'; this._primaryIndex = new KeyValueStore('primary'); this._primaryCrc = new KeyValueStore('primaryCrc'); this._crcLookup = new KeyValueStore('crcLookup'); this._name = name; this._data = []; this._metrics = new Metrics(); this._deferQueue = { insert: [], update: [], remove: [], upsert: [] }; this._deferThreshold = { insert: 100, update: 100, remove: 100, upsert: 100 }; this._deferTime = { insert: 1, update: 1, remove: 1, upsert: 1 }; // Set the subset to itself since it is the root collection this._subsetOf(this); }; Shared.addModule('Collection', Collection); Shared.mixin(Collection.prototype, 'Mixin.Common'); Shared.mixin(Collection.prototype, 'Mixin.Events'); Shared.mixin(Collection.prototype, 'Mixin.ChainReactor'); Shared.mixin(Collection.prototype, 'Mixin.CRUD'); Shared.mixin(Collection.prototype, 'Mixin.Constants'); Shared.mixin(Collection.prototype, 'Mixin.Triggers'); Shared.mixin(Collection.prototype, 'Mixin.Sorting'); Shared.mixin(Collection.prototype, 'Mixin.Matching'); Metrics = _dereq_('./Metrics'); KeyValueStore = _dereq_('./KeyValueStore'); Path = _dereq_('./Path'); IndexHashMap = _dereq_('./IndexHashMap'); IndexBinaryTree = _dereq_('./IndexBinaryTree'); Crc = _dereq_('./Crc'); Core = Shared.modules.Core; Overload = _dereq_('./Overload'); ReactorIO = _dereq_('./ReactorIO'); /** * Returns a checksum of a string. * @param {String} string The string to checksum. * @return {String} The checksum generated. */ Collection.prototype.crc = Crc; /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'state'); /** * Gets / sets the name of the collection. * @param {String=} val The name of the collection to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'name'); /** * Get the internal data * @returns {Array} */ Collection.prototype.data = function () { return this._data; }; /** * Drops a collection and all it's stored data from the database. * @returns {boolean} True on success, false on failure. */ Collection.prototype.drop = function () { var key; if (this._state !== 'dropped') { if (this._db && this._db._collection && this._name) { if (this.debug()) { console.log('Dropping collection ' + this._name); } this._state = 'dropped'; this.emit('drop', this); delete this._db._collection[this._name]; // Remove any reactor IO chain links if (this._collate) { for (key in this._collate) { if (this._collate.hasOwnProperty(key)) { this.collateRemove(key); } } } delete this._primaryKey; delete this._primaryIndex; delete this._primaryCrc; delete this._crcLookup; delete this._name; delete this._data; delete this._metrics; return true; } } else { return true; } return false; }; /** * Gets / sets the primary key for this collection. * @param {String=} keyName The name of the primary key. * @returns {*} */ Collection.prototype.primaryKey = function (keyName) { if (keyName !== undefined) { if (this._primaryKey !== keyName) { this._primaryKey = keyName; // Set the primary key index primary key this._primaryIndex.primaryKey(keyName); // Rebuild the primary key index this.rebuildPrimaryKeyIndex(); } return this; } return this._primaryKey; }; /** * Handles insert events and routes changes to binds and views as required. * @param {Array} inserted An array of inserted documents. * @param {Array} failed An array of documents that failed to insert. * @private */ Collection.prototype._onInsert = function (inserted, failed) { this.emit('insert', inserted, failed); }; /** * Handles update events and routes changes to binds and views as required. * @param {Array} items An array of updated documents. * @private */ Collection.prototype._onUpdate = function (items) { this.emit('update', items); }; /** * Handles remove events and routes changes to binds and views as required. * @param {Array} items An array of removed documents. * @private */ Collection.prototype._onRemove = function (items) { this.emit('remove', items); }; /** * Gets / sets the db instance this class instance belongs to. * @param {Core=} db The db instance. * @returns {*} */ Shared.synthesize(Collection.prototype, 'db', function (db) { if (db) { if (this.primaryKey() === '_id') { // Set primary key to the db's key by default this.primaryKey(db.primaryKey()); } } return this.$super.apply(this, arguments); }); /** * Sets the collection's data to the array of documents passed. * @param data * @param options Optional options object. * @param callback Optional callback function. */ Collection.prototype.setData = function (data, options, callback) { if (this._state === 'dropped') { throw('ForerunnerDB.Collection "' + this.name() + '": Cannot operate in a dropped state!'); } if (data) { var op = this._metrics.create('setData'); op.start(); options = this.options(options); this.preSetData(data, options, callback); if (options.$decouple) { data = this.decouple(data); } if (!(data instanceof Array)) { data = [data]; } op.time('transformIn'); data = this.transformIn(data); op.time('transformIn'); var oldData = [].concat(this._data); this._dataReplace(data); // Update the primary key index op.time('Rebuild Primary Key Index'); this.rebuildPrimaryKeyIndex(options); op.time('Rebuild Primary Key Index'); // Rebuild all other indexes op.time('Rebuild All Other Indexes'); this._rebuildIndexes(); op.time('Rebuild All Other Indexes'); op.time('Resolve chains'); this.chainSend('setData', data, {oldData: oldData}); op.time('Resolve chains'); op.stop(); this.emit('setData', this._data, oldData); } if (callback) { callback(false); } return this; }; /** * Drops and rebuilds the primary key index for all documents in the collection. * @param {Object=} options An optional options object. * @private */ Collection.prototype.rebuildPrimaryKeyIndex = function (options) { options = options || { $ensureKeys: undefined, $violationCheck: undefined }; var ensureKeys = options && options.$ensureKeys !== undefined ? options.$ensureKeys : true, violationCheck = options && options.$violationCheck !== undefined ? options.$violationCheck : true, arr, arrCount, arrItem, pIndex = this._primaryIndex, crcIndex = this._primaryCrc, crcLookup = this._crcLookup, pKey = this._primaryKey, jString; // Drop the existing primary index pIndex.truncate(); crcIndex.truncate(); crcLookup.truncate(); // Loop the data and check for a primary key in each object arr = this._data; arrCount = arr.length; while (arrCount--) { arrItem = arr[arrCount]; if (ensureKeys) { // Make sure the item has a primary key this.ensurePrimaryKey(arrItem); } if (violationCheck) { // Check for primary key violation if (!pIndex.uniqueSet(arrItem[pKey], arrItem)) { // Primary key violation throw('ForerunnerDB.Collection "' + this.name() + '": Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: ' + arrItem[this._primaryKey]); } } else { pIndex.set(arrItem[pKey], arrItem); } // Generate a CRC string jString = JSON.stringify(arrItem); crcIndex.set(arrItem[pKey], jString); crcLookup.set(jString, arrItem); } }; /** * Checks for a primary key on the document and assigns one if none * currently exists. * @param {Object} obj The object to check a primary key against. * @private */ Collection.prototype.ensurePrimaryKey = function (obj) { if (obj[this._primaryKey] === undefined) { // Assign a primary key automatically obj[this._primaryKey] = this.objectId(); } }; /** * Clears all data from the collection. * @returns {Collection} */ Collection.prototype.truncate = function () { if (this._state === 'dropped') { throw('ForerunnerDB.Collection "' + this.name() + '": Cannot operate in a dropped state!'); } this.emit('truncate', this._data); // Clear all the data from the collection this._data.length = 0; // Re-create the primary index data this._primaryIndex = new KeyValueStore('primary'); this._primaryCrc = new KeyValueStore('primaryCrc'); this._crcLookup = new KeyValueStore('crcLookup'); this.deferEmit('change', {type: 'truncate'}); return this; }; /** * Modifies an existing document or documents in a collection. This will update * all matches for 'query' with the data held in 'update'. It will not overwrite * the matched documents with the update document. * * @param {Object} obj The document object to upsert or an array containing * documents to upsert. * * If the document contains a primary key field (based on the collections's primary * key) then the database will search for an existing document with a matching id. * If a matching document is found, the document will be updated. Any keys that * match keys on the existing document will be overwritten with new data. Any keys * that do not currently exist on the document will be added to the document. * * If the document does not contain an id or the id passed does not match an existing * document, an insert is performed instead. If no id is present a new primary key * id is provided for the item. * * @param {Function=} callback Optional callback method. * @returns {Object} An object containing two keys, "op" contains either "insert" or * "update" depending on the type of operation that was performed and "result" * contains the return data from the operation used. */ Collection.prototype.upsert = function (obj, callback) { if (this._state === 'dropped') { throw('ForerunnerDB.Collection "' + this.name() + '": Cannot operate in a dropped state!'); } if (obj) { var queue = this._deferQueue.upsert, deferThreshold = this._deferThreshold.upsert; var returnData = {}, query, i; // Determine if the object passed is an array or not if (obj instanceof Array) { if (obj.length > deferThreshold) { // Break up upsert into blocks this._deferQueue.upsert = queue.concat(obj); // Fire off the insert queue handler this.processQueue('upsert', callback); return {}; } else { // Loop the array and upsert each item returnData = []; for (i = 0; i < obj.length; i++) { returnData.push(this.upsert(obj[i])); } if (callback) { callback(); } return returnData; } } // Determine if the operation is an insert or an update if (obj[this._primaryKey]) { // Check if an object with this primary key already exists query = {}; query[this._primaryKey] = obj[this._primaryKey]; if (this._primaryIndex.lookup(query)[0]) { // The document already exists with this id, this operation is an update returnData.op = 'update'; } else { // No document with this id exists, this operation is an insert returnData.op = 'insert'; } } else { // The document passed does not contain an id, this operation is an insert returnData.op = 'insert'; } switch (returnData.op) { case 'insert': returnData.result = this.insert(obj); break; case 'update': returnData.result = this.update(query, obj); break; default: break; } return returnData; } else { if (callback) { callback(); } } return {}; }; /** * Modifies an existing document or documents in a collection. This will update * all matches for 'query' with the data held in 'update'. It will not overwrite * the matched documents with the update document. * * @param {Object} query The query that must be matched for a document to be * operated on. * @param {Object} update The object containing updated key/values. Any keys that * match keys on the existing document will be overwritten with this data. Any * keys that do not currently exist on the document will be added to the document. * @param {Object=} options An options object. * @returns {Array} The items that were updated. */ Collection.prototype.update = function (query, update, options) { if (this._state === 'dropped') { throw('ForerunnerDB.Collection "' + this.name() + '": Cannot operate in a dropped state!'); } // Decouple the update data update = this.decouple(update); // Handle transform update = this.transformIn(update); if (this.debug()) { console.log('Updating some collection data for collection "' + this.name() + '"'); } var self = this, op = this._metrics.create('update'), dataSet, updated, updateCall = function (originalDoc) { var newDoc = self.decouple(originalDoc), triggerOperation, result; if (self.willTrigger(self.TYPE_UPDATE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_UPDATE, self.PHASE_AFTER)) { triggerOperation = { type: 'update', query: self.decouple(query), update: self.decouple(update), options: self.decouple(options), op: op }; // Update newDoc with the update criteria so we know what the data will look // like AFTER the update is processed result = self.updateObject(newDoc, triggerOperation.update, triggerOperation.query, triggerOperation.options, ''); if (self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_BEFORE, originalDoc, newDoc) !== false) { // No triggers complained so let's execute the replacement of the existing // object with the new one result = self.updateObject(originalDoc, newDoc, triggerOperation.query, triggerOperation.options, ''); // NOTE: If for some reason we would only like to fire this event if changes are actually going // to occur on the object from the proposed update then we can add "result &&" to the if self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_AFTER, originalDoc, newDoc); } else { // Trigger cancelled operation so tell result that it was not updated result = false; } } else { // No triggers complained so let's execute the replacement of the existing // object with the new one result = self.updateObject(originalDoc, update, query, options, ''); } return result; }; op.start(); op.time('Retrieve documents to update'); dataSet = this.find(query, {$decouple: false}); op.time('Retrieve documents to update'); if (dataSet.length) { op.time('Update documents'); updated = dataSet.filter(updateCall); op.time('Update documents'); if (updated.length) { op.time('Resolve chains'); this.chainSend('update', { query: query, update: update, dataSet: dataSet }, options); op.time('Resolve chains'); this._onUpdate(updated); this.deferEmit('change', {type: 'update', data: updated}); } } op.stop(); // TODO: Should we decouple the updated array before return by default? return updated || []; }; Collection.prototype._replaceObj = function (currentObj, newObj) { var i; // Check if the new document has a different primary key value from the existing one // Remove item from indexes this._removeFromIndexes(currentObj); // Remove existing keys from current object for (i in currentObj) { if (currentObj.hasOwnProperty(i)) { delete currentObj[i]; } } // Add new keys to current object for (i in newObj) { if (newObj.hasOwnProperty(i)) { currentObj[i] = newObj[i]; } } // Update the item in the primary index if (!this._insertIntoIndexes(currentObj)) { throw('ForerunnerDB.Collection "' + this.name() + '": Primary key violation in update! Key violated: ' + currentObj[this._primaryKey]); } // Update the object in the collection data //this._data.splice(this._data.indexOf(currentObj), 1, newObj); return true; }; /** * Helper method to update a document from it's id. * @param {String} id The id of the document. * @param {Object} update The object containing the key/values to update to. * @returns {Array} The items that were updated. */ Collection.prototype.updateById = function (id, update) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.update(searchObj, update); }; /** * Internal method for document updating. * @param {Object} doc The document to update. * @param {Object} update The object with key/value pairs to update the document with. * @param {Object} query The query object that we need to match to perform an update. * @param {Object} options An options object. * @param {String} path The current recursive path. * @param {String} opType The type of update operation to perform, if none is specified * default is to set new data against matching fields. * @returns {Boolean} True if the document was updated with new / changed data or * false if it was not updated because the data was the same. * @private */ Collection.prototype.updateObject = function (doc, update, query, options, path, opType) { // TODO: This method is long, try to break it into smaller pieces update = this.decouple(update); // Clear leading dots from path path = path || ''; if (path.substr(0, 1) === '.') { path = path.substr(1, path.length -1); } //var oldDoc = this.decouple(doc), var updated = false, recurseUpdated = false, operation, tmpArray, tmpIndex, tmpCount, tempIndex, pathInstance, sourceIsArray, updateIsArray, i; // Loop each key in the update object for (i in update) { if (update.hasOwnProperty(i)) { // Reset operation flag operation = false; // Check if the property starts with a dollar (function) if (i.substr(0, 1) === '$') { // Check for commands switch (i) { case '$key': case '$index': // Ignore some operators operation = true; break; default: operation = true; // Now run the operation recurseUpdated = this.updateObject(doc, update[i], query, options, path, i); updated = updated || recurseUpdated; break; } } // Check if the key has a .$ at the end, denoting an array lookup if (this._isPositionalKey(i)) { operation = true; // Modify i to be the name of the field i = i.substr(0, i.length - 2); pathInstance = new Path(path + '.' + i); // Check if the key is an array and has items if (doc[i] && doc[i] instanceof Array && doc[i].length) { tmpArray = []; // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], pathInstance.value(query)[0], '', {})) { tmpArray.push(tmpIndex); } } // Loop the items that matched and update them for (tmpIndex = 0; tmpIndex < tmpArray.length; tmpIndex++) { recurseUpdated = this.updateObject(doc[i][tmpArray[tmpIndex]], update[i + '.$'], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } } if (!operation) { if (!opType && typeof(update[i]) === 'object') { if (doc[i] !== null && typeof(doc[i]) === 'object') { // Check if we are dealing with arrays sourceIsArray = doc[i] instanceof Array; updateIsArray = update[i] instanceof Array; if (sourceIsArray || updateIsArray) { // Check if the update is an object and the doc is an array if (!updateIsArray && sourceIsArray) { // Update is an object, source is an array so match the array items // with our query object to find the one to update inside this array // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { recurseUpdated = this.updateObject(doc[i][tmpIndex], update[i], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } else { // Either both source and update are arrays or the update is // an array and the source is not, so set source to update if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } } } else { // The doc key is an object so traverse the // update further recurseUpdated = this.updateObject(doc[i], update[i], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } else { if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } } } else { switch (opType) { case '$inc': this._updateIncrement(doc, i, update[i]); updated = true; break; case '$push': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { // Check for a $position modifier with an $each if (update[i].$position !== undefined && update[i].$each instanceof Array) { // Grab the position to insert at tempIndex = update[i].$position; // Loop the each array and push each item tmpCount = update[i].$each.length; for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) { this._updateSplicePush(doc[i], tempIndex + tmpIndex, update[i].$each[tmpIndex]); } } else if (update[i].$each instanceof Array) { // Do a loop over the each to push multiple items tmpCount = update[i].$each.length; for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) { this._updatePush(doc[i], update[i].$each[tmpIndex]); } } else { // Do a standard push this._updatePush(doc[i], update[i]); } updated = true; } else { throw('ForerunnerDB.Collection "' + this.name() + '": Cannot push to a key that is not an array! (' + i + ')'); } break; case '$pull': if (doc[i] instanceof Array) { tmpArray = []; // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], update[i], '', {})) { tmpArray.push(tmpIndex); } } tmpCount = tmpArray.length; // Now loop the pull array and remove items to be pulled while (tmpCount--) { this._updatePull(doc[i], tmpArray[tmpCount]); updated = true; } } break; case '$pullAll': if (doc[i] instanceof Array) { if (update[i] instanceof Array) { tmpArray = doc[i]; tmpCount = tmpArray.length; if (tmpCount > 0) { // Now loop the pull array and remove items to be pulled while (tmpCount--) { for (tempIndex = 0; tempIndex < update[i].length; tempIndex++) { if (tmpArray[tmpCount] === update[i][tempIndex]) { this._updatePull(doc[i], tmpCount); tmpCount--; updated = true; } } if (tmpCount < 0) { break; } } } } else { throw('ForerunnerDB.Collection "' + this.name() + '": Cannot pullAll without being given an array of values to pull! (' + i + ')'); } } break; case '$addToSet': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { // Loop the target array and check for existence of item var targetArr = doc[i], targetArrIndex, targetArrCount = targetArr.length, objHash, addObj = true, optionObj = (options && options.$addToSet), hashMode, pathSolver; // Check if we have an options object for our operation if (update[i].$key) { hashMode = false; pathSolver = new Path(update[i].$key); objHash = pathSolver.value(update[i])[0]; // Remove the key from the object before we add it delete update[i].$key; } else if (optionObj && optionObj.key) { hashMode = false; pathSolver = new Path(optionObj.key); objHash = pathSolver.value(update[i])[0]; } else { objHash = JSON.stringify(update[i]); hashMode = true; } for (targetArrIndex = 0; targetArrIndex < targetArrCount; targetArrIndex++) { if (hashMode) { // Check if objects match via a string hash (JSON) if (JSON.stringify(targetArr[targetArrIndex]) === objHash) { // The object already exists, don't add it addObj = false; break; } } else { // Check if objects match based on the path if (objHash === pathSolver.value(targetArr[targetArrIndex])[0]) { // The object already exists, don't add it addObj = false; break; } } } if (addObj) { this._updatePush(doc[i], update[i]); updated = true; } } else { throw('ForerunnerDB.Collection "' + this.name() + '": Cannot addToSet on a key that is not an array! (' + i + ')'); } break; case '$splicePush': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { tempIndex = update.$index; if (tempIndex !== undefined) { delete update.$index; // Check for out of bounds index if (tempIndex > doc[i].length) { tempIndex = doc[i].length; } this._updateSplicePush(doc[i], tempIndex, update[i]); updated = true; } else { throw('ForerunnerDB.Collection "' + this.name() + '": Cannot splicePush without a $index integer value!'); } } else { throw('ForerunnerDB.Collection "' + this.name() + '": Cannot splicePush with a key that is not an array! (' + i + ')'); } break; case '$move': if (doc[i] instanceof Array) { // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], update[i], '', {})) { var moveToIndex = update.$index; if (moveToIndex !== undefined) { delete update.$index; this._updateSpliceMove(doc[i], tmpIndex, moveToIndex); updated = true; } else { throw('ForerunnerDB.Collection "' + this.name() + '": Cannot move without a $index integer value!'); } break; } } } else { throw('ForerunnerDB.Collection "' + this.name() + '": Cannot move on a key that is not an array! (' + i + ')'); } break; case '$mul': this._updateMultiply(doc, i, update[i]); updated = true; break; case '$rename': this._updateRename(doc, i, update[i]); updated = true; break; case '$unset': this._updateUnset(doc, i); updated = true; break; case '$pop': if (doc[i] instanceof Array) { if (this._updatePop(doc[i], update[i])) { updated = true; } } else { throw('ForerunnerDB.Collection "' + this.name() + '": Cannot pop from a key that is not an array! (' + i + ')'); } break; default: if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } break; } } } } } return updated; }; /** * Determines if the passed key has an array positional mark (a dollar at the end * of its name). * @param {String} key The key to check. * @returns {Boolean} True if it is a positional or false if not. * @private */ Collection.prototype._isPositionalKey = function (key) { return key.substr(key.length - 2, 2) === '.$'; }; /** * Updates a property on an object depending on if the collection is * currently running data-binding or not. * @param {Object} doc The object whose property is to be updated. * @param {String} prop The property to update. * @param {*} val The new value of the property. * @private */ Collection.prototype._updateProperty = function (doc, prop, val) { doc[prop] = val; if (this.debug()) { console.log('ForerunnerDB.Collection: Setting non-data-bound document property "' + prop + '" for collection "' + this.name() + '"'); } }; /** * Increments a value for a property on a document by the passed number. * @param {Object} doc The document to modify. * @param {String} prop The property to modify. * @param {Number} val The amount to increment by. * @private */ Collection.prototype._updateIncrement = function (doc, prop, val) { doc[prop] += val; }; /** * Changes the index of an item in the passed array. * @param {Array} arr The array to modify. * @param {Number} indexFrom The index to move the item from. * @param {Number} indexTo The index to move the item to. * @private */ Collection.prototype._updateSpliceMove = function (arr, indexFrom, indexTo) { arr.splice(indexTo, 0, arr.splice(indexFrom, 1)[0]); if (this.debug()) { console.log('ForerunnerDB.Collection: Moving non-data-bound document array index from "' + indexFrom + '" to "' + indexTo + '" for collection "' + this.name() + '"'); } }; /** * Inserts an item into the passed array at the specified index. * @param {Array} arr The array to insert into. * @param {Number} index The index to insert at. * @param {Object} doc The document to insert. * @private */ Collection.prototype._updateSplicePush = function (arr, index, doc) { if (arr.length > index) { arr.splice(index, 0, doc); } else { arr.push(doc); } }; /** * Inserts an item at the end of an array. * @param {Array} arr The array to insert the item into. * @param {Object} doc The document to insert. * @private */ Collection.prototype._updatePush = function (arr, doc) { arr.push(doc); }; /** * Removes an item from the passed array. * @param {Array} arr The array to modify. * @param {Number} index The index of the item in the array to remove. * @private */ Collection.prototype._updatePull = function (arr, index) { arr.splice(index, 1); }; /** * Multiplies a value for a property on a document by the passed number. * @param {Object} doc The document to modify. * @param {String} prop The property to modify. * @param {Number} val The amount to multiply by. * @private */ Collection.prototype._updateMultiply = function (doc, prop, val) { doc[prop] *= val; }; /** * Renames a property on a document to the passed property. * @param {Object} doc The document to modify. * @param {String} prop The property to rename. * @param {Number} val The new property name. * @private */ Collection.prototype._updateRename = function (doc, prop, val) { doc[val] = doc[prop]; delete doc[prop]; }; /** * Deletes a property on a document. * @param {Object} doc The document to modify. * @param {String} prop The property to delete. * @private */ Collection.prototype._updateUnset = function (doc, prop) { delete doc[prop]; }; /** * Pops an item from the array stack. * @param {Object} doc The document to modify. * @param {Number=} val Optional, if set to 1 will pop, if set to -1 will shift. * @return {Boolean} * @private */ Collection.prototype._updatePop = function (doc, val) { var updated = false; if (doc.length > 0) { if (val === 1) { doc.pop(); updated = true; } else if (val === -1) { doc.shift(); updated = true; } } return updated; }; /** * Removes any documents from the collection that match the search query * key/values. * @param {Object} query The query object. * @param {Object=} options An options object. * @param {Function=} callback A callback method. * @returns {Array} An array of the documents that were removed. */ Collection.prototype.remove = function (query, options, callback) { if (this._state === 'dropped') { throw('ForerunnerDB.Collection "' + this.name() + '": Cannot operate in a dropped state!'); } var self = this, dataSet, index, arrIndex, returnArr, removeMethod, triggerOperation, doc, newDoc; if (query instanceof Array) { returnArr = []; for (arrIndex = 0; arrIndex < query.length; arrIndex++) { returnArr.push(this.remove(query[arrIndex], {noEmit: true})); } if (!options || (options && !options.noEmit)) { this._onRemove(returnArr); } if (callback) { callback(false, returnArr); } return returnArr; } else { dataSet = this.find(query, {$decouple: false}); if (dataSet.length) { removeMethod = function (dataItem) { // Remove the item from the collection's indexes self._removeFromIndexes(dataItem); // Remove data from internal stores index = self._data.indexOf(dataItem); self._dataRemoveAtIndex(index); }; // Remove the data from the collection for (var i = 0; i < dataSet.length; i++) { doc = dataSet[i]; if (self.willTrigger(self.TYPE_REMOVE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_REMOVE, self.PHASE_AFTER)) { triggerOperation = { type: 'remove' }; newDoc = self.decouple(doc); if (self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_BEFORE, newDoc, newDoc) !== false) { // The trigger didn't ask to cancel so execute the removal method removeMethod(doc); self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_AFTER, newDoc, newDoc); } } else { // No triggers to execute removeMethod(doc); } } //op.time('Resolve chains'); this.chainSend('remove', { query: query, dataSet: dataSet }, options); //op.time('Resolve chains'); if (!options || (options && !options.noEmit)) { this._onRemove(dataSet); } this.deferEmit('change', {type: 'remove', data: dataSet}); } if (callback) { callback(false, dataSet); } return dataSet; } }; /** * Helper method that removes a document that matches the given id. * @param {String} id The id of the document to remove. * @returns {Array} An array of documents that were removed. */ Collection.prototype.removeById = function (id) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.remove(searchObj); }; /** * Queues an event to be fired. This has automatic de-bouncing so that any * events of the same type that occur within 100 milliseconds of a previous * one will all be wrapped into a single emit rather than emitting tons of * events for lots of chained inserts etc. * @private */ Collection.prototype.deferEmit = function () { var self = this, args; if (!this._noEmitDefer && (!this._db || (this._db && !this._db._noEmitDefer))) { args = arguments; // Check for an existing timeout if (this._changeTimeout) { clearTimeout(this._changeTimeout); } // Set a timeout this._changeTimeout = setTimeout(function () { if (self.debug()) { console.log('ForerunnerDB.Collection: Emitting ' + args[0]); } self.emit.apply(self, args); }, 100); } else { this.emit.apply(this, arguments); } }; /** * Processes a deferred action queue. * @param {String} type The queue name to process. * @param {Function} callback A method to call when the queue has processed. */ Collection.prototype.processQueue = function (type, callback) { var queue = this._deferQueue[type], deferThreshold = this._deferThreshold[type], deferTime = this._deferTime[type]; if (queue.length) { var self = this, dataArr; // Process items up to the threshold if (queue.length) { if (queue.length > deferThreshold) { // Grab items up to the threshold value dataArr = queue.splice(0, deferThreshold); } else { // Grab all the remaining items dataArr = queue.splice(0, queue.length); } this[type](dataArr); } // Queue another process setTimeout(function () { self.processQueue(type, callback); }, deferTime); } else { if (callback) { callback(); } } }; /** * Inserts a document or array of documents into the collection. * @param {Object||Array} data Either a document object or array of document * @param {Number=} index Optional index to insert the record at. * @param {Function=} callback Optional callback called once action is complete. * objects to insert into the collection. */ Collection.prototype.insert = function (data, index, callback) { if (this._state === 'dropped') { throw('ForerunnerDB.Collection "' + this.name() + '": Cannot operate in a dropped state!'); } if (typeof(index) === 'function') { callback = index; index = this._data.length; } else if (index === undefined) { index = this._data.length; } data = this.transformIn(data); return this._insertHandle(data, index, callback); }; /** * Inserts a document or array of documents into the collection. * @param {Object||Array} data Either a document object or array of document * @param {Number=} index Optional index to insert the record at. * @param {Function=} callback Optional callback called once action is complete. * objects to insert into the collection. */ Collection.prototype._insertHandle = function (data, index, callback) { var //self = this, queue = this._deferQueue.insert, deferThreshold = this._deferThreshold.insert, //deferTime = this._deferTime.insert, inserted = [], failed = [], insertResult, i; if (data instanceof Array) { // Check if there are more insert items than the insert defer // threshold, if so, break up inserts so we don't tie up the // ui or thread if (data.length > deferThreshold) { // Break up insert into blocks this._deferQueue.insert = queue.concat(data); // Fire off the insert queue handler this.processQueue('insert', callback); return; } else { // Loop the array and add items for (i = 0; i < data.length; i++) { insertResult = this._insert(data[i], index + i); if (insertResult === true) { inserted.push(data[i]); } else { failed.push({ doc: data[i], reason: insertResult }); } } } } else { // Store the data item insertResult = this._insert(data, index); if (insertResult === true) { inserted.push(data); } else { failed.push({ doc: data, reason: insertResult }); } } //op.time('Resolve chains'); this.chainSend('insert', data, {index: index}); //op.time('Resolve chains'); this._onInsert(inserted, failed); if (callback) { callback(); } this.deferEmit('change', {type: 'insert', data: inserted}); return { inserted: inserted, failed: failed }; }; /** * Internal method to insert a document into the collection. Will * check for index violations before allowing the document to be inserted. * @param {Object} doc The document to insert after passing index violation * tests. * @param {Number=} index Optional index to insert the document at. * @returns {Boolean|Object} True on success, false if no document passed, * or an object containing details about an index violation if one occurred. * @private */ Collection.prototype._insert = function (doc, index) { if (doc) { var self = this, indexViolation, triggerOperation, insertMethod, newDoc; this.ensurePrimaryKey(doc); // Check indexes are not going to be broken by the document indexViolation = this.insertIndexViolation(doc); insertMethod = function (doc) { // Add the item to the collection's indexes self._insertIntoIndexes(doc); // Check index overflow if (index > self._data.length) { index = self._data.length; } // Insert the document self._dataInsertAtIndex(index, doc); }; if (!indexViolation) { if (self.willTrigger(self.TYPE_INSERT, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) { triggerOperation = { type: 'insert' }; if (self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_BEFORE, {}, doc) !== false) { insertMethod(doc); if (self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) { // Clone the doc so that the programmer cannot update the internal document // on the "after" phase trigger newDoc = self.decouple(doc); self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_AFTER, {}, newDoc); } } else { // The trigger just wants to cancel the operation return false; } } else { // No triggers to execute insertMethod(doc); } return true; } else { return 'Index violation in index: ' + indexViolation; } } return 'No document passed to insert'; }; /** * Inserts a document into the internal collection data array at * Inserts a document into the internal collection data array at * the specified index. * @param {number} index The index to insert at. * @param {object} doc The document to insert. * @private */ Collection.prototype._dataInsertAtIndex = function (index, doc) { this._data.splice(index, 0, doc); }; /** * Removes a document from the internal collection data array at * the specified index. * @param {number} index The index to remove from. * @private */ Collection.prototype._dataRemoveAtIndex = function (index) { this._data.splice(index, 1); }; /** * Replaces all data in the collection's internal data array with * the passed array of data. * @param {array} data The array of data to replace existing data with. * @private */ Collection.prototype._dataReplace = function (data) { // Clear the array - using a while loop with pop is by far the // fastest way to clear an array currently while (this._data.length) { this._data.pop(); } // Append new items to the array this._data = this._data.concat(data); }; /** * Inserts a document into the collection indexes. * @param {Object} doc The document to insert. * @private */ Collection.prototype._insertIntoIndexes = function (doc) { var arr = this._indexByName, arrIndex, violated, jString = JSON.stringify(doc); // Insert to primary key index violated = this._primaryIndex.uniqueSet(doc[this._primaryKey], doc); this._primaryCrc.uniqueSet(doc[this._primaryKey], jString); this._crcLookup.uniqueSet(jString, doc); // Insert into other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].insert(doc); } } return violated; }; /** * Removes a document from the collection indexes. * @param {Object} doc The document to remove. * @private */ Collection.prototype._removeFromIndexes = function (doc) { var arr = this._indexByName, arrIndex, jString = JSON.stringify(doc); // Remove from primary key index this._primaryIndex.unSet(doc[this._primaryKey]); this._primaryCrc.unSet(doc[this._primaryKey]); this._crcLookup.unSet(jString); // Remove from other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].remove(doc); } } }; /** * Rebuild collection indexes. * @private */ Collection.prototype._rebuildIndexes = function () { var arr = this._indexByName, arrIndex; // Remove from other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].rebuild(); } } }; /** * Returns the index of the document identified by the passed item's primary key. * @param {Object} item The item whose primary key should be used to lookup. * @returns {Number} The index the item with the matching primary key is occupying. */ Collection.prototype.indexOfDocById = function (item) { return this._data.indexOf( this._primaryIndex.get( item[this._primaryKey] ) ); }; /** * Uses the passed query to generate a new collection with results * matching the query parameters. * * @param query * @param options * @returns {*} */ Collection.prototype.subset = function (query, options) { var result = this.find(query, options); return new Collection() ._subsetOf(this) .primaryKey(this._primaryKey) .setData(result); }; /** * Gets the collection that this collection is a subset of. * @returns {Collection} */ Collection.prototype.subsetOf = function () { return this.__subsetOf; }; /** * Sets the collection that this collection is a subset of. * @param {Collection} collection The collection to set as the parent of this subset. * @returns {*} This object for chaining. * @private */ Collection.prototype._subsetOf = function (collection) { this.__subsetOf = collection; return this; }; /** * Find the distinct values for a specified field across a single collection and * returns the results in an array. * @param {String} key The field path to return distinct values for e.g. "person.name". * @param {Object=} query The query to use to filter the documents used to return values from. * @param {Object=} options The query options to use when running the query. * @returns {Array} */ Collection.prototype.distinct = function (key, query, options) { if (this._state === 'dropped') { throw('ForerunnerDB.Collection "' + this.name() + '": Cannot operate in a dropped state!'); } var data = this.find(query, options), pathSolver = new Path(key), valueUsed = {}, distinctValues = [], value, i; // Loop the data and build array of distinct values for (i = 0; i < data.length; i++) { value = pathSolver.value(data[i])[0]; if (value && !valueUsed[value]) { valueUsed[value] = true; distinctValues.push(value); } } return distinctValues; }; /** * Helper method to find a document by it's id. * @param {String} id The id of the document. * @param {Object=} options The options object, allowed keys are sort and limit. * @returns {Array} The items that were updated. */ Collection.prototype.findById = function (id, options) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.find(searchObj, options)[0]; }; /** * Finds all documents that contain the passed string or search object * regardless of where the string might occur within the document. This * will match strings from the start, middle or end of the document's * string (partial match). * @param search The string to search for. Case sensitive. * @param options A standard find() options object. * @returns {Array} An array of documents that matched the search string. */ Collection.prototype.peek = function (search, options) { // Loop all items var arr = this._data, arrCount = arr.length, arrIndex, arrItem, tempColl = new Collection(), typeOfSearch = typeof search; if (typeOfSearch === 'string') { for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { // Get json representation of object arrItem = JSON.stringify(arr[arrIndex]); // Check if string exists in object json if (arrItem.indexOf(search) > -1) { // Add this item to the temp collection tempColl.insert(arr[arrIndex]); } } return tempColl.find({}, options); } else { return this.find(search, options); } }; /** * Provides a query plan / operations log for a query. * @param {Object} query The query to execute. * @param {Object=} options Optional options object. * @returns {Object} The query plan. */ Collection.prototype.explain = function (query, options) { var result = this.find(query, options); return result.__fdbOp._data; }; /** * Generates an options object with default values or adds default * values to a passed object if those values are not currently set * to anything. * @param {object=} obj Optional options object to modify. * @returns {object} The options object. */ Collection.prototype.options = function (obj) { obj = obj || {}; obj.$decouple = obj.$decouple !== undefined ? obj.$decouple : true; obj.$explain = obj.$explain !== undefined ? obj.$explain : false; return obj; }; /** * Queries the collection based on the query object passed. * @param {Object} query The query key/values that a document must match in * order for it to be returned in the result array. * @param {Object=} options An optional options object. * * @returns {Array} The results array from the find operation, containing all * documents that matched the query. */ Collection.prototype.find = function (query, options) { if (this._state === 'dropped') { throw('ForerunnerDB.Collection "' + this.name() + '": Cannot operate in a dropped state!'); } // TODO: This method is quite long, break into smaller pieces query = query || {}; options = this.options(options); var op = this._metrics.create('find'), pk = this.primaryKey(), self = this, analysis, //finalQuery, scanLength, requiresTableScan = true, resultArr, joinCollectionIndex, joinIndex, joinCollection = {}, joinQuery, joinPath, joinCollectionName, joinCollectionInstance, joinMatch, joinMatchIndex, joinSearch, joinMulti, joinRequire, joinFindResults, resultCollectionName, resultIndex, resultRemove = [], index, i, j, k, fieldListOn = [], fieldListOff = [], elemMatchPathSolver, elemMatchSubArr, elemMatchSpliceArr, matcherTmpOptions = {}, result, matcher = function (doc) { return self._match(doc, query, 'and', matcherTmpOptions); }; op.start(); if (query) { // Get query analysis to execute best optimised code path op.time('analyseQuery'); analysis = this._analyseQuery(query, options, op); op.time('analyseQuery'); op.data('analysis', analysis); if (analysis.hasJoin && analysis.queriesJoin) { // The query has a join and tries to limit by it's joined data // Get an instance reference to the join collections op.time('joinReferences'); for (joinIndex = 0; joinIndex < analysis.joinsOn.length; joinIndex++) { joinCollectionName = analysis.joinsOn[joinIndex]; joinPath = new Path(analysis.joinQueries[joinCollectionName]); joinQuery = joinPath.value(query)[0]; joinCollection[analysis.joinsOn[joinIndex]] = this._db.collection(analysis.joinsOn[joinIndex]).subset(joinQuery); } op.time('joinReferences'); } // Check if an index lookup can be used to return this result if (analysis.indexMatch.length && (!options || (options && !options.$skipIndex))) { op.data('index.potential', analysis.indexMatch); op.data('index.used', analysis.indexMatch[0].index); // Get the data from the index op.time('indexLookup'); resultArr = analysis.indexMatch[0].lookup; op.time('indexLookup'); // Check if the index coverage is all keys, if not we still need to table scan it if (analysis.indexMatch[0].keyData.totalKeyCount === analysis.indexMatch[0].keyData.score) { // Require a table scan to find relevant documents requiresTableScan = false; } } else { op.flag('usedIndex', false); } if (requiresTableScan) { if (resultArr && resultArr.length) { scanLength = resultArr.length; op.time('tableScan: ' + scanLength); // Filter the source data and return the result resultArr = resultArr.filter(matcher); } else { // Filter the source data and return the result scanLength = this._data.length; op.time('tableScan: ' + scanLength); resultArr = this._data.filter(matcher); } // Order the array if we were passed a sort clause if (options.$orderBy) { op.time('sort'); resultArr = this.sort(options.$orderBy, resultArr); op.time('sort'); } op.time('tableScan: ' + scanLength); } if (options.$limit && resultArr && resultArr.length > options.$limit) { resultArr.length = options.$limit; op.data('limit', options.$limit); } if (options.$decouple) { // Now decouple the data from the original objects op.time('decouple'); resultArr = this.decouple(resultArr); op.time('decouple'); op.data('flag.decouple', true); } // Now process any joins on the final data if (options.$join) { for (joinCollectionIndex = 0; joinCollectionIndex < options.$join.length; joinCollectionIndex++) { for (joinCollectionName in options.$join[joinCollectionIndex]) { if (options.$join[joinCollectionIndex].hasOwnProperty(joinCollectionName)) { // Set the key to store the join result in to the collection name by default resultCollectionName = joinCollectionName; // Get the join collection instance from the DB joinCollectionInstance = this._db.collection(joinCollectionName); // Get the match data for the join joinMatch = options.$join[joinCollectionIndex][joinCollectionName]; // Loop our result data array for (resultIndex = 0; resultIndex < resultArr.length; resultIndex++) { // Loop the join conditions and build a search object from them joinSearch = {}; joinMulti = false; joinRequire = false; for (joinMatchIndex in joinMatch) { if (joinMatch.hasOwnProperty(joinMatchIndex)) { // Check the join condition name for a special command operator if (joinMatchIndex.substr(0, 1) === '$') { // Special command switch (joinMatchIndex) { case '$as': // Rename the collection when stored in the result document resultCollectionName = joinMatch[joinMatchIndex]; break; case '$multi': // Return an array of documents instead of a single matching document joinMulti = joinMatch[joinMatchIndex]; break; case '$require': // Remove the result item if no matching join data is found joinRequire = joinMatch[joinMatchIndex]; break; /*default: // Check for a double-dollar which is a back-reference to the root collection item if (joinMatchIndex.substr(0, 3) === '$$.') { // Back reference // TODO: Support complex joins } break;*/ } } else { // TODO: Could optimise this by caching path objects // Get the data to match against and store in the search object joinSearch[joinMatchIndex] = new Path(joinMatch[joinMatchIndex]).value(resultArr[resultIndex])[0]; } } } // Do a find on the target collection against the match data joinFindResults = joinCollectionInstance.find(joinSearch); // Check if we require a joined row to allow the result item if (!joinRequire || (joinRequire && joinFindResults[0])) { // Join is not required or condition is met resultArr[resultIndex][resultCollectionName] = joinMulti === false ? joinFindResults[0] : joinFindResults; } else { // Join required but condition not met, add item to removal queue resultRemove.push(resultArr[resultIndex]); } } } } } op.data('flag.join', true); } // Process removal queue if (resultRemove.length) { op.time('removalQueue'); for (i = 0; i < resultRemove.length; i++) { index = resultArr.indexOf(resultRemove[i]); if (index > -1) { resultArr.splice(index, 1); } } op.time('removalQueue'); } if (options.$transform) { op.time('transform'); for (i = 0; i < resultArr.length; i++) { resultArr.splice(i, 1, options.$transform(resultArr[i])); } op.time('transform'); op.data('flag.transform', true); } // Process transforms if (this._transformEnabled && this._transformOut) { op.time('transformOut'); resultArr = this.transformOut(resultArr); op.time('transformOut'); } op.data('results', resultArr.length); } else { resultArr = []; } // Generate a list of fields to limit data by // Each property starts off being enabled by default (= 1) then // if any property is explicitly specified as 1 then all switch to // zero except _id. // // Any that are explicitly set to zero are switched off. op.time('scanFields'); for (i in options) { if (options.hasOwnProperty(i) && i.indexOf('$') !== 0) { if (options[i] === 1) { fieldListOn.push(i); } else if (options[i] === 0) { fieldListOff.push(i); } } } op.time('scanFields'); // Limit returned fields by the options data if (fieldListOn.length || fieldListOff.length) { op.data('flag.limitFields', true); op.data('limitFields.on', fieldListOn); op.data('limitFields.off', fieldListOff); op.time('limitFields'); // We have explicit fields switched on or off for (i = 0; i < resultArr.length; i++) { result = resultArr[i]; for (j in result) { if (result.hasOwnProperty(j)) { if (fieldListOn.length) { // We have explicit fields switched on so remove all fields // that are not explicitly switched on // Check if the field name is not the primary key if (j !== pk) { if (fieldListOn.indexOf(j) === -1) { // This field is not in the on list, remove it delete result[j]; } } } if (fieldListOff.length) { // We have explicit fields switched off so remove fields // that are explicitly switched off if (fieldListOff.indexOf(j) > -1) { // This field is in the off list, remove it delete result[j]; } } } } } op.time('limitFields'); } // Now run any projections on the data required if (options.$elemMatch) { op.data('flag.elemMatch', true); op.time('projection-elemMatch'); for (i in options.$elemMatch) { if (options.$elemMatch.hasOwnProperty(i)) { elemMatchPathSolver = new Path(i); // Loop the results array for (j = 0; j < resultArr.length; j++) { elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0]; // Check we have a sub-array to loop if (elemMatchSubArr && elemMatchSubArr.length) { // Loop the sub-array and check for projection query matches for (k = 0; k < elemMatchSubArr.length; k++) { // Check if the current item in the sub-array matches the projection query if (self._match(elemMatchSubArr[k], options.$elemMatch[i], '', {})) { // The item matches the projection query so set the sub-array // to an array that ONLY contains the matching item and then // exit the loop since we only want to match the first item elemMatchPathSolver.set(resultArr[j], i, [elemMatchSubArr[k]]); break; } } } } } } op.time('projection-elemMatch'); } if (options.$elemsMatch) { op.data('flag.elemsMatch', true); op.time('projection-elemsMatch'); for (i in options.$elemsMatch) { if (options.$elemsMatch.hasOwnProperty(i)) { elemMatchPathSolver = new Path(i); // Loop the results array for (j = 0; j < resultArr.length; j++) { elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0]; // Check we have a sub-array to loop if (elemMatchSubArr && elemMatchSubArr.length) { elemMatchSpliceArr = []; // Loop the sub-array and check for projection query matches for (k = 0; k < elemMatchSubArr.length; k++) { // Check if the current item in the sub-array matches the projection query if (self._match(elemMatchSubArr[k], options.$elemsMatch[i], '', {})) { // The item matches the projection query so add it to the final array elemMatchSpliceArr.push(elemMatchSubArr[k]); } } // Now set the final sub-array to the matched items elemMatchPathSolver.set(resultArr[j], i, elemMatchSpliceArr); } } } } op.time('projection-elemsMatch'); } op.stop(); resultArr.__fdbOp = op; return resultArr; }; /** * Returns one document that satisfies the specified query criteria. If multiple * documents satisfy the query, this method returns the first document to match * the query. * @returns {*} */ Collection.prototype.findOne = function () { return (this.find.apply(this, arguments))[0]; }; /** * Gets the index in the collection data array of the first item matched by * the passed query object. * @param {Object} query The query to run to find the item to return the index of. * @returns {Number} */ Collection.prototype.indexOf = function (query) { var item = this.find(query, {$decouple: false})[0]; if (item) { return this._data.indexOf(item); } }; /** * Gets / sets the collection transform options. * @param {Object} obj A collection transform options object. * @returns {*} */ Collection.prototype.transform = function (obj) { if (obj !== undefined) { if (typeof obj === "object") { if (obj.enabled !== undefined) { this._transformEnabled = obj.enabled; } if (obj.dataIn !== undefined) { this._transformIn = obj.dataIn; } if (obj.dataOut !== undefined) { this._transformOut = obj.dataOut; } } else { this._transformEnabled = obj !== false; } return this; } return { enabled: this._transformEnabled, dataIn: this._transformIn, dataOut: this._transformOut }; }; /** * Transforms data using the set transformIn method. * @param {Object} data The data to transform. * @returns {*} */ Collection.prototype.transformIn = function (data) { if (this._transformEnabled && this._transformIn) { if (data instanceof Array) { var finalArr = [], i; for (i = 0; i < data.length; i++) { finalArr[i] = this._transformIn(data[i]); } return finalArr; } else { return this._transformIn(data); } } return data; }; /** * Transforms data using the set transformOut method. * @param {Object} data The data to transform. * @returns {*} */ Collection.prototype.transformOut = function (data) { if (this._transformEnabled && this._transformOut) { if (data instanceof Array) { var finalArr = [], i; for (i = 0; i < data.length; i++) { finalArr[i] = this._transformOut(data[i]); } return finalArr; } else { return this._transformOut(data); } } return data; }; /** * Sorts an array of documents by the given sort path. * @param {*} sortObj The keys and orders the array objects should be sorted by. * @param {Array} arr The array of documents to sort. * @returns {Array} */ Collection.prototype.sort = function (sortObj, arr) { // Make sure we have an array object arr = arr || []; var sortArr = [], sortKey, sortSingleObj; for (sortKey in sortObj) { if (sortObj.hasOwnProperty(sortKey)) { sortSingleObj = {}; sortSingleObj[sortKey] = sortObj[sortKey]; sortSingleObj.___fdbKey = sortKey; sortArr.push(sortSingleObj); } } if (sortArr.length < 2) { // There is only one sort criteria, do a simple sort and return it return this._sort(sortObj, arr); } else { return this._bucketSort(sortArr, arr); } }; /** * Takes array of sort paths and sorts them into buckets before returning final * array fully sorted by multi-keys. * @param keyArr * @param arr * @returns {*} * @private */ Collection.prototype._bucketSort = function (keyArr, arr) { var keyObj = keyArr.shift(), arrCopy, buckets, i, finalArr = []; if (keyArr.length > 0) { // Sort array by bucket key arr = this._sort(keyObj, arr); // Split items into buckets buckets = this.bucket(keyObj.___fdbKey, arr); // Loop buckets and sort contents for (i in buckets) { if (buckets.hasOwnProperty(i)) { arrCopy = [].concat(keyArr); finalArr = finalArr.concat(this._bucketSort(arrCopy, buckets[i])); } } return finalArr; } else { return this._sort(keyObj, arr); } }; /** * Sorts array by individual sort path. * @param key * @param arr * @returns {Array|*} * @private */ Collection.prototype._sort = function (key, arr) { var self = this, sorterMethod, pathSolver = new Path(), dataPath = pathSolver.parse(key, true)[0]; pathSolver.path(dataPath.path); if (dataPath.value === 1) { // Sort ascending sorterMethod = function (a, b) { var valA = pathSolver.value(a)[0], valB = pathSolver.value(b)[0]; return self.sortAsc(valA, valB); }; } else if (dataPath.value === -1) { // Sort descending sorterMethod = function (a, b) { var valA = pathSolver.value(a)[0], valB = pathSolver.value(b)[0]; return self.sortDesc(valA, valB); }; } else { throw('ForerunnerDB.Collection "' + this.name() + '": $orderBy clause has invalid direction: ' + dataPath.value + ', accepted values are 1 or -1 for ascending or descending!'); } return arr.sort(sorterMethod); }; /** * Takes an array of objects and returns a new object with the array items * split into buckets by the passed key. * @param {String} key The key to split the array into buckets by. * @param {Array} arr An array of objects. * @returns {Object} */ Collection.prototype.bucket = function (key, arr) { var i, buckets = {}; for (i = 0; i < arr.length; i++) { buckets[arr[i][key]] = buckets[arr[i][key]] || []; buckets[arr[i][key]].push(arr[i]); } return buckets; }; /** * Internal method that takes a search query and options and returns an object * containing details about the query which can be used to optimise the search. * * @param query * @param options * @param op * @returns {Object} * @private */ Collection.prototype._analyseQuery = function (query, options, op) { var analysis = { queriesOn: [this._name], indexMatch: [], hasJoin: false, queriesJoin: false, joinQueries: {}, query: query, options: options }, joinCollectionIndex, joinCollectionName, joinCollections = [], joinCollectionReferences = [], queryPath, index, indexMatchData, indexRef, indexRefName, indexLookup, pathSolver, queryKeyCount, i; // Check if the query is a primary key lookup op.time('checkIndexes'); pathSolver = new Path(); queryKeyCount = pathSolver.countKeys(query); if (queryKeyCount) { if (query[this._primaryKey] !== undefined) { // Return item via primary key possible op.time('checkIndexMatch: Primary Key'); analysis.indexMatch.push({ lookup: this._primaryIndex.lookup(query, options), keyData: { matchedKeys: [this._primaryKey], totalKeyCount: queryKeyCount, score: 1 }, index: this._primaryIndex }); op.time('checkIndexMatch: Primary Key'); } // Check if an index can speed up the query for (i in this._indexById) { if (this._indexById.hasOwnProperty(i)) { indexRef = this._indexById[i]; indexRefName = indexRef.name(); op.time('checkIndexMatch: ' + indexRefName); indexMatchData = indexRef.match(query, options); if (indexMatchData.score > 0) { // This index can be used, store it indexLookup = indexRef.lookup(query, options); analysis.indexMatch.push({ lookup: indexLookup, keyData: indexMatchData, index: indexRef }); } op.time('checkIndexMatch: ' + indexRefName); if (indexMatchData.score === queryKeyCount) { // Found an optimal index, do not check for any more break; } } } op.time('checkIndexes'); // Sort array descending on index key count (effectively a measure of relevance to the query) if (analysis.indexMatch.length > 1) { op.time('findOptimalIndex'); analysis.indexMatch.sort(function (a, b) { if (a.keyData.score > b.keyData.score) { // This index has a higher score than the other return -1; } if (a.keyData.score < b.keyData.score) { // This index has a lower score than the other return 1; } // The indexes have the same score but can still be compared by the number of records // they return from the query. The fewer records they return the better so order by // record count if (a.keyData.score === b.keyData.score) { return a.lookup.length - b.lookup.length; } }); op.time('findOptimalIndex'); } } // Check for join data if (options.$join) { analysis.hasJoin = true; // Loop all join operations for (joinCollectionIndex = 0; joinCollectionIndex < options.$join.length; joinCollectionIndex++) { // Loop the join collections and keep a reference to them for (joinCollectionName in options.$join[joinCollectionIndex]) { if (options.$join[joinCollectionIndex].hasOwnProperty(joinCollectionName)) { joinCollections.push(joinCollectionName); // Check if the join uses an $as operator if ('$as' in options.$join[joinCollectionIndex][joinCollectionName]) { joinCollectionReferences.push(options.$join[joinCollectionIndex][joinCollectionName].$as); } else { joinCollectionReferences.push(joinCollectionName); } } } } // Loop the join collection references and determine if the query references // any of the collections that are used in the join. If there no queries against // joined collections the find method can use a code path optimised for this. // Queries against joined collections requires the joined collections to be filtered // first and then joined so requires a little more work. for (index = 0; index < joinCollectionReferences.length; index++) { // Check if the query references any collection data that the join will create queryPath = this._queryReferencesCollection(query, joinCollectionReferences[index], ''); if (queryPath) { analysis.joinQueries[joinCollections[index]] = queryPath; analysis.queriesJoin = true; } } analysis.joinsOn = joinCollections; analysis.queriesOn = analysis.queriesOn.concat(joinCollections); } return analysis; }; /** * Checks if the passed query references this collection. * @param query * @param collection * @param path * @returns {*} * @private */ Collection.prototype._queryReferencesCollection = function (query, collection, path) { var i; for (i in query) { if (query.hasOwnProperty(i)) { // Check if this key is a reference match if (i === collection) { if (path) { path += '.'; } return path + i; } else { if (typeof(query[i]) === 'object') { // Recurse if (path) { path += '.'; } path += i; return this._queryReferencesCollection(query[i], collection, path); } } } } return false; }; /** * Returns the number of documents currently in the collection. * @returns {Number} */ Collection.prototype.count = function (query, options) { if (!query) { return this._data.length; } else { // Run query and return count return this.find(query, options).length; } }; /** * Finds sub-documents from the collection's documents. * @param match * @param path * @param subDocQuery * @param subDocOptions * @returns {*} */ Collection.prototype.findSub = function (match, path, subDocQuery, subDocOptions) { var pathHandler = new Path(path), docArr = this.find(match), docCount = docArr.length, docIndex, subDocArr, subDocCollection = this._db.collection('__FDB_temp_' + this.objectId()), subDocResults, resultObj = { parents: docCount, subDocTotal: 0, subDocs: [], pathFound: false, err: '' }; for (docIndex = 0; docIndex < docCount; docIndex++) { subDocArr = pathHandler.value(docArr[docIndex])[0]; if (subDocArr) { subDocCollection.setData(subDocArr); subDocResults = subDocCollection.find(subDocQuery, subDocOptions); if (subDocOptions.returnFirst && subDocResults.length) { return subDocResults[0]; } resultObj.subDocs.push(subDocResults); resultObj.subDocTotal += subDocResults.length; resultObj.pathFound = true; } } // Drop the sub-document collection subDocCollection.drop(); // Check if the call should not return stats, if so return only subDocs array if (subDocOptions.noStats) { return resultObj.subDocs; } if (!resultObj.pathFound) { resultObj.err = 'No objects found in the parent documents with a matching path of: ' + path; } return resultObj; }; /** * Checks that the passed document will not violate any index rules if * inserted into the collection. * @param {Object} doc The document to check indexes against. * @returns {Boolean} Either false (no violation occurred) or true if * a violation was detected. */ Collection.prototype.insertIndexViolation = function (doc) { var indexViolated, arr = this._indexByName, arrIndex, arrItem; // Check the item's primary key is not already in use if (this._primaryIndex.get(doc[this._primaryKey])) { indexViolated = this._primaryIndex; } else { // Check violations of other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arrItem = arr[arrIndex]; if (arrItem.unique()) { if (arrItem.violation(doc)) { indexViolated = arrItem; break; } } } } } return indexViolated ? indexViolated.name() : false; }; /** * Creates an index on the specified keys. * @param {Object} keys The object containing keys to index. * @param {Object} options An options object. * @returns {*} */ Collection.prototype.ensureIndex = function (keys, options) { if (this._state === 'dropped') { throw('ForerunnerDB.Collection "' + this.name() + '": Cannot operate in a dropped state!'); } this._indexByName = this._indexByName || {}; this._indexById = this._indexById || {}; var index, time = { start: new Date().getTime() }; if (options) { switch (options.type) { case 'hashed': index = new IndexHashMap(keys, options, this); break; case 'btree': index = new IndexBinaryTree(keys, options, this); break; default: // Default index = new IndexHashMap(keys, options, this); break; } } else { // Default index = new IndexHashMap(keys, options, this); } // Check the index does not already exist if (this._indexByName[index.name()]) { // Index already exists return { err: 'Index with that name already exists' }; } if (this._indexById[index.id()]) { // Index already exists return { err: 'Index with those keys already exists' }; } // Create the index index.rebuild(); // Add the index this._indexByName[index.name()] = index; this._indexById[index.id()] = index; time.end = new Date().getTime(); time.total = time.end - time.start; this._lastOp = { type: 'ensureIndex', stats: { time: time } }; return { index: index, id: index.id(), name: index.name(), state: index.state() }; }; /** * Gets an index by it's name. * @param {String} name The name of the index to retreive. * @returns {*} */ Collection.prototype.index = function (name) { if (this._indexByName) { return this._indexByName[name]; } }; /** * Gets the last reporting operation's details such as run time. * @returns {Object} */ Collection.prototype.lastOp = function () { return this._metrics.list(); }; /** * Generates a difference object that contains insert, update and remove arrays * representing the operations to execute to make this collection have the same * data as the one passed. * @param {Collection} collection The collection to diff against. * @returns {{}} */ Collection.prototype.diff = function (collection) { var diff = { insert: [], update: [], remove: [] }; var pm = this.primaryKey(), arr, arrIndex, arrItem, arrCount; // Check if the primary key index of each collection can be utilised if (pm !== collection.primaryKey()) { throw('ForerunnerDB.Collection "' + this.name() + '": Collection diffing requires that both collections have the same primary key!'); } // Use the collection primary key index to do the diff (super-fast) arr = collection._data; // Check if we have an array or another collection while (arr && !(arr instanceof Array)) { // We don't have an array, assign collection and get data collection = arr; arr = collection._data; } arrCount = arr.length; // Loop the collection's data array and check for matching items for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = arr[arrIndex]; // Check for a matching item in this collection if (this._primaryIndex.get(arrItem[pm])) { // Matching item exists, check if the data is the same if (this._primaryCrc.get(arrItem[pm]) !== collection._primaryCrc.get(arrItem[pm])) { // The documents exist in both collections but data differs, update required diff.update.push(arrItem); } } else { // The document is missing from this collection, insert required diff.insert.push(arrItem); } } // Now loop this collection's data and check for matching items arr = this._data; arrCount = arr.length; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = arr[arrIndex]; if (!collection._primaryIndex.get(arrItem[pm])) { // The document does not exist in the other collection, remove required diff.remove.push(arrItem); } } return diff; }; Collection.prototype.collateAdd = function (collection, process) { if (typeof collection === 'string') { // The collection passed is a name, not a reference so get // the reference from the name collection = this._db.collection(collection, { autoCreate: false, throwError: false }); } if (collection) { this._collate = this._collate || {}; this._collate[collection.name()] = new ReactorIO(collection, this, process); return this; } else { throw('Cannot collate from a non-existent collection!'); } }; Collection.prototype.collateRemove = function (collection) { if (typeof collection === 'object') { // We need to have the name of the collection to remove it collection = collection.name(); } if (collection) { // Drop the reactor IO chain node this._collate[collection].drop(); // Remove the collection data from the collate object delete this._collate[collection]; return this; } else { throw('No collection name passed to collateRemove() or collection not found!'); } }; Core.prototype.collection = new Overload({ /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @param {Object} options An options object. * @returns {Collection} */ 'object': function (options) { return this.$main.call(this, options); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @param {String} collectionName The name of the collection. * @returns {Collection} */ 'string': function (collectionName) { return this.$main.call(this, { name: collectionName }); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @param {String} collectionName The name of the collection. * @param {String} primaryKey Optional primary key to specify the primary key field on the collection * objects. Defaults to "_id". * @returns {Collection} */ 'string, string': function (collectionName, primaryKey) { return this.$main.call(this, { name: collectionName, primaryKey: primaryKey }); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @param {String} collectionName The name of the collection. * @param {Object} options An options object. * @returns {Collection} */ 'string, object': function (collectionName, options) { options.name = collectionName; return this.$main.call(this, options); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @param {String} collectionName The name of the collection. * @param {String} primaryKey Optional primary key to specify the primary key field on the collection * objects. Defaults to "_id". * @param {Object} options An options object. * @returns {Collection} */ 'string, string, object': function (collectionName, primaryKey, options) { options.name = collectionName; options.primaryKey = primaryKey; return this.$main.call(this, options); }, /** * The main handler method. This get's called by all the other variants and * handles the actual logic of the overloaded method. * @param {Object} options An options object. * @returns {*} */ '$main': function (options) { var name = options.name; if (name) { if (!this._collection[name]) { if (options && options.autoCreate === false) { if (options && options.throwError !== false) { throw('ForerunnerDB.Core "' + this.name() + '": Cannot get collection ' + name + ' because it does not exist and auto-create has been disabled!'); } } if (this.debug()) { console.log('Creating collection ' + name); } } this._collection[name] = this._collection[name] || new Collection(name).db(this); if (options.primaryKey !== undefined) { this._collection[name].primaryKey(options.primaryKey); } return this._collection[name]; } else { if (!options || (options && options.throwError !== false)) { throw('ForerunnerDB.Core "' + this.name() + '": Cannot get collection with undefined name!'); } } } }); /** * Determine if a collection with the passed name already exists. * @param {String} viewName The name of the collection to check for. * @returns {boolean} */ Core.prototype.collectionExists = function (viewName) { return Boolean(this._collection[viewName]); }; /** * Returns an array of collections the DB currently has. * @param {String|RegExp=} search The optional search string or regular expression to use * to match collection names against. * @returns {Array} An array of objects containing details of each collection * the database is currently managing. */ Core.prototype.collections = function (search) { var arr = [], i; if (search) { if (!(search instanceof RegExp)) { // Turn the search into a regular expression search = new RegExp(search); } } for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { if (search) { if (search.exec(i)) { arr.push({ name: i, count: this._collection[i].count() }); } } else { arr.push({ name: i, count: this._collection[i].count() }); } } } return arr; }; Shared.finishModule('Collection'); module.exports = Collection; },{"./Crc":6,"./IndexBinaryTree":9,"./IndexHashMap":10,"./KeyValueStore":11,"./Metrics":12,"./Overload":24,"./Path":26,"./ReactorIO":28,"./Shared":29}],4:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared, Core, CoreInit, Collection; Shared = _dereq_('./Shared'); var CollectionGroup = function () { this.init.apply(this, arguments); }; CollectionGroup.prototype.init = function (name) { var self = this; self._name = name; self._data = new Collection('__FDB__cg_data_' + self._name); self._collections = []; self._view = []; }; Shared.addModule('CollectionGroup', CollectionGroup); Shared.mixin(CollectionGroup.prototype, 'Mixin.Common'); Shared.mixin(CollectionGroup.prototype, 'Mixin.ChainReactor'); Shared.mixin(CollectionGroup.prototype, 'Mixin.Constants'); Shared.mixin(CollectionGroup.prototype, 'Mixin.Triggers'); Collection = _dereq_('./Collection'); Core = Shared.modules.Core; CoreInit = Shared.modules.Core.prototype.init; CollectionGroup.prototype.on = function () { this._data.on.apply(this._data, arguments); }; CollectionGroup.prototype.off = function () { this._data.off.apply(this._data, arguments); }; CollectionGroup.prototype.emit = function () { this._data.emit.apply(this._data, arguments); }; /** * Gets / sets the primary key for this collection group. * @param {String=} keyName The name of the primary key. * @returns {*} */ CollectionGroup.prototype.primaryKey = function (keyName) { if (keyName !== undefined) { this._primaryKey = keyName; return this; } return this._primaryKey; }; /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(CollectionGroup.prototype, 'state'); /** * Gets / sets the db instance the collection group belongs to. * @param {Core=} db The db instance. * @returns {*} */ Shared.synthesize(CollectionGroup.prototype, 'db'); CollectionGroup.prototype.addCollection = function (collection) { if (collection) { if (this._collections.indexOf(collection) === -1) { //var self = this; // Check for compatible primary keys if (this._collections.length) { if (this._primaryKey !== collection.primaryKey()) { throw('ForerunnerDB.CollectionGroup "' + this.name() + '": All collections in a collection group must have the same primary key!'); } } else { // Set the primary key to the first collection added this.primaryKey(collection.primaryKey()); } // Add the collection this._collections.push(collection); collection._groups = collection._groups || []; collection._groups.push(this); collection.chain(this); // Hook the collection's drop event to destroy group data collection.on('drop', function () { // Remove collection from any group associations if (collection._groups && collection._groups.length) { var groupArr = [], i; // Copy the group array because if we call removeCollection on a group // it will alter the groups array of this collection mid-loop! for (i = 0; i < collection._groups.length; i++) { groupArr.push(collection._groups[i]); } // Loop any groups we are part of and remove ourselves from them for (i = 0; i < groupArr.length; i++) { collection._groups[i].removeCollection(collection); } } delete collection._groups; }); // Add collection's data this._data.insert(collection.find()); } } return this; }; CollectionGroup.prototype.removeCollection = function (collection) { if (collection) { var collectionIndex = this._collections.indexOf(collection), groupIndex; if (collectionIndex !== -1) { collection.unChain(this); this._collections.splice(collectionIndex, 1); collection._groups = collection._groups || []; groupIndex = collection._groups.indexOf(this); if (groupIndex !== -1) { collection._groups.splice(groupIndex, 1); } collection.off('drop'); } if (this._collections.length === 0) { // Wipe the primary key delete this._primaryKey; } } return this; }; CollectionGroup.prototype._chainHandler = function (chainPacket) { //sender = chainPacket.sender; switch (chainPacket.type) { case 'setData': // Decouple the data to ensure we are working with our own copy chainPacket.data = this.decouple(chainPacket.data); // Remove old data this._data.remove(chainPacket.options.oldData); // Add new data this._data.insert(chainPacket.data); break; case 'insert': // Decouple the data to ensure we are working with our own copy chainPacket.data = this.decouple(chainPacket.data); // Add new data this._data.insert(chainPacket.data); break; case 'update': // Update data this._data.update(chainPacket.data.query, chainPacket.data.update, chainPacket.options); break; case 'remove': this._data.remove(chainPacket.data.query, chainPacket.options); break; default: break; } }; CollectionGroup.prototype.insert = function () { this._collectionsRun('insert', arguments); }; CollectionGroup.prototype.update = function () { this._collectionsRun('update', arguments); }; CollectionGroup.prototype.updateById = function () { this._collectionsRun('updateById', arguments); }; CollectionGroup.prototype.remove = function () { this._collectionsRun('remove', arguments); }; CollectionGroup.prototype._collectionsRun = function (type, args) { for (var i = 0; i < this._collections.length; i++) { this._collections[i][type].apply(this._collections[i], args); } }; CollectionGroup.prototype.find = function (query, options) { return this._data.find(query, options); }; /** * Helper method that removes a document that matches the given id. * @param {String} id The id of the document to remove. */ CollectionGroup.prototype.removeById = function (id) { // Loop the collections in this group and apply the remove for (var i = 0; i < this._collections.length; i++) { this._collections[i].removeById(id); } }; /** * Uses the passed query to generate a new collection with results * matching the query parameters. * * @param query * @param options * @returns {*} */ CollectionGroup.prototype.subset = function (query, options) { var result = this.find(query, options); return new Collection() ._subsetOf(this) .primaryKey(this._primaryKey) .setData(result); }; /** * Drops a collection group from the database. * @returns {boolean} True on success, false on failure. */ CollectionGroup.prototype.drop = function () { if (this._state !== 'dropped') { var i, collArr, viewArr; if (this._debug) { console.log('Dropping collection group ' + this._name); } this._state = 'dropped'; if (this._collections && this._collections.length) { collArr = [].concat(this._collections); for (i = 0; i < collArr.length; i++) { this.removeCollection(collArr[i]); } } if (this._view && this._view.length) { viewArr = [].concat(this._view); for (i = 0; i < viewArr.length; i++) { this._removeView(viewArr[i]); } } this.emit('drop', this); } return true; }; // Extend DB to include collection groups Core.prototype.init = function () { this._collectionGroup = {}; CoreInit.apply(this, arguments); }; Core.prototype.collectionGroup = function (collectionGroupName) { if (collectionGroupName) { this._collectionGroup[collectionGroupName] = this._collectionGroup[collectionGroupName] || new CollectionGroup(collectionGroupName).db(this); return this._collectionGroup[collectionGroupName]; } else { // Return an object of collection data return this._collectionGroup; } }; /** * Returns an array of collection groups the DB currently has. * @returns {Array} An array of objects containing details of each collection group * the database is currently managing. */ Core.prototype.collectionGroups = function () { var arr = [], i; for (i in this._collectionGroup) { if (this._collectionGroup.hasOwnProperty(i)) { arr.push({ name: i }); } } return arr; }; module.exports = CollectionGroup; },{"./Collection":3,"./Shared":29}],5:[function(_dereq_,module,exports){ /* License Copyright (c) 2015 Irrelon Software Limited http://www.irrelon.com http://www.forerunnerdb.com Please visit the license page to see latest license information: http://www.forerunnerdb.com/licensing.html */ "use strict"; var Shared, Collection, Metrics, Crc, Overload; Shared = _dereq_('./Shared'); Overload = _dereq_('./Overload'); /** * The main ForerunnerDB core object. * @constructor */ var Core = function (name) { this.init.apply(this, arguments); }; Core.prototype.init = function (name) { this._primaryKey = '_id'; this._name = name; this._collection = {}; this._debug = {}; }; Core.prototype.moduleLoaded = new Overload({ /** * Checks if a module has been loaded into the database. * @param {String} moduleName The name of the module to check for. * @returns {Boolean} True if the module is loaded, false if not. */ 'string': function (moduleName) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } return true; } return false; }, /** * Checks if a module is loaded and if so calls the passed * callback method. * @param {String} moduleName The name of the module to check for. * @param {Function} callback The callback method to call if module is loaded. */ 'string, function': function (moduleName, callback) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } callback(); } }, /** * Checks if a module is loaded and if so calls the passed * success method, otherwise calls the failure method. * @param {String} moduleName The name of the module to check for. * @param {Function} success The callback method to call if module is loaded. * @param {Function} failure The callback method to call if module not loaded. */ 'string, function, function': function (moduleName, success, failure) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { failure(); return false; } } success(); } } }); /** * Checks version against the string passed and if it matches (or partially matches) * then the callback is called. * @param {String} val The version to check against. * @param {Function} callback The callback to call if match is true. * @returns {Boolean} */ Core.prototype.version = function (val, callback) { if (val !== undefined) { if (Shared.version.indexOf(val) === 0) { if (callback) { callback(); } return true; } return false; } return Shared.version; }; // Expose moduleLoaded method to non-instantiated object ForerunnerDB Core.moduleLoaded = Core.prototype.moduleLoaded; // Expose version method to non-instantiated object ForerunnerDB Core.version = Core.prototype.version; // Provide public access to the Shared object Core.shared = Shared; Core.prototype.shared = Shared; Shared.addModule('Core', Core); Shared.mixin(Core.prototype, 'Mixin.Common'); Shared.mixin(Core.prototype, 'Mixin.ChainReactor'); Shared.mixin(Core.prototype, 'Mixin.Constants'); Collection = _dereq_('./Collection.js'); Metrics = _dereq_('./Metrics.js'); Crc = _dereq_('./Crc.js'); Core.prototype._isServer = false; /** * Gets / sets the default primary key for new collections. * @param {String=} val The name of the primary key to set. * @returns {*} */ Shared.synthesize(Core.prototype, 'primaryKey'); /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(Core.prototype, 'state'); /** * Gets / sets the name of the database. * @param {String=} val The name of the database to set. * @returns {*} */ Shared.synthesize(Core.prototype, 'name'); /** * Returns true if ForerunnerDB is running on a client browser. * @returns {boolean} */ Core.prototype.isClient = function () { return !this._isServer; }; /** * Returns true if ForerunnerDB is running on a server. * @returns {boolean} */ Core.prototype.isServer = function () { return this._isServer; }; /** * Returns a checksum of a string. * @param {String} string The string to checksum. * @return {String} The checksum generated. */ Core.prototype.crc = Crc; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a browser. */ Core.prototype.isClient = function () { return !this._isServer; }; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a server. */ Core.prototype.isServer = function () { return this._isServer; }; /** * Converts a normal javascript array of objects into a DB collection. * @param {Array} arr An array of objects. * @returns {Collection} A new collection instance with the data set to the * array passed. */ Core.prototype.arrayToCollection = function (arr) { return new Collection().setData(arr); }; /** * Registers an event listener against an event name. * @param {String} event The name of the event to listen for. * @param {Function} listener The listener method to call when * the event is fired. * @returns {*} */ Core.prototype.on = function(event, listener) { this._listeners = this._listeners || {}; this._listeners[event] = this._listeners[event] || []; this._listeners[event].push(listener); return this; }; /** * De-registers an event listener from an event name. * @param {String} event The name of the event to stop listening for. * @param {Function} listener The listener method passed to on() when * registering the event listener. * @returns {*} */ Core.prototype.off = function(event, listener) { if (event in this._listeners) { var arr = this._listeners[event], index = arr.indexOf(listener); if (index > -1) { arr.splice(index, 1); } } return this; }; /** * Emits an event by name with the given data. * @param {String} event The name of the event to emit. * @param {*=} data The data to emit with the event. * @returns {*} */ Core.prototype.emit = function(event, data) { this._listeners = this._listeners || {}; if (event in this._listeners) { var arr = this._listeners[event], arrCount = arr.length, arrIndex; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arr[arrIndex].apply(this, Array.prototype.slice.call(arguments, 1)); } } return this; }; /** * Find all documents across all collections in the database that match the passed * string or search object. * @param search String or search object. * @returns {Array} */ Core.prototype.peek = function (search) { var i, coll, arr = [], typeOfSearch = typeof search; // Loop collections for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { coll = this._collection[i]; if (typeOfSearch === 'string') { arr = arr.concat(coll.peek(search)); } else { arr = arr.concat(coll.find(search)); } } } return arr; }; /** * Find all documents across all collections in the database that match the passed * string or search object and return them in an object where each key is the name * of the collection that the document was matched in. * @param search String or search object. * @returns {object} */ Core.prototype.peekCat = function (search) { var i, coll, cat = {}, arr, typeOfSearch = typeof search; // Loop collections for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { coll = this._collection[i]; if (typeOfSearch === 'string') { arr = coll.peek(search); if (arr && arr.length) { cat[coll.name()] = arr; } } else { arr = coll.find(search); if (arr && arr.length) { cat[coll.name()] = arr; } } } } return cat; }; /** * Drops all collections in the database. * @param {Function=} callback Optional callback method. */ Core.prototype.drop = function (callback) { if (this._state !== 'dropped') { var arr = this.collections(), arrCount = arr.length, arrIndex, finishCount = 0, afterDrop = function () { finishCount++; if (finishCount === arrCount) { if (callback) { callback(); } } }; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(afterDrop); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); } return true; }; module.exports = Core; },{"./Collection.js":3,"./Crc.js":6,"./Metrics.js":12,"./Overload":24,"./Shared":29}],6:[function(_dereq_,module,exports){ "use strict"; var crcTable = (function () { var crcTable = [], c, n, k; for (n = 0; n < 256; n++) { c = n; for (k = 0; k < 8; k++) { c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); // jshint ignore:line } crcTable[n] = c; } return crcTable; }()); module.exports = function(str) { var crc = 0 ^ (-1), // jshint ignore:line i; for (i = 0; i < str.length; i++) { crc = (crc >>> 8) ^ crcTable[(crc ^ str.charCodeAt(i)) & 0xFF]; // jshint ignore:line } return (crc ^ (-1)) >>> 0; // jshint ignore:line }; },{}],7:[function(_dereq_,module,exports){ "use strict"; var Shared, Collection, Core, CoreInit; Shared = _dereq_('./Shared'); (function init () { var Document = function () { this.init.apply(this, arguments); }; Document.prototype.init = function (name) { this._name = name; this._data = {}; }; Shared.addModule('Document', Document); Shared.mixin(Document.prototype, 'Mixin.Common'); Shared.mixin(Document.prototype, 'Mixin.Events'); Shared.mixin(Document.prototype, 'Mixin.ChainReactor'); Shared.mixin(Document.prototype, 'Mixin.Constants'); Shared.mixin(Document.prototype, 'Mixin.Triggers'); Collection = _dereq_('./Collection'); Core = Shared.modules.Core; CoreInit = Shared.modules.Core.prototype.init; /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(Document.prototype, 'state'); /** * Gets / sets the db instance this class instance belongs to. * @param {Core=} db The db instance. * @returns {*} */ Shared.synthesize(Document.prototype, 'db'); /** * Gets / sets the document name. * @param {String=} val The name to assign * @returns {*} */ Shared.synthesize(Document.prototype, 'name'); Document.prototype.setData = function (data) { var i, $unset; if (data) { data = this.decouple(data); if (this._linked) { $unset = {}; // Remove keys that don't exist in the new data from the current object for (i in this._data) { if (i.substr(0, 6) !== 'jQuery' && this._data.hasOwnProperty(i)) { // Check if existing data has key if (data[i] === undefined) { // Add property name to those to unset $unset[i] = 1; } } } data.$unset = $unset; // Now update the object with new data this.updateObject(this._data, data, {}); } else { // Straight data assignment this._data = data; } } return this; }; /** * Modifies the document. This will update the document with the data held in 'update'. * * @param {Object} query The query that must be matched for a document to be * operated on. * @param {Object} update The object containing updated key/values. Any keys that * match keys on the existing document will be overwritten with this data. Any * keys that do not currently exist on the document will be added to the document. * @param {Object=} options An options object. * @returns {Array} The items that were updated. */ Document.prototype.update = function (query, update, options) { this.updateObject(this._data, update, query, options); }; /** * Internal method for document updating. * @param {Object} doc The document to update. * @param {Object} update The object with key/value pairs to update the document with. * @param {Object} query The query object that we need to match to perform an update. * @param {Object} options An options object. * @param {String} path The current recursive path. * @param {String} opType The type of update operation to perform, if none is specified * default is to set new data against matching fields. * @returns {Boolean} True if the document was updated with new / changed data or * false if it was not updated because the data was the same. * @private */ Document.prototype.updateObject = Collection.prototype.updateObject; /** * Determines if the passed key has an array positional mark (a dollar at the end * of its name). * @param {String} key The key to check. * @returns {Boolean} True if it is a positional or false if not. * @private */ Document.prototype._isPositionalKey = function (key) { return key.substr(key.length - 2, 2) === '.$'; }; /** * Updates a property on an object depending on if the collection is * currently running data-binding or not. * @param {Object} doc The object whose property is to be updated. * @param {String} prop The property to update. * @param {*} val The new value of the property. * @private */ Document.prototype._updateProperty = function (doc, prop, val) { if (this._linked) { window.jQuery.observable(doc).setProperty(prop, val); if (this.debug()) { console.log('ForerunnerDB.Document: Setting data-bound document property "' + prop + '" for collection "' + this.name() + '"'); } } else { doc[prop] = val; if (this.debug()) { console.log('ForerunnerDB.Document: Setting non-data-bound document property "' + prop + '" for collection "' + this.name() + '"'); } } }; /** * Increments a value for a property on a document by the passed number. * @param {Object} doc The document to modify. * @param {String} prop The property to modify. * @param {Number} val The amount to increment by. * @private */ Document.prototype._updateIncrement = function (doc, prop, val) { if (this._linked) { window.jQuery.observable(doc).setProperty(prop, doc[prop] + val); } else { doc[prop] += val; } }; /** * Changes the index of an item in the passed array. * @param {Array} arr The array to modify. * @param {Number} indexFrom The index to move the item from. * @param {Number} indexTo The index to move the item to. * @private */ Document.prototype._updateSpliceMove = function (arr, indexFrom, indexTo) { if (this._linked) { window.jQuery.observable(arr).move(indexFrom, indexTo); if (this.debug()) { console.log('ForerunnerDB.Document: Moving data-bound document array index from "' + indexFrom + '" to "' + indexTo + '" for collection "' + this.name() + '"'); } } else { arr.splice(indexTo, 0, arr.splice(indexFrom, 1)[0]); if (this.debug()) { console.log('ForerunnerDB.Document: Moving non-data-bound document array index from "' + indexFrom + '" to "' + indexTo + '" for collection "' + this.name() + '"'); } } }; /** * Inserts an item into the passed array at the specified index. * @param {Array} arr The array to insert into. * @param {Number} index The index to insert at. * @param {Object} doc The document to insert. * @private */ Document.prototype._updateSplicePush = function (arr, index, doc) { if (arr.length > index) { if (this._linked) { window.jQuery.observable(arr).insert(index, doc); } else { arr.splice(index, 0, doc); } } else { if (this._linked) { window.jQuery.observable(arr).insert(doc); } else { arr.push(doc); } } }; /** * Inserts an item at the end of an array. * @param {Array} arr The array to insert the item into. * @param {Object} doc The document to insert. * @private */ Document.prototype._updatePush = function (arr, doc) { if (this._linked) { window.jQuery.observable(arr).insert(doc); } else { arr.push(doc); } }; /** * Removes an item from the passed array. * @param {Array} arr The array to modify. * @param {Number} index The index of the item in the array to remove. * @private */ Document.prototype._updatePull = function (arr, index) { if (this._linked) { window.jQuery.observable(arr).remove(index); } else { arr.splice(index, 1); } }; /** * Multiplies a value for a property on a document by the passed number. * @param {Object} doc The document to modify. * @param {String} prop The property to modify. * @param {Number} val The amount to multiply by. * @private */ Document.prototype._updateMultiply = function (doc, prop, val) { if (this._linked) { window.jQuery.observable(doc).setProperty(prop, doc[prop] * val); } else { doc[prop] *= val; } }; /** * Renames a property on a document to the passed property. * @param {Object} doc The document to modify. * @param {String} prop The property to rename. * @param {Number} val The new property name. * @private */ Document.prototype._updateRename = function (doc, prop, val) { var existingVal = doc[prop]; if (this._linked) { window.jQuery.observable(doc).setProperty(val, existingVal); window.jQuery.observable(doc).removeProperty(prop); } else { doc[val] = existingVal; delete doc[prop]; } }; /** * Deletes a property on a document. * @param {Object} doc The document to modify. * @param {String} prop The property to delete. * @private */ Document.prototype._updateUnset = function (doc, prop) { if (this._linked) { window.jQuery.observable(doc).removeProperty(prop); } else { delete doc[prop]; } }; /** * Deletes a property on a document. * @param {Object} doc The document to modify. * @param {*} val The property to delete. * @return {Boolean} * @private */ Document.prototype._updatePop = function (doc, val) { var index, updated = false; if (doc.length > 0) { if (this._linked) { if (val === 1) { index = doc.length - 1; } else if (val === -1) { index = 0; } if (index > -1) { window.jQuery.observable(doc).remove(index); updated = true; } } else { if (val === 1) { doc.pop(); updated = true; } else if (val === -1) { doc.shift(); updated = true; } } } return updated; }; Document.prototype.drop = function () { if (this._state !== 'dropped') { if (this._db && this._name) { if (this._db && this._db._document && this._db._document[this._name]) { this._state = 'dropped'; delete this._db._document[this._name]; delete this._data; this.emit('drop', this); return true; } } } else { return true; } return false; }; // Extend DB to include documents Core.prototype.init = function () { CoreInit.apply(this, arguments); }; Core.prototype.document = function (documentName) { if (documentName) { this._document = this._document || {}; this._document[documentName] = this._document[documentName] || new Document(documentName).db(this); return this._document[documentName]; } else { // Return an object of document data return this._document; } }; /** * Returns an array of documents the DB currently has. * @returns {Array} An array of objects containing details of each document * the database is currently managing. */ Core.prototype.documents = function () { var arr = [], i; for (i in this._document) { if (this._document.hasOwnProperty(i)) { arr.push({ name: i }); } } return arr; }; Shared.finishModule('Document'); module.exports = Document; }()); },{"./Collection":3,"./Shared":29}],8:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared, Collection, CollectionInit, Overload; Shared = _dereq_('./Shared'); Overload = _dereq_('./Overload'); /** * The constructor. * * @constructor */ var Highchart = function (collection, options) { this.init.apply(this, arguments); }; Highchart.prototype.init = function (collection, options) { this._options = options; this._selector = window.jQuery(this._options.selector); if (!this._selector[0]) { throw('ForerunnerDB.Highchart "' + collection.name() + '": Chart target element does not exist via selector: ' + this._options.selector); } this._listeners = {}; this._collection = collection; // Setup the chart this._options.series = []; // Disable attribution on highcharts options.chartOptions = options.chartOptions || {}; options.chartOptions.credits = false; // Set the data for the chart var data, seriesObj, chartData; switch (this._options.type) { case 'pie': // Create chart from data this._selector.highcharts(this._options.chartOptions); this._chart = this._selector.highcharts(); // Generate graph data from collection data data = this._collection.find(); seriesObj = { allowPointSelect: true, cursor: 'pointer', dataLabels: { enabled: true, format: '<b>{point.name}</b>: {y} ({point.percentage:.0f}%)', style: { color: (window.Highcharts.theme && window.Highcharts.theme.contrastTextColor) || 'black' } } }; chartData = this.pieDataFromCollectionData(data, this._options.keyField, this._options.valField); window.jQuery.extend(seriesObj, this._options.seriesOptions); window.jQuery.extend(seriesObj, { name: this._options.seriesName, data: chartData }); this._chart.addSeries(seriesObj, true, true); break; case 'line': case 'area': case 'column': case 'bar': // Generate graph data from collection data chartData = this.seriesDataFromCollectionData( this._options.seriesField, this._options.keyField, this._options.valField, this._options.orderBy ); this._options.chartOptions.xAxis = chartData.xAxis; this._options.chartOptions.series = chartData.series; this._selector.highcharts(this._options.chartOptions); this._chart = this._selector.highcharts(); break; default: throw('ForerunnerDB.Highchart "' + collection.name() + '": Chart type specified is not currently supported by ForerunnerDB: ' + this._options.type); } // Hook the collection events to auto-update the chart this._hookEvents(); }; Shared.addModule('Highchart', Highchart); Collection = Shared.modules.Collection; CollectionInit = Collection.prototype.init; Shared.mixin(Highchart.prototype, 'Mixin.Events'); /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(Highchart.prototype, 'state'); /** * Generate pie-chart series data from the given collection data array. * @param data * @param keyField * @param valField * @returns {Array} */ Highchart.prototype.pieDataFromCollectionData = function (data, keyField, valField) { var graphData = [], i; for (i = 0; i < data.length; i++) { graphData.push([data[i][keyField], data[i][valField]]); } return graphData; }; /** * Generate line-chart series data from the given collection data array. * @param seriesField * @param keyField * @param valField * @param orderBy */ Highchart.prototype.seriesDataFromCollectionData = function (seriesField, keyField, valField, orderBy) { var data = this._collection.distinct(seriesField), seriesData = [], xAxis = { categories: [] }, seriesName, query, dataSearch, seriesValues, i, k; // What we WANT to output: /*series: [{ name: 'Responses', data: [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6] }]*/ // Loop keys for (i = 0; i < data.length; i++) { seriesName = data[i]; query = {}; query[seriesField] = seriesName; seriesValues = []; dataSearch = this._collection.find(query, { orderBy: orderBy }); // Loop the keySearch data and grab the value for each item for (k = 0; k < dataSearch.length; k++) { xAxis.categories.push(dataSearch[k][keyField]); seriesValues.push(dataSearch[k][valField]); } seriesData.push({ name: seriesName, data: seriesValues }); } return { xAxis: xAxis, series: seriesData }; }; /** * Hook the events the chart needs to know about from the internal collection. * @private */ Highchart.prototype._hookEvents = function () { var self = this; self._collection.on('change', function () { self._changeListener.apply(self, arguments); }); // If the collection is dropped, clean up after ourselves self._collection.on('drop', function () { self.drop.apply(self, arguments); }); }; /** * Handles changes to the collection data that the chart is reading from and then * updates the data in the chart display. * @private */ Highchart.prototype._changeListener = function () { var self = this; // Update the series data on the chart if(typeof self._collection !== 'undefined' && self._chart) { var data = self._collection.find(), i; switch (self._options.type) { case 'pie': self._chart.series[0].setData( self.pieDataFromCollectionData( data, self._options.keyField, self._options.valField ), true, true ); break; case 'bar': case 'line': case 'area': case 'column': var seriesData = self.seriesDataFromCollectionData( self._options.seriesField, self._options.keyField, self._options.valField, self._options.orderBy ); self._chart.xAxis[0].setCategories( seriesData.xAxis.categories ); for (i = 0; i < seriesData.series.length; i++) { if (self._chart.series[i]) { // Series exists, set it's data self._chart.series[i].setData( seriesData.series[i].data, true, true ); } else { // Series data does not yet exist, add a new series self._chart.addSeries( seriesData.series[i], true, true ); } } break; default: break; } } }; /** * Destroys the chart and all internal references. * @returns {Boolean} */ Highchart.prototype.drop = function () { if (this._state !== 'dropped') { this._state = 'dropped'; if (this._chart) { this._chart.destroy(); } if (this._collection) { this._collection.off('change', this._changeListener); this._collection.off('drop', this.drop); if (this._collection._highcharts) { delete this._collection._highcharts[this._options.selector]; } } delete this._chart; delete this._options; delete this._collection; this.emit('drop', this); return true; } else { return true; } }; // Extend collection with highchart init Collection.prototype.init = function () { this._highcharts = {}; CollectionInit.apply(this, arguments); }; /** * Creates a pie chart from the collection. * @type {Overload} */ Collection.prototype.pieChart = new Overload({ /** * Chart via options object. * @param {Object} options The options object. * @returns {*} */ 'object': function (options) { options.type = 'pie'; options.chartOptions = options.chartOptions || {}; options.chartOptions.chart = options.chartOptions.chart || {}; options.chartOptions.chart.type = 'pie'; if (!this._highcharts[options.selector]) { // Store new chart in charts array this._highcharts[options.selector] = new Highchart(this, options); } return this._highcharts[options.selector]; }, /** * Chart via defined params and an options object. * @param {String|jQuery} selector The element to render the chart to. * @param {String} keyField The field to use as the data key. * @param {String} valField The field to use as the data value. * @param {String} seriesName The name of the series to display on the chart. * @param {Object} options The options object. */ '*, string, string, string, ...': function (selector, keyField, valField, seriesName, options) { options = options || {}; options.selector = selector; options.keyField = keyField; options.valField = valField; options.seriesName = seriesName; // Call the main chart method this.pieChart(options); } }); /** * Creates a line chart from the collection. * @type {Overload} */ Collection.prototype.lineChart = new Overload({ /** * Chart via options object. * @param {Object} options The options object. * @returns {*} */ 'object': function (options) { options.type = 'line'; options.chartOptions = options.chartOptions || {}; options.chartOptions.chart = options.chartOptions.chart || {}; options.chartOptions.chart.type = 'line'; if (!this._highcharts[options.selector]) { // Store new chart in charts array this._highcharts[options.selector] = new Highchart(this, options); } return this._highcharts[options.selector]; }, /** * Chart via defined params and an options object. * @param {String|jQuery} selector The element to render the chart to. * @param {String} seriesField The name of the series to plot. * @param {String} keyField The field to use as the data key. * @param {String} valField The field to use as the data value. * @param {Object} options The options object. */ '*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) { options = options || {}; options.seriesField = seriesField; options.selector = selector; options.keyField = keyField; options.valField = valField; // Call the main chart method this.lineChart(options); } }); /** * Creates an area chart from the collection. * @type {Overload} */ Collection.prototype.areaChart = new Overload({ /** * Chart via options object. * @param {Object} options The options object. * @returns {*} */ 'object': function (options) { options.type = 'area'; options.chartOptions = options.chartOptions || {}; options.chartOptions.chart = options.chartOptions.chart || {}; options.chartOptions.chart.type = 'area'; if (!this._highcharts[options.selector]) { // Store new chart in charts array this._highcharts[options.selector] = new Highchart(this, options); } return this._highcharts[options.selector]; }, /** * Chart via defined params and an options object. * @param {String|jQuery} selector The element to render the chart to. * @param {String} seriesField The name of the series to plot. * @param {String} keyField The field to use as the data key. * @param {String} valField The field to use as the data value. * @param {Object} options The options object. */ '*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) { options = options || {}; options.seriesField = seriesField; options.selector = selector; options.keyField = keyField; options.valField = valField; // Call the main chart method this.areaChart(options); } }); /** * Creates a column chart from the collection. * @type {Overload} */ Collection.prototype.columnChart = new Overload({ /** * Chart via options object. * @param {Object} options The options object. * @returns {*} */ 'object': function (options) { options.type = 'column'; options.chartOptions = options.chartOptions || {}; options.chartOptions.chart = options.chartOptions.chart || {}; options.chartOptions.chart.type = 'column'; if (!this._highcharts[options.selector]) { // Store new chart in charts array this._highcharts[options.selector] = new Highchart(this, options); } return this._highcharts[options.selector]; }, /** * Chart via defined params and an options object. * @param {String|jQuery} selector The element to render the chart to. * @param {String} seriesField The name of the series to plot. * @param {String} keyField The field to use as the data key. * @param {String} valField The field to use as the data value. * @param {Object} options The options object. */ '*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) { options = options || {}; options.seriesField = seriesField; options.selector = selector; options.keyField = keyField; options.valField = valField; // Call the main chart method this.columnChart(options); } }); /** * Creates a bar chart from the collection. * @type {Overload} */ Collection.prototype.barChart = new Overload({ /** * Chart via options object. * @param {Object} options The options object. * @returns {*} */ 'object': function (options) { options.type = 'bar'; options.chartOptions = options.chartOptions || {}; options.chartOptions.chart = options.chartOptions.chart || {}; options.chartOptions.chart.type = 'bar'; if (!this._highcharts[options.selector]) { // Store new chart in charts array this._highcharts[options.selector] = new Highchart(this, options); } return this._highcharts[options.selector]; }, /** * Chart via defined params and an options object. * @param {String|jQuery} selector The element to render the chart to. * @param {String} seriesField The name of the series to plot. * @param {String} keyField The field to use as the data key. * @param {String} valField The field to use as the data value. * @param {Object} options The options object. */ '*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) { options = options || {}; options.seriesField = seriesField; options.selector = selector; options.keyField = keyField; options.valField = valField; // Call the main chart method this.barChart(options); } }); /** * Creates a stacked bar chart from the collection. * @type {Overload} */ Collection.prototype.stackedBarChart = new Overload({ /** * Chart via options object. * @param {Object} options The options object. * @returns {*} */ 'object': function (options) { options.type = 'bar'; options.chartOptions = options.chartOptions || {}; options.chartOptions.chart = options.chartOptions.chart || {}; options.chartOptions.chart.type = 'bar'; options.plotOptions = options.plotOptions || {}; options.plotOptions.series = options.plotOptions.series || {}; options.plotOptions.series.stacking = options.plotOptions.series.stacking || 'normal'; if (!this._highcharts[options.selector]) { // Store new chart in charts array this._highcharts[options.selector] = new Highchart(this, options); } return this._highcharts[options.selector]; }, /** * Chart via defined params and an options object. * @param {String|jQuery} selector The element to render the chart to. * @param {String} seriesField The name of the series to plot. * @param {String} keyField The field to use as the data key. * @param {String} valField The field to use as the data value. * @param {Object} options The options object. */ '*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) { options = options || {}; options.seriesField = seriesField; options.selector = selector; options.keyField = keyField; options.valField = valField; // Call the main chart method this.stackedBarChart(options); } }); /** * Removes a chart from the page by it's selector. * @param {String} selector The chart selector. */ Collection.prototype.dropChart = function (selector) { if (this._highcharts && this._highcharts[selector]) { this._highcharts[selector].drop(); } }; Shared.finishModule('Highchart'); module.exports = Highchart; },{"./Overload":24,"./Shared":29}],9:[function(_dereq_,module,exports){ "use strict"; /* name id rebuild state match lookup */ var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'), btree = function () {}; /** * The index class used to instantiate hash map indexes that the database can * use to speed up queries on collections and views. * @constructor */ var IndexBinaryTree = function () { this.init.apply(this, arguments); }; IndexBinaryTree.prototype.init = function (keys, options, collection) { this._btree = new (btree.create(2, this.sortAsc))(); this._size = 0; this._id = this._itemKeyHash(keys, keys); this.unique(options && options.unique ? options.unique : false); if (keys !== undefined) { this.keys(keys); } if (collection !== undefined) { this.collection(collection); } this.name(options && options.name ? options.name : this._id); }; Shared.addModule('IndexBinaryTree', IndexBinaryTree); Shared.mixin(IndexBinaryTree.prototype, 'Mixin.ChainReactor'); Shared.mixin(IndexBinaryTree.prototype, 'Mixin.Sorting'); IndexBinaryTree.prototype.id = function () { return this._id; }; IndexBinaryTree.prototype.state = function () { return this._state; }; IndexBinaryTree.prototype.size = function () { return this._size; }; Shared.synthesize(IndexBinaryTree.prototype, 'data'); Shared.synthesize(IndexBinaryTree.prototype, 'name'); Shared.synthesize(IndexBinaryTree.prototype, 'collection'); Shared.synthesize(IndexBinaryTree.prototype, 'type'); Shared.synthesize(IndexBinaryTree.prototype, 'unique'); IndexBinaryTree.prototype.keys = function (val) { if (val !== undefined) { this._keys = val; // Count the keys this._keyCount = (new Path()).parse(this._keys).length; return this; } return this._keys; }; IndexBinaryTree.prototype.rebuild = function () { // Do we have a collection? if (this._collection) { // Get sorted data var collection = this._collection.subset({}, { $decouple: false, $orderBy: this._keys }), collectionData = collection.find(), dataIndex, dataCount = collectionData.length; // Clear the index data for the index this._btree = new (btree.create(2, this.sortAsc))(); if (this._unique) { this._uniqueLookup = {}; } // Loop the collection data for (dataIndex = 0; dataIndex < dataCount; dataIndex++) { this.insert(collectionData[dataIndex]); } } this._state = { name: this._name, keys: this._keys, indexSize: this._size, built: new Date(), updated: new Date(), ok: true }; }; IndexBinaryTree.prototype.insert = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash, dataItemHash = this._itemKeyHash(dataItem, this._keys), keyArr; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); this._uniqueLookup[uniqueHash] = dataItem; } // We store multiple items that match a key inside an array // that is then stored against that key in the tree... // Check if item exists for this key already keyArr = this._btree.get(dataItemHash); // Check if the array exists if (keyArr === undefined) { // Generate an array for this key first keyArr = []; // Put the new array into the tree under the key this._btree.put(dataItemHash, keyArr); } // Push the item into the array keyArr.push(dataItem); this._size++; }; IndexBinaryTree.prototype.remove = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash, dataItemHash = this._itemKeyHash(dataItem, this._keys), keyArr, itemIndex; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); delete this._uniqueLookup[uniqueHash]; } // Try and get the array for the item hash key keyArr = this._btree.get(dataItemHash); if (keyArr !== undefined) { // The key array exits, remove the item from the key array itemIndex = keyArr.indexOf(dataItem); if (itemIndex > -1) { // Check the length of the array if (keyArr.length === 1) { // This item is the last in the array, just kill the tree entry this._btree.del(dataItemHash); } else { // Remove the item keyArr.splice(itemIndex, 1); } this._size--; } } }; IndexBinaryTree.prototype.violation = function (dataItem) { // Generate item hash var uniqueHash = this._itemHash(dataItem, this._keys); // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexBinaryTree.prototype.hashViolation = function (uniqueHash) { // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexBinaryTree.prototype.lookup = function (query) { return this._data[this._itemHash(query, this._keys)] || []; }; IndexBinaryTree.prototype.match = function (query, options) { // Check if the passed query has data in the keys our index // operates on and if so, is the query sort matching our order var pathSolver = new Path(); var indexKeyArr = pathSolver.parseArr(this._keys), queryArr = pathSolver.parseArr(query), matchedKeys = [], matchedKeyCount = 0, i; // Loop the query array and check the order of keys against the // index key array to see if this index can be used for (i = 0; i < indexKeyArr.length; i++) { if (queryArr[i] === indexKeyArr[i]) { matchedKeyCount++; matchedKeys.push(queryArr[i]); } else { // Query match failed - this is a hash map index so partial key match won't work return { matchedKeys: [], totalKeyCount: queryArr.length, score: 0 }; } } return { matchedKeys: matchedKeys, totalKeyCount: queryArr.length, score: matchedKeyCount }; //return pathSolver.countObjectPaths(this._keys, query); }; IndexBinaryTree.prototype._itemHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.value(item, pathData[k].path).join(':'); } return hash; }; IndexBinaryTree.prototype._itemKeyHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.keyValue(item, pathData[k].path); } return hash; }; IndexBinaryTree.prototype._itemHashArr = function (item, keys) { var path = new Path(), pathData, //hash = '', hashArr = [], valArr, i, k, j; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { valArr = path.value(item, pathData[k].path); for (i = 0; i < valArr.length; i++) { if (k === 0) { // Setup the initial hash array hashArr.push(valArr[i]); } else { // Loop the hash array and concat the value to it for (j = 0; j < hashArr.length; j++) { hashArr[j] = hashArr[j] + '_' + valArr[i]; } } } } return hashArr; }; Shared.finishModule('IndexBinaryTree'); module.exports = IndexBinaryTree; },{"./Path":26,"./Shared":29}],10:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'); /** * The index class used to instantiate hash map indexes that the database can * use to speed up queries on collections and views. * @constructor */ var IndexHashMap = function () { this.init.apply(this, arguments); }; IndexHashMap.prototype.init = function (keys, options, collection) { this._crossRef = {}; this._size = 0; this._id = this._itemKeyHash(keys, keys); this.data({}); this.unique(options && options.unique ? options.unique : false); if (keys !== undefined) { this.keys(keys); } if (collection !== undefined) { this.collection(collection); } this.name(options && options.name ? options.name : this._id); }; Shared.addModule('IndexHashMap', IndexHashMap); Shared.mixin(IndexHashMap.prototype, 'Mixin.ChainReactor'); IndexHashMap.prototype.id = function () { return this._id; }; IndexHashMap.prototype.state = function () { return this._state; }; IndexHashMap.prototype.size = function () { return this._size; }; Shared.synthesize(IndexHashMap.prototype, 'data'); Shared.synthesize(IndexHashMap.prototype, 'name'); Shared.synthesize(IndexHashMap.prototype, 'collection'); Shared.synthesize(IndexHashMap.prototype, 'type'); Shared.synthesize(IndexHashMap.prototype, 'unique'); IndexHashMap.prototype.keys = function (val) { if (val !== undefined) { this._keys = val; // Count the keys this._keyCount = (new Path()).parse(this._keys).length; return this; } return this._keys; }; IndexHashMap.prototype.rebuild = function () { // Do we have a collection? if (this._collection) { // Get sorted data var collection = this._collection.subset({}, { $decouple: false, $orderBy: this._keys }), collectionData = collection.find(), dataIndex, dataCount = collectionData.length; // Clear the index data for the index this._data = {}; if (this._unique) { this._uniqueLookup = {}; } // Loop the collection data for (dataIndex = 0; dataIndex < dataCount; dataIndex++) { this.insert(collectionData[dataIndex]); } } this._state = { name: this._name, keys: this._keys, indexSize: this._size, built: new Date(), updated: new Date(), ok: true }; }; IndexHashMap.prototype.insert = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash, itemHashArr, hashIndex; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); this._uniqueLookup[uniqueHash] = dataItem; } // Generate item hash itemHashArr = this._itemHashArr(dataItem, this._keys); // Get the path search results and store them for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) { this.pushToPathValue(itemHashArr[hashIndex], dataItem); } }; IndexHashMap.prototype.remove = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash, itemHashArr, hashIndex; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); delete this._uniqueLookup[uniqueHash]; } // Generate item hash itemHashArr = this._itemHashArr(dataItem, this._keys); // Get the path search results and store them for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) { this.pullFromPathValue(itemHashArr[hashIndex], dataItem); } }; IndexHashMap.prototype.violation = function (dataItem) { // Generate item hash var uniqueHash = this._itemHash(dataItem, this._keys); // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexHashMap.prototype.hashViolation = function (uniqueHash) { // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexHashMap.prototype.pushToPathValue = function (hash, obj) { var pathValArr = this._data[hash] = this._data[hash] || []; // Make sure we have not already indexed this object at this path/value if (pathValArr.indexOf(obj) === -1) { // Index the object pathValArr.push(obj); // Record the reference to this object in our index size this._size++; // Cross-reference this association for later lookup this.pushToCrossRef(obj, pathValArr); } }; IndexHashMap.prototype.pullFromPathValue = function (hash, obj) { var pathValArr = this._data[hash], indexOfObject; // Make sure we have already indexed this object at this path/value indexOfObject = pathValArr.indexOf(obj); if (indexOfObject > -1) { // Un-index the object pathValArr.splice(indexOfObject, 1); // Record the reference to this object in our index size this._size--; // Remove object cross-reference this.pullFromCrossRef(obj, pathValArr); } // Check if we should remove the path value array if (!pathValArr.length) { // Remove the array delete this._data[hash]; } }; IndexHashMap.prototype.pull = function (obj) { // Get all places the object has been used and remove them var id = obj[this._collection.primaryKey()], crossRefArr = this._crossRef[id], arrIndex, arrCount = crossRefArr.length, arrItem; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = crossRefArr[arrIndex]; // Remove item from this index lookup array this._pullFromArray(arrItem, obj); } // Record the reference to this object in our index size this._size--; // Now remove the cross-reference entry for this object delete this._crossRef[id]; }; IndexHashMap.prototype._pullFromArray = function (arr, obj) { var arrCount = arr.length; while (arrCount--) { if (arr[arrCount] === obj) { arr.splice(arrCount, 1); } } }; IndexHashMap.prototype.pushToCrossRef = function (obj, pathValArr) { var id = obj[this._collection.primaryKey()], crObj; this._crossRef[id] = this._crossRef[id] || []; // Check if the cross-reference to the pathVal array already exists crObj = this._crossRef[id]; if (crObj.indexOf(pathValArr) === -1) { // Add the cross-reference crObj.push(pathValArr); } }; IndexHashMap.prototype.pullFromCrossRef = function (obj, pathValArr) { var id = obj[this._collection.primaryKey()]; delete this._crossRef[id]; }; IndexHashMap.prototype.lookup = function (query) { return this._data[this._itemHash(query, this._keys)] || []; }; IndexHashMap.prototype.match = function (query, options) { // Check if the passed query has data in the keys our index // operates on and if so, is the query sort matching our order var pathSolver = new Path(); var indexKeyArr = pathSolver.parseArr(this._keys), queryArr = pathSolver.parseArr(query), matchedKeys = [], matchedKeyCount = 0, i; // Loop the query array and check the order of keys against the // index key array to see if this index can be used for (i = 0; i < indexKeyArr.length; i++) { if (queryArr[i] === indexKeyArr[i]) { matchedKeyCount++; matchedKeys.push(queryArr[i]); } else { // Query match failed - this is a hash map index so partial key match won't work return { matchedKeys: [], totalKeyCount: queryArr.length, score: 0 }; } } return { matchedKeys: matchedKeys, totalKeyCount: queryArr.length, score: matchedKeyCount }; //return pathSolver.countObjectPaths(this._keys, query); }; IndexHashMap.prototype._itemHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.value(item, pathData[k].path).join(':'); } return hash; }; IndexHashMap.prototype._itemKeyHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.keyValue(item, pathData[k].path); } return hash; }; IndexHashMap.prototype._itemHashArr = function (item, keys) { var path = new Path(), pathData, //hash = '', hashArr = [], valArr, i, k, j; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { valArr = path.value(item, pathData[k].path); for (i = 0; i < valArr.length; i++) { if (k === 0) { // Setup the initial hash array hashArr.push(valArr[i]); } else { // Loop the hash array and concat the value to it for (j = 0; j < hashArr.length; j++) { hashArr[j] = hashArr[j] + '_' + valArr[i]; } } } } return hashArr; }; Shared.finishModule('IndexHashMap'); module.exports = IndexHashMap; },{"./Path":26,"./Shared":29}],11:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); /** * The key value store class used when storing basic in-memory KV data, * and can be queried for quick retrieval. Mostly used for collection * primary key indexes and lookups. * @param {String=} name Optional KV store name. * @constructor */ var KeyValueStore = function (name) { this.init.apply(this, arguments); }; KeyValueStore.prototype.init = function (name) { this._name = name; this._data = {}; this._primaryKey = '_id'; }; Shared.addModule('KeyValueStore', KeyValueStore); Shared.mixin(KeyValueStore.prototype, 'Mixin.ChainReactor'); /** * Get / set the name of the key/value store. * @param {String} val The name to set. * @returns {*} */ Shared.synthesize(KeyValueStore.prototype, 'name'); /** * Get / set the primary key. * @param {String} key The key to set. * @returns {*} */ KeyValueStore.prototype.primaryKey = function (key) { if (key !== undefined) { this._primaryKey = key; return this; } return this._primaryKey; }; /** * Removes all data from the store. * @returns {*} */ KeyValueStore.prototype.truncate = function () { this._data = {}; return this; }; /** * Sets data against a key in the store. * @param {String} key The key to set data for. * @param {*} value The value to assign to the key. * @returns {*} */ KeyValueStore.prototype.set = function (key, value) { this._data[key] = value ? value : true; return this; }; /** * Gets data stored for the passed key. * @param {String} key The key to get data for. * @returns {*} */ KeyValueStore.prototype.get = function (key) { return this._data[key]; }; /** * Get / set the primary key. * @param {*} obj A lookup query, can be a string key, an array of string keys, * an object with further query clauses or a regular expression that should be * run against all keys. * @returns {*} */ KeyValueStore.prototype.lookup = function (obj) { var pKeyVal = obj[this._primaryKey], arrIndex, arrCount, lookupItem, result; if (pKeyVal instanceof Array) { // An array of primary keys, find all matches arrCount = pKeyVal.length; result = []; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { lookupItem = this._data[pKeyVal[arrIndex]]; if (lookupItem) { result.push(lookupItem); } } return result; } else if (pKeyVal instanceof RegExp) { // Create new data result = []; for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (pKeyVal.test(arrIndex)) { result.push(this._data[arrIndex]); } } } return result; } else if (typeof pKeyVal === 'object') { // The primary key clause is an object, now we have to do some // more extensive searching if (pKeyVal.$ne) { // Create new data result = []; for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (arrIndex !== pKeyVal.$ne) { result.push(this._data[arrIndex]); } } } return result; } if (pKeyVal.$in && (pKeyVal.$in instanceof Array)) { // Create new data result = []; for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (pKeyVal.$in.indexOf(arrIndex) > -1) { result.push(this._data[arrIndex]); } } } return result; } if (pKeyVal.$nin && (pKeyVal.$nin instanceof Array)) { // Create new data result = []; for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (pKeyVal.$nin.indexOf(arrIndex) === -1) { result.push(this._data[arrIndex]); } } } return result; } if (pKeyVal.$or && (pKeyVal.$or instanceof Array)) { // Create new data result = []; for (arrIndex = 0; arrIndex < pKeyVal.$or.length; arrIndex++) { result = result.concat(this.lookup(pKeyVal.$or[arrIndex])); } return result; } } else { // Key is a basic lookup from string lookupItem = this._data[pKeyVal]; if (lookupItem !== undefined) { return [lookupItem]; } else { return []; } } }; /** * Removes data for the given key from the store. * @param {String} key The key to un-set. * @returns {*} */ KeyValueStore.prototype.unSet = function (key) { delete this._data[key]; return this; }; /** * Sets data for the give key in the store only where the given key * does not already have a value in the store. * @param {String} key The key to set data for. * @param {*} value The value to assign to the key. * @returns {Boolean} True if data was set or false if data already * exists for the key. */ KeyValueStore.prototype.uniqueSet = function (key, value) { if (this._data[key] === undefined) { this._data[key] = value; return true; } return false; }; Shared.finishModule('KeyValueStore'); module.exports = KeyValueStore; },{"./Shared":29}],12:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Operation = _dereq_('./Operation'); /** * The metrics class used to store details about operations. * @constructor */ var Metrics = function () { this.init.apply(this, arguments); }; Metrics.prototype.init = function () { this._data = []; }; Shared.addModule('Metrics', Metrics); Shared.mixin(Metrics.prototype, 'Mixin.ChainReactor'); /** * Creates an operation within the metrics instance and if metrics * are currently enabled (by calling the start() method) the operation * is also stored in the metrics log. * @param {String} name The name of the operation. * @returns {Operation} */ Metrics.prototype.create = function (name) { var op = new Operation(name); if (this._enabled) { this._data.push(op); } return op; }; /** * Starts logging operations. * @returns {Metrics} */ Metrics.prototype.start = function () { this._enabled = true; return this; }; /** * Stops logging operations. * @returns {Metrics} */ Metrics.prototype.stop = function () { this._enabled = false; return this; }; /** * Clears all logged operations. * @returns {Metrics} */ Metrics.prototype.clear = function () { this._data = []; return this; }; /** * Returns an array of all logged operations. * @returns {Array} */ Metrics.prototype.list = function () { return this._data; }; Shared.finishModule('Metrics'); module.exports = Metrics; },{"./Operation":23,"./Shared":29}],13:[function(_dereq_,module,exports){ "use strict"; var CRUD = { preSetData: function () { }, postSetData: function () { } }; module.exports = CRUD; },{}],14:[function(_dereq_,module,exports){ "use strict"; // TODO: Document the methods in this mixin var ChainReactor = { chain: function (obj) { this._chain = this._chain || []; var index = this._chain.indexOf(obj); if (index === -1) { this._chain.push(obj); } }, unChain: function (obj) { if (this._chain) { var index = this._chain.indexOf(obj); if (index > -1) { this._chain.splice(index, 1); } } }, chainSend: function (type, data, options) { if (this._chain) { var arr = this._chain, count = arr.length, index; for (index = 0; index < count; index++) { arr[index].chainReceive(this, type, data, options); } } }, chainReceive: function (sender, type, data, options) { var chainPacket = { sender: sender, type: type, data: data, options: options }; // Fire our internal handler if (!this._chainHandler || (this._chainHandler && !this._chainHandler(chainPacket))) { // Propagate the message down the chain this.chainSend(chainPacket.type, chainPacket.data, chainPacket.options); } } }; module.exports = ChainReactor; },{}],15:[function(_dereq_,module,exports){ "use strict"; var idCounter = 0, Overload = _dereq_('./Overload'), Common; Common = { /** * Gets / sets data in the item store. The store can be used to set and * retrieve data against a key. Useful for adding arbitrary key/value data * to a collection / view etc and retrieving it later. * @param {String|*} key The key under which to store the passed value or * retrieve the existing stored value. * @param {*=} val Optional value. If passed will overwrite the existing value * stored against the specified key if one currently exists. * @returns {*} */ store: function (key, val) { if (key !== undefined) { if (val !== undefined) { // Store the data this._store = this._store || {}; this._store[key] = val; return this; } if (this._store) { return this._store[key]; } } return undefined; }, /** * Removes a previously stored key/value pair from the item store, set previously * by using the store() method. * @param {String|*} key The key of the key/value pair to remove; * @returns {Common} Returns this for chaining. */ unStore: function (key) { if (key !== undefined) { delete this._store[key]; } return this; }, /** * Returns a non-referenced version of the passed object / array. * @param {Object} data The object or array to return as a non-referenced version. * @param {Number=} copies Optional number of copies to produce. If specified, the return * value will be an array of decoupled objects, each distinct from the other. * @returns {*} */ decouple: function (data, copies) { if (data !== undefined) { if (!copies) { return JSON.parse(JSON.stringify(data)); } else { var i, json = JSON.stringify(data), copyArr = []; for (i = 0; i < copies; i++) { copyArr.push(JSON.parse(json)); } return copyArr; } } return undefined; }, /** * Generates a new 16-character hexadecimal unique ID or * generates a new 16-character hexadecimal ID based on * the passed string. Will always generate the same ID * for the same string. * @param {String=} str A string to generate the ID from. * @return {String} */ objectId: function (str) { var id, pow = Math.pow(10, 17); if (!str) { idCounter++; id = (idCounter + ( Math.random() * pow + Math.random() * pow + Math.random() * pow + Math.random() * pow )).toString(16); } else { var val = 0, count = str.length, i; for (i = 0; i < count; i++) { val += str.charCodeAt(i) * pow; } id = val.toString(16); } return id; }, /** * Gets / sets debug flag that can enable debug message output to the * console if required. * @param {Boolean} val The value to set debug flag to. * @return {Boolean} True if enabled, false otherwise. */ /** * Sets debug flag for a particular type that can enable debug message * output to the console if required. * @param {String} type The name of the debug type to set flag for. * @param {Boolean} val The value to set debug flag to. * @return {Boolean} True if enabled, false otherwise. */ debug: new Overload([ function () { return this._debug && this._debug.all; }, function (val) { if (val !== undefined) { if (typeof val === 'boolean') { this._debug = this._debug || {}; this._debug.all = val; this.chainSend('debug', this._debug); return this; } else { return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[val]) || (this._debug && this._debug.all); } } return this._debug && this._debug.all; }, function (type, val) { if (type !== undefined) { if (val !== undefined) { this._debug = this._debug || {}; this._debug[type] = val; this.chainSend('debug', this._debug); return this; } return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[type]); } return this._debug && this._debug.all; } ]) }; module.exports = Common; },{"./Overload":24}],16:[function(_dereq_,module,exports){ "use strict"; var Constants = { TYPE_INSERT: 0, TYPE_UPDATE: 1, TYPE_REMOVE: 2, PHASE_BEFORE: 0, PHASE_AFTER: 1 }; module.exports = Constants; },{}],17:[function(_dereq_,module,exports){ "use strict"; var Overload = _dereq_('./Overload'); var Events = { on: new Overload({ /** * Attach an event listener to the passed event. * @param {String} event The name of the event to listen for. * @param {Function} listener The method to call when the event is fired. */ 'string, function': function (event, listener) { this._listeners = this._listeners || {}; this._listeners[event] = this._listeners[event] || {}; this._listeners[event]['*'] = this._listeners[event]['*'] || []; this._listeners[event]['*'].push(listener); return this; }, /** * Attach an event listener to the passed event only if the passed * id matches the document id for the event being fired. * @param {String} event The name of the event to listen for. * @param {*} id The document id to match against. * @param {Function} listener The method to call when the event is fired. */ 'string, *, function': function (event, id, listener) { this._listeners = this._listeners || {}; this._listeners[event] = this._listeners[event] || {}; this._listeners[event][id] = this._listeners[event][id] || []; this._listeners[event][id].push(listener); return this; } }), off: new Overload({ 'string': function (event) { if (this._listeners && this._listeners[event] && event in this._listeners) { delete this._listeners[event]; } return this; }, 'string, function': function (event, listener) { var arr, index; if (typeof(listener) === 'string') { if (this._listeners && this._listeners[event] && this._listeners[event][listener]) { delete this._listeners[event][listener]; } } else { if (event in this._listeners) { arr = this._listeners[event]['*']; index = arr.indexOf(listener); if (index > -1) { arr.splice(index, 1); } } } return this; }, 'string, *, function': function (event, id, listener) { if (this._listeners && event in this._listeners && id in this.listeners[event]) { var arr = this._listeners[event][id], index = arr.indexOf(listener); if (index > -1) { arr.splice(index, 1); } } }, 'string, *': function (event, id) { if (this._listeners && event in this._listeners && id in this._listeners[event]) { // Kill all listeners for this event id delete this._listeners[event][id]; } } }), emit: function (event, data) { this._listeners = this._listeners || {}; if (event in this._listeners) { var arrIndex, arrCount; // Handle global emit if (this._listeners[event]['*']) { var arr = this._listeners[event]['*']; arrCount = arr.length; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arr[arrIndex].apply(this, Array.prototype.slice.call(arguments, 1)); } } // Handle individual emit if (data instanceof Array) { // Check if the array is an array of objects in the collection if (data[0] && data[0][this._primaryKey]) { // Loop the array and check for listeners against the primary key var listenerIdArr = this._listeners[event], listenerIdCount, listenerIdIndex; arrCount = data.length; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { if (listenerIdArr[data[arrIndex][this._primaryKey]]) { // Emit for this id listenerIdCount = listenerIdArr[data[arrIndex][this._primaryKey]].length; for (listenerIdIndex = 0; listenerIdIndex < listenerIdCount; listenerIdIndex++) { listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex].apply(this, Array.prototype.slice.call(arguments, 1)); } } } } } } return this; } }; module.exports = Events; },{"./Overload":24}],18:[function(_dereq_,module,exports){ "use strict"; var Matching = { /** * Internal method that checks a document against a test object. * @param {*} source The source object or value to test against. * @param {*} test The test object or value to test with. * @param {String=} opToApply The special operation to apply to the test such * as 'and' or an 'or' operator. * @param {Object=} options An object containing options to apply to the * operation such as limiting the fields returned etc. * @returns {Boolean} True if the test was positive, false on negative. * @private */ _match: function (source, test, opToApply, options) { // TODO: This method is quite long, break into smaller pieces var operation, applyOp, recurseVal, tmpIndex, sourceType = typeof source, testType = typeof test, matchedAll = true, opResult, substringCache, i; options = options || {}; // Check if options currently holds a root query object if (!options.$rootQuery) { // Root query not assigned, hold the root query options.$rootQuery = test; } // Check if the comparison data are both strings or numbers if ((sourceType === 'string' || sourceType === 'number') && (testType === 'string' || testType === 'number')) { // The source and test data are flat types that do not require recursive searches, // so just compare them and return the result if (sourceType === 'number') { // Number comparison if (source !== test) { matchedAll = false; } } else { // String comparison if (source.localeCompare(test)) { matchedAll = false; } } } else { for (i in test) { if (test.hasOwnProperty(i)) { // Reset operation flag operation = false; substringCache = i.substr(0, 2); // Check if the property is a comment (ignorable) if (substringCache === '//') { // Skip this property continue; } // Check if the property starts with a dollar (function) if (substringCache.indexOf('$') === 0) { // Ask the _matchOp method to handle the operation opResult = this._matchOp(i, source, test[i], options); // Check the result of the matchOp operation // If the result is -1 then no operation took place, otherwise the result // will be a boolean denoting a match (true) or no match (false) if (opResult > -1) { if (opResult) { if (opToApply === 'or') { return true; } } else { // Set the matchedAll flag to the result of the operation // because the operation did not return true matchedAll = opResult; } // Record that an operation was handled operation = true; } } // Check for regex if (!operation && test[i] instanceof RegExp) { operation = true; if (typeof(source) === 'object' && source[i] !== undefined && test[i].test(source[i])) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } if (!operation) { // Check if our query is an object if (typeof(test[i]) === 'object') { // Because test[i] is an object, source must also be an object // Check if our source data we are checking the test query against // is an object or an array if (source[i] !== undefined) { if (source[i] instanceof Array && !(test[i] instanceof Array)) { // The source data is an array, so check each item until a // match is found recurseVal = false; for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) { recurseVal = this._match(source[i][tmpIndex], test[i], applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else if (!(source[i] instanceof Array) && test[i] instanceof Array) { // The test key data is an array and the source key data is not so check // each item in the test key data to see if the source item matches one // of them. This is effectively an $in search. recurseVal = false; for (tmpIndex = 0; tmpIndex < test[i].length; tmpIndex++) { recurseVal = this._match(source[i], test[i][tmpIndex], applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else if (typeof(source) === 'object') { // Recurse down the object tree recurseVal = this._match(source[i], test[i], applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { recurseVal = this._match(undefined, test[i], applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } } else { // First check if the test match is an $exists if (test[i] && test[i].$exists !== undefined) { // Push the item through another match recurse recurseVal = this._match(undefined, test[i], applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { matchedAll = false; } } } else { // Check if the prop matches our test value if (source && source[i] === test[i]) { if (opToApply === 'or') { return true; } } else if (source && source[i] && source[i] instanceof Array && test[i] && typeof(test[i]) !== "object") { // We are looking for a value inside an array // The source data is an array, so check each item until a // match is found recurseVal = false; for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) { recurseVal = this._match(source[i][tmpIndex], test[i], applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { matchedAll = false; } } } if (opToApply === 'and' && !matchedAll) { return false; } } } } return matchedAll; }, /** * Internal method, performs a matching process against a query operator such as $gt or $nin. * @param {String} key The property name in the test that matches the operator to perform * matching against. * @param {*} source The source data to match the query against. * @param {*} test The query to match the source against. * @param {Object=} options An options object. * @returns {*} * @private */ _matchOp: function (key, source, test, options) { // Check for commands switch (key) { case '$gt': // Greater than return source > test; case '$gte': // Greater than or equal return source >= test; case '$lt': // Less than return source < test; case '$lte': // Less than or equal return source <= test; case '$exists': // Property exists return (source === undefined) !== test; case '$ne': // Not equals return source != test; // jshint ignore:line case '$or': // Match true on ANY check to pass for (var orIndex = 0; orIndex < test.length; orIndex++) { if (this._match(source, test[orIndex], 'and', options)) { return true; } } return false; case '$and': // Match true on ALL checks to pass for (var andIndex = 0; andIndex < test.length; andIndex++) { if (!this._match(source, test[andIndex], 'and', options)) { return false; } } return true; case '$in': // In // Check that the in test is an array if (test instanceof Array) { var inArr = test, inArrCount = inArr.length, inArrIndex; for (inArrIndex = 0; inArrIndex < inArrCount; inArrIndex++) { if (inArr[inArrIndex] === source) { return true; } } return false; } else { throw('ForerunnerDB.Mixin.Matching "' + this.name() + '": Cannot use an $in operator on a non-array key: ' + key); } break; case '$nin': // Not in // Check that the not-in test is an array if (test instanceof Array) { var notInArr = test, notInArrCount = notInArr.length, notInArrIndex; for (notInArrIndex = 0; notInArrIndex < notInArrCount; notInArrIndex++) { if (notInArr[notInArrIndex] === source) { return false; } } return true; } else { throw('ForerunnerDB.Mixin.Matching "' + this.name() + '": Cannot use a $nin operator on a non-array key: ' + key); } break; case '$distinct': // Ensure options holds a distinct lookup options.$rootQuery['//distinctLookup'] = options.$rootQuery['//distinctLookup'] || {}; for (var distinctProp in test) { if (test.hasOwnProperty(distinctProp)) { options.$rootQuery['//distinctLookup'][distinctProp] = options.$rootQuery['//distinctLookup'][distinctProp] || {}; // Check if the options distinct lookup has this field's value if (options.$rootQuery['//distinctLookup'][distinctProp][source[distinctProp]]) { // Value is already in use return false; } else { // Set the value in the lookup options.$rootQuery['//distinctLookup'][distinctProp][source[distinctProp]] = true; // Allow the item in the results return true; } } } break; } return -1; } }; module.exports = Matching; },{}],19:[function(_dereq_,module,exports){ "use strict"; var Sorting = { /** * Sorts the passed value a against the passed value b ascending. * @param {*} a The first value to compare. * @param {*} b The second value to compare. * @returns {*} 1 if a is sorted after b, -1 if a is sorted before b. */ sortAsc: function (a, b) { if (typeof(a) === 'string' && typeof(b) === 'string') { return a.localeCompare(b); } else { if (a > b) { return 1; } else if (a < b) { return -1; } } return 0; }, /** * Sorts the passed value a against the passed value b descending. * @param {*} a The first value to compare. * @param {*} b The second value to compare. * @returns {*} 1 if a is sorted after b, -1 if a is sorted before b. */ sortDesc: function (a, b) { if (typeof(a) === 'string' && typeof(b) === 'string') { return b.localeCompare(a); } else { if (a > b) { return -1; } else if (a < b) { return 1; } } return 0; } }; module.exports = Sorting; },{}],20:[function(_dereq_,module,exports){ "use strict"; var Triggers = { /** * Add a trigger by id. * @param {String} id The id of the trigger. This must be unique to the type and * phase of the trigger. Only one trigger may be added with this id per type and * phase. * @param {Number} type The type of operation to apply the trigger to. See * Mixin.Constants for constants to use. * @param {Number} phase The phase of an operation to fire the trigger on. See * Mixin.Constants for constants to use. * @param {Function} method The method to call when the trigger is fired. * @returns {boolean} True if the trigger was added successfully, false if not. */ addTrigger: function (id, type, phase, method) { var self = this, triggerIndex; // Check if the trigger already exists triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex === -1) { // The trigger does not exist, create it self._trigger = self._trigger || {}; self._trigger[type] = self._trigger[type] || {}; self._trigger[type][phase] = self._trigger[type][phase] || []; self._trigger[type][phase].push({ id: id, method: method }); return true; } return false; }, /** * * @param {String} id The id of the trigger to remove. * @param {Number} type The type of operation to remove the trigger from. See * Mixin.Constants for constants to use. * @param {Number} phase The phase of the operation to remove the trigger from. * See Mixin.Constants for constants to use. * @returns {boolean} True if removed successfully, false if not. */ removeTrigger: function (id, type, phase) { var self = this, triggerIndex; // Check if the trigger already exists triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // The trigger does not exist, create it self._trigger[type][phase].splice(triggerIndex, 1); } return false; }, /** * Checks if a trigger will fire based on the type and phase provided. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @returns {Boolean} True if the trigger will fire, false otherwise. */ willTrigger: function (type, phase) { return this._trigger && this._trigger[type] && this._trigger[type][phase] && this._trigger[type][phase].length; }, /** * Processes trigger actions based on the operation, type and phase. * @param {Object} operation Operation data to pass to the trigger. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @param {Object} oldDoc The document snapshot before operations are * carried out against the data. * @param {Object} newDoc The document snapshot after operations are * carried out against the data. * @returns {boolean} */ processTrigger: function (operation, type, phase, oldDoc, newDoc) { var self = this, triggerArr, triggerIndex, triggerCount, triggerItem, response; if (self._trigger && self._trigger[type] && self._trigger[type][phase]) { triggerArr = self._trigger[type][phase]; triggerCount = triggerArr.length; for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) { triggerItem = triggerArr[triggerIndex]; if (this.debug()) { var typeName, phaseName; switch (type) { case this.TYPE_INSERT: typeName = 'insert'; break; case this.TYPE_UPDATE: typeName = 'update'; break; case this.TYPE_REMOVE: typeName = 'remove'; break; default: typeName = ''; break; } switch (phase) { case this.PHASE_BEFORE: phaseName = 'before'; break; case this.PHASE_AFTER: phaseName = 'after'; break; default: phaseName = ''; break; } //console.log('Triggers: Processing trigger "' + id + '" for ' + typeName + ' in phase "' + phaseName + '"'); } // Run the trigger's method and store the response response = triggerItem.method.call(self, operation, oldDoc, newDoc); // Check the response for a non-expected result (anything other than // undefined, true or false is considered a throwable error) if (response === false) { // The trigger wants us to cancel operations return false; } if (response !== undefined && response !== true && response !== false) { // Trigger responded with error, throw the error throw('ForerunnerDB.Mixin.Triggers: Trigger error: ' + response); } } // Triggers all ran without issue, return a success (true) return true; } }, /** * Returns the index of a trigger by id based on type and phase. * @param {String} id The id of the trigger to find the index of. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @returns {number} * @private */ _triggerIndexOf: function (id, type, phase) { var self = this, triggerArr, triggerCount, triggerIndex; if (self._trigger && self._trigger[type] && self._trigger[type][phase]) { triggerArr = self._trigger[type][phase]; triggerCount = triggerArr.length; for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) { if (triggerArr[triggerIndex].id === id) { return triggerIndex; } } } return -1; } }; module.exports = Triggers; },{}],21:[function(_dereq_,module,exports){ "use strict"; // Grab the view class var Shared, Core, OldView, OldViewInit; Shared = _dereq_('./Shared'); Core = Shared.modules.Core; OldView = Shared.modules.OldView; OldViewInit = OldView.prototype.init; OldView.prototype.init = function () { var self = this; this._binds = []; this._renderStart = 0; this._renderEnd = 0; this._deferQueue = { insert: [], update: [], remove: [], upsert: [], _bindInsert: [], _bindUpdate: [], _bindRemove: [], _bindUpsert: [] }; this._deferThreshold = { insert: 100, update: 100, remove: 100, upsert: 100, _bindInsert: 100, _bindUpdate: 100, _bindRemove: 100, _bindUpsert: 100 }; this._deferTime = { insert: 100, update: 1, remove: 1, upsert: 1, _bindInsert: 100, _bindUpdate: 1, _bindRemove: 1, _bindUpsert: 1 }; OldViewInit.apply(this, arguments); // Hook view events to update binds this.on('insert', function (successArr, failArr) { self._bindEvent('insert', successArr, failArr); }); this.on('update', function (successArr, failArr) { self._bindEvent('update', successArr, failArr); }); this.on('remove', function (successArr, failArr) { self._bindEvent('remove', successArr, failArr); }); this.on('change', self._bindChange); }; /** * Binds a selector to the insert, update and delete events of a particular * view and keeps the selector in sync so that updates are reflected on the * web page in real-time. * * @param {String} selector The jQuery selector string to get target elements. * @param {Object} options The options object. */ OldView.prototype.bind = function (selector, options) { if (options && options.template) { this._binds[selector] = options; } else { throw('ForerunnerDB.OldView "' + this.name() + '": Cannot bind data to element, missing options information!'); } return this; }; /** * Un-binds a selector from the view changes. * @param {String} selector The jQuery selector string to identify the bind to remove. * @returns {Collection} */ OldView.prototype.unBind = function (selector) { delete this._binds[selector]; return this; }; /** * Returns true if the selector is bound to the view. * @param {String} selector The jQuery selector string to identify the bind to check for. * @returns {boolean} */ OldView.prototype.isBound = function (selector) { return Boolean(this._binds[selector]); }; /** * Sorts items in the DOM based on the bind settings and the passed item array. * @param {String} selector The jQuery selector of the bind container. * @param {Array} itemArr The array of items used to determine the order the DOM * elements should be in based on the order they are in, in the array. */ OldView.prototype.bindSortDom = function (selector, itemArr) { var container = window.jQuery(selector), arrIndex, arrItem, domItem; if (this.debug()) { console.log('ForerunnerDB.OldView.Bind: Sorting data in DOM...', itemArr); } for (arrIndex = 0; arrIndex < itemArr.length; arrIndex++) { arrItem = itemArr[arrIndex]; // Now we've done our inserts into the DOM, let's ensure // they are still ordered correctly domItem = container.find('#' + arrItem[this._primaryKey]); if (domItem.length) { if (arrIndex === 0) { if (this.debug()) { console.log('ForerunnerDB.OldView.Bind: Sort, moving to index 0...', domItem); } container.prepend(domItem); } else { if (this.debug()) { console.log('ForerunnerDB.OldView.Bind: Sort, moving to index ' + arrIndex + '...', domItem); } domItem.insertAfter(container.children(':eq(' + (arrIndex - 1) + ')')); } } else { if (this.debug()) { console.log('ForerunnerDB.OldView.Bind: Warning, element for array item not found!', arrItem); } } } }; OldView.prototype.bindRefresh = function (obj) { var binds = this._binds, bindKey, bind; if (!obj) { // Grab current data obj = { data: this.find() }; } for (bindKey in binds) { if (binds.hasOwnProperty(bindKey)) { bind = binds[bindKey]; if (this.debug()) { console.log('ForerunnerDB.OldView.Bind: Sorting DOM...'); } this.bindSortDom(bindKey, obj.data); if (bind.afterOperation) { bind.afterOperation(); } if (bind.refresh) { bind.refresh(); } } } }; /** * Renders a bind view data to the DOM. * @param {String} bindSelector The jQuery selector string to use to identify * the bind target. Must match the selector used when defining the original bind. * @param {Function=} domHandler If specified, this handler method will be called * with the final HTML for the view instead of the DB handling the DOM insertion. */ OldView.prototype.bindRender = function (bindSelector, domHandler) { // Check the bind exists var bind = this._binds[bindSelector], domTarget = window.jQuery(bindSelector), allData, dataItem, itemHtml, finalHtml = window.jQuery('<ul></ul>'), bindCallback, i; if (bind) { allData = this._data.find(); bindCallback = function (itemHtml) { finalHtml.append(itemHtml); }; // Loop all items and add them to the screen for (i = 0; i < allData.length; i++) { dataItem = allData[i]; itemHtml = bind.template(dataItem, bindCallback); } if (!domHandler) { domTarget.append(finalHtml.html()); } else { domHandler(bindSelector, finalHtml.html()); } } }; OldView.prototype.processQueue = function (type, callback) { var queue = this._deferQueue[type], deferThreshold = this._deferThreshold[type], deferTime = this._deferTime[type]; if (queue.length) { var self = this, dataArr; // Process items up to the threshold if (queue.length) { if (queue.length > deferThreshold) { // Grab items up to the threshold value dataArr = queue.splice(0, deferThreshold); } else { // Grab all the remaining items dataArr = queue.splice(0, queue.length); } this._bindEvent(type, dataArr, []); } // Queue another process setTimeout(function () { self.processQueue(type, callback); }, deferTime); } else { if (callback) { callback(); } this.emit('bindQueueComplete'); } }; OldView.prototype._bindEvent = function (type, successArr, failArr) { /*var queue = this._deferQueue[type], deferThreshold = this._deferThreshold[type], deferTime = this._deferTime[type];*/ var binds = this._binds, unfilteredDataSet = this.find({}), filteredDataSet, bindKey; // Check if the number of inserts is greater than the defer threshold /*if (successArr && successArr.length > deferThreshold) { // Break up upsert into blocks this._deferQueue[type] = queue.concat(successArr); // Fire off the insert queue handler this.processQueue(type); return; } else {*/ for (bindKey in binds) { if (binds.hasOwnProperty(bindKey)) { if (binds[bindKey].reduce) { filteredDataSet = this.find(binds[bindKey].reduce.query, binds[bindKey].reduce.options); } else { filteredDataSet = unfilteredDataSet; } switch (type) { case 'insert': this._bindInsert(bindKey, binds[bindKey], successArr, failArr, filteredDataSet); break; case 'update': this._bindUpdate(bindKey, binds[bindKey], successArr, failArr, filteredDataSet); break; case 'remove': this._bindRemove(bindKey, binds[bindKey], successArr, failArr, filteredDataSet); break; } } } //} }; OldView.prototype._bindChange = function (newDataArr) { if (this.debug()) { console.log('ForerunnerDB.OldView.Bind: Bind data change, refreshing bind...', newDataArr); } this.bindRefresh(newDataArr); }; OldView.prototype._bindInsert = function (selector, options, successArr, failArr, all) { var container = window.jQuery(selector), itemElem, itemHtml, makeCallback, i; makeCallback = function (itemElem, insertedItem, failArr, all) { return function (itemHtml) { // Check if there is custom DOM insert method if (options.insert) { options.insert(itemHtml, insertedItem, failArr, all); } else { // Handle the insert automatically // Add the item to the container if (options.prependInsert) { container.prepend(itemHtml); } else { container.append(itemHtml); } } if (options.afterInsert) { options.afterInsert(itemHtml, insertedItem, failArr, all); } }; }; // Loop the inserted items for (i = 0; i < successArr.length; i++) { // Check for existing item in the container itemElem = container.find('#' + successArr[i][this._primaryKey]); if (!itemElem.length) { itemHtml = options.template(successArr[i], makeCallback(itemElem, successArr[i], failArr, all)); } } }; OldView.prototype._bindUpdate = function (selector, options, successArr, failArr, all) { var container = window.jQuery(selector), itemElem, makeCallback, i; makeCallback = function (itemElem, itemData) { return function (itemHtml) { // Check if there is custom DOM insert method if (options.update) { options.update(itemHtml, itemData, all, itemElem.length ? 'update' : 'append'); } else { if (itemElem.length) { // An existing item is in the container, replace it with the // new rendered item from the updated data itemElem.replaceWith(itemHtml); } else { // The item element does not already exist, append it if (options.prependUpdate) { container.prepend(itemHtml); } else { container.append(itemHtml); } } } if (options.afterUpdate) { options.afterUpdate(itemHtml, itemData, all); } }; }; // Loop the updated items for (i = 0; i < successArr.length; i++) { // Check for existing item in the container itemElem = container.find('#' + successArr[i][this._primaryKey]); options.template(successArr[i], makeCallback(itemElem, successArr[i])); } }; OldView.prototype._bindRemove = function (selector, options, successArr, failArr, all) { var container = window.jQuery(selector), itemElem, makeCallback, i; makeCallback = function (itemElem, data, all) { return function () { if (options.remove) { options.remove(itemElem, data, all); } else { itemElem.remove(); if (options.afterRemove) { options.afterRemove(itemElem, data, all); } } }; }; // Loop the removed items for (i = 0; i < successArr.length; i++) { // Check for existing item in the container itemElem = container.find('#' + successArr[i][this._primaryKey]); if (itemElem.length) { if (options.beforeRemove) { options.beforeRemove(itemElem, successArr[i], all, makeCallback(itemElem, successArr[i], all)); } else { if (options.remove) { options.remove(itemElem, successArr[i], all); } else { itemElem.remove(); if (options.afterRemove) { options.afterRemove(itemElem, successArr[i], all); } } } } } }; },{"./Shared":29}],22:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared, Core, CollectionGroup, Collection, CollectionInit, CollectionGroupInit, CoreInit; Shared = _dereq_('./Shared'); /** * The view constructor. * @param viewName * @constructor */ var OldView = function (viewName) { this.init.apply(this, arguments); }; OldView.prototype.init = function (viewName) { var self = this; this._name = viewName; this._listeners = {}; this._query = { query: {}, options: {} }; // Register listeners for the CRUD events this._onFromSetData = function () { self._onSetData.apply(self, arguments); }; this._onFromInsert = function () { self._onInsert.apply(self, arguments); }; this._onFromUpdate = function () { self._onUpdate.apply(self, arguments); }; this._onFromRemove = function () { self._onRemove.apply(self, arguments); }; this._onFromChange = function () { if (self.debug()) { console.log('ForerunnerDB.OldView: Received change'); } self._onChange.apply(self, arguments); }; }; Shared.addModule('OldView', OldView); CollectionGroup = _dereq_('./CollectionGroup'); Collection = _dereq_('./Collection'); CollectionInit = Collection.prototype.init; CollectionGroupInit = CollectionGroup.prototype.init; Core = Shared.modules.Core; CoreInit = Core.prototype.init; Shared.mixin(OldView.prototype, 'Mixin.Events'); /** * Drops a view and all it's stored data from the database. * @returns {boolean} True on success, false on failure. */ OldView.prototype.drop = function () { if ((this._db || this._from) && this._name) { if (this.debug()) { console.log('ForerunnerDB.OldView: Dropping view ' + this._name); } this._state = 'dropped'; this.emit('drop', this); if (this._db && this._db._oldViews) { delete this._db._oldViews[this._name]; } if (this._from && this._from._oldViews) { delete this._from._oldViews[this._name]; } return true; } return false; }; OldView.prototype.debug = function () { // TODO: Make this function work return false; }; /** * Gets / sets the DB the view is bound against. Automatically set * when the db.oldView(viewName) method is called. * @param db * @returns {*} */ OldView.prototype.db = function (db) { if (db !== undefined) { this._db = db; return this; } return this._db; }; /** * Gets / sets the collection that the view derives it's data from. * @param {*} collection A collection instance or the name of a collection * to use as the data set to derive view data from. * @returns {*} */ OldView.prototype.from = function (collection) { if (collection !== undefined) { // Check if this is a collection name or a collection instance if (typeof(collection) === 'string') { if (this._db.collectionExists(collection)) { collection = this._db.collection(collection); } else { throw('ForerunnerDB.OldView "' + this.name() + '": Invalid collection in view.from() call.'); } } // Check if the existing from matches the passed one if (this._from !== collection) { // Check if we already have a collection assigned if (this._from) { // Remove ourselves from the collection view lookup this.removeFrom(); } this.addFrom(collection); } return this; } return this._from; }; OldView.prototype.addFrom = function (collection) { //var self = this; this._from = collection; if (this._from) { this._from.on('setData', this._onFromSetData); //this._from.on('insert', this._onFromInsert); //this._from.on('update', this._onFromUpdate); //this._from.on('remove', this._onFromRemove); this._from.on('change', this._onFromChange); // Add this view to the collection's view lookup this._from._addOldView(this); this._primaryKey = this._from._primaryKey; this.refresh(); return this; } else { throw('ForerunnerDB.OldView "' + this.name() + '": Cannot determine collection type in view.from()'); } }; OldView.prototype.removeFrom = function () { // Unsubscribe from events on this "from" this._from.off('setData', this._onFromSetData); //this._from.off('insert', this._onFromInsert); //this._from.off('update', this._onFromUpdate); //this._from.off('remove', this._onFromRemove); this._from.off('change', this._onFromChange); this._from._removeOldView(this); }; /** * Gets the primary key for this view from the assigned collection. * @returns {String} */ OldView.prototype.primaryKey = function () { if (this._from) { return this._from.primaryKey(); } return undefined; }; /** * Gets / sets the query that the view uses to build it's data set. * @param {Object=} query * @param {Boolean=} options An options object. * @param {Boolean=} refresh Whether to refresh the view data after * this operation. Defaults to true. * @returns {*} */ OldView.prototype.queryData = function (query, options, refresh) { if (query !== undefined) { this._query.query = query; } if (options !== undefined) { this._query.options = options; } if (query !== undefined || options !== undefined) { if (refresh === undefined || refresh === true) { this.refresh(); } return this; } return this._query; }; /** * Add data to the existing query. * @param {Object} obj The data whose keys will be added to the existing * query object. * @param {Boolean} overwrite Whether or not to overwrite data that already * exists in the query object. Defaults to true. * @param {Boolean=} refresh Whether or not to refresh the view data set * once the operation is complete. Defaults to true. */ OldView.prototype.queryAdd = function (obj, overwrite, refresh) { var query = this._query.query, i; if (obj !== undefined) { // Loop object properties and add to existing query for (i in obj) { if (obj.hasOwnProperty(i)) { if (query[i] === undefined || (query[i] !== undefined && overwrite)) { query[i] = obj[i]; } } } } if (refresh === undefined || refresh === true) { this.refresh(); } }; /** * Remove data from the existing query. * @param {Object} obj The data whose keys will be removed from the existing * query object. * @param {Boolean=} refresh Whether or not to refresh the view data set * once the operation is complete. Defaults to true. */ OldView.prototype.queryRemove = function (obj, refresh) { var query = this._query.query, i; if (obj !== undefined) { // Loop object properties and add to existing query for (i in obj) { if (obj.hasOwnProperty(i)) { delete query[i]; } } } if (refresh === undefined || refresh === true) { this.refresh(); } }; /** * Gets / sets the query being used to generate the view data. * @param {Object=} query The query to set. * @param {Boolean=} refresh Whether to refresh the view data after * this operation. Defaults to true. * @returns {*} */ OldView.prototype.query = function (query, refresh) { if (query !== undefined) { this._query.query = query; if (refresh === undefined || refresh === true) { this.refresh(); } return this; } return this._query.query; }; /** * Gets / sets the query options used when applying sorting etc to the * view data set. * @param {Object=} options An options object. * @param {Boolean=} refresh Whether to refresh the view data after * this operation. Defaults to true. * @returns {*} */ OldView.prototype.queryOptions = function (options, refresh) { if (options !== undefined) { this._query.options = options; if (refresh === undefined || refresh === true) { this.refresh(); } return this; } return this._query.options; }; /** * Refreshes the view data and diffs between previous and new data to * determine if any events need to be triggered or DOM binds updated. */ OldView.prototype.refresh = function (force) { if (this._from) { // Take a copy of the data before updating it, we will use this to // "diff" between the old and new data and handle DOM bind updates var oldData = this._data, oldDataArr, oldDataItem, newData, newDataArr, query, primaryKey, dataItem, inserted = [], updated = [], removed = [], operated = false, i; if (this.debug()) { console.log('ForerunnerDB.OldView: Refreshing view ' + this._name); console.log('ForerunnerDB.OldView: Existing data: ' + (typeof(this._data) !== "undefined")); if (typeof(this._data) !== "undefined") { console.log('ForerunnerDB.OldView: Current data rows: ' + this._data.find().length); } //console.log(OldView.prototype.refresh.caller); } // Query the collection and update the data if (this._query) { if (this.debug()) { console.log('ForerunnerDB.OldView: View has query and options, getting subset...'); } // Run query against collection //console.log('refresh with query and options', this._query.options); this._data = this._from.subset(this._query.query, this._query.options); //console.log(this._data); } else { // No query, return whole collection if (this._query.options) { if (this.debug()) { console.log('ForerunnerDB.OldView: View has options, getting subset...'); } this._data = this._from.subset({}, this._query.options); } else { if (this.debug()) { console.log('ForerunnerDB.OldView: View has no query or options, getting subset...'); } this._data = this._from.subset({}); } } // Check if there was old data if (!force && oldData) { if (this.debug()) { console.log('ForerunnerDB.OldView: Refresh not forced, old data detected...'); } // Now determine the difference newData = this._data; if (oldData.subsetOf() === newData.subsetOf()) { if (this.debug()) { console.log('ForerunnerDB.OldView: Old and new data are from same collection...'); } newDataArr = newData.find(); oldDataArr = oldData.find(); primaryKey = newData._primaryKey; // The old data and new data were derived from the same parent collection // so scan the data to determine changes for (i = 0; i < newDataArr.length; i++) { dataItem = newDataArr[i]; query = {}; query[primaryKey] = dataItem[primaryKey]; // Check if this item exists in the old data oldDataItem = oldData.find(query)[0]; if (!oldDataItem) { // New item detected inserted.push(dataItem); } else { // Check if an update has occurred if (JSON.stringify(oldDataItem) !== JSON.stringify(dataItem)) { // Updated / already included item detected updated.push(dataItem); } } } // Now loop the old data and check if any records were removed for (i = 0; i < oldDataArr.length; i++) { dataItem = oldDataArr[i]; query = {}; query[primaryKey] = dataItem[primaryKey]; // Check if this item exists in the old data if (!newData.find(query)[0]) { // Removed item detected removed.push(dataItem); } } if (this.debug()) { console.log('ForerunnerDB.OldView: Removed ' + removed.length + ' rows'); console.log('ForerunnerDB.OldView: Inserted ' + inserted.length + ' rows'); console.log('ForerunnerDB.OldView: Updated ' + updated.length + ' rows'); } // Now we have a diff of the two data sets, we need to get the DOM updated if (inserted.length) { this._onInsert(inserted, []); operated = true; } if (updated.length) { this._onUpdate(updated, []); operated = true; } if (removed.length) { this._onRemove(removed, []); operated = true; } } else { // The previous data and the new data are derived from different collections // and can therefore not be compared, all data is therefore effectively "new" // so first perform a remove of all existing data then do an insert on all new data if (this.debug()) { console.log('ForerunnerDB.OldView: Old and new data are from different collections...'); } removed = oldData.find(); if (removed.length) { this._onRemove(removed); operated = true; } inserted = newData.find(); if (inserted.length) { this._onInsert(inserted); operated = true; } } } else { // Force an update as if the view never got created by padding all elements // to the insert if (this.debug()) { console.log('ForerunnerDB.OldView: Forcing data update', newDataArr); } this._data = this._from.subset(this._query.query, this._query.options); newDataArr = this._data.find(); if (this.debug()) { console.log('ForerunnerDB.OldView: Emitting change event with data', newDataArr); } this._onInsert(newDataArr, []); } if (this.debug()) { console.log('ForerunnerDB.OldView: Emitting change'); } this.emit('change'); } return this; }; /** * Returns the number of documents currently in the view. * @returns {Number} */ OldView.prototype.count = function () { return this._data && this._data._data ? this._data._data.length : 0; }; /** * Queries the view data. See Collection.find() for more information. * @returns {*} */ OldView.prototype.find = function () { if (this._data) { if (this.debug()) { console.log('ForerunnerDB.OldView: Finding data in view collection...', this._data); } return this._data.find.apply(this._data, arguments); } else { return []; } }; /** * Inserts into view data via the view collection. See Collection.insert() for more information. * @returns {*} */ OldView.prototype.insert = function () { if (this._from) { // Pass the args through to the from object return this._from.insert.apply(this._from, arguments); } else { return []; } }; /** * Updates into view data via the view collection. See Collection.update() for more information. * @returns {*} */ OldView.prototype.update = function () { if (this._from) { // Pass the args through to the from object return this._from.update.apply(this._from, arguments); } else { return []; } }; /** * Removed from view data via the view collection. See Collection.remove() for more information. * @returns {*} */ OldView.prototype.remove = function () { if (this._from) { // Pass the args through to the from object return this._from.remove.apply(this._from, arguments); } else { return []; } }; OldView.prototype._onSetData = function (newDataArr, oldDataArr) { this.emit('remove', oldDataArr, []); this.emit('insert', newDataArr, []); //this.refresh(); }; OldView.prototype._onInsert = function (successArr, failArr) { this.emit('insert', successArr, failArr); //this.refresh(); }; OldView.prototype._onUpdate = function (successArr, failArr) { this.emit('update', successArr, failArr); //this.refresh(); }; OldView.prototype._onRemove = function (successArr, failArr) { this.emit('remove', successArr, failArr); //this.refresh(); }; OldView.prototype._onChange = function () { if (this.debug()) { console.log('ForerunnerDB.OldView: Refreshing data'); } this.refresh(); }; // Extend collection with view init Collection.prototype.init = function () { this._oldViews = []; CollectionInit.apply(this, arguments); }; /** * Adds a view to the internal view lookup. * @param {View} view The view to add. * @returns {Collection} * @private */ Collection.prototype._addOldView = function (view) { if (view !== undefined) { this._oldViews[view._name] = view; } return this; }; /** * Removes a view from the internal view lookup. * @param {View} view The view to remove. * @returns {Collection} * @private */ Collection.prototype._removeOldView = function (view) { if (view !== undefined) { delete this._oldViews[view._name]; } return this; }; // Extend collection with view init CollectionGroup.prototype.init = function () { this._oldViews = []; CollectionGroupInit.apply(this, arguments); }; /** * Adds a view to the internal view lookup. * @param {View} view The view to add. * @returns {Collection} * @private */ CollectionGroup.prototype._addOldView = function (view) { if (view !== undefined) { this._oldViews[view._name] = view; } return this; }; /** * Removes a view from the internal view lookup. * @param {View} view The view to remove. * @returns {Collection} * @private */ CollectionGroup.prototype._removeOldView = function (view) { if (view !== undefined) { delete this._oldViews[view._name]; } return this; }; // Extend DB with views init Core.prototype.init = function () { this._oldViews = {}; CoreInit.apply(this, arguments); }; /** * Gets a view by it's name. * @param {String} viewName The name of the view to retrieve. * @returns {*} */ Core.prototype.oldView = function (viewName) { if (!this._oldViews[viewName]) { if (this.debug()) { console.log('ForerunnerDB.OldView: Creating view ' + viewName); } } this._oldViews[viewName] = this._oldViews[viewName] || new OldView(viewName).db(this); return this._oldViews[viewName]; }; /** * Determine if a view with the passed name already exists. * @param {String} viewName The name of the view to check for. * @returns {boolean} */ Core.prototype.oldViewExists = function (viewName) { return Boolean(this._oldViews[viewName]); }; /** * Returns an array of views the DB currently has. * @returns {Array} An array of objects containing details of each view * the database is currently managing. */ Core.prototype.oldViews = function () { var arr = [], i; for (i in this._oldViews) { if (this._oldViews.hasOwnProperty(i)) { arr.push({ name: i, count: this._oldViews[i].count() }); } } return arr; }; Shared.finishModule('OldView'); module.exports = OldView; },{"./Collection":3,"./CollectionGroup":4,"./Shared":29}],23:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'); /** * The operation class, used to store details about an operation being * performed by the database. * @param {String} name The name of the operation. * @constructor */ var Operation = function (name) { this.pathSolver = new Path(); this.counter = 0; this.init.apply(this, arguments); }; Operation.prototype.init = function (name) { this._data = { operation: name, // The name of the operation executed such as "find", "update" etc index: { potential: [], // Indexes that could have potentially been used used: false // The index that was picked to use }, steps: [], // The steps taken to generate the query results, time: { startMs: 0, stopMs: 0, totalMs: 0, process: {} }, flag: {}, // An object with flags that denote certain execution paths log: [] // Any extra data that might be useful such as warnings or helpful hints }; }; Shared.addModule('Operation', Operation); Shared.mixin(Operation.prototype, 'Mixin.ChainReactor'); /** * Starts the operation timer. */ Operation.prototype.start = function () { this._data.time.startMs = new Date().getTime(); }; /** * Adds an item to the operation log. * @param {String} event The item to log. * @returns {*} */ Operation.prototype.log = function (event) { if (event) { var lastLogTime = this._log.length > 0 ? this._data.log[this._data.log.length - 1].time : 0, logObj = { event: event, time: new Date().getTime(), delta: 0 }; this._data.log.push(logObj); if (lastLogTime) { logObj.delta = logObj.time - lastLogTime; } return this; } return this._data.log; }; /** * Called when starting and ending a timed operation, used to time * internal calls within an operation's execution. * @param {String} section An operation name. * @returns {*} */ Operation.prototype.time = function (section) { if (section !== undefined) { var process = this._data.time.process, processObj = process[section] = process[section] || {}; if (!processObj.startMs) { // Timer started processObj.startMs = new Date().getTime(); processObj.stepObj = { name: section }; this._data.steps.push(processObj.stepObj); } else { processObj.stopMs = new Date().getTime(); processObj.totalMs = processObj.stopMs - processObj.startMs; processObj.stepObj.totalMs = processObj.totalMs; delete processObj.stepObj; } return this; } return this._data.time; }; /** * Used to set key/value flags during operation execution. * @param {String} key * @param {String} val * @returns {*} */ Operation.prototype.flag = function (key, val) { if (key !== undefined && val !== undefined) { this._data.flag[key] = val; } else if (key !== undefined) { return this._data.flag[key]; } else { return this._data.flag; } }; Operation.prototype.data = function (path, val, noTime) { if (val !== undefined) { // Assign value to object path this.pathSolver.set(this._data, path, val); return this; } return this.pathSolver.get(this._data, path); }; Operation.prototype.pushData = function (path, val, noTime) { // Assign value to object path this.pathSolver.push(this._data, path, val); }; /** * Stops the operation timer. */ Operation.prototype.stop = function () { this._data.time.stopMs = new Date().getTime(); this._data.time.totalMs = this._data.time.stopMs - this._data.time.startMs; }; Shared.finishModule('Operation'); module.exports = Operation; },{"./Path":26,"./Shared":29}],24:[function(_dereq_,module,exports){ "use strict"; /** * Allows a method to accept overloaded calls with different parameters controlling * which passed overload function is called. * @param {Object} def * @returns {Function} * @constructor */ var Overload = function (def) { if (def) { var self = this, index, count, tmpDef, defNewKey, sigIndex, signatures; if (!(def instanceof Array)) { tmpDef = {}; // Def is an object, make sure all prop names are devoid of spaces for (index in def) { if (def.hasOwnProperty(index)) { defNewKey = index.replace(/ /g, ''); // Check if the definition array has a * string in it if (defNewKey.indexOf('*') === -1) { // No * found tmpDef[defNewKey] = def[index]; } else { // A * was found, generate the different signatures that this // definition could represent signatures = this.generateSignaturePermutations(defNewKey); for (sigIndex = 0; sigIndex < signatures.length; sigIndex++) { if (!tmpDef[signatures[sigIndex]]) { tmpDef[signatures[sigIndex]] = def[index]; } } } } } def = tmpDef; } return function () { var arr = [], lookup, type; // Check if we are being passed a key/function object or an array of functions if (def instanceof Array) { // We were passed an array of functions count = def.length; for (index = 0; index < count; index++) { if (def[index].length === arguments.length) { return self.callExtend(this, '$main', def, def[index], arguments); } } } else { // Generate lookup key from arguments // Copy arguments to an array for (index = 0; index < arguments.length; index++) { type = typeof arguments[index]; // Handle detecting arrays if (type === 'object' && arguments[index] instanceof Array) { type = 'array'; } // Add the type to the argument types array arr.push(type); } lookup = arr.join(','); // Check for an exact lookup match if (def[lookup]) { return self.callExtend(this, '$main', def, def[lookup], arguments); } else { for (index = arr.length; index >= 0; index--) { // Get the closest match lookup = arr.slice(0, index).join(','); if (def[lookup + ',...']) { // Matched against arguments + "any other" return self.callExtend(this, '$main', def, def[lookup + ',...'], arguments); } } } } throw('ForerunnerDB.Overload "' + this.name() + '": Overloaded method does not have a matching signature for the passed arguments: ' + JSON.stringify(arr)); }; } return function () {}; }; /** * Generates an array of all the different definition signatures that can be * created from the passed string with a catch-all wildcard *. E.g. it will * convert the signature: string,*,string to all potentials: * string,string,string * string,number,string * string,object,string, * string,function,string, * string,undefined,string * * @param {String} str Signature string with a wildcard in it. * @returns {Array} An array of signature strings that are generated. */ Overload.prototype.generateSignaturePermutations = function (str) { var signatures = [], newSignature, types = ['string', 'object', 'number', 'function', 'undefined'], index; if (str.indexOf('*') > -1) { // There is at least one "any" type, break out into multiple keys // We could do this at query time with regular expressions but // would be significantly slower for (index = 0; index < types.length; index++) { newSignature = str.replace('*', types[index]); signatures = signatures.concat(this.generateSignaturePermutations(newSignature)); } } else { signatures.push(str); } return signatures; }; Overload.prototype.callExtend = function (context, prop, propContext, func, args) { var tmp, ret; if (context && propContext[prop]) { tmp = context[prop]; context[prop] = propContext[prop]; ret = func.apply(context, args); context[prop] = tmp; return ret; } else { return func.apply(context, args); } }; module.exports = Overload; },{}],25:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared, Core, CoreInit, Collection, DbDocument; Shared = _dereq_('./Shared'); var Overview = function () { this.init.apply(this, arguments); }; Overview.prototype.init = function (name) { var self = this; this._name = name; this._data = new DbDocument('__FDB__dc_data_' + this._name); this._collData = new Collection(); this._collections = []; this._collectionDroppedWrap = function () { self._collectionDropped.apply(self, arguments); }; }; Shared.addModule('Overview', Overview); Shared.mixin(Overview.prototype, 'Mixin.Common'); Shared.mixin(Overview.prototype, 'Mixin.ChainReactor'); Shared.mixin(Overview.prototype, 'Mixin.Constants'); Shared.mixin(Overview.prototype, 'Mixin.Triggers'); Shared.mixin(Overview.prototype, 'Mixin.Events'); Collection = _dereq_('./Collection'); DbDocument = _dereq_('./Document'); Core = Shared.modules.Core; CoreInit = Core.prototype.init; /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(Overview.prototype, 'state'); Shared.synthesize(Overview.prototype, 'db'); Shared.synthesize(Overview.prototype, 'name'); Shared.synthesize(Overview.prototype, 'query', function (val) { var ret = this.$super(val); if (val !== undefined) { this._refresh(); } return ret; }); Shared.synthesize(Overview.prototype, 'queryOptions', function (val) { var ret = this.$super(val); if (val !== undefined) { this._refresh(); } return ret; }); Shared.synthesize(Overview.prototype, 'reduce', function (val) { var ret = this.$super(val); if (val !== undefined) { this._refresh(); } return ret; }); Overview.prototype.from = function (collection) { if (collection !== undefined) { if (typeof(collection) === 'string') { collection = this._db.collection(collection); } this._addCollection(collection); return this; } return this._collections; }; Overview.prototype.find = function () { return this._collData.find.apply(this._collData, arguments); }; Overview.prototype.count = function () { return this._collData.count.apply(this._collData, arguments); }; Overview.prototype._addCollection = function (collection) { if (this._collections.indexOf(collection) === -1) { this._collections.push(collection); collection.chain(this); collection.on('drop', this._collectionDroppedWrap); this._refresh(); } return this; }; Overview.prototype._removeCollection = function (collection) { var collectionIndex = this._collections.indexOf(collection); if (collectionIndex > -1) { this._collections.splice(collection, 1); collection.unChain(this); collection.off('drop', this._collectionDroppedWrap); this._refresh(); } return this; }; Overview.prototype._collectionDropped = function (collection) { if (collection) { // Collection was dropped, remove from overview this._removeCollection(collection); } }; Overview.prototype._refresh = function () { if (this._state !== 'dropped') { if (this._collections && this._collections[0]) { this._collData.primaryKey(this._collections[0].primaryKey()); var tempArr = [], i; for (i = 0; i < this._collections.length; i++) { tempArr = tempArr.concat(this._collections[i].find(this._query, this._queryOptions)); } this._collData.setData(tempArr); } // Now execute the reduce method if (this._reduce) { var reducedData = this._reduce(); // Update the document with the newly returned data this._data.setData(reducedData); } } }; Overview.prototype._chainHandler = function (chainPacket) { switch (chainPacket.type) { case 'setData': case 'insert': case 'update': case 'remove': this._refresh(); break; default: break; } }; /** * Gets the module's internal data collection. * @returns {Collection} */ Overview.prototype.data = function () { return this._data; }; Overview.prototype.drop = function () { if (this._state !== 'dropped') { this._state = 'dropped'; delete this._data; delete this._collData; // Remove all collection references while (this._collections.length) { this._removeCollection(this._collections[0]); } delete this._collections; if (this._db && this._name) { delete this._db._overview[this._name]; } delete this._name; this.emit('drop', this); } return true; }; // Extend DB to include collection groups Core.prototype.init = function () { this._overview = {}; CoreInit.apply(this, arguments); }; Core.prototype.overview = function (overviewName) { if (overviewName) { this._overview[overviewName] = this._overview[overviewName] || new Overview(overviewName).db(this); return this._overview[overviewName]; } else { // Return an object of collection data return this._overview; } }; Shared.finishModule('Overview'); module.exports = Overview; },{"./Collection":3,"./Document":7,"./Shared":29}],26:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); /** * Path object used to resolve object paths and retrieve data from * objects by using paths. * @param {String=} path The path to assign. * @constructor */ var Path = function (path) { this.init.apply(this, arguments); }; Path.prototype.init = function (path) { if (path) { this.path(path); } }; Shared.addModule('Path', Path); Shared.mixin(Path.prototype, 'Mixin.ChainReactor'); /** * Gets / sets the given path for the Path instance. * @param {String=} path The path to assign. */ Path.prototype.path = function (path) { if (path !== undefined) { this._path = this.clean(path); this._pathParts = this._path.split('.'); return this; } return this._path; }; /** * Tests if the passed object has the paths that are specified and that * a value exists in those paths. * @param {Object} testKeys The object describing the paths to test for. * @param {Object} testObj The object to test paths against. * @returns {Boolean} True if the object paths exist. */ Path.prototype.hasObjectPaths = function (testKeys, testObj) { var result = true, i; for (i in testKeys) { if (testKeys.hasOwnProperty(i)) { if (testObj[i] === undefined) { return false; } if (typeof testKeys[i] === 'object') { // Recurse object result = this.hasObjectPaths(testKeys[i], testObj[i]); // Should we exit early? if (!result) { return false; } } } } return result; }; /** * Counts the total number of key endpoints in the passed object. * @param {Object} testObj The object to count key endpoints for. * @returns {Number} The number of endpoints. */ Path.prototype.countKeys = function (testObj) { var totalKeys = 0, i; for (i in testObj) { if (testObj.hasOwnProperty(i)) { if (testObj[i] !== undefined) { if (typeof testObj[i] !== 'object') { totalKeys++; } else { totalKeys += this.countKeys(testObj[i]); } } } } return totalKeys; }; /** * Tests if the passed object has the paths that are specified and that * a value exists in those paths and if so returns the number matched. * @param {Object} testKeys The object describing the paths to test for. * @param {Object} testObj The object to test paths against. * @returns {Object} Stats on the matched keys */ Path.prototype.countObjectPaths = function (testKeys, testObj) { var matchData, matchedKeys = {}, matchedKeyCount = 0, totalKeyCount = 0, i; for (i in testObj) { if (testObj.hasOwnProperty(i)) { if (typeof testObj[i] === 'object') { // The test / query object key is an object, recurse matchData = this.countObjectPaths(testKeys[i], testObj[i]); matchedKeys[i] = matchData.matchedKeys; totalKeyCount += matchData.totalKeyCount; matchedKeyCount += matchData.matchedKeyCount; } else { // The test / query object has a property that is not an object so add it as a key totalKeyCount++; // Check if the test keys also have this key and it is also not an object if (testKeys && testKeys[i] && typeof testKeys[i] !== 'object') { matchedKeys[i] = true; matchedKeyCount++; } else { matchedKeys[i] = false; } } } } return { matchedKeys: matchedKeys, matchedKeyCount: matchedKeyCount, totalKeyCount: totalKeyCount }; }; /** * Takes a non-recursive object and converts the object hierarchy into * a path string. * @param {Object} obj The object to parse. * @param {Boolean=} withValue If true will include a 'value' key in the returned * object that represents the value the object path points to. * @returns {Object} */ Path.prototype.parse = function (obj, withValue) { var paths = [], path = '', resultData, i, k; for (i in obj) { if (obj.hasOwnProperty(i)) { // Set the path to the key path = i; if (typeof(obj[i]) === 'object') { if (withValue) { resultData = this.parse(obj[i], withValue); for (k = 0; k < resultData.length; k++) { paths.push({ path: path + '.' + resultData[k].path, value: resultData[k].value }); } } else { resultData = this.parse(obj[i]); for (k = 0; k < resultData.length; k++) { paths.push({ path: path + '.' + resultData[k].path }); } } } else { if (withValue) { paths.push({ path: path, value: obj[i] }); } else { paths.push({ path: path }); } } } } return paths; }; /** * Takes a non-recursive object and converts the object hierarchy into * an array of path strings that allow you to target all possible paths * in an object. * * @returns {Array} */ Path.prototype.parseArr = function (obj, options) { options = options || {}; return this._parseArr(obj, '', [], options); }; Path.prototype._parseArr = function (obj, path, paths, options) { var i, newPath = ''; path = path || ''; paths = paths || []; for (i in obj) { if (obj.hasOwnProperty(i)) { if (!options.ignore || (options.ignore && !options.ignore.test(i))) { if (path) { newPath = path + '.' + i; } else { newPath = i; } if (typeof(obj[i]) === 'object') { this._parseArr(obj[i], newPath, paths, options); } else { paths.push(newPath); } } } } return paths; }; /** * Gets the value(s) that the object contains for the currently assigned path string. * @param {Object} obj The object to evaluate the path against. * @param {String=} path A path to use instead of the existing one passed in path(). * @returns {Array} An array of values for the given path. */ Path.prototype.value = function (obj, path) { if (obj !== undefined && typeof obj === 'object') { var pathParts, arr, arrCount, objPart, objPartParent, valuesArr = [], i, k; if (path !== undefined) { path = this.clean(path); pathParts = path.split('.'); } arr = pathParts || this._pathParts; arrCount = arr.length; objPart = obj; for (i = 0; i < arrCount; i++) { objPart = objPart[arr[i]]; if (objPartParent instanceof Array) { // Search inside the array for the next key for (k = 0; k < objPartParent.length; k++) { valuesArr = valuesArr.concat(this.value(objPartParent, k + '.' + arr[i])); } return valuesArr; } else { if (!objPart || typeof(objPart) !== 'object') { break; } } objPartParent = objPart; } return [objPart]; } else { return []; } }; /** * Sets a value on an object for the specified path. * @param {Object} obj The object to update. * @param {String} path The path to update. * @param {*} val The value to set the object path to. * @returns {*} */ Path.prototype.set = function (obj, path, val) { if (obj !== undefined && path !== undefined) { var pathParts, part; path = this.clean(path); pathParts = path.split('.'); part = pathParts.shift(); if (pathParts.length) { // Generate the path part in the object if it does not already exist obj[part] = obj[part] || {}; // Recurse this.set(obj[part], pathParts.join('.'), val); } else { // Set the value obj[part] = val; } } return obj; }; Path.prototype.get = function (obj, path) { return this.value(obj, path)[0]; }; /** * Push a value to an array on an object for the specified path. * @param {Object} obj The object to update. * @param {String} path The path to the array to push to. * @param {*} val The value to push to the array at the object path. * @returns {*} */ Path.prototype.push = function (obj, path, val) { if (obj !== undefined && path !== undefined) { var pathParts, part; path = this.clean(path); pathParts = path.split('.'); part = pathParts.shift(); if (pathParts.length) { // Generate the path part in the object if it does not already exist obj[part] = obj[part] || {}; // Recurse this.set(obj[part], pathParts.join('.'), val); } else { // Set the value obj[part] = obj[part] || []; if (obj[part] instanceof Array) { obj[part].push(val); } else { throw('ForerunnerDB.Path: Cannot push to a path whose endpoint is not an array!'); } } } return obj; }; /** * Gets the value(s) that the object contains for the currently assigned path string * with their associated keys. * @param {Object} obj The object to evaluate the path against. * @param {String=} path A path to use instead of the existing one passed in path(). * @returns {Array} An array of values for the given path with the associated key. */ Path.prototype.keyValue = function (obj, path) { var pathParts, arr, arrCount, objPart, objPartParent, objPartHash, i; if (path !== undefined) { path = this.clean(path); pathParts = path.split('.'); } arr = pathParts || this._pathParts; arrCount = arr.length; objPart = obj; for (i = 0; i < arrCount; i++) { objPart = objPart[arr[i]]; if (!objPart || typeof(objPart) !== 'object') { objPartHash = arr[i] + ':' + objPart; break; } objPartParent = objPart; } return objPartHash; }; /** * Removes leading period (.) from string and returns it. * @param {String} str The string to clean. * @returns {*} */ Path.prototype.clean = function (str) { if (str.substr(0, 1) === '.') { str = str.substr(1, str.length -1); } return str; }; Shared.finishModule('Path'); module.exports = Path; },{"./Shared":29}],27:[function(_dereq_,module,exports){ "use strict"; // TODO: Add doc comments to this class // Import external names locally var Shared = _dereq_('./Shared'), localforage = _dereq_('localforage'), Core, Collection, CollectionDrop, CollectionGroup, CollectionInit, CoreInit, Persist, Overload; Persist = function () { this.init.apply(this, arguments); }; Persist.prototype.init = function (db) { // Check environment if (db.isClient()) { if (window.Storage !== undefined) { this.mode('localforage'); localforage.config({ driver: [ localforage.INDEXEDDB, localforage.WEBSQL, localforage.LOCALSTORAGE ], name: 'ForerunnerDB', storeName: 'FDB' }); } } }; Shared.addModule('Persist', Persist); Shared.mixin(Persist.prototype, 'Mixin.ChainReactor'); Core = Shared.modules.Core; Collection = _dereq_('./Collection'); CollectionDrop = Collection.prototype.drop; CollectionGroup = _dereq_('./CollectionGroup'); CollectionInit = Collection.prototype.init; CoreInit = Core.prototype.init; Overload = Shared.overload; Persist.prototype.mode = function (type) { if (type !== undefined) { this._mode = type; return this; } return this._mode; }; Persist.prototype.driver = function (val) { if (val !== undefined) { switch (val.toUpperCase()) { case 'LOCALSTORAGE': localforage.setDriver(localforage.LOCALSTORAGE); break; case 'WEBSQL': localforage.setDriver(localforage.WEBSQL); break; case 'INDEXEDDB': localforage.setDriver(localforage.INDEXEDDB); break; default: throw('ForerunnerDB.Persist: The persistence driver you have specified is not found. Please use either IndexedDB, WebSQL or LocalStorage!'); } return this; } return localforage.driver(); }; Persist.prototype.save = function (key, data, callback) { var encode; encode = function (val, finished) { if (typeof val === 'object') { val = 'json::fdb::' + JSON.stringify(val); } else { val = 'raw::fdb::' + val; } if (finished) { finished(false, val); } }; switch (this.mode()) { case 'localforage': encode(data, function (err, data) { localforage.setItem(key, data).then(function (data) { callback(false, data); }, function (err) { callback(err); }); }); break; default: if (callback) { callback('No data handler.'); } break; } }; Persist.prototype.load = function (key, callback) { var parts, data, decode; decode = function (val, finished) { if (val) { parts = val.split('::fdb::'); switch (parts[0]) { case 'json': data = JSON.parse(parts[1]); break; case 'raw': data = parts[1]; break; default: break; } if (finished) { finished(false, data); } } else { finished(false, val); } }; switch (this.mode()) { case 'localforage': localforage.getItem(key).then(function (val) { decode(val, callback); }, function (err) { callback(err); }); break; default: if (callback) { callback('No data handler or unrecognised data type.'); } break; } }; Persist.prototype.drop = function (key, callback) { switch (this.mode()) { case 'localforage': localforage.removeItem(key).then(function () { callback(false); }, function (err) { callback(err); }); break; default: if (callback) { callback('No data handler or unrecognised data type.'); } break; } }; // Extend the Collection prototype with persist methods Collection.prototype.drop = new Overload({ /** * Drop collection and persistent storage. */ '': function () { if (this._state !== 'dropped') { this.drop(true); } }, /** * Drop collection and persistent storage with callback. * @param {Function} callback Callback method. */ 'function': function (callback) { if (this._state !== 'dropped') { this.drop(true, callback); } }, /** * Drop collection and optionally drop persistent storage. * @param {Boolean} removePersistent True to drop persistent storage, false to keep it. */ 'boolean': function (removePersistent) { if (this._state !== 'dropped') { // Remove persistent storage if (removePersistent) { if (this._name) { if (this._db) { // Save the collection data this._db.persist.drop(this._name); } else { throw('ForerunnerDB.Persist: Cannot drop a collection\'s persistent storage when the collection is not attached to a database!'); } } else { throw('ForerunnerDB.Persist: Cannot drop a collection\'s persistent storage when no name assigned to collection!'); } } // Call the original method CollectionDrop.apply(this, arguments); } }, /** * Drop collections and optionally drop persistent storage with callback. * @param {Boolean} removePersistent True to drop persistent storage, false to keep it. * @param {Function} callback Callback method. */ 'boolean, function': function (removePersistent, callback) { if (this._state !== 'dropped') { // Remove persistent storage if (removePersistent) { if (this._name) { if (this._db) { // Save the collection data this._db.persist.drop(this._name, callback); } else { if (callback) { callback('Cannot drop a collection\'s persistent storage when the collection is not attached to a database!'); } } } else { if (callback) { callback('Cannot drop a collection\'s persistent storage when no name assigned to collection!'); } } } // Call the original method CollectionDrop.apply(this, arguments); } } }); Collection.prototype.save = function (callback) { if (this._name) { if (this._db) { // Save the collection data this._db.persist.save(this._name, this._data, callback); } else { if (callback) { callback('Cannot save a collection that is not attached to a database!'); } } } else { if (callback) { callback('Cannot save a collection with no assigned name!'); } } }; Collection.prototype.load = function (callback) { var self = this; if (this._name) { if (this._db) { // Load the collection data this._db.persist.load(this._name, function (err, data) { if (!err) { if (data) { self.setData(data); } if (callback) { callback(false); } } else { if (callback) { callback(err); } } }); } else { if (callback) { callback('Cannot load a collection that is not attached to a database!'); } } } else { if (callback) { callback('Cannot load a collection with no assigned name!'); } } }; // Override the DB init to instantiate the plugin Core.prototype.init = function () { this.persist = new Persist(this); CoreInit.apply(this, arguments); }; Core.prototype.load = function (callback) { // Loop the collections in the database var obj = this._collection, keys = obj.keys(), keyCount = keys.length, loadCallback, index; loadCallback = function (err) { if (!err) { keyCount--; if (keyCount === 0) { callback(false); } } else { callback(err); } }; for (index in obj) { if (obj.hasOwnProperty(index)) { // Call the collection load method obj[index].load(loadCallback); } } }; Core.prototype.save = function (callback) { // Loop the collections in the database var obj = this._collection, keys = obj.keys(), keyCount = keys.length, saveCallback, index; saveCallback = function (err) { if (!err) { keyCount--; if (keyCount === 0) { callback(false); } } else { callback(err); } }; for (index in obj) { if (obj.hasOwnProperty(index)) { // Call the collection save method obj[index].save(saveCallback); } } }; Shared.finishModule('Persist'); module.exports = Persist; },{"./Collection":3,"./CollectionGroup":4,"./Shared":29,"localforage":38}],28:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); var ReactorIO = function (reactorIn, reactorOut, reactorProcess) { if (reactorIn && reactorOut && reactorProcess) { this._reactorIn = reactorIn; this._reactorOut = reactorOut; this._chainHandler = reactorProcess; if (!reactorIn.chain || !reactorOut.chainReceive) { throw('ForerunnerDB.ReactorIO: ReactorIO requires passed in and out objects to implement the ChainReactor mixin!'); } // Register the reactorIO with the input reactorIn.chain(this); // Register the output with the reactorIO this.chain(reactorOut); } else { throw('ForerunnerDB.ReactorIO: ReactorIO requires in, out and process arguments to instantiate!'); } }; Shared.addModule('ReactorIO', ReactorIO); ReactorIO.prototype.drop = function () { if (this._state !== 'dropped') { this._state = 'dropped'; // Remove links if (this._reactorIn) { this._reactorIn.unChain(this); } if (this._reactorOut) { this.unChain(this._reactorOut); } delete this._reactorIn; delete this._reactorOut; delete this._chainHandler; this.emit('drop', this); } return true; }; /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(ReactorIO.prototype, 'state'); Shared.mixin(ReactorIO.prototype, 'Mixin.ChainReactor'); Shared.mixin(ReactorIO.prototype, 'Mixin.Events'); Shared.finishModule('ReactorIO'); module.exports = ReactorIO; },{"./Shared":29}],29:[function(_dereq_,module,exports){ "use strict"; var Shared = { version: '1.3.29', modules: {}, _synth: {}, /** * Adds a module to ForerunnerDB. * @param {String} name The name of the module. * @param {Function} module The module class. */ addModule: function (name, module) { this.modules[name] = module; this.emit('moduleLoad', [name, module]); }, /** * Called by the module once all processing has been completed. Used to determine * if the module is ready for use by other modules. * @param {String} name The name of the module. */ finishModule: function (name) { if (this.modules[name]) { this.modules[name]._fdbFinished = true; this.emit('moduleFinished', [name, this.modules[name]]); } else { throw('ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): ' + name); } }, /** * Will call your callback method when the specified module has loaded. If the module * is already loaded the callback is called immediately. * @param {String} name The name of the module. * @param {Function} callback The callback method to call when the module is loaded. */ moduleFinished: function (name, callback) { if (this.modules[name] && this.modules[name]._fdbFinished) { callback(name, this.modules[name]); } else { this.on('moduleFinished', callback); } }, /** * Determines if a module has been added to ForerunnerDB or not. * @param {String} name The name of the module. * @returns {Boolean} True if the module exists or false if not. */ moduleExists: function (name) { return Boolean(this.modules[name]); }, /** * Adds the properties and methods defined in the mixin to the passed object. * @param {Object} obj The target object to add mixin key/values to. * @param {String} mixinName The name of the mixin to add to the object. */ mixin: function (obj, mixinName) { var system = this.mixins[mixinName]; if (system) { for (var i in system) { if (system.hasOwnProperty(i)) { obj[i] = system[i]; } } } else { throw('ForerunnerDB.Shared: Cannot find mixin named: ' + mixinName); } }, /** * Generates a generic getter/setter method for the passed method name. * @param {Object} obj The object to add the getter/setter to. * @param {String} name The name of the getter/setter to generate. * @param {Function=} extend A method to call before executing the getter/setter. * The existing getter/setter can be accessed from the extend method via the * $super e.g. this.$super(); */ synthesize: function (obj, name, extend) { this._synth[name] = this._synth[name] || function (val) { if (val !== undefined) { this['_' + name] = val; return this; } return this['_' + name]; }; if (extend) { var self = this; obj[name] = function () { var tmp = this.$super, ret; this.$super = self._synth[name]; ret = extend.apply(this, arguments); this.$super = tmp; return ret; }; } else { obj[name] = this._synth[name]; } }, /** * Allows a method to be overloaded. * @param arr * @returns {Function} * @constructor */ overload: _dereq_('./Overload'), /** * Define the mixins that other modules can use as required. */ mixins: { 'Mixin.Common': _dereq_('./Mixin.Common'), 'Mixin.Events': _dereq_('./Mixin.Events'), 'Mixin.ChainReactor': _dereq_('./Mixin.ChainReactor'), 'Mixin.CRUD': _dereq_('./Mixin.CRUD'), 'Mixin.Constants': _dereq_('./Mixin.Constants'), 'Mixin.Triggers': _dereq_('./Mixin.Triggers'), 'Mixin.Sorting': _dereq_('./Mixin.Sorting'), 'Mixin.Matching': _dereq_('./Mixin.Matching') } }; // Add event handling to shared Shared.mixin(Shared, 'Mixin.Events'); module.exports = Shared; },{"./Mixin.CRUD":13,"./Mixin.ChainReactor":14,"./Mixin.Common":15,"./Mixin.Constants":16,"./Mixin.Events":17,"./Mixin.Matching":18,"./Mixin.Sorting":19,"./Mixin.Triggers":20,"./Overload":24}],30:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared, Core, Collection, CollectionGroup, CollectionInit, CoreInit, ReactorIO, ActiveBucket; Shared = _dereq_('./Shared'); /** * The view constructor. * @param name * @param query * @param options * @constructor */ var View = function (name, query, options) { this.init.apply(this, arguments); }; View.prototype.init = function (name, query, options) { var self = this; this._name = name; this._listeners = {}; this._querySettings = {}; this._debug = {}; this.query(query, false); this.queryOptions(options, false); this._collectionDroppedWrap = function () { self._collectionDropped.apply(self, arguments); }; this._privateData = new Collection('__FDB__view_privateData_' + this._name); }; Shared.addModule('View', View); Shared.mixin(View.prototype, 'Mixin.Common'); Shared.mixin(View.prototype, 'Mixin.ChainReactor'); Shared.mixin(View.prototype, 'Mixin.Constants'); Shared.mixin(View.prototype, 'Mixin.Triggers'); Collection = _dereq_('./Collection'); CollectionGroup = _dereq_('./CollectionGroup'); ActiveBucket = _dereq_('./ActiveBucket'); ReactorIO = _dereq_('./ReactorIO'); CollectionInit = Collection.prototype.init; Core = Shared.modules.Core; CoreInit = Core.prototype.init; /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(View.prototype, 'state'); Shared.synthesize(View.prototype, 'name'); /** * Executes an insert against the view's underlying data-source. */ View.prototype.insert = function () { this._from.insert.apply(this._from, arguments); }; /** * Executes an update against the view's underlying data-source. */ View.prototype.update = function () { this._from.update.apply(this._from, arguments); }; /** * Executes an updateById against the view's underlying data-source. */ View.prototype.updateById = function () { this._from.updateById.apply(this._from, arguments); }; /** * Executes a remove against the view's underlying data-source. */ View.prototype.remove = function () { this._from.remove.apply(this._from, arguments); }; /** * Queries the view data. See Collection.find() for more information. * @returns {*} */ View.prototype.find = function (query, options) { return this.publicData().find(query, options); }; /** * Gets the module's internal data collection. * @returns {Collection} */ View.prototype.data = function () { return this._privateData; }; /** * Sets the collection from which the view will assemble its data. * @param {Collection} collection The collection to use to assemble view data. * @returns {View} */ View.prototype.from = function (collection) { var self = this; if (collection !== undefined) { // Check if we have an existing from if (this._from) { // Remove the listener to the drop event this._from.off('drop', this._collectionDroppedWrap); delete this._from; } if (typeof(collection) === 'string') { collection = this._db.collection(collection); } this._from = collection; this._from.on('drop', this._collectionDroppedWrap); // Create a new reactor IO graph node that intercepts chain packets from the // view's "from" collection and determines how they should be interpreted by // this view. If the view does not have a query then this reactor IO will // simply pass along the chain packet without modifying it. this._io = new ReactorIO(collection, this, function (chainPacket) { var data, diff, query, filteredData, doSend, pk, i; // Check if we have a constraining query if (self._querySettings.query) { if (chainPacket.type === 'insert') { data = chainPacket.data; // Check if the data matches our query if (data instanceof Array) { filteredData = []; for (i = 0; i < data.length; i++) { if (self._privateData._match(data[i], self._querySettings.query, 'and', {})) { filteredData.push(data[i]); doSend = true; } } } else { if (self._privateData._match(data, self._querySettings.query, 'and', {})) { filteredData = data; doSend = true; } } if (doSend) { this.chainSend('insert', filteredData); } return true; } if (chainPacket.type === 'update') { // Do a DB diff between this view's data and the underlying collection it reads from // to see if something has changed diff = self._privateData.diff(self._from.subset(self._querySettings.query, self._querySettings.options)); if (diff.insert.length || diff.remove.length) { // Now send out new chain packets for each operation if (diff.insert.length) { this.chainSend('insert', diff.insert); } if (diff.update.length) { pk = self._privateData.primaryKey(); for (i = 0; i < diff.update.length; i++) { query = {}; query[pk] = diff.update[i][pk]; this.chainSend('update', { query: query, update: diff.update[i] }); } } if (diff.remove.length) { pk = self._privateData.primaryKey(); var $or = [], removeQuery = { query: { $or: $or } }; for (i = 0; i < diff.remove.length; i++) { $or.push({_id: diff.remove[i][pk]}); } this.chainSend('remove', removeQuery); } // Return true to stop further propagation of the chain packet return true; } else { // Returning false informs the chain reactor to continue propagation // of the chain packet down the graph tree return false; } } } // Returning false informs the chain reactor to continue propagation // of the chain packet down the graph tree return false; }); var collData = collection.find(this._querySettings.query, this._querySettings.options); this._transformPrimaryKey(collection.primaryKey()); this._transformSetData(collData); this._privateData.primaryKey(collection.primaryKey()); this._privateData.setData(collData); if (this._querySettings.options && this._querySettings.options.$orderBy) { this.rebuildActiveBucket(this._querySettings.options.$orderBy); } else { this.rebuildActiveBucket(); } } return this; }; View.prototype._collectionDropped = function (collection) { if (collection) { // Collection was dropped, remove from view delete this._from; } }; View.prototype.ensureIndex = function () { return this._privateData.ensureIndex.apply(this._privateData, arguments); }; View.prototype._chainHandler = function (chainPacket) { var //self = this, arr, count, index, insertIndex, //tempData, //dataIsArray, updates, //finalUpdates, primaryKey, tQuery, item, currentIndex, i; switch (chainPacket.type) { case 'setData': if (this.debug()) { console.log('ForerunnerDB.View: Setting data on view "' + this.name() + '" in underlying (internal) view collection "' + this._privateData.name() + '"'); } // Get the new data from our underlying data source sorted as we want var collData = this._from.find(this._querySettings.query, this._querySettings.options); // Modify transform data this._transformSetData(collData); this._privateData.setData(collData); break; case 'insert': if (this.debug()) { console.log('ForerunnerDB.View: Inserting some data on view "' + this.name() + '" in underlying (internal) view collection "' + this._privateData.name() + '"'); } // Decouple the data to ensure we are working with our own copy chainPacket.data = this.decouple(chainPacket.data); // Make sure we are working with an array if (!(chainPacket.data instanceof Array)) { chainPacket.data = [chainPacket.data]; } if (this._querySettings.options && this._querySettings.options.$orderBy) { // Loop the insert data and find each item's index arr = chainPacket.data; count = arr.length; for (index = 0; index < count; index++) { insertIndex = this._activeBucket.insert(arr[index]); // Modify transform data this._transformInsert(chainPacket.data, insertIndex); this._privateData._insertHandle(chainPacket.data, insertIndex); } } else { // Set the insert index to the passed index, or if none, the end of the view data array insertIndex = this._privateData._data.length; // Modify transform data this._transformInsert(chainPacket.data, insertIndex); this._privateData._insertHandle(chainPacket.data, insertIndex); } break; case 'update': if (this.debug()) { console.log('ForerunnerDB.View: Updating some data on view "' + this.name() + '" in underlying (internal) view collection "' + this._privateData.name() + '"'); } primaryKey = this._privateData.primaryKey(); // Do the update updates = this._privateData.update( chainPacket.data.query, chainPacket.data.update, chainPacket.data.options ); if (this._querySettings.options && this._querySettings.options.$orderBy) { // TODO: This would be a good place to improve performance by somehow // TODO: inspecting the change that occurred when update was performed // TODO: above and determining if it affected the order clause keys // TODO: and if not, skipping the active bucket updates here // Loop the updated items and work out their new sort locations count = updates.length; for (index = 0; index < count; index++) { item = updates[index]; // Remove the item from the active bucket (via it's id) this._activeBucket.remove(item); // Get the current location of the item currentIndex = this._privateData._data.indexOf(item); // Add the item back in to the active bucket insertIndex = this._activeBucket.insert(item); if (currentIndex !== insertIndex) { // Move the updated item to the new index this._privateData._updateSpliceMove(this._privateData._data, currentIndex, insertIndex); } } } if (this._transformEnabled && this._transformIn) { primaryKey = this._publicData.primaryKey(); for (i = 0; i < updates.length; i++) { tQuery = {}; item = updates[i]; tQuery[primaryKey] = item[primaryKey]; this._transformUpdate(tQuery, item); } } break; case 'remove': if (this.debug()) { console.log('ForerunnerDB.View: Removing some data on view "' + this.name() + '" in underlying (internal) view collection "' + this._privateData.name() + '"'); } // Modify transform data this._transformRemove(chainPacket.data.query, chainPacket.options); this._privateData.remove(chainPacket.data.query, chainPacket.options); break; default: break; } }; View.prototype.on = function () { this._privateData.on.apply(this._privateData, arguments); }; View.prototype.off = function () { this._privateData.off.apply(this._privateData, arguments); }; View.prototype.emit = function () { this._privateData.emit.apply(this._privateData, arguments); }; /** * Find the distinct values for a specified field across a single collection and * returns the results in an array. * @param {String} key The field path to return distinct values for e.g. "person.name". * @param {Object=} query The query to use to filter the documents used to return values from. * @param {Object=} options The query options to use when running the query. * @returns {Array} */ View.prototype.distinct = function (key, query, options) { return this._privateData.distinct.apply(this._privateData, arguments); }; /** * Gets the primary key for this view from the assigned collection. * @returns {String} */ View.prototype.primaryKey = function () { return this._privateData.primaryKey(); }; /** * Drops a view and all it's stored data from the database. * @returns {boolean} True on success, false on failure. */ View.prototype.drop = function () { if (this._state !== 'dropped') { if (this._from) { this._from.off('drop', this._collectionDroppedWrap); this._from._removeView(this); if (this.debug() || (this._db && this._db.debug())) { console.log('ForerunnerDB.View: Dropping view ' + this._name); } this._state = 'dropped'; // Clear io and chains if (this._io) { this._io.drop(); } // Drop the view's internal collection if (this._privateData) { this._privateData.drop(); } if (this._db && this._name) { delete this._db._view[this._name]; } this.emit('drop', this); delete this._chain; delete this._from; delete this._privateData; delete this._io; delete this._listeners; delete this._querySettings; delete this._db; return true; } } else { return true; } return false; }; /** * Gets / sets the DB the view is bound against. Automatically set * when the db.oldView(viewName) method is called. * @param db * @returns {*} */ View.prototype.db = function (db) { if (db !== undefined) { this._db = db; this.privateData().db(db); this.publicData().db(db); return this; } return this._db; }; /** * Gets / sets the query that the view uses to build it's data set. * @param {Object=} query * @param {Boolean=} options An options object. * @param {Boolean=} refresh Whether to refresh the view data after * this operation. Defaults to true. * @returns {*} */ View.prototype.queryData = function (query, options, refresh) { if (query !== undefined) { this._querySettings.query = query; } if (options !== undefined) { this._querySettings.options = options; } if (query !== undefined || options !== undefined) { if (refresh === undefined || refresh === true) { this.refresh(); } return this; } return this._querySettings; }; /** * Add data to the existing query. * @param {Object} obj The data whose keys will be added to the existing * query object. * @param {Boolean} overwrite Whether or not to overwrite data that already * exists in the query object. Defaults to true. * @param {Boolean=} refresh Whether or not to refresh the view data set * once the operation is complete. Defaults to true. */ View.prototype.queryAdd = function (obj, overwrite, refresh) { this._querySettings.query = this._querySettings.query || {}; var query = this._querySettings.query, i; if (obj !== undefined) { // Loop object properties and add to existing query for (i in obj) { if (obj.hasOwnProperty(i)) { if (query[i] === undefined || (query[i] !== undefined && overwrite !== false)) { query[i] = obj[i]; } } } } if (refresh === undefined || refresh === true) { this.refresh(); } }; /** * Remove data from the existing query. * @param {Object} obj The data whose keys will be removed from the existing * query object. * @param {Boolean=} refresh Whether or not to refresh the view data set * once the operation is complete. Defaults to true. */ View.prototype.queryRemove = function (obj, refresh) { var query = this._querySettings.query, i; if (obj !== undefined) { // Loop object properties and add to existing query for (i in obj) { if (obj.hasOwnProperty(i)) { delete query[i]; } } } if (refresh === undefined || refresh === true) { this.refresh(); } }; /** * Gets / sets the query being used to generate the view data. * @param {Object=} query The query to set. * @param {Boolean=} refresh Whether to refresh the view data after * this operation. Defaults to true. * @returns {*} */ View.prototype.query = function (query, refresh) { if (query !== undefined) { this._querySettings.query = query; if (refresh === undefined || refresh === true) { this.refresh(); } return this; } return this._querySettings.query; }; /** * Gets / sets the orderBy clause in the query options for the view. * @param {Object=} val The order object. * @returns {*} */ View.prototype.orderBy = function (val) { if (val !== undefined) { var queryOptions = this.queryOptions() || {}; queryOptions.$orderBy = val; this.queryOptions(queryOptions); return this; } return (this.queryOptions() || {}).$orderBy; }; /** * Gets / sets the query options used when applying sorting etc to the * view data set. * @param {Object=} options An options object. * @param {Boolean=} refresh Whether to refresh the view data after * this operation. Defaults to true. * @returns {*} */ View.prototype.queryOptions = function (options, refresh) { if (options !== undefined) { this._querySettings.options = options; if (options.$decouple === undefined) { options.$decouple = true; } if (refresh === undefined || refresh === true) { this.refresh(); } else { this.rebuildActiveBucket(options.$orderBy); } return this; } return this._querySettings.options; }; View.prototype.rebuildActiveBucket = function (orderBy) { if (orderBy) { var arr = this._privateData._data, arrCount = arr.length; // Build a new active bucket this._activeBucket = new ActiveBucket(orderBy); this._activeBucket.primaryKey(this._privateData.primaryKey()); // Loop the current view data and add each item for (var i = 0; i < arrCount; i++) { this._activeBucket.insert(arr[i]); } } else { // Remove any existing active bucket delete this._activeBucket; } }; /** * Refreshes the view data such as ordering etc. */ View.prototype.refresh = function () { if (this._from) { var pubData = this.publicData(); // Re-grab all the data for the view from the collection this._privateData.remove(); pubData.remove(); this._privateData.insert(this._from.find(this._querySettings.query, this._querySettings.options)); /*if (pubData._linked) { // Update data and observers //var transformedData = this._privateData.find(); // TODO: Shouldn't this data get passed into a transformIn first? // TODO: This breaks linking because its passing decoupled data and overwriting non-decoupled data // TODO: Is this even required anymore? After commenting it all seems to work // TODO: Might be worth setting up a test to check trasforms and linking then remove this if working? //jQuery.observable(pubData._data).refresh(transformedData); }*/ } if (this._querySettings.options && this._querySettings.options.$orderBy) { this.rebuildActiveBucket(this._querySettings.options.$orderBy); } else { this.rebuildActiveBucket(); } return this; }; /** * Returns the number of documents currently in the view. * @returns {Number} */ View.prototype.count = function () { return this._privateData && this._privateData._data ? this._privateData._data.length : 0; }; // Call underlying View.prototype.subset = function () { return this.publicData().subset.apply(this._privateData, arguments); }; /** * Takes the passed data and uses it to set transform methods and globally * enable or disable the transform system for the view. * @param {Object} obj The new transform system settings "enabled", "dataIn" and "dataOut": * { * "enabled": true, * "dataIn": function (data) { return data; }, * "dataOut": function (data) { return data; } * } * @returns {*} */ View.prototype.transform = function (obj) { if (obj !== undefined) { if (typeof obj === "object") { if (obj.enabled !== undefined) { this._transformEnabled = obj.enabled; } if (obj.dataIn !== undefined) { this._transformIn = obj.dataIn; } if (obj.dataOut !== undefined) { this._transformOut = obj.dataOut; } } else { this._transformEnabled = obj !== false; } // Update the transformed data object this._transformPrimaryKey(this.privateData().primaryKey()); this._transformSetData(this.privateData().find()); return this; } return { enabled: this._transformEnabled, dataIn: this._transformIn, dataOut: this._transformOut }; }; /** * Returns the non-transformed data the view holds as a collection * reference. * @return {Collection} The non-transformed collection reference. */ View.prototype.privateData = function () { return this._privateData; }; /** * Returns a data object representing the public data this view * contains. This can change depending on if transforms are being * applied to the view or not. * * If no transforms are applied then the public data will be the * same as the private data the view holds. If transforms are * applied then the public data will contain the transformed version * of the private data. * * The public data collection is also used by data binding to only * changes to the publicData will show in a data-bound element. */ View.prototype.publicData = function () { if (this._transformEnabled) { return this._publicData; } else { return this._privateData; } }; /** * Updates the public data object to match data from the private data object * by running private data through the dataIn method provided in * the transform() call. * @private */ View.prototype._transformSetData = function (data) { if (this._transformEnabled) { // Clear existing data this._publicData = new Collection('__FDB__view_publicData_' + this._name); this._publicData.db(this._privateData._db); this._publicData.transform({ enabled: true, dataIn: this._transformIn, dataOut: this._transformOut }); this._publicData.setData(data); } }; View.prototype._transformInsert = function (data, index) { if (this._transformEnabled && this._publicData) { this._publicData.insert(data, index); } }; View.prototype._transformUpdate = function (query, update, options) { if (this._transformEnabled && this._publicData) { this._publicData.update(query, update, options); } }; View.prototype._transformRemove = function (query, options) { if (this._transformEnabled && this._publicData) { this._publicData.remove(query, options); } }; View.prototype._transformPrimaryKey = function (key) { if (this._transformEnabled && this._publicData) { this._publicData.primaryKey(key); } }; // Extend collection with view init Collection.prototype.init = function () { this._view = []; CollectionInit.apply(this, arguments); }; /** * Creates a view and assigns the collection as its data source. * @param {String} name The name of the new view. * @param {Object} query The query to apply to the new view. * @param {Object} options The options object to apply to the view. * @returns {*} */ Collection.prototype.view = function (name, query, options) { if (this._db && this._db._view ) { if (!this._db._view[name]) { var view = new View(name, query, options) .db(this._db) .from(this); this._view = this._view || []; this._view.push(view); return view; } else { throw('ForerunnerDB.Collection "' + this.name() + '": Cannot create a view using this collection because a view with this name already exists: ' + name); } } }; /** * Adds a view to the internal view lookup. * @param {View} view The view to add. * @returns {Collection} * @private */ Collection.prototype._addView = CollectionGroup.prototype._addView = function (view) { if (view !== undefined) { this._view.push(view); } return this; }; /** * Removes a view from the internal view lookup. * @param {View} view The view to remove. * @returns {Collection} * @private */ Collection.prototype._removeView = CollectionGroup.prototype._removeView = function (view) { if (view !== undefined) { var index = this._view.indexOf(view); if (index > -1) { this._view.splice(index, 1); } } return this; }; // Extend DB with views init Core.prototype.init = function () { this._view = {}; CoreInit.apply(this, arguments); }; /** * Gets a view by it's name. * @param {String} viewName The name of the view to retrieve. * @returns {*} */ Core.prototype.view = function (viewName) { if (!this._view[viewName]) { if (this.debug() || (this._db && this._db.debug())) { console.log('Core.View: Creating view ' + viewName); } } this._view[viewName] = this._view[viewName] || new View(viewName).db(this); return this._view[viewName]; }; /** * Determine if a view with the passed name already exists. * @param {String} viewName The name of the view to check for. * @returns {boolean} */ Core.prototype.viewExists = function (viewName) { return Boolean(this._view[viewName]); }; /** * Returns an array of views the DB currently has. * @returns {Array} An array of objects containing details of each view * the database is currently managing. */ Core.prototype.views = function () { var arr = [], i; for (i in this._view) { if (this._view.hasOwnProperty(i)) { arr.push({ name: i, count: this._view[i].count() }); } } return arr; }; Shared.finishModule('View'); module.exports = View; },{"./ActiveBucket":2,"./Collection":3,"./CollectionGroup":4,"./ReactorIO":28,"./Shared":29}],31:[function(_dereq_,module,exports){ // shim for using process in browser var process = module.exports = {}; var queue = []; var draining = false; function drainQueue() { if (draining) { return; } draining = true; var currentQueue; var len = queue.length; while(len) { currentQueue = queue; queue = []; var i = -1; while (++i < len) { currentQueue[i](); } len = queue.length; } draining = false; } process.nextTick = function (fun) { queue.push(fun); if (!draining) { setTimeout(drainQueue, 0); } }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.binding = function (name) { throw new Error('process.binding is not supported'); }; // TODO(shtylman) process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; },{}],32:[function(_dereq_,module,exports){ 'use strict'; var asap = _dereq_('asap') module.exports = Promise function Promise(fn) { if (typeof this !== 'object') throw new TypeError('Promises must be constructed via new') if (typeof fn !== 'function') throw new TypeError('not a function') var state = null var value = null var deferreds = [] var self = this this.then = function(onFulfilled, onRejected) { return new Promise(function(resolve, reject) { handle(new Handler(onFulfilled, onRejected, resolve, reject)) }) } function handle(deferred) { if (state === null) { deferreds.push(deferred) return } asap(function() { var cb = state ? deferred.onFulfilled : deferred.onRejected if (cb === null) { (state ? deferred.resolve : deferred.reject)(value) return } var ret try { ret = cb(value) } catch (e) { deferred.reject(e) return } deferred.resolve(ret) }) } function resolve(newValue) { try { //Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure if (newValue === self) throw new TypeError('A promise cannot be resolved with itself.') if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) { var then = newValue.then if (typeof then === 'function') { doResolve(then.bind(newValue), resolve, reject) return } } state = true value = newValue finale() } catch (e) { reject(e) } } function reject(newValue) { state = false value = newValue finale() } function finale() { for (var i = 0, len = deferreds.length; i < len; i++) handle(deferreds[i]) deferreds = null } doResolve(fn, resolve, reject) } function Handler(onFulfilled, onRejected, resolve, reject){ this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null this.onRejected = typeof onRejected === 'function' ? onRejected : null this.resolve = resolve this.reject = reject } /** * Take a potentially misbehaving resolver function and make sure * onFulfilled and onRejected are only called once. * * Makes no guarantees about asynchrony. */ function doResolve(fn, onFulfilled, onRejected) { var done = false; try { fn(function (value) { if (done) return done = true onFulfilled(value) }, function (reason) { if (done) return done = true onRejected(reason) }) } catch (ex) { if (done) return done = true onRejected(ex) } } },{"asap":34}],33:[function(_dereq_,module,exports){ 'use strict'; //This file contains then/promise specific extensions to the core promise API var Promise = _dereq_('./core.js') var asap = _dereq_('asap') module.exports = Promise /* Static Functions */ function ValuePromise(value) { this.then = function (onFulfilled) { if (typeof onFulfilled !== 'function') return this return new Promise(function (resolve, reject) { asap(function () { try { resolve(onFulfilled(value)) } catch (ex) { reject(ex); } }) }) } } ValuePromise.prototype = Object.create(Promise.prototype) var TRUE = new ValuePromise(true) var FALSE = new ValuePromise(false) var NULL = new ValuePromise(null) var UNDEFINED = new ValuePromise(undefined) var ZERO = new ValuePromise(0) var EMPTYSTRING = new ValuePromise('') Promise.resolve = function (value) { if (value instanceof Promise) return value if (value === null) return NULL if (value === undefined) return UNDEFINED if (value === true) return TRUE if (value === false) return FALSE if (value === 0) return ZERO if (value === '') return EMPTYSTRING if (typeof value === 'object' || typeof value === 'function') { try { var then = value.then if (typeof then === 'function') { return new Promise(then.bind(value)) } } catch (ex) { return new Promise(function (resolve, reject) { reject(ex) }) } } return new ValuePromise(value) } Promise.from = Promise.cast = function (value) { var err = new Error('Promise.from and Promise.cast are deprecated, use Promise.resolve instead') err.name = 'Warning' console.warn(err.stack) return Promise.resolve(value) } Promise.denodeify = function (fn, argumentCount) { argumentCount = argumentCount || Infinity return function () { var self = this var args = Array.prototype.slice.call(arguments) return new Promise(function (resolve, reject) { while (args.length && args.length > argumentCount) { args.pop() } args.push(function (err, res) { if (err) reject(err) else resolve(res) }) fn.apply(self, args) }) } } Promise.nodeify = function (fn) { return function () { var args = Array.prototype.slice.call(arguments) var callback = typeof args[args.length - 1] === 'function' ? args.pop() : null try { return fn.apply(this, arguments).nodeify(callback) } catch (ex) { if (callback === null || typeof callback == 'undefined') { return new Promise(function (resolve, reject) { reject(ex) }) } else { asap(function () { callback(ex) }) } } } } Promise.all = function () { var calledWithArray = arguments.length === 1 && Array.isArray(arguments[0]) var args = Array.prototype.slice.call(calledWithArray ? arguments[0] : arguments) if (!calledWithArray) { var err = new Error('Promise.all should be called with a single array, calling it with multiple arguments is deprecated') err.name = 'Warning' console.warn(err.stack) } return new Promise(function (resolve, reject) { if (args.length === 0) return resolve([]) var remaining = args.length function res(i, val) { try { if (val && (typeof val === 'object' || typeof val === 'function')) { var then = val.then if (typeof then === 'function') { then.call(val, function (val) { res(i, val) }, reject) return } } args[i] = val if (--remaining === 0) { resolve(args); } } catch (ex) { reject(ex) } } for (var i = 0; i < args.length; i++) { res(i, args[i]) } }) } Promise.reject = function (value) { return new Promise(function (resolve, reject) { reject(value); }); } Promise.race = function (values) { return new Promise(function (resolve, reject) { values.forEach(function(value){ Promise.resolve(value).then(resolve, reject); }) }); } /* Prototype Methods */ Promise.prototype.done = function (onFulfilled, onRejected) { var self = arguments.length ? this.then.apply(this, arguments) : this self.then(null, function (err) { asap(function () { throw err }) }) } Promise.prototype.nodeify = function (callback) { if (typeof callback != 'function') return this this.then(function (value) { asap(function () { callback(null, value) }) }, function (err) { asap(function () { callback(err) }) }) } Promise.prototype['catch'] = function (onRejected) { return this.then(null, onRejected); } },{"./core.js":32,"asap":34}],34:[function(_dereq_,module,exports){ (function (process){ // Use the fastest possible means to execute a task in a future turn // of the event loop. // linked list of tasks (single, with head node) var head = {task: void 0, next: null}; var tail = head; var flushing = false; var requestFlush = void 0; var isNodeJS = false; function flush() { /* jshint loopfunc: true */ while (head.next) { head = head.next; var task = head.task; head.task = void 0; var domain = head.domain; if (domain) { head.domain = void 0; domain.enter(); } try { task(); } catch (e) { if (isNodeJS) { // In node, uncaught exceptions are considered fatal errors. // Re-throw them synchronously to interrupt flushing! // Ensure continuation if the uncaught exception is suppressed // listening "uncaughtException" events (as domains does). // Continue in next event to avoid tick recursion. if (domain) { domain.exit(); } setTimeout(flush, 0); if (domain) { domain.enter(); } throw e; } else { // In browsers, uncaught exceptions are not fatal. // Re-throw them asynchronously to avoid slow-downs. setTimeout(function() { throw e; }, 0); } } if (domain) { domain.exit(); } } flushing = false; } if (typeof process !== "undefined" && process.nextTick) { // Node.js before 0.9. Note that some fake-Node environments, like the // Mocha test runner, introduce a `process` global without a `nextTick`. isNodeJS = true; requestFlush = function () { process.nextTick(flush); }; } else if (typeof setImmediate === "function") { // In IE10, Node.js 0.9+, or https://github.com/NobleJS/setImmediate if (typeof window !== "undefined") { requestFlush = setImmediate.bind(window, flush); } else { requestFlush = function () { setImmediate(flush); }; } } else if (typeof MessageChannel !== "undefined") { // modern browsers // http://www.nonblocking.io/2011/06/windownexttick.html var channel = new MessageChannel(); channel.port1.onmessage = flush; requestFlush = function () { channel.port2.postMessage(0); }; } else { // old browsers requestFlush = function () { setTimeout(flush, 0); }; } function asap(task) { tail = tail.next = { task: task, domain: isNodeJS && process.domain, next: null }; if (!flushing) { flushing = true; requestFlush(); } }; module.exports = asap; }).call(this,_dereq_('_process')) },{"_process":31}],35:[function(_dereq_,module,exports){ // Some code originally from async_storage.js in // [Gaia](https://github.com/mozilla-b2g/gaia). (function() { 'use strict'; // Originally found in https://github.com/mozilla-b2g/gaia/blob/e8f624e4cc9ea945727278039b3bc9bcb9f8667a/shared/js/async_storage.js // Promises! var Promise = (typeof module !== 'undefined' && module.exports) ? _dereq_('promise') : this.Promise; // Initialize IndexedDB; fall back to vendor-prefixed versions if needed. var indexedDB = indexedDB || this.indexedDB || this.webkitIndexedDB || this.mozIndexedDB || this.OIndexedDB || this.msIndexedDB; // If IndexedDB isn't available, we get outta here! if (!indexedDB) { return; } // Open the IndexedDB database (automatically creates one if one didn't // previously exist), using any options set in the config. function _initStorage(options) { var self = this; var dbInfo = { db: null }; if (options) { for (var i in options) { dbInfo[i] = options[i]; } } return new Promise(function(resolve, reject) { var openreq = indexedDB.open(dbInfo.name, dbInfo.version); openreq.onerror = function() { reject(openreq.error); }; openreq.onupgradeneeded = function() { // First time setup: create an empty object store openreq.result.createObjectStore(dbInfo.storeName); }; openreq.onsuccess = function() { dbInfo.db = openreq.result; self._dbInfo = dbInfo; resolve(); }; }); } function getItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { window.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly') .objectStore(dbInfo.storeName); var req = store.get(key); req.onsuccess = function() { var value = req.result; if (value === undefined) { value = null; } resolve(value); }; req.onerror = function() { reject(req.error); }; })['catch'](reject); }); executeDeferedCallback(promise, callback); return promise; } // Iterate over all items stored in database. function iterate(iterator, callback) { var self = this; var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly') .objectStore(dbInfo.storeName); var req = store.openCursor(); var iterationNumber = 1; req.onsuccess = function() { var cursor = req.result; if (cursor) { var result = iterator(cursor.value, cursor.key, iterationNumber++); if (result !== void(0)) { resolve(result); } else { cursor['continue'](); } } else { resolve(); } }; req.onerror = function() { reject(req.error); }; })['catch'](reject); }); executeDeferedCallback(promise, callback); return promise; } function setItem(key, value, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { window.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite'); var store = transaction.objectStore(dbInfo.storeName); // The reason we don't _save_ null is because IE 10 does // not support saving the `null` type in IndexedDB. How // ironic, given the bug below! // See: https://github.com/mozilla/localForage/issues/161 if (value === null) { value = undefined; } var req = store.put(value, key); transaction.oncomplete = function() { // Cast to undefined so the value passed to // callback/promise is the same as what one would get out // of `getItem()` later. This leads to some weirdness // (setItem('foo', undefined) will return `null`), but // it's not my fault localStorage is our baseline and that // it's weird. if (value === undefined) { value = null; } resolve(value); }; transaction.onabort = transaction.onerror = function() { reject(req.error); }; })['catch'](reject); }); executeDeferedCallback(promise, callback); return promise; } function removeItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { window.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite'); var store = transaction.objectStore(dbInfo.storeName); // We use a Grunt task to make this safe for IE and some // versions of Android (including those used by Cordova). // Normally IE won't like `['delete']()` and will insist on // using `['delete']()`, but we have a build step that // fixes this for us now. var req = store['delete'](key); transaction.oncomplete = function() { resolve(); }; transaction.onerror = function() { reject(req.error); }; // The request will be aborted if we've exceeded our storage // space. In this case, we will reject with a specific // "QuotaExceededError". transaction.onabort = function(event) { var error = event.target.error; if (error === 'QuotaExceededError') { reject(error); } }; })['catch'](reject); }); executeDeferedCallback(promise, callback); return promise; } function clear(callback) { var self = this; var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite'); var store = transaction.objectStore(dbInfo.storeName); var req = store.clear(); transaction.oncomplete = function() { resolve(); }; transaction.onabort = transaction.onerror = function() { reject(req.error); }; })['catch'](reject); }); executeDeferedCallback(promise, callback); return promise; } function length(callback) { var self = this; var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly') .objectStore(dbInfo.storeName); var req = store.count(); req.onsuccess = function() { resolve(req.result); }; req.onerror = function() { reject(req.error); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function key(n, callback) { var self = this; var promise = new Promise(function(resolve, reject) { if (n < 0) { resolve(null); return; } self.ready().then(function() { var dbInfo = self._dbInfo; var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly') .objectStore(dbInfo.storeName); var advanced = false; var req = store.openCursor(); req.onsuccess = function() { var cursor = req.result; if (!cursor) { // this means there weren't enough keys resolve(null); return; } if (n === 0) { // We have the first key, return it if that's what they // wanted. resolve(cursor.key); } else { if (!advanced) { // Otherwise, ask the cursor to skip ahead n // records. advanced = true; cursor.advance(n); } else { // When we get here, we've got the nth key. resolve(cursor.key); } } }; req.onerror = function() { reject(req.error); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function keys(callback) { var self = this; var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly') .objectStore(dbInfo.storeName); var req = store.openCursor(); var keys = []; req.onsuccess = function() { var cursor = req.result; if (!cursor) { resolve(keys); return; } keys.push(cursor.key); cursor['continue'](); }; req.onerror = function() { reject(req.error); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function executeCallback(promise, callback) { if (callback) { promise.then(function(result) { callback(null, result); }, function(error) { callback(error); }); } } function executeDeferedCallback(promise, callback) { if (callback) { promise.then(function(result) { deferCallback(callback, result); }, function(error) { callback(error); }); } } // Under Chrome the callback is called before the changes (save, clear) // are actually made. So we use a defer function which wait that the // call stack to be empty. // For more info : https://github.com/mozilla/localForage/issues/175 // Pull request : https://github.com/mozilla/localForage/pull/178 function deferCallback(callback, result) { if (callback) { return setTimeout(function() { return callback(null, result); }, 0); } } var asyncStorage = { _driver: 'asyncStorage', _initStorage: _initStorage, iterate: iterate, getItem: getItem, setItem: setItem, removeItem: removeItem, clear: clear, length: length, key: key, keys: keys }; if (typeof module !== 'undefined' && module.exports) { module.exports = asyncStorage; } else if (typeof define === 'function' && define.amd) { define('asyncStorage', function() { return asyncStorage; }); } else { this.asyncStorage = asyncStorage; } }).call(window); },{"promise":33}],36:[function(_dereq_,module,exports){ // If IndexedDB isn't available, we'll fall back to localStorage. // Note that this will have considerable performance and storage // side-effects (all data will be serialized on save and only data that // can be converted to a string via `JSON.stringify()` will be saved). (function() { 'use strict'; // Promises! var Promise = (typeof module !== 'undefined' && module.exports) ? _dereq_('promise') : this.Promise; var globalObject = this; var serializer = null; var localStorage = null; // If the app is running inside a Google Chrome packaged webapp, or some // other context where localStorage isn't available, we don't use // localStorage. This feature detection is preferred over the old // `if (window.chrome && window.chrome.runtime)` code. // See: https://github.com/mozilla/localForage/issues/68 try { // If localStorage isn't available, we get outta here! // This should be inside a try catch if (!this.localStorage || !('setItem' in this.localStorage)) { return; } // Initialize localStorage and create a variable to use throughout // the code. localStorage = this.localStorage; } catch (e) { return; } var ModuleType = { DEFINE: 1, EXPORT: 2, WINDOW: 3 }; // Attaching to window (i.e. no module loader) is the assumed, // simple default. var moduleType = ModuleType.WINDOW; // Find out what kind of module setup we have; if none, we'll just attach // localForage to the main window. if (typeof module !== 'undefined' && module.exports) { moduleType = ModuleType.EXPORT; } else if (typeof define === 'function' && define.amd) { moduleType = ModuleType.DEFINE; } // Config the localStorage backend, using options set in the config. function _initStorage(options) { var self = this; var dbInfo = {}; if (options) { for (var i in options) { dbInfo[i] = options[i]; } } dbInfo.keyPrefix = dbInfo.name + '/'; self._dbInfo = dbInfo; var serializerPromise = new Promise(function(resolve/*, reject*/) { // We allow localForage to be declared as a module or as a // library available without AMD/require.js. if (moduleType === ModuleType.DEFINE) { _dereq_(['localforageSerializer'], resolve); } else if (moduleType === ModuleType.EXPORT) { // Making it browserify friendly resolve(_dereq_('./../utils/serializer')); } else { resolve(globalObject.localforageSerializer); } }); return serializerPromise.then(function(lib) { serializer = lib; return Promise.resolve(); }); } // Remove all keys from the datastore, effectively destroying all data in // the app's key/value store! function clear(callback) { var self = this; var promise = self.ready().then(function() { var keyPrefix = self._dbInfo.keyPrefix; for (var i = localStorage.length - 1; i >= 0; i--) { var key = localStorage.key(i); if (key.indexOf(keyPrefix) === 0) { localStorage.removeItem(key); } } }); executeCallback(promise, callback); return promise; } // Retrieve an item from the store. Unlike the original async_storage // library in Gaia, we don't modify return values at all. If a key's value // is `undefined`, we pass that value to the callback function. function getItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { window.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = self.ready().then(function() { var dbInfo = self._dbInfo; var result = localStorage.getItem(dbInfo.keyPrefix + key); // If a result was found, parse it from the serialized // string into a JS object. If result isn't truthy, the key // is likely undefined and we'll pass it straight to the // callback. if (result) { result = serializer.deserialize(result); } return result; }); executeCallback(promise, callback); return promise; } // Iterate over all items in the store. function iterate(iterator, callback) { var self = this; var promise = self.ready().then(function() { var keyPrefix = self._dbInfo.keyPrefix; var keyPrefixLength = keyPrefix.length; var length = localStorage.length; for (var i = 0; i < length; i++) { var key = localStorage.key(i); var value = localStorage.getItem(key); // If a result was found, parse it from the serialized // string into a JS object. If result isn't truthy, the // key is likely undefined and we'll pass it straight // to the iterator. if (value) { value = serializer.deserialize(value); } value = iterator(value, key.substring(keyPrefixLength), i + 1); if (value !== void(0)) { return value; } } }); executeCallback(promise, callback); return promise; } // Same as localStorage's key() method, except takes a callback. function key(n, callback) { var self = this; var promise = self.ready().then(function() { var dbInfo = self._dbInfo; var result; try { result = localStorage.key(n); } catch (error) { result = null; } // Remove the prefix from the key, if a key is found. if (result) { result = result.substring(dbInfo.keyPrefix.length); } return result; }); executeCallback(promise, callback); return promise; } function keys(callback) { var self = this; var promise = self.ready().then(function() { var dbInfo = self._dbInfo; var length = localStorage.length; var keys = []; for (var i = 0; i < length; i++) { if (localStorage.key(i).indexOf(dbInfo.keyPrefix) === 0) { keys.push(localStorage.key(i).substring(dbInfo.keyPrefix.length)); } } return keys; }); executeCallback(promise, callback); return promise; } // Supply the number of keys in the datastore to the callback function. function length(callback) { var self = this; var promise = self.keys().then(function(keys) { return keys.length; }); executeCallback(promise, callback); return promise; } // Remove an item from the store, nice and simple. function removeItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { window.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = self.ready().then(function() { var dbInfo = self._dbInfo; localStorage.removeItem(dbInfo.keyPrefix + key); }); executeCallback(promise, callback); return promise; } // Set a key's value and run an optional callback once the value is set. // Unlike Gaia's implementation, the callback function is passed the value, // in case you want to operate on that value only after you're sure it // saved, or something like that. function setItem(key, value, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { window.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = self.ready().then(function() { // Convert undefined values to null. // https://github.com/mozilla/localForage/pull/42 if (value === undefined) { value = null; } // Save the original value to pass to the callback. var originalValue = value; return new Promise(function(resolve, reject) { serializer.serialize(value, function(value, error) { if (error) { reject(error); } else { try { var dbInfo = self._dbInfo; localStorage.setItem(dbInfo.keyPrefix + key, value); resolve(originalValue); } catch (e) { // localStorage capacity exceeded. // TODO: Make this a specific error/event. if (e.name === 'QuotaExceededError' || e.name === 'NS_ERROR_DOM_QUOTA_REACHED') { reject(e); } reject(e); } } }); }); }); executeCallback(promise, callback); return promise; } function executeCallback(promise, callback) { if (callback) { promise.then(function(result) { callback(null, result); }, function(error) { callback(error); }); } } var localStorageWrapper = { _driver: 'localStorageWrapper', _initStorage: _initStorage, // Default API, from Gaia/localStorage. iterate: iterate, getItem: getItem, setItem: setItem, removeItem: removeItem, clear: clear, length: length, key: key, keys: keys }; if (moduleType === ModuleType.EXPORT) { module.exports = localStorageWrapper; } else if (moduleType === ModuleType.DEFINE) { define('localStorageWrapper', function() { return localStorageWrapper; }); } else { this.localStorageWrapper = localStorageWrapper; } }).call(window); },{"./../utils/serializer":39,"promise":33}],37:[function(_dereq_,module,exports){ /* * Includes code from: * * base64-arraybuffer * https://github.com/niklasvh/base64-arraybuffer * * Copyright (c) 2012 Niklas von Hertzen * Licensed under the MIT license. */ (function() { 'use strict'; // Promises! var Promise = (typeof module !== 'undefined' && module.exports) ? _dereq_('promise') : this.Promise; var globalObject = this; var serializer = null; var openDatabase = this.openDatabase; // If WebSQL methods aren't available, we can stop now. if (!openDatabase) { return; } var ModuleType = { DEFINE: 1, EXPORT: 2, WINDOW: 3 }; // Attaching to window (i.e. no module loader) is the assumed, // simple default. var moduleType = ModuleType.WINDOW; // Find out what kind of module setup we have; if none, we'll just attach // localForage to the main window. if (typeof module !== 'undefined' && module.exports) { moduleType = ModuleType.EXPORT; } else if (typeof define === 'function' && define.amd) { moduleType = ModuleType.DEFINE; } // Open the WebSQL database (automatically creates one if one didn't // previously exist), using any options set in the config. function _initStorage(options) { var self = this; var dbInfo = { db: null }; if (options) { for (var i in options) { dbInfo[i] = typeof(options[i]) !== 'string' ? options[i].toString() : options[i]; } } var serializerPromise = new Promise(function(resolve/*, reject*/) { // We allow localForage to be declared as a module or as a // library available without AMD/require.js. if (moduleType === ModuleType.DEFINE) { _dereq_(['localforageSerializer'], resolve); } else if (moduleType === ModuleType.EXPORT) { // Making it browserify friendly resolve(_dereq_('./../utils/serializer')); } else { resolve(globalObject.localforageSerializer); } }); var dbInfoPromise = new Promise(function(resolve, reject) { // Open the database; the openDatabase API will automatically // create it for us if it doesn't exist. try { dbInfo.db = openDatabase(dbInfo.name, String(dbInfo.version), dbInfo.description, dbInfo.size); } catch (e) { return self.setDriver(self.LOCALSTORAGE).then(function() { return self._initStorage(options); }).then(resolve)['catch'](reject); } // Create our key/value table if it doesn't exist. dbInfo.db.transaction(function(t) { t.executeSql('CREATE TABLE IF NOT EXISTS ' + dbInfo.storeName + ' (id INTEGER PRIMARY KEY, key unique, value)', [], function() { self._dbInfo = dbInfo; resolve(); }, function(t, error) { reject(error); }); }); }); return serializerPromise.then(function(lib) { serializer = lib; return dbInfoPromise; }); } function getItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { window.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; dbInfo.db.transaction(function(t) { t.executeSql('SELECT * FROM ' + dbInfo.storeName + ' WHERE key = ? LIMIT 1', [key], function(t, results) { var result = results.rows.length ? results.rows.item(0).value : null; // Check to see if this is serialized content we need to // unpack. if (result) { result = serializer.deserialize(result); } resolve(result); }, function(t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } function iterate(iterator, callback) { var self = this; var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; dbInfo.db.transaction(function(t) { t.executeSql('SELECT * FROM ' + dbInfo.storeName, [], function(t, results) { var rows = results.rows; var length = rows.length; for (var i = 0; i < length; i++) { var item = rows.item(i); var result = item.value; // Check to see if this is serialized content // we need to unpack. if (result) { result = serializer.deserialize(result); } result = iterator(result, item.key, i + 1); // void(0) prevents problems with redefinition // of `undefined`. if (result !== void(0)) { resolve(result); return; } } resolve(); }, function(t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } function setItem(key, value, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { window.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function(resolve, reject) { self.ready().then(function() { // The localStorage API doesn't return undefined values in an // "expected" way, so undefined is always cast to null in all // drivers. See: https://github.com/mozilla/localForage/pull/42 if (value === undefined) { value = null; } // Save the original value to pass to the callback. var originalValue = value; serializer.serialize(value, function(value, error) { if (error) { reject(error); } else { var dbInfo = self._dbInfo; dbInfo.db.transaction(function(t) { t.executeSql('INSERT OR REPLACE INTO ' + dbInfo.storeName + ' (key, value) VALUES (?, ?)', [key, value], function() { resolve(originalValue); }, function(t, error) { reject(error); }); }, function(sqlError) { // The transaction failed; check // to see if it's a quota error. if (sqlError.code === sqlError.QUOTA_ERR) { // We reject the callback outright for now, but // it's worth trying to re-run the transaction. // Even if the user accepts the prompt to use // more storage on Safari, this error will // be called. // // TODO: Try to re-run the transaction. reject(sqlError); } }); } }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } function removeItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { window.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; dbInfo.db.transaction(function(t) { t.executeSql('DELETE FROM ' + dbInfo.storeName + ' WHERE key = ?', [key], function() { resolve(); }, function(t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } // Deletes every item in the table. // TODO: Find out if this resets the AUTO_INCREMENT number. function clear(callback) { var self = this; var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; dbInfo.db.transaction(function(t) { t.executeSql('DELETE FROM ' + dbInfo.storeName, [], function() { resolve(); }, function(t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } // Does a simple `COUNT(key)` to get the number of items stored in // localForage. function length(callback) { var self = this; var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; dbInfo.db.transaction(function(t) { // Ahhh, SQL makes this one soooooo easy. t.executeSql('SELECT COUNT(key) as c FROM ' + dbInfo.storeName, [], function(t, results) { var result = results.rows.item(0).c; resolve(result); }, function(t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } // Return the key located at key index X; essentially gets the key from a // `WHERE id = ?`. This is the most efficient way I can think to implement // this rarely-used (in my experience) part of the API, but it can seem // inconsistent, because we do `INSERT OR REPLACE INTO` on `setItem()`, so // the ID of each key will change every time it's updated. Perhaps a stored // procedure for the `setItem()` SQL would solve this problem? // TODO: Don't change ID on `setItem()`. function key(n, callback) { var self = this; var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; dbInfo.db.transaction(function(t) { t.executeSql('SELECT key FROM ' + dbInfo.storeName + ' WHERE id = ? LIMIT 1', [n + 1], function(t, results) { var result = results.rows.length ? results.rows.item(0).key : null; resolve(result); }, function(t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } function keys(callback) { var self = this; var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; dbInfo.db.transaction(function(t) { t.executeSql('SELECT key FROM ' + dbInfo.storeName, [], function(t, results) { var keys = []; for (var i = 0; i < results.rows.length; i++) { keys.push(results.rows.item(i).key); } resolve(keys); }, function(t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } function executeCallback(promise, callback) { if (callback) { promise.then(function(result) { callback(null, result); }, function(error) { callback(error); }); } } var webSQLStorage = { _driver: 'webSQLStorage', _initStorage: _initStorage, iterate: iterate, getItem: getItem, setItem: setItem, removeItem: removeItem, clear: clear, length: length, key: key, keys: keys }; if (moduleType === ModuleType.DEFINE) { define('webSQLStorage', function() { return webSQLStorage; }); } else if (moduleType === ModuleType.EXPORT) { module.exports = webSQLStorage; } else { this.webSQLStorage = webSQLStorage; } }).call(window); },{"./../utils/serializer":39,"promise":33}],38:[function(_dereq_,module,exports){ (function() { 'use strict'; // Promises! var Promise = (typeof module !== 'undefined' && module.exports) ? _dereq_('promise') : this.Promise; // Custom drivers are stored here when `defineDriver()` is called. // They are shared across all instances of localForage. var CustomDrivers = {}; var DriverType = { INDEXEDDB: 'asyncStorage', LOCALSTORAGE: 'localStorageWrapper', WEBSQL: 'webSQLStorage' }; var DefaultDriverOrder = [ DriverType.INDEXEDDB, DriverType.WEBSQL, DriverType.LOCALSTORAGE ]; var LibraryMethods = [ 'clear', 'getItem', 'iterate', 'key', 'keys', 'length', 'removeItem', 'setItem' ]; var ModuleType = { DEFINE: 1, EXPORT: 2, WINDOW: 3 }; var DefaultConfig = { description: '', driver: DefaultDriverOrder.slice(), name: 'localforage', // Default DB size is _JUST UNDER_ 5MB, as it's the highest size // we can use without a prompt. size: 4980736, storeName: 'keyvaluepairs', version: 1.0 }; // Attaching to window (i.e. no module loader) is the assumed, // simple default. var moduleType = ModuleType.WINDOW; // Find out what kind of module setup we have; if none, we'll just attach // localForage to the main window. if (typeof module !== 'undefined' && module.exports) { moduleType = ModuleType.EXPORT; } else if (typeof define === 'function' && define.amd) { moduleType = ModuleType.DEFINE; } // Check to see if IndexedDB is available and if it is the latest // implementation; it's our preferred backend library. We use "_spec_test" // as the name of the database because it's not the one we'll operate on, // but it's useful to make sure its using the right spec. // See: https://github.com/mozilla/localForage/issues/128 var driverSupport = (function(self) { // Initialize IndexedDB; fall back to vendor-prefixed versions // if needed. var indexedDB = indexedDB || self.indexedDB || self.webkitIndexedDB || self.mozIndexedDB || self.OIndexedDB || self.msIndexedDB; var result = {}; result[DriverType.WEBSQL] = !!self.openDatabase; result[DriverType.INDEXEDDB] = !!(function() { // We mimic PouchDB here; just UA test for Safari (which, as of // iOS 8/Yosemite, doesn't properly support IndexedDB). // IndexedDB support is broken and different from Blink's. // This is faster than the test case (and it's sync), so we just // do this. *SIGH* // http://bl.ocks.org/nolanlawson/raw/c83e9039edf2278047e9/ // // We test for openDatabase because IE Mobile identifies itself // as Safari. Oh the lulz... if (typeof self.openDatabase !== 'undefined' && self.navigator && self.navigator.userAgent && /Safari/.test(self.navigator.userAgent) && !/Chrome/.test(self.navigator.userAgent)) { return false; } try { return indexedDB && typeof indexedDB.open === 'function' && // Some Samsung/HTC Android 4.0-4.3 devices // have older IndexedDB specs; if this isn't available // their IndexedDB is too old for us to use. // (Replaces the onupgradeneeded test.) typeof self.IDBKeyRange !== 'undefined'; } catch (e) { return false; } })(); result[DriverType.LOCALSTORAGE] = !!(function() { try { return (self.localStorage && ('setItem' in self.localStorage) && (self.localStorage.setItem)); } catch (e) { return false; } })(); return result; })(this); var isArray = Array.isArray || function(arg) { return Object.prototype.toString.call(arg) === '[object Array]'; }; function callWhenReady(localForageInstance, libraryMethod) { localForageInstance[libraryMethod] = function() { var _args = arguments; return localForageInstance.ready().then(function() { return localForageInstance[libraryMethod].apply(localForageInstance, _args); }); }; } function extend() { for (var i = 1; i < arguments.length; i++) { var arg = arguments[i]; if (arg) { for (var key in arg) { if (arg.hasOwnProperty(key)) { if (isArray(arg[key])) { arguments[0][key] = arg[key].slice(); } else { arguments[0][key] = arg[key]; } } } } } return arguments[0]; } function isLibraryDriver(driverName) { for (var driver in DriverType) { if (DriverType.hasOwnProperty(driver) && DriverType[driver] === driverName) { return true; } } return false; } var globalObject = this; function LocalForage(options) { this._config = extend({}, DefaultConfig, options); this._driverSet = null; this._ready = false; this._dbInfo = null; // Add a stub for each driver API method that delays the call to the // corresponding driver method until localForage is ready. These stubs // will be replaced by the driver methods as soon as the driver is // loaded, so there is no performance impact. for (var i = 0; i < LibraryMethods.length; i++) { callWhenReady(this, LibraryMethods[i]); } this.setDriver(this._config.driver); } LocalForage.prototype.INDEXEDDB = DriverType.INDEXEDDB; LocalForage.prototype.LOCALSTORAGE = DriverType.LOCALSTORAGE; LocalForage.prototype.WEBSQL = DriverType.WEBSQL; // Set any config values for localForage; can be called anytime before // the first API call (e.g. `getItem`, `setItem`). // We loop through options so we don't overwrite existing config // values. LocalForage.prototype.config = function(options) { // If the options argument is an object, we use it to set values. // Otherwise, we return either a specified config value or all // config values. if (typeof(options) === 'object') { // If localforage is ready and fully initialized, we can't set // any new configuration values. Instead, we return an error. if (this._ready) { return new Error("Can't call config() after localforage " + 'has been used.'); } for (var i in options) { if (i === 'storeName') { options[i] = options[i].replace(/\W/g, '_'); } this._config[i] = options[i]; } // after all config options are set and // the driver option is used, try setting it if ('driver' in options && options.driver) { this.setDriver(this._config.driver); } return true; } else if (typeof(options) === 'string') { return this._config[options]; } else { return this._config; } }; // Used to define a custom driver, shared across all instances of // localForage. LocalForage.prototype.defineDriver = function(driverObject, callback, errorCallback) { var defineDriver = new Promise(function(resolve, reject) { try { var driverName = driverObject._driver; var complianceError = new Error( 'Custom driver not compliant; see ' + 'https://mozilla.github.io/localForage/#definedriver' ); var namingError = new Error( 'Custom driver name already in use: ' + driverObject._driver ); // A driver name should be defined and not overlap with the // library-defined, default drivers. if (!driverObject._driver) { reject(complianceError); return; } if (isLibraryDriver(driverObject._driver)) { reject(namingError); return; } var customDriverMethods = LibraryMethods.concat('_initStorage'); for (var i = 0; i < customDriverMethods.length; i++) { var customDriverMethod = customDriverMethods[i]; if (!customDriverMethod || !driverObject[customDriverMethod] || typeof driverObject[customDriverMethod] !== 'function') { reject(complianceError); return; } } var supportPromise = Promise.resolve(true); if ('_support' in driverObject) { if (driverObject._support && typeof driverObject._support === 'function') { supportPromise = driverObject._support(); } else { supportPromise = Promise.resolve(!!driverObject._support); } } supportPromise.then(function(supportResult) { driverSupport[driverName] = supportResult; CustomDrivers[driverName] = driverObject; resolve(); }, reject); } catch (e) { reject(e); } }); defineDriver.then(callback, errorCallback); return defineDriver; }; LocalForage.prototype.driver = function() { return this._driver || null; }; LocalForage.prototype.ready = function(callback) { var self = this; var ready = new Promise(function(resolve, reject) { self._driverSet.then(function() { if (self._ready === null) { self._ready = self._initStorage(self._config); } self._ready.then(resolve, reject); })['catch'](reject); }); ready.then(callback, callback); return ready; }; LocalForage.prototype.setDriver = function(drivers, callback, errorCallback) { var self = this; if (typeof drivers === 'string') { drivers = [drivers]; } this._driverSet = new Promise(function(resolve, reject) { var driverName = self._getFirstSupportedDriver(drivers); var error = new Error('No available storage method found.'); if (!driverName) { self._driverSet = Promise.reject(error); reject(error); return; } self._dbInfo = null; self._ready = null; if (isLibraryDriver(driverName)) { // We allow localForage to be declared as a module or as a // library available without AMD/require.js. if (moduleType === ModuleType.DEFINE) { _dereq_([driverName], function(lib) { self._extend(lib); resolve(); }); return; } else if (moduleType === ModuleType.EXPORT) { // Making it browserify friendly var driver; switch (driverName) { case self.INDEXEDDB: driver = _dereq_('./drivers/indexeddb'); break; case self.LOCALSTORAGE: driver = _dereq_('./drivers/localstorage'); break; case self.WEBSQL: driver = _dereq_('./drivers/websql'); } self._extend(driver); } else { self._extend(globalObject[driverName]); } } else if (CustomDrivers[driverName]) { self._extend(CustomDrivers[driverName]); } else { self._driverSet = Promise.reject(error); reject(error); return; } resolve(); }); function setDriverToConfig() { self._config.driver = self.driver(); } this._driverSet.then(setDriverToConfig, setDriverToConfig); this._driverSet.then(callback, errorCallback); return this._driverSet; }; LocalForage.prototype.supports = function(driverName) { return !!driverSupport[driverName]; }; LocalForage.prototype._extend = function(libraryMethodsAndProperties) { extend(this, libraryMethodsAndProperties); }; // Used to determine which driver we should use as the backend for this // instance of localForage. LocalForage.prototype._getFirstSupportedDriver = function(drivers) { if (drivers && isArray(drivers)) { for (var i = 0; i < drivers.length; i++) { var driver = drivers[i]; if (this.supports(driver)) { return driver; } } } return null; }; LocalForage.prototype.createInstance = function(options) { return new LocalForage(options); }; // The actual localForage object that we expose as a module or via a // global. It's extended by pulling in one of our other libraries. var localForage = new LocalForage(); // We allow localForage to be declared as a module or as a library // available without AMD/require.js. if (moduleType === ModuleType.DEFINE) { define('localforage', function() { return localForage; }); } else if (moduleType === ModuleType.EXPORT) { module.exports = localForage; } else { this.localforage = localForage; } }).call(window); },{"./drivers/indexeddb":35,"./drivers/localstorage":36,"./drivers/websql":37,"promise":33}],39:[function(_dereq_,module,exports){ (function() { 'use strict'; // Sadly, the best way to save binary data in WebSQL/localStorage is serializing // it to Base64, so this is how we store it to prevent very strange errors with less // verbose ways of binary <-> string data storage. var BASE_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; var SERIALIZED_MARKER = '__lfsc__:'; var SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER.length; // OMG the serializations! var TYPE_ARRAYBUFFER = 'arbf'; var TYPE_BLOB = 'blob'; var TYPE_INT8ARRAY = 'si08'; var TYPE_UINT8ARRAY = 'ui08'; var TYPE_UINT8CLAMPEDARRAY = 'uic8'; var TYPE_INT16ARRAY = 'si16'; var TYPE_INT32ARRAY = 'si32'; var TYPE_UINT16ARRAY = 'ur16'; var TYPE_UINT32ARRAY = 'ui32'; var TYPE_FLOAT32ARRAY = 'fl32'; var TYPE_FLOAT64ARRAY = 'fl64'; var TYPE_SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER_LENGTH + TYPE_ARRAYBUFFER.length; // Serialize a value, afterwards executing a callback (which usually // instructs the `setItem()` callback/promise to be executed). This is how // we store binary data with localStorage. function serialize(value, callback) { var valueString = ''; if (value) { valueString = value.toString(); } // Cannot use `value instanceof ArrayBuffer` or such here, as these // checks fail when running the tests using casper.js... // // TODO: See why those tests fail and use a better solution. if (value && (value.toString() === '[object ArrayBuffer]' || value.buffer && value.buffer.toString() === '[object ArrayBuffer]')) { // Convert binary arrays to a string and prefix the string with // a special marker. var buffer; var marker = SERIALIZED_MARKER; if (value instanceof ArrayBuffer) { buffer = value; marker += TYPE_ARRAYBUFFER; } else { buffer = value.buffer; if (valueString === '[object Int8Array]') { marker += TYPE_INT8ARRAY; } else if (valueString === '[object Uint8Array]') { marker += TYPE_UINT8ARRAY; } else if (valueString === '[object Uint8ClampedArray]') { marker += TYPE_UINT8CLAMPEDARRAY; } else if (valueString === '[object Int16Array]') { marker += TYPE_INT16ARRAY; } else if (valueString === '[object Uint16Array]') { marker += TYPE_UINT16ARRAY; } else if (valueString === '[object Int32Array]') { marker += TYPE_INT32ARRAY; } else if (valueString === '[object Uint32Array]') { marker += TYPE_UINT32ARRAY; } else if (valueString === '[object Float32Array]') { marker += TYPE_FLOAT32ARRAY; } else if (valueString === '[object Float64Array]') { marker += TYPE_FLOAT64ARRAY; } else { callback(new Error('Failed to get type for BinaryArray')); } } callback(marker + bufferToString(buffer)); } else if (valueString === '[object Blob]') { // Conver the blob to a binaryArray and then to a string. var fileReader = new FileReader(); fileReader.onload = function() { var str = bufferToString(this.result); callback(SERIALIZED_MARKER + TYPE_BLOB + str); }; fileReader.readAsArrayBuffer(value); } else { try { callback(JSON.stringify(value)); } catch (e) { window.console.error("Couldn't convert value into a JSON " + 'string: ', value); callback(null, e); } } } // Deserialize data we've inserted into a value column/field. We place // special markers into our strings to mark them as encoded; this isn't // as nice as a meta field, but it's the only sane thing we can do whilst // keeping localStorage support intact. // // Oftentimes this will just deserialize JSON content, but if we have a // special marker (SERIALIZED_MARKER, defined above), we will extract // some kind of arraybuffer/binary data/typed array out of the string. function deserialize(value) { // If we haven't marked this string as being specially serialized (i.e. // something other than serialized JSON), we can just return it and be // done with it. if (value.substring(0, SERIALIZED_MARKER_LENGTH) !== SERIALIZED_MARKER) { return JSON.parse(value); } // The following code deals with deserializing some kind of Blob or // TypedArray. First we separate out the type of data we're dealing // with from the data itself. var serializedString = value.substring(TYPE_SERIALIZED_MARKER_LENGTH); var type = value.substring(SERIALIZED_MARKER_LENGTH, TYPE_SERIALIZED_MARKER_LENGTH); var buffer = stringToBuffer(serializedString); // Return the right type based on the code/type set during // serialization. switch (type) { case TYPE_ARRAYBUFFER: return buffer; case TYPE_BLOB: return new Blob([buffer]); case TYPE_INT8ARRAY: return new Int8Array(buffer); case TYPE_UINT8ARRAY: return new Uint8Array(buffer); case TYPE_UINT8CLAMPEDARRAY: return new Uint8ClampedArray(buffer); case TYPE_INT16ARRAY: return new Int16Array(buffer); case TYPE_UINT16ARRAY: return new Uint16Array(buffer); case TYPE_INT32ARRAY: return new Int32Array(buffer); case TYPE_UINT32ARRAY: return new Uint32Array(buffer); case TYPE_FLOAT32ARRAY: return new Float32Array(buffer); case TYPE_FLOAT64ARRAY: return new Float64Array(buffer); default: throw new Error('Unkown type: ' + type); } } function stringToBuffer(serializedString) { // Fill the string into a ArrayBuffer. var bufferLength = serializedString.length * 0.75; var len = serializedString.length; var i; var p = 0; var encoded1, encoded2, encoded3, encoded4; if (serializedString[serializedString.length - 1] === '=') { bufferLength--; if (serializedString[serializedString.length - 2] === '=') { bufferLength--; } } var buffer = new ArrayBuffer(bufferLength); var bytes = new Uint8Array(buffer); for (i = 0; i < len; i+=4) { encoded1 = BASE_CHARS.indexOf(serializedString[i]); encoded2 = BASE_CHARS.indexOf(serializedString[i+1]); encoded3 = BASE_CHARS.indexOf(serializedString[i+2]); encoded4 = BASE_CHARS.indexOf(serializedString[i+3]); /*jslint bitwise: true */ bytes[p++] = (encoded1 << 2) | (encoded2 >> 4); bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2); bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63); } return buffer; } // Converts a buffer to a string to store, serialized, in the backend // storage library. function bufferToString(buffer) { // base64-arraybuffer var bytes = new Uint8Array(buffer); var base64String = ''; var i; for (i = 0; i < bytes.length; i += 3) { /*jslint bitwise: true */ base64String += BASE_CHARS[bytes[i] >> 2]; base64String += BASE_CHARS[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)]; base64String += BASE_CHARS[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)]; base64String += BASE_CHARS[bytes[i + 2] & 63]; } if ((bytes.length % 3) === 2) { base64String = base64String.substring(0, base64String.length - 1) + '='; } else if (bytes.length % 3 === 1) { base64String = base64String.substring(0, base64String.length - 2) + '=='; } return base64String; } var localforageSerializer = { serialize: serialize, deserialize: deserialize, stringToBuffer: stringToBuffer, bufferToString: bufferToString }; if (typeof module !== 'undefined' && module.exports) { module.exports = localforageSerializer; } else if (typeof define === 'function' && define.amd) { define('localforageSerializer', function() { return localforageSerializer; }); } else { this.localforageSerializer = localforageSerializer; } }).call(window); },{}]},{},[1]);
bootcdn/cdnjs
ajax/libs/forerunnerdb/1.3.29/fdb-legacy.js
JavaScript
mit
346,425
/* Plugin Name: amCharts Data Loader Description: This plugin adds external data loading capabilities to all amCharts libraries. Author: Martynas Majeris, amCharts Version: 1.0.2 Author URI: http://www.amcharts.com/ Copyright 2015 amCharts 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. Please note that the above license covers only this plugin. It by all means does not apply to any other amCharts products that are covered by different licenses. */ /** * TODO: * incremental load * XML support (?) */ /** * Initialize language prompt container */ AmCharts.translations.dataLoader = {} /** * Set init handler */ AmCharts.addInitHandler( function ( chart ) { /** * Check if dataLoader is set (initialize it) */ if ( undefined === chart.dataLoader || ! isObject( chart.dataLoader ) ) chart.dataLoader = {}; /** * Check charts version for compatibility: * the first compatible version is 3.13 */ var version = chart.version.split( '.' ); if ( ( Number( version[0] ) < 3 ) || ( 3 == Number( version[0] ) && ( Number( version[1] ) < 13 ) ) ) return; /** * Define object reference for easy access */ var l = chart.dataLoader; l.remaining = 0; /** * Set defaults */ var defaults = { 'async': true, 'format': 'json', 'showErrors': true, 'showCurtain': true, 'noStyles': false, 'reload': 0, 'timestamp': false, 'delimiter': ',', 'skip': 0, 'useColumnNames': false, 'reverse': false, 'reloading': false, 'complete': false, 'error': false }; /** * Load all files in a row */ if ( 'stock' === chart.type ) { // delay this a little bit so the chart has the chance to build itself setTimeout( function () { // preserve animation if ( 0 > chart.panelsSettings.startDuration ) { l.startDuration = chart.panelsSettings.startDuration; chart.panelsSettings.startDuration = 0; } // cycle through all of the data sets for ( var x = 0; x < chart.dataSets.length; x++ ) { var ds = chart.dataSets[ x ]; // load data if ( undefined !== ds.dataLoader && undefined !== ds.dataLoader.url ) { ds.dataProvider = []; applyDefaults( ds.dataLoader ); loadFile( ds.dataLoader.url, ds, ds.dataLoader, 'dataProvider' ); } // load events data if ( undefined !== ds.eventDataLoader && undefined !== ds.eventDataLoader.url ) { ds.events = []; applyDefaults( ds.eventDataLoader ); loadFile( ds.eventDataLoader.url, ds, ds.eventDataLoader, 'stockEvents' ); } } }, 100 ); } else { applyDefaults( l ); if ( undefined === l.url ) return; // preserve animation if ( undefined !== chart.startDuration && ( 0 < chart.startDuration ) ) { l.startDuration = chart.startDuration; chart.startDuration = 0; } chart.dataProvider = []; loadFile( l.url, chart, l, 'dataProvider' ); } /** * Loads a file and determines correct parsing mechanism for it */ function loadFile( url, holder, options, providerKey ) { // set default providerKey if ( undefined === providerKey ) providerKey = 'dataProvider'; // show curtain if ( options.showCurtain ) showCurtain( undefined, options.noStyles ); // increment loader count l.remaining++; // load the file AmCharts.loadFile( url, options, function ( response ) { // error? if ( false === response ) { callFunction( options.error, url, options ); raiseError( AmCharts.__( 'Error loading the file', chart.language ) + ': ' + url, false, options ); } else { // determine the format if ( undefined === options.format ) { // TODO options.format = 'json'; } // lowercase options.format = options.format.toLowerCase(); // invoke parsing function switch( options.format ) { case 'json': holder[providerKey] = AmCharts.parseJSON( response, options ); if ( false === holder[providerKey] ) { callFunction( options.error, options ); raiseError( AmCharts.__( 'Error parsing JSON file', chart.language ) + ': ' + l.url, false, options ); holder[providerKey] = []; return; } else { holder[providerKey] = postprocess( holder[providerKey], options ); callFunction( options.load, options ); } break; case 'csv': holder[providerKey] = AmCharts.parseCSV( response, options ); if ( false === holder[providerKey] ) { callFunction( options.error, options ); raiseError( AmCharts.__( 'Error parsing CSV file', chart.language ) + ': ' + l.url, false, options ); holder[providerKey] = []; return; } else { holder[providerKey] = postprocess( holder[providerKey], options ); callFunction( options.load, options ); } break; default: callFunction( options.error, options ); raiseError( AmCharts.__( 'Unsupported data format', chart.language ) + ': ' + options.format, false, options.noStyles ); return; break; } // decrement remaining counter l.remaining--; // we done? if ( 0 === l.remaining ) { // callback callFunction( options.complete ); // take in the new data if ( options.async ) { if ( 'map' === chart.type ) chart.validateNow( true ); else { // take in new data chart.validateData(); // make the chart animate again if ( l.startDuration ) { if ( 'stock' === chart.type ) { chart.panelsSettings.startDuration = l.startDuration; for ( var x = 0; x < chart.panels.length; x++ ) { chart.panels[x].startDuration = l.startDuration; chart.panels[x].animateAgain(); } } else { chart.startDuration = l.startDuration; chart.animateAgain(); } } } } // restore default period if ( 'stock' === chart.type && ! options.reloading ) chart.periodSelector.setDefaultPeriod(); // remove curtain removeCurtain(); } // schedule another load of necessary if ( options.reload ) { if ( options.timeout ) clearTimeout( options.timeout ); options.timeout = setTimeout( loadFile, 1000 * options.reload, url, holder, options ); options.reloading = true; } } } ); } /** * Checks if postProcess is set and invokes the handler */ function postprocess ( data, options ) { if ( undefined !== options.postProcess && isFunction( options.postProcess ) ) try { return options.postProcess.call( this, data, options ); } catch ( e ) { raiseError( AmCharts.__( 'Error loading file', chart.language ) + ': ' + options.url, false, options ); return data; } else return data; } /** * Returns true if argument is object */ function isArray ( obj ) { return obj instanceof Array; } /** * Returns true if argument is array */ function isObject ( obj ) { return 'object' === typeof( obj ); } /** * Returns true is argument is a function */ function isFunction ( obj ) { return 'function' === typeof( obj ); } /** * Applies defaults to config object */ function applyDefaults ( obj ) { for ( var x = 0; x < defaults.length; x++ ) { setDefault( obj, x, defaults[ x ] ); } } /** * Checks if object property is set, sets with a default if it isn't */ function setDefault ( obj, key, value ) { if ( undefined === obj[ key ] ) obj[ key ] = value; } /** * Raises an internal error (writes it out to console) */ function raiseError ( msg, error, options ) { if ( options.showErrors ) showCurtain( msg, options.noStyles ); else { removeCurtain(); console.log( msg ); } } /** * Shows curtain over chart area */ function showCurtain ( msg, noStyles ) { // remove previous curtain if there is one removeCurtain(); // did we pass in the message? if ( undefined === msg ) msg = AmCharts.__( 'Loading data...', chart.language ); // create and populate curtain element var curtain =document.createElement( 'div' ); curtain.setAttribute( 'id', chart.div.id + '-curtain' ); curtain.className = 'amcharts-dataloader-curtain'; if ( true !== noStyles ) { curtain.style.position = 'absolute'; curtain.style.top = 0; curtain.style.left = 0; curtain.style.width = ( undefined !== chart.realWidth ? chart.realWidth : chart.divRealWidth ) + 'px'; curtain.style.height = ( undefined !== chart.realHeight ? chart.realHeight : chart.divRealHeight ) + 'px'; curtain.style.textAlign = 'center'; curtain.style.display = 'table'; curtain.style.fontSize = '20px'; curtain.style.background = 'rgba(255, 255, 255, 0.3)'; curtain.innerHTML = '<div style="display: table-cell; vertical-align: middle;">' + msg + '</div>'; } else { curtain.innerHTML = msg; } chart.containerDiv.appendChild( curtain ); l.curtain = curtain; } /** * Removes the curtain */ function removeCurtain () { try { if ( undefined !== l.curtain ) chart.containerDiv.removeChild( l.curtain ); } catch ( e ) { // do nothing } l.curtain = undefined; } /** * Execute callback function */ function callFunction ( func, param1, param2 ) { if ( 'function' === typeof func ) func.call( l, param1, param2 ); } }, [ 'pie', 'serial', 'xy', 'funnel', 'radar', 'gauge', 'gantt', 'stock', 'map' ] ); /** * Returns prompt in a chart language (set by chart.language) if it is * available */ if ( undefined === AmCharts.__ ) { AmCharts.__ = function ( msg, language ) { if ( undefined !== language && undefined !== AmCharts.translations.dataLoader[ chart.language ] && undefined !== AmCharts.translations.dataLoader[ chart.language ][ msg ] ) return AmCharts.translations.dataLoader[ chart.language ][ msg ]; else return msg; } } /** * Loads a file from url and calls function handler with the result */ AmCharts.loadFile = function ( url, options, handler ) { // create the request if ( window.XMLHttpRequest ) { // IE7+, Firefox, Chrome, Opera, Safari var request = new XMLHttpRequest(); } else { // code for IE6, IE5 var request = new ActiveXObject( 'Microsoft.XMLHTTP' ); } // set handler for data if async loading request.onreadystatechange = function () { if ( 4 == request.readyState && 404 == request.status ) handler.call( this, false ); else if ( 4 == request.readyState && 200 == request.status ) handler.call( this, request.responseText ); } // load the file try { request.open( 'GET', options.timestamp ? AmCharts.timestampUrl( url ) : url, options.async ); request.send(); } catch ( e ) { handler.call( this, false ); } }; /** * Parses JSON string into an object */ AmCharts.parseJSON = function ( response, options ) { try { if ( undefined !== JSON ) return JSON.parse( response ); else return eval( response ); } catch ( e ) { return false; } } /** * Prases CSV string into an object */ AmCharts.parseCSV = function ( response, options ) { // parse CSV into array var data = AmCharts.CSVToArray( response, options.delimiter ); // init resuling array var res = []; var cols = []; // first row holds column names? if ( options.useColumnNames ) { cols = data.shift(); // normalize column names for ( var x = 0; x < cols.length; x++ ) { // trim var col = cols[ x ].replace( /^\s+|\s+$/gm, '' ); // check for empty if ( '' === col ) col = 'col' + x; cols[ x ] = col; } if ( 0 < options.skip ) options.skip--; } // skip rows for ( var i = 0; i < options.skip; i++ ) data.shift(); // iterate through the result set var row; while ( row = options.reverse ? data.pop() : data.shift() ) { var dataPoint = {}; for ( var i = 0; i < row.length; i++ ) { var col = undefined === cols[ i ] ? 'col' + i : cols[ i ]; dataPoint[ col ] = row[ i ]; } res.push( dataPoint ); } return res; } /** * Parses CSV data into array * Taken from here: (thanks!) * http://www.bennadel.com/blog/1504-ask-ben-parsing-csv-strings-with-javascript-exec-regular-expression-command.htm */ AmCharts.CSVToArray = function ( strData, strDelimiter ){ // Check to see if the delimiter is defined. If not, // then default to comma. strDelimiter = (strDelimiter || ","); // Create a regular expression to parse the CSV values. var objPattern = new RegExp( ( // Delimiters. "(\\" + strDelimiter + "|\\r?\\n|\\r|^)" + // Quoted fields. "(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" + // Standard fields. "([^\"\\" + strDelimiter + "\\r\\n]*))" ), "gi" ); // Create an array to hold our data. Give the array // a default empty first row. var arrData = [[]]; // Create an array to hold our individual pattern // matching groups. var arrMatches = null; // Keep looping over the regular expression matches // until we can no longer find a match. while (arrMatches = objPattern.exec( strData )){ // Get the delimiter that was found. var strMatchedDelimiter = arrMatches[ 1 ]; // Check to see if the given delimiter has a length // (is not the start of string) and if it matches // field delimiter. If id does not, then we know // that this delimiter is a row delimiter. if ( strMatchedDelimiter.length && (strMatchedDelimiter != strDelimiter) ){ // Since we have reached a new row of data, // add an empty row to our data array. arrData.push( [] ); } // Now that we have our delimiter out of the way, // let's check to see which kind of value we // captured (quoted or unquoted). if (arrMatches[ 2 ]){ // We found a quoted value. When we capture // this value, unescape any double quotes. var strMatchedValue = arrMatches[ 2 ].replace( new RegExp( "\"\"", "g" ), "\"" ); } else { // We found a non-quoted value. var strMatchedValue = arrMatches[ 3 ]; } // Now that we have our value string, let's add // it to the data array. arrData[ arrData.length - 1 ].push( strMatchedValue ); } // Return the parsed data. return( arrData ); } /** * Appends timestamp to the url */ AmCharts.timestampUrl = function ( url ) { var p = url.split( '?' ); if ( 1 === p.length ) p[1] = new Date().getTime(); else p[1] += '&' + new Date().getTime(); return p.join( '?' ); }
abhikalotra/Salon-Solutions
theme/backend/assets/global/plugins/amcharts/ammap/plugins/dataloader/dataloader.js
JavaScript
mit
16,824
loadIonicon('<svg xmlns="http://www.w3.org/2000/svg" width="512" height="512" viewBox="0 0 512 512"><path d="M64 64v384h384V64H64zm80 304c-8.836 0-16-7.164-16-16s7.164-16 16-16 16 7.164 16 16-7.164 16-16 16zm0-96c-8.836 0-16-7.164-16-16s7.164-16 16-16 16 7.164 16 16-7.164 16-16 16zm0-96c-8.836 0-16-7.164-16-16s7.164-16 16-16 16 7.164 16 16-7.164 16-16 16zm240 184H192v-16h192v16zm0-96H192v-16h192v16zm0-96H192v-16h192v16z"/></svg>','ios-list-box');
holtkamp/cdnjs
ajax/libs/ionicons/4.0.0-5/ionicons/svg/ios-list-box.js
JavaScript
mit
450
module("Options"); (function () { test("classPrefix", function () { /* Initialization */ $('#t').append('<img id="test-img" src="data/elephant.jpg" />'); stop(); $('#test-img').imgAreaSelect({ classPrefix: 'test', x1: 50, y1: 50, x2: 150, y2: 150, onInit: function (img, selection) { ok($('.test-selection').length == 1, 'Check if there is one element with the class ' + '"test-selection"'); $('#test-img').imgAreaSelect({ handles: true }); ok($('.test-handle').length == 8, 'Check if the added handle elements have the class ' + '"test-handle"'); /* Cleanup */ $('#test-img').imgAreaSelect({ remove: true }); testCleanup(); start(); } }); }); test("handles", function () { /* Initialization */ $('#t').append('<img id="test-img" src="data/elephant.jpg" />'); stop(); $('#test-img').imgAreaSelect({ x1: 50, y1: 50, x2: 150, y2: 150, handles: true, onInit: function (img, selection) { ok($('.imgareaselect-handle:visible').length == 8, 'Check if eight handles are visible with "handles: true"'); var imgLeft = Math.round($('#test-img').offset().left), imgTop = Math.round($('#test-img').offset().top); deepEqual([ $(".imgareaselect-handle").eq(0).offset(), $(".imgareaselect-handle").eq(2).offset() ], [ { left: imgLeft + 50, top: imgTop + 50 }, { left: imgLeft + 150 - 5 - 2, top: imgTop + 150 - 5 - 2 } ], 'Check if the handles are positioned correctly'); $('#test-img').imgAreaSelect({ handles: 'corners', show: true }); ok($('.imgareaselect-handle:visible').length == 4, 'Check if four handles are visible with "handles: \'corners\'"'); $('#test-img').imgAreaSelect({ handles: false, show: true }); ok($('.imgareaselect-handle').length == 0, 'Check if no handles are present with "handles: false"'); /* Cleanup */ $('#test-img').imgAreaSelect({ remove: true }); testCleanup(); start(); } }); }); test("imageWidth/imageHeight", function () { /* Initialization */ $('#t').append('<img id="test-img" src="data/elephant.jpg" ' + 'style="width: 160px; height: 100px;" />'); stop(); $('#test-img').imgAreaSelect({ imageWidth: 320, imageHeight: 200, onInit: function (img, selection) { var x = $(img).offset().left - $(document).scrollLeft(), y = $(img).offset().top - $(document).scrollTop(); /* Simulate selecting a 30x30 pixels area */ $(img).simulate("mousedown", { clientX: x + 10, clientY: y + 10 }); $(img).simulate("mousemove", { clientX: x + 40, clientY: y + 40 }); $(img).simulate("mousemove", { clientX: x + 40, clientY: y + 40 }); $(img).simulate("mouseup", { clientX: x + 40, clientY: y + 40 }); var selection = $(img).imgAreaSelect({ instance: true }) .getSelection(); deepEqual([ selection.width, selection.height ], [ 60, 60 ], "Check " + "if the selected area has the correct dimensions"); deepEqual([ $('.imgareaselect-selection').width(), $('.imgareaselect-selection').height() ], [ 30, 30 ], "Check if the selection area div element has the correct " + "dimensions"); $(img).imgAreaSelect({ instance: true }).cancelSelection(); /* Simulate selecting the whole image */ $(img).simulate("mousemove", { clientX: x, clientY: y }); $(img).simulate("mousedown", { clientX: x, clientY: y }); $(img).simulate("mousemove", { clientX: x + 160, clientY: y + 100 }); $(img).simulate("mousemove", { clientX: x + 160, clientY: y + 100 }); $(img).simulate("mouseup", { clientX: x + 160, clientY: y + 100 }); selection = $(img).imgAreaSelect({ instance: true }).getSelection(); deepEqual([ selection.width, selection.height ], [ 320, 200 ], "Check " + "if the selected area has the correct dimensions"); deepEqual([ $('.imgareaselect-selection').width(), $('.imgareaselect-selection').height() ], [ 160, 100 ], "Check if the selection area div element has the correct " + "dimensions"); /* Cleanup */ $('#test-img').imgAreaSelect({ remove: true }); testCleanup(); start(); } }); }); test("minWidth/minHeight", function () { /* Initialization */ $('#t').append('<img id="test-img" src="data/elephant.jpg" />'); stop(); $('#test-img').imgAreaSelect({ minWidth: 50, minHeight: 50, onInit: function (img, selection) { var x = $(img).offset().left - $(document).scrollLeft(), y = $(img).offset().top - $(document).scrollTop(); /* Simulate selecting a 10x10 pixels area */ $(img).simulate("mousedown", { clientX: x + 10, clientY: y + 10 }); $(img).simulate("mousemove", { clientX: x + 20, clientY: y + 20 }); $(img).simulate("mousemove", { clientX: x + 20, clientY: y + 20 }); $(img).simulate("mouseup", { clientX: x + 20, clientY: y + 20 }); var selection = $(img).imgAreaSelect({ instance: true }) .getSelection(); deepEqual([ selection.width, selection.height ], [ 50, 50 ], "Check " + "if the selected area has the specified minimum " + "dimensions"); /* Cleanup */ $('#test-img').imgAreaSelect({ remove: true }); testCleanup(); start(); } }); }); test("maxWidth/maxHeight", function () { /* Initialization */ $('#t').append('<img id="test-img" src="data/elephant.jpg" />'); stop(); $('#test-img').imgAreaSelect({ maxWidth: 100, maxHeight: 100, onInit: function (img, selection) { var x = $(img).offset().left - $(document).scrollLeft(), y = $(img).offset().top - $(document).scrollTop(); /* Simulate selecting a 140x140 pixels area */ $(img).simulate("mousedown", { clientX: x + 10, clientY: y + 10 }); $(img).simulate("mousemove", { clientX: x + 150, clientY: y + 150 }); $(img).simulate("mousemove", { clientX: x + 150, clientY: y + 150 }); $(img).simulate("mouseup", { clientX: x + 150, clientY: y + 150 }); var selection = $(img).imgAreaSelect({ instance: true }) .getSelection(); deepEqual([ selection.width, selection.height ], [ 100, 100 ], "Check " + "if the selected area has the specified maximum " + "dimensions"); /* Cleanup */ $('#test-img').imgAreaSelect({ remove: true }); testCleanup(); start(); } }); }); test("minWidth/minHeight with scaling", function () { /* Initialization */ $('#t').append('<img id="test-img" src="data/elephant.jpg" ' + 'style="width: 640px; height: 400px;" />'); stop(); $('#test-img').imgAreaSelect({ minWidth: 50, minHeight: 50, imageWidth: 320, imageHeight: 200, onInit: function (img, selection) { var x = $(img).offset().left - $(document).scrollLeft(), y = $(img).offset().top - $(document).scrollTop(); /* Simulate selecting a 10x10 pixels area */ $(img).simulate("mousedown", { clientX: x + 10, clientY: y + 10 }); $(img).simulate("mousemove", { clientX: x + 20, clientY: y + 20 }); $(img).simulate("mousemove", { clientX: x + 20, clientY: y + 20 }); $(img).simulate("mouseup", { clientX: x + 20, clientY: y + 20 }); var selection = $(img).imgAreaSelect({ instance: true }) .getSelection(); deepEqual([ selection.width, selection.height ], [ 50, 50 ], "Check " + "if the selected area has the specified minimum " + "dimensions"); deepEqual([ $('.imgareaselect-selection').width(), $('.imgareaselect-selection').height() ], [ 100, 100 ], "Check if the selection area div element has the correct " + "dimensions"); /* Cleanup */ $('#test-img').imgAreaSelect({ remove: true }); testCleanup(); start(); } }); }); test("maxWidth/maxHeight with scaling", function () { /* Initialization */ $('#t').append('<img id="test-img" src="data/elephant.jpg" ' + 'style="width: 160px; height: 100px;" />'); stop(); $('#test-img').imgAreaSelect({ maxWidth: 100, maxHeight: 100, imageWidth: 320, imageHeight: 200, onInit: function (img, selection) { var x = $(img).offset().left - $(document).scrollLeft(), y = $(img).offset().top - $(document).scrollTop(); /* Simulate selecting a 80x80 pixels area */ $(img).simulate("mousedown", { clientX: x + 10, clientY: y + 10 }); $(img).simulate("mousemove", { clientX: x + 90, clientY: y + 90 }); $(img).simulate("mousemove", { clientX: x + 90, clientY: y + 90 }); $(img).simulate("mouseup", { clientX: x + 90, clientY: y + 90 }); var selection = $(img).imgAreaSelect({ instance: true }) .getSelection(); deepEqual([ selection.width, selection.height ], [ 100, 100 ], "Check " + "if the selected area has the specified maximum " + "dimensions"); deepEqual([ $('.imgareaselect-selection').width(), $('.imgareaselect-selection').height() ], [ 50, 50 ], "Check if the selection area div element has the correct " + "dimensions"); /* Cleanup */ $('#test-img').imgAreaSelect({ remove: true }); testCleanup(); start(); } }); }); test("movable", function () { /* Initialization */ $('#t').append('<img id="test-img" src="data/elephant.jpg" />'); stop(); var tryMove = function () { var eventDown = jQuery.Event('mousedown'), eventMove = jQuery.Event('mousemove'), eventUp = jQuery.Event('mouseup'); eventDown.which = eventUp.which = 1; var x = $('.imgareaselect-selection').offset().left, y = $('.imgareaselect-selection').offset().top; eventMove.pageX = eventDown.pageX = x + 25; eventMove.pageY = eventDown.pageY = y + 25; $('.imgareaselect-selection').trigger(eventMove); $('.imgareaselect-selection').trigger(eventDown); eventMove.pageX = eventUp.pageX = x; eventMove.pageY = eventUp.pageY = y; $('.imgareaselect-selection').trigger(eventMove); $('.imgareaselect-selection').trigger(eventUp); }; $('#test-img').imgAreaSelect({ x1: 50, y1: 50, x2: 150, y2: 150, show: true, onInit: function (img, selection) { tryMove(); var newSelection = $(img).imgAreaSelect({ instance: true }) .getSelection(); deepEqual(newSelection, { x1: 25, y1: 25, x2: 125, y2: 125, width: 100, height: 100 }, 'Check if the returned selection is correct after move'); setTimeout(function () { checkNotMovable(); }, 0); } }); var checkNotMovable = function () { $('#test-img').imgAreaSelect({ remove: true }); $('#test-img').imgAreaSelect({ x1: 50, y1: 50, x2: 150, y2: 150, movable: false, onInit: function (img, selection) { tryMove(); var newSelection = $(img).imgAreaSelect({ instance: true }) .getSelection(); deepEqual(newSelection, { x1: 50, y1: 50, x2: 150, y2: 150, width: 100, height: 100 }, 'Check if the returned selection is correct when ' + 'movable is set to false'); /* Cleanup */ $('#test-img').imgAreaSelect({ remove: true }); testCleanup(); start(); } }); }; }); test("parent", function () { /* Initialization */ $('#t').append('<div id="test-div">' + '<img id="test-img" src="data/elephant.jpg" /></div>'); stop(); $('#test-img').imgAreaSelect({ parent: '#test-div', x1: 10, y1: 10, x2: 20, y2: 20, onInit: function (img, selection) { equal($('.imgareaselect-selection').parent().parent().attr('id'), 'test-div', 'Check if the parent element is set correctly'); /* Cleanup */ $('#test-img').imgAreaSelect({ remove: true }); testCleanup(); start(); } }); }); test("persistent", function () { /* Initialization */ $('#t').append('<img id="test-img" src="data/elephant.jpg" />'); stop(); $('#test-img').imgAreaSelect({ x1: 50, y1: 50, x2: 150, y2: 150, persistent: true, onInit: function (img, selection) { var eventDown = jQuery.Event('mousedown'), eventUp = jQuery.Event('mouseup'); eventDown.which = eventUp.which = 1; $('.imgareaselect-outer').eq(0).trigger(eventDown); $('.imgareaselect-outer').eq(0).trigger(eventUp); ok($('.imgareaselect-selection').is(':visible'), 'persistent: Check if the selection remains visible ' + 'after the outer area is clicked and "persistent" is ' + 'true'); $('#test-img').imgAreaSelect({ persistent: false }); $('.imgareaselect-outer').eq(0).trigger(eventDown); $('.imgareaselect-outer').eq(0).trigger(eventUp); ok(!$('.imgareaselect-selection').is(':visible'), 'persistent: Check if the selection is no longer ' + 'visible after the outer area is clicked and ' + '"persistent" is false'); /* Cleanup */ $('#test-img').imgAreaSelect({ remove: true }); testCleanup(); start(); } }); }); test("resizable", function () { /* Initialization */ $('#t').append('<img id="test-img" src="data/elephant.jpg" />'); stop(); var tryResize = function () { var eventDown = jQuery.Event('mousedown'), eventMove = jQuery.Event('mousemove'), eventUp = jQuery.Event('mouseup'); eventDown.which = eventUp.which = 1; var x = $('.imgareaselect-selection').offset().left, y = $('.imgareaselect-selection').offset().top; eventMove.pageX = eventDown.pageX = x; eventMove.pageY = eventDown.pageY = y; $('.imgareaselect-selection').trigger(eventMove); $('.imgareaselect-selection').trigger(eventDown); eventMove.pageX = eventUp.pageX = x - 25; eventMove.pageY = eventUp.pageY = y - 25; $('.imgareaselect-selection').trigger(eventMove); $('.imgareaselect-selection').trigger(eventUp); }; $('#test-img').imgAreaSelect({ x1: 50, y1: 50, x2: 150, y2: 150, show: true, onInit: function (img, selection) { tryResize(); var newSelection = $(img).imgAreaSelect({ instance: true }) .getSelection(); deepEqual(newSelection, { x1: 25, y1: 25, x2: 150, y2: 150, width: 125, height: 125 }, 'Check if the returned selection is correct after resize'); setTimeout(function () { checkNotResizable(); }, 0); } }); var checkNotResizable = function () { $('#test-img').imgAreaSelect({ remove: true }); $('#test-img').imgAreaSelect({ x1: 50, y1: 50, x2: 150, y2: 150, resizable: false, onInit: function (img, selection) { tryResize(); var newSelection = $(img).imgAreaSelect({ instance: true }) .getSelection(); deepEqual(newSelection, { x1: 25, y1: 25, x2: 125, y2: 125, width: 100, height: 100 }, 'Check if the returned selection is correct when ' + 'resizable is set to false'); /* Cleanup */ $('#test-img').imgAreaSelect({ remove: true }); testCleanup(); start(); } }); }; }); test("resizeMargin", function () { /* Initialization */ $('#t').append('<img id="test-img" src="data/elephant.jpg" />'); stop(); $('#test-img').imgAreaSelect({ x1: 50, y1: 50, x2: 150, y2: 150, onInit: function (img, selection) { var eventMove = jQuery.Event('mousemove'), x = $('.imgareaselect-selection').offset().left, y = $('.imgareaselect-selection').offset().top; eventMove.pageX = x + 1; eventMove.pageY = y + 1; $('.imgareaselect-selection').trigger(eventMove); equal($('.imgareaselect-selection').parent().css('cursor'), 'nw-resize', 'Check if the resize mode is enabled when ' + 'the mouse cursor is within resizeMargin'); eventMove.pageX = x + 20; eventMove.pageY = y + 20; $('.imgareaselect-selection').trigger(eventMove); equal($('.imgareaselect-selection').parent().css('cursor'), 'move', 'Check if the resize mode is disabled when ' + 'the mouse cursor is not within resizeMargin'); /* Cleanup */ $('#test-img').imgAreaSelect({ remove: true }); testCleanup(); start(); } }); }); test("x1, y1, ...", function () { /* Initialization */ $('#t').append('<img id="test-img" src="data/elephant.jpg" />'); stop(); $('#test-img').imgAreaSelect({ x1: 50, y1: 50, x2: 150, y2: 150, persistent: true, onInit: function (img, selection) { ok($('.imgareaselect-selection').is(':visible'), 'Check if the selection area is visible upon initialization'); deepEqual({ x1: 50, y1: 50, x2: 150, y2: 150, width: 100, height: 100 }, selection, 'Check if the returned selection object is correct'); $('#test-img').imgAreaSelect({ remove: true }); testCleanup(); start(); } }); }); test("zIndex", function () { /* Initialization */ $('#t').append('<img id="test-img" src="data/elephant.jpg" \ style="position: relative; z-index: 50;" />'); stop(); $('#test-img').imgAreaSelect({ zIndex: 100, onInit: function (img, selection) { equal($('.imgareaselect-selection').parent().css('z-index'), 102, 'Check if the z-index value is correct'); /* Cleanup */ $('#test-img').imgAreaSelect({ remove: true }); testCleanup(); start(); } }); }); })();
angrycactus/dkan
webroot/profiles/dkan/libraries/jquery.imgareaselect/test/unit/options.js
JavaScript
gpl-2.0
20,730
/// <reference path="/umbraco_client/Application/NamespaceManager.js" /> /// <reference path="/umbraco_client/Application/HistoryManager.js" /> /// <reference path="/umbraco_client/ui/jquery.js" /> /// <reference path="/umbraco_client/Tree/UmbracoTree.js" /> /// <reference name="MicrosoftAjax.js"/> Umbraco.Sys.registerNamespace("Umbraco.Application"); (function($) { Umbraco.Application.ClientManager = function() { /// <summary> /// A class which ensures that all calls made to the objects that it owns are done in the context /// of the main Umbraco application window. /// </summary> return { _isDirty: false, _isDebug: false, _mainTree: null, _appActions: null, _historyMgr: null, _rootPath: "/umbraco", //this is the default _modal: new Array(), //track all modal window objects (they get stacked) historyManager: function() { if (!this._historyMgr) { this._historyMgr = new Umbraco.Controls.HistoryManager(); } return this._historyMgr; }, setUmbracoPath: function(strPath) { /// <summary> /// sets the Umbraco root path folder /// </summary> this._debug("setUmbracoPath: " + strPath); this._rootPath = strPath; }, mainWindow: function() { /// <summary> /// Returns a reference to the main frame of the application /// </summary> return top; }, mainTree: function() { /// <summary> /// Returns a reference to the main UmbracoTree API object. /// Sometimes an Umbraco page will need to be opened without being contained in the iFrame from the main window /// so this method is will construct a false tree to be returned if this is the case as to avoid errors. /// </summary> /// <returns type="Umbraco.Controls.UmbracoTree" /> if (this._mainTree == null) { this._mainTree = top.UmbClientMgr.mainTree(); } return this._mainTree; }, appActions: function() { /// <summary> /// Returns a reference to the application actions object /// </summary> //if the main window has no actions, we'll create some if (this._appActions == null) { if (typeof this.mainWindow().appActions == 'undefined') { this._appActions = new Umbraco.Application.Actions(); } else this._appActions = this.mainWindow().appActions; } return this._appActions; }, uiKeys: function() { /// <summary> /// Returns a reference to the main windows uiKeys object for globalization /// </summary> //TODO: If there is no main window, we need to go retrieve the appActions from the server! return this.mainWindow().uiKeys; }, // windowMgr: function() // return null; // }, contentFrameAndSection: function(app, rightFrameUrl) { //this.appActions().shiftApp(app, this.uiKeys()['sections_' + app]); var self = this; self.mainWindow().UmbClientMgr.historyManager().addHistory(app, true); window.setTimeout(function() { self.mainWindow().UmbClientMgr.contentFrame(rightFrameUrl); }, 200); }, contentFrame: function (strLocation) { /// <summary> /// This will return the reference to the right content frame if strLocation is null or empty, /// or set the right content frames location to the one specified by strLocation. /// </summary> this._debug("contentFrame: " + strLocation); if (strLocation == null || strLocation == "") { if (typeof this.mainWindow().right != "undefined") { return this.mainWindow().right; } else { return this.mainWindow(); //return the current window if the content frame doesn't exist in the current context } } else { //its a hash change so process that like angular if (strLocation.substr(0, 1) !== "#") { if (strLocation.substr(0, 1) != "/") { //if the path doesn't start with "/" or with the root path then //prepend the root path strLocation = this._rootPath + "/" + strLocation; } else if (strLocation.length >= this._rootPath.length && strLocation.substr(0, this._rootPath.length) != this._rootPath) { strLocation = this._rootPath + "/" + strLocation; } } this._debug("contentFrame: parsed location: " + strLocation); if (!this.mainWindow().UmbClientMgr) { window.setTimeout(function() { var self = this; self.mainWindow().location.href = strLocation; }, 200); } else { this.mainWindow().UmbClientMgr.contentFrame(strLocation); } } }, reloadContentFrameUrlIfPathLoaded: function (url) { var contentFrame; if (typeof this.mainWindow().right != "undefined") { contentFrame = this.mainWindow().right; } else { contentFrame = this.mainWindow(); } var currentPath = contentFrame.location.pathname + (contentFrame.location.search ? contentFrame.location.search : ""); if (currentPath == url) { contentFrame.location.reload(); } }, /** This is used to launch an angular based modal window instead of the legacy window */ openAngularModalWindow: function (options) { if (!this.mainWindow().UmbClientMgr) { throw "An angular modal window can only be launched when the modal is running within the main Umbraco application"; } else { this.mainWindow().UmbClientMgr.openAngularModalWindow.apply(this.mainWindow().UmbClientMgr, [options]); } }, /** This is used to launch an angular based modal window instead of the legacy window */ rootScope: function () { if (!this.mainWindow().UmbClientMgr) { throw "An angular modal window can only be launched when the modal is running within the main Umbraco application"; } else { return this.mainWindow().UmbClientMgr.rootScope(); } }, openModalWindow: function(url, name, showHeader, width, height, top, leftOffset, closeTriggers, onCloseCallback) { //need to create the modal on the top window if the top window has a client manager, if not, create it on the current window //if this is the top window, or if the top window doesn't have a client manager, create the modal in this manager if (window == this.mainWindow() || !this.mainWindow().UmbClientMgr) { var m = new Umbraco.Controls.ModalWindow(); this._modal.push(m); m.open(url, name, showHeader, width, height, top, leftOffset, closeTriggers, onCloseCallback); } else { //if the main window has a client manager, then call the main window's open modal method whilst keeping the context of it's manager. if (this.mainWindow().UmbClientMgr) { this.mainWindow().UmbClientMgr.openModalWindow.apply(this.mainWindow().UmbClientMgr, [url, name, showHeader, width, height, top, leftOffset, closeTriggers, onCloseCallback]); } else { return; //exit recurse. } } }, openModalWindowForContent: function (jQueryElement, name, showHeader, width, height, top, leftOffset, closeTriggers, onCloseCallback) { //need to create the modal on the top window if the top window has a client manager, if not, create it on the current window //if this is the top window, or if the top window doesn't have a client manager, create the modal in this manager if (window == this.mainWindow() || !this.mainWindow().UmbClientMgr) { var m = new Umbraco.Controls.ModalWindow(); this._modal.push(m); m.show(jQueryElement, name, showHeader, width, height, top, leftOffset, closeTriggers, onCloseCallback); } else { //if the main window has a client manager, then call the main window's open modal method whilst keeping the context of it's manager. if (this.mainWindow().UmbClientMgr) { this.mainWindow().UmbClientMgr.openModalWindowForContent.apply(this.mainWindow().UmbClientMgr, [jQueryElement, name, showHeader, width, height, top, leftOffset, closeTriggers, onCloseCallback]); } else { return; //exit recurse. } } }, closeModalWindow: function(rVal) { /// <summary> /// will close the latest open modal window. /// if an rVal is passed in, then this will be sent to the onCloseCallback method if it was specified. /// </summary> if (this._modal != null && this._modal.length > 0) { this._modal.pop().close(rVal); } else { //this will recursively try to close a modal window until the parent window has a modal object or the window is the top and has the modal object var mgr = null; if (window.parent == null || window.parent == window) { //we are at the root window, check if we can close the modal window from here if (window.UmbClientMgr != null && window.UmbClientMgr._modal != null && window.UmbClientMgr._modal.length > 0) { mgr = window.UmbClientMgr; } else { return; //exit recursion. } } else if (typeof window.parent.UmbClientMgr != "undefined") { mgr = window.parent.UmbClientMgr; } mgr.closeModalWindow.call(mgr, rVal); } }, _debug: function(strMsg) { if (this._isDebug) { Sys.Debug.trace("UmbClientMgr: " + strMsg); } }, get_isDirty: function() { return this._isDirty; }, set_isDirty: function(value) { this._isDirty = value; } }; }; })(jQuery); //define alias for use throughout application var UmbClientMgr = new Umbraco.Application.ClientManager();
khm1985/kennethhein.dk
umbraco_client/Application/UmbracoClientManager.js
JavaScript
mit
12,388
//// [constructorsWithSpecializedSignatures.ts] // errors declare class C { constructor(x: "hi"); constructor(x: "foo"); constructor(x: number); } // ok declare class C2 { constructor(x: "hi"); constructor(x: "foo"); constructor(x: string); } // errors class D { constructor(x: "hi"); constructor(x: "foo"); constructor(x: number); constructor(x: "hi") { } } // overloads are ok class D2 { constructor(x: "hi"); constructor(x: "foo"); constructor(x: string); constructor(x: "hi") { } // error } // errors interface I { new (x: "hi"); new (x: "foo"); new (x: number); } // ok interface I2 { new (x: "hi"); new (x: "foo"); new (x: string); } //// [constructorsWithSpecializedSignatures.js] // errors var D = (function () { function D(x) { } return D; })(); // overloads are ok var D2 = (function () { function D2(x) { } // error return D2; })();
yukulele/TypeScript
tests/baselines/reference/constructorsWithSpecializedSignatures.js
JavaScript
apache-2.0
970
/*! * froala_editor v1.1.8 (http://editor.froala.com) * Copyright 2014-2014 Froala */ /** * English spoken in Canada */ $.Editable.LANGS['en_ca'] = { translation: { "Bold": "Bold", "Italic": "Italic", "Underline": "Underline", "Strikethrough": "Strikethrough", "Font Size": "Font Size", "Color": "Colour", "Background Color": "Background Colour", "Text Color": "Text Colour", "Format Block": "Format Block", "Normal": "Normal", "Paragraph": "Paragraph", "Code": "Code", "Quote": "Quote", "Heading 1": "Heading 1", "Heading 2": "Heading 2", "Heading 3": "Heading 3", "Heading 4": "Heading 4", "Heading 5": "Heading 5", "Heading 6": "Heading 6", "Alignment": "Alignment", "Align Left": "Align Left", "Align Center": "Align Center", "Align Right": "Align Right", "Justify": "Justify", "Numbered List": "Numbered List", "Bulleted List": "Bulleted List", "Indent Less": "Indent Less", "Indent More": "Indent More", "Select All": "Select All", "Insert Link": "Insert Link", "Insert Image": "Insert Image", "Insert Video": "Insert Video", "Undo": "Undo", "Redo": "Redo", "Show HTML": "Show HTML", "Float Left": "Float Left", "Float None": "Float None", "Float Right": "Float Right", "Replace Image": "Replace Image", "Remove Image": "Remove Image", "Title": "Title", "Insert image": "Insert image", "Drop image": "Drop image", "or click": "or click", "Enter URL": "Enter URL", "Please wait!": "Please wait!", "Are you sure? Image will be deleted.": "Are you sure? Image will be deleted.", "UNLINK": "UNLINK", "Open in new tab": "Open in new tab", "Type something": "Type something", "Cancel": "Cancel", "OK": "OK", "Manage images": "Manage images", "Delete": "Delete", "Font Family": "Font Family", "Insert Horizontal Line": "Insert Horizontal Line", "Table": "Table", "Insert table": "Insert table", "Cell": "Cell", "Row": "Row", "Column": "Column", "Delete table": "Delete table", "Insert cell before": "Insert cell before", "Insert cell after": "Insert cell after", "Delete cell": "Delete cell", "Merge cells": "Merge cells", "Horizontal split": "Horizontal split", "Vertical split": "Vertical split", "Insert row above": "Insert row above", "Insert row below": "Insert row below", "Delete row": "Delete row", "Insert column before": "Insert column before", "Insert column after": "Insert column after", "Delete column": "Delete column" }, direction: "ltr" };
plusonedev/pliant
public/plugins/froala/js/langs/en_ca.js
JavaScript
gpl-2.0
2,664
(function() { var ATTACHMENT, Evented, Shepherd, Step, addClass, createFromHTML, extend, matchesSelector, parseShorthand, removeClass, uniqueId, _ref, __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __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; }; _ref = Tether.Utils, extend = _ref.extend, removeClass = _ref.removeClass, addClass = _ref.addClass, Evented = _ref.Evented; ATTACHMENT = { 'top': 'top center', 'left': 'middle right', 'right': 'middle left', 'bottom': 'bottom center' }; uniqueId = (function() { var id; id = 0; return function() { return id++; }; })(); createFromHTML = function(html) { var el; el = document.createElement('div'); el.innerHTML = html; return el.children[0]; }; matchesSelector = function(el, sel) { var matches, _ref1, _ref2, _ref3, _ref4; matches = (_ref1 = (_ref2 = (_ref3 = (_ref4 = el.matches) != null ? _ref4 : el.matchesSelector) != null ? _ref3 : el.webkitMatchesSelector) != null ? _ref2 : el.mozMatchesSelector) != null ? _ref1 : el.oMatchesSelector; return matches.call(el, sel); }; parseShorthand = function(obj, props) { var i, out, prop, vals, _i, _len; if (obj == null) { return obj; } else if (typeof obj === 'object') { return obj; } else { vals = obj.split(' '); if (vals.length > props.length) { vals[0] = vals.slice(0, +(vals.length - props.length) + 1 || 9e9).join(' '); vals.splice(1, vals.length - props.length); } out = {}; for (i = _i = 0, _len = props.length; _i < _len; i = ++_i) { prop = props[i]; out[prop] = vals[i]; } return out; } }; Step = (function(_super) { __extends(Step, _super); function Step(shepherd, options) { this.shepherd = shepherd; this.destroy = __bind(this.destroy, this); this.scrollTo = __bind(this.scrollTo, this); this.complete = __bind(this.complete, this); this.cancel = __bind(this.cancel, this); this.hide = __bind(this.hide, this); this.show = __bind(this.show, this); this.setOptions(options); } Step.prototype.setOptions = function(options) { var event, handler, _base, _ref1; this.options = options != null ? options : {}; this.destroy(); this.id = this.options.id || this.id || ("step-" + (uniqueId())); if (this.options.when) { _ref1 = this.options.when; for (event in _ref1) { handler = _ref1[event]; this.on(event, handler, this); } } return (_base = this.options).buttons != null ? (_base = this.options).buttons : _base.buttons = [ { text: 'Next', action: this.shepherd.next } ]; }; Step.prototype.bindAdvance = function() { var event, handler, selector, _ref1, _this = this; _ref1 = parseShorthand(this.options.advanceOn, ['event', 'selector']), event = _ref1.event, selector = _ref1.selector; handler = function(e) { if (selector != null) { if (matchesSelector(e.target, selector)) { return _this.shepherd.advance(); } } else { if (_this.el && e.target === _this.el) { return _this.shepherd.advance(); } } }; document.body.addEventListener(event, handler); return this.on('destroy', function() { return document.body.removeEventListener(event, handler); }); }; Step.prototype.getAttachTo = function() { var opts; opts = parseShorthand(this.options.attachTo, ['element', 'on']); if (opts == null) { opts = {}; } if (typeof opts.element === 'string') { opts.element = document.querySelector(opts.element); if (opts.element == null) { throw new Error("Shepherd step's attachTo was not found in the page"); } } return opts; }; Step.prototype.setupTether = function() { var attachment, opts, tetherOpts; if (typeof Tether === "undefined" || Tether === null) { throw new Error("Using the attachment feature of Shepherd requires the Tether library"); } opts = this.getAttachTo(); attachment = ATTACHMENT[opts.on || 'right']; if (opts.element == null) { opts.element = 'viewport'; attachment = 'middle center'; } tetherOpts = { classPrefix: 'shepherd', element: this.el, constraints: [ { to: 'window', pin: true, attachment: 'together' } ], target: opts.element, offset: opts.offset || '0 0', attachment: attachment }; return this.tether = new Tether(extend(tetherOpts, this.options.tetherOptions)); }; Step.prototype.show = function() { var _ref1, _this = this; if (this.el == null) { this.render(); } addClass(this.el, 'shepherd-open'); if ((_ref1 = this.tether) != null) { _ref1.enable(); } if (this.options.scrollTo) { setTimeout(function() { return _this.scrollTo(); }); } return this.trigger('show'); }; Step.prototype.hide = function() { var _ref1; removeClass(this.el, 'shepherd-open'); if ((_ref1 = this.tether) != null) { _ref1.disable(); } return this.trigger('hide'); }; Step.prototype.cancel = function() { this.hide(); return this.trigger('cancel'); }; Step.prototype.complete = function() { this.hide(); return this.trigger('complete'); }; Step.prototype.scrollTo = function() { var $attachTo, elHeight, elLeft, elTop, element, height, left, offset, top, _ref1; element = this.getAttachTo().element; if (element == null) { return; } $attachTo = jQuery(element); _ref1 = $attachTo.offset(), top = _ref1.top, left = _ref1.left; height = $attachTo.outerHeight(); offset = $(this.el).offset(); elTop = offset.top; elLeft = offset.left; elHeight = $(this.el).outerHeight(); if (top < pageYOffset || elTop < pageYOffset) { return jQuery(document.body).scrollTop(Math.min(top, elTop) - 10); } else if ((top + height) > (pageYOffset + innerHeight) || (elTop + elHeight) > (pageYOffset + innerHeight)) { return jQuery(document.body).scrollTop(Math.max(top + height, elTop + elHeight) - innerHeight + 10); } }; Step.prototype.destroy = function() { var _ref1; if (this.el != null) { document.body.removeChild(this.el); delete this.el; } if ((_ref1 = this.tether) != null) { _ref1.destroy(); } return this.trigger('destroy'); }; Step.prototype.render = function() { var button, buttons, cfg, content, footer, header, paragraph, paragraphs, text, _i, _j, _len, _len1, _ref1, _ref2, _ref3; if (this.el != null) { this.destroy(); } this.el = createFromHTML("<div class='shepherd-step " + ((_ref1 = this.options.classes) != null ? _ref1 : '') + "' data-id='" + this.id + "'></div>"); content = document.createElement('div'); content.className = 'shepherd-content'; this.el.appendChild(content); if (this.options.title != null) { header = document.createElement('header'); header.innerHTML = "<h3 class='shepherd-title'>" + this.options.title + "</h3>"; this.el.className += ' shepherd-has-title'; content.appendChild(header); } if (this.options.text != null) { text = createFromHTML("<div class='shepherd-text'></div>"); paragraphs = this.options.text; if (typeof paragraphs === 'string') { paragraphs = [paragraphs]; } for (_i = 0, _len = paragraphs.length; _i < _len; _i++) { paragraph = paragraphs[_i]; text.innerHTML += "<p>" + paragraph + "</p>"; } content.appendChild(text); } footer = document.createElement('footer'); if (this.options.buttons) { buttons = createFromHTML("<ul class='shepherd-buttons'></ul>"); _ref2 = this.options.buttons; for (_j = 0, _len1 = _ref2.length; _j < _len1; _j++) { cfg = _ref2[_j]; button = createFromHTML("<li><a class='shepherd-button " + ((_ref3 = cfg.classes) != null ? _ref3 : '') + "'>" + cfg.text + "</a>"); buttons.appendChild(button); this.bindButtonEvents(cfg, button.querySelector('a')); } footer.appendChild(buttons); } content.appendChild(footer); document.body.appendChild(this.el); this.setupTether(); if (this.options.advanceOn) { return this.bindAdvance(); } }; Step.prototype.bindButtonEvents = function(cfg, el) { var event, handler, page, _ref1, _this = this; if (cfg.events == null) { cfg.events = {}; } if (cfg.action != null) { cfg.events.click = cfg.action; } _ref1 = cfg.events; for (event in _ref1) { handler = _ref1[event]; if (typeof handler === 'string') { page = handler; handler = function() { return _this.shepherd.show(page); }; } el.addEventListener(event, handler); } return this.on('destroy', function() { var _ref2, _results; _ref2 = cfg.events; _results = []; for (event in _ref2) { handler = _ref2[event]; _results.push(el.removeEventListener(event, handler)); } return _results; }); }; return Step; })(Evented); Shepherd = (function(_super) { __extends(Shepherd, _super); function Shepherd(options) { var _ref1; this.options = options != null ? options : {}; this.hide = __bind(this.hide, this); this.cancel = __bind(this.cancel, this); this.back = __bind(this.back, this); this.next = __bind(this.next, this); this.steps = (_ref1 = this.options.steps) != null ? _ref1 : []; } Shepherd.prototype.addStep = function(name, step) { if (step == null) { step = name; } else { step.id = name; } step = extend({}, this.options.defaults, step); return this.steps.push(new Step(this, step)); }; Shepherd.prototype.getById = function(id) { var step, _i, _len, _ref1; _ref1 = this.steps; for (_i = 0, _len = _ref1.length; _i < _len; _i++) { step = _ref1[_i]; if (step.id === id) { return step; } } }; Shepherd.prototype.next = function() { var index; index = this.steps.indexOf(this.currentStep); if (index === this.steps.length - 1) { this.hide(index); return this.trigger('complete'); } else { return this.show(index + 1); } }; Shepherd.prototype.back = function() { var index; index = this.steps.indexOf(this.currentStep); return this.show(index - 1); }; Shepherd.prototype.cancel = function() { var _ref1; if ((_ref1 = this.currentStep) != null) { _ref1.cancel(); } return this.trigger('cancel'); }; Shepherd.prototype.hide = function() { var _ref1; if ((_ref1 = this.currentStep) != null) { _ref1.hide(); } return this.trigger('hide'); }; Shepherd.prototype.show = function(key) { var next; if (key == null) { key = 0; } if (this.currentStep) { this.currentStep.hide(); } if (typeof key === 'string') { next = this.getById(key); } else { next = this.steps[key]; } if (next) { this.trigger('shown', { step: next, previous: this.currentStep }); this.currentStep = next; return next.show(); } }; Shepherd.prototype.start = function() { this.currentStep = null; return this.next(); }; return Shepherd; })(Evented); window.Shepherd = Shepherd; }).call(this);
danut007ro/cdnjs
ajax/libs/shepherd/0.2.1/shepherd.js
JavaScript
mit
12,600
define( "dojox/atom/widget/nls/ja/FeedEntryEditor", ({ doNew: "[新規]", edit: "[編集]", save: "[保存]", cancel: "[キャンセル]" }) );
Caspar12/zh.sw
zh.web.site.admin/src/main/resources/static/js/dojo/dojox/atom/widget/nls/ja/FeedEntryEditor.js.uncompressed.js
JavaScript
apache-2.0
148
//>>built define("dojox/grid/enhanced/nls/it/Pagination",({"descTemplate":"${2} - ${3} di ${1} ${0}","firstTip":"Prima pagina","lastTip":"Ultima pagina","nextTip":"Pagina successiva","prevTip":"Pagina precedente","itemTitle":"elementi","singularItemTitle":"elemento","pageStepLabelTemplate":"Pagina ${0}","pageSizeLabelTemplate":"${0} elementi per pagina","allItemsLabelTemplate":"Tutti gli elementi","gotoButtonTitle":"Vai a pagina specifica","dialogTitle":"Vai a pagina","dialogIndication":"Specifica numero pagina","pageCountIndication":" (${0} pagine)","dialogConfirm":"Vai","dialogCancel":"Annulla","all":"Tutto"}));
ISTang/sitemap
web/public/libs/dojo/1.8.3/dojox/grid/enhanced/nls/it/Pagination.js
JavaScript
gpl-2.0
622
/* Copyright (c) 2006-2013 by OpenLayers Contributors (see authors.txt for * full list of contributors). Published under the 2-clause BSD license. * See license.txt in the OpenLayers distribution or repository for the * full text of the license. */ /** * @requires OpenLayers/Control.js * @requires OpenLayers/Handler/Click.js * @requires OpenLayers/Handler/Hover.js * @requires OpenLayers/Request.js * @requires OpenLayers/Format/WMSGetFeatureInfo.js */ /** * Class: OpenLayers.Control.WMTSGetFeatureInfo * The WMTSGetFeatureInfo control uses a WMTS query to get information about a * point on the map. The information may be in a display-friendly format * such as HTML, or a machine-friendly format such as GML, depending on the * server's capabilities and the client's configuration. This control * handles click or hover events, attempts to parse the results using an * OpenLayers.Format, and fires a 'getfeatureinfo' event for each layer * queried. * * Inherits from: * - <OpenLayers.Control> */ OpenLayers.Control.WMTSGetFeatureInfo = OpenLayers.Class(OpenLayers.Control, { /** * APIProperty: hover * {Boolean} Send GetFeatureInfo requests when mouse stops moving. * Default is false. */ hover: false, /** * Property: requestEncoding * {String} One of "KVP" or "REST". Only KVP encoding is supported at this * time. */ requestEncoding: "KVP", /** * APIProperty: drillDown * {Boolean} Drill down over all WMTS layers in the map. When * using drillDown mode, hover is not possible. A getfeatureinfo event * will be fired for each layer queried. */ drillDown: false, /** * APIProperty: maxFeatures * {Integer} Maximum number of features to return from a WMTS query. This * sets the feature_count parameter on WMTS GetFeatureInfo * requests. */ maxFeatures: 10, /** APIProperty: clickCallback * {String} The click callback to register in the * {<OpenLayers.Handler.Click>} object created when the hover * option is set to false. Default is "click". */ clickCallback: "click", /** * Property: layers * {Array(<OpenLayers.Layer.WMTS>)} The layers to query for feature info. * If omitted, all map WMTS layers will be considered. */ layers: null, /** * APIProperty: queryVisible * {Boolean} Filter out hidden layers when searching the map for layers to * query. Default is true. */ queryVisible: true, /** * Property: infoFormat * {String} The mimetype to request from the server */ infoFormat: 'text/html', /** * Property: vendorParams * {Object} Additional parameters that will be added to the request, for * WMTS implementations that support them. This could e.g. look like * (start code) * { * radius: 5 * } * (end) */ vendorParams: {}, /** * Property: format * {<OpenLayers.Format>} A format for parsing GetFeatureInfo responses. * Default is <OpenLayers.Format.WMSGetFeatureInfo>. */ format: null, /** * Property: formatOptions * {Object} Optional properties to set on the format (if one is not provided * in the <format> property. */ formatOptions: null, /** * APIProperty: handlerOptions * {Object} Additional options for the handlers used by this control, e.g. * (start code) * { * "click": {delay: 100}, * "hover": {delay: 300} * } * (end) */ /** * Property: handler * {Object} Reference to the <OpenLayers.Handler> for this control */ handler: null, /** * Property: hoverRequest * {<OpenLayers.Request>} contains the currently running hover request * (if any). */ hoverRequest: null, /** * APIProperty: events * {<OpenLayers.Events>} Events instance for listeners and triggering * control specific events. * * Register a listener for a particular event with the following syntax: * (code) * control.events.register(type, obj, listener); * (end) * * Supported event types (in addition to those from <OpenLayers.Control.events>): * beforegetfeatureinfo - Triggered before each request is sent. * The event object has an *xy* property with the position of the * mouse click or hover event that triggers the request and a *layer* * property referencing the layer about to be queried. If a listener * returns false, the request will not be issued. * getfeatureinfo - Triggered when a GetFeatureInfo response is received. * The event object has a *text* property with the body of the * response (String), a *features* property with an array of the * parsed features, an *xy* property with the position of the mouse * click or hover event that triggered the request, a *layer* property * referencing the layer queried and a *request* property with the * request itself. If drillDown is set to true, one event will be fired * for each layer queried. * exception - Triggered when a GetFeatureInfo request fails (with a * status other than 200) or whenparsing fails. Listeners will receive * an event with *request*, *xy*, and *layer* properties. In the case * of a parsing error, the event will also contain an *error* property. */ /** * Property: pending * {Number} The number of pending requests. */ pending: 0, /** * Constructor: <OpenLayers.Control.WMTSGetFeatureInfo> * * Parameters: * options - {Object} */ initialize: function(options) { options = options || {}; options.handlerOptions = options.handlerOptions || {}; OpenLayers.Control.prototype.initialize.apply(this, [options]); if (!this.format) { this.format = new OpenLayers.Format.WMSGetFeatureInfo( options.formatOptions ); } if (this.drillDown === true) { this.hover = false; } if (this.hover) { this.handler = new OpenLayers.Handler.Hover( this, { move: this.cancelHover, pause: this.getInfoForHover }, OpenLayers.Util.extend( this.handlerOptions.hover || {}, {delay: 250} ) ); } else { var callbacks = {}; callbacks[this.clickCallback] = this.getInfoForClick; this.handler = new OpenLayers.Handler.Click( this, callbacks, this.handlerOptions.click || {} ); } }, /** * Method: getInfoForClick * Called on click * * Parameters: * evt - {<OpenLayers.Event>} */ getInfoForClick: function(evt) { this.request(evt.xy, {}); }, /** * Method: getInfoForHover * Pause callback for the hover handler * * Parameters: * evt - {Object} */ getInfoForHover: function(evt) { this.request(evt.xy, {hover: true}); }, /** * Method: cancelHover * Cancel callback for the hover handler */ cancelHover: function() { if (this.hoverRequest) { --this.pending; if (this.pending <= 0) { OpenLayers.Element.removeClass(this.map.viewPortDiv, "olCursorWait"); this.pending = 0; } this.hoverRequest.abort(); this.hoverRequest = null; } }, /** * Method: findLayers * Internal method to get the layers, independent of whether we are * inspecting the map or using a client-provided array */ findLayers: function() { var candidates = this.layers || this.map.layers; var layers = []; var layer; for (var i=candidates.length-1; i>=0; --i) { layer = candidates[i]; if (layer instanceof OpenLayers.Layer.WMTS && layer.requestEncoding === this.requestEncoding && (!this.queryVisible || layer.getVisibility())) { layers.push(layer); if (!this.drillDown || this.hover) { break; } } } return layers; }, /** * Method: buildRequestOptions * Build an object with the relevant options for the GetFeatureInfo request. * * Parameters: * layer - {<OpenLayers.Layer.WMTS>} A WMTS layer. * xy - {<OpenLayers.Pixel>} The position on the map where the * mouse event occurred. */ buildRequestOptions: function(layer, xy) { var loc = this.map.getLonLatFromPixel(xy); var getTileUrl = layer.getURL( new OpenLayers.Bounds(loc.lon, loc.lat, loc.lon, loc.lat) ); var params = OpenLayers.Util.getParameters(getTileUrl); var tileInfo = layer.getTileInfo(loc); OpenLayers.Util.extend(params, { service: "WMTS", version: layer.version, request: "GetFeatureInfo", infoFormat: this.infoFormat, i: tileInfo.i, j: tileInfo.j }); OpenLayers.Util.applyDefaults(params, this.vendorParams); return { url: OpenLayers.Util.isArray(layer.url) ? layer.url[0] : layer.url, params: OpenLayers.Util.upperCaseObject(params), callback: function(request) { this.handleResponse(xy, request, layer); }, scope: this }; }, /** * Method: request * Sends a GetFeatureInfo request to the WMTS * * Parameters: * xy - {<OpenLayers.Pixel>} The position on the map where the mouse event * occurred. * options - {Object} additional options for this method. * * Valid options: * - *hover* {Boolean} true if we do the request for the hover handler */ request: function(xy, options) { options = options || {}; var layers = this.findLayers(); if (layers.length > 0) { var issue, layer; for (var i=0, len=layers.length; i<len; i++) { layer = layers[i]; issue = this.events.triggerEvent("beforegetfeatureinfo", { xy: xy, layer: layer }); if (issue !== false) { ++this.pending; var requestOptions = this.buildRequestOptions(layer, xy); var request = OpenLayers.Request.GET(requestOptions); if (options.hover === true) { this.hoverRequest = request; } } } if (this.pending > 0) { OpenLayers.Element.addClass(this.map.viewPortDiv, "olCursorWait"); } } }, /** * Method: handleResponse * Handler for the GetFeatureInfo response. * * Parameters: * xy - {<OpenLayers.Pixel>} The position on the map where the mouse event * occurred. * request - {XMLHttpRequest} The request object. * layer - {<OpenLayers.Layer.WMTS>} The queried layer. */ handleResponse: function(xy, request, layer) { --this.pending; if (this.pending <= 0) { OpenLayers.Element.removeClass(this.map.viewPortDiv, "olCursorWait"); this.pending = 0; } if (request.status && (request.status < 200 || request.status >= 300)) { this.events.triggerEvent("exception", { xy: xy, request: request, layer: layer }); } else { var doc = request.responseXML; if (!doc || !doc.documentElement) { doc = request.responseText; } var features, except; try { features = this.format.read(doc); } catch (error) { except = true; this.events.triggerEvent("exception", { xy: xy, request: request, error: error, layer: layer }); } if (!except) { this.events.triggerEvent("getfeatureinfo", { text: request.responseText, features: features, request: request, xy: xy, layer: layer }); } } }, CLASS_NAME: "OpenLayers.Control.WMTSGetFeatureInfo" });
savchukoleksii/beaversteward
www/settings/tools/mysql/js/openlayers/src/openlayers/lib/OpenLayers/Control/WMTSGetFeatureInfo.js
JavaScript
mit
13,040
function f() { /* infinite */ while (true) { } /* bar */ var each; }
Jazzling/jazzle-parser
test/test-esprima/fixtures/comment/migrated_0035.js
JavaScript
mit
68
describe('uiValidate', function ($compile) { var scope, compileAndDigest; var trueValidator = function () { return true; }; var falseValidator = function () { return false; }; var passedValueValidator = function (valueToValidate) { return valueToValidate; }; beforeEach(module('ui')); beforeEach(inject(function ($rootScope, $compile) { scope = $rootScope.$new(); compileAndDigest = function (inputHtml, scope) { var inputElm = angular.element(inputHtml); var formElm = angular.element('<form name="form"></form>'); formElm.append(inputElm); $compile(formElm)(scope); scope.$digest(); return inputElm; }; })); describe('initial validation', function () { it('should mark input as valid if initial model is valid', inject(function () { scope.validate = trueValidator; compileAndDigest('<input name="input" ng-model="value" ui-validate="\'validate($value)\'">', scope); expect(scope.form.input.$valid).toBeTruthy(); expect(scope.form.input.$error).toEqual({validator: false}); })); it('should mark input as invalid if initial model is invalid', inject(function () { scope.validate = falseValidator; compileAndDigest('<input name="input" ng-model="value" ui-validate="\'validate($value)\'">', scope); expect(scope.form.input.$valid).toBeFalsy(); expect(scope.form.input.$error).toEqual({ validator: true }); })); }); describe('validation on model change', function () { it('should change valid state in response to model changes', inject(function () { scope.value = false; scope.validate = passedValueValidator; compileAndDigest('<input name="input" ng-model="value" ui-validate="\'validate($value)\'">', scope); expect(scope.form.input.$valid).toBeFalsy(); scope.$apply('value = true'); expect(scope.form.input.$valid).toBeTruthy(); })); }); describe('validation on element change', function () { var sniffer; beforeEach(inject(function ($sniffer) { sniffer = $sniffer; })); it('should change valid state in response to element events', function () { scope.value = false; scope.validate = passedValueValidator; var inputElm = compileAndDigest('<input name="input" ng-model="value" ui-validate="\'validate($value)\'">', scope); expect(scope.form.input.$valid).toBeFalsy(); inputElm.val('true'); inputElm.trigger((sniffer.hasEvent('input') ? 'input' : 'change')); expect(scope.form.input.$valid).toBeTruthy(); }); }); describe('multiple validators with custom keys', function () { it('should support multiple validators with custom keys', function () { scope.validate1 = trueValidator; scope.validate2 = falseValidator; compileAndDigest('<input name="input" ng-model="value" ui-validate="{key1 : \'validate1($value)\', key2 : \'validate2($value)\'}">', scope); expect(scope.form.input.$valid).toBeFalsy(); expect(scope.form.input.$error.key1).toBeFalsy(); expect(scope.form.input.$error.key2).toBeTruthy(); }); }); describe('uiValidateWatch', function(){ function validateWatch(watchMe) { return watchMe; }; beforeEach(function(){ scope.validateWatch = validateWatch; }); it('should watch the string and refire the single validator', function () { scope.watchMe = false; compileAndDigest('<input name="input" ng-model="value" ui-validate="\'validateWatch(watchMe)\'" ui-validate-watch="\'watchMe\'">', scope); expect(scope.form.input.$valid).toBe(false); expect(scope.form.input.$error.validator).toBe(true); scope.$apply('watchMe=true'); expect(scope.form.input.$valid).toBe(true); expect(scope.form.input.$error.validator).toBe(false); }); it('should watch the string and refire all validators', function () { scope.watchMe = false; compileAndDigest('<input name="input" ng-model="value" ui-validate="{foo:\'validateWatch(watchMe)\',bar:\'validateWatch(watchMe)\'}" ui-validate-watch="\'watchMe\'">', scope); expect(scope.form.input.$valid).toBe(false); expect(scope.form.input.$error.foo).toBe(true); expect(scope.form.input.$error.bar).toBe(true); scope.$apply('watchMe=true'); expect(scope.form.input.$valid).toBe(true); expect(scope.form.input.$error.foo).toBe(false); expect(scope.form.input.$error.bar).toBe(false); }); it('should watch the all object attributes and each respective validator', function () { scope.watchFoo = false; scope.watchBar = false; compileAndDigest('<input name="input" ng-model="value" ui-validate="{foo:\'validateWatch(watchFoo)\',bar:\'validateWatch(watchBar)\'}" ui-validate-watch="{foo:\'watchFoo\',bar:\'watchBar\'}">', scope); expect(scope.form.input.$valid).toBe(false); expect(scope.form.input.$error.foo).toBe(true); expect(scope.form.input.$error.bar).toBe(true); scope.$apply('watchFoo=true'); expect(scope.form.input.$valid).toBe(false); expect(scope.form.input.$error.foo).toBe(false); expect(scope.form.input.$error.bar).toBe(true); scope.$apply('watchBar=true'); scope.$apply('watchFoo=false'); expect(scope.form.input.$valid).toBe(false); expect(scope.form.input.$error.foo).toBe(true); expect(scope.form.input.$error.bar).toBe(false); scope.$apply('watchFoo=true'); expect(scope.form.input.$valid).toBe(true); expect(scope.form.input.$error.foo).toBe(false); expect(scope.form.input.$error.bar).toBe(false); }); }); describe('error cases', function () { it('should fail if ngModel not present', inject(function () { expect(function () { compileAndDigest('<input name="input" ui-validate="\'validate($value)\'">', scope); }).toThrow(new Error('No controller: ngModel')); })); it('should have no effect if validate expression is empty', inject(function () { compileAndDigest('<input ng-model="value" ui-validate="">', scope); })); }); });
spawashe/poc-mango-cad
www/lib/bower_components/angular-ui/modules/directives/validate/test/validateSpec.js
JavaScript
mit
6,308
/* Copyright (c) 2003-2021, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ CKEDITOR.plugins.setLang("specialchar","es",{euro:"Símbolo de euro",lsquo:"Comilla simple izquierda",rsquo:"Comilla simple derecha",ldquo:"Comilla doble izquierda",rdquo:"Comilla doble derecha",ndash:"Guión corto",mdash:"Guión medio largo",iexcl:"Signo de admiración invertido",cent:"Símbolo centavo",pound:"Símbolo libra",curren:"Símbolo moneda",yen:"Símbolo yen",brvbar:"Barra vertical rota",sect:"Símbolo sección",uml:"Diéresis",copy:"Signo de derechos de autor",ordf:"Indicador ordinal femenino",laquo:"Abre comillas angulares", not:"Signo negación",reg:"Signo de marca registrada",macr:"Guión alto",deg:"Signo de grado",sup2:"Superíndice dos",sup3:"Superíndice tres",acute:"Acento agudo",micro:"Signo micro",para:"Signo de pi",middot:"Punto medio",cedil:"Cedilla",sup1:"Superíndice uno",ordm:"Indicador orginal masculino",raquo:"Cierra comillas angulares",frac14:"Fracción ordinaria de un quarto",frac12:"Fracción ordinaria de una mitad",frac34:"Fracción ordinaria de tres cuartos",iquest:"Signo de interrogación invertido",Agrave:"Letra A latina mayúscula con acento grave", Aacute:"Letra A latina mayúscula con acento agudo",Acirc:"Letra A latina mayúscula con acento circunflejo",Atilde:"Letra A latina mayúscula con tilde",Auml:"Letra A latina mayúscula con diéresis",Aring:"Letra A latina mayúscula con aro arriba",AElig:"Letra Æ latina mayúscula",Ccedil:"Letra C latina mayúscula con cedilla",Egrave:"Letra E latina mayúscula con acento grave",Eacute:"Letra E latina mayúscula con acento agudo",Ecirc:"Letra E latina mayúscula con acento circunflejo",Euml:"Letra E latina mayúscula con diéresis", Igrave:"Letra I latina mayúscula con acento grave",Iacute:"Letra I latina mayúscula con acento agudo",Icirc:"Letra I latina mayúscula con acento circunflejo",Iuml:"Letra I latina mayúscula con diéresis",ETH:"Letra Eth latina mayúscula",Ntilde:"Letra N latina mayúscula con tilde",Ograve:"Letra O latina mayúscula con acento grave",Oacute:"Letra O latina mayúscula con acento agudo",Ocirc:"Letra O latina mayúscula con acento circunflejo",Otilde:"Letra O latina mayúscula con tilde",Ouml:"Letra O latina mayúscula con diéresis", times:"Signo de multiplicación",Oslash:"Letra O latina mayúscula con barra inclinada",Ugrave:"Letra U latina mayúscula con acento grave",Uacute:"Letra U latina mayúscula con acento agudo",Ucirc:"Letra U latina mayúscula con acento circunflejo",Uuml:"Letra U latina mayúscula con diéresis",Yacute:"Letra Y latina mayúscula con acento agudo",THORN:"Letra Thorn latina mayúscula",szlig:"Letra s latina fuerte pequeña",agrave:"Letra a latina pequeña con acento grave",aacute:"Letra a latina pequeña con acento agudo", acirc:"Letra a latina pequeña con acento circunflejo",atilde:"Letra a latina pequeña con tilde",auml:"Letra a latina pequeña con diéresis",aring:"Letra a latina pequeña con aro arriba",aelig:"Letra æ latina pequeña",ccedil:"Letra c latina pequeña con cedilla",egrave:"Letra e latina pequeña con acento grave",eacute:"Letra e latina pequeña con acento agudo",ecirc:"Letra e latina pequeña con acento circunflejo",euml:"Letra e latina pequeña con diéresis",igrave:"Letra i latina pequeña con acento grave", iacute:"Letra i latina pequeña con acento agudo",icirc:"Letra i latina pequeña con acento circunflejo",iuml:"Letra i latina pequeña con diéresis",eth:"Letra eth latina pequeña",ntilde:"Letra n latina pequeña con tilde",ograve:"Letra o latina pequeña con acento grave",oacute:"Letra o latina pequeña con acento agudo",ocirc:"Letra o latina pequeña con acento circunflejo",otilde:"Letra o latina pequeña con tilde",ouml:"Letra o latina pequeña con diéresis",divide:"Signo de división",oslash:"Letra o latina minúscula con barra inclinada", ugrave:"Letra u latina pequeña con acento grave",uacute:"Letra u latina pequeña con acento agudo",ucirc:"Letra u latina pequeña con acento circunflejo",uuml:"Letra u latina pequeña con diéresis",yacute:"Letra u latina pequeña con acento agudo",thorn:"Letra thorn latina minúscula",yuml:"Letra y latina pequeña con diéresis",OElig:"Diptongo OE latino en mayúscula",oelig:"Diptongo oe latino en minúscula",372:"Letra W latina mayúscula con acento circunflejo",374:"Letra Y latina mayúscula con acento circunflejo", 373:"Letra w latina pequeña con acento circunflejo",375:"Letra y latina pequeña con acento circunflejo",sbquo:"Comilla simple baja-9",8219:"Comilla simple alta invertida-9",bdquo:"Comillas dobles bajas-9",hellip:"Puntos suspensivos horizontales",trade:"Signo de marca registrada",9658:"Apuntador negro apuntando a la derecha",bull:"Viñeta",rarr:"Flecha a la derecha",rArr:"Flecha doble a la derecha",hArr:"Flecha izquierda derecha doble",diams:"Diamante negro",asymp:"Casi igual a"});
YAFNET/YAFNET
yafsrc/YetAnotherForum.NET/Scripts/ckeditor/plugins/specialchar/dialogs/lang/es.js
JavaScript
apache-2.0
4,963
"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()}}}]);
sreym/cdnjs
ajax/libs/ng-parallax/1.0.1/ngParallax.min.js
JavaScript
mit
721
/** * angular-drag-and-drop-lists v1.4.0 * * Copyright (c) 2014 Marcel Juenemann marcel@juenemann.cc * 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 {} });
kurideja/pizza-diagram
www/libs/angular-drag-and-drop-lists/angular-drag-and-drop-lists.js
JavaScript
mit
29,810
/* @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>&nbsp;</P>' : '<p>&nbsp;</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() + '>&nbsp;</' + attrs.taDefaultWrap.toUpperCase() + '>' : '<' + attrs.taDefaultWrap + '>&nbsp;</' + 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|&nbsp;)*<\/[^>]+>$/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('&nbsp;' + 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); }); } }; } ]);})();
gogoleva/cdnjs
ajax/libs/textAngular/1.3.0-17/src/textAngular.js
JavaScript
mit
107,500
//On page load // TODO - remove nonconflict stuff once prototype is gone for good var $j = jQuery.noConflict(); replace_ids = function(s){ var new_id = new Date().getTime(); return s.replace(/NEW_RECORD/g, new_id); } $j(function() { $j('a[id*=nested]').click(function() { var template = $j(this).attr('href').replace(/.*#/, ''); html = replace_ids(eval(template)); $j('#ul-' + $j(this).attr('id')).append(html); update_remove_links(); }); update_remove_links(); }) var update_remove_links = function() { $j('.remove').click(function() { $j(this).prevAll(':first').val(1); $j(this).parent().hide(); }); };
rafarubert/loja
vendor/spree/vendor/extensions/theme_default/public/javascripts/nested-attribute.js
JavaScript
bsd-3-clause
660
/* * jQuery Textarea Characters Counter Plugin v 2.0 * Examples and documentation at: http://roy-jin.appspot.com/jsp/textareaCounter.jsp * Copyright (c) 2010 Roy Jin * Version: 2.0 (11-JUN-2010) * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * Requires: jQuery v1.4.2 or later */ (function($){ $.fn.textareaCount = function(options, fn) { var defaults = { maxCharacterSize: -1, originalStyle: 'originalTextareaInfo', warningStyle: 'warningTextareaInfo', warningNumber: 20, displayFormat: '#input characters | #words words' }; var options = $.extend(defaults, options); var container = $(this); $("<div class='charleft'>&nbsp;</div>").insertAfter(container); //create charleft css var charLeftCss = { 'width' : container.width() }; var charLeftInfo = getNextCharLeftInformation(container); charLeftInfo.addClass(options.originalStyle); //charLeftInfo.css(charLeftCss); var numInput = 0; var maxCharacters = options.maxCharacterSize; var numLeft = 0; var numWords = 0; container.bind('keyup', function(event){limitTextAreaByCharacterCount();}) .bind('mouseover', function(event){setTimeout(function(){limitTextAreaByCharacterCount();}, 10);}) .bind('paste', function(event){setTimeout(function(){limitTextAreaByCharacterCount();}, 10);}); limitTextAreaByCharacterCount(); function limitTextAreaByCharacterCount(){ charLeftInfo.html(countByCharacters()); //function call back if(typeof fn != 'undefined'){ fn.call(this, getInfo()); } return true; } function countByCharacters(){ var content = container.val(); var contentLength = content.length; //Start Cut if(options.maxCharacterSize > 0){ //If copied content is already more than maxCharacterSize, chop it to maxCharacterSize. if(contentLength >= options.maxCharacterSize) { content = content.substring(0, options.maxCharacterSize); } var newlineCount = getNewlineCount(content); // newlineCount new line character. For windows, it occupies 2 characters var systemmaxCharacterSize = options.maxCharacterSize - newlineCount; if (!isWin()){ systemmaxCharacterSize = options.maxCharacterSize } if(contentLength > systemmaxCharacterSize){ //avoid scroll bar moving var originalScrollTopPosition = this.scrollTop; container.val(content.substring(0, systemmaxCharacterSize)); this.scrollTop = originalScrollTopPosition; } charLeftInfo.removeClass(options.warningStyle); if(systemmaxCharacterSize - contentLength <= options.warningNumber){ charLeftInfo.addClass(options.warningStyle); } numInput = container.val().length + newlineCount; if(!isWin()){ numInput = container.val().length; } numWords = countWord(getCleanedWordString(container.val())); numLeft = maxCharacters - numInput; } else { //normal count, no cut var newlineCount = getNewlineCount(content); numInput = container.val().length + newlineCount; if(!isWin()){ numInput = container.val().length; } numWords = countWord(getCleanedWordString(container.val())); } return formatDisplayInfo(); } function formatDisplayInfo(){ var format = options.displayFormat; format = format.replace('#input', numInput); format = format.replace('#words', numWords); //When maxCharacters <= 0, #max, #left cannot be substituted. if(maxCharacters > 0){ format = format.replace('#max', maxCharacters); format = format.replace('#left', numLeft); } return format; } function getInfo(){ var info = { input: numInput, max: maxCharacters, left: numLeft, words: numWords }; return info; } function getNextCharLeftInformation(container){ return container.next('.charleft'); } function isWin(){ var strOS = navigator.appVersion; if (strOS.toLowerCase().indexOf('win') != -1){ return true; } return false; } function getNewlineCount(content){ var newlineCount = 0; for(var i=0; i<content.length;i++){ if(content.charAt(i) == '\n'){ newlineCount++; } } return newlineCount; } function getCleanedWordString(content){ var fullStr = content + " "; var initial_whitespace_rExp = /^[^A-Za-z0-9]+/gi; var left_trimmedStr = fullStr.replace(initial_whitespace_rExp, ""); var non_alphanumerics_rExp = rExp = /[^A-Za-z0-9]+/gi; var cleanedStr = left_trimmedStr.replace(non_alphanumerics_rExp, " "); var splitString = cleanedStr.split(" "); return splitString; } function countWord(cleanedWordString){ var word_count = cleanedWordString.length-1; return word_count; } }; })(jQuery);
cypherjones/lazy-j-ranch
wp-content/wp-content/plugins/gravityforms/js/jquery.textareaCounter.plugin.js
JavaScript
gpl-2.0
4,961
/* -*- Mode: Javascript; indent-tabs-mode:nil; js-indent-level: 2 -*- */ /* vim: set ts=2 et sw=2 tw=80: */ /************************************************************* * * MathJax/jax/output/HTML-CSS/autoload/ms.js * * Implements the HTML-CSS output for <ms> elements. * * --------------------------------------------------------------------- * * Copyright (c) 2010-2015 The MathJax Consortium * * 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. */ MathJax.Hub.Register.StartupHook("HTML-CSS Jax Ready",function () { var VERSION = "2.6.0"; var MML = MathJax.ElementJax.mml, HTMLCSS = MathJax.OutputJax["HTML-CSS"]; MML.ms.Augment({ toHTML: function (span) { span = this.HTMLhandleSize(this.HTMLcreateSpan(span)); var values = this.getValues("lquote","rquote","mathvariant"); if (!this.hasValue("lquote") || values.lquote === '"') values.lquote = "\u201C"; if (!this.hasValue("rquote") || values.rquote === '"') values.rquote = "\u201D"; if (values.lquote === "\u201C" && values.mathvariant === "monospace") values.lquote = '"'; if (values.rquote === "\u201D" && values.mathvariant === "monospace") values.rquote = '"'; var text = values.lquote+this.data.join("")+values.rquote; // FIXME: handle mglyph? this.HTMLhandleVariant(span,this.HTMLgetVariant(),text); this.HTMLhandleSpace(span); this.HTMLhandleColor(span); this.HTMLhandleDir(span); return span; } }); MathJax.Hub.Startup.signal.Post("HTML-CSS ms Ready"); MathJax.Ajax.loadComplete(HTMLCSS.autoloadDir+"/ms.js"); });
AndrewSyktyvkar/Math
wysivig/MathJax/unpacked/jax/output/HTML-CSS/autoload/ms.js
JavaScript
bsd-3-clause
2,124
//// 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) }); })();
jdegraft/Windows-universal-samples
Samples/AdaptiveStreaming/js/js/sample-configuration.js
JavaScript
mit
634
YUI.add('moodle-mod_quiz-repaginate', function (Y, NAME) { // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Repaginate functionality for a popup in quiz editing page. * * @package mod_quiz * @copyright 2014 The Open University * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ var CSS = { REPAGINATECONTAINERCLASS: '.rpcontainerclass', REPAGINATECOMMAND: '#repaginatecommand' }; var PARAMS = { CMID: 'cmid', HEADER: 'header', FORM: 'form' }; var POPUP = function() { POPUP.superclass.constructor.apply(this, arguments); }; Y.extend(POPUP, Y.Base, { header: null, body: null, initializer: function() { var rpcontainerclass = Y.one(CSS.REPAGINATECONTAINERCLASS); // Set popup header and body. this.header = rpcontainerclass.getAttribute(PARAMS.HEADER); this.body = rpcontainerclass.getAttribute(PARAMS.FORM); Y.one(CSS.REPAGINATECOMMAND).on('click', this.display_dialog, this); }, display_dialog: function(e) { e.preventDefault(); // Configure the popup. var config = { headerContent: this.header, bodyContent: this.body, draggable: true, modal: true, zIndex: 1000, context: [CSS.REPAGINATECOMMAND, 'tr', 'br', ['beforeShow']], centered: false, width: '30em', visible: false, postmethod: 'form', footerContent: null }; var popup = {dialog: null}; popup.dialog = new M.core.dialogue(config); popup.dialog.show(); } }); M.mod_quiz = M.mod_quiz || {}; M.mod_quiz.repaginate = M.mod_quiz.repaginate || {}; M.mod_quiz.repaginate.init = function() { return new POPUP(); }; }, '@VERSION@', {"requires": ["base", "event", "node", "io", "moodle-core-notification-dialogue"]});
soonsystems/moodle
mod/quiz/yui/build/moodle-mod_quiz-repaginate/moodle-mod_quiz-repaginate.js
JavaScript
gpl-3.0
2,532
export default function isPlainFunction(test) { return typeof test === 'function' && test.PrototypeMixin === undefined; }
nipunas/ember.js
packages/ember-debug/lib/is-plain-function.js
JavaScript
mit
124
(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('&nbsp;'); 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);
gregorypratt/jsdelivr
files/maxmertkit/1.0.0/js/maxmertkit.js
JavaScript
mit
51,646
/* * jQuery Easing v1.3 - http://gsgd.co.uk/sandbox/jquery/easing/ * * Uses the built in easing capabilities added In jQuery 1.1 * to offer multiple easing options * * TERMS OF USE - jQuery Easing * * Open source under the BSD License. * * Copyright © 2008 George McGinley Smith * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * Neither the name of the author nor the names of contributors may be used to endorse * or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * */ // t: current time, b: begInnIng value, c: change In value, d: duration jQuery.easing['jswing'] = jQuery.easing['swing']; jQuery.extend( jQuery.easing, { def: 'easeOutQuad', swing: function (x, t, b, c, d) { //alert(jQuery.easing.default); return jQuery.easing[jQuery.easing.def](x, t, b, c, d); }, easeInQuad: function (x, t, b, c, d) { return c*(t/=d)*t + b; }, easeOutQuad: function (x, t, b, c, d) { return -c *(t/=d)*(t-2) + b; }, easeInOutQuad: function (x, t, b, c, d) { if ((t/=d/2) < 1) return c/2*t*t + b; return -c/2 * ((--t)*(t-2) - 1) + b; }, easeInCubic: function (x, t, b, c, d) { return c*(t/=d)*t*t + b; }, easeOutCubic: function (x, t, b, c, d) { return c*((t=t/d-1)*t*t + 1) + b; }, easeInOutCubic: function (x, t, b, c, d) { if ((t/=d/2) < 1) return c/2*t*t*t + b; return c/2*((t-=2)*t*t + 2) + b; }, easeInQuart: function (x, t, b, c, d) { return c*(t/=d)*t*t*t + b; }, easeOutQuart: function (x, t, b, c, d) { return -c * ((t=t/d-1)*t*t*t - 1) + b; }, easeInOutQuart: function (x, t, b, c, d) { if ((t/=d/2) < 1) return c/2*t*t*t*t + b; return -c/2 * ((t-=2)*t*t*t - 2) + b; }, easeInQuint: function (x, t, b, c, d) { return c*(t/=d)*t*t*t*t + b; }, easeOutQuint: function (x, t, b, c, d) { return c*((t=t/d-1)*t*t*t*t + 1) + b; }, easeInOutQuint: function (x, t, b, c, d) { if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b; return c/2*((t-=2)*t*t*t*t + 2) + b; }, easeInSine: function (x, t, b, c, d) { return -c * Math.cos(t/d * (Math.PI/2)) + c + b; }, easeOutSine: function (x, t, b, c, d) { return c * Math.sin(t/d * (Math.PI/2)) + b; }, easeInOutSine: function (x, t, b, c, d) { return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b; }, easeInExpo: function (x, t, b, c, d) { return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b; }, easeOutExpo: function (x, t, b, c, d) { return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b; }, easeInOutExpo: function (x, t, b, c, d) { if (t==0) return b; if (t==d) return b+c; if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b; return c/2 * (-Math.pow(2, -10 * --t) + 2) + b; }, easeInCirc: function (x, t, b, c, d) { return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b; }, easeOutCirc: function (x, t, b, c, d) { return c * Math.sqrt(1 - (t=t/d-1)*t) + b; }, easeInOutCirc: function (x, t, b, c, d) { if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b; return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b; }, easeInElastic: function (x, t, b, c, d) { var s=1.70158;var p=0;var a=c; if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3; if (a < Math.abs(c)) { a=c; var s=p/4; } else var s = p/(2*Math.PI) * Math.asin (c/a); return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b; }, easeOutElastic: function (x, t, b, c, d) { var s=1.70158;var p=0;var a=c; if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3; if (a < Math.abs(c)) { a=c; var s=p/4; } else var s = p/(2*Math.PI) * Math.asin (c/a); return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b; }, easeInOutElastic: function (x, t, b, c, d) { var s=1.70158;var p=0;var a=c; if (t==0) return b; if ((t/=d/2)==2) return b+c; if (!p) p=d*(.3*1.5); if (a < Math.abs(c)) { a=c; var s=p/4; } else var s = p/(2*Math.PI) * Math.asin (c/a); if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b; return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b; }, easeInBack: function (x, t, b, c, d, s) { if (s == undefined) s = 1.70158; return c*(t/=d)*t*((s+1)*t - s) + b; }, easeOutBack: function (x, t, b, c, d, s) { if (s == undefined) s = 1.70158; return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b; }, easeInOutBack: function (x, t, b, c, d, s) { if (s == undefined) s = 1.70158; if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b; return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b; }, easeInBounce: function (x, t, b, c, d) { return c - jQuery.easing.easeOutBounce (x, d-t, 0, c, d) + b; }, easeOutBounce: function (x, t, b, c, d) { if ((t/=d) < (1/2.75)) { return c*(7.5625*t*t) + b; } else if (t < (2/2.75)) { return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b; } else if (t < (2.5/2.75)) { return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b; } else { return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b; } }, easeInOutBounce: function (x, t, b, c, d) { if (t < d/2) return jQuery.easing.easeInBounce (x, t*2, 0, c, d) * .5 + b; return jQuery.easing.easeOutBounce (x, t*2-d, 0, c, d) * .5 + c*.5 + b; } });
amit0773/manaslake
wp-content/plugins/mapplic/js/jquery.easing.js
JavaScript
gpl-2.0
6,632
videojs.addLanguage("da",{ "Play": "Afspil", "Pause": "Pause", "Current Time": "Aktuel tid", "Duration Time": "Varighed", "Remaining Time": "Resterende tid", "Stream Type": "Stream-type", "LIVE": "LIVE", "Loaded": "Indlæst", "Progress": "Status", "Fullscreen": "Fuldskærm", "Non-Fullscreen": "Luk fuldskærm", "Mute": "Uden lyd", "Unmuted": "Med lyd", "Playback Rate": "Afspilningsrate", "Subtitles": "Undertekster", "subtitles off": "Uden undertekster", "Captions": "Undertekster for hørehæmmede", "captions off": "Uden undertekster for hørehæmmede", "Chapters": "Kapitler", "You aborted the video playback": "Du afbrød videoafspilningen.", "A network error caused the video download to fail part-way.": "En netværksfejl fik download af videoen til at fejle.", "The video could not be loaded, either because the server or network failed or because the format is not supported.": "Videoen kunne ikke indlæses, enten fordi serveren eller netværket fejlede, eller fordi formatet ikke er understøttet.", "The video playback was aborted due to a corruption problem or because the video used features your browser did not support.": "Videoafspilningen blev afbrudt på grund af ødelagte data eller fordi videoen benyttede faciliteter som din browser ikke understøtter.", "No compatible source was found for this video.": "Fandt ikke en kompatibel kilde for denne video." });
hoenirvili/EDeC
src/html/plugins/videojs/dist/lang/da.js
JavaScript
gpl-2.0
1,406
define([ 'jquery', 'underscore', 'common/js/spec_helpers/template_helpers', 'js/spec/edxnotes/helpers', 'js/edxnotes/collections/notes', 'js/edxnotes/collections/tabs', 'js/edxnotes/views/tabs/course_structure', 'js/spec/edxnotes/custom_matchers', 'jasmine-jquery' ], function( $, _, TemplateHelpers, Helpers, NotesCollection, TabsCollection, CourseStructureView, customMatchers ) { 'use strict'; describe('EdxNotes CourseStructureView', function() { var notes = Helpers.getDefaultNotes(), getView, getText; getText = function (selector) { return $(selector).map(function () { return _.trim($(this).text()); }).toArray(); }; getView = function (collection, tabsCollection, options) { var view; options = _.defaults(options || {}, { el: $('.wrapper-student-notes'), collection: collection, tabsCollection: tabsCollection, }); view = new CourseStructureView(options); tabsCollection.at(0).activate(); return view; }; beforeEach(function () { customMatchers(this); loadFixtures('js/fixtures/edxnotes/edxnotes.html'); TemplateHelpers.installTemplates([ 'templates/edxnotes/note-item', 'templates/edxnotes/tab-item' ]); this.collection = new NotesCollection(notes); this.tabsCollection = new TabsCollection(); }); it('displays a tab and content with proper data and order', function () { var view = getView(this.collection, this.tabsCollection), chapters = getText('.course-title'), sections = getText('.course-subtitle'), notes = getText('.note-excerpt-p'); expect(this.tabsCollection).toHaveLength(1); expect(this.tabsCollection.at(0).toJSON()).toEqual({ name: 'Location in Course', identifier: 'view-course-structure', icon: 'fa fa-list-ul', is_active: true, is_closable: false, view: 'Location in Course' }); expect(view.$('#structure-panel')).toExist(); expect(chapters).toEqual(['First Chapter', 'Second Chapter']); expect(sections).toEqual(['First Section', 'Second Section', 'Third Section']); expect(notes).toEqual(['Note 1', 'Note 2', 'Note 3', 'Note 4', 'Note 5']); }); }); });
Semi-global/edx-platform
lms/static/js/spec/edxnotes/views/tabs/course_structure_spec.js
JavaScript
agpl-3.0
2,601
// This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /* * @package atto_fontcolor * @copyright 2014 Rossiani Wijaya <rwijaya@moodle.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ /** * @module moodle-atto_align-button */ /** * Atto text editor fontcolor plugin. * * @namespace M.atto_fontcolor * @class button * @extends M.editor_atto.EditorPlugin */ var colors = [ { name: 'white', color: '#FFFFFF' }, { name: 'red', color: '#EF4540' }, { name: 'yellow', color: '#FFCF35' }, { name: 'green', color: '#98CA3E' }, { name: 'blue', color: '#7D9FD3' }, { name: 'black', color: '#333333' } ]; Y.namespace('M.atto_fontcolor').Button = Y.Base.create('button', Y.M.editor_atto.EditorPlugin, [], { initializer: function() { var items = []; Y.Array.each(colors, function(color) { items.push({ text: '<div style="width: 20px; height: 20px; border: 1px solid #CCC; background-color: ' + color.color + '"></div>', callbackArgs: color.color, callback: this._changeStyle }); }); this.addToolbarMenu({ icon: 'e/text_color', overlayWidth: '4', menuColor: '#333333', globalItemConfig: { callback: this._changeStyle }, items: items }); }, /** * Change the font color to the specified color. * * @method _changeStyle * @param {EventFacade} e * @param {string} color The new font color * @private */ _changeStyle: function(e, color) { this.get('host').formatSelectionInlineStyle({ color: color }); } });
sameertechworks/wpmoodle
moodle/lib/editor/atto/plugins/fontcolor/yui/src/button/js/button.js
JavaScript
gpl-2.0
2,604
/*! 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}})();
arterli/CmsWing
www/static/assets/plugins/select2/js/i18n/az.js
JavaScript
mit
706
//// 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); } })();
oldnewthing/Windows-universal-samples
archived/AnimationLibrary/js/js/crossfade.js
JavaScript
mit
791
import "../arrays/map"; import "../core/array"; import "../core/identity"; import "../math/trigonometry"; var d3_ease_default = function() { return d3_identity; }; var d3_ease = d3.map({ linear: d3_ease_default, poly: d3_ease_poly, quad: function() { return d3_ease_quad; }, cubic: function() { return d3_ease_cubic; }, sin: function() { return d3_ease_sin; }, exp: function() { return d3_ease_exp; }, circle: function() { return d3_ease_circle; }, elastic: d3_ease_elastic, back: d3_ease_back, bounce: function() { return d3_ease_bounce; } }); var d3_ease_mode = d3.map({ "in": d3_identity, "out": d3_ease_reverse, "in-out": d3_ease_reflect, "out-in": function(f) { return d3_ease_reflect(d3_ease_reverse(f)); } }); d3.ease = function(name) { var i = name.indexOf("-"), t = i >= 0 ? name.slice(0, i) : name, m = i >= 0 ? name.slice(i + 1) : "in"; t = d3_ease.get(t) || d3_ease_default; m = d3_ease_mode.get(m) || d3_identity; return d3_ease_clamp(m(t.apply(null, d3_arraySlice.call(arguments, 1)))); }; function d3_ease_clamp(f) { return function(t) { return t <= 0 ? 0 : t >= 1 ? 1 : f(t); }; } function d3_ease_reverse(f) { return function(t) { return 1 - f(1 - t); }; } function d3_ease_reflect(f) { return function(t) { return 0.5 * (t < 0.5 ? f(2 * t) : (2 - f(2 - 2 * t))); }; } function d3_ease_quad(t) { return t * t; } function d3_ease_cubic(t) { return t * t * t; } // Optimized clamp(reflect(poly(3))). function d3_ease_cubicInOut(t) { if (t <= 0) return 0; if (t >= 1) return 1; var t2 = t * t, t3 = t2 * t; return 4 * (t < 0.5 ? t3 : 3 * (t - t2) + t3 - 0.75); } function d3_ease_poly(e) { return function(t) { return Math.pow(t, e); }; } function d3_ease_sin(t) { return 1 - Math.cos(t * halfπ); } function d3_ease_exp(t) { return Math.pow(2, 10 * (t - 1)); } function d3_ease_circle(t) { return 1 - Math.sqrt(1 - t * t); } function d3_ease_elastic(a, p) { var s; if (arguments.length < 2) p = 0.45; if (arguments.length) s = p / τ * Math.asin(1 / a); else a = 1, s = p / 4; return function(t) { return 1 + a * Math.pow(2, -10 * t) * Math.sin((t - s) * τ / p); }; } function d3_ease_back(s) { if (!s) s = 1.70158; return function(t) { return t * t * ((s + 1) * t - s); }; } function d3_ease_bounce(t) { return t < 1 / 2.75 ? 7.5625 * t * t : t < 2 / 2.75 ? 7.5625 * (t -= 1.5 / 2.75) * t + 0.75 : t < 2.5 / 2.75 ? 7.5625 * (t -= 2.25 / 2.75) * t + 0.9375 : 7.5625 * (t -= 2.625 / 2.75) * t + 0.984375; }
angrycactus/dkan
webroot/profiles/dkan/libraries/d3/src/interpolate/ease.js
JavaScript
gpl-2.0
2,583
module.exports = []
MatteoGabriele/vue-i18n-manager
webpack/plugins.js
JavaScript
mit
20
var mdeps = require('../'); var test = require('tape'); var JSONStream = require('JSONStream'); var packer = require('browser-pack'); var concat = require('concat-stream'); var path = require('path'); test('global transforms', function (t) { t.plan(1); var p = mdeps({ transform: [ 'tr-c', 'tr-d' ], globalTransform: [ path.join(__dirname, '/files/tr_global/node_modules/tr-e'), path.join(__dirname, '/files/tr_global/node_modules/tr-f') ], transformKey: [ 'browserify', 'transform' ] }); p.end(path.join(__dirname, '/files/tr_global/main.js')); var pack = packer(); p.pipe(JSONStream.stringify()).pipe(pack).pipe(concat(function (src) { Function(['console'], src)({ log: function (msg) { t.equal(msg, 111111); } }); })); });
bpatters/eservice
ui/node_modules/browserify/node_modules/module-deps/test/tr_global.js
JavaScript
apache-2.0
877
'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;} }); }]);
marcoR80/simple-app-mobile
www/vendor/angular-1.3.9/i18n/angular-locale_chr-us.js
JavaScript
mit
2,554
var Types = require('../constants/types'); var Charsets = require('../constants/charsets'); var Field = require('./Field'); var IEEE_754_BINARY_64_PRECISION = Math.pow(2, 53); module.exports = RowDataPacket; function RowDataPacket() { } Object.defineProperty(RowDataPacket.prototype, 'parse', { configurable : true, enumerable : false, value : parse }); Object.defineProperty(RowDataPacket.prototype, '_typeCast', { configurable : true, enumerable : false, value : typeCast }); function parse(parser, fieldPackets, typeCast, nestTables, connection) { var self = this; var next = function () { return self._typeCast(fieldPacket, parser, connection.config.timezone, connection.config.supportBigNumbers, connection.config.bigNumberStrings, connection.config.dateStrings); }; for (var i = 0; i < fieldPackets.length; i++) { var fieldPacket = fieldPackets[i]; var value; if (typeof typeCast === 'function') { value = typeCast.apply(connection, [ new Field({ packet: fieldPacket, parser: parser }), next ]); } else { value = (typeCast) ? this._typeCast(fieldPacket, parser, connection.config.timezone, connection.config.supportBigNumbers, connection.config.bigNumberStrings, connection.config.dateStrings) : ( (fieldPacket.charsetNr === Charsets.BINARY) ? parser.parseLengthCodedBuffer() : parser.parseLengthCodedString() ); } if (typeof nestTables === 'string' && nestTables.length) { this[fieldPacket.table + nestTables + fieldPacket.name] = value; } else if (nestTables) { this[fieldPacket.table] = this[fieldPacket.table] || {}; this[fieldPacket.table][fieldPacket.name] = value; } else { this[fieldPacket.name] = value; } } } function typeCast(field, parser, timeZone, supportBigNumbers, bigNumberStrings, dateStrings) { var numberString; switch (field.type) { case Types.TIMESTAMP: case Types.TIMESTAMP2: case Types.DATE: case Types.DATETIME: case Types.DATETIME2: case Types.NEWDATE: var dateString = parser.parseLengthCodedString(); if (typeMatch(field.type, dateStrings)) { return dateString; } if (dateString === null) { return null; } var originalString = dateString; if (field.type === Types.DATE) { dateString += ' 00:00:00'; } if (timeZone !== 'local') { dateString += ' ' + timeZone; } var dt = new Date(dateString); if (isNaN(dt.getTime())) { return originalString; } return dt; case Types.TINY: case Types.SHORT: case Types.LONG: case Types.INT24: case Types.YEAR: case Types.FLOAT: case Types.DOUBLE: numberString = parser.parseLengthCodedString(); return (numberString === null || (field.zeroFill && numberString[0] === '0')) ? numberString : Number(numberString); case Types.NEWDECIMAL: case Types.LONGLONG: numberString = parser.parseLengthCodedString(); return (numberString === null || (field.zeroFill && numberString[0] === '0')) ? numberString : ((supportBigNumbers && (bigNumberStrings || (Number(numberString) >= IEEE_754_BINARY_64_PRECISION) || Number(numberString) <= -IEEE_754_BINARY_64_PRECISION)) ? numberString : Number(numberString)); case Types.BIT: return parser.parseLengthCodedBuffer(); case Types.STRING: case Types.VAR_STRING: case Types.TINY_BLOB: case Types.MEDIUM_BLOB: case Types.LONG_BLOB: case Types.BLOB: return (field.charsetNr === Charsets.BINARY) ? parser.parseLengthCodedBuffer() : parser.parseLengthCodedString(); case Types.GEOMETRY: return parser.parseGeometryValue(); default: return parser.parseLengthCodedString(); } } function typeMatch(type, list) { if (Array.isArray(list)) { for (var i = 0; i < list.length; i++) { if (Types[list[i]] === type) return true; } return false; } else { return Boolean(list); } }
bestlingna/test
极客学院任务学习/任务九/nodeBaiduNews/node_modules/mysql/lib/protocol/packets/RowDataPacket.js
JavaScript
apache-2.0
4,159
/**! * TableSorter 2.17.7 - Client-side table sorting with ease! * @requires jQuery v1.2.6+ * * Copyright (c) 2007 Christian Bach * Examples and docs at: http://tablesorter.com * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * * @type jQuery * @name tablesorter * @cat Plugins/Tablesorter * @author Christian Bach/christian.bach@polyester.se * @contributor Rob Garrison/https://github.com/Mottie/tablesorter */ /*jshint browser:true, jquery:true, unused:false, expr: true */ /*global console:false, alert:false */ !(function($) { "use strict"; $.extend({ /*jshint supernew:true */ tablesorter: new function() { var ts = this; ts.version = "2.17.7"; ts.parsers = []; ts.widgets = []; ts.defaults = { // *** appearance theme : 'default', // adds tablesorter-{theme} to the table for styling widthFixed : false, // adds colgroup to fix widths of columns showProcessing : false, // show an indeterminate timer icon in the header when the table is sorted or filtered. headerTemplate : '{content}',// header layout template (HTML ok); {content} = innerHTML, {icon} = <i/> (class from cssIcon) onRenderTemplate : null, // function(index, template){ return template; }, (template is a string) onRenderHeader : null, // function(index){}, (nothing to return) // *** functionality cancelSelection : true, // prevent text selection in the header tabIndex : true, // add tabindex to header for keyboard accessibility dateFormat : 'mmddyyyy', // other options: "ddmmyyy" or "yyyymmdd" sortMultiSortKey : 'shiftKey', // key used to select additional columns sortResetKey : 'ctrlKey', // key used to remove sorting on a column usNumberFormat : true, // false for German "1.234.567,89" or French "1 234 567,89" delayInit : false, // if false, the parsed table contents will not update until the first sort serverSideSorting: false, // if true, server-side sorting should be performed because client-side sorting will be disabled, but the ui and events will still be used. // *** sort options headers : {}, // set sorter, string, empty, locked order, sortInitialOrder, filter, etc. ignoreCase : true, // ignore case while sorting sortForce : null, // column(s) first sorted; always applied sortList : [], // Initial sort order; applied initially; updated when manually sorted sortAppend : null, // column(s) sorted last; always applied sortStable : false, // when sorting two rows with exactly the same content, the original sort order is maintained sortInitialOrder : 'asc', // sort direction on first click sortLocaleCompare: false, // replace equivalent character (accented characters) sortReset : false, // third click on the header will reset column to default - unsorted sortRestart : false, // restart sort to "sortInitialOrder" when clicking on previously unsorted columns emptyTo : 'bottom', // sort empty cell to bottom, top, none, zero stringTo : 'max', // sort strings in numerical column as max, min, top, bottom, zero textExtraction : 'basic', // text extraction method/function - function(node, table, cellIndex){} textAttribute : 'data-text',// data-attribute that contains alternate cell text (used in textExtraction function) textSorter : null, // choose overall or specific column sorter function(a, b, direction, table, columnIndex) [alt: ts.sortText] numberSorter : null, // choose overall numeric sorter function(a, b, direction, maxColumnValue) // *** widget options widgets: [], // method to add widgets, e.g. widgets: ['zebra'] widgetOptions : { zebra : [ 'even', 'odd' ] // zebra widget alternating row class names }, initWidgets : true, // apply widgets on tablesorter initialization // *** callbacks initialized : null, // function(table){}, // *** extra css class names tableClass : '', cssAsc : '', cssDesc : '', cssNone : '', cssHeader : '', cssHeaderRow : '', cssProcessing : '', // processing icon applied to header during sort/filter cssChildRow : 'tablesorter-childRow', // class name indiciating that a row is to be attached to the its parent cssIcon : 'tablesorter-icon', // if this class exists, a <i> will be added to the header automatically cssInfoBlock : 'tablesorter-infoOnly', // don't sort tbody with this class name (only one class name allowed here!) // *** selectors selectorHeaders : '> thead th, > thead td', selectorSort : 'th, td', // jQuery selector of content within selectorHeaders that is clickable to trigger a sort selectorRemove : '.remove-me', // *** advanced debug : false, // *** Internal variables headerList: [], empties: {}, strings: {}, parsers: [] // deprecated; but retained for backwards compatibility // widgetZebra: { css: ["even", "odd"] } }; // internal css classes - these will ALWAYS be added to // the table and MUST only contain one class name - fixes #381 ts.css = { table : 'tablesorter', cssHasChild: 'tablesorter-hasChildRow', childRow : 'tablesorter-childRow', header : 'tablesorter-header', headerRow : 'tablesorter-headerRow', headerIn : 'tablesorter-header-inner', icon : 'tablesorter-icon', info : 'tablesorter-infoOnly', processing : 'tablesorter-processing', sortAsc : 'tablesorter-headerAsc', sortDesc : 'tablesorter-headerDesc', sortNone : 'tablesorter-headerUnSorted' }; // labels applied to sortable headers for accessibility (aria) support ts.language = { sortAsc : 'Ascending sort applied, ', sortDesc : 'Descending sort applied, ', sortNone : 'No sort applied, ', nextAsc : 'activate to apply an ascending sort', nextDesc : 'activate to apply a descending sort', nextNone : 'activate to remove the sort' }; /* debuging utils */ function log() { var a = arguments[0], s = arguments.length > 1 ? Array.prototype.slice.call(arguments) : a; if (typeof console !== "undefined" && typeof console.log !== "undefined") { console[ /error/i.test(a) ? 'error' : /warn/i.test(a) ? 'warn' : 'log' ](s); } else { alert(s); } } function benchmark(s, d) { log(s + " (" + (new Date().getTime() - d.getTime()) + "ms)"); } ts.log = log; ts.benchmark = benchmark; // $.isEmptyObject from jQuery v1.4 function isEmptyObject(obj) { /*jshint forin: false */ for (var name in obj) { return false; } return true; } function getElementText(table, node, cellIndex) { if (!node) { return ""; } var te, c = table.config, t = c.textExtraction || '', text = ""; if (t === "basic") { // check data-attribute first text = $(node).attr(c.textAttribute) || node.textContent || node.innerText || $(node).text() || ""; } else { if (typeof(t) === "function") { text = t(node, table, cellIndex); } else if (typeof (te = ts.getColumnData( table, t, cellIndex )) === 'function') { text = te(node, table, cellIndex); } else { // previous "simple" method text = node.textContent || node.innerText || $(node).text() || ""; } } return $.trim(text); } function detectParserForColumn(table, rows, rowIndex, cellIndex) { var cur, i = ts.parsers.length, node = false, nodeValue = '', keepLooking = true; while (nodeValue === '' && keepLooking) { rowIndex++; if (rows[rowIndex]) { node = rows[rowIndex].cells[cellIndex]; nodeValue = getElementText(table, node, cellIndex); if (table.config.debug) { log('Checking if value was empty on row ' + rowIndex + ', column: ' + cellIndex + ': "' + nodeValue + '"'); } } else { keepLooking = false; } } while (--i >= 0) { cur = ts.parsers[i]; // ignore the default text parser because it will always be true if (cur && cur.id !== 'text' && cur.is && cur.is(nodeValue, table, node)) { return cur; } } // nothing found, return the generic parser (text) return ts.getParserById('text'); } function buildParserCache(table) { var c = table.config, // update table bodies in case we start with an empty table tb = c.$tbodies = c.$table.children('tbody:not(.' + c.cssInfoBlock + ')'), rows, list, l, i, h, ch, np, p, e, time, j = 0, parsersDebug = "", len = tb.length; if ( len === 0) { return c.debug ? log('Warning: *Empty table!* Not building a parser cache') : ''; } else if (c.debug) { time = new Date(); log('Detecting parsers for each column'); } list = { extractors: [], parsers: [] }; while (j < len) { rows = tb[j].rows; if (rows[j]) { l = c.columns; // rows[j].cells.length; for (i = 0; i < l; i++) { h = c.$headers.filter('[data-column="' + i + '"]:last'); // get column indexed table cell ch = ts.getColumnData( table, c.headers, i ); // get column parser/extractor e = ts.getParserById( ts.getData(h, ch, 'extractor') ); p = ts.getParserById( ts.getData(h, ch, 'sorter') ); np = ts.getData(h, ch, 'parser') === 'false'; // empty cells behaviour - keeping emptyToBottom for backwards compatibility c.empties[i] = ts.getData(h, ch, 'empty') || c.emptyTo || (c.emptyToBottom ? 'bottom' : 'top' ); // text strings behaviour in numerical sorts c.strings[i] = ts.getData(h, ch, 'string') || c.stringTo || 'max'; if (np) { p = ts.getParserById('no-parser'); } if (!e) { // For now, maybe detect someday e = false; } if (!p) { p = detectParserForColumn(table, rows, -1, i); } if (c.debug) { parsersDebug += "column:" + i + "; extractor:" + e.id + "; parser:" + p.id + "; string:" + c.strings[i] + '; empty: ' + c.empties[i] + "\n"; } list.parsers[i] = p; list.extractors[i] = e; } } j += (list.parsers.length) ? len : 1; } if (c.debug) { log(parsersDebug ? parsersDebug : "No parsers detected"); benchmark("Completed detecting parsers", time); } c.parsers = list.parsers; c.extractors = list.extractors; } /* utils */ function buildCache(table) { var cc, t, tx, v, i, j, k, $row, rows, cols, cacheTime, totalRows, rowData, colMax, c = table.config, $tb = c.$table.children('tbody'), extractors = c.extractors, parsers = c.parsers; c.cache = {}; c.totalRows = 0; // if no parsers found, return - it's an empty table. if (!parsers) { return c.debug ? log('Warning: *Empty table!* Not building a cache') : ''; } if (c.debug) { cacheTime = new Date(); } // processing icon if (c.showProcessing) { ts.isProcessing(table, true); } for (k = 0; k < $tb.length; k++) { colMax = []; // column max value per tbody cc = c.cache[k] = { normalized: [] // array of normalized row data; last entry contains "rowData" above // colMax: # // added at the end }; // ignore tbodies with class name from c.cssInfoBlock if (!$tb.eq(k).hasClass(c.cssInfoBlock)) { totalRows = ($tb[k] && $tb[k].rows.length) || 0; for (i = 0; i < totalRows; ++i) { rowData = { // order: original row order # // $row : jQuery Object[] child: [] // child row text (filter widget) }; /** Add the table data to main data array */ $row = $($tb[k].rows[i]); rows = [ new Array(c.columns) ]; cols = []; // if this is a child row, add it to the last row's children and continue to the next row // ignore child row class, if it is the first row if ($row.hasClass(c.cssChildRow) && i !== 0) { t = cc.normalized.length - 1; cc.normalized[t][c.columns].$row = cc.normalized[t][c.columns].$row.add($row); // add "hasChild" class name to parent row if (!$row.prev().hasClass(c.cssChildRow)) { $row.prev().addClass(ts.css.cssHasChild); } // save child row content (un-parsed!) rowData.child[t] = $.trim( $row[0].textContent || $row[0].innerText || $row.text() || "" ); // go to the next for loop continue; } rowData.$row = $row; rowData.order = i; // add original row position to rowCache for (j = 0; j < c.columns; ++j) { if (typeof parsers[j] === 'undefined') { if (c.debug) { log('No parser found for cell:', $row[0].cells[j], 'does it have a header?'); } continue; } t = getElementText(table, $row[0].cells[j], j); // do extract before parsing if there is one if (typeof extractors[j].id === 'undefined') { tx = t; } else { tx = extractors[j].format(t, table, $row[0].cells[j], j); } // allow parsing if the string is empty, previously parsing would change it to zero, // in case the parser needs to extract data from the table cell attributes v = parsers[j].id === 'no-parser' ? '' : parsers[j].format(tx, table, $row[0].cells[j], j); cols.push( c.ignoreCase && typeof v === 'string' ? v.toLowerCase() : v ); if ((parsers[j].type || '').toLowerCase() === "numeric") { // determine column max value (ignore sign) colMax[j] = Math.max(Math.abs(v) || 0, colMax[j] || 0); } } // ensure rowData is always in the same location (after the last column) cols[c.columns] = rowData; cc.normalized.push(cols); } cc.colMax = colMax; // total up rows, not including child rows c.totalRows += cc.normalized.length; } } if (c.showProcessing) { ts.isProcessing(table); // remove processing icon } if (c.debug) { benchmark("Building cache for " + totalRows + " rows", cacheTime); } } // init flag (true) used by pager plugin to prevent widget application function appendToTable(table, init) { var c = table.config, wo = c.widgetOptions, b = table.tBodies, rows = [], cc = c.cache, n, totalRows, $bk, $tb, i, k, appendTime; // empty table - fixes #206/#346 if (isEmptyObject(cc)) { // run pager appender in case the table was just emptied return c.appender ? c.appender(table, rows) : table.isUpdating ? c.$table.trigger("updateComplete", table) : ''; // Fixes #532 } if (c.debug) { appendTime = new Date(); } for (k = 0; k < b.length; k++) { $bk = $(b[k]); if ($bk.length && !$bk.hasClass(c.cssInfoBlock)) { // get tbody $tb = ts.processTbody(table, $bk, true); n = cc[k].normalized; totalRows = n.length; for (i = 0; i < totalRows; i++) { rows.push(n[i][c.columns].$row); // removeRows used by the pager plugin; don't render if using ajax - fixes #411 if (!c.appender || (c.pager && (!c.pager.removeRows || !wo.pager_removeRows) && !c.pager.ajax)) { $tb.append(n[i][c.columns].$row); } } // restore tbody ts.processTbody(table, $tb, false); } } if (c.appender) { c.appender(table, rows); } if (c.debug) { benchmark("Rebuilt table", appendTime); } // apply table widgets; but not before ajax completes if (!init && !c.appender) { ts.applyWidget(table); } if (table.isUpdating) { c.$table.trigger("updateComplete", table); } } function formatSortingOrder(v) { // look for "d" in "desc" order; return true return (/^d/i.test(v) || v === 1); } function buildHeaders(table) { var ch, $t, h, i, t, lock, time, c = table.config; c.headerList = []; c.headerContent = []; if (c.debug) { time = new Date(); } // children tr in tfoot - see issue #196 & #547 c.columns = ts.computeColumnIndex( c.$table.children('thead, tfoot').children('tr') ); // add icon if cssIcon option exists i = c.cssIcon ? '<i class="' + ( c.cssIcon === ts.css.icon ? ts.css.icon : c.cssIcon + ' ' + ts.css.icon ) + '"></i>' : ''; // redefine c.$headers here in case of an updateAll that replaces or adds an entire header cell - see #683 c.$headers = $(table).find(c.selectorHeaders).each(function(index) { $t = $(this); // make sure to get header cell & not column indexed cell ch = ts.getColumnData( table, c.headers, index, true ); // save original header content c.headerContent[index] = $(this).html(); // set up header template t = c.headerTemplate.replace(/\{content\}/g, $(this).html()).replace(/\{icon\}/g, i); if (c.onRenderTemplate) { h = c.onRenderTemplate.apply($t, [index, t]); if (h && typeof h === 'string') { t = h; } // only change t if something is returned } $(this).html('<div class="' + ts.css.headerIn + '">' + t + '</div>'); // faster than wrapInner if (c.onRenderHeader) { c.onRenderHeader.apply($t, [index]); } this.column = parseInt( $(this).attr('data-column'), 10); this.order = formatSortingOrder( ts.getData($t, ch, 'sortInitialOrder') || c.sortInitialOrder ) ? [1,0,2] : [0,1,2]; this.count = -1; // set to -1 because clicking on the header automatically adds one this.lockedOrder = false; lock = ts.getData($t, ch, 'lockedOrder') || false; if (typeof lock !== 'undefined' && lock !== false) { this.order = this.lockedOrder = formatSortingOrder(lock) ? [1,1,1] : [0,0,0]; } $t.addClass(ts.css.header + ' ' + c.cssHeader); // add cell to headerList c.headerList[index] = this; // add to parent in case there are multiple rows $t.parent().addClass(ts.css.headerRow + ' ' + c.cssHeaderRow).attr('role', 'row'); // allow keyboard cursor to focus on element if (c.tabIndex) { $t.attr("tabindex", 0); } }).attr({ scope: 'col', role : 'columnheader' }); // enable/disable sorting updateHeader(table); if (c.debug) { benchmark("Built headers:", time); log(c.$headers); } } function commonUpdate(table, resort, callback) { var c = table.config; // remove rows/elements before update c.$table.find(c.selectorRemove).remove(); // rebuild parsers buildParserCache(table); // rebuild the cache map buildCache(table); checkResort(c.$table, resort, callback); } function updateHeader(table) { var s, $th, col, c = table.config; c.$headers.each(function(index, th){ $th = $(th); col = ts.getColumnData( table, c.headers, index, true ); // add "sorter-false" class if "parser-false" is set s = ts.getData( th, col, 'sorter' ) === 'false' || ts.getData( th, col, 'parser' ) === 'false'; th.sortDisabled = s; $th[ s ? 'addClass' : 'removeClass' ]('sorter-false').attr('aria-disabled', '' + s); // aria-controls - requires table ID if (table.id) { if (s) { $th.removeAttr('aria-controls'); } else { $th.attr('aria-controls', table.id); } } }); } function setHeadersCss(table) { var f, i, j, c = table.config, list = c.sortList, len = list.length, none = ts.css.sortNone + ' ' + c.cssNone, css = [ts.css.sortAsc + ' ' + c.cssAsc, ts.css.sortDesc + ' ' + c.cssDesc], aria = ['ascending', 'descending'], // find the footer $t = $(table).find('tfoot tr').children().add(c.$extraHeaders).removeClass(css.join(' ')); // remove all header information c.$headers .removeClass(css.join(' ')) .addClass(none).attr('aria-sort', 'none'); for (i = 0; i < len; i++) { // direction = 2 means reset! if (list[i][1] !== 2) { // multicolumn sorting updating - choose the :last in case there are nested columns f = c.$headers.not('.sorter-false').filter('[data-column="' + list[i][0] + '"]' + (len === 1 ? ':last' : '') ); if (f.length) { for (j = 0; j < f.length; j++) { if (!f[j].sortDisabled) { f.eq(j).removeClass(none).addClass(css[list[i][1]]).attr('aria-sort', aria[list[i][1]]); } } // add sorted class to footer & extra headers, if they exist if ($t.length) { $t.filter('[data-column="' + list[i][0] + '"]').removeClass(none).addClass(css[list[i][1]]); } } } } // add verbose aria labels c.$headers.not('.sorter-false').each(function(){ var $this = $(this), nextSort = this.order[(this.count + 1) % (c.sortReset ? 3 : 2)], txt = $this.text() + ': ' + ts.language[ $this.hasClass(ts.css.sortAsc) ? 'sortAsc' : $this.hasClass(ts.css.sortDesc) ? 'sortDesc' : 'sortNone' ] + ts.language[ nextSort === 0 ? 'nextAsc' : nextSort === 1 ? 'nextDesc' : 'nextNone' ]; $this.attr('aria-label', txt ); }); } // automatically add col group, and column sizes if set function fixColumnWidth(table) { if (table.config.widthFixed && $(table).find('colgroup').length === 0) { var colgroup = $('<colgroup>'), overallWidth = $(table).width(); // only add col for visible columns - fixes #371 $(table.tBodies[0]).find("tr:first").children(":visible").each(function() { colgroup.append($('<col>').css('width', parseInt(($(this).width()/overallWidth)*1000, 10)/10 + '%')); }); $(table).prepend(colgroup); } } function updateHeaderSortCount(table, list) { var s, t, o, col, primary, c = table.config, sl = list || c.sortList; c.sortList = []; $.each(sl, function(i,v){ // ensure all sortList values are numeric - fixes #127 col = parseInt(v[0], 10); // make sure header exists o = c.$headers.filter('[data-column="' + col + '"]:last')[0]; if (o) { // prevents error if sorton array is wrong // o.count = o.count + 1; t = ('' + v[1]).match(/^(1|d|s|o|n)/); t = t ? t[0] : ''; // 0/(a)sc (default), 1/(d)esc, (s)ame, (o)pposite, (n)ext switch(t) { case '1': case 'd': // descending t = 1; break; case 's': // same direction (as primary column) // if primary sort is set to "s", make it ascending t = primary || 0; break; case 'o': s = o.order[(primary || 0) % (c.sortReset ? 3 : 2)]; // opposite of primary column; but resets if primary resets t = s === 0 ? 1 : s === 1 ? 0 : 2; break; case 'n': o.count = o.count + 1; t = o.order[(o.count) % (c.sortReset ? 3 : 2)]; break; default: // ascending t = 0; break; } primary = i === 0 ? t : primary; s = [ col, parseInt(t, 10) || 0 ]; c.sortList.push(s); t = $.inArray(s[1], o.order); // fixes issue #167 o.count = t >= 0 ? t : s[1] % (c.sortReset ? 3 : 2); } }); } function getCachedSortType(parsers, i) { return (parsers && parsers[i]) ? parsers[i].type || '' : ''; } function initSort(table, cell, event){ if (table.isUpdating) { // let any updates complete before initializing a sort return setTimeout(function(){ initSort(table, cell, event); }, 50); } var arry, indx, col, order, s, c = table.config, key = !event[c.sortMultiSortKey], $table = c.$table; // Only call sortStart if sorting is enabled $table.trigger("sortStart", table); // get current column sort order cell.count = event[c.sortResetKey] ? 2 : (cell.count + 1) % (c.sortReset ? 3 : 2); // reset all sorts on non-current column - issue #30 if (c.sortRestart) { indx = cell; c.$headers.each(function() { // only reset counts on columns that weren't just clicked on and if not included in a multisort if (this !== indx && (key || !$(this).is('.' + ts.css.sortDesc + ',.' + ts.css.sortAsc))) { this.count = -1; } }); } // get current column index indx = cell.column; // user only wants to sort on one column if (key) { // flush the sort list c.sortList = []; if (c.sortForce !== null) { arry = c.sortForce; for (col = 0; col < arry.length; col++) { if (arry[col][0] !== indx) { c.sortList.push(arry[col]); } } } // add column to sort list order = cell.order[cell.count]; if (order < 2) { c.sortList.push([indx, order]); // add other columns if header spans across multiple if (cell.colSpan > 1) { for (col = 1; col < cell.colSpan; col++) { c.sortList.push([indx + col, order]); } } } // multi column sorting } else { // get rid of the sortAppend before adding more - fixes issue #115 & #523 if (c.sortAppend && c.sortList.length > 1) { for (col = 0; col < c.sortAppend.length; col++) { s = ts.isValueInArray(c.sortAppend[col][0], c.sortList); if (s >= 0) { c.sortList.splice(s,1); } } } // the user has clicked on an already sorted column if (ts.isValueInArray(indx, c.sortList) >= 0) { // reverse the sorting direction for (col = 0; col < c.sortList.length; col++) { s = c.sortList[col]; order = c.$headers.filter('[data-column="' + s[0] + '"]:last')[0]; if (s[0] === indx) { // order.count seems to be incorrect when compared to cell.count s[1] = order.order[cell.count]; if (s[1] === 2) { c.sortList.splice(col,1); order.count = -1; } } } } else { // add column to sort list array order = cell.order[cell.count]; if (order < 2) { c.sortList.push([indx, order]); // add other columns if header spans across multiple if (cell.colSpan > 1) { for (col = 1; col < cell.colSpan; col++) { c.sortList.push([indx + col, order]); } } } } } if (c.sortAppend !== null) { arry = c.sortAppend; for (col = 0; col < arry.length; col++) { if (arry[col][0] !== indx) { c.sortList.push(arry[col]); } } } // sortBegin event triggered immediately before the sort $table.trigger("sortBegin", table); // setTimeout needed so the processing icon shows up setTimeout(function(){ // set css for headers setHeadersCss(table); multisort(table); appendToTable(table); $table.trigger("sortEnd", table); }, 1); } // sort multiple columns function multisort(table) { /*jshint loopfunc:true */ var i, k, num, col, sortTime, colMax, cache, order, sort, x, y, dir = 0, c = table.config, cts = c.textSorter || '', sortList = c.sortList, l = sortList.length, bl = table.tBodies.length; if (c.serverSideSorting || isEmptyObject(c.cache)) { // empty table - fixes #206/#346 return; } if (c.debug) { sortTime = new Date(); } for (k = 0; k < bl; k++) { colMax = c.cache[k].colMax; cache = c.cache[k].normalized; cache.sort(function(a, b) { // cache is undefined here in IE, so don't use it! for (i = 0; i < l; i++) { col = sortList[i][0]; order = sortList[i][1]; // sort direction, true = asc, false = desc dir = order === 0; if (c.sortStable && a[col] === b[col] && l === 1) { return a[c.columns].order - b[c.columns].order; } // fallback to natural sort since it is more robust num = /n/i.test(getCachedSortType(c.parsers, col)); if (num && c.strings[col]) { // sort strings in numerical columns if (typeof (c.string[c.strings[col]]) === 'boolean') { num = (dir ? 1 : -1) * (c.string[c.strings[col]] ? -1 : 1); } else { num = (c.strings[col]) ? c.string[c.strings[col]] || 0 : 0; } // fall back to built-in numeric sort // var sort = $.tablesorter["sort" + s](table, a[c], b[c], c, colMax[c], dir); sort = c.numberSorter ? c.numberSorter(a[col], b[col], dir, colMax[col], table) : ts[ 'sortNumeric' + (dir ? 'Asc' : 'Desc') ](a[col], b[col], num, colMax[col], col, table); } else { // set a & b depending on sort direction x = dir ? a : b; y = dir ? b : a; // text sort function if (typeof(cts) === 'function') { // custom OVERALL text sorter sort = cts(x[col], y[col], dir, col, table); } else if (typeof(cts) === 'object' && cts.hasOwnProperty(col)) { // custom text sorter for a SPECIFIC COLUMN sort = cts[col](x[col], y[col], dir, col, table); } else { // fall back to natural sort sort = ts[ 'sortNatural' + (dir ? 'Asc' : 'Desc') ](a[col], b[col], col, table, c); } } if (sort) { return sort; } } return a[c.columns].order - b[c.columns].order; }); } if (c.debug) { benchmark("Sorting on " + sortList.toString() + " and dir " + order + " time", sortTime); } } function resortComplete($table, callback){ var table = $table[0]; if (table.isUpdating) { $table.trigger('updateComplete'); } if ($.isFunction(callback)) { callback($table[0]); } } function checkResort($table, flag, callback) { var sl = $table[0].config.sortList; // don't try to resort if the table is still processing // this will catch spamming of the updateCell method if (flag !== false && !$table[0].isProcessing && sl.length) { $table.trigger("sorton", [sl, function(){ resortComplete($table, callback); }, true]); } else { resortComplete($table, callback); ts.applyWidget($table[0], false); } } function bindMethods(table){ var c = table.config, $table = c.$table; // apply easy methods that trigger bound events $table .unbind('sortReset update updateRows updateCell updateAll addRows updateComplete sorton appendCache updateCache applyWidgetId applyWidgets refreshWidgets destroy mouseup mouseleave '.split(' ').join(c.namespace + ' ')) .bind("sortReset" + c.namespace, function(e, callback){ e.stopPropagation(); c.sortList = []; setHeadersCss(table); multisort(table); appendToTable(table); if ($.isFunction(callback)) { callback(table); } }) .bind("updateAll" + c.namespace, function(e, resort, callback){ e.stopPropagation(); table.isUpdating = true; ts.refreshWidgets(table, true, true); ts.restoreHeaders(table); buildHeaders(table); ts.bindEvents(table, c.$headers, true); bindMethods(table); commonUpdate(table, resort, callback); }) .bind("update" + c.namespace + " updateRows" + c.namespace, function(e, resort, callback) { e.stopPropagation(); table.isUpdating = true; // update sorting (if enabled/disabled) updateHeader(table); commonUpdate(table, resort, callback); }) .bind("updateCell" + c.namespace, function(e, cell, resort, callback) { e.stopPropagation(); table.isUpdating = true; $table.find(c.selectorRemove).remove(); // get position from the dom var v, t, row, icell, $tb = $table.find('tbody'), $cell = $(cell), // update cache - format: function(s, table, cell, cellIndex) // no closest in jQuery v1.2.6 - tbdy = $tb.index( $(cell).closest('tbody') ),$row = $(cell).closest('tr'); tbdy = $tb.index( $.fn.closest ? $cell.closest('tbody') : $cell.parents('tbody').filter(':first') ), $row = $.fn.closest ? $cell.closest('tr') : $cell.parents('tr').filter(':first'); cell = $cell[0]; // in case cell is a jQuery object // tbody may not exist if update is initialized while tbody is removed for processing if ($tb.length && tbdy >= 0) { row = $tb.eq(tbdy).find('tr').index( $row ); icell = $cell.index(); c.cache[tbdy].normalized[row][c.columns].$row = $row; if (typeof c.extractors[icell].id === 'undefined') { t = getElementText(table, cell, icell); } else { t = c.extractors[icell].format( getElementText(table, cell, icell), table, cell, icell ); } v = c.parsers[icell].id === 'no-parser' ? '' : c.parsers[icell].format( t, table, cell, icell ); c.cache[tbdy].normalized[row][icell] = c.ignoreCase && typeof v === 'string' ? v.toLowerCase() : v; if ((c.parsers[icell].type || '').toLowerCase() === "numeric") { // update column max value (ignore sign) c.cache[tbdy].colMax[icell] = Math.max(Math.abs(v) || 0, c.cache[tbdy].colMax[icell] || 0); } checkResort($table, resort, callback); } }) .bind("addRows" + c.namespace, function(e, $row, resort, callback) { e.stopPropagation(); table.isUpdating = true; if (isEmptyObject(c.cache)) { // empty table, do an update instead - fixes #450 updateHeader(table); commonUpdate(table, resort, callback); } else { $row = $($row).attr('role', 'row'); // make sure we're using a jQuery object var i, j, l, t, v, rowData, cells, rows = $row.filter('tr').length, tbdy = $table.find('tbody').index( $row.parents('tbody').filter(':first') ); // fixes adding rows to an empty table - see issue #179 if (!(c.parsers && c.parsers.length)) { buildParserCache(table); } // add each row for (i = 0; i < rows; i++) { l = $row[i].cells.length; cells = []; rowData = { child: [], $row : $row.eq(i), order: c.cache[tbdy].normalized.length }; // add each cell for (j = 0; j < l; j++) { if (typeof c.extractors[j].id === 'undefined') { t = getElementText(table, $row[i].cells[j], j); } else { t = c.extractors[j].format( getElementText(table, $row[i].cells[j], j), table, $row[i].cells[j], j ); } v = c.parsers[j].id === 'no-parser' ? '' : c.parsers[j].format( t, table, $row[i].cells[j], j ); cells[j] = c.ignoreCase && typeof v === 'string' ? v.toLowerCase() : v; if ((c.parsers[j].type || '').toLowerCase() === "numeric") { // update column max value (ignore sign) c.cache[tbdy].colMax[j] = Math.max(Math.abs(cells[j]) || 0, c.cache[tbdy].colMax[j] || 0); } } // add the row data to the end cells.push(rowData); // update cache c.cache[tbdy].normalized.push(cells); } // resort using current settings checkResort($table, resort, callback); } }) .bind("updateComplete" + c.namespace, function(){ table.isUpdating = false; }) .bind("sorton" + c.namespace, function(e, list, callback, init) { var c = table.config; e.stopPropagation(); $table.trigger("sortStart", this); // update header count index updateHeaderSortCount(table, list); // set css for headers setHeadersCss(table); // fixes #346 if (c.delayInit && isEmptyObject(c.cache)) { buildCache(table); } $table.trigger("sortBegin", this); // sort the table and append it to the dom multisort(table); appendToTable(table, init); $table.trigger("sortEnd", this); ts.applyWidget(table); if ($.isFunction(callback)) { callback(table); } }) .bind("appendCache" + c.namespace, function(e, callback, init) { e.stopPropagation(); appendToTable(table, init); if ($.isFunction(callback)) { callback(table); } }) .bind("updateCache" + c.namespace, function(e, callback){ // rebuild parsers if (!(c.parsers && c.parsers.length)) { buildParserCache(table); } // rebuild the cache map buildCache(table); if ($.isFunction(callback)) { callback(table); } }) .bind("applyWidgetId" + c.namespace, function(e, id) { e.stopPropagation(); ts.getWidgetById(id).format(table, c, c.widgetOptions); }) .bind("applyWidgets" + c.namespace, function(e, init) { e.stopPropagation(); // apply widgets ts.applyWidget(table, init); }) .bind("refreshWidgets" + c.namespace, function(e, all, dontapply){ e.stopPropagation(); ts.refreshWidgets(table, all, dontapply); }) .bind("destroy" + c.namespace, function(e, c, cb){ e.stopPropagation(); ts.destroy(table, c, cb); }) .bind("resetToLoadState" + c.namespace, function(){ // remove all widgets ts.refreshWidgets(table, true, true); // restore original settings; this clears out current settings, but does not clear // values saved to storage. c = $.extend(true, ts.defaults, c.originalSettings); table.hasInitialized = false; // setup the entire table again ts.setup( table, c ); }); } /* public methods */ ts.construct = function(settings) { return this.each(function() { var table = this, // merge & extend config options c = $.extend(true, {}, ts.defaults, settings); // save initial settings c.originalSettings = settings; // create a table from data (build table widget) if (!table.hasInitialized && ts.buildTable && this.tagName !== 'TABLE') { // return the table (in case the original target is the table's container) ts.buildTable(table, c); } else { ts.setup(table, c); } }); }; ts.setup = function(table, c) { // if no thead or tbody, or tablesorter is already present, quit if (!table || !table.tHead || table.tBodies.length === 0 || table.hasInitialized === true) { return c.debug ? log('ERROR: stopping initialization! No table, thead, tbody or tablesorter has already been initialized') : ''; } var k = '', $table = $(table), m = $.metadata; // initialization flag table.hasInitialized = false; // table is being processed flag table.isProcessing = true; // make sure to store the config object table.config = c; // save the settings where they read $.data(table, "tablesorter", c); if (c.debug) { $.data( table, 'startoveralltimer', new Date()); } // removing this in version 3 (only supports jQuery 1.7+) c.supportsDataObject = (function(version) { version[0] = parseInt(version[0], 10); return (version[0] > 1) || (version[0] === 1 && parseInt(version[1], 10) >= 4); })($.fn.jquery.split(".")); // digit sort text location; keeping max+/- for backwards compatibility c.string = { 'max': 1, 'min': -1, 'emptyMin': 1, 'emptyMax': -1, 'zero': 0, 'none': 0, 'null': 0, 'top': true, 'bottom': false }; // add table theme class only if there isn't already one there if (!/tablesorter\-/.test($table.attr('class'))) { k = (c.theme !== '' ? ' tablesorter-' + c.theme : ''); } c.table = table; c.$table = $table .addClass(ts.css.table + ' ' + c.tableClass + k) .attr('role', 'grid'); c.$headers = $table.find(c.selectorHeaders); // give the table a unique id, which will be used in namespace binding if (!c.namespace) { c.namespace = '.tablesorter' + Math.random().toString(16).slice(2); } else { // make sure namespace starts with a period & doesn't have weird characters c.namespace = '.' + c.namespace.replace(/\W/g,''); } c.$table.children().children('tr').attr('role', 'row'); c.$tbodies = $table.children('tbody:not(.' + c.cssInfoBlock + ')').attr({ 'aria-live' : 'polite', 'aria-relevant' : 'all' }); if (c.$table.find('caption').length) { c.$table.attr('aria-labelledby', 'theCaption'); } c.widgetInit = {}; // keep a list of initialized widgets // change textExtraction via data-attribute c.textExtraction = c.$table.attr('data-text-extraction') || c.textExtraction || 'basic'; // build headers buildHeaders(table); // fixate columns if the users supplies the fixedWidth option // do this after theme has been applied fixColumnWidth(table); // try to auto detect column type, and store in tables config buildParserCache(table); // start total row count at zero c.totalRows = 0; // build the cache for the tbody cells // delayInit will delay building the cache until the user starts a sort if (!c.delayInit) { buildCache(table); } // bind all header events and methods ts.bindEvents(table, c.$headers, true); bindMethods(table); // get sort list from jQuery data or metadata // in jQuery < 1.4, an error occurs when calling $table.data() if (c.supportsDataObject && typeof $table.data().sortlist !== 'undefined') { c.sortList = $table.data().sortlist; } else if (m && ($table.metadata() && $table.metadata().sortlist)) { c.sortList = $table.metadata().sortlist; } // apply widget init code ts.applyWidget(table, true); // if user has supplied a sort list to constructor if (c.sortList.length > 0) { $table.trigger("sorton", [c.sortList, {}, !c.initWidgets, true]); } else { setHeadersCss(table); if (c.initWidgets) { // apply widget format ts.applyWidget(table, false); } } // show processesing icon if (c.showProcessing) { $table .unbind('sortBegin' + c.namespace + ' sortEnd' + c.namespace) .bind('sortBegin' + c.namespace + ' sortEnd' + c.namespace, function(e) { clearTimeout(c.processTimer); ts.isProcessing(table); if (e.type === 'sortBegin') { c.processTimer = setTimeout(function(){ ts.isProcessing(table, true); }, 500); } }); } // initialized table.hasInitialized = true; table.isProcessing = false; if (c.debug) { ts.benchmark("Overall initialization time", $.data( table, 'startoveralltimer')); } $table.trigger('tablesorter-initialized', table); if (typeof c.initialized === 'function') { c.initialized(table); } }; ts.getColumnData = function(table, obj, indx, getCell){ if (typeof obj === 'undefined' || obj === null) { return; } table = $(table)[0]; var result, $h, k, c = table.config; if (obj[indx]) { return getCell ? obj[indx] : obj[c.$headers.index( c.$headers.filter('[data-column="' + indx + '"]:last') )]; } for (k in obj) { if (typeof k === 'string') { if (getCell) { // get header cell $h = c.$headers.eq(indx).filter(k); } else { // get column indexed cell $h = c.$headers.filter('[data-column="' + indx + '"]:last').filter(k); } if ($h.length) { return obj[k]; } } } return result; }; // computeTableHeaderCellIndexes from: // http://www.javascripttoolbox.com/lib/table/examples.php // http://www.javascripttoolbox.com/temp/table_cellindex.html ts.computeColumnIndex = function(trs) { var matrix = [], lookup = {}, cols = 0, // determine the number of columns i, j, k, l, $cell, cell, cells, rowIndex, cellId, rowSpan, colSpan, firstAvailCol, matrixrow; for (i = 0; i < trs.length; i++) { cells = trs[i].cells; for (j = 0; j < cells.length; j++) { cell = cells[j]; $cell = $(cell); rowIndex = cell.parentNode.rowIndex; cellId = rowIndex + "-" + $cell.index(); rowSpan = cell.rowSpan || 1; colSpan = cell.colSpan || 1; if (typeof(matrix[rowIndex]) === "undefined") { matrix[rowIndex] = []; } // Find first available column in the first row for (k = 0; k < matrix[rowIndex].length + 1; k++) { if (typeof(matrix[rowIndex][k]) === "undefined") { firstAvailCol = k; break; } } lookup[cellId] = firstAvailCol; cols = Math.max(firstAvailCol, cols); // add data-column $cell.attr({ 'data-column' : firstAvailCol }); // 'data-row' : rowIndex for (k = rowIndex; k < rowIndex + rowSpan; k++) { if (typeof(matrix[k]) === "undefined") { matrix[k] = []; } matrixrow = matrix[k]; for (l = firstAvailCol; l < firstAvailCol + colSpan; l++) { matrixrow[l] = "x"; } } } } // may not be accurate if # header columns !== # tbody columns return cols + 1; // add one because it's a zero-based index }; // *** Process table *** // add processing indicator ts.isProcessing = function(table, toggle, $ths) { table = $(table); var c = table[0].config, // default to all headers $h = $ths || table.find('.' + ts.css.header); if (toggle) { // don't use sortList if custom $ths used if (typeof $ths !== 'undefined' && c.sortList.length > 0) { // get headers from the sortList $h = $h.filter(function(){ // get data-column from attr to keep compatibility with jQuery 1.2.6 return this.sortDisabled ? false : ts.isValueInArray( parseFloat($(this).attr('data-column')), c.sortList) >= 0; }); } table.add($h).addClass(ts.css.processing + ' ' + c.cssProcessing); } else { table.add($h).removeClass(ts.css.processing + ' ' + c.cssProcessing); } }; // detach tbody but save the position // don't use tbody because there are portions that look for a tbody index (updateCell) ts.processTbody = function(table, $tb, getIt){ table = $(table)[0]; var holdr; if (getIt) { table.isProcessing = true; $tb.before('<span class="tablesorter-savemyplace"/>'); holdr = ($.fn.detach) ? $tb.detach() : $tb.remove(); return holdr; } holdr = $(table).find('span.tablesorter-savemyplace'); $tb.insertAfter( holdr ); holdr.remove(); table.isProcessing = false; }; ts.clearTableBody = function(table) { $(table)[0].config.$tbodies.children().detach(); }; ts.bindEvents = function(table, $headers, core){ table = $(table)[0]; var downTime, c = table.config; if (core !== true) { c.$extraHeaders = c.$extraHeaders ? c.$extraHeaders.add($headers) : $headers; } // apply event handling to headers and/or additional headers (stickyheaders, scroller, etc) $headers // http://stackoverflow.com/questions/5312849/jquery-find-self; .find(c.selectorSort).add( $headers.filter(c.selectorSort) ) .unbind('mousedown mouseup sort keyup '.split(' ').join(c.namespace + ' ')) .bind('mousedown mouseup sort keyup '.split(' ').join(c.namespace + ' '), function(e, external) { var cell, type = e.type; // only recognize left clicks or enter if ( ((e.which || e.button) !== 1 && !/sort|keyup/.test(type)) || (type === 'keyup' && e.which !== 13) ) { return; } // ignore long clicks (prevents resizable widget from initializing a sort) if (type === 'mouseup' && external !== true && (new Date().getTime() - downTime > 250)) { return; } // set timer on mousedown if (type === 'mousedown') { downTime = new Date().getTime(); return /(input|select|button|textarea)/i.test(e.target.tagName) ? '' : !c.cancelSelection; } if (c.delayInit && isEmptyObject(c.cache)) { buildCache(table); } // jQuery v1.2.6 doesn't have closest() cell = $.fn.closest ? $(this).closest('th, td')[0] : /TH|TD/.test(this.tagName) ? this : $(this).parents('th, td')[0]; // reference original table headers and find the same cell cell = c.$headers[ $headers.index( cell ) ]; if (!cell.sortDisabled) { initSort(table, cell, e); } }); if (c.cancelSelection) { // cancel selection $headers .attr('unselectable', 'on') .bind('selectstart', false) .css({ 'user-select': 'none', 'MozUserSelect': 'none' // not needed for jQuery 1.8+ }); } }; // restore headers ts.restoreHeaders = function(table){ var c = $(table)[0].config; // don't use c.$headers here in case header cells were swapped c.$table.find(c.selectorHeaders).each(function(i){ // only restore header cells if it is wrapped // because this is also used by the updateAll method if ($(this).find('.' + ts.css.headerIn).length){ $(this).html( c.headerContent[i] ); } }); }; ts.destroy = function(table, removeClasses, callback){ table = $(table)[0]; if (!table.hasInitialized) { return; } // remove all widgets ts.refreshWidgets(table, true, true); var $t = $(table), c = table.config, $h = $t.find('thead:first'), $r = $h.find('tr.' + ts.css.headerRow).removeClass(ts.css.headerRow + ' ' + c.cssHeaderRow), $f = $t.find('tfoot:first > tr').children('th, td'); if (removeClasses === false && $.inArray('uitheme', c.widgets) >= 0) { // reapply uitheme classes, in case we want to maintain appearance $t.trigger('applyWidgetId', ['uitheme']); $t.trigger('applyWidgetId', ['zebra']); } // remove widget added rows, just in case $h.find('tr').not($r).remove(); // disable tablesorter $t .removeData('tablesorter') .unbind('sortReset update updateAll updateRows updateCell addRows updateComplete sorton appendCache updateCache applyWidgetId applyWidgets refreshWidgets destroy mouseup mouseleave keypress sortBegin sortEnd resetToLoadState '.split(' ').join(c.namespace + ' ')); c.$headers.add($f) .removeClass( [ts.css.header, c.cssHeader, c.cssAsc, c.cssDesc, ts.css.sortAsc, ts.css.sortDesc, ts.css.sortNone].join(' ') ) .removeAttr('data-column') .removeAttr('aria-label') .attr('aria-disabled', 'true'); $r.find(c.selectorSort).unbind('mousedown mouseup keypress '.split(' ').join(c.namespace + ' ')); ts.restoreHeaders(table); $t.toggleClass(ts.css.table + ' ' + c.tableClass + ' tablesorter-' + c.theme, removeClasses === false); // clear flag in case the plugin is initialized again table.hasInitialized = false; delete table.config.cache; if (typeof callback === 'function') { callback(table); } }; // *** sort functions *** // regex used in natural sort ts.regex = { chunk : /(^([+\-]?(?:0|[1-9]\d*)(?:\.\d*)?(?:[eE][+\-]?\d+)?)?$|^0x[0-9a-f]+$|\d+)/gi, // chunk/tokenize numbers & letters chunks: /(^\\0|\\0$)/, // replace chunks @ ends hex: /^0x[0-9a-f]+$/i // hex }; // Natural sort - https://github.com/overset/javascript-natural-sort (date sorting removed) // this function will only accept strings, or you'll see "TypeError: undefined is not a function" // I could add a = a.toString(); b = b.toString(); but it'll slow down the sort overall ts.sortNatural = function(a, b) { if (a === b) { return 0; } var xN, xD, yN, yD, xF, yF, i, mx, r = ts.regex; // first try and sort Hex codes if (r.hex.test(b)) { xD = parseInt(a.match(r.hex), 16); yD = parseInt(b.match(r.hex), 16); if ( xD < yD ) { return -1; } if ( xD > yD ) { return 1; } } // chunk/tokenize xN = a.replace(r.chunk, '\\0$1\\0').replace(r.chunks, '').split('\\0'); yN = b.replace(r.chunk, '\\0$1\\0').replace(r.chunks, '').split('\\0'); mx = Math.max(xN.length, yN.length); // natural sorting through split numeric strings and default strings for (i = 0; i < mx; i++) { // find floats not starting with '0', string or 0 if not defined xF = isNaN(xN[i]) ? xN[i] || 0 : parseFloat(xN[i]) || 0; yF = isNaN(yN[i]) ? yN[i] || 0 : parseFloat(yN[i]) || 0; // handle numeric vs string comparison - number < string - (Kyle Adams) if (isNaN(xF) !== isNaN(yF)) { return (isNaN(xF)) ? 1 : -1; } // rely on string comparison if different types - i.e. '02' < 2 != '02' < '2' if (typeof xF !== typeof yF) { xF += ''; yF += ''; } if (xF < yF) { return -1; } if (xF > yF) { return 1; } } return 0; }; ts.sortNaturalAsc = function(a, b, col, table, c) { if (a === b) { return 0; } var e = c.string[ (c.empties[col] || c.emptyTo ) ]; if (a === '' && e !== 0) { return typeof e === 'boolean' ? (e ? -1 : 1) : -e || -1; } if (b === '' && e !== 0) { return typeof e === 'boolean' ? (e ? 1 : -1) : e || 1; } return ts.sortNatural(a, b); }; ts.sortNaturalDesc = function(a, b, col, table, c) { if (a === b) { return 0; } var e = c.string[ (c.empties[col] || c.emptyTo ) ]; if (a === '' && e !== 0) { return typeof e === 'boolean' ? (e ? -1 : 1) : e || 1; } if (b === '' && e !== 0) { return typeof e === 'boolean' ? (e ? 1 : -1) : -e || -1; } return ts.sortNatural(b, a); }; // basic alphabetical sort ts.sortText = function(a, b) { return a > b ? 1 : (a < b ? -1 : 0); }; // return text string value by adding up ascii value // so the text is somewhat sorted when using a digital sort // this is NOT an alphanumeric sort ts.getTextValue = function(a, num, mx) { if (mx) { // make sure the text value is greater than the max numerical value (mx) var i, l = a ? a.length : 0, n = mx + num; for (i = 0; i < l; i++) { n += a.charCodeAt(i); } return num * n; } return 0; }; ts.sortNumericAsc = function(a, b, num, mx, col, table) { if (a === b) { return 0; } var c = table.config, e = c.string[ (c.empties[col] || c.emptyTo ) ]; if (a === '' && e !== 0) { return typeof e === 'boolean' ? (e ? -1 : 1) : -e || -1; } if (b === '' && e !== 0) { return typeof e === 'boolean' ? (e ? 1 : -1) : e || 1; } if (isNaN(a)) { a = ts.getTextValue(a, num, mx); } if (isNaN(b)) { b = ts.getTextValue(b, num, mx); } return a - b; }; ts.sortNumericDesc = function(a, b, num, mx, col, table) { if (a === b) { return 0; } var c = table.config, e = c.string[ (c.empties[col] || c.emptyTo ) ]; if (a === '' && e !== 0) { return typeof e === 'boolean' ? (e ? -1 : 1) : e || 1; } if (b === '' && e !== 0) { return typeof e === 'boolean' ? (e ? 1 : -1) : -e || -1; } if (isNaN(a)) { a = ts.getTextValue(a, num, mx); } if (isNaN(b)) { b = ts.getTextValue(b, num, mx); } return b - a; }; ts.sortNumeric = function(a, b) { return a - b; }; // used when replacing accented characters during sorting ts.characterEquivalents = { "a" : "\u00e1\u00e0\u00e2\u00e3\u00e4\u0105\u00e5", // áàâãäąå "A" : "\u00c1\u00c0\u00c2\u00c3\u00c4\u0104\u00c5", // ÁÀÂÃÄĄÅ "c" : "\u00e7\u0107\u010d", // çćč "C" : "\u00c7\u0106\u010c", // ÇĆČ "e" : "\u00e9\u00e8\u00ea\u00eb\u011b\u0119", // éèêëěę "E" : "\u00c9\u00c8\u00ca\u00cb\u011a\u0118", // ÉÈÊËĚĘ "i" : "\u00ed\u00ec\u0130\u00ee\u00ef\u0131", // íìİîïı "I" : "\u00cd\u00cc\u0130\u00ce\u00cf", // ÍÌİÎÏ "o" : "\u00f3\u00f2\u00f4\u00f5\u00f6", // óòôõö "O" : "\u00d3\u00d2\u00d4\u00d5\u00d6", // ÓÒÔÕÖ "ss": "\u00df", // ß (s sharp) "SS": "\u1e9e", // ẞ (Capital sharp s) "u" : "\u00fa\u00f9\u00fb\u00fc\u016f", // úùûüů "U" : "\u00da\u00d9\u00db\u00dc\u016e" // ÚÙÛÜŮ }; ts.replaceAccents = function(s) { var a, acc = '[', eq = ts.characterEquivalents; if (!ts.characterRegex) { ts.characterRegexArray = {}; for (a in eq) { if (typeof a === 'string') { acc += eq[a]; ts.characterRegexArray[a] = new RegExp('[' + eq[a] + ']', 'g'); } } ts.characterRegex = new RegExp(acc + ']'); } if (ts.characterRegex.test(s)) { for (a in eq) { if (typeof a === 'string') { s = s.replace( ts.characterRegexArray[a], a ); } } } return s; }; // *** utilities *** ts.isValueInArray = function(column, arry) { var indx, len = arry.length; for (indx = 0; indx < len; indx++) { if (arry[indx][0] === column) { return indx; } } return -1; }; ts.addParser = function(parser) { var i, l = ts.parsers.length, a = true; for (i = 0; i < l; i++) { if (ts.parsers[i].id.toLowerCase() === parser.id.toLowerCase()) { a = false; } } if (a) { ts.parsers.push(parser); } }; ts.getParserById = function(name) { /*jshint eqeqeq:false */ if (name == 'false') { return false; } var i, l = ts.parsers.length; for (i = 0; i < l; i++) { if (ts.parsers[i].id.toLowerCase() === (name.toString()).toLowerCase()) { return ts.parsers[i]; } } return false; }; ts.addWidget = function(widget) { ts.widgets.push(widget); }; ts.hasWidget = function(table, name){ table = $(table); return table.length && table[0].config && table[0].config.widgetInit[name] || false; }; ts.getWidgetById = function(name) { var i, w, l = ts.widgets.length; for (i = 0; i < l; i++) { w = ts.widgets[i]; if (w && w.hasOwnProperty('id') && w.id.toLowerCase() === name.toLowerCase()) { return w; } } }; ts.applyWidget = function(table, init) { table = $(table)[0]; // in case this is called externally var c = table.config, wo = c.widgetOptions, widgets = [], time, w, wd; // prevent numerous consecutive widget applications if (init !== false && table.hasInitialized && (table.isApplyingWidgets || table.isUpdating)) { return; } if (c.debug) { time = new Date(); } if (c.widgets.length) { table.isApplyingWidgets = true; // ensure unique widget ids c.widgets = $.grep(c.widgets, function(v, k){ return $.inArray(v, c.widgets) === k; }); // build widget array & add priority as needed $.each(c.widgets || [], function(i,n){ wd = ts.getWidgetById(n); if (wd && wd.id) { // set priority to 10 if not defined if (!wd.priority) { wd.priority = 10; } widgets[i] = wd; } }); // sort widgets by priority widgets.sort(function(a, b){ return a.priority < b.priority ? -1 : a.priority === b.priority ? 0 : 1; }); // add/update selected widgets $.each(widgets, function(i,w){ if (w) { if (init || !(c.widgetInit[w.id])) { // set init flag first to prevent calling init more than once (e.g. pager) c.widgetInit[w.id] = true; if (w.hasOwnProperty('options')) { wo = table.config.widgetOptions = $.extend( true, {}, w.options, wo ); } if (w.hasOwnProperty('init')) { w.init(table, w, c, wo); } } if (!init && w.hasOwnProperty('format')) { w.format(table, c, wo, false); } } }); } setTimeout(function(){ table.isApplyingWidgets = false; }, 0); if (c.debug) { w = c.widgets.length; benchmark("Completed " + (init === true ? "initializing " : "applying ") + w + " widget" + (w !== 1 ? "s" : ""), time); } }; ts.refreshWidgets = function(table, doAll, dontapply) { table = $(table)[0]; // see issue #243 var i, c = table.config, cw = c.widgets, w = ts.widgets, l = w.length; // remove previous widgets for (i = 0; i < l; i++){ if ( w[i] && w[i].id && (doAll || $.inArray( w[i].id, cw ) < 0) ) { if (c.debug) { log( 'Refeshing widgets: Removing "' + w[i].id + '"' ); } // only remove widgets that have been initialized - fixes #442 if (w[i].hasOwnProperty('remove') && c.widgetInit[w[i].id]) { w[i].remove(table, c, c.widgetOptions); c.widgetInit[w[i].id] = false; } } } if (dontapply !== true) { ts.applyWidget(table, doAll); } }; // get sorter, string, empty, etc options for each column from // jQuery data, metadata, header option or header class name ("sorter-false") // priority = jQuery data > meta > headers option > header class name ts.getData = function(h, ch, key) { var val = '', $h = $(h), m, cl; if (!$h.length) { return ''; } m = $.metadata ? $h.metadata() : false; cl = ' ' + ($h.attr('class') || ''); if (typeof $h.data(key) !== 'undefined' || typeof $h.data(key.toLowerCase()) !== 'undefined'){ // "data-lockedOrder" is assigned to "lockedorder"; but "data-locked-order" is assigned to "lockedOrder" // "data-sort-initial-order" is assigned to "sortInitialOrder" val += $h.data(key) || $h.data(key.toLowerCase()); } else if (m && typeof m[key] !== 'undefined') { val += m[key]; } else if (ch && typeof ch[key] !== 'undefined') { val += ch[key]; } else if (cl !== ' ' && cl.match(' ' + key + '-')) { // include sorter class name "sorter-text", etc; now works with "sorter-my-custom-parser" val = cl.match( new RegExp('\\s' + key + '-([\\w-]+)') )[1] || ''; } return $.trim(val); }; ts.formatFloat = function(s, table) { if (typeof s !== 'string' || s === '') { return s; } // allow using formatFloat without a table; defaults to US number format var i, t = table && table.config ? table.config.usNumberFormat !== false : typeof table !== "undefined" ? table : true; if (t) { // US Format - 1,234,567.89 -> 1234567.89 s = s.replace(/,/g,''); } else { // German Format = 1.234.567,89 -> 1234567.89 // French Format = 1 234 567,89 -> 1234567.89 s = s.replace(/[\s|\.]/g,'').replace(/,/g,'.'); } if(/^\s*\([.\d]+\)/.test(s)) { // make (#) into a negative number -> (10) = -10 s = s.replace(/^\s*\(([.\d]+)\)/, '-$1'); } i = parseFloat(s); // return the text instead of zero return isNaN(i) ? $.trim(s) : i; }; ts.isDigit = function(s) { // replace all unwanted chars and match return isNaN(s) ? (/^[\-+(]?\d+[)]?$/).test(s.toString().replace(/[,.'"\s]/g, '')) : true; }; }() }); // make shortcut var ts = $.tablesorter; // extend plugin scope $.fn.extend({ tablesorter: ts.construct }); // add default parsers ts.addParser({ id: 'no-parser', is: function() { return false; }, format: function() { return ''; }, type: 'text' }); ts.addParser({ id: "text", is: function() { return true; }, format: function(s, table) { var c = table.config; if (s) { s = $.trim( c.ignoreCase ? s.toLocaleLowerCase() : s ); s = c.sortLocaleCompare ? ts.replaceAccents(s) : s; } return s; }, type: "text" }); ts.addParser({ id: "digit", is: function(s) { return ts.isDigit(s); }, format: function(s, table) { var n = ts.formatFloat((s || '').replace(/[^\w,. \-()]/g, ""), table); return s && typeof n === 'number' ? n : s ? $.trim( s && table.config.ignoreCase ? s.toLocaleLowerCase() : s ) : s; }, type: "numeric" }); ts.addParser({ id: "currency", is: function(s) { return (/^\(?\d+[\u00a3$\u20ac\u00a4\u00a5\u00a2?.]|[\u00a3$\u20ac\u00a4\u00a5\u00a2?.]\d+\)?$/).test((s || '').replace(/[+\-,. ]/g,'')); // £$€¤¥¢ }, format: function(s, table) { var n = ts.formatFloat((s || '').replace(/[^\w,. \-()]/g, ""), table); return s && typeof n === 'number' ? n : s ? $.trim( s && table.config.ignoreCase ? s.toLocaleLowerCase() : s ) : s; }, type: "numeric" }); ts.addParser({ id: "ipAddress", is: function(s) { return (/^\d{1,3}[\.]\d{1,3}[\.]\d{1,3}[\.]\d{1,3}$/).test(s); }, format: function(s, table) { var i, a = s ? s.split(".") : '', r = "", l = a.length; for (i = 0; i < l; i++) { r += ("00" + a[i]).slice(-3); } return s ? ts.formatFloat(r, table) : s; }, type: "numeric" }); ts.addParser({ id: "url", is: function(s) { return (/^(https?|ftp|file):\/\//).test(s); }, format: function(s) { return s ? $.trim(s.replace(/(https?|ftp|file):\/\//, '')) : s; }, type: "text" }); ts.addParser({ id: "isoDate", is: function(s) { return (/^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}/).test(s); }, format: function(s, table) { return s ? ts.formatFloat((s !== "") ? (new Date(s.replace(/-/g, "/")).getTime() || s) : "", table) : s; }, type: "numeric" }); ts.addParser({ id: "percent", is: function(s) { return (/(\d\s*?%|%\s*?\d)/).test(s) && s.length < 15; }, format: function(s, table) { return s ? ts.formatFloat(s.replace(/%/g, ""), table) : s; }, type: "numeric" }); ts.addParser({ id: "usLongDate", is: function(s) { // two digit years are not allowed cross-browser // Jan 01, 2013 12:34:56 PM or 01 Jan 2013 return (/^[A-Z]{3,10}\.?\s+\d{1,2},?\s+(\d{4})(\s+\d{1,2}:\d{2}(:\d{2})?(\s+[AP]M)?)?$/i).test(s) || (/^\d{1,2}\s+[A-Z]{3,10}\s+\d{4}/i).test(s); }, format: function(s, table) { return s ? ts.formatFloat( (new Date(s.replace(/(\S)([AP]M)$/i, "$1 $2")).getTime() || s), table) : s; }, type: "numeric" }); ts.addParser({ id: "shortDate", // "mmddyyyy", "ddmmyyyy" or "yyyymmdd" is: function(s) { // testing for ##-##-#### or ####-##-##, so it's not perfect; time can be included return (/(^\d{1,2}[\/\s]\d{1,2}[\/\s]\d{4})|(^\d{4}[\/\s]\d{1,2}[\/\s]\d{1,2})/).test((s || '').replace(/\s+/g," ").replace(/[\-.,]/g, "/")); }, format: function(s, table, cell, cellIndex) { if (s) { var c = table.config, ci = c.$headers.filter('[data-column=' + cellIndex + ']:last'), format = ci.length && ci[0].dateFormat || ts.getData( ci, ts.getColumnData( table, c.headers, cellIndex ), 'dateFormat') || c.dateFormat; s = s.replace(/\s+/g," ").replace(/[\-.,]/g, "/"); // escaped - because JSHint in Firefox was showing it as an error if (format === "mmddyyyy") { s = s.replace(/(\d{1,2})[\/\s](\d{1,2})[\/\s](\d{4})/, "$3/$1/$2"); } else if (format === "ddmmyyyy") { s = s.replace(/(\d{1,2})[\/\s](\d{1,2})[\/\s](\d{4})/, "$3/$2/$1"); } else if (format === "yyyymmdd") { s = s.replace(/(\d{4})[\/\s](\d{1,2})[\/\s](\d{1,2})/, "$1/$2/$3"); } } return s ? ts.formatFloat( (new Date(s).getTime() || s), table) : s; }, type: "numeric" }); ts.addParser({ id: "time", is: function(s) { return (/^(([0-2]?\d:[0-5]\d)|([0-1]?\d:[0-5]\d\s?([AP]M)))$/i).test(s); }, format: function(s, table) { return s ? ts.formatFloat( (new Date("2000/01/01 " + s.replace(/(\S)([AP]M)$/i, "$1 $2")).getTime() || s), table) : s; }, type: "numeric" }); ts.addParser({ id: "metadata", is: function() { return false; }, format: function(s, table, cell) { var c = table.config, p = (!c.parserMetadataName) ? 'sortValue' : c.parserMetadataName; return $(cell).metadata()[p]; }, type: "numeric" }); // add default widgets ts.addWidget({ id: "zebra", priority: 90, format: function(table, c, wo) { var $tb, $tv, $tr, row, even, time, k, l, child = new RegExp(c.cssChildRow, 'i'), b = c.$tbodies; if (c.debug) { time = new Date(); } for (k = 0; k < b.length; k++ ) { // loop through the visible rows $tb = b.eq(k); l = $tb.children('tr').length; if (l > 1) { row = 0; $tv = $tb.children('tr:visible').not(c.selectorRemove); // revered back to using jQuery each - strangely it's the fastest method /*jshint loopfunc:true */ $tv.each(function(){ $tr = $(this); // style children rows the same way the parent row was styled if (!child.test(this.className)) { row++; } even = (row % 2 === 0); $tr.removeClass(wo.zebra[even ? 1 : 0]).addClass(wo.zebra[even ? 0 : 1]); }); } } if (c.debug) { ts.benchmark("Applying Zebra widget", time); } }, remove: function(table, c, wo){ var k, $tb, b = c.$tbodies, rmv = (wo.zebra || [ "even", "odd" ]).join(' '); for (k = 0; k < b.length; k++ ){ $tb = $.tablesorter.processTbody(table, b.eq(k), true); // remove tbody $tb.children().removeClass(rmv); $.tablesorter.processTbody(table, $tb, false); // restore tbody } } }); })(jQuery);
asward/PaInstDb
public/js/tablesorter/js/jquery.tablesorter.js
JavaScript
bsd-3-clause
68,454
!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);
tmthrgd/pagespeed-libraries-cdnjs
packages/bootstrap-datepicker/1.2.0/js/locales/bootstrap-datepicker.sw.min.js
JavaScript
mit
454
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"]});
khasinski/cdnjs
ajax/libs/yui/3.4.0pr2/datatype/lang/datatype_zh-Hans-CN.js
JavaScript
mit
812
export {foo, bar};
sebmck/espree
tests/fixtures/ecma-features/modules/export-named-specifiers.src.js
JavaScript
bsd-2-clause
19
var convert = require('./convert'); module.exports = convert('chunk', require('../chunk'));
migua1204/jikexueyuan
极客学院/极客学院首页/jkxy/node_modules/grunt-legacy-util/node_modules/lodash/fp/chunk.js
JavaScript
apache-2.0
92
define( "dojo/cldr/nls/fr/islamic", //begin v1.x content { "dateFormatItem-yM": "M/yyyy", "dateFormatItem-yyyyMMMEd": "E d MMM y G", "dateFormatItem-yQ": "'T'Q y", "dateFormatItem-MMMEd": "E d MMM", "dateFormatItem-hms": "h:mm:ss a", "dateFormatItem-yQQQ": "QQQ y", "dateFormatItem-MMdd": "dd/MM", "days-standAlone-wide": [ "dimanche", "lundi", "mardi", "mercredi", "jeudi", "vendredi", "samedi" ], "dateFormatItem-MMM": "LLL", "months-standAlone-narrow": [ "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12" ], "quarters-standAlone-abbr": [ "T1", "T2", "T3", "T4" ], "dateFormatItem-y": "y", "dateFormatItem-MMMdd": "dd MMM", "dateFormatItem-yyyy": "y G", "months-standAlone-abbr": [ "mouh.", "saf.", "rab.aw.", "rab.th.", "joum.ou.", "joum.th.", "raj.", "chaa.", "ram.", "chaw.", "dhou.qi.", "dhou.hi." ], "dateFormatItem-Ed": "E d", "dateFormatItem-yMMM": "MMM y", "days-standAlone-narrow": [ "D", "L", "M", "M", "J", "V", "S" ], "eraAbbr": [ "AH" ], "dateFormatItem-yyyyMMMM": "MMMM y G", "dateFormat-long": "d MMMM y G", "dateFormatItem-Hm": "HH:mm", "dateFormatItem-MMd": "d/MM", "dateFormatItem-yyMM": "MM/y G", "dateFormat-medium": "d MMM, y G", "dateFormatItem-Hms": "HH:mm:ss", "dayPeriods-format-narrow-pm": "p", "dateFormatItem-yyMMM": "MMM y G", "dateFormatItem-yyQQQQ": "QQQQ y G", "dateFormatItem-yMd": "d/M/yyyy", "quarters-standAlone-wide": [ "1er trimestre", "2e trimestre", "3e trimestre", "4e trimestre" ], "dateFormatItem-ms": "mm:ss", "dateFormatItem-yyMMMd": "d MMM y G", "months-standAlone-wide": [ "mouharram", "safar", "rabia al awal", "rabia ath-thani", "joumada al oula", "joumada ath-thania", "rajab", "chaabane", "ramadan", "chawwal", "dhou al qi`da", "dhou al-hijja" ], "dateFormatItem-yyyyMd": "d/M/y G", "dateFormatItem-yyyyMMMd": "d MMM y G", "dateFormatItem-MMMMEd": "E d MMMM", "dateFormatItem-yyyyMEd": "E d/M/y G", "dateFormatItem-MMMd": "d MMM", "dateFormatItem-yyMMMEd": "E d MMM y G", "dateFormatItem-yyQ": "'T'Q y G", "months-format-abbr": [ "mouh.", "saf.", "rab.aw.", "rab.th.", "joum.oul.", "joum.tha.", "raj.", "chaa.", "ram.", "chaw.", "dhou.q.", "dhou.h." ], "dateFormatItem-H": "HH", "quarters-format-abbr": [ "T1", "T2", "T3", "T4" ], "days-format-abbr": [ "dim.", "lun.", "mar.", "mer.", "jeu.", "ven.", "sam." ], "dateFormatItem-M": "L", "days-format-narrow": [ "D", "L", "M", "M", "J", "V", "S" ], "dateFormatItem-yMMMd": "d MMM y", "dateFormatItem-MEd": "E d/M", "dateFormatItem-yyyyQQQ": "QQQ y G", "months-format-narrow": [ "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12" ], "days-standAlone-short": [ "dim.", "lun.", "mar.", "mer.", "jeu.", "ven.", "sam." ], "dateFormatItem-hm": "h:mm a", "days-standAlone-abbr": [ "dim.", "lun.", "mar.", "mer.", "jeu.", "ven.", "sam." ], "dateFormat-short": "d/M/y G", "dateFormatItem-yyyyM": "M/y G", "dateFormatItem-yMMMEd": "E d MMM y", "dateFormat-full": "EEEE d MMMM y G", "dateFormatItem-Md": "d/M", "dateFormatItem-yMEd": "E d/M/yyyy", "dateFormatItem-yyyyQ": "'T'Q y G", "months-format-wide": [ "mouharram", "safar", "rabia al awal", "rabia ath-thani", "joumada al oula", "joumada ath-thania", "rajab", "chaabane", "ramadan", "chawwal", "dhou al qi`da", "dhou al-hijja" ], "days-format-short": [ "di", "lu", "ma", "me", "je", "ve", "sa" ], "dateFormatItem-yyyyMMM": "MMM y G", "dateFormatItem-d": "d", "quarters-format-wide": [ "1er trimestre", "2e trimestre", "3e trimestre", "4e trimestre" ], "days-format-wide": [ "dimanche", "lundi", "mardi", "mercredi", "jeudi", "vendredi", "samedi" ], "dateFormatItem-h": "h a" } //end v1.x content );
ISTang/sitemap
web/public/libs/dojo/1.8.3/dojo/cldr/nls/fr/islamic.js.uncompressed.js
JavaScript
gpl-2.0
3,944
/* Slovenian locals for flatpickr */ var flatpickr = flatpickr || { l10ns: {} }; flatpickr.l10ns.sl = {}; flatpickr.l10ns.sl.weekdays = { shorthand: ["Ned", "Pon", "Tor", "Sre", "Čet", "Pet", "Sob"], longhand: ["Nedelja", "Ponedeljek", "Torek", "Sreda", "Četrtek", "Petek", "Sobota"] }; flatpickr.l10ns.sl.months = { shorthand: ["Jan", "Feb", "Mar", "Apr", "Maj", "Jun", "Jul", "Avg", "Sep", "Okt", "Nov", "Dec"], longhand: ["Januar", "Februar", "Marec", "April", "Maj", "Junij", "Julij", "Avgust", "September", "Oktober", "November", "December"] }; flatpickr.l10ns.sl.firstDayOfWeek = 1; flatpickr.l10ns.sl.rangeSeparator = " do "; flatpickr.l10ns.sl.ordinal = function () { return "."; }; if (typeof module !== "undefined") module.exports = flatpickr.l10ns;
spohlenz/trestle
vendor/assets/bower_components/trestle/flatpickr/dist/l10n/sl.js
JavaScript
lgpl-3.0
770
/** * angular-strap * @version v2.2.1 - 2015-05-15 * @link http://mgcrea.github.io/angular-strap * @author Olivier Louvignes <olivier@mg-crea.com> (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; } ] }; });
dlueth/cdnjs
ajax/libs/angular-strap/2.2.2/modules/affix.js
JavaScript
mit
7,104
;(function($){ /** * jqGrid Danish Translation * Aesiras A/S * http://www.aesiras.dk * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html **/ $.jgrid = $.jgrid || {}; $.extend($.jgrid,{ defaults : { recordtext: "Vis {0} - {1} of {2}", emptyrecords: "Ingen linjer fundet", loadtext: "Henter...", pgtext : "Side {0} af {1}" }, search : { caption: "Søg...", Find: "Find", Reset: "Nulstil", odata: [{ oper:'eq', text:"lig"},{ oper:'ne', text:"forskellige fra"},{ oper:'lt', text:"mindre"},{ oper:'le', text:"mindre eller lig"},{ oper:'gt', text:"større"},{ oper:'ge', text:"større eller lig"},{ oper:'bw', text:"begynder med"},{ oper:'bn', text:"begynder ikke med"},{ oper:'in', text:"findes i"},{ oper:'ni', text:"findes ikke i"},{ oper:'ew', text:"ender med"},{ oper:'en', text:"ender ikke med"},{ oper:'cn', text:"indeholder"},{ oper:'nc', text:"indeholder ikke"},{ oper:'nu', text:'is null'},{ oper:'nn', text:'is not null'}], groupOps: [ { op: "AND", text: "all" }, { op: "OR", text: "any" } ], operandTitle : "Click to select search operation.", resetTitle : "Reset Search Value" }, edit : { addCaption: "Tilføj", editCaption: "Ret", bSubmit: "Send", bCancel: "Annuller", bClose: "Luk", saveData: "Data er ændret. Gem data?", bYes : "Ja", bNo : "Nej", bExit : "Fortryd", msg: { required:"Felt er nødvendigt", number:"Indtast venligst et validt tal", minValue:"værdi skal være større end eller lig med", maxValue:"værdi skal være mindre end eller lig med", email: "er ikke en gyldig email", integer: "Indtast venligst et gyldigt heltal", date: "Indtast venligst en gyldig datoværdi", url: "er ugyldig URL. Prefix mangler ('http://' or 'https://')", nodefined : " er ikke defineret!", novalue : " returværdi kræves!", customarray : "Custom function should return array!", customfcheck : "Custom function should be present in case of custom checking!" } }, view : { caption: "Vis linje", bClose: "Luk" }, del : { caption: "Slet", msg: "Slet valgte linje(r)?", bSubmit: "Slet", bCancel: "Fortryd" }, nav : { edittext: " ", edittitle: "Rediger valgte linje", addtext:" ", addtitle: "Tilføj ny linje", deltext: " ", deltitle: "Slet valgte linje", searchtext: " ", searchtitle: "Find linjer", refreshtext: "", refreshtitle: "Indlæs igen", alertcap: "Advarsel", alerttext: "Vælg venligst linje", viewtext: "", viewtitle: "Vis valgte linje" }, col : { caption: "Vis/skjul kolonner", bSubmit: "Opdatere", bCancel: "Fortryd" }, errors : { errcap : "Fejl", nourl : "Ingen url valgt", norecords: "Ingen linjer at behandle", model : "colNames og colModel har ikke samme længde!" }, formatter : { integer : {thousandsSeparator: " ", defaultValue: '0'}, number : {decimalSeparator:",", thousandsSeparator: " ", decimalPlaces: 2, defaultValue: '0,00'}, currency : {decimalSeparator:",", thousandsSeparator: " ", decimalPlaces: 2, prefix: "", suffix:"", defaultValue: '0,00'}, date : { dayNames: [ "Søn", "Man", "Tir", "Ons", "Tor", "Fre", "Lør", "Søndag", "Mandag", "Tirsdag", "Onsdag", "Torsdag", "Fredag", "Lørdag" ], monthNames: [ "Jan", "Feb", "Mar", "Apr", "Maj", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dec", "Januar", "Februar", "Marts", "April", "Maj", "Juni", "Juli", "August", "September", "Oktober", "November", "December" ], AmPm : ["","","",""], S: function (j) {return '.'}, srcformat: 'Y-m-d', newformat: 'd/m/Y', parseRe : /[#%\\\/:_;.,\t\s-]/, masks : { ISO8601Long:"Y-m-d H:i:s", ISO8601Short:"Y-m-d", ShortDate: "j/n/Y", LongDate: "l d. F Y", FullDateTime: "l d F Y G:i:s", MonthDay: "d. F", ShortTime: "G:i", LongTime: "G:i:s", SortableDateTime: "Y-m-d\\TH:i:s", UniversalSortableDateTime: "Y-m-d H:i:sO", YearMonth: "F Y" }, reformatAfterEdit : false }, baseLinkUrl: '', showAction: '', target: '', checkbox : {disabled:true}, idName : 'id' } }); // DA })(jQuery);
zxinStar/footshop
zxAdmin/assets/js/jqGrid/i18n/grid.locale-da.js
JavaScript
agpl-3.0
4,406
(function(angular) { 'use strict'; angular.module('nonStringSelect', []) .run(function($rootScope) { $rootScope.model = { id: 2 }; }) .directive('convertToNumber', function() { return { require: 'ngModel', link: function(scope, element, attrs, ngModel) { ngModel.$parsers.push(function(val) { return parseInt(val, 10); }); ngModel.$formatters.push(function(val) { return '' + val; }); } }; }); })(window.angular);
LearnNavi/Naranawm
www/assets/library/angular-1.6.5/docs/examples/example-select-with-non-string-options/app.js
JavaScript
agpl-3.0
505
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"]});
pcarrier/cdnjs
ajax/libs/yui/3.9.0pr3/swf/swf.js
JavaScript
mit
7,203
// FILE H TWO module.exports = 2
frangucc/gamify
www/sandbox/pals/node_modules/cordova/node_modules/cordova-lib/node_modules/cordova-js/node_modules/browserify/test/hash_instance_context/two/dir/h.js
JavaScript
mit
33
/** * 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 * &nbsp; * 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> * &nbsp; Y.Get.script( * &nbsp; ["http://yui.yahooapis.com/2.5.2/build/yahoo/yahoo-min.js", * &nbsp; "http://yui.yahooapis.com/2.5.2/build/event/event-min.js"], * &nbsp; &#123; * &nbsp; onSuccess: function(o) &#123; * &nbsp; this.log("won't cause error because Y is the context"); * &nbsp; Y.log(o.data); // foo * &nbsp; Y.log(o.nodes.length === 2) // true * &nbsp; // o.purge(); // optionally remove the script nodes * &nbsp; // immediately * &nbsp; &#125;, * &nbsp; onFailure: function(o) &#123; * &nbsp; Y.log("transaction failed"); * &nbsp; &#125;, * &nbsp; onTimeout: function(o) &#123; * &nbsp; Y.log("transaction timed out"); * &nbsp; &#125;, * &nbsp; data: "foo", * &nbsp; timeout: 10000, // 10 second timeout * &nbsp; context: Y, // make the YUI instance * &nbsp; // win: otherframe // target another window/frame * &nbsp; autopurge: true // allow the utility to choose when to * &nbsp; // remove the nodes * &nbsp; purgetheshold: 1 // purge previous transaction before * &nbsp; // next transaction * &nbsp; &#125;);. * </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> * &nbsp; Y.Get.css( * &nbsp; ["http://localhost/css/menu.css", * &nbsp; "http://localhost/css/logger.css"], &#123; * &nbsp; insertBefore: 'custom-styles' // nodes will be inserted * &nbsp; // before the specified node * &nbsp; &#125;);. * </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']});
sympmarc/cdnjs
ajax/libs/yui/3.4.0/yui-rls/yui-rls-debug.js
JavaScript
mit
160,222
var setDesc = require('./$').setDesc , createDesc = require('./$.property-desc') , has = require('./$.has') , FProto = Function.prototype , nameRE = /^\s*function ([^ (]*)/ , NAME = 'name'; // 19.2.4.2 name NAME in FProto || require('./$.support-desc') && setDesc(FProto, NAME, { configurable: true, get: function(){ var match = ('' + this).match(nameRE) , name = match ? match[1] : ''; has(this, NAME) || setDesc(this, NAME, createDesc(5, name)); return name; } });
sammyboy45467/Portfolio
wp-content/themes/themer/node_modules/core-js/modules/es6.function.name.js
JavaScript
gpl-2.0
525
/** * 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;
dggriffin/react-native-mariomakely
node_modules/react-native/Libraries/Picker/PickerIOS.ios.js
JavaScript
mit
3,519
/** * 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; });
jdarling/radxa-rock
examples/web/web/src/vendor/ink/js/ink.formvalidator-2.js
JavaScript
mit
36,630
'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);
niranjan22/generator-seeki
generators/app/templates/server.model.js
JavaScript
isc
1,333
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); } }
lellimecnar/js-card-game
packages/deck-uno/src/card/index.js
JavaScript
isc
590
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;
alanhoff/node-hapi-faker
lib/hapi-faker.js
JavaScript
isc
2,992
/** * 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); }
yjpgfwxf/angularjs_recruitment
services/controller/version.js
JavaScript
isc
360
/* 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)); }); }); });
marten-de-vries/kneden
test/index.js
JavaScript
isc
958
#!/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);
medikoo/cli-color
test/__playground/throbber.js
JavaScript
isc
248
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 } }
alpheios-project/inflection-tables
views/lang/greek/numeral/greek-numeral-view.js
JavaScript
isc
3,833
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;
ThinkingInReact/ThinkingInReact.xyz
src/common/content/Packages.js
JavaScript
isc
697
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 }])
MadMartians/alcohol
public/js/bundle.js
JavaScript
mit
3,585
version https://git-lfs.github.com/spec/v1 oid sha256:0f37b0ed995928892d2a7c5d05dbecd85b0d4d248931074f5f228f0c14bf5909 size 11378
yogeshsaroya/new-cdnjs
ajax/libs/yui/3.4.0/event-delegate/event-delegate-debug.js
JavaScript
mit
130
// 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)); } }
Diullei/Storm
Storm.Test/SputnikV1/15_Native_ECMA_Script_Objects/15.10_RegExp_Objects/15.10.2_Pattern_Semantics/15.10.2.15_NonemptyClassRanges/S15.10.2.15_A1_T23.js
JavaScript
mit
824
/* 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]); }); });
acnrecife/Front-End-Test-Interview
client/app/components/main-menu/main-menu.controller.spec.js
JavaScript
mit
929
'use strict'; /* lib/encode.js * Encode WebSocket message frames. * * */
jamen/rela
lib/encode.js
JavaScript
mit
76
// 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 }); }); }); });
Wolfhergang/crodeWeb
js/plugins.js
JavaScript
mit
4,534
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); };
kwhinnery/trivia
controllers/sms.js
JavaScript
mit
6,553
(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: '' }) })();
peterhalasz/opensnap-frontend
app/template_constants.js
JavaScript
mit
416
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` }); } });
angus-c/flight-exercise
app/js/component/switcher.js
JavaScript
mit
816
const other = { something: 'here' }; const other$1 = { somethingElse: 'here' };
corneliusweig/rollup
test/form/samples/no-treeshake-conflict/_expected/es.js
JavaScript
mit
83
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;
paidico/condominio-api
app/models/autorizada.js
JavaScript
mit
745
'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;
dstructs/ndarray
lib/getCtor.js
JavaScript
mit
800
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); }
llucbrell/WebGL
Chap7/pickCube3.js
JavaScript
mit
8,258
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, };
ringcentral/ringcentral-js-widget
packages/ringcentral-widgets/components/NotificationSectionV2/index.js
JavaScript
mit
3,818
/************************************************************************************************************ 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&oslash;r','S&oslash;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&ccedil;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&aacute;b','Dom']; var weekString = 'Sem.'; var todayString = 'Hoje &eacute;'; 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&oslash;r','s&oslash;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 &egrave; 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&aring;n','Tis','Ons','Tor','Fre','L&ouml;r','S&ouml;n']; var weekString = 'Vecka'; var todayString = 'Idag &auml;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 = '&nbsp;&nbsp;- '; 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 = '&nbsp;&nbsp;+ '; 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 = '&nbsp;&nbsp;- '; 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 = '&nbsp;&nbsp;+ '; 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 = '&nbsp;'; } 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(); }
vlnpractice/master
lessons/files/calendar.js
JavaScript
mit
48,487
import Resolver from 'ember/resolver'; var resolver = Resolver.create(); resolver.namespace = { modulePrefix: 'map-app' }; export default resolver;
jsanchez034/CrowdSourceWeather
tests/helpers/resolver.js
JavaScript
mit
153
'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
patelsan/fetchpipe
node_modules/es5-ext/test/function/_define-length-compiled.js
JavaScript
mit
393
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; } } }
bd4/chrome_mhx_translate
translate_armor_search.js
JavaScript
mit
566