code
stringlengths
2
1.05M
"use strict"; /** * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* jshint maxlen: false */ const apirequest_1 = require("../../lib/apirequest"); /** * TaskQueue API * * Accesses a Google App Engine Pull Task Queue over REST. * * @example * const google = require('googleapis'); * const taskqueue = google.taskqueue('v1beta2'); * * @namespace taskqueue * @type {Function} * @version v1beta2 * @variation v1beta2 * @param {object=} options Options for Taskqueue */ function Taskqueue(options) { const self = this; self._options = options || {}; self.taskqueues = { /** * taskqueue.taskqueues.get * * @desc Get detailed information about a TaskQueue. * * @alias taskqueue.taskqueues.get * @memberOf! taskqueue(v1beta2) * * @param {object} params Parameters for request * @param {boolean=} params.getStats Whether to get stats. Optional. * @param {string} params.project The project under which the queue lies. * @param {string} params.taskqueue The id of the taskqueue to get the properties of. * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ get: function (params, options, callback) { if (typeof options === 'function') { callback = options; options = {}; } options || (options = {}); const rootUrl = options.rootUrl || 'https://www.googleapis.com/'; const parameters = { options: Object.assign({ url: (rootUrl + '/taskqueue/v1beta2/projects/{project}/taskqueues/{taskqueue}').replace(/([^:]\/)\/+/g, '$1'), method: 'GET' }, options), params: params, requiredParams: ['project', 'taskqueue'], pathParams: ['project', 'taskqueue'], context: self }; return apirequest_1.default(parameters, callback); } }; self.tasks = { /** * taskqueue.tasks.delete * * @desc Delete a task from a TaskQueue. * * @alias taskqueue.tasks.delete * @memberOf! taskqueue(v1beta2) * * @param {object} params Parameters for request * @param {string} params.project The project under which the queue lies. * @param {string} params.task The id of the task to delete. * @param {string} params.taskqueue The taskqueue to delete a task from. * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ delete: function (params, options, callback) { if (typeof options === 'function') { callback = options; options = {}; } options || (options = {}); const rootUrl = options.rootUrl || 'https://www.googleapis.com/'; const parameters = { options: Object.assign({ url: (rootUrl + '/taskqueue/v1beta2/projects/{project}/taskqueues/{taskqueue}/tasks/{task}').replace(/([^:]\/)\/+/g, '$1'), method: 'DELETE' }, options), params: params, requiredParams: ['project', 'taskqueue', 'task'], pathParams: ['project', 'task', 'taskqueue'], context: self }; return apirequest_1.default(parameters, callback); }, /** * taskqueue.tasks.get * * @desc Get a particular task from a TaskQueue. * * @alias taskqueue.tasks.get * @memberOf! taskqueue(v1beta2) * * @param {object} params Parameters for request * @param {string} params.project The project under which the queue lies. * @param {string} params.task The task to get properties of. * @param {string} params.taskqueue The taskqueue in which the task belongs. * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ get: function (params, options, callback) { if (typeof options === 'function') { callback = options; options = {}; } options || (options = {}); const rootUrl = options.rootUrl || 'https://www.googleapis.com/'; const parameters = { options: Object.assign({ url: (rootUrl + '/taskqueue/v1beta2/projects/{project}/taskqueues/{taskqueue}/tasks/{task}').replace(/([^:]\/)\/+/g, '$1'), method: 'GET' }, options), params: params, requiredParams: ['project', 'taskqueue', 'task'], pathParams: ['project', 'task', 'taskqueue'], context: self }; return apirequest_1.default(parameters, callback); }, /** * taskqueue.tasks.insert * * @desc Insert a new task in a TaskQueue * * @alias taskqueue.tasks.insert * @memberOf! taskqueue(v1beta2) * * @param {object} params Parameters for request * @param {string} params.project The project under which the queue lies * @param {string} params.taskqueue The taskqueue to insert the task into * @param {taskqueue(v1beta2).Task} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ insert: function (params, options, callback) { if (typeof options === 'function') { callback = options; options = {}; } options || (options = {}); const rootUrl = options.rootUrl || 'https://www.googleapis.com/'; const parameters = { options: Object.assign({ url: (rootUrl + '/taskqueue/v1beta2/projects/{project}/taskqueues/{taskqueue}/tasks').replace(/([^:]\/)\/+/g, '$1'), method: 'POST' }, options), params: params, requiredParams: ['project', 'taskqueue'], pathParams: ['project', 'taskqueue'], context: self }; return apirequest_1.default(parameters, callback); }, /** * taskqueue.tasks.lease * * @desc Lease 1 or more tasks from a TaskQueue. * * @alias taskqueue.tasks.lease * @memberOf! taskqueue(v1beta2) * * @param {object} params Parameters for request * @param {boolean=} params.groupByTag When true, all returned tasks will have the same tag * @param {integer} params.leaseSecs The lease in seconds. * @param {integer} params.numTasks The number of tasks to lease. * @param {string} params.project The project under which the queue lies. * @param {string=} params.tag The tag allowed for tasks in the response. Must only be specified if group_by_tag is true. If group_by_tag is true and tag is not specified the tag will be that of the oldest task by eta, i.e. the first available tag * @param {string} params.taskqueue The taskqueue to lease a task from. * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ lease: function (params, options, callback) { if (typeof options === 'function') { callback = options; options = {}; } options || (options = {}); const rootUrl = options.rootUrl || 'https://www.googleapis.com/'; const parameters = { options: Object.assign({ url: (rootUrl + '/taskqueue/v1beta2/projects/{project}/taskqueues/{taskqueue}/tasks/lease').replace(/([^:]\/)\/+/g, '$1'), method: 'POST' }, options), params: params, requiredParams: ['project', 'taskqueue', 'numTasks', 'leaseSecs'], pathParams: ['project', 'taskqueue'], context: self }; return apirequest_1.default(parameters, callback); }, /** * taskqueue.tasks.list * * @desc List Tasks in a TaskQueue * * @alias taskqueue.tasks.list * @memberOf! taskqueue(v1beta2) * * @param {object} params Parameters for request * @param {string} params.project The project under which the queue lies. * @param {string} params.taskqueue The id of the taskqueue to list tasks from. * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ list: function (params, options, callback) { if (typeof options === 'function') { callback = options; options = {}; } options || (options = {}); const rootUrl = options.rootUrl || 'https://www.googleapis.com/'; const parameters = { options: Object.assign({ url: (rootUrl + '/taskqueue/v1beta2/projects/{project}/taskqueues/{taskqueue}/tasks').replace(/([^:]\/)\/+/g, '$1'), method: 'GET' }, options), params: params, requiredParams: ['project', 'taskqueue'], pathParams: ['project', 'taskqueue'], context: self }; return apirequest_1.default(parameters, callback); }, /** * taskqueue.tasks.patch * * @desc Update tasks that are leased out of a TaskQueue. This method supports patch semantics. * * @alias taskqueue.tasks.patch * @memberOf! taskqueue(v1beta2) * * @param {object} params Parameters for request * @param {integer} params.newLeaseSeconds The new lease in seconds. * @param {string} params.project The project under which the queue lies. * @param {string} params.task * @param {string} params.taskqueue * @param {taskqueue(v1beta2).Task} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ patch: function (params, options, callback) { if (typeof options === 'function') { callback = options; options = {}; } options || (options = {}); const rootUrl = options.rootUrl || 'https://www.googleapis.com/'; const parameters = { options: Object.assign({ url: (rootUrl + '/taskqueue/v1beta2/projects/{project}/taskqueues/{taskqueue}/tasks/{task}').replace(/([^:]\/)\/+/g, '$1'), method: 'PATCH' }, options), params: params, requiredParams: ['project', 'taskqueue', 'task', 'newLeaseSeconds'], pathParams: ['project', 'task', 'taskqueue'], context: self }; return apirequest_1.default(parameters, callback); }, /** * taskqueue.tasks.update * * @desc Update tasks that are leased out of a TaskQueue. * * @alias taskqueue.tasks.update * @memberOf! taskqueue(v1beta2) * * @param {object} params Parameters for request * @param {integer} params.newLeaseSeconds The new lease in seconds. * @param {string} params.project The project under which the queue lies. * @param {string} params.task * @param {string} params.taskqueue * @param {taskqueue(v1beta2).Task} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ update: function (params, options, callback) { if (typeof options === 'function') { callback = options; options = {}; } options || (options = {}); const rootUrl = options.rootUrl || 'https://www.googleapis.com/'; const parameters = { options: Object.assign({ url: (rootUrl + '/taskqueue/v1beta2/projects/{project}/taskqueues/{taskqueue}/tasks/{task}').replace(/([^:]\/)\/+/g, '$1'), method: 'POST' }, options), params: params, requiredParams: ['project', 'taskqueue', 'task', 'newLeaseSeconds'], pathParams: ['project', 'task', 'taskqueue'], context: self }; return apirequest_1.default(parameters, callback); } }; } module.exports = Taskqueue; //# sourceMappingURL=v1beta2.js.map
'use strict'; /** * Module dependencies */ var racesPolicy = require('../policies/races.server.policy'), races = require('../controllers/races.server.controller'); module.exports = function(app) { // Races Routes app.route('/api/races').all(racesPolicy.isAllowed) .get(races.list) .post(races.create); app.route('/api/races/:raceId').all(racesPolicy.isAllowed) .get(races.read) .put(races.update) .delete(races.delete); // Finish by binding the Race middleware app.param('raceId', races.raceByID); };
/* * Copyright (c) 2015 Adobe Systems Incorporated. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * */ /*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */ /*global define, $, brackets, console */ define(function (require, exports, module) { "use strict"; var AppInit = brackets.getModule("utils/AppInit"), PreferencesManager = brackets.getModule("preferences/PreferencesManager"), UrlParams = brackets.getModule("utils/UrlParams").UrlParams, Strings = brackets.getModule("strings"), HealthDataUtils = require("HealthDataUtils"), uuid = require("thirdparty/uuid"); var prefs = PreferencesManager.getExtensionPrefs("healthData"); prefs.definePreference("healthDataTracking", "boolean", true, { description: Strings.DESCRIPTION_HEALTH_DATA_TRACKING }); var ONE_MINUTE = 60 * 1000, ONE_DAY = 24 * 60 * ONE_MINUTE, FIRST_LAUNCH_SEND_DELAY = 30 * ONE_MINUTE, timeoutVar; var params = new UrlParams(); params.parse(); /** * Get the Health Data which will be sent to the server. Initially it is only one time data. */ function getHealthData() { var result = new $.Deferred(), oneTimeHealthData = {}; var userUuid = PreferencesManager.getViewState("UUID"); if (!userUuid) { userUuid = uuid.v4(); PreferencesManager.setViewState("UUID", userUuid); } oneTimeHealthData.uuid = userUuid; oneTimeHealthData.snapshotTime = Date.now(); oneTimeHealthData.os = brackets.platform; oneTimeHealthData.userAgent = navigator.userAgent; oneTimeHealthData.osLanguage = brackets.app.language; oneTimeHealthData.bracketsLanguage = brackets.getLocale(); oneTimeHealthData.bracketsVersion = brackets.metadata.version; HealthDataUtils.getUserInstalledExtensions() .done(function (userInstalledExtensions) { oneTimeHealthData.installedExtensions = userInstalledExtensions; }) .always(function () { return result.resolve(oneTimeHealthData); }); return result.promise(); } /** * Send data to the server */ function sendHealthDataToServer() { var result = new $.Deferred(); getHealthData().done(function (healthData) { var url = brackets.config.healthDataServerURL, data = JSON.stringify(healthData); $.ajax({ url: url, type: "POST", data: data, dataType: "text", contentType: "text/plain" }) .done(function () { result.resolve(); }) .fail(function (jqXHR, status, errorThrown) { console.error("Error in sending Health Data. Response : " + jqXHR.responseText + ". Status : " + status + ". Error : " + errorThrown); result.reject(); }); }) .fail(function () { result.reject(); }); return result.promise(); } /* * Check if the Health Data is to be sent to the server. If the user has enabled tracking, Health Data will be sent once every 24 hours. * Send Health Data to the server if the period is more than 24 hours. * We are sending the data as soon as the user launches brackets. The data will be sent to the server only after the notification dialog * for opt-out/in is closed. */ function checkHealthDataSend() { var result = new $.Deferred(), isHDTracking = prefs.get("healthDataTracking"); window.clearTimeout(timeoutVar); if (isHDTracking) { var nextTimeToSend = PreferencesManager.getViewState("nextHealthDataSendTime"), currentTime = Date.now(); // Never send data before FIRST_LAUNCH_SEND_DELAY has ellapsed on a fresh install. This gives the user time to read the notification // popup, learn more, and opt out if desired if (!nextTimeToSend) { nextTimeToSend = currentTime + FIRST_LAUNCH_SEND_DELAY; PreferencesManager.setViewState("nextHealthDataSendTime", nextTimeToSend); // don't return yet though - still want to set the timeout below } if (currentTime >= nextTimeToSend) { // Bump up nextHealthDataSendTime now to avoid any chance of sending data again before 24 hours, e.g. if the server request fails // or the code below crashes PreferencesManager.setViewState("nextHealthDataSendTime", currentTime + ONE_DAY); sendHealthDataToServer() .done(function () { result.resolve(); }) .fail(function () { result.reject(); }) .always(function () { timeoutVar = setTimeout(checkHealthDataSend, ONE_DAY); }); } else { timeoutVar = setTimeout(checkHealthDataSend, nextTimeToSend - currentTime); result.reject(); } } else { result.reject(); } return result.promise(); } prefs.on("change", "healthDataTracking", function () { checkHealthDataSend(); }); window.addEventListener("online", function () { checkHealthDataSend(); }); window.addEventListener("offline", function () { window.clearTimeout(timeoutVar); }); AppInit.appReady(function () { checkHealthDataSend(); }); exports.getHealthData = getHealthData; exports.checkHealthDataSend = checkHealthDataSend; });
import Footer from './Footer'; import Nav from './Nav'; import Layout from './Layout'; export default { Nav, Layout, Footer };
var getArticleInfo = new XMLHttpRequest(); getArticleInfo.open("GET", "articleName.html"); getArticleInfo.send(); getArticleInfo.onreadystatechange = function() { var text = document.getElementById("textTarget"); if ((getArticleInfo.readyState === 4) && (getArticleInfo.status === 200)) { text.innerHTML = getArticleInfo.responseText; } else { console.log("There was a problem with the request."); } };
/* ======================================================================== * Bootstrap: affix.js v3.1.0 * http://getbootstrap.com/javascript/#affix * ======================================================================== * Copyright 2011-2014 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // AFFIX CLASS DEFINITION // ====================== var Affix = function (element, options) { this.options = $.extend({}, Affix.DEFAULTS, options) this.$window = $(window) .on('scroll.bs.affix.data-api', $.proxy(this.checkPosition, this)) .on('click.bs.affix.data-api', $.proxy(this.checkPositionWithEventLoop, this)) this.$element = $(element) this.affixed = this.unpin = this.pinnedOffset = null this.checkPosition() } Affix.RESET = 'affix affix-top affix-bottom' Affix.DEFAULTS = { offset: 0 } Affix.prototype.getPinnedOffset = function () { if (this.pinnedOffset) return this.pinnedOffset this.$element.removeClass(Affix.RESET).addClass('affix') var scrollTop = this.$window.scrollTop() var position = this.$element.offset() return (this.pinnedOffset = position.top - scrollTop) } Affix.prototype.checkPositionWithEventLoop = function () { setTimeout($.proxy(this.checkPosition, this), 1) } Affix.prototype.checkPosition = function () { if (!this.$element.is(':visible')) return var scrollHeight = $(document).height() var scrollTop = this.$window.scrollTop() var position = this.$element.offset() var offset = this.options.offset var offsetTop = offset.top var offsetBottom = offset.bottom if (this.affixed == 'top') position.top += scrollTop if (typeof offset != 'object') offsetBottom = offsetTop = offset if (typeof offsetTop == 'function') offsetTop = offset.top(this.$element) if (typeof offsetBottom == 'function') offsetBottom = offset.bottom(this.$element) var affix = this.unpin != null && (scrollTop + this.unpin <= position.top) ? false : offsetBottom != null && (position.top + this.$element.height() >= scrollHeight - offsetBottom) ? 'bottom' : offsetTop != null && (scrollTop <= offsetTop) ? 'top' : false if (this.affixed === affix) return if (this.unpin) this.$element.css('top', '') var affixType = 'affix' + (affix ? '-' + affix : '') var e = $.Event(affixType + '.bs.affix') this.$element.trigger(e) if (e.isDefaultPrevented()) return this.affixed = affix this.unpin = affix == 'bottom' ? this.getPinnedOffset() : null this.$element .removeClass(Affix.RESET) .addClass(affixType) .trigger($.Event(affixType.replace('affix', 'affixed'))) if (affix == 'bottom') { this.$element.offset({ top: scrollHeight - offsetBottom - this.$element.height() }) } } // AFFIX PLUGIN DEFINITION // ======================= var old = $.fn.affix $.fn.affix = function (option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.affix') var options = typeof option == 'object' && option if (!data) $this.data('bs.affix', (data = new Affix(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.affix.Constructor = Affix // AFFIX NO CONFLICT // ================= $.fn.affix.noConflict = function () { $.fn.affix = old return this } // AFFIX DATA-API // ============== $(window).on('load', function () { $('[data-spy="affix"]').each(function () { var $spy = $(this) var data = $spy.data() data.offset = data.offset || {} if (data.offsetBottom) data.offset.bottom = data.offsetBottom if (data.offsetTop) data.offset.top = data.offsetTop $spy.affix(data) }) }) }(jQuery); /* ======================================================================== * Bootstrap: button.js v3.1.0 * http://getbootstrap.com/javascript/#buttons * ======================================================================== * Copyright 2011-2014 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // BUTTON PUBLIC CLASS DEFINITION // ============================== var Button = function (element, options) { this.$element = $(element) this.options = $.extend({}, Button.DEFAULTS, options) this.isLoading = false } Button.DEFAULTS = { loadingText: 'loading...' } Button.prototype.setState = function (state) { var d = 'disabled' var $el = this.$element var val = $el.is('input') ? 'val' : 'html' var data = $el.data() state = state + 'Text' if (!data.resetText) $el.data('resetText', $el[val]()) $el[val](data[state] || this.options[state]) // push to event loop to allow forms to submit setTimeout($.proxy(function () { if (state == 'loadingText') { this.isLoading = true $el.addClass(d).attr(d, d) } else if (this.isLoading) { this.isLoading = false $el.removeClass(d).removeAttr(d) } }, this), 0) } Button.prototype.toggle = function () { var changed = true var $parent = this.$element.closest('[data-toggle="buttons"]') if ($parent.length) { var $input = this.$element.find('input') if ($input.prop('type') == 'radio') { if ($input.prop('checked') && this.$element.hasClass('active')) changed = false else $parent.find('.active').removeClass('active') } if (changed) $input.prop('checked', !this.$element.hasClass('active')).trigger('change') } if (changed) this.$element.toggleClass('active') } // BUTTON PLUGIN DEFINITION // ======================== var old = $.fn.button $.fn.button = function (option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.button') var options = typeof option == 'object' && option if (!data) $this.data('bs.button', (data = new Button(this, options))) if (option == 'toggle') data.toggle() else if (option) data.setState(option) }) } $.fn.button.Constructor = Button // BUTTON NO CONFLICT // ================== $.fn.button.noConflict = function () { $.fn.button = old return this } // BUTTON DATA-API // =============== $(document).on('click.bs.button.data-api', '[data-toggle^=button]', function (e) { var $btn = $(e.target) if (!$btn.hasClass('btn')) $btn = $btn.closest('.btn') $btn.button('toggle') e.preventDefault() }) }(jQuery); /* ======================================================================== * Bootstrap: carousel.js v3.1.0 * http://getbootstrap.com/javascript/#carousel * ======================================================================== * Copyright 2011-2014 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // CAROUSEL CLASS DEFINITION // ========================= var Carousel = function (element, options) { this.$element = $(element) this.$indicators = this.$element.find('.carousel-indicators') this.options = options this.paused = this.sliding = this.interval = this.$active = this.$items = null this.options.pause == 'hover' && this.$element .on('mouseenter', $.proxy(this.pause, this)) .on('mouseleave', $.proxy(this.cycle, this)) } Carousel.DEFAULTS = { interval: 5000, pause: 'hover', wrap: true } Carousel.prototype.cycle = function (e) { e || (this.paused = false) this.interval && clearInterval(this.interval) this.options.interval && !this.paused && (this.interval = setInterval($.proxy(this.next, this), this.options.interval)) return this } Carousel.prototype.getActiveIndex = function () { this.$active = this.$element.find('.item.active') this.$items = this.$active.parent().children() return this.$items.index(this.$active) } Carousel.prototype.to = function (pos) { var that = this var activeIndex = this.getActiveIndex() if (pos > (this.$items.length - 1) || pos < 0) return if (this.sliding) return this.$element.one('slid.bs.carousel', function () { that.to(pos) }) if (activeIndex == pos) return this.pause().cycle() return this.slide(pos > activeIndex ? 'next' : 'prev', $(this.$items[pos])) } Carousel.prototype.pause = function (e) { e || (this.paused = true) if (this.$element.find('.next, .prev').length && $.support.transition) { this.$element.trigger($.support.transition.end) this.cycle(true) } this.interval = clearInterval(this.interval) return this } Carousel.prototype.next = function () { if (this.sliding) return return this.slide('next') } Carousel.prototype.prev = function () { if (this.sliding) return return this.slide('prev') } Carousel.prototype.slide = function (type, next) { var $active = this.$element.find('.item.active') var $next = next || $active[type]() var isCycling = this.interval var direction = type == 'next' ? 'left' : 'right' var fallback = type == 'next' ? 'first' : 'last' var that = this if (!$next.length) { if (!this.options.wrap) return $next = this.$element.find('.item')[fallback]() } if ($next.hasClass('active')) return this.sliding = false var e = $.Event('slide.bs.carousel', { relatedTarget: $next[0], direction: direction }) this.$element.trigger(e) if (e.isDefaultPrevented()) return this.sliding = true isCycling && this.pause() if (this.$indicators.length) { this.$indicators.find('.active').removeClass('active') this.$element.one('slid.bs.carousel', function () { var $nextIndicator = $(that.$indicators.children()[that.getActiveIndex()]) $nextIndicator && $nextIndicator.addClass('active') }) } if ($.support.transition && this.$element.hasClass('slide')) { $next.addClass(type) $next[0].offsetWidth // force reflow $active.addClass(direction) $next.addClass(direction) $active .one($.support.transition.end, function () { $next.removeClass([type, direction].join(' ')).addClass('active') $active.removeClass(['active', direction].join(' ')) that.sliding = false setTimeout(function () { that.$element.trigger('slid.bs.carousel') }, 0) }) .emulateTransitionEnd($active.css('transition-duration').slice(0, -1) * 1000) } else { $active.removeClass('active') $next.addClass('active') this.sliding = false this.$element.trigger('slid.bs.carousel') } isCycling && this.cycle() return this } // CAROUSEL PLUGIN DEFINITION // ========================== var old = $.fn.carousel $.fn.carousel = function (option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.carousel') var options = $.extend({}, Carousel.DEFAULTS, $this.data(), typeof option == 'object' && option) var action = typeof option == 'string' ? option : options.slide if (!data) $this.data('bs.carousel', (data = new Carousel(this, options))) if (typeof option == 'number') data.to(option) else if (action) data[action]() else if (options.interval) data.pause().cycle() }) } $.fn.carousel.Constructor = Carousel // CAROUSEL NO CONFLICT // ==================== $.fn.carousel.noConflict = function () { $.fn.carousel = old return this } // CAROUSEL DATA-API // ================= $(document).on('click.bs.carousel.data-api', '[data-slide], [data-slide-to]', function (e) { var $this = $(this), href var $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) //strip for ie7 var options = $.extend({}, $target.data(), $this.data()) var slideIndex = $this.attr('data-slide-to') if (slideIndex) options.interval = false $target.carousel(options) if (slideIndex = $this.attr('data-slide-to')) { $target.data('bs.carousel').to(slideIndex) } e.preventDefault() }) $(window).on('load', function () { $('[data-ride="carousel"]').each(function () { var $carousel = $(this) $carousel.carousel($carousel.data()) }) }) }(jQuery); /* ======================================================================== * Bootstrap: collapse.js v3.1.0 * http://getbootstrap.com/javascript/#collapse * ======================================================================== * Copyright 2011-2014 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // COLLAPSE PUBLIC CLASS DEFINITION // ================================ var Collapse = function (element, options) { this.$element = $(element) this.options = $.extend({}, Collapse.DEFAULTS, options) this.transitioning = null if (this.options.parent) this.$parent = $(this.options.parent) if (this.options.toggle) this.toggle() } Collapse.DEFAULTS = { toggle: true } Collapse.prototype.dimension = function () { var hasWidth = this.$element.hasClass('width') return hasWidth ? 'width' : 'height' } Collapse.prototype.show = function () { if (this.transitioning || this.$element.hasClass('in')) return var startEvent = $.Event('show.bs.collapse') this.$element.trigger(startEvent) if (startEvent.isDefaultPrevented()) return var actives = this.$parent && this.$parent.find('> .panel > .in') if (actives && actives.length) { var hasData = actives.data('bs.collapse') if (hasData && hasData.transitioning) return actives.collapse('hide') hasData || actives.data('bs.collapse', null) } var dimension = this.dimension() this.$element .removeClass('collapse') .addClass('collapsing') [dimension](0) this.transitioning = 1 var complete = function () { this.$element .removeClass('collapsing') .addClass('collapse in') [dimension]('auto') this.transitioning = 0 this.$element.trigger('shown.bs.collapse') } if (!$.support.transition) return complete.call(this) var scrollSize = $.camelCase(['scroll', dimension].join('-')) this.$element .one($.support.transition.end, $.proxy(complete, this)) .emulateTransitionEnd(350) [dimension](this.$element[0][scrollSize]) } Collapse.prototype.hide = function () { if (this.transitioning || !this.$element.hasClass('in')) return var startEvent = $.Event('hide.bs.collapse') this.$element.trigger(startEvent) if (startEvent.isDefaultPrevented()) return var dimension = this.dimension() this.$element [dimension](this.$element[dimension]()) [0].offsetHeight this.$element .addClass('collapsing') .removeClass('collapse') .removeClass('in') this.transitioning = 1 var complete = function () { this.transitioning = 0 this.$element .trigger('hidden.bs.collapse') .removeClass('collapsing') .addClass('collapse') } if (!$.support.transition) return complete.call(this) this.$element [dimension](0) .one($.support.transition.end, $.proxy(complete, this)) .emulateTransitionEnd(350) } Collapse.prototype.toggle = function () { this[this.$element.hasClass('in') ? 'hide' : 'show']() } // COLLAPSE PLUGIN DEFINITION // ========================== var old = $.fn.collapse $.fn.collapse = function (option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.collapse') var options = $.extend({}, Collapse.DEFAULTS, $this.data(), typeof option == 'object' && option) if (!data && options.toggle && option == 'show') option = !option if (!data) $this.data('bs.collapse', (data = new Collapse(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.collapse.Constructor = Collapse // COLLAPSE NO CONFLICT // ==================== $.fn.collapse.noConflict = function () { $.fn.collapse = old return this } // COLLAPSE DATA-API // ================= $(document).on('click.bs.collapse.data-api', '[data-toggle=collapse]', function (e) { var $this = $(this), href var target = $this.attr('data-target') || e.preventDefault() || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') //strip for ie7 var $target = $(target) var data = $target.data('bs.collapse') var option = data ? 'toggle' : $this.data() var parent = $this.attr('data-parent') var $parent = parent && $(parent) if (!data || !data.transitioning) { if ($parent) $parent.find('[data-toggle=collapse][data-parent="' + parent + '"]').not($this).addClass('collapsed') $this[$target.hasClass('in') ? 'addClass' : 'removeClass']('collapsed') } $target.collapse(option) }) }(jQuery); /* ======================================================================== * Bootstrap: dropdown.js v3.1.0 * http://getbootstrap.com/javascript/#dropdowns * ======================================================================== * Copyright 2011-2014 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // DROPDOWN CLASS DEFINITION // ========================= var backdrop = '.dropdown-backdrop' var toggle = '[data-toggle=dropdown]' var Dropdown = function (element) { $(element).on('click.bs.dropdown', this.toggle) } Dropdown.prototype.toggle = function (e) { var $this = $(this) if ($this.is('.disabled, :disabled')) return var $parent = getParent($this) var isActive = $parent.hasClass('open') clearMenus() if (!isActive) { if ('ontouchstart' in document.documentElement && !$parent.closest('.navbar-nav').length) { // if mobile we use a backdrop because click events don't delegate $('<div class="dropdown-backdrop"/>').insertAfter($(this)).on('click', clearMenus) } var relatedTarget = { relatedTarget: this } $parent.trigger(e = $.Event('show.bs.dropdown', relatedTarget)) if (e.isDefaultPrevented()) return $parent .toggleClass('open') .trigger('shown.bs.dropdown', relatedTarget) $this.focus() } return false } Dropdown.prototype.keydown = function (e) { if (!/(38|40|27)/.test(e.keyCode)) return var $this = $(this) e.preventDefault() e.stopPropagation() if ($this.is('.disabled, :disabled')) return var $parent = getParent($this) var isActive = $parent.hasClass('open') if (!isActive || (isActive && e.keyCode == 27)) { if (e.which == 27) $parent.find(toggle).focus() return $this.click() } var desc = ' li:not(.divider):visible a' var $items = $parent.find('[role=menu]' + desc + ', [role=listbox]' + desc) if (!$items.length) return var index = $items.index($items.filter(':focus')) if (e.keyCode == 38 && index > 0) index-- // up if (e.keyCode == 40 && index < $items.length - 1) index++ // down if (!~index) index = 0 $items.eq(index).focus() } function clearMenus(e) { $(backdrop).remove() $(toggle).each(function () { var $parent = getParent($(this)) var relatedTarget = { relatedTarget: this } if (!$parent.hasClass('open')) return $parent.trigger(e = $.Event('hide.bs.dropdown', relatedTarget)) if (e.isDefaultPrevented()) return $parent.removeClass('open').trigger('hidden.bs.dropdown', relatedTarget) }) } function getParent($this) { var selector = $this.attr('data-target') if (!selector) { selector = $this.attr('href') selector = selector && /#[A-Za-z]/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7 } var $parent = selector && $(selector) return $parent && $parent.length ? $parent : $this.parent() } // DROPDOWN PLUGIN DEFINITION // ========================== var old = $.fn.dropdown $.fn.dropdown = function (option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.dropdown') if (!data) $this.data('bs.dropdown', (data = new Dropdown(this))) if (typeof option == 'string') data[option].call($this) }) } $.fn.dropdown.Constructor = Dropdown // DROPDOWN NO CONFLICT // ==================== $.fn.dropdown.noConflict = function () { $.fn.dropdown = old return this } // APPLY TO STANDARD DROPDOWN ELEMENTS // =================================== $(document) .on('click.bs.dropdown.data-api', clearMenus) .on('click.bs.dropdown.data-api', '.dropdown form', function (e) { e.stopPropagation() }) .on('click.bs.dropdown.data-api', toggle, Dropdown.prototype.toggle) .on('keydown.bs.dropdown.data-api', toggle + ', [role=menu], [role=listbox]', Dropdown.prototype.keydown) }(jQuery); /* ======================================================================== * Bootstrap: tab.js v3.1.0 * http://getbootstrap.com/javascript/#tabs * ======================================================================== * Copyright 2011-2014 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // TAB CLASS DEFINITION // ==================== var Tab = function (element) { this.element = $(element) } Tab.prototype.show = function () { var $this = this.element var $ul = $this.closest('ul:not(.dropdown-menu)') var selector = $this.data('target') if (!selector) { selector = $this.attr('href') selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7 } if ($this.parent('li').hasClass('active')) return var previous = $ul.find('.active:last a')[0] var e = $.Event('show.bs.tab', { relatedTarget: previous }) $this.trigger(e) if (e.isDefaultPrevented()) return var $target = $(selector) this.activate($this.parent('li'), $ul) this.activate($target, $target.parent(), function () { $this.trigger({ type: 'shown.bs.tab', relatedTarget: previous }) }) } Tab.prototype.activate = function (element, container, callback) { var $active = container.find('> .active') var transition = callback && $.support.transition && $active.hasClass('fade') function next() { $active .removeClass('active') .find('> .dropdown-menu > .active') .removeClass('active') element.addClass('active') if (transition) { element[0].offsetWidth // reflow for transition element.addClass('in') } else { element.removeClass('fade') } if (element.parent('.dropdown-menu')) { element.closest('li.dropdown').addClass('active') } callback && callback() } transition ? $active .one($.support.transition.end, next) .emulateTransitionEnd(150) : next() $active.removeClass('in') } // TAB PLUGIN DEFINITION // ===================== var old = $.fn.tab $.fn.tab = function ( option ) { return this.each(function () { var $this = $(this) var data = $this.data('bs.tab') if (!data) $this.data('bs.tab', (data = new Tab(this))) if (typeof option == 'string') data[option]() }) } $.fn.tab.Constructor = Tab // TAB NO CONFLICT // =============== $.fn.tab.noConflict = function () { $.fn.tab = old return this } // TAB DATA-API // ============ $(document).on('click.bs.tab.data-api', '[data-toggle="tab"], [data-toggle="pill"]', function (e) { e.preventDefault() $(this).tab('show') }) }(jQuery); /* ======================================================================== * Bootstrap: transition.js v3.1.0 * http://getbootstrap.com/javascript/#transitions * ======================================================================== * Copyright 2011-2014 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // CSS TRANSITION SUPPORT (Shoutout: http://www.modernizr.com/) // ============================================================ function transitionEnd() { var el = document.createElement('bootstrap') var transEndEventNames = { 'WebkitTransition' : 'webkitTransitionEnd', 'MozTransition' : 'transitionend', 'OTransition' : 'oTransitionEnd otransitionend', 'transition' : 'transitionend' } for (var name in transEndEventNames) { if (el.style[name] !== undefined) { return { end: transEndEventNames[name] } } } return false // explicit for ie8 ( ._.) } // http://blog.alexmaccaw.com/css-transitions $.fn.emulateTransitionEnd = function (duration) { var called = false, $el = this $(this).one($.support.transition.end, function () { called = true }) var callback = function () { if (!called) $($el).trigger($.support.transition.end) } setTimeout(callback, duration) return this } $(function () { $.support.transition = transitionEnd() }) }(jQuery); /* ======================================================================== * Bootstrap: scrollspy.js v3.1.0 * http://getbootstrap.com/javascript/#scrollspy * ======================================================================== * Copyright 2011-2014 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // SCROLLSPY CLASS DEFINITION // ========================== function ScrollSpy(element, options) { var href var process = $.proxy(this.process, this) this.$element = $(element).is('body') ? $(window) : $(element) this.$body = $('body') this.$scrollElement = this.$element.on('scroll.bs.scroll-spy.data-api', process) this.options = $.extend({}, ScrollSpy.DEFAULTS, options) this.selector = (this.options.target || ((href = $(element).attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) //strip for ie7 || '') + ' .nav li > a' this.offsets = $([]) this.targets = $([]) this.activeTarget = null this.refresh() this.process() } ScrollSpy.DEFAULTS = { offset: 10 } ScrollSpy.prototype.refresh = function () { var offsetMethod = this.$element[0] == window ? 'offset' : 'position' this.offsets = $([]) this.targets = $([]) var self = this var $targets = this.$body .find(this.selector) .map(function () { var $el = $(this) var href = $el.data('target') || $el.attr('href') var $href = /^#./.test(href) && $(href) return ($href && $href.length && $href.is(':visible') && [[ $href[offsetMethod]().top + (!$.isWindow(self.$scrollElement.get(0)) && self.$scrollElement.scrollTop()), href ]]) || null }) .sort(function (a, b) { return a[0] - b[0] }) .each(function () { self.offsets.push(this[0]) self.targets.push(this[1]) }) } ScrollSpy.prototype.process = function () { var scrollTop = this.$scrollElement.scrollTop() + this.options.offset var scrollHeight = this.$scrollElement[0].scrollHeight || this.$body[0].scrollHeight var maxScroll = scrollHeight - this.$scrollElement.height() var offsets = this.offsets var targets = this.targets var activeTarget = this.activeTarget var i if (scrollTop >= maxScroll) { return activeTarget != (i = targets.last()[0]) && this.activate(i) } if (activeTarget && scrollTop <= offsets[0]) { return activeTarget != (i = targets[0]) && this.activate(i) } for (i = offsets.length; i--;) { activeTarget != targets[i] && scrollTop >= offsets[i] && (!offsets[i + 1] || scrollTop <= offsets[i + 1]) && this.activate( targets[i] ) } } ScrollSpy.prototype.activate = function (target) { this.activeTarget = target $(this.selector) .parentsUntil(this.options.target, '.active') .removeClass('active') var selector = this.selector + '[data-target="' + target + '"],' + this.selector + '[href="' + target + '"]' var active = $(selector) .parents('li') .addClass('active') if (active.parent('.dropdown-menu').length) { active = active .closest('li.dropdown') .addClass('active') } active.trigger('activate.bs.scrollspy') } // SCROLLSPY PLUGIN DEFINITION // =========================== var old = $.fn.scrollspy $.fn.scrollspy = function (option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.scrollspy') var options = typeof option == 'object' && option if (!data) $this.data('bs.scrollspy', (data = new ScrollSpy(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.scrollspy.Constructor = ScrollSpy // SCROLLSPY NO CONFLICT // ===================== $.fn.scrollspy.noConflict = function () { $.fn.scrollspy = old return this } // SCROLLSPY DATA-API // ================== $(window).on('load', function () { $('[data-spy="scroll"]').each(function () { var $spy = $(this) $spy.scrollspy($spy.data()) }) }) }(jQuery); /* ======================================================================== * Bootstrap: modal.js v3.1.0 * http://getbootstrap.com/javascript/#modals * ======================================================================== * Copyright 2011-2014 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // MODAL CLASS DEFINITION // ====================== var Modal = function (element, options) { this.options = options this.$element = $(element) this.$backdrop = this.isShown = null if (this.options.remote) { this.$element .find('.modal-content') .load(this.options.remote, $.proxy(function () { this.$element.trigger('loaded.bs.modal') }, this)) } } Modal.DEFAULTS = { backdrop: true, keyboard: true, show: true } Modal.prototype.toggle = function (_relatedTarget) { return this[!this.isShown ? 'show' : 'hide'](_relatedTarget) } Modal.prototype.show = function (_relatedTarget) { var that = this var e = $.Event('show.bs.modal', { relatedTarget: _relatedTarget }) this.$element.trigger(e) if (this.isShown || e.isDefaultPrevented()) return this.isShown = true this.escape() this.$element.on('click.dismiss.bs.modal', '[data-dismiss="modal"]', $.proxy(this.hide, this)) this.backdrop(function () { var transition = $.support.transition && that.$element.hasClass('fade') if (!that.$element.parent().length) { that.$element.appendTo(document.body) // don't move modals dom position } that.$element .show() .scrollTop(0) if (transition) { that.$element[0].offsetWidth // force reflow } that.$element .addClass('in') .attr('aria-hidden', false) that.enforceFocus() var e = $.Event('shown.bs.modal', { relatedTarget: _relatedTarget }) transition ? that.$element.find('.modal-dialog') // wait for modal to slide in .one($.support.transition.end, function () { that.$element.focus().trigger(e) }) .emulateTransitionEnd(300) : that.$element.focus().trigger(e) }) } Modal.prototype.hide = function (e) { if (e) e.preventDefault() e = $.Event('hide.bs.modal') this.$element.trigger(e) if (!this.isShown || e.isDefaultPrevented()) return this.isShown = false this.escape() $(document).off('focusin.bs.modal') this.$element .removeClass('in') .attr('aria-hidden', true) .off('click.dismiss.bs.modal') $.support.transition && this.$element.hasClass('fade') ? this.$element .one($.support.transition.end, $.proxy(this.hideModal, this)) .emulateTransitionEnd(300) : this.hideModal() } Modal.prototype.enforceFocus = function () { $(document) .off('focusin.bs.modal') // guard against infinite focus loop .on('focusin.bs.modal', $.proxy(function (e) { if (this.$element[0] !== e.target && !this.$element.has(e.target).length) { this.$element.focus() } }, this)) } Modal.prototype.escape = function () { if (this.isShown && this.options.keyboard) { this.$element.on('keyup.dismiss.bs.modal', $.proxy(function (e) { e.which == 27 && this.hide() }, this)) } else if (!this.isShown) { this.$element.off('keyup.dismiss.bs.modal') } } Modal.prototype.hideModal = function () { var that = this this.$element.hide() this.backdrop(function () { that.removeBackdrop() that.$element.trigger('hidden.bs.modal') }) } Modal.prototype.removeBackdrop = function () { this.$backdrop && this.$backdrop.remove() this.$backdrop = null } Modal.prototype.backdrop = function (callback) { var animate = this.$element.hasClass('fade') ? 'fade' : '' if (this.isShown && this.options.backdrop) { var doAnimate = $.support.transition && animate this.$backdrop = $('<div class="modal-backdrop ' + animate + '" />') .appendTo(document.body) this.$element.on('click.dismiss.bs.modal', $.proxy(function (e) { if (e.target !== e.currentTarget) return this.options.backdrop == 'static' ? this.$element[0].focus.call(this.$element[0]) : this.hide.call(this) }, this)) if (doAnimate) this.$backdrop[0].offsetWidth // force reflow this.$backdrop.addClass('in') if (!callback) return doAnimate ? this.$backdrop .one($.support.transition.end, callback) .emulateTransitionEnd(150) : callback() } else if (!this.isShown && this.$backdrop) { this.$backdrop.removeClass('in') $.support.transition && this.$element.hasClass('fade') ? this.$backdrop .one($.support.transition.end, callback) .emulateTransitionEnd(150) : callback() } else if (callback) { callback() } } // MODAL PLUGIN DEFINITION // ======================= var old = $.fn.modal $.fn.modal = function (option, _relatedTarget) { return this.each(function () { var $this = $(this) var data = $this.data('bs.modal') var options = $.extend({}, Modal.DEFAULTS, $this.data(), typeof option == 'object' && option) if (!data) $this.data('bs.modal', (data = new Modal(this, options))) if (typeof option == 'string') data[option](_relatedTarget) else if (options.show) data.show(_relatedTarget) }) } $.fn.modal.Constructor = Modal // MODAL NO CONFLICT // ================= $.fn.modal.noConflict = function () { $.fn.modal = old return this } // MODAL DATA-API // ============== $(document).on('click.bs.modal.data-api', '[data-toggle="modal"]', function (e) { var $this = $(this) var href = $this.attr('href') var $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) //strip for ie7 var option = $target.data('bs.modal') ? 'toggle' : $.extend({ remote: !/#/.test(href) && href }, $target.data(), $this.data()) if ($this.is('a')) e.preventDefault() $target .modal(option, this) .one('hide', function () { $this.is(':visible') && $this.focus() }) }) $(document) .on('show.bs.modal', '.modal', function () { $(document.body).addClass('modal-open') }) .on('hidden.bs.modal', '.modal', function () { $(document.body).removeClass('modal-open') }) }(jQuery); /* ======================================================================== * Bootstrap: tooltip.js v3.1.0 * http://getbootstrap.com/javascript/#tooltip * Inspired by the original jQuery.tipsy by Jason Frame * ======================================================================== * Copyright 2011-2014 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // TOOLTIP PUBLIC CLASS DEFINITION // =============================== var Tooltip = function (element, options) { this.type = this.options = this.enabled = this.timeout = this.hoverState = this.$element = null this.init('tooltip', element, options) } Tooltip.DEFAULTS = { animation: true, placement: 'top', selector: false, template: '<div class="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>', trigger: 'hover focus', title: '', delay: 0, html: false, container: false } Tooltip.prototype.init = function (type, element, options) { this.enabled = true this.type = type this.$element = $(element) this.options = this.getOptions(options) var triggers = this.options.trigger.split(' ') for (var i = triggers.length; i--;) { var trigger = triggers[i] if (trigger == 'click') { this.$element.on('click.' + this.type, this.options.selector, $.proxy(this.toggle, this)) } else if (trigger != 'manual') { var eventIn = trigger == 'hover' ? 'mouseenter' : 'focusin' var eventOut = trigger == 'hover' ? 'mouseleave' : 'focusout' this.$element.on(eventIn + '.' + this.type, this.options.selector, $.proxy(this.enter, this)) this.$element.on(eventOut + '.' + this.type, this.options.selector, $.proxy(this.leave, this)) } } this.options.selector ? (this._options = $.extend({}, this.options, { trigger: 'manual', selector: '' })) : this.fixTitle() } Tooltip.prototype.getDefaults = function () { return Tooltip.DEFAULTS } Tooltip.prototype.getOptions = function (options) { options = $.extend({}, this.getDefaults(), this.$element.data(), options) if (options.delay && typeof options.delay == 'number') { options.delay = { show: options.delay, hide: options.delay } } return options } Tooltip.prototype.getDelegateOptions = function () { var options = {} var defaults = this.getDefaults() this._options && $.each(this._options, function (key, value) { if (defaults[key] != value) options[key] = value }) return options } Tooltip.prototype.enter = function (obj) { var self = obj instanceof this.constructor ? obj : $(obj.currentTarget)[this.type](this.getDelegateOptions()).data('bs.' + this.type) clearTimeout(self.timeout) self.hoverState = 'in' if (!self.options.delay || !self.options.delay.show) return self.show() self.timeout = setTimeout(function () { if (self.hoverState == 'in') self.show() }, self.options.delay.show) } Tooltip.prototype.leave = function (obj) { var self = obj instanceof this.constructor ? obj : $(obj.currentTarget)[this.type](this.getDelegateOptions()).data('bs.' + this.type) clearTimeout(self.timeout) self.hoverState = 'out' if (!self.options.delay || !self.options.delay.hide) return self.hide() self.timeout = setTimeout(function () { if (self.hoverState == 'out') self.hide() }, self.options.delay.hide) } Tooltip.prototype.show = function () { var e = $.Event('show.bs.' + this.type) if (this.hasContent() && this.enabled) { this.$element.trigger(e) if (e.isDefaultPrevented()) return var that = this; var $tip = this.tip() this.setContent() if (this.options.animation) $tip.addClass('fade') var placement = typeof this.options.placement == 'function' ? this.options.placement.call(this, $tip[0], this.$element[0]) : this.options.placement var autoToken = /\s?auto?\s?/i var autoPlace = autoToken.test(placement) if (autoPlace) placement = placement.replace(autoToken, '') || 'top' $tip .detach() .css({ top: 0, left: 0, display: 'block' }) .addClass(placement) this.options.container ? $tip.appendTo(this.options.container) : $tip.insertAfter(this.$element) var pos = this.getPosition() var actualWidth = $tip[0].offsetWidth var actualHeight = $tip[0].offsetHeight if (autoPlace) { var $parent = this.$element.parent() var orgPlacement = placement var docScroll = document.documentElement.scrollTop || document.body.scrollTop var parentWidth = this.options.container == 'body' ? window.innerWidth : $parent.outerWidth() var parentHeight = this.options.container == 'body' ? window.innerHeight : $parent.outerHeight() var parentLeft = this.options.container == 'body' ? 0 : $parent.offset().left placement = placement == 'bottom' && pos.top + pos.height + actualHeight - docScroll > parentHeight ? 'top' : placement == 'top' && pos.top - docScroll - actualHeight < 0 ? 'bottom' : placement == 'right' && pos.right + actualWidth > parentWidth ? 'left' : placement == 'left' && pos.left - actualWidth < parentLeft ? 'right' : placement $tip .removeClass(orgPlacement) .addClass(placement) } var calculatedOffset = this.getCalculatedOffset(placement, pos, actualWidth, actualHeight) this.applyPlacement(calculatedOffset, placement) this.hoverState = null var complete = function() { that.$element.trigger('shown.bs.' + that.type) } $.support.transition && this.$tip.hasClass('fade') ? $tip .one($.support.transition.end, complete) .emulateTransitionEnd(150) : complete() } } Tooltip.prototype.applyPlacement = function (offset, placement) { var replace var $tip = this.tip() var width = $tip[0].offsetWidth var height = $tip[0].offsetHeight // manually read margins because getBoundingClientRect includes difference var marginTop = parseInt($tip.css('margin-top'), 10) var marginLeft = parseInt($tip.css('margin-left'), 10) // we must check for NaN for ie 8/9 if (isNaN(marginTop)) marginTop = 0 if (isNaN(marginLeft)) marginLeft = 0 offset.top = offset.top + marginTop offset.left = offset.left + marginLeft // $.fn.offset doesn't round pixel values // so we use setOffset directly with our own function B-0 $.offset.setOffset($tip[0], $.extend({ using: function (props) { $tip.css({ top: Math.round(props.top), left: Math.round(props.left) }) } }, offset), 0) $tip.addClass('in') // check to see if placing tip in new offset caused the tip to resize itself var actualWidth = $tip[0].offsetWidth var actualHeight = $tip[0].offsetHeight if (placement == 'top' && actualHeight != height) { replace = true offset.top = offset.top + height - actualHeight } if (/bottom|top/.test(placement)) { var delta = 0 if (offset.left < 0) { delta = offset.left * -2 offset.left = 0 $tip.offset(offset) actualWidth = $tip[0].offsetWidth actualHeight = $tip[0].offsetHeight } this.replaceArrow(delta - width + actualWidth, actualWidth, 'left') } else { this.replaceArrow(actualHeight - height, actualHeight, 'top') } if (replace) $tip.offset(offset) } Tooltip.prototype.replaceArrow = function (delta, dimension, position) { this.arrow().css(position, delta ? (50 * (1 - delta / dimension) + '%') : '') } Tooltip.prototype.setContent = function () { var $tip = this.tip() var title = this.getTitle() $tip.find('.tooltip-inner')[this.options.html ? 'html' : 'text'](title) $tip.removeClass('fade in top bottom left right') } Tooltip.prototype.hide = function () { var that = this var $tip = this.tip() var e = $.Event('hide.bs.' + this.type) function complete() { if (that.hoverState != 'in') $tip.detach() that.$element.trigger('hidden.bs.' + that.type) } this.$element.trigger(e) if (e.isDefaultPrevented()) return $tip.removeClass('in') $.support.transition && this.$tip.hasClass('fade') ? $tip .one($.support.transition.end, complete) .emulateTransitionEnd(150) : complete() this.hoverState = null return this } Tooltip.prototype.fixTitle = function () { var $e = this.$element if ($e.attr('title') || typeof($e.attr('data-original-title')) != 'string') { $e.attr('data-original-title', $e.attr('title') || '').attr('title', '') } } Tooltip.prototype.hasContent = function () { return this.getTitle() } Tooltip.prototype.getPosition = function () { var el = this.$element[0] return $.extend({}, (typeof el.getBoundingClientRect == 'function') ? el.getBoundingClientRect() : { width: el.offsetWidth, height: el.offsetHeight }, this.$element.offset()) } Tooltip.prototype.getCalculatedOffset = function (placement, pos, actualWidth, actualHeight) { return placement == 'bottom' ? { top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2 } : placement == 'top' ? { top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2 } : placement == 'left' ? { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth } : /* placement == 'right' */ { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width } } Tooltip.prototype.getTitle = function () { var title var $e = this.$element var o = this.options title = $e.attr('data-original-title') || (typeof o.title == 'function' ? o.title.call($e[0]) : o.title) return title } Tooltip.prototype.tip = function () { return this.$tip = this.$tip || $(this.options.template) } Tooltip.prototype.arrow = function () { return this.$arrow = this.$arrow || this.tip().find('.tooltip-arrow') } Tooltip.prototype.validate = function () { if (!this.$element[0].parentNode) { this.hide() this.$element = null this.options = null } } Tooltip.prototype.enable = function () { this.enabled = true } Tooltip.prototype.disable = function () { this.enabled = false } Tooltip.prototype.toggleEnabled = function () { this.enabled = !this.enabled } Tooltip.prototype.toggle = function (e) { var self = e ? $(e.currentTarget)[this.type](this.getDelegateOptions()).data('bs.' + this.type) : this self.tip().hasClass('in') ? self.leave(self) : self.enter(self) } Tooltip.prototype.destroy = function () { clearTimeout(this.timeout) this.hide().$element.off('.' + this.type).removeData('bs.' + this.type) } // TOOLTIP PLUGIN DEFINITION // ========================= var old = $.fn.tooltip $.fn.tooltip = function (option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.tooltip') var options = typeof option == 'object' && option if (!data && option == 'destroy') return if (!data) $this.data('bs.tooltip', (data = new Tooltip(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.tooltip.Constructor = Tooltip // TOOLTIP NO CONFLICT // =================== $.fn.tooltip.noConflict = function () { $.fn.tooltip = old return this } }(jQuery); /* ======================================================================== * Bootstrap: popover.js v3.1.0 * http://getbootstrap.com/javascript/#popovers * ======================================================================== * Copyright 2011-2014 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // POPOVER PUBLIC CLASS DEFINITION // =============================== var Popover = function (element, options) { this.init('popover', element, options) } if (!$.fn.tooltip) throw new Error('Popover requires tooltip.js') Popover.DEFAULTS = $.extend({}, $.fn.tooltip.Constructor.DEFAULTS, { placement: 'right', trigger: 'click', content: '', template: '<div class="popover"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>' }) // NOTE: POPOVER EXTENDS tooltip.js // ================================ Popover.prototype = $.extend({}, $.fn.tooltip.Constructor.prototype) Popover.prototype.constructor = Popover Popover.prototype.getDefaults = function () { return Popover.DEFAULTS } Popover.prototype.setContent = function () { var $tip = this.tip() var title = this.getTitle() var content = this.getContent() $tip.find('.popover-title')[this.options.html ? 'html' : 'text'](title) $tip.find('.popover-content')[ // we use append for html objects to maintain js events this.options.html ? (typeof content == 'string' ? 'html' : 'append') : 'text' ](content) $tip.removeClass('fade top bottom left right in') // IE8 doesn't accept hiding via the `:empty` pseudo selector, we have to do // this manually by checking the contents. if (!$tip.find('.popover-title').html()) $tip.find('.popover-title').hide() } Popover.prototype.hasContent = function () { return this.getTitle() || this.getContent() } Popover.prototype.getContent = function () { var $e = this.$element var o = this.options return $e.attr('data-content') || (typeof o.content == 'function' ? o.content.call($e[0]) : o.content) } Popover.prototype.arrow = function () { return this.$arrow = this.$arrow || this.tip().find('.arrow') } Popover.prototype.tip = function () { if (!this.$tip) this.$tip = $(this.options.template) return this.$tip } // POPOVER PLUGIN DEFINITION // ========================= var old = $.fn.popover $.fn.popover = function (option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.popover') var options = typeof option == 'object' && option if (!data && option == 'destroy') return if (!data) $this.data('bs.popover', (data = new Popover(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.popover.Constructor = Popover // POPOVER NO CONFLICT // =================== $.fn.popover.noConflict = function () { $.fn.popover = old return this } }(jQuery);
CAAT.Module({ defines : "CAAT.Module.Preloader.XHR", extendsWith : { /** * * @param callback function({string},{object}) a callback function. string will be "ok" or "error" * @param url {string} a url * @param asynch {bool} load synchronous or asynchronously * @param method {string} GET or POST */ load : function( callback, url, asynch, method ) { if (typeof asynch==="undefined") { asynch= true; } if (typeof method==="undefined") { method= "GET";; } var req = false; if(window.XMLHttpRequest && !(window.ActiveXObject)) { try { req = new XMLHttpRequest(); } catch(e) { req = false; } } else if(window.ActiveXObject) { try { req = new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) { try { req = new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) { req = false; } } } if(req) { req.open(method, url, false); req.onreadystatechange = function(e) { if( req.status != 200 ) return callback("error"); var text= e.currentTarget ? e.currentTarget.responseText : e.target.responseText; callback("ok", text); } ; req.send(); } } } });
var postgres = require('../config.js').postgres; module.exports = function(ws, data) { if (data.action === 'list') { var patches = []; postgres.query('SELECT time, patch, user_email, id, parent FROM changes WHERE file_id=$1 AND time>$2 ORDER BY time ASC', [ws.docId, new Date(data.after || 0)]).on('row', function(row) { patches.push(row); }).on('end', function() { ws.sendJSON({ type: 'diff_list', reqId: data.reqId, patches: patches }); }); } };
'use strict'; describe('$routeProvider', function() { var $routeProvider; beforeEach(module('ngRoute')); beforeEach(module(function(_$routeProvider_) { $routeProvider = _$routeProvider_; $routeProvider.when('/foo', {template: 'Hello, world!'}); })); it('should support enabling/disabling automatic instantiation upon initial load', inject(function() { expect($routeProvider.eagerInstantiationEnabled(true)).toBe($routeProvider); expect($routeProvider.eagerInstantiationEnabled()).toBe(true); expect($routeProvider.eagerInstantiationEnabled(false)).toBe($routeProvider); expect($routeProvider.eagerInstantiationEnabled()).toBe(false); expect($routeProvider.eagerInstantiationEnabled(true)).toBe($routeProvider); expect($routeProvider.eagerInstantiationEnabled()).toBe(true); }) ); it('should automatically instantiate `$route` upon initial load', function() { inject(function($location, $rootScope) { $location.path('/foo'); $rootScope.$digest(); }); inject(function($route) { expect($route.current).toBeDefined(); }); }); it('should not automatically instantiate `$route` if disabled', function() { module(function($routeProvider) { $routeProvider.eagerInstantiationEnabled(false); }); inject(function($location, $rootScope) { $location.path('/foo'); $rootScope.$digest(); }); inject(function($route) { expect($route.current).toBeUndefined(); }); }); }); describe('$route', function() { var $httpBackend, element; beforeEach(module('ngRoute')); beforeEach(module(function() { return function(_$httpBackend_) { $httpBackend = _$httpBackend_; $httpBackend.when('GET', 'Chapter.html').respond('chapter'); $httpBackend.when('GET', 'test.html').respond('test'); $httpBackend.when('GET', 'foo.html').respond('foo'); $httpBackend.when('GET', 'baz.html').respond('baz'); $httpBackend.when('GET', 'bar.html').respond('bar'); $httpBackend.when('GET', 'http://example.com/trusted-template.html').respond('cross domain trusted template'); $httpBackend.when('GET', '404.html').respond('not found'); }; })); afterEach(function() { dealoc(element); }); it('should allow cancellation via $locationChangeStart via $routeChangeStart', function() { module(function($routeProvider) { $routeProvider.when('/Edit', { id: 'edit', template: 'Some edit functionality' }); $routeProvider.when('/Home', { id: 'home' }); }); module(provideLog); inject(function($route, $location, $rootScope, $compile, log) { $rootScope.$on('$routeChangeStart', function(event, next, current) { if (next.id === 'home' && current.scope.unsavedChanges) { event.preventDefault(); } }); element = $compile('<div><div ng-view></div></div>')($rootScope); $rootScope.$apply(function() { $location.path('/Edit'); }); $rootScope.$on('$routeChangeSuccess', log.fn('routeChangeSuccess')); $rootScope.$on('$locationChangeSuccess', log.fn('locationChangeSuccess')); // aborted route change $rootScope.$apply(function() { $route.current.scope.unsavedChanges = true; }); $rootScope.$apply(function() { $location.path('/Home'); }); expect($route.current.id).toBe('edit'); expect($location.path()).toBe('/Edit'); expect(log).toEqual([]); // successful route change $rootScope.$apply(function() { $route.current.scope.unsavedChanges = false; }); $rootScope.$apply(function() { $location.path('/Home'); }); expect($route.current.id).toBe('home'); expect($location.path()).toBe('/Home'); expect(log).toEqual(['locationChangeSuccess', 'routeChangeSuccess']); }); }); it('should allow redirects while handling $routeChangeStart', function() { module(function($routeProvider) { $routeProvider.when('/some', { id: 'some', template: 'Some functionality' }); $routeProvider.when('/redirect', { id: 'redirect' }); }); module(provideLog); inject(function($route, $location, $rootScope, $compile, log) { $rootScope.$on('$routeChangeStart', function(event, next, current) { if (next.id === 'some') { $location.path('/redirect'); } }); $compile('<div><div ng-view></div></div>')($rootScope); $rootScope.$on('$routeChangeStart', log.fn('routeChangeStart')); $rootScope.$on('$routeChangeError', log.fn('routeChangeError')); $rootScope.$on('$routeChangeSuccess', log.fn('routeChangeSuccess')); $rootScope.$apply(function() { $location.path('/some'); }); expect($route.current.id).toBe('redirect'); expect($location.path()).toBe('/redirect'); expect(log).toEqual(['routeChangeStart', 'routeChangeStart', 'routeChangeSuccess']); }); }); it('should route and fire change event', function() { var log = '', lastRoute, nextRoute; module(function($routeProvider) { $routeProvider.when('/Book/:book/Chapter/:chapter', {controller: angular.noop, templateUrl: 'Chapter.html'}); $routeProvider.when('/Blank', {}); }); inject(function($route, $location, $rootScope) { $rootScope.$on('$routeChangeStart', function(event, next, current) { log += 'before();'; expect(current).toBe($route.current); lastRoute = current; nextRoute = next; }); $rootScope.$on('$routeChangeSuccess', function(event, current, last) { log += 'after();'; expect(current).toBe($route.current); expect(lastRoute).toBe(last); expect(nextRoute).toBe(current); }); $location.path('/Book/Moby/Chapter/Intro').search('p=123'); $rootScope.$digest(); $httpBackend.flush(); expect(log).toEqual('before();after();'); expect($route.current.params).toEqual({book:'Moby', chapter:'Intro', p:'123'}); log = ''; $location.path('/Blank').search('ignore'); $rootScope.$digest(); expect(log).toEqual('before();after();'); expect($route.current.params).toEqual({ignore:true}); log = ''; $location.path('/NONE'); $rootScope.$digest(); expect(log).toEqual('before();after();'); expect($route.current).toEqual(undefined); }); }); it('should route and fire change event when catch-all params are used', function() { var log = '', lastRoute, nextRoute; module(function($routeProvider) { $routeProvider.when('/Book1/:book/Chapter/:chapter/:highlight*/edit', {controller: angular.noop, templateUrl: 'Chapter.html'}); $routeProvider.when('/Book2/:book/:highlight*/Chapter/:chapter', {controller: angular.noop, templateUrl: 'Chapter.html'}); $routeProvider.when('/Blank', {}); }); inject(function($route, $location, $rootScope) { $rootScope.$on('$routeChangeStart', function(event, next, current) { log += 'before();'; expect(current).toBe($route.current); lastRoute = current; nextRoute = next; }); $rootScope.$on('$routeChangeSuccess', function(event, current, last) { log += 'after();'; expect(current).toBe($route.current); expect(lastRoute).toBe(last); expect(nextRoute).toBe(current); }); $location.path('/Book1/Moby/Chapter/Intro/one/edit').search('p=123'); $rootScope.$digest(); $httpBackend.flush(); expect(log).toEqual('before();after();'); expect($route.current.params).toEqual({book:'Moby', chapter:'Intro', highlight:'one', p:'123'}); log = ''; $location.path('/Blank').search('ignore'); $rootScope.$digest(); expect(log).toEqual('before();after();'); expect($route.current.params).toEqual({ignore:true}); log = ''; $location.path('/Book1/Moby/Chapter/Intro/one/two/edit').search('p=123'); $rootScope.$digest(); expect(log).toEqual('before();after();'); expect($route.current.params).toEqual({book:'Moby', chapter:'Intro', highlight:'one/two', p:'123'}); log = ''; $location.path('/Book2/Moby/one/two/Chapter/Intro').search('p=123'); $rootScope.$digest(); expect(log).toEqual('before();after();'); expect($route.current.params).toEqual({book:'Moby', chapter:'Intro', highlight:'one/two', p:'123'}); log = ''; $location.path('/NONE'); $rootScope.$digest(); expect(log).toEqual('before();after();'); expect($route.current).toEqual(undefined); }); }); it('should route and fire change event correctly whenever the case insensitive flag is utilized', function() { var log = '', lastRoute, nextRoute; module(function($routeProvider) { $routeProvider.when('/Book1/:book/Chapter/:chapter/:highlight*/edit', {controller: angular.noop, templateUrl: 'Chapter.html', caseInsensitiveMatch: true}); $routeProvider.when('/Book2/:book/:highlight*/Chapter/:chapter', {controller: angular.noop, templateUrl: 'Chapter.html'}); $routeProvider.when('/Blank', {}); }); inject(function($route, $location, $rootScope) { $rootScope.$on('$routeChangeStart', function(event, next, current) { log += 'before();'; expect(current).toBe($route.current); lastRoute = current; nextRoute = next; }); $rootScope.$on('$routeChangeSuccess', function(event, current, last) { log += 'after();'; expect(current).toBe($route.current); expect(lastRoute).toBe(last); expect(nextRoute).toBe(current); }); $location.path('/Book1/Moby/Chapter/Intro/one/edit').search('p=123'); $rootScope.$digest(); $httpBackend.flush(); expect(log).toEqual('before();after();'); expect($route.current.params).toEqual({book:'Moby', chapter:'Intro', highlight:'one', p:'123'}); log = ''; $location.path('/BOOK1/Moby/CHAPTER/Intro/one/EDIT').search('p=123'); $rootScope.$digest(); expect(log).toEqual('before();after();'); expect($route.current.params).toEqual({book:'Moby', chapter:'Intro', highlight:'one', p:'123'}); log = ''; $location.path('/Blank').search('ignore'); $rootScope.$digest(); expect(log).toEqual('before();after();'); expect($route.current.params).toEqual({ignore:true}); log = ''; $location.path('/BLANK'); $rootScope.$digest(); expect(log).toEqual('before();after();'); expect($route.current).toEqual(undefined); log = ''; $location.path('/Book2/Moby/one/two/Chapter/Intro').search('p=123'); $rootScope.$digest(); expect(log).toEqual('before();after();'); expect($route.current.params).toEqual({book:'Moby', chapter:'Intro', highlight:'one/two', p:'123'}); log = ''; $location.path('/BOOK2/Moby/one/two/CHAPTER/Intro').search('p=123'); $rootScope.$digest(); expect(log).toEqual('before();after();'); expect($route.current).toEqual(undefined); }); }); it('should allow configuring caseInsensitiveMatch on the route provider level', function() { module(function($routeProvider) { $routeProvider.caseInsensitiveMatch = true; $routeProvider.when('/Blank', {template: 'blank'}); $routeProvider.otherwise({template: 'other'}); }); inject(function($route, $location, $rootScope) { $location.path('/bLaNk'); $rootScope.$digest(); expect($route.current.template).toBe('blank'); }); }); it('should allow overriding provider\'s caseInsensitiveMatch setting on the route level', function() { module(function($routeProvider) { $routeProvider.caseInsensitiveMatch = true; $routeProvider.when('/Blank', {template: 'blank', caseInsensitiveMatch: false}); $routeProvider.otherwise({template: 'other'}); }); inject(function($route, $location, $rootScope) { $location.path('/bLaNk'); $rootScope.$digest(); expect($route.current.template).toBe('other'); }); }); it('should not change route when location is canceled', function() { module(function($routeProvider) { $routeProvider.when('/somePath', {template: 'some path'}); }); inject(function($route, $location, $rootScope, $log) { $rootScope.$on('$locationChangeStart', function(event) { $log.info('$locationChangeStart'); event.preventDefault(); }); $rootScope.$on('$routeChangeSuccess', function(event) { throw new Error('Should not get here'); }); $location.path('/somePath'); $rootScope.$digest(); expect($log.info.logs.shift()).toEqual(['$locationChangeStart']); }); }); describe('should match a route that contains special chars in the path', function() { beforeEach(module(function($routeProvider) { $routeProvider.when('/$test.23/foo*(bar)/:baz', {templateUrl: 'test.html'}); })); it('matches the full path', inject(function($route, $location, $rootScope) { $location.path('/test'); $rootScope.$digest(); expect($route.current).toBeUndefined(); })); it('matches literal .', inject(function($route, $location, $rootScope) { $location.path('/$testX23/foo*(bar)/222'); $rootScope.$digest(); expect($route.current).toBeUndefined(); })); it('matches literal *', inject(function($route, $location, $rootScope) { $location.path('/$test.23/foooo(bar)/222'); $rootScope.$digest(); expect($route.current).toBeUndefined(); })); it('treats backslashes normally', inject(function($route, $location, $rootScope) { $location.path('/$test.23/foo*\\(bar)/222'); $rootScope.$digest(); expect($route.current).toBeUndefined(); })); it('matches a URL with special chars', inject(function($route, $location, $rootScope) { $location.path('/$test.23/foo*(bar)/~!@#$%^&*()_+=-`'); $rootScope.$digest(); expect($route.current).toBeDefined(); })); it('should use route params inherited from prototype chain', function() { function BaseRoute() {} BaseRoute.prototype.templateUrl = 'foo.html'; module(function($routeProvider) { $routeProvider.when('/foo', new BaseRoute()); }); inject(function($route, $location, $rootScope) { $location.path('/foo'); $rootScope.$digest(); expect($route.current.templateUrl).toBe('foo.html'); }); }); }); describe('should match a route that contains optional params in the path', function() { beforeEach(module(function($routeProvider) { $routeProvider.when('/test/:opt?/:baz/edit', {templateUrl: 'test.html'}); })); it('matches a URL with optional params', inject(function($route, $location, $rootScope) { $location.path('/test/optValue/bazValue/edit'); $rootScope.$digest(); expect($route.current).toBeDefined(); })); it('matches a URL without optional param', inject(function($route, $location, $rootScope) { $location.path('/test//bazValue/edit'); $rootScope.$digest(); expect($route.current).toBeDefined(); })); it('not match a URL with a required param', inject(function($route, $location, $rootScope) { $location.path('///edit'); $rootScope.$digest(); expect($route.current).not.toBeDefined(); })); }); it('should change route even when only search param changes', function() { module(function($routeProvider) { $routeProvider.when('/test', {templateUrl: 'test.html'}); }); inject(function($route, $location, $rootScope) { var callback = jasmine.createSpy('onRouteChange'); $rootScope.$on('$routeChangeStart', callback); $location.path('/test'); $rootScope.$digest(); callback.calls.reset(); $location.search({any: true}); $rootScope.$digest(); expect(callback).toHaveBeenCalled(); }); }); it('should allow routes to be defined with just templates without controllers', function() { module(function($routeProvider) { $routeProvider.when('/foo', {templateUrl: 'foo.html'}); }); inject(function($route, $location, $rootScope) { var onChangeSpy = jasmine.createSpy('onChange'); $rootScope.$on('$routeChangeStart', onChangeSpy); expect($route.current).toBeUndefined(); expect(onChangeSpy).not.toHaveBeenCalled(); $location.path('/foo'); $rootScope.$digest(); expect($route.current.templateUrl).toEqual('foo.html'); expect($route.current.controller).toBeUndefined(); expect(onChangeSpy).toHaveBeenCalled(); }); }); it('should chain whens and otherwise', function() { module(function($routeProvider) { $routeProvider.when('/foo', {templateUrl: 'foo.html'}). otherwise({templateUrl: 'bar.html'}). when('/baz', {templateUrl: 'baz.html'}); }); inject(function($route, $location, $rootScope) { $rootScope.$digest(); expect($route.current.templateUrl).toBe('bar.html'); $location.url('/baz'); $rootScope.$digest(); expect($route.current.templateUrl).toBe('baz.html'); }); }); it('should skip routes with incomplete params', function() { module(function($routeProvider) { $routeProvider .otherwise({template: 'other'}) .when('/pages/:page/:comment*', {template: 'comment'}) .when('/pages/:page', {template: 'page'}) .when('/pages', {template: 'index'}) .when('/foo/', {template: 'foo'}) .when('/foo/:bar', {template: 'bar'}) .when('/foo/:bar*/:baz', {template: 'baz'}); }); inject(function($route, $location, $rootScope) { $location.url('/pages/'); $rootScope.$digest(); expect($route.current.template).toBe('index'); $location.url('/pages/page/'); $rootScope.$digest(); expect($route.current.template).toBe('page'); $location.url('/pages/page/1/'); $rootScope.$digest(); expect($route.current.template).toBe('comment'); $location.url('/foo/'); $rootScope.$digest(); expect($route.current.template).toBe('foo'); $location.url('/foo/bar/'); $rootScope.$digest(); expect($route.current.template).toBe('bar'); $location.url('/foo/bar/baz/'); $rootScope.$digest(); expect($route.current.template).toBe('baz'); $location.url('/something/'); $rootScope.$digest(); expect($route.current.template).toBe('other'); }); }); describe('otherwise', function() { it('should handle unknown routes with "otherwise" route definition', function() { function NotFoundCtrl() {} module(function($routeProvider) { $routeProvider.when('/foo', {templateUrl: 'foo.html'}); $routeProvider.otherwise({templateUrl: '404.html', controller: NotFoundCtrl}); }); inject(function($route, $location, $rootScope) { var onChangeSpy = jasmine.createSpy('onChange'); $rootScope.$on('$routeChangeStart', onChangeSpy); expect($route.current).toBeUndefined(); expect(onChangeSpy).not.toHaveBeenCalled(); $location.path('/unknownRoute'); $rootScope.$digest(); expect($route.current.templateUrl).toBe('404.html'); expect($route.current.controller).toBe(NotFoundCtrl); expect(onChangeSpy).toHaveBeenCalled(); onChangeSpy.calls.reset(); $location.path('/foo'); $rootScope.$digest(); expect($route.current.templateUrl).toEqual('foo.html'); expect($route.current.controller).toBeUndefined(); expect(onChangeSpy).toHaveBeenCalled(); }); }); it('should update $route.current and $route.next when default route is matched', function() { module(function($routeProvider) { $routeProvider.when('/foo', {templateUrl: 'foo.html'}); $routeProvider.otherwise({templateUrl: '404.html'}); }); inject(function($route, $location, $rootScope) { var currentRoute, nextRoute, onChangeSpy = jasmine.createSpy('onChange').and.callFake(function(e, next) { currentRoute = $route.current; nextRoute = next; }); // init $rootScope.$on('$routeChangeStart', onChangeSpy); expect($route.current).toBeUndefined(); expect(onChangeSpy).not.toHaveBeenCalled(); // match otherwise route $location.path('/unknownRoute'); $rootScope.$digest(); expect(currentRoute).toBeUndefined(); expect(nextRoute.templateUrl).toBe('404.html'); expect($route.current.templateUrl).toBe('404.html'); expect(onChangeSpy).toHaveBeenCalled(); onChangeSpy.calls.reset(); // match regular route $location.path('/foo'); $rootScope.$digest(); expect(currentRoute.templateUrl).toBe('404.html'); expect(nextRoute.templateUrl).toBe('foo.html'); expect($route.current.templateUrl).toEqual('foo.html'); expect(onChangeSpy).toHaveBeenCalled(); onChangeSpy.calls.reset(); // match otherwise route again $location.path('/anotherUnknownRoute'); $rootScope.$digest(); expect(currentRoute.templateUrl).toBe('foo.html'); expect(nextRoute.templateUrl).toBe('404.html'); expect($route.current.templateUrl).toEqual('404.html'); expect(onChangeSpy).toHaveBeenCalled(); }); }); it('should interpret a string as a redirect route', function() { module(function($routeProvider) { $routeProvider.when('/foo', {templateUrl: 'foo.html'}); $routeProvider.when('/baz', {templateUrl: 'baz.html'}); $routeProvider.otherwise('/foo'); }); inject(function($route, $location, $rootScope) { $location.path('/unknownRoute'); $rootScope.$digest(); expect($location.path()).toBe('/foo'); expect($route.current.templateUrl).toBe('foo.html'); }); }); }); describe('events', function() { it('should not fire $routeChangeStart/Success during bootstrap (if no route)', function() { var routeChangeSpy = jasmine.createSpy('route change'); module(function($routeProvider) { $routeProvider.when('/one', {}); // no otherwise defined }); inject(function($rootScope, $route, $location) { $rootScope.$on('$routeChangeStart', routeChangeSpy); $rootScope.$on('$routeChangeSuccess', routeChangeSpy); $rootScope.$digest(); expect(routeChangeSpy).not.toHaveBeenCalled(); $location.path('/no-route-here'); $rootScope.$digest(); expect(routeChangeSpy).not.toHaveBeenCalled(); $location.path('/one'); $rootScope.$digest(); expect(routeChangeSpy).toHaveBeenCalled(); }); }); it('should fire $routeChangeStart and resolve promises', function() { var deferA, deferB; module(function($provide, $routeProvider) { $provide.factory('b', function($q) { deferB = $q.defer(); return deferB.promise; }); $routeProvider.when('/path', { templateUrl: 'foo.html', resolve: { a: ['$q', function($q) { deferA = $q.defer(); return deferA.promise; }], b: 'b' } }); }); inject(function($location, $route, $rootScope, $httpBackend) { var log = ''; $httpBackend.expectGET('foo.html').respond('FOO'); $location.path('/path'); $rootScope.$digest(); expect(log).toEqual(''); $httpBackend.flush(); expect(log).toEqual(''); deferA.resolve(); $rootScope.$digest(); expect(log).toEqual(''); deferB.resolve(); $rootScope.$digest(); expect($route.current.locals.$template).toEqual('FOO'); }); }); it('should fire $routeChangeError event on resolution error', function() { var deferA; module(function($provide, $routeProvider) { $routeProvider.when('/path', { template: 'foo', resolve: { a: function($q) { deferA = $q.defer(); return deferA.promise; } } }); }); inject(function($location, $route, $rootScope) { var log = ''; $rootScope.$on('$routeChangeStart', function() { log += 'before();'; }); $rootScope.$on('$routeChangeError', function(e, n, l, reason) { log += 'failed(' + reason + ');'; }); $location.path('/path'); $rootScope.$digest(); expect(log).toEqual('before();'); deferA.reject('MyError'); $rootScope.$digest(); expect(log).toEqual('before();failed(MyError);'); }); }); it('should fetch templates', function() { module(function($routeProvider) { $routeProvider. when('/r1', { templateUrl: 'r1.html' }). when('/r2', { templateUrl: 'r2.html' }); }); inject(function($route, $httpBackend, $location, $rootScope) { var log = ''; $rootScope.$on('$routeChangeStart', function(e, next) { log += '$before(' + next.templateUrl + ');'; }); $rootScope.$on('$routeChangeSuccess', function(e, next) { log += '$after(' + next.templateUrl + ');'; }); $httpBackend.expectGET('r1.html').respond('R1'); $httpBackend.expectGET('r2.html').respond('R2'); $location.path('/r1'); $rootScope.$digest(); expect(log).toBe('$before(r1.html);'); $location.path('/r2'); $rootScope.$digest(); expect(log).toBe('$before(r1.html);$before(r2.html);'); $httpBackend.flush(); expect(log).toBe('$before(r1.html);$before(r2.html);$after(r2.html);'); expect(log).not.toContain('$after(r1.html);'); }); }); it('should NOT load cross domain templates by default', function() { module(function($routeProvider) { $routeProvider.when('/foo', { templateUrl: 'http://example.com/foo.html' }); }); inject(function($route, $location, $rootScope) { var onError = jasmine.createSpy('onError'); var onSuccess = jasmine.createSpy('onSuccess'); $rootScope.$on('$routeChangeError', onError); $rootScope.$on('$routeChangeSuccess', onSuccess); $location.path('/foo'); $rootScope.$digest(); expect(onSuccess).not.toHaveBeenCalled(); expect(onError).toHaveBeenCalled(); expect(onError.calls.mostRecent().args[3]).toEqualMinErr('$sce', 'insecurl', 'Blocked loading resource from url not allowed by $sceDelegate policy. ' + 'URL: http://example.com/foo.html'); }); }); it('should load cross domain templates that are trusted', function() { module(function($routeProvider, $sceDelegateProvider) { $routeProvider.when('/foo', { templateUrl: 'http://example.com/foo.html' }); $sceDelegateProvider.resourceUrlWhitelist([/^http:\/\/example\.com\/foo\.html$/]); }); inject(function($route, $location, $rootScope) { $httpBackend.whenGET('http://example.com/foo.html').respond('FOO BODY'); $location.path('/foo'); $rootScope.$digest(); $httpBackend.flush(); expect($route.current.locals.$template).toEqual('FOO BODY'); }); }); it('should not update $routeParams until $routeChangeSuccess', function() { module(function($routeProvider) { $routeProvider. when('/r1/:id', { templateUrl: 'r1.html' }). when('/r2/:id', { templateUrl: 'r2.html' }); }); inject(function($route, $httpBackend, $location, $rootScope, $routeParams) { var log = ''; $rootScope.$on('$routeChangeStart', function(e, next) { log += '$before' + angular.toJson($routeParams) + ';'; }); $rootScope.$on('$routeChangeSuccess', function(e, next) { log += '$after' + angular.toJson($routeParams) + ';'; }); $httpBackend.whenGET('r1.html').respond('R1'); $httpBackend.whenGET('r2.html').respond('R2'); $location.path('/r1/1'); $rootScope.$digest(); expect(log).toBe('$before{};'); $httpBackend.flush(); expect(log).toBe('$before{};$after{"id":"1"};'); log = ''; $location.path('/r2/2'); $rootScope.$digest(); expect(log).toBe('$before{"id":"1"};'); $httpBackend.flush(); expect(log).toBe('$before{"id":"1"};$after{"id":"2"};'); }); }); it('should drop in progress route change when new route change occurs', function() { module(function($routeProvider) { $routeProvider. when('/r1', { templateUrl: 'r1.html' }). when('/r2', { templateUrl: 'r2.html' }); }); inject(function($route, $httpBackend, $location, $rootScope) { var log = ''; $rootScope.$on('$routeChangeStart', function(e, next) { log += '$before(' + next.templateUrl + ');'; }); $rootScope.$on('$routeChangeSuccess', function(e, next) { log += '$after(' + next.templateUrl + ');'; }); $httpBackend.expectGET('r1.html').respond('R1'); $httpBackend.expectGET('r2.html').respond('R2'); $location.path('/r1'); $rootScope.$digest(); expect(log).toBe('$before(r1.html);'); $location.path('/r2'); $rootScope.$digest(); expect(log).toBe('$before(r1.html);$before(r2.html);'); $httpBackend.flush(); expect(log).toBe('$before(r1.html);$before(r2.html);$after(r2.html);'); expect(log).not.toContain('$after(r1.html);'); }); }); it('should throw an error when a template is not found', function() { module(function($routeProvider, $exceptionHandlerProvider) { $exceptionHandlerProvider.mode('log'); $routeProvider. when('/r1', { templateUrl: 'r1.html' }). when('/r2', { templateUrl: 'r2.html' }). when('/r3', { templateUrl: 'r3.html' }); }); inject(function($route, $httpBackend, $location, $rootScope, $exceptionHandler) { $httpBackend.expectGET('r1.html').respond(404, 'R1'); $location.path('/r1'); $rootScope.$digest(); $httpBackend.flush(); expect($exceptionHandler.errors.pop()). toEqualMinErr('$templateRequest', 'tpload', 'Failed to load template: r1.html'); $httpBackend.expectGET('r2.html').respond(''); $location.path('/r2'); $rootScope.$digest(); $httpBackend.flush(); expect($exceptionHandler.errors.length).toBe(0); $httpBackend.expectGET('r3.html').respond('abc'); $location.path('/r3'); $rootScope.$digest(); $httpBackend.flush(); expect($exceptionHandler.errors.length).toBe(0); }); }); it('should catch local factory errors', function() { var myError = new Error('MyError'); module(function($routeProvider) { $routeProvider.when('/locals', { resolve: { a: function($q) { throw myError; } } }); }); inject(function($location, $route, $rootScope) { spyOn($rootScope, '$broadcast').and.callThrough(); $location.path('/locals'); $rootScope.$digest(); expect($rootScope.$broadcast).toHaveBeenCalledWith( '$routeChangeError', jasmine.any(Object), undefined, myError); }); }); }); it('should match route with and without trailing slash', function() { module(function($routeProvider) { $routeProvider.when('/foo', {templateUrl: 'foo.html'}); $routeProvider.when('/bar/', {templateUrl: 'bar.html'}); }); inject(function($route, $location, $rootScope) { $location.path('/foo'); $rootScope.$digest(); expect($location.path()).toBe('/foo'); expect($route.current.templateUrl).toBe('foo.html'); $location.path('/foo/'); $rootScope.$digest(); expect($location.path()).toBe('/foo'); expect($route.current.templateUrl).toBe('foo.html'); $location.path('/bar'); $rootScope.$digest(); expect($location.path()).toBe('/bar/'); expect($route.current.templateUrl).toBe('bar.html'); $location.path('/bar/'); $rootScope.$digest(); expect($location.path()).toBe('/bar/'); expect($route.current.templateUrl).toBe('bar.html'); }); }); it('should not get affected by modifying the route definition object after route registration', function() { module(function($routeProvider) { var rdo = {}; rdo.templateUrl = 'foo.html'; $routeProvider.when('/foo', rdo); rdo.templateUrl = 'bar.html'; $routeProvider.when('/bar', rdo); }); inject(function($location, $rootScope, $route) { $location.path('/bar'); $rootScope.$digest(); expect($location.path()).toBe('/bar'); expect($route.current.templateUrl).toBe('bar.html'); $location.path('/foo'); $rootScope.$digest(); expect($location.path()).toBe('/foo'); expect($route.current.templateUrl).toBe('foo.html'); }); } ); it('should use the property values of the passed in route definition object directly', function() { var $routeProvider; module(function(_$routeProvider_) { $routeProvider = _$routeProvider_; }); inject(function($location, $rootScope, $route, $sce) { var sceWrappedUrl = $sce.trustAsResourceUrl('foo.html'); $routeProvider.when('/foo', {templateUrl: sceWrappedUrl}); $location.path('/foo'); $rootScope.$digest(); expect($location.path()).toBe('/foo'); expect($route.current.templateUrl).toBe(sceWrappedUrl); }); } ); it('should support custom `$sce` implementations', function() { function MySafeResourceUrl(val) { var self = this; this._val = val; this.getVal = function() { return (this !== self) ? null : this._val; }; } var $routeProvider; module(function($provide, _$routeProvider_) { $routeProvider = _$routeProvider_; $provide.decorator('$sce', function($delegate) { function getVal(v) { return v.getVal ? v.getVal() : v; } $delegate.trustAsResourceUrl = function(url) { return new MySafeResourceUrl(url); }; $delegate.getTrustedResourceUrl = function(v) { return getVal(v); }; $delegate.valueOf = function(v) { return getVal(v); }; return $delegate; }); }); inject(function($location, $rootScope, $route, $sce) { $routeProvider.when('/foo', {templateUrl: $sce.trustAsResourceUrl('foo.html')}); $location.path('/foo'); $rootScope.$digest(); expect($location.path()).toBe('/foo'); expect($sce.valueOf($route.current.templateUrl)).toBe('foo.html'); }); }); describe('redirection', function() { describe('via `redirectTo`', function() { it('should support redirection via redirectTo property by updating $location', function() { module(function($routeProvider) { $routeProvider.when('/', {redirectTo: '/foo'}); $routeProvider.when('/foo', {templateUrl: 'foo.html'}); $routeProvider.when('/bar', {templateUrl: 'bar.html'}); $routeProvider.when('/baz', {redirectTo: '/bar'}); $routeProvider.otherwise({templateUrl: '404.html'}); }); inject(function($route, $location, $rootScope) { var onChangeSpy = jasmine.createSpy('onChange'); $rootScope.$on('$routeChangeStart', onChangeSpy); expect($route.current).toBeUndefined(); expect(onChangeSpy).not.toHaveBeenCalled(); $location.path('/'); $rootScope.$digest(); expect($location.path()).toBe('/foo'); expect($route.current.templateUrl).toBe('foo.html'); expect(onChangeSpy).toHaveBeenCalledTimes(2); onChangeSpy.calls.reset(); $location.path('/baz'); $rootScope.$digest(); expect($location.path()).toBe('/bar'); expect($route.current.templateUrl).toBe('bar.html'); expect(onChangeSpy).toHaveBeenCalledTimes(2); }); }); it('should interpolate route vars in the redirected path from original path', function() { module(function($routeProvider) { $routeProvider.when('/foo/:id/foo/:subid/:extraId', {redirectTo: '/bar/:id/:subid/23'}); $routeProvider.when('/bar/:id/:subid/:subsubid', {templateUrl: 'bar.html'}); $routeProvider.when('/baz/:id/:path*', {redirectTo: '/path/:path/:id'}); $routeProvider.when('/path/:path*/:id', {templateUrl: 'foo.html'}); }); inject(function($route, $location, $rootScope) { $location.path('/foo/id1/foo/subid3/gah'); $rootScope.$digest(); expect($location.path()).toEqual('/bar/id1/subid3/23'); expect($location.search()).toEqual({extraId: 'gah'}); expect($route.current.templateUrl).toEqual('bar.html'); $location.path('/baz/1/foovalue/barvalue'); $rootScope.$digest(); expect($location.path()).toEqual('/path/foovalue/barvalue/1'); expect($route.current.templateUrl).toEqual('foo.html'); }); }); it('should interpolate route vars in the redirected path from original search', function() { module(function($routeProvider) { $routeProvider.when('/bar/:id/:subid/:subsubid', {templateUrl: 'bar.html'}); $routeProvider.when('/foo/:id/:extra', {redirectTo: '/bar/:id/:subid/99'}); }); inject(function($route, $location, $rootScope) { $location.path('/foo/id3/eId').search('subid=sid1&appended=true'); $rootScope.$digest(); expect($location.path()).toEqual('/bar/id3/sid1/99'); expect($location.search()).toEqual({appended: 'true', extra: 'eId'}); expect($route.current.templateUrl).toEqual('bar.html'); }); }); it('should properly process route params which are both eager and optional', function() { module(function($routeProvider) { $routeProvider.when('/foo/:param1*?/:param2', {templateUrl: 'foo.html'}); }); inject(function($location, $rootScope, $route) { $location.path('/foo/bar1/bar2/bar3/baz'); $rootScope.$digest(); expect($location.path()).toEqual('/foo/bar1/bar2/bar3/baz'); expect($route.current.params.param1).toEqual('bar1/bar2/bar3'); expect($route.current.params.param2).toEqual('baz'); expect($route.current.templateUrl).toEqual('foo.html'); $location.path('/foo/baz'); $rootScope.$digest(); expect($location.path()).toEqual('/foo/baz'); expect($route.current.params.param1).toEqual(undefined); expect($route.current.params.param2).toEqual('baz'); expect($route.current.templateUrl).toEqual('foo.html'); }); }); it('should properly interpolate optional and eager route vars ' + 'when redirecting from path with trailing slash', function() { module(function($routeProvider) { $routeProvider.when('/foo/:id?/:subid?', {templateUrl: 'foo.html'}); $routeProvider.when('/bar/:id*/:subid', {templateUrl: 'bar.html'}); }); inject(function($location, $rootScope, $route) { $location.path('/foo/id1/subid2/'); $rootScope.$digest(); expect($location.path()).toEqual('/foo/id1/subid2'); expect($route.current.templateUrl).toEqual('foo.html'); $location.path('/bar/id1/extra/subid2/'); $rootScope.$digest(); expect($location.path()).toEqual('/bar/id1/extra/subid2'); expect($route.current.templateUrl).toEqual('bar.html'); }); }); it('should allow custom redirectTo function to be used', function() { function customRedirectFn(routePathParams, path, search) { expect(routePathParams).toEqual({id: 'id3'}); expect(path).toEqual('/foo/id3'); expect(search).toEqual({subid: 'sid1', appended: 'true'}); return '/custom'; } module(function($routeProvider) { $routeProvider.when('/foo/:id', {redirectTo: customRedirectFn}); }); inject(function($route, $location, $rootScope) { $location.path('/foo/id3').search('subid=sid1&appended=true'); $rootScope.$digest(); expect($location.path()).toEqual('/custom'); }); }); it('should broadcast `$routeChangeError` when redirectTo throws', function() { var error = new Error('Test'); module(function($routeProvider) { $routeProvider.when('/foo', {redirectTo: function() { throw error; }}); }); inject(function($exceptionHandler, $location, $rootScope, $route) { spyOn($rootScope, '$broadcast').and.callThrough(); $location.path('/foo'); $rootScope.$digest(); var lastCallArgs = $rootScope.$broadcast.calls.mostRecent().args; expect(lastCallArgs[0]).toBe('$routeChangeError'); expect(lastCallArgs[3]).toBe(error); }); }); it('should replace the url when redirecting', function() { module(function($routeProvider) { $routeProvider.when('/bar/:id', {templateUrl: 'bar.html'}); $routeProvider.when('/foo/:id/:extra', {redirectTo: '/bar/:id'}); }); inject(function($browser, $route, $location, $rootScope) { var $browserUrl = spyOnlyCallsWithArgs($browser, 'url').and.callThrough(); $location.path('/foo/id3/eId'); $rootScope.$digest(); expect($location.path()).toEqual('/bar/id3'); expect($browserUrl.calls.mostRecent().args) .toEqual(['http://server/#!/bar/id3?extra=eId', true, null]); }); }); it('should not process route bits', function() { var firstController = jasmine.createSpy('first controller spy'); var firstTemplate = jasmine.createSpy('first template spy').and.returnValue('redirected view'); var firstResolve = jasmine.createSpy('first resolve spy'); var secondController = jasmine.createSpy('second controller spy'); var secondTemplate = jasmine.createSpy('second template spy').and.returnValue('redirected view'); var secondResolve = jasmine.createSpy('second resolve spy'); module(function($routeProvider) { $routeProvider.when('/redirect', { template: firstTemplate, redirectTo: '/redirected', resolve: { value: firstResolve }, controller: firstController }); $routeProvider.when('/redirected', { template: secondTemplate, resolve: { value: secondResolve }, controller: secondController }); }); inject(function($route, $location, $rootScope, $compile) { var element = $compile('<div><ng-view></ng-view></div>')($rootScope); $location.path('/redirect'); $rootScope.$digest(); expect(firstController).not.toHaveBeenCalled(); expect(firstTemplate).not.toHaveBeenCalled(); expect(firstResolve).not.toHaveBeenCalled(); expect(secondController).toHaveBeenCalled(); expect(secondTemplate).toHaveBeenCalled(); expect(secondResolve).toHaveBeenCalled(); dealoc(element); }); }); it('should not redirect transition if `redirectTo` returns `undefined`', function() { var controller = jasmine.createSpy('first controller spy'); var templateFn = jasmine.createSpy('first template spy').and.returnValue('redirected view'); module(function($routeProvider) { $routeProvider.when('/redirect/to/undefined', { template: templateFn, redirectTo: function() {}, controller: controller }); }); inject(function($route, $location, $rootScope, $compile) { var element = $compile('<div><ng-view></ng-view></div>')($rootScope); $location.path('/redirect/to/undefined'); $rootScope.$digest(); expect(controller).toHaveBeenCalled(); expect(templateFn).toHaveBeenCalled(); expect($location.path()).toEqual('/redirect/to/undefined'); dealoc(element); }); }); }); describe('via `resolveRedirectTo`', function() { var $compile; var $location; var $rootScope; var $route; beforeEach(module(function() { return function(_$compile_, _$location_, _$rootScope_, _$route_) { $compile = _$compile_; $location = _$location_; $rootScope = _$rootScope_; $route = _$route_; }; })); it('should be ignored if `redirectTo` is also present', function() { var newUrl; var getNewUrl = function() { return newUrl; }; var resolveRedirectToSpy = jasmine.createSpy('resolveRedirectTo').and.returnValue('/bar'); var redirectToSpy = jasmine.createSpy('redirectTo').and.callFake(getNewUrl); var templateSpy = jasmine.createSpy('template').and.returnValue('Foo'); module(function($routeProvider) { $routeProvider. when('/foo', { resolveRedirectTo: resolveRedirectToSpy, redirectTo: redirectToSpy, template: templateSpy }). when('/bar', {template: 'Bar'}). when('/baz', {template: 'Baz'}); }); inject(function() { newUrl = '/baz'; $location.path('/foo'); $rootScope.$digest(); expect($location.path()).toBe('/baz'); expect($route.current.template).toBe('Baz'); expect(resolveRedirectToSpy).not.toHaveBeenCalled(); expect(redirectToSpy).toHaveBeenCalled(); expect(templateSpy).not.toHaveBeenCalled(); redirectToSpy.calls.reset(); newUrl = undefined; $location.path('/foo'); $rootScope.$digest(); expect($location.path()).toBe('/foo'); expect($route.current.template).toBe(templateSpy); expect(resolveRedirectToSpy).not.toHaveBeenCalled(); expect(redirectToSpy).toHaveBeenCalled(); expect(templateSpy).toHaveBeenCalled(); }); }); it('should redirect to the returned url', function() { module(function($routeProvider) { $routeProvider. when('/foo', {resolveRedirectTo: function() { return '/bar?baz=qux'; }}). when('/bar', {template: 'Bar'}); }); inject(function() { $location.path('/foo'); $rootScope.$digest(); expect($location.path()).toBe('/bar'); expect($location.search()).toEqual({baz: 'qux'}); expect($route.current.template).toBe('Bar'); }); }); it('should support returning a promise', function() { module(function($routeProvider) { $routeProvider. when('/foo', {resolveRedirectTo: function($q) { return $q.resolve('/bar'); }}). when('/bar', {template: 'Bar'}); }); inject(function() { $location.path('/foo'); $rootScope.$digest(); expect($location.path()).toBe('/bar'); expect($route.current.template).toBe('Bar'); }); }); it('should support dependency injection', function() { module(function($provide, $routeProvider) { $provide.value('nextRoute', '/bar'); $routeProvider. when('/foo', { resolveRedirectTo: function(nextRoute) { return nextRoute; } }); }); inject(function() { $location.path('/foo'); $rootScope.$digest(); expect($location.path()).toBe('/bar'); }); }); it('should have access to the current routeParams via `$route.current.params`', function() { module(function($routeProvider) { $routeProvider. when('/foo/:bar/baz/:qux', { resolveRedirectTo: function($route) { expect($route.current.params).toEqual(jasmine.objectContaining({ bar: '1', qux: '2' })); return '/passed'; } }); }); inject(function() { $location.path('/foo/1/baz/2').search({bar: 'qux'}); $rootScope.$digest(); expect($location.path()).toBe('/passed'); }); }); it('should not process route bits until the promise is resolved', function() { var spies = createSpies(); var called = false; var deferred; module(function($routeProvider) { setupRoutes($routeProvider, spies, function($q) { called = true; deferred = $q.defer(); return deferred.promise; }); }); inject(function() { var element = $compile('<div><ng-view></ng-view></div>')($rootScope); $location.path('/foo'); $rootScope.$digest(); expect($location.path()).toBe('/foo'); expect(called).toBe(true); expect(spies.fooResolveSpy).not.toHaveBeenCalled(); expect(spies.fooTemplateSpy).not.toHaveBeenCalled(); expect(spies.fooControllerSpy).not.toHaveBeenCalled(); expect(spies.barResolveSpy).not.toHaveBeenCalled(); expect(spies.barTemplateSpy).not.toHaveBeenCalled(); expect(spies.barControllerSpy).not.toHaveBeenCalled(); deferred.resolve('/bar'); $rootScope.$digest(); expect($location.path()).toBe('/bar'); expect(spies.fooResolveSpy).not.toHaveBeenCalled(); expect(spies.fooTemplateSpy).not.toHaveBeenCalled(); expect(spies.fooControllerSpy).not.toHaveBeenCalled(); expect(spies.barResolveSpy).toHaveBeenCalled(); expect(spies.barTemplateSpy).toHaveBeenCalled(); expect(spies.barControllerSpy).toHaveBeenCalled(); dealoc(element); }); }); it('should not redirect if `undefined` is returned', function() { var spies = createSpies(); var called = false; module(function($routeProvider) { setupRoutes($routeProvider, spies, function() { called = true; return undefined; }); }); inject(function() { var element = $compile('<div><ng-view></ng-view></div>')($rootScope); $location.path('/foo'); $rootScope.$digest(); expect($location.path()).toBe('/foo'); expect(called).toBe(true); expect(spies.fooResolveSpy).toHaveBeenCalled(); expect(spies.fooTemplateSpy).toHaveBeenCalled(); expect(spies.fooControllerSpy).toHaveBeenCalled(); expect(spies.barResolveSpy).not.toHaveBeenCalled(); expect(spies.barTemplateSpy).not.toHaveBeenCalled(); expect(spies.barControllerSpy).not.toHaveBeenCalled(); dealoc(element); }); }); it('should not redirect if the returned promise resolves to `undefined`', function() { var spies = createSpies(); var called = false; module(function($routeProvider) { setupRoutes($routeProvider, spies, function($q) { called = true; return $q.resolve(undefined); }); }); inject(function() { var element = $compile('<div><ng-view></ng-view></div>')($rootScope); $location.path('/foo'); $rootScope.$digest(); expect($location.path()).toBe('/foo'); expect(called).toBe(true); expect(spies.fooResolveSpy).toHaveBeenCalled(); expect(spies.fooTemplateSpy).toHaveBeenCalled(); expect(spies.fooControllerSpy).toHaveBeenCalled(); expect(spies.barResolveSpy).not.toHaveBeenCalled(); expect(spies.barTemplateSpy).not.toHaveBeenCalled(); expect(spies.barControllerSpy).not.toHaveBeenCalled(); dealoc(element); }); }); it('should not redirect if the returned promise gets rejected', function() { var spies = createSpies(); var called = false; module(function($routeProvider) { setupRoutes($routeProvider, spies, function($q) { called = true; return $q.reject(''); }); }); inject(function() { spyOn($rootScope, '$broadcast').and.callThrough(); var element = $compile('<div><ng-view></ng-view></div>')($rootScope); $location.path('/foo'); $rootScope.$digest(); expect($location.path()).toBe('/foo'); expect(called).toBe(true); expect(spies.fooResolveSpy).not.toHaveBeenCalled(); expect(spies.fooTemplateSpy).not.toHaveBeenCalled(); expect(spies.fooControllerSpy).not.toHaveBeenCalled(); expect(spies.barResolveSpy).not.toHaveBeenCalled(); expect(spies.barTemplateSpy).not.toHaveBeenCalled(); expect(spies.barControllerSpy).not.toHaveBeenCalled(); var lastCallArgs = $rootScope.$broadcast.calls.mostRecent().args; expect(lastCallArgs[0]).toBe('$routeChangeError'); dealoc(element); }); }); it('should ignore previous redirection if newer transition happened', function() { var spies = createSpies(); var called = false; var deferred; module(function($routeProvider) { setupRoutes($routeProvider, spies, function($q) { called = true; deferred = $q.defer(); return deferred.promise; }); }); inject(function() { spyOn($location, 'url').and.callThrough(); var element = $compile('<div><ng-view></ng-view></div>')($rootScope); $location.path('/foo'); $rootScope.$digest(); expect($location.path()).toBe('/foo'); expect(called).toBe(true); expect(spies.fooResolveSpy).not.toHaveBeenCalled(); expect(spies.fooTemplateSpy).not.toHaveBeenCalled(); expect(spies.fooControllerSpy).not.toHaveBeenCalled(); expect(spies.barResolveSpy).not.toHaveBeenCalled(); expect(spies.barTemplateSpy).not.toHaveBeenCalled(); expect(spies.barControllerSpy).not.toHaveBeenCalled(); expect(spies.bazResolveSpy).not.toHaveBeenCalled(); expect(spies.bazTemplateSpy).not.toHaveBeenCalled(); expect(spies.bazControllerSpy).not.toHaveBeenCalled(); $location.path('/baz'); $rootScope.$digest(); expect($location.path()).toBe('/baz'); expect(spies.fooResolveSpy).not.toHaveBeenCalled(); expect(spies.fooTemplateSpy).not.toHaveBeenCalled(); expect(spies.fooControllerSpy).not.toHaveBeenCalled(); expect(spies.barResolveSpy).not.toHaveBeenCalled(); expect(spies.barTemplateSpy).not.toHaveBeenCalled(); expect(spies.barControllerSpy).not.toHaveBeenCalled(); expect(spies.bazResolveSpy).toHaveBeenCalledOnce(); expect(spies.bazTemplateSpy).toHaveBeenCalledOnce(); expect(spies.bazControllerSpy).toHaveBeenCalledOnce(); deferred.resolve(); $rootScope.$digest(); expect($location.path()).toBe('/baz'); expect(spies.fooResolveSpy).not.toHaveBeenCalled(); expect(spies.fooTemplateSpy).not.toHaveBeenCalled(); expect(spies.fooControllerSpy).not.toHaveBeenCalled(); expect(spies.barResolveSpy).not.toHaveBeenCalled(); expect(spies.barTemplateSpy).not.toHaveBeenCalled(); expect(spies.barControllerSpy).not.toHaveBeenCalled(); expect(spies.bazResolveSpy).toHaveBeenCalledOnce(); expect(spies.bazTemplateSpy).toHaveBeenCalledOnce(); expect(spies.bazControllerSpy).toHaveBeenCalledOnce(); dealoc(element); }); }); // Helpers function createSpies() { return { fooResolveSpy: jasmine.createSpy('fooResolve'), fooTemplateSpy: jasmine.createSpy('fooTemplate').and.returnValue('Foo'), fooControllerSpy: jasmine.createSpy('fooController'), barResolveSpy: jasmine.createSpy('barResolve'), barTemplateSpy: jasmine.createSpy('barTemplate').and.returnValue('Bar'), barControllerSpy: jasmine.createSpy('barController'), bazResolveSpy: jasmine.createSpy('bazResolve'), bazTemplateSpy: jasmine.createSpy('bazTemplate').and.returnValue('Baz'), bazControllerSpy: jasmine.createSpy('bazController') }; } function setupRoutes(routeProvider, spies, resolveRedirectToFn) { routeProvider. when('/foo', { resolveRedirectTo: resolveRedirectToFn, resolve: {_: spies.fooResolveSpy}, template: spies.fooTemplateSpy, controller: spies.fooControllerSpy }). when('/bar', { resolve: {_: spies.barResolveSpy}, template: spies.barTemplateSpy, controller: spies.barControllerSpy }). when('/baz', { resolve: {_: spies.bazResolveSpy}, template: spies.bazTemplateSpy, controller: spies.bazControllerSpy }); } }); }); describe('reloadOnSearch', function() { it('should reload a route when reloadOnSearch is enabled and .search() changes', function() { var reloaded = jasmine.createSpy('route reload'); module(function($routeProvider) { $routeProvider.when('/foo', {controller: angular.noop}); }); inject(function($route, $location, $rootScope, $routeParams) { $rootScope.$on('$routeChangeStart', reloaded); $location.path('/foo'); $rootScope.$digest(); expect(reloaded).toHaveBeenCalled(); expect($routeParams).toEqual({}); reloaded.calls.reset(); // trigger reload $location.search({foo: 'bar'}); $rootScope.$digest(); expect(reloaded).toHaveBeenCalled(); expect($routeParams).toEqual({foo:'bar'}); }); }); it('should not reload a route when reloadOnSearch is disabled and only .search() changes', function() { var routeChange = jasmine.createSpy('route change'), routeUpdate = jasmine.createSpy('route update'); module(function($routeProvider) { $routeProvider.when('/foo', {controller: angular.noop, reloadOnSearch: false}); }); inject(function($route, $location, $rootScope) { $rootScope.$on('$routeChangeStart', routeChange); $rootScope.$on('$routeChangeSuccess', routeChange); $rootScope.$on('$routeUpdate', routeUpdate); expect(routeChange).not.toHaveBeenCalled(); $location.path('/foo'); $rootScope.$digest(); expect(routeChange).toHaveBeenCalled(); expect(routeChange).toHaveBeenCalledTimes(2); expect(routeUpdate).not.toHaveBeenCalled(); routeChange.calls.reset(); // don't trigger reload $location.search({foo: 'bar'}); $rootScope.$digest(); expect(routeChange).not.toHaveBeenCalled(); expect(routeUpdate).toHaveBeenCalled(); }); }); it('should reload reloadOnSearch route when url differs only in route path param', function() { var routeChange = jasmine.createSpy('route change'); module(function($routeProvider) { $routeProvider.when('/foo/:fooId', {controller: angular.noop, reloadOnSearch: false}); }); inject(function($route, $location, $rootScope) { $rootScope.$on('$routeChangeStart', routeChange); $rootScope.$on('$routeChangeSuccess', routeChange); expect(routeChange).not.toHaveBeenCalled(); $location.path('/foo/aaa'); $rootScope.$digest(); expect(routeChange).toHaveBeenCalled(); expect(routeChange).toHaveBeenCalledTimes(2); routeChange.calls.reset(); $location.path('/foo/bbb'); $rootScope.$digest(); expect(routeChange).toHaveBeenCalled(); expect(routeChange).toHaveBeenCalledTimes(2); routeChange.calls.reset(); $location.search({foo: 'bar'}); $rootScope.$digest(); expect(routeChange).not.toHaveBeenCalled(); }); }); it('should update params when reloadOnSearch is disabled and .search() changes', function() { var routeParamsWatcher = jasmine.createSpy('routeParamsWatcher'); module(function($routeProvider) { $routeProvider.when('/foo', {controller: angular.noop}); $routeProvider.when('/bar/:barId', {controller: angular.noop, reloadOnSearch: false}); }); inject(function($route, $location, $rootScope, $routeParams) { $rootScope.$watch(function() { return $routeParams; }, function(value) { routeParamsWatcher(value); }, true); expect(routeParamsWatcher).not.toHaveBeenCalled(); $location.path('/foo'); $rootScope.$digest(); expect(routeParamsWatcher).toHaveBeenCalledWith({}); routeParamsWatcher.calls.reset(); // trigger reload $location.search({foo: 'bar'}); $rootScope.$digest(); expect(routeParamsWatcher).toHaveBeenCalledWith({foo: 'bar'}); routeParamsWatcher.calls.reset(); $location.path('/bar/123').search({}); $rootScope.$digest(); expect(routeParamsWatcher).toHaveBeenCalledWith({barId: '123'}); routeParamsWatcher.calls.reset(); // don't trigger reload $location.search({foo: 'bar'}); $rootScope.$digest(); expect(routeParamsWatcher).toHaveBeenCalledWith({barId: '123', foo: 'bar'}); }); }); it('should allow using a function as a template', function() { var customTemplateWatcher = jasmine.createSpy('customTemplateWatcher'); function customTemplateFn(routePathParams) { customTemplateWatcher(routePathParams); expect(routePathParams).toEqual({id: 'id3'}); return '<h1>' + routePathParams.id + '</h1>'; } module(function($routeProvider) { $routeProvider.when('/bar/:id/:subid/:subsubid', {templateUrl: 'bar.html'}); $routeProvider.when('/foo/:id', {template: customTemplateFn}); }); inject(function($route, $location, $rootScope) { $location.path('/foo/id3'); $rootScope.$digest(); expect(customTemplateWatcher).toHaveBeenCalledWith({id: 'id3'}); }); }); it('should allow using a function as a templateUrl', function() { var customTemplateUrlWatcher = jasmine.createSpy('customTemplateUrlWatcher'); function customTemplateUrlFn(routePathParams) { customTemplateUrlWatcher(routePathParams); expect(routePathParams).toEqual({id: 'id3'}); return 'foo.html'; } module(function($routeProvider) { $routeProvider.when('/bar/:id/:subid/:subsubid', {templateUrl: 'bar.html'}); $routeProvider.when('/foo/:id', {templateUrl: customTemplateUrlFn}); }); inject(function($route, $location, $rootScope) { $location.path('/foo/id3'); $rootScope.$digest(); expect(customTemplateUrlWatcher).toHaveBeenCalledWith({id: 'id3'}); expect($route.current.loadedTemplateUrl).toEqual('foo.html'); }); }); describe('reload', function() { var $location; var $log; var $rootScope; var $route; var routeChangeStartSpy; var routeChangeSuccessSpy; beforeEach(module(function($routeProvider) { $routeProvider.when('/bar/:barId', { template: '', controller: controller, reloadOnSearch: false }); function controller($log) { $log.debug('initialized'); } })); beforeEach(inject(function($compile, _$location_, _$log_, _$rootScope_, _$route_) { $location = _$location_; $log = _$log_; $rootScope = _$rootScope_; $route = _$route_; routeChangeStartSpy = jasmine.createSpy('routeChangeStart'); routeChangeSuccessSpy = jasmine.createSpy('routeChangeSuccess'); $rootScope.$on('$routeChangeStart', routeChangeStartSpy); $rootScope.$on('$routeChangeSuccess', routeChangeSuccessSpy); element = $compile('<div><div ng-view></div></div>')($rootScope); })); it('should reload the current route', function() { $location.path('/bar/123'); $rootScope.$digest(); expect($location.path()).toBe('/bar/123'); expect(routeChangeStartSpy).toHaveBeenCalledOnce(); expect(routeChangeSuccessSpy).toHaveBeenCalledOnce(); expect($log.debug.logs).toEqual([['initialized']]); routeChangeStartSpy.calls.reset(); routeChangeSuccessSpy.calls.reset(); $log.reset(); $route.reload(); $rootScope.$digest(); expect($location.path()).toBe('/bar/123'); expect(routeChangeStartSpy).toHaveBeenCalledOnce(); expect(routeChangeSuccessSpy).toHaveBeenCalledOnce(); expect($log.debug.logs).toEqual([['initialized']]); $log.reset(); }); it('should support preventing a route reload', function() { $location.path('/bar/123'); $rootScope.$digest(); expect($location.path()).toBe('/bar/123'); expect(routeChangeStartSpy).toHaveBeenCalledOnce(); expect(routeChangeSuccessSpy).toHaveBeenCalledOnce(); expect($log.debug.logs).toEqual([['initialized']]); routeChangeStartSpy.calls.reset(); routeChangeSuccessSpy.calls.reset(); $log.reset(); routeChangeStartSpy.and.callFake(function(evt) { evt.preventDefault(); }); $route.reload(); $rootScope.$digest(); expect($location.path()).toBe('/bar/123'); expect(routeChangeStartSpy).toHaveBeenCalledOnce(); expect(routeChangeSuccessSpy).not.toHaveBeenCalled(); expect($log.debug.logs).toEqual([]); }); it('should reload even if reloadOnSearch is false', inject(function($routeParams) { $location.path('/bar/123'); $rootScope.$digest(); expect($routeParams).toEqual({barId: '123'}); expect(routeChangeSuccessSpy).toHaveBeenCalledOnce(); expect($log.debug.logs).toEqual([['initialized']]); routeChangeSuccessSpy.calls.reset(); $log.reset(); $location.search('a=b'); $rootScope.$digest(); expect($routeParams).toEqual({barId: '123', a: 'b'}); expect(routeChangeSuccessSpy).not.toHaveBeenCalled(); expect($log.debug.logs).toEqual([]); $route.reload(); $rootScope.$digest(); expect($routeParams).toEqual({barId: '123', a: 'b'}); expect(routeChangeSuccessSpy).toHaveBeenCalledOnce(); expect($log.debug.logs).toEqual([['initialized']]); $log.reset(); })); }); }); describe('update', function() { it('should support single-parameter route updating', function() { var routeChangeSpy = jasmine.createSpy('route change'); module(function($routeProvider) { $routeProvider.when('/bar/:barId', {controller: angular.noop}); }); inject(function($route, $routeParams, $location, $rootScope) { $rootScope.$on('$routeChangeSuccess', routeChangeSpy); $location.path('/bar/1'); $rootScope.$digest(); routeChangeSpy.calls.reset(); $route.updateParams({barId: '2'}); $rootScope.$digest(); expect($routeParams).toEqual({barId: '2'}); expect(routeChangeSpy).toHaveBeenCalledOnce(); expect($location.path()).toEqual('/bar/2'); }); }); it('should support total multi-parameter route updating', function() { var routeChangeSpy = jasmine.createSpy('route change'); module(function($routeProvider) { $routeProvider.when('/bar/:barId/:fooId/:spamId/:eggId', {controller: angular.noop}); }); inject(function($route, $routeParams, $location, $rootScope) { $rootScope.$on('$routeChangeSuccess', routeChangeSpy); $location.path('/bar/1/2/3/4'); $rootScope.$digest(); routeChangeSpy.calls.reset(); $route.updateParams({barId: '5', fooId: '6', spamId: '7', eggId: '8'}); $rootScope.$digest(); expect($routeParams).toEqual({barId: '5', fooId: '6', spamId: '7', eggId: '8'}); expect(routeChangeSpy).toHaveBeenCalledOnce(); expect($location.path()).toEqual('/bar/5/6/7/8'); }); }); it('should support partial multi-parameter route updating', function() { var routeChangeSpy = jasmine.createSpy('route change'); module(function($routeProvider) { $routeProvider.when('/bar/:barId/:fooId/:spamId/:eggId', {controller: angular.noop}); }); inject(function($route, $routeParams, $location, $rootScope) { $rootScope.$on('$routeChangeSuccess', routeChangeSpy); $location.path('/bar/1/2/3/4'); $rootScope.$digest(); routeChangeSpy.calls.reset(); $route.updateParams({barId: '5', fooId: '6'}); $rootScope.$digest(); expect($routeParams).toEqual({barId: '5', fooId: '6', spamId: '3', eggId: '4'}); expect(routeChangeSpy).toHaveBeenCalledOnce(); expect($location.path()).toEqual('/bar/5/6/3/4'); }); }); it('should update query params when new properties are not in path', function() { var routeChangeSpy = jasmine.createSpy('route change'); module(function($routeProvider) { $routeProvider.when('/bar/:barId/:fooId/:spamId/', {controller: angular.noop}); }); inject(function($route, $routeParams, $location, $rootScope) { $rootScope.$on('$routeChangeSuccess', routeChangeSpy); $location.path('/bar/1/2/3'); $location.search({initial: 'true'}); $rootScope.$digest(); routeChangeSpy.calls.reset(); $route.updateParams({barId: '5', fooId: '6', eggId: '4'}); $rootScope.$digest(); expect($routeParams).toEqual({barId: '5', fooId: '6', spamId: '3', eggId: '4', initial: 'true'}); expect(routeChangeSpy).toHaveBeenCalledOnce(); expect($location.path()).toEqual('/bar/5/6/3/'); expect($location.search()).toEqual({eggId: '4', initial: 'true'}); }); }); it('should not update query params when an optional property was previously not in path', function() { var routeChangeSpy = jasmine.createSpy('route change'); module(function($routeProvider) { $routeProvider.when('/bar/:barId/:fooId/:spamId/:eggId?', {controller: angular.noop}); }); inject(function($route, $routeParams, $location, $rootScope) { $rootScope.$on('$routeChangeSuccess', routeChangeSpy); $location.path('/bar/1/2/3'); $location.search({initial: 'true'}); $rootScope.$digest(); routeChangeSpy.calls.reset(); $route.updateParams({barId: '5', fooId: '6', eggId: '4'}); $rootScope.$digest(); expect($routeParams).toEqual({barId: '5', fooId: '6', spamId: '3', eggId: '4', initial: 'true'}); expect(routeChangeSpy).toHaveBeenCalledOnce(); expect($location.path()).toEqual('/bar/5/6/3/4'); expect($location.search()).toEqual({initial: 'true'}); }); }); it('should complain if called without an existing route', inject(function($route) { expect(function() { $route.updateParams(); }).toThrowMinErr('ngRoute', 'norout'); })); }); describe('testability', function() { it('should wait for $resolve promises before calling callbacks', function() { var deferred; module(function($provide, $routeProvider) { $routeProvider.when('/path', { template: '', resolve: { a: function($q) { deferred = $q.defer(); return deferred.promise; } } }); }); inject(function($location, $route, $rootScope, $httpBackend, $$testability) { $location.path('/path'); $rootScope.$digest(); var callback = jasmine.createSpy('callback'); $$testability.whenStable(callback); expect(callback).not.toHaveBeenCalled(); deferred.resolve(); $rootScope.$digest(); expect(callback).toHaveBeenCalled(); }); }); it('should call callback after $resolve promises are rejected', function() { var deferred; module(function($provide, $routeProvider) { $routeProvider.when('/path', { template: '', resolve: { a: function($q) { deferred = $q.defer(); return deferred.promise; } } }); }); inject(function($location, $route, $rootScope, $httpBackend, $$testability) { $location.path('/path'); $rootScope.$digest(); var callback = jasmine.createSpy('callback'); $$testability.whenStable(callback); expect(callback).not.toHaveBeenCalled(); deferred.reject(); $rootScope.$digest(); expect(callback).toHaveBeenCalled(); }); }); it('should wait for resolveRedirectTo promises before calling callbacks', function() { var deferred; module(function($provide, $routeProvider) { $routeProvider.when('/path', { resolveRedirectTo: function($q) { deferred = $q.defer(); return deferred.promise; } }); }); inject(function($location, $route, $rootScope, $httpBackend, $$testability) { $location.path('/path'); $rootScope.$digest(); var callback = jasmine.createSpy('callback'); $$testability.whenStable(callback); expect(callback).not.toHaveBeenCalled(); deferred.resolve(); $rootScope.$digest(); expect(callback).toHaveBeenCalled(); }); }); it('should call callback after resolveRedirectTo promises are rejected', function() { var deferred; module(function($provide, $routeProvider) { $routeProvider.when('/path', { resolveRedirectTo: function($q) { deferred = $q.defer(); return deferred.promise; } }); }); inject(function($location, $route, $rootScope, $httpBackend, $$testability) { $location.path('/path'); $rootScope.$digest(); var callback = jasmine.createSpy('callback'); $$testability.whenStable(callback); expect(callback).not.toHaveBeenCalled(); deferred.reject(); $rootScope.$digest(); expect(callback).toHaveBeenCalled(); }); }); it('should wait for all route promises before calling callbacks', function() { var deferreds = {}; module(function($provide, $routeProvider) { // While normally `$browser.defer()` modifies the `outstandingRequestCount`, the mocked // version (provided by `ngMock`) does not. This doesn't matter in most tests, but in this // case we need the `outstandingRequestCount` logic to ensure that we don't call the // `$$testability.whenStable()` callbacks part way through a `$rootScope.$evalAsync` block. // See ngRoute's commitRoute()'s finally() block for details. $provide.decorator('$browser', function($delegate) { var oldDefer = $delegate.defer; var newDefer = function(fn, delay) { var requestCountAwareFn = function() { $delegate.$$completeOutstandingRequest(fn); }; $delegate.$$incOutstandingRequestCount(); return oldDefer.call($delegate, requestCountAwareFn, delay); }; $delegate.defer = angular.extend(newDefer, oldDefer); return $delegate; }); addRouteWithAsyncRedirect('/foo', '/bar'); addRouteWithAsyncRedirect('/bar', '/baz'); addRouteWithAsyncRedirect('/baz', '/qux'); $routeProvider.when('/qux', { template: '', resolve: { a: function($q) { var deferred = deferreds['/qux'] = $q.defer(); return deferred.promise; } } }); // Helpers function addRouteWithAsyncRedirect(fromPath, toPath) { $routeProvider.when(fromPath, { resolveRedirectTo: function($q) { var deferred = deferreds[fromPath] = $q.defer(); return deferred.promise.then(function() { return toPath; }); } }); } }); inject(function($browser, $location, $rootScope, $route, $$testability) { $location.path('/foo'); $rootScope.$digest(); var callback = jasmine.createSpy('callback'); $$testability.whenStable(callback); expect(callback).not.toHaveBeenCalled(); deferreds['/foo'].resolve(); $browser.defer.flush(); expect(callback).not.toHaveBeenCalled(); deferreds['/bar'].resolve(); $browser.defer.flush(); expect(callback).not.toHaveBeenCalled(); deferreds['/baz'].resolve(); $browser.defer.flush(); expect(callback).not.toHaveBeenCalled(); deferreds['/qux'].resolve(); $browser.defer.flush(); expect(callback).toHaveBeenCalled(); }); }); }); });
import { usingEvalSync, usingEval } from '../lib/utils' export async function getServerSideProps() { return { props: await usingEval(), } } export default function Page(props) { return ( <div> {props.value} and {usingEvalSync().value} </div> ) }
var assert = require('assert'); var common = require('../../common'); var cluster = common.createPoolCluster({canRetry: false}); var server = common.createFakeServer(); var connCount = 0; var poolConfig = common.getTestConfig({port: common.fakeServerPort}); cluster.add('MASTER', poolConfig); server.listen(common.fakeServerPort, function(err) { assert.ifError(err); cluster.getConnection('MASTER', function (err) { assert.ok(err); assert.equal(err.code, 'ER_ACCESS_DENIED_ERROR'); assert.equal(err.fatal, true); assert.equal(connCount, 1); cluster.end(function (err) { assert.ifError(err); server.destroy(); }); }); }); server.on('connection', function (conn) { connCount += 1; conn.deny(); });
// @flow export { default as CircularProgress } from './CircularProgress'; export { default as LinearProgress } from './LinearProgress';
JSMpeg.Decoder.Base = (function(){ "use strict"; var BaseDecoder = function(options) { this.destination = null; this.canPlay = false; this.collectTimestamps = !options.streaming; this.timestamps = []; this.timestampIndex = 0; this.startTime = 0; this.decodedTime = 0; Object.defineProperty(this, 'currentTime', {get: this.getCurrentTime}); }; BaseDecoder.prototype.connect = function(destination) { this.destination = destination; }; BaseDecoder.prototype.write = function(pts, buffers) { if (this.collectTimestamps) { if (this.timestamps.length === 0) { this.startTime = pts; this.decodedTime = pts; } this.timestamps.push({index: this.bits.byteLength << 3, time: pts}); } this.bits.write(buffers); this.canPlay = true; }; BaseDecoder.prototype.seek = function(time) { if (!this.collectTimestamps) { return; } this.timestampIndex = 0; for (var i = 0; i < this.timestamps.length; i++) { if (this.timestamps[i].time > time) { break; } this.timestampIndex = i; } var ts = this.timestamps[this.timestampIndex]; if (ts) { this.bits.index = ts.index; this.decodedTime = ts.time; } else { this.bits.index = 0; this.decodedTime = this.startTime; } }; BaseDecoder.prototype.decode = function() { this.advanceDecodedTime(0); }; BaseDecoder.prototype.advanceDecodedTime = function(seconds) { if (this.collectTimestamps) { var newTimestampIndex = -1; for (var i = this.timestampIndex; i < this.timestamps.length; i++) { if (this.timestamps[i].index > this.bits.index) { break; } newTimestampIndex = i; } // Did we find a new PTS, different from the last? If so, we don't have // to advance the decoded time manually and can instead sync it exactly // to the PTS. if ( newTimestampIndex !== -1 && newTimestampIndex !== this.timestampIndex ) { this.timestampIndex = newTimestampIndex; this.decodedTime = this.timestamps[this.timestampIndex].time; return; } } this.decodedTime += seconds; }; BaseDecoder.prototype.getCurrentTime = function() { return this.decodedTime; }; return BaseDecoder; })();
'use strict'; /** * @ngdoc function * @name inflightHubApp.controller:MainCtrl * @description * # MainCtrl * Controller of the inflightHubApp */ angular.module('inflightHubApp') .controller('MainCtrl', function () { this.awesomeThings = [ 'HTML5 Boilerplate', 'AngularJS', 'Karma' ]; });
version https://git-lfs.github.com/spec/v1 oid sha256:c4fdd080b70bb03e8f649ff90f86d76a3604a3589ce2f201730c4441edb66ec1 size 8234
'use strict'; /** * Mounts a folder in a connect server */ module.exports = function mountFolder(connect, dir) { return connect.static(require('path').resolve(dir)); };
$(function () { var form = $('#search'); var input = form.find('input'); var list = form.find('.results'); var items = list.find('a'); var selected = null; // Don't submit on return. form.on('submit', function () { return false; }); // Open search input.on('focus', function () { form.addClass('open'); }); // Close search. $(window).click(function () { form.removeClass('open'); }); form.click(function (e) { e.stopPropagation(); }); // Handle simple searching input.on('keydown', function (e) { /** * Capture the down arrow. */ if (e.which == 40) { if (selected) { /** * If we have a selection then * push to the next visible option. */ if (selected.nextAll('a:visible').length) { items.removeClass('active'); selected = selected.nextAll('a:visible').first(); selected.addClass('active'); } } else { /** * Otherwise select the first * visible option in the list. */ selected = items.filter('a:visible').first(); selected.addClass('active'); } } /** * Capture the up arrow. */ if (e.which == 38) { if (selected) { /** * If we have a selection then push * to the previous visible option. */ if (selected.prevAll('a:visible').length) { items.removeClass('active'); selected = selected.prevAll('a:visible').first(); selected.addClass('active'); } } else { /** * Otherwise select the last * visible option in the list. */ selected = items.filter('a:visible').last(); selected.addClass('active'); } } /** * Capture the enter key. */ if (e.which == 13) { if (selected) { /** * If the key press was the return * key and we have a selection * then follow the link. */ if (selected.hasClass('has-click-event') || selected.hasClass('ajax')) { selected.trigger('click'); } else { /** * If nothing is selected * there's nothing to do. */ if (!selected.length) { return false; } /** * If control or the meta key is * being held open a new window. */ if (e.ctrlKey || e.metaKey) { window.open(selected.attr('href'), "_blank"); } else { window.location = selected.attr('href'); } input.val(''); input.blur(); form.removeClass('open'); modal.find('.modal-content').append('<div class="modal-loading"><div class="active large loader"></div></div>'); } } } /** * Capture up and down arrows. */ if (e.which == 38 || e.which == 40) { // store current positions in variables var start = input[0].selectionStart, end = input[0].selectionEnd; // restore from variables... input[0].setSelectionRange(start, end); e.preventDefault(); } /** * Capture the escape key. */ if (e.which == 27) { form.removeClass('open'); items .show() .removeClass('active'); input.val('').blur(); } }); input.on('keyup', function (e) { /** * If the keyup was a an arrow * up or down then skip this step. */ if (e.which == 38 || e.which == 40) { return; } var value = $(this).val(); /** * Filter the list by the items to * show only those containing value. */ items.each(function () { if ($(this).text().toLowerCase().indexOf(value.toLowerCase()) >= 0) { $(this).show(); } else { $(this).hide(); } }); /** * If we don't have a selected item * then choose the first visible option. */ if (!selected || !selected.is(':visible')) { selected = items.filter(':visible').first(); selected.addClass('active'); } }); });
var global = require('../internals/global'); var getOwnPropertyDescriptor = require('../internals/object-get-own-property-descriptor').f; var createNonEnumerableProperty = require('../internals/create-non-enumerable-property'); var redefine = require('../internals/redefine'); var setGlobal = require('../internals/set-global'); var copyConstructorProperties = require('../internals/copy-constructor-properties'); var isForced = require('../internals/is-forced'); /* options.target - name of the target object options.global - target is the global object options.stat - export as static methods of target options.proto - export as prototype methods of target options.real - real prototype method for the `pure` version options.forced - export even if the native feature is available options.bind - bind methods to the target, required for the `pure` version options.wrap - wrap constructors to preventing global pollution, required for the `pure` version options.unsafe - use the simple assignment of property instead of delete + defineProperty options.sham - add a flag to not completely full polyfills options.enumerable - export as enumerable property options.noTargetGet - prevent calling a getter on target options.name - the .name of the function if it does not match the key */ module.exports = function (options, source) { var TARGET = options.target; var GLOBAL = options.global; var STATIC = options.stat; var FORCED, target, key, targetProperty, sourceProperty, descriptor; if (GLOBAL) { target = global; } else if (STATIC) { target = global[TARGET] || setGlobal(TARGET, {}); } else { target = (global[TARGET] || {}).prototype; } if (target) for (key in source) { sourceProperty = source[key]; if (options.noTargetGet) { descriptor = getOwnPropertyDescriptor(target, key); targetProperty = descriptor && descriptor.value; } else targetProperty = target[key]; FORCED = isForced(GLOBAL ? key : TARGET + (STATIC ? '.' : '#') + key, options.forced); // contained in target if (!FORCED && targetProperty !== undefined) { if (typeof sourceProperty == typeof targetProperty) continue; copyConstructorProperties(sourceProperty, targetProperty); } // add a flag to not completely full polyfills if (options.sham || (targetProperty && targetProperty.sham)) { createNonEnumerableProperty(sourceProperty, 'sham', true); } // extend global redefine(target, key, sourceProperty, options); } };
// word frequencies of first two chapters of Oliver Twist var words = [ {text: 'have', size: 102}, {text: 'Oliver', size: 47}, {text: 'say', size: 46}, {text: 'said', size: 36}, {text: 'bumble', size: 29, href: 'https://en.wikipedia.org/wiki/Beadle'}, {text: 'will', size: 29}, {text: 'Mrs', size: 56, href: 'https://en.wikipedia.org/wiki/Mrs.'}, {text: 'Mann', size: 27, href: 'http://educationcing.blogspot.nl/2012/06/oliver-twist-mrs-manns-character.html'}, {text: 'Mr', size: 27}, {text: 'very', size: 26}, {text: 'child', size: 20}, {text: 'all', size: 19}, {text: 'boy', size: 19}, {text: 'gentleman', size: 19, href: 'http://www.thefreelibrary.com/The+gentleman+in+the+white+waistcoat%3a+Dickens+and+metonymy.-a0154239625'}, {text: 'great', size: 19}, {text: 'take', size: 19}, {text: 'but', size: 18}, {text: 'beadle', size: 16}, {text: 'twist', size: 16}, {text: 'board', size: 15}, {text: 'more', size: 15}, {text: 'one', size: 15}, {text: 'workhouse', size: 15}, {text: 'parish', size: 14}, {text: 'there', size: 14}, {text: 'come', size: 13}, {text: 'hand', size: 13}, {text: 'know', size: 13}, {text: 'sir', size: 13}, {text: 'being', size: 12}, {text: 'head', size: 12}, {text: 'make', size: 12}, {text: 'out', size: 12}, {text: 'can', size: 11}, {text: 'little', size: 11}, {text: 'reply', size: 11}, {text: 'any', size: 10}, {text: 'cry', size: 10}, {text: 'good', size: 10}, {text: 'name', size: 10}, {text: 'poor', size: 10}, {text: 'time', size: 10}, {text: 'two', size: 10}, {text: 'after', size: 9}, {text: 'dear', size: 9}, {text: 'get', size: 9}, {text: 'gruel', size: 9}, {text: 'long', size: 9}, {text: 'may', size: 9}, {text: 'never', size: 9}, {text: 'some', size: 9}, {text: 'well', size: 9}, {text: 'white', size: 9}, {text: 'woman', size: 9}, {text: 'chair', size: 8}, {text: 'day', size: 8}, {text: 'give', size: 8}, {text: 'inquire', size: 8}, {text: 'made', size: 8}, {text: 'next', size: 8}, {text: 'now', size: 8}, {text: 'other', size: 8}, {text: 'over', size: 8}, {text: 'small', size: 8}, {text: 'surgeon', size: 8}, {text: 'think', size: 8}, {text: 'too', size: 8}, {text: 'walk', size: 8}, {text: 'want', size: 8}, {text: 'bless', size: 7}, {text: 'eye', size: 7}, {text: 'man', size: 7}, {text: 'master', size: 7}, {text: 'most', size: 7}, {text: 'old', size: 7}, {text: 'people', size: 7}, {text: 'see', size: 7}, {text: 'another', size: 6}, {text: 'at all', size: 6}, {text: 'authorities', size: 6}, {text: 'authority', size: 6}, {text: 'away', size: 6}, {text: 'face', size: 6}, {text: 'gate', size: 6}, {text: 'half', size: 6}, {text: 'hands', size: 6}, {text: 'heart', size: 6}, {text: 'last', size: 6}, {text: 'might', size: 6}, {text: 'nurse', size: 6}, {text: 'once', size: 6}, {text: 'place', size: 6}, {text: 'room', size: 6}, {text: 'table', size: 6}, {text: 'three', size: 6}, {text: 'voice', size: 6}, {text: 'waistcoat', size: 6}, {text: 'wash', size: 6}, {text: 'water', size: 6}, {text: 'a little', size: 5}, {text: 'bow', size: 5}, {text: 'business', size: 5}, {text: 'drop', size: 5}, {text: 'eyes', size: 5}, {text: 'fall', size: 5}, {text: 'find', size: 5}, {text: 'gin', size: 5}, {text: 'high', size: 5}, {text: 'house', size: 5}, {text: 'infant', size: 5}, {text: 'night', size: 5}, {text: 'nobody', size: 5}, {text: 'orphan', size: 5}, {text: 'pauper', size: 5}, {text: 'perhaps', size: 5}, {text: 'rather', size: 5}, {text: 'round', size: 5}, {text: 'sit', size: 5}, {text: 'world', size: 5}, {text: 'young', size: 5}, {text: 'add', size: 4}, {text: 'ask', size: 4}, {text: 'at once', size: 4}, {text: 'behind', size: 4}, {text: 'bottle', size: 4}, {text: 'bread', size: 4}, {text: 'care', size: 4}, {text: 'copper', size: 4}, {text: 'die', size: 4}, {text: 'farm', size: 4}, {text: 'fat', size: 4}, {text: 'father', size: 4}, {text: 'fell', size: 4}, {text: 'female', size: 4}, {text: 'going', size: 4}, {text: 'happen', size: 4}, {text: 'hat', size: 4}, {text: 'here', size: 4}, {text: 'however', size: 4}, {text: 'hungry', size: 4}, {text: 'in this', size: 4}, {text: 'keep', size: 4}, {text: 'large', size: 4}, {text: 'low', size: 4}, {text: 'matter', size: 4}, {text: 'out of', size: 4}, {text: 'pound', size: 4}, {text: 'public', size: 4}, {text: 'quarter', size: 4}, {text: 'quite', size: 4}, {text: 'raise', size: 4}, {text: 'sleep', size: 4}, {text: 'spirit', size: 4}, {text: 'ten', size: 4}, {text: 'turn', size: 4}, {text: 'wanted', size: 4}, {text: 'washing', size: 4}, {text: 'week', size: 4}, {text: 'word', size: 4}, {text: 'age', size: 3}, {text: 'arm', size: 3}, {text: 'ask for', size: 3}, {text: 'assistant', size: 3}, {text: 'be born', size: 3}, {text: 'bed', size: 3}, {text: 'bill', size: 3}, {text: 'body', size: 3}, {text: 'born', size: 3}, {text: 'brick', size: 3}, {text: 'bring', size: 3}, {text: 'cane', size: 3}, {text: 'case', size: 3}, {text: 'Christian', size: 3}, {text: 'circumstance', size: 3}, {text: 'cock', size: 3}, {text: 'cocked hat', size: 3}, {text: 'cold', size: 3}, {text: 'come to', size: 3}, {text: 'companion', size: 3}, {text: 'consequence', size: 3}, {text: 'corner', size: 3}, {text: 'deposit', size: 3}, {text: 'dress', size: 3}, {text: 'eat', size: 3}, {text: 'eight', size: 3}, {text: 'expect', size: 3}, {text: 'expected', size: 3}, {text: 'experimental', size: 3}, {text: 'feed', size: 3}, {text: 'fire', size: 3}, {text: 'glass', size: 3}, {text: 'go to', size: 3}, {text: 'green', size: 3}, {text: 'halfpenny', size: 3}, {text: 'hang', size: 3}, {text: 'have got', size: 3}, {text: 'hint', size: 3}, {text: 'hunger', size: 3}, {text: 'interest', size: 3}, {text: 'known', size: 3}, {text: 'latter', size: 3}, {text: 'lay', size: 3}, {text: 'lead', size: 3}, {text: 'let', size: 3}, {text: 'live', size: 3}, {text: 'mention', size: 3}, {text: 'month', size: 3}, {text: 'morning', size: 3}, {text: 'ninth', size: 3}, {text: 'offer', size: 3}, {text: 'old woman', size: 3}, {text: 'open', size: 3}, {text: 'operation', size: 3}, {text: 'order', size: 3}, {text: 'pale', size: 3}, {text: 'pick', size: 3}, {text: 'possess', size: 3}, {text: 'possible', size: 3}, {text: 'pray', size: 3}, {text: 'process', size: 3}, {text: 'proper', size: 3}, {text: 'purpose', size: 3}, {text: 'raised', size: 3}, {text: 'remove', size: 3}, {text: 'removed', size: 3}, {text: 'render', size: 3}, {text: 'set', size: 3}, {text: 'shake', size: 3}, {text: 'sitting', size: 3}, {text: 'smile', size: 3}, {text: 'somewhat', size: 3}, {text: 'speak', size: 3}, {text: 'spoon', size: 3}, {text: 'supper', size: 3}, {text: 'sure', size: 3}, {text: 'system', size: 3}, {text: 'tender', size: 3}, {text: 'thin', size: 3}, {text: 'troublesome', size: 3}, {text: 'twenty', size: 3}, {text: 'usually', size: 3}, {text: 'words', size: 3}, {text: 'yes', size: 3}, {text: 'a great deal', size: 2}, {text: 'accident', size: 2}, {text: 'accompanied', size: 2}, {text: 'accompany', size: 2}, {text: 'advance', size: 2}, {text: 'advancing', size: 2}, {text: 'allowance', size: 2}, {text: 'answer', size: 2}, {text: 'appear', size: 2}, {text: 'apron', size: 2}, {text: 'arrive', size: 2}, {text: 'assign', size: 2}, {text: 'astonishment', size: 2}, {text: 'at last', size: 2}, {text: 'attend', size: 2}, {text: 'basin', size: 2}, {text: 'bedstead', size: 2}, {text: 'besides', size: 2}, {text: 'birth', size: 2}, {text: 'birthday', size: 2}, {text: 'bowed', size: 2}, {text: 'bowl', size: 2}, {text: 'bowls', size: 2}, {text: 'breast', size: 2}, {text: 'brief', size: 2}, {text: 'bring up', size: 2}, {text: 'cast', size: 2}, {text: 'catch', size: 2}, {text: 'class', size: 2}, {text: 'clothe', size: 2}, {text: 'common', size: 2}, {text: 'compel', size: 2}, {text: 'compose', size: 2}, {text: 'conduct', size: 2}, {text: 'considerable', size: 2}, {text: 'consolation', size: 2}, {text: 'contract', size: 2}, {text: 'convince', size: 2}, {text: 'convinced', size: 2}, {text: 'cook', size: 2}, {text: 'countenance', size: 2}, {text: 'couple', size: 2}, {text: 'cry for', size: 2}, {text: 'crying', size: 2}, {text: 'cuff', size: 2}, {text: 'deal', size: 2}, {text: 'decidedly', size: 2}, {text: 'deeply', size: 2}, {text: 'diet', size: 2}, {text: 'difficulty', size: 2}, {text: 'dinner', size: 2}, {text: 'directly', size: 2}, {text: 'discover', size: 2}, {text: 'draw', size: 2}, {text: 'ecstasy', size: 2}, {text: 'elderly', size: 2}, {text: 'evening', size: 2}, {text: 'excellent', size: 2}, {text: 'except', size: 2}, {text: 'experience', size: 2}, {text: 'extraordinary', size: 2}, {text: 'faint', size: 2}, {text: 'fall into', size: 2}, {text: 'fist', size: 2}, {text: 'floor', size: 2}, {text: 'follow', size: 2}, {text: 'food', size: 2}, {text: 'fool', size: 2}, {text: 'forehead', size: 2}, {text: 'frighten', size: 2}, {text: 'frightened', size: 2}, {text: 'garden', size: 2}, {text: 'gaze', size: 2}, {text: 'glance', size: 2}, {text: 'go along', size: 2}, {text: 'grasp', size: 2}, {text: 'grasping', size: 2}, {text: 'great deal', size: 2}, {text: 'hope', size: 2}, {text: 'horse', size: 2}, {text: 'humane', size: 2}, {text: 'humility', size: 2}, {text: 'impress', size: 2}, {text: 'impressed', size: 2}, {text: 'in no time', size: 2}, {text: 'in other words', size: 2}, {text: 'increase', size: 2}, {text: 'inmate', size: 2}, {text: 'inside', size: 2}, {text: 'instead', size: 2}, {text: 'interesting', size: 2}, {text: 'interpose', size: 2}, {text: 'ladle', size: 2}, {text: 'lady', size: 2}, {text: 'leaving', size: 2}, {text: 'loud', size: 2}, {text: 'mile', size: 2}, {text: 'misery', size: 2}, {text: 'nearly', size: 2}, {text: 'necessary', size: 2}, {text: 'notwithstanding', size: 2}, {text: 'oakum', size: 2}, {text: 'on the table', size: 2}, {text: 'opened', size: 2}, {text: 'overseer', size: 2}, {text: 'philosopher', size: 2}, {text: 'picking', size: 2}, {text: 'piece', size: 2}, {text: 'pillow', size: 2}, {text: 'please', size: 2}, {text: 'pocket', size: 2}, {text: 'poor people', size: 2}, {text: 'possessed', size: 2}, {text: 'probable', size: 2}, {text: 'proceed', size: 2}, {text: 'produce', size: 2}, {text: 'provide', size: 2}, {text: 'putt', size: 2}, {text: 'putting', size: 2}, {text: 'red', size: 2}, {text: 'relief', size: 2}, {text: 'remain', size: 2}, {text: 'repeat', size: 2}, {text: 'result', size: 2}, {text: 'reward', size: 2}, {text: 'roll', size: 2}, {text: 'rose', size: 2}, {text: 'seat', size: 2}, {text: 'sense', size: 2}, {text: 'shaking', size: 2}, {text: 'sight', size: 2}, {text: 'situation', size: 2}, {text: 'six', size: 2, href: 'https://en.wikipedia.org/wiki/Six'}, {text: 'slice', size: 2}, {text: 'society', size: 2}, {text: 'spoke', size: 2}, {text: 'start', size: 2}, {text: 'starve', size: 2}, {text: 'starved', size: 2}, {text: 'station', size: 2}, {text: 'stop', size: 2}, {text: 'stranger', size: 2}, {text: 'suffer', size: 2}, {text: 'supply', size: 2}, {text: 'support', size: 2}, {text: 'suppose', size: 2}, {text: 'take care', size: 2}, {text: 'taking', size: 2}, {text: 'talk', size: 2}, {text: 'tap', size: 2}, {text: 'teach', size: 2}, {text: 'tear', size: 2}, {text: 'tears', size: 2}, {text: 'telling', size: 2}, {text: 'to that', size: 2}, {text: 'tone', size: 2}, {text: 'too much', size: 2}, {text: 'town', size: 2}, {text: 'trade', size: 2}, {text: 'treat', size: 2}, {text: 'trouble', size: 2}, {text: 'useful', size: 2}, {text: 'usher', size: 2}, {text: 'view', size: 2}, {text: 'walk in', size: 2}, {text: 'warden', size: 2}, {text: 'wicket', size: 2}, {text: 'wild', size: 2}, {text: 'wisdom', size: 2}, {text: 'wretched', size: 2}, {text: 'young woman', size: 2}, {text: 'a couple of', size: 1}, {text: 'accurate', size: 1}, {text: 'address', size: 1}, {text: 'advertise', size: 1}, {text: 'affect', size: 1}, {text: 'affected', size: 1}, {text: 'affix', size: 1}, {text: 'agony', size: 1}, {text: 'aim', size: 1}, {text: 'alarm', size: 1}, {text: 'alarmed', size: 1}, {text: 'alive', size: 1}, {text: 'all over', size: 1}, {text: 'all the way', size: 1}, {text: 'allot', size: 1}, {text: 'allotted', size: 1}, {text: 'aloud', size: 1}, {text: 'alphabet', size: 1}, {text: 'alphabetical', size: 1}, {text: 'alternately', size: 1}, {text: 'alternative', size: 1}, {text: 'anciently', size: 1}, {text: 'animate', size: 1}, {text: 'animated', size: 1}, {text: 'anxious', size: 1}, {text: 'apparently', size: 1}, {text: 'apparition', size: 1}, {text: 'appendage', size: 1}, {text: 'appetite', size: 1}, {text: 'applicant', size: 1}, {text: 'applied', size: 1}, {text: 'apply', size: 1}, {text: 'apprentice', size: 1}, {text: 'approach', size: 1}, {text: 'approaching', size: 1}, {text: 'appropriate', size: 1}, {text: 'approvingly', size: 1}, {text: 'arrive at', size: 1}, {text: 'articulate', size: 1}, {text: 'articulated', size: 1}, {text: 'as it is', size: 1}, {text: 'assiduously', size: 1}, {text: 'assigned', size: 1}, {text: 'assist', size: 1}, {text: 'assisted', size: 1}, {text: 'astound', size: 1}, {text: 'astounded', size: 1}, {text: 'at length', size: 1}, {text: 'atrociously', size: 1}, {text: 'attended', size: 1}, {text: 'attending', size: 1}, {text: 'attribute', size: 1}, {text: 'awaken', size: 1}, {text: 'bachelor', size: 1}, {text: 'badge', size: 1}, {text: 'bait', size: 1}, {text: 'balance', size: 1}, {text: 'baptize', size: 1}, {text: 'baptized', size: 1}, {text: 'Beadle', size: 1}, {text: 'beer', size: 1}, {text: 'befall', size: 1}, {text: 'beg', size: 1}, {text: 'beggar', size: 1}, {text: 'behold', size: 1}, {text: 'benevolent', size: 1}, {text: 'bestow', size: 1}, {text: 'bid', size: 1}, {text: 'bidding', size: 1}, {text: 'biography', size: 1}, {text: 'bitterly', size: 1}, {text: 'blandness', size: 1}, {text: 'blanket', size: 1}, {text: 'blessed', size: 1}, {text: 'blessing', size: 1}, {text: 'blow', size: 1}, {text: 'bolt', size: 1}, {text: 'bosom', size: 1}, {text: 'branch', size: 1}, {text: 'brat', size: 1}, {text: 'bread and butter', size: 1}, {text: 'breakfast', size: 1}, {text: 'breathe', size: 1}, {text: 'breathed', size: 1}, {text: 'brown', size: 1}, {text: 'brush', size: 1}, {text: 'brushed', size: 1}, {text: 'buffet', size: 1}, {text: 'buffeted', size: 1}, {text: 'build', size: 1}, {text: 'burden', size: 1}, {text: 'burst', size: 1}, {text: 'butter', size: 1}, {text: 'by hand', size: 1}, {text: 'by no means', size: 1}, {text: 'calico', size: 1}, {text: 'calling', size: 1}, {text: 'calm', size: 1}, {text: 'cap', size: 1}, {text: 'capital', size: 1}, {text: 'captivate', size: 1}, {text: 'captivating', size: 1}, {text: 'careful', size: 1}, {text: 'carelessly', size: 1}, {text: 'catch sight', size: 1}, {text: 'catch up', size: 1}, {text: 'catching', size: 1}, {text: 'cellar', size: 1}, {text: 'chafe', size: 1}, {text: 'chafed', size: 1}, {text: 'check', size: 1}, {text: 'checked', size: 1}, {text: 'cheerfulness', size: 1}, {text: 'childish', size: 1}, {text: 'choleric', size: 1}, {text: 'circumference', size: 1}, {text: 'clean', size: 1}, {text: 'clearly', size: 1}, {text: 'cling', size: 1}, {text: 'cloth', size: 1}, {text: 'clothes', size: 1}, {text: 'clothing', size: 1}, {text: 'coal', size: 1}, {text: 'coat', size: 1}, {text: 'cold water', size: 1}, {text: 'combination', size: 1}, {text: 'come on', size: 1}, {text: 'come out', size: 1}, {text: 'comfort', size: 1}, {text: 'comfortable', size: 1}, {text: 'Commons', size: 1}, {text: 'commons', size: 1}, {text: 'compelling', size: 1}, {text: 'complacently', size: 1}, {text: 'completed', size: 1}, {text: 'compliment', size: 1}, {text: 'composed', size: 1}, {text: 'composition', size: 1}, {text: 'comprise', size: 1}, {text: 'concise', size: 1}, {text: 'conclave', size: 1}, {text: 'confinement', size: 1}, {text: 'consideration', size: 1}, {text: 'consign', size: 1}, {text: 'consolatory', size: 1}, {text: 'contents', size: 1}, {text: 'contracted', size: 1}, {text: 'contrive', size: 1}, {text: 'contrived', size: 1}, {text: 'controvert', size: 1}, {text: 'cork', size: 1}, {text: 'corn', size: 1}, {text: 'cottage', size: 1}, {text: 'cough', size: 1}, {text: 'coupled', size: 1}, {text: 'cover', size: 1}, {text: 'covering', size: 1}, {text: 'coverlet', size: 1}, {text: 'crop', size: 1}, {text: 'culprit', size: 1}, {text: 'cupboard', size: 1}, {text: 'curtsey', size: 1}, {text: 'custom', size: 1}, {text: 'darkly', size: 1}, {text: 'date', size: 1}, {text: 'deceive', size: 1}, {text: 'deception', size: 1}, {text: 'decision', size: 1}, {text: 'define', size: 1}, {text: 'defined', size: 1}, {text: 'delegate', size: 1}, {text: 'deliberation', size: 1}, {text: 'deliver', size: 1}, {text: 'demolition', size: 1}, {text: 'demonstrate', size: 1}, {text: 'demonstrated', size: 1}, {text: 'depict', size: 1}, {text: 'depicted', size: 1}, {text: 'depth', size: 1}, {text: 'desperate', size: 1}, {text: 'despise', size: 1}, {text: 'despised', size: 1}, {text: 'destitute', size: 1}, {text: 'determine', size: 1}, {text: 'devotional', size: 1}, {text: 'devour', size: 1}, {text: 'dietary', size: 1}, {text: 'dignified', size: 1}, {text: 'dignify', size: 1}, {text: 'dignity', size: 1}, {text: 'diminutive', size: 1}, {text: 'dirt', size: 1}, {text: 'disappear', size: 1}, {text: 'discussion', size: 1}, {text: 'dispatch', size: 1}, {text: 'display', size: 1}, {text: 'dispose', size: 1}, {text: 'disposed', size: 1}, {text: 'distinctly', size: 1}, {text: 'divide', size: 1}, {text: 'divided', size: 1}, {text: 'divorce', size: 1}, {text: 'doctor', size: 1}, {text: 'Doctor', size: 1}, {text: 'domicile', size: 1}, {text: 'dressed', size: 1}, {text: 'drudge', size: 1}, {text: 'duly', size: 1}, {text: 'dying', size: 1}, {text: 'eager', size: 1}, {text: 'ease', size: 1}, {text: 'eating', size: 1}, {text: 'educate', size: 1}, {text: 'educated', size: 1}, {text: 'education', size: 1}, {text: 'emanate', size: 1}, {text: 'embrace', size: 1}, {text: 'employ', size: 1}, {text: 'encrust', size: 1}, {text: 'encrusted', size: 1}, {text: 'engender', size: 1}, {text: 'entertainment', size: 1}, {text: 'envelop', size: 1}, {text: 'enviable', size: 1}, {text: 'establish', size: 1}, {text: 'established', size: 1}, {text: 'establishment', size: 1}, {text: 'evaporate', size: 1}, {text: 'evaporated', size: 1}, {text: 'event', size: 1}, {text: 'every night', size: 1}, {text: 'every quarter', size: 1}, {text: 'evident', size: 1}, {text: 'evidently', size: 1}, {text: 'excitement', size: 1}, {text: 'exercise', size: 1}, {text: 'exertion', size: 1}, {text: 'exist', size: 1}, {text: 'expand', size: 1}, {text: 'expense', size: 1}, {text: 'expensive', size: 1}, {text: 'experienced', size: 1}, {text: 'extant', size: 1}, {text: 'faced', size: 1}, {text: 'factor', size: 1}, {text: 'fail', size: 1}, {text: 'faithful', size: 1}, {text: 'fall back', size: 1}, {text: 'fall out', size: 1}, {text: 'farming', size: 1}, {text: 'favour', size: 1}, {text: 'feebly', size: 1}, {text: 'feint', size: 1}, {text: 'festive', size: 1}, {text: 'fetch', size: 1}, {text: 'fictitious', size: 1}, {text: 'fictitious name', size: 1}, {text: 'find out', size: 1}, {text: 'finding', size: 1}, {text: 'finger', size: 1}, {text: 'finish', size: 1}, {text: 'firmly', size: 1}, {text: 'fling', size: 1}, {text: 'flock', size: 1}, {text: 'flutter', size: 1}, {text: 'folk', size: 1}, {text: 'folks', size: 1}, {text: 'fond', size: 1}, {text: 'fondling', size: 1}, {text: 'for the first time', size: 1}, {text: 'forever', size: 1}, {text: 'forgotten', size: 1}, {text: 'forthwith', size: 1}, {text: 'fortunate', size: 1}, {text: 'fortunately', size: 1}, {text: 'furious', size: 1}, {text: 'gasp', size: 1}, {text: 'gather', size: 1}, {text: 'gathered', size: 1}, {text: 'generation', size: 1}, {text: 'gesture', size: 1}, {text: 'get behind', size: 1}, {text: 'get to', size: 1}, {text: 'gloom', size: 1}, {text: 'glove', size: 1}, {text: 'go away', size: 1}, {text: 'go to sleep', size: 1}, {text: 'go with', size: 1}, {text: 'going away', size: 1}, {text: 'good-looking', size: 1}, {text: 'goodness', size: 1}, {text: 'grace', size: 1}, {text: 'gracious', size: 1}, {text: 'gradual', size: 1}, {text: 'grandmother', size: 1}, {text: 'gratified', size: 1}, {text: 'gratify', size: 1}, {text: 'grief', size: 1}, {text: 'grown', size: 1}, {text: 'gruff', size: 1}, {text: 'hall', size: 1}, {text: 'hand over', size: 1}, {text: 'handed', size: 1}, {text: 'hastily', size: 1}, {text: 'haughty', size: 1}, {text: 'headed', size: 1}, {text: 'healthy', size: 1}, {text: 'hesitate', size: 1}, {text: 'hesitating', size: 1}, {text: 'hitherto', size: 1}, {text: 'horror', size: 1}, {text: 'human being', size: 1}, {text: 'humanely', size: 1}, {text: 'humble', size: 1}, {text: 'hurried', size: 1}, {text: 'hurry', size: 1}, {text: 'hush', size: 1}, {text: 'ill-usage', size: 1}, {text: 'illustration', size: 1}, {text: 'impart', size: 1}, {text: 'imperfectly', size: 1}, {text: 'impertinence', size: 1}, {text: 'implant', size: 1}, {text: 'implanted', size: 1}, {text: 'implicitly', size: 1}, {text: 'importance', size: 1}, {text: 'impose', size: 1}, {text: 'imposed', size: 1}, {text: 'imprint', size: 1}, {text: 'in full', size: 1}, {text: 'in hand', size: 1}, {text: 'inadvertently', size: 1}, {text: 'inconvenience', size: 1}, {text: 'increased', size: 1}, {text: 'indubitably', size: 1}, {text: 'induce', size: 1}, {text: 'inducing', size: 1}, {text: 'inestimable', size: 1}, {text: 'inevitably', size: 1}, {text: 'inflame', size: 1}, {text: 'inflaming', size: 1}, {text: 'inform', size: 1}, {text: 'informed', size: 1}, {text: 'inheritance', size: 1}, {text: 'inquest', size: 1}, {text: 'inquiring', size: 1}, {text: 'inseparable', size: 1}, {text: 'instant', size: 1}, {text: 'intelligence', size: 1}, {text: 'interrogation', size: 1}, {text: 'invariably', size: 1}, {text: 'invitation', size: 1}, {text: 'issue', size: 1}, {text: 'item', size: 1}, {text: 'jury', size: 1}, {text: 'juvenile', size: 1}, {text: 'keeping', size: 1}, {text: 'kick', size: 1}, {text: 'kill', size: 1}, {text: 'kindly', size: 1}, {text: 'kindness', size: 1}, {text: 'kindred', size: 1}, {text: 'knock', size: 1}, {text: 'knowing', size: 1}, {text: 'lace', size: 1}, {text: 'laced', size: 1}, {text: 'lady of the house', size: 1}, {text: 'lamb', size: 1}, {text: 'large white', size: 1}, {text: 'lean', size: 1}, {text: 'leave behind', size: 1}, {text: 'left hand', size: 1}, {text: 'leg', size: 1}, {text: 'lie', size: 1}, {text: 'lie in', size: 1}, {text: 'lighted', size: 1}, {text: 'liked', size: 1}, {text: 'linger', size: 1}, {text: 'lingering', size: 1}, {text: 'lip', size: 1}, {text: 'listen', size: 1}, {text: 'literary', size: 1}, {text: 'literature', size: 1}, {text: 'lively', size: 1}, {text: 'lock', size: 1}, {text: 'lock up', size: 1}, {text: 'loneliness', size: 1}, {text: 'long time', size: 1}, {text: 'long-headed', size: 1}, {text: 'loosely', size: 1}, {text: 'lots', size: 1}, {text: 'lowest', size: 1}, {text: 'lump', size: 1}, {text: 'lung', size: 1}, {text: 'lustily', size: 1}, {text: 'luxuriant', size: 1}, {text: 'magnanimously', size: 1}, {text: 'maintain', size: 1}, {text: 'majestic', size: 1}, {text: 'make it', size: 1}, {text: 'male', size: 1}, {text: 'mar', size: 1}, {text: 'marry', size: 1}, {text: 'marvellously', size: 1}, {text: 'material', size: 1}, {text: 'mattress', size: 1}, {text: 'meal', size: 1}, {text: 'mealtime', size: 1}, {text: 'meanwhile', size: 1}, {text: 'medical', size: 1}, {text: 'member', size: 1}, {text: 'memoir', size: 1}, {text: 'mercy', size: 1}, {text: 'merit', size: 1}, {text: 'miserable', size: 1}, {text: 'misty', size: 1}, {text: 'mix', size: 1}, {text: 'mixing', size: 1}, {text: 'mollify', size: 1}, {text: 'morrow', size: 1}, {text: 'mortality', size: 1}, {text: 'mortar', size: 1}, {text: 'narrative', size: 1}, {text: 'naturally', size: 1}, {text: 'neat', size: 1}, {text: 'necessity', size: 1}, {text: 'neglect', size: 1}, {text: 'neighbor', size: 1}, {text: 'nobleman', size: 1}, {text: 'noticed', size: 1}, {text: 'notion', size: 1}, {text: 'nourishment', size: 1}, {text: 'novel', size: 1}, {text: 'nudge', size: 1}, {text: "o'clock", size: 1}, {text: 'oatmeal', size: 1}, {text: 'oblige', size: 1}, {text: 'obliged', size: 1}, {text: 'observe', size: 1}, {text: 'occasionally', size: 1}, {text: 'occasions', size: 1}, {text: 'occur', size: 1}, {text: 'occurrence', size: 1}, {text: 'offend', size: 1}, {text: 'offended', size: 1}, {text: 'offender', size: 1}, {text: 'offering', size: 1}, {text: 'officiously', size: 1}, {text: 'once again', size: 1}, {text: 'onion', size: 1}, {text: 'oratorical', size: 1}, {text: 'originally', size: 1}, {text: 'ounce', size: 1}, {text: 'outer', size: 1}, {text: 'overload', size: 1}, {text: 'overlook', size: 1}, {text: 'overlooked', size: 1}, {text: 'page', size: 1}, {text: 'palm', size: 1}, {text: 'paralyse', size: 1}, {text: 'pardon', size: 1}, {text: 'parental', size: 1}, {text: 'parishioner', size: 1}, {text: 'parlour', size: 1}, {text: 'parochial', size: 1}, {text: 'participate', size: 1}, {text: 'participating', size: 1}, {text: 'passionately', size: 1}, {text: 'paste', size: 1}, {text: 'pasted', size: 1}, {text: 'patchwork', size: 1}, {text: 'patient', size: 1}, {text: 'pause', size: 1}, {text: 'per diem', size: 1}, {text: 'perception', size: 1}, {text: 'perform', size: 1}, {text: 'periodical', size: 1}, {text: 'periodically', size: 1}, {text: 'perspective', size: 1}, {text: 'perspiration', size: 1}, {text: 'persuasively', size: 1}, {text: 'perversely', size: 1}, {text: 'philosophical', size: 1}, {text: 'philosophy', size: 1}, {text: 'pick up', size: 1}, {text: 'pilgrimage', size: 1}, {text: 'pinion', size: 1}, {text: 'pinioned', size: 1}, {text: 'pity', size: 1}, {text: 'placid', size: 1}, {text: 'plenty', size: 1}, {text: 'poise', size: 1}, {text: 'poised', size: 1}, {text: 'polish', size: 1}, {text: 'polished', size: 1}, {text: 'porringer', size: 1}, {text: 'portion', size: 1}, {text: 'possibility', size: 1}, {text: 'possibly', size: 1}, {text: 'prayer', size: 1}, {text: 'prefix', size: 1}, {text: 'presume', size: 1}, {text: 'pride', size: 1}, {text: 'profound', size: 1}, {text: 'proof', size: 1}, {text: 'prophetic', size: 1}, {text: 'prospect', size: 1}, {text: 'protect', size: 1}, {text: 'protecting', size: 1}, {text: 'prudent', size: 1}, {text: 'put on', size: 1}, {text: 'quantity', size: 1}, {text: 'quite a', size: 1}, {text: 'raising', size: 1}, {text: 'range', size: 1}, {text: 'rare', size: 1}, {text: 'reader', size: 1}, {text: 'readiness', size: 1}, {text: 'reasonably', size: 1}, {text: 'rebel', size: 1}, {text: 'rebelliously', size: 1}, {text: 'recent', size: 1}, {text: 'reckless', size: 1}, {text: 'recollection', size: 1}, {text: 'red-faced', size: 1}, {text: 'reference', size: 1}, {text: 'reflection', size: 1}, {text: 'refrain', size: 1}, {text: 'refusal', size: 1}, {text: 'regret', size: 1}, {text: 'regular', size: 1}, {text: 'regulation', size: 1}, {text: 'rejoice', size: 1}, {text: 'rejoicing', size: 1}, {text: 'relax', size: 1}, {text: 'relaxed', size: 1}, {text: 'remonstrance', size: 1}, {text: 'reported', size: 1}, {text: 'resolve', size: 1}, {text: 'resolved', size: 1}, {text: 'respectful', size: 1}, {text: 'respiration', size: 1}, {text: 'respond', size: 1}, {text: 'right hand', size: 1}, {text: 'ring', size: 1}, {text: 'robe', size: 1}, {text: 'rolled', size: 1}, {text: 'rough', size: 1}, {text: 'rub', size: 1}, {text: 'run out', size: 1}, {text: 'rush', size: 1}, {text: 'rushed', size: 1}, {text: 'rustle', size: 1}, {text: 'sage', size: 1}, {text: 'salutation', size: 1}, {text: 'satisfaction', size: 1}, {text: 'scald', size: 1}, {text: 'scarce', size: 1}, {text: 'scrub', size: 1}, {text: 'scrubbed', size: 1}, {text: 'seated', size: 1}, {text: 'select', size: 1}, {text: 'self', size: 1}, {text: 'sending', size: 1}, {text: 'sequel', size: 1}, {text: 'set down', size: 1}, {text: 'set up', size: 1}, {text: 'setting', size: 1}, {text: 'settlement', size: 1}, {text: 'shine', size: 1}, {text: 'shoe', size: 1}, {text: 'shoes', size: 1}, {text: 'shook', size: 1}, {text: 'shop', size: 1}, {text: 'shriek', size: 1}, {text: 'shrieked', size: 1}, {text: 'shrunken', size: 1}, {text: 'shudder', size: 1}, {text: 'sicken', size: 1}, {text: 'signature', size: 1}, {text: 'sink', size: 1}, {text: 'sit down', size: 1}, {text: 'sit in', size: 1}, {text: 'sleep in', size: 1}, {text: 'sleeping', size: 1}, {text: 'slow', size: 1}, {text: 'smother', size: 1}, {text: 'smothered', size: 1}, {text: 'snappish', size: 1}, {text: 'sneeze', size: 1}, {text: 'sob', size: 1}, {text: 'soften', size: 1}, {text: 'softened', size: 1}, {text: 'solemn', size: 1}, {text: 'sorrow', size: 1}, {text: 'spare', size: 1}, {text: 'specimen', size: 1}, {text: 'speedily', size: 1}, {text: 'spirited', size: 1}, {text: 'spirits', size: 1}, {text: 'splash', size: 1}, {text: 'spoken', size: 1}, {text: 'stammer', size: 1}, {text: 'stand in', size: 1}, {text: 'stare', size: 1}, {text: 'staring', size: 1}, {text: 'start up', size: 1}, {text: 'startle', size: 1}, {text: 'startled', size: 1}, {text: 'starvation', size: 1}, {text: 'stature', size: 1}, {text: 'stipend', size: 1}, {text: 'stipendiary', size: 1}, {text: 'stir', size: 1}, {text: 'stirred', size: 1}, {text: 'stomach', size: 1}, {text: 'stone', size: 1}, {text: 'stoop', size: 1}, {text: 'stoop to', size: 1}, {text: 'stooped', size: 1}, {text: 'straw', size: 1}, {text: 'stray', size: 1}, {text: 'stretch', size: 1}, {text: 'stretch out', size: 1}, {text: 'stretched', size: 1}, {text: 'stride', size: 1}, {text: 'strive', size: 1}, {text: 'striving', size: 1}, {text: 'struggle', size: 1}, {text: 'stupefied', size: 1}, {text: 'stupefy', size: 1}, {text: 'sturdy', size: 1}, {text: 'suck', size: 1}, {text: 'sucking', size: 1}, {text: 'sugar', size: 1}, {text: 'suit', size: 1}, {text: 'summon', size: 1}, {text: 'superintendence', size: 1}, {text: 'superlative', size: 1}, {text: 'surly', size: 1}, {text: 'surround', size: 1}, {text: 'surrounded', size: 1}, {text: 'survive', size: 1}, {text: 'swallow', size: 1}, {text: 'swear', size: 1}, {text: 'sweetness', size: 1}, {text: 'systematic', size: 1}, {text: 'take down', size: 1}, {text: 'take in', size: 1}, {text: 'take on', size: 1}, {text: 'take out', size: 1}, {text: 'take place', size: 1}, {text: 'take up', size: 1}, {text: 'talk about', size: 1}, {text: 'talk of', size: 1}, {text: 'tall', size: 1}, {text: 'taste', size: 1}, {text: 'tasting', size: 1}, {text: 'tavern', size: 1}, {text: 'tea', size: 1}, {text: 'tear into', size: 1}, {text: 'temerity', size: 1}, {text: 'temple', size: 1}, {text: 'temporary', size: 1}, {text: 'termination', size: 1}, {text: 'testimony', size: 1}, {text: 'thanks', size: 1}, {text: 'the Street', size: 1}, {text: 'theory', size: 1}, {text: 'thereby', size: 1}, {text: 'thereon', size: 1}, {text: 'theretofore', size: 1}, {text: 'thingummy', size: 1}, {text: 'think about', size: 1}, {text: 'thirteen', size: 1}, {text: 'thirty', size: 1}, {text: 'thrash', size: 1}, {text: 'thrashing', size: 1}, {text: 'thrust', size: 1}, {text: 'thrusting', size: 1}, {text: 'ticket', size: 1}, {text: 'to be sure', size: 1}, {text: 'to wit', size: 1}, {text: 'torture', size: 1}, {text: 'treachery', size: 1}, {text: 'tremble', size: 1}, {text: 'tremendous', size: 1}, {text: 'trot', size: 1}, {text: 'turn up', size: 1}, {text: 'twice', size: 1}, {text: 'uncomfortable', size: 1}, {text: 'unconsciously', size: 1}, {text: 'unconsciousness', size: 1}, {text: 'undertake', size: 1}, {text: 'undertaker', size: 1}, {text: 'undo', size: 1}, {text: 'unequally', size: 1}, {text: 'unexpectedly', size: 1}, {text: 'unfortunately', size: 1}, {text: 'uniform', size: 1}, {text: 'unlimited', size: 1}, {text: 'unquestionably', size: 1}, {text: 'unwonted', size: 1}, {text: 'upstairs', size: 1}, {text: 'upward', size: 1}, {text: 'usage', size: 1}, {text: 'venture', size: 1}, {text: 'victim', size: 1}, {text: 'vindicate', size: 1}, {text: 'vindicated', size: 1}, {text: 'violent', size: 1}, {text: 'voracious', size: 1}, {text: 'wake', size: 1}, {text: 'walk away', size: 1}, {text: 'ward', size: 1}, {text: 'washed', size: 1}, {text: 'waste', size: 1}, {text: 'wasted', size: 1}, {text: 'wave', size: 1}, {text: 'waving', size: 1}, {text: 'weak', size: 1}, {text: 'weakly', size: 1}, {text: 'wed', size: 1}, {text: 'wedding', size: 1}, {text: 'weekly', size: 1}, {text: 'weep', size: 1}, {text: 'weeping', size: 1}, {text: 'whisper', size: 1}, {text: 'whispered', size: 1}, {text: 'wildly', size: 1}, {text: 'wink', size: 1}, {text: 'wink at', size: 1}, {text: 'wipe', size: 1}, {text: 'wise', size: 1}, {text: 'wit', size: 1}, {text: 'worn', size: 1}, {text: 'wrap', size: 1}, {text: 'wrapped', size: 1}, {text: 'yellow', size: 1}, {text: 'Young', size: 1} ];
'use strict'; const cleanup = require('rollup-plugin-cleanup'); const common = require('rollup-plugin-commonjs'); const node = require('rollup-plugin-node-resolve'); const path = require('path'); const pkg = require('../package.json'); const rollup = require('rollup').rollup; /** * Wrap a bundled dependency for consumption by the Compiler. * @param {Object} ext Details from the `ext` object in package.json. * @return {Object} A rollup plugin. */ function wrap(ext) { return { name: 'googup', transformBundle: function(source) { let name = `ol.ext.${ext.name || ext.module}`; let postamble = ''; if (ext.import) { name += '.' + ext.import; } else { postamble = `${name} = ${name}.default;\n`; } return ` /** * @fileoverview * @suppress {accessControls, ambiguousFunctionDecl, checkDebuggerStatement, checkRegExp, checkTypes, checkVars, const, constantProperty, deprecated, duplicate, es5Strict, fileoverviewTags, missingProperties, nonStandardJsDocs, strictModuleDepCheck, suspiciousCode, undefinedNames, undefinedVars, unknownDefines, unusedLocalVariables, uselessCode, visibility} */ goog.provide('${name}'); /** @typedef {function(*)} */ ${name} = function() {}; (function() {${source}}).call(ol.ext); ${postamble}`; } }; } /** * Build all external modules. * @return {Promise} Resolves on successful completion. */ function main() { return Promise.all(pkg.ext.map(ext => { const moduleName = ext.name || ext.module; const options = { extend: true, entry: require.resolve(ext.module), dest: `${path.join(__dirname, '..', 'build', 'ol.ext', moduleName.toLowerCase())}.js`, format: 'iife', moduleName: moduleName, exports: 'named', plugins: [ node(), common(), cleanup(), wrap(ext) ] }; return rollup(options).then(bundle => bundle.write(options)); })); } if (require.main === module) { main().catch(err => { process.stderr.write(`${err.message}\n`, () => process.exit(1)); }); } module.exports = main;
var gulp = require('gulp'); var paths = require('../paths'); var tslint = require('gulp-tslint'); gulp.task('lint', function () { return gulp.src(paths.source) .pipe(tslint({ formatter: "verbose" })) .pipe(tslint.report()) });
import * as Cookies from 'js-cookie'; import axios from 'axios'; import { route } from 'preact-router'; function storeUserCredentials({ user, accessToken, expires }) { Cookies.set('crendentials', { user, accessToken }, { expires: new Date(expires) }); } export function getUserCredentials() { return Cookies.getJSON('crendentials'); } export function isAuthenticated() { const crendentials = getUserCredentials(); return !(crendentials === null || crendentials === undefined); } export function onLogin(response) { storeUserCredentials(response); route('/', true); } export function logout() { Cookies.remove('crendentials'); route('/login', true); } export function authenticate(params = {}) { axios .post(`/auth/${params.network}`, { access_token: params.access_token }) .then(response => response.data) .then(onLogin) .catch((error) => { alert('User could not login'); console.error(error); }); }
import _curry2 from './_curry2.js'; import _xfBase from './_xfBase.js'; function XDropLast(n, xf) { this.xf = xf; this.pos = 0; this.full = false; this.acc = new Array(n); } XDropLast.prototype['@@transducer/init'] = _xfBase.init; XDropLast.prototype['@@transducer/result'] = function(result) { this.acc = null; return this.xf['@@transducer/result'](result); }; XDropLast.prototype['@@transducer/step'] = function(result, input) { if (this.full) { result = this.xf['@@transducer/step'](result, this.acc[this.pos]); } this.store(input); return result; }; XDropLast.prototype.store = function(input) { this.acc[this.pos] = input; this.pos += 1; if (this.pos === this.acc.length) { this.pos = 0; this.full = true; } }; var _xdropLast = _curry2(function _xdropLast(n, xf) { return new XDropLast(n, xf); }); export default _xdropLast;
(function() { var $, Builder, Events, SelfClosingTags, Tags, View, callAttachHook, docEl, exports, idCounter, jQuery, matches, matchesSelector, methodName, originalCleanData, _, _fn, _fn1, _i, _j, _len, _len1, _ref, _ref1, __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; }, __slice = [].slice; if (typeof require === 'function') { _ = require('underscore-plus'); $ = jQuery = require('../vendor/jquery'); } else { _ = window._, jQuery = window.jQuery; $ = jQuery; } Tags = 'a abbr address article aside audio b bdi bdo blockquote body button canvas\ caption cite code colgroup datalist dd del details dfn dialog div dl dt em\ fieldset figcaption figure footer form h1 h2 h3 h4 h5 h6 head header html i\ iframe ins kbd label legend li main map mark menu meter nav noscript object\ ol optgroup option output p pre progress q rp rt ruby s samp script section\ select small span strong style sub summary sup table tbody td textarea tfoot\ th thead time title tr u ul var video area base br col command embed hr img\ input keygen link meta param source track wbr'.split(/\s+/); SelfClosingTags = {}; 'area base br col command embed hr img input keygen link meta param\ source track wbr'.split(/\s+/).forEach(function(tag) { return SelfClosingTags[tag] = true; }); Events = 'blur change click dblclick error focus input keydown\ keypress keyup load mousedown mousemove mouseout mouseover\ mouseup resize scroll select submit unload'.split(/\s+/); docEl = document.documentElement; matches = docEl.matchesSelector || docEl.mozMatchesSelector || docEl.webkitMatchesSelector || docEl.oMatchesSelector || docEl.msMatchesSelector; matchesSelector = matches ? (function(elem, selector) { return matches.call(elem[0], selector); }) : (function(elem, selector) { return elem.is(selector); }); idCounter = 0; View = (function(_super) { __extends(View, _super); View.builderStack = null; Tags.forEach(function(tagName) { return View[tagName] = function() { var args, _ref; args = 1 <= arguments.length ? __slice.call(arguments, 0) : []; return (_ref = this.currentBuilder).tag.apply(_ref, [tagName].concat(__slice.call(args))); }; }); View.subview = function(name, view) { return this.currentBuilder.subview(name, view); }; View.text = function(string) { return this.currentBuilder.text(string); }; View.tag = function() { var args, tagName, _ref; tagName = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : []; return (_ref = this.currentBuilder).tag.apply(_ref, [tagName].concat(__slice.call(args))); }; View.raw = function(string) { return this.currentBuilder.raw(string); }; View.pushBuilder = function() { var builder; builder = new Builder; if (this.builderStack == null) { this.builderStack = []; } this.builderStack.push(builder); return this.currentBuilder = builder; }; View.popBuilder = function() { this.currentBuilder = this.builderStack[this.builderStack.length - 2]; return this.builderStack.pop(); }; View.buildHtml = function(fn) { var html, postProcessingSteps, _ref; this.pushBuilder(); fn.call(this); return _ref = this.popBuilder().buildHtml(), html = _ref[0], postProcessingSteps = _ref[1], _ref; }; View.render = function(fn) { var div, fragment, html, postProcessingSteps, step, _i, _len, _ref; _ref = this.buildHtml(fn), html = _ref[0], postProcessingSteps = _ref[1]; div = document.createElement('div'); div.innerHTML = html; fragment = $(div.childNodes); for (_i = 0, _len = postProcessingSteps.length; _i < _len; _i++) { step = postProcessingSteps[_i]; step(fragment); } return fragment; }; function View() { var args, element, html, postProcessingSteps, step, _i, _j, _len, _len1, _ref, _ref1; args = 1 <= arguments.length ? __slice.call(arguments, 0) : []; _ref = this.constructor.buildHtml(function() { return this.content.apply(this, args); }), html = _ref[0], postProcessingSteps = _ref[1]; jQuery.fn.init.call(this, html); if (this.length !== 1) { throw new Error("View markup must have a single root element"); } this.wireOutlets(this); this.bindEventHandlers(this); jQuery.data(this[0], 'view', this); _ref1 = this[0].getElementsByTagName('*'); for (_i = 0, _len = _ref1.length; _i < _len; _i++) { element = _ref1[_i]; jQuery.data(element, 'view', this); } this[0].setAttribute('callAttachHooks', true); for (_j = 0, _len1 = postProcessingSteps.length; _j < _len1; _j++) { step = postProcessingSteps[_j]; step(this); } if (typeof this.initialize === "function") { this.initialize.apply(this, args); } } View.prototype.buildHtml = function(params) { var html, postProcessingSteps, _ref; this.constructor.builder = new Builder; this.constructor.content(params); _ref = this.constructor.builder.buildHtml(), html = _ref[0], postProcessingSteps = _ref[1]; this.constructor.builder = null; return postProcessingSteps; }; View.prototype.wireOutlets = function(view) { var element, outlet, _i, _len, _ref; _ref = view[0].querySelectorAll('[outlet]'); for (_i = 0, _len = _ref.length; _i < _len; _i++) { element = _ref[_i]; outlet = element.getAttribute('outlet'); view[outlet] = $(element); element.removeAttribute('outlet'); } return void 0; }; View.prototype.bindEventHandlers = function(view) { var element, eventName, methodName, selector, _fn, _i, _j, _len, _len1, _ref; for (_i = 0, _len = Events.length; _i < _len; _i++) { eventName = Events[_i]; selector = "[" + eventName + "]"; _ref = view[0].querySelectorAll(selector); _fn = function(element) { var methodName; methodName = element.getAttribute(eventName); element = $(element); return element.on(eventName, function(event) { return view[methodName](event, element); }); }; for (_j = 0, _len1 = _ref.length; _j < _len1; _j++) { element = _ref[_j]; _fn(element); } if (matchesSelector(view, selector)) { methodName = view[0].getAttribute(eventName); (function(methodName) { return view.on(eventName, function(event) { return view[methodName](event, view); }); })(methodName); } } return void 0; }; View.prototype.pushStack = function(elems) { var ret; ret = jQuery.merge(jQuery(), elems); ret.prevObject = this; ret.context = this.context; return ret; }; View.prototype.end = function() { var _ref; return (_ref = this.prevObject) != null ? _ref : jQuery(null); }; View.prototype.command = function(commandName, selector, options, handler) { return View.__super__.command.call(this, commandName, selector, options, handler); }; View.prototype.preempt = function(eventName, handler) { return View.__super__.preempt.call(this, eventName, handler); }; return View; })(jQuery); Builder = (function() { function Builder() { this.document = []; this.postProcessingSteps = []; } Builder.prototype.buildHtml = function() { return [this.document.join(''), this.postProcessingSteps]; }; Builder.prototype.tag = function() { var args, name, options; name = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : []; options = this.extractOptions(args); this.openTag(name, options.attributes); if (SelfClosingTags.hasOwnProperty(name)) { if ((options.text != null) || (options.content != null)) { throw new Error("Self-closing tag " + name + " cannot have text or content"); } } else { if (typeof options.content === "function") { options.content(); } if (options.text) { this.text(options.text); } return this.closeTag(name); } }; Builder.prototype.openTag = function(name, attributes) { var attributeName, attributePairs, attributesString, value; attributePairs = (function() { var _results; _results = []; for (attributeName in attributes) { value = attributes[attributeName]; _results.push("" + attributeName + "=\"" + value + "\""); } return _results; })(); attributesString = attributePairs.length ? " " + attributePairs.join(" ") : ""; return this.document.push("<" + name + attributesString + ">"); }; Builder.prototype.closeTag = function(name) { return this.document.push("</" + name + ">"); }; Builder.prototype.text = function(string) { var escapedString; escapedString = string.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/'/g, '&#39;').replace(/</g, '&lt;').replace(/>/g, '&gt;'); return this.document.push(escapedString); }; Builder.prototype.raw = function(string) { return this.document.push(string); }; Builder.prototype.subview = function(outletName, subview) { var subviewId; subviewId = "subview-" + (++idCounter); this.tag('div', { id: subviewId }); return this.postProcessingSteps.push(function(view) { view[outletName] = subview; subview.parentView = view; return view.find("div#" + subviewId).replaceWith(subview); }); }; Builder.prototype.extractOptions = function(args) { var arg, options, _i, _len; options = {}; for (_i = 0, _len = args.length; _i < _len; _i++) { arg = args[_i]; switch (typeof arg) { case 'function': options.content = arg; break; case 'string': case 'number': options.text = arg.toString(); break; default: options.attributes = arg; } } return options; }; return Builder; })(); callAttachHook = function(element) { var child, elementsWithHooks, onDom, _i, _j, _len, _len1, _ref, _ref1, _results; if (!(element instanceof jQuery && element[0])) { return; } onDom = (typeof element.parents === "function" ? element.parents('html').length : void 0) > 0; elementsWithHooks = []; if (element[0].getAttribute('callAttachHooks')) { elementsWithHooks.push(element[0]); } if (onDom) { _ref = element[0].querySelectorAll('[callAttachHooks]'); for (_i = 0, _len = _ref.length; _i < _len; _i++) { child = _ref[_i]; elementsWithHooks.push(child); } } _results = []; for (_j = 0, _len1 = elementsWithHooks.length; _j < _len1; _j++) { element = elementsWithHooks[_j]; _results.push((_ref1 = $(element).view()) != null ? typeof _ref1.afterAttach === "function" ? _ref1.afterAttach(onDom) : void 0 : void 0); } return _results; }; _ref = ['append', 'prepend', 'after', 'before']; _fn = function(methodName) { var originalMethod; originalMethod = $.fn[methodName]; return jQuery.fn[methodName] = function() { var arg, args, flatArgs, result, _j, _len1, _ref1; args = 1 <= arguments.length ? __slice.call(arguments, 0) : []; flatArgs = (_ref1 = []).concat.apply(_ref1, args); result = originalMethod.apply(this, flatArgs); for (_j = 0, _len1 = flatArgs.length; _j < _len1; _j++) { arg = flatArgs[_j]; callAttachHook(arg); } return result; }; }; for (_i = 0, _len = _ref.length; _i < _len; _i++) { methodName = _ref[_i]; _fn(methodName); } _ref1 = ['prependTo', 'appendTo', 'insertAfter', 'insertBefore']; _fn1 = function(methodName) { var originalMethod; originalMethod = jQuery.fn[methodName]; return jQuery.fn[methodName] = function() { var args, result; args = 1 <= arguments.length ? __slice.call(arguments, 0) : []; result = originalMethod.apply(this, args); callAttachHook(this); return result; }; }; for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) { methodName = _ref1[_j]; _fn1(methodName); } originalCleanData = jQuery.cleanData; jQuery.cleanData = function(elements) { var element, view, _k, _len2; for (_k = 0, _len2 = elements.length; _k < _len2; _k++) { element = elements[_k]; view = $(element).view(); if (view && (view != null ? view[0] : void 0) === element) { if (typeof view.beforeRemove === "function") { view.beforeRemove(); } } } return originalCleanData(elements); }; $.fn.view = function() { return this.data('view'); }; $.fn.views = function() { return this.toArray().map(function(elt) { var $elt, _ref2; $elt = $(elt); return (_ref2 = $elt.view()) != null ? _ref2 : $elt; }); }; $.fn.containingView = function() { var element, view; element = this; while (element.length > 0) { if (view = element.data('view')) { return view; } element = element.parent(); } }; $.fn.scrollBottom = function(newValue) { if (newValue != null) { return this.scrollTop(newValue - this.height()); } else { return this.scrollTop() + this.height(); } }; $.fn.scrollDown = function() { return this.scrollTop(this.scrollTop() + $(window).height() / 20); }; $.fn.scrollUp = function() { return this.scrollTop(this.scrollTop() - $(window).height() / 20); }; $.fn.scrollToTop = function() { return this.scrollTop(0); }; $.fn.scrollToBottom = function() { return this.scrollTop(this.prop('scrollHeight')); }; $.fn.scrollRight = function(newValue) { if (newValue != null) { return this.scrollLeft(newValue - this.width()); } else { return this.scrollLeft() + this.width(); } }; $.fn.pageUp = function() { return this.scrollTop(this.scrollTop() - this.height()); }; $.fn.pageDown = function() { return this.scrollTop(this.scrollTop() + this.height()); }; $.fn.isOnDom = function() { return this.closest(document.body).length === 1; }; $.fn.isVisible = function() { return !this.isHidden(); }; $.fn.isHidden = function() { var style; style = this[0].style; if (style.display === 'none' || !this.isOnDom()) { return true; } else if (style.display) { return false; } else { return getComputedStyle(this[0]).display === 'none'; } }; $.fn.isDisabled = function() { return !!this.attr('disabled'); }; $.fn.enable = function() { return this.removeAttr('disabled'); }; $.fn.disable = function() { return this.attr('disabled', 'disabled'); }; $.fn.insertAt = function(index, element) { var target; target = this.children(":eq(" + index + ")"); if (target.length) { return $(element).insertBefore(target); } else { return this.append(element); } }; $.fn.removeAt = function(index) { return this.children(":eq(" + index + ")").remove(); }; $.fn.indexOf = function(child) { return this.children().toArray().indexOf($(child)[0]); }; $.fn.containsElement = function(element) { return (element[0].compareDocumentPosition(this[0]) & 8) === 8; }; $.fn.preempt = function(eventName, handler) { var eventNameWithoutNamespace, handlers, wrappedHandler, _ref2, _this = this; wrappedHandler = function() { var args, e; e = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : []; if (handler.apply(null, [e].concat(__slice.call(args))) === false) { return e.stopImmediatePropagation(); } }; this.on(eventName, wrappedHandler); eventNameWithoutNamespace = eventName.split('.')[0]; handlers = (_ref2 = this.handlers()[eventNameWithoutNamespace]) != null ? _ref2 : []; handlers.unshift(handlers.pop()); return { off: function() { return _this.off(eventName, wrappedHandler); } }; }; $.fn.handlers = function(eventName) { var handlers, _ref2, _ref3; handlers = this.length ? (_ref2 = $._data(this[0], 'events')) != null ? _ref2 : {} : {}; if (arguments.length === 1) { handlers = (_ref3 = handlers[eventName]) != null ? _ref3 : []; } return handlers; }; $.fn.hasParent = function() { return this.parent()[0] != null; }; $.fn.hasFocus = function() { return this.is(':focus') || this.is(':has(:focus)'); }; $.fn.flashError = function() { var removeErrorClass, _this = this; this.addClass('error'); removeErrorClass = function() { return _this.removeClass('error'); }; return window.setTimeout(removeErrorClass, 300); }; $.fn.trueHeight = function() { return this[0].getBoundingClientRect().height; }; $.fn.trueWidth = function() { return this[0].getBoundingClientRect().width; }; $.fn.document = function(eventName, docString) { var eventDescriptions; eventDescriptions = {}; eventDescriptions[eventName] = docString; if (!this.data('documentation')) { this.data('documentation', {}); } return _.extend(this.data('documentation'), eventDescriptions); }; $.fn.events = function() { var documentation, eventName, events, _ref2, _ref3; documentation = (_ref2 = this.data('documentation')) != null ? _ref2 : {}; events = {}; for (eventName in this.handlers()) { events[eventName] = (_ref3 = documentation[eventName]) != null ? _ref3 : null; } if (this.hasParent()) { return _.extend(this.parent().events(), events); } else { return events; } }; $.fn.command = function(eventName, selector, options, handler) { if (options == null) { handler = selector; selector = null; } else if (handler == null) { handler = options; options = null; } if ((selector != null) && typeof selector === 'object') { options = selector; selector = null; } this.document(eventName, _.humanizeEventName(eventName, options != null ? options['doc'] : void 0)); return this.on(eventName, selector, options != null ? options['data'] : void 0, handler); }; $.fn.iconSize = function(size) { return this.width(size).height(size).css('font-size', size); }; $.fn.intValue = function() { return parseInt(this.text()); }; $.Event.prototype.abortKeyBinding = function() {}; $.Event.prototype.currentTargetView = function() { return $(this.currentTarget).containingView(); }; $.Event.prototype.targetView = function() { return $(this.target).containingView(); }; exports = exports != null ? exports : this; exports.View = View; exports.jQuery = jQuery; exports.$ = $; exports.$$ = function(fn) { return View.render.call(View, fn); }; exports.$$$ = function(fn) { return View.buildHtml.call(View, fn)[0]; }; }).call(this);
module.exports = require('regenerate')().addRange(0x10350, 0x1037A);
/* CryptoJS v3.1.2 enc-base64.js code.google.com/p/crypto-js (c) 2009-2013 by Jeff Mott. All rights reserved. code.google.com/p/crypto-js/wiki/License */ (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var C_enc = C.enc; /** * Base64 encoding strategy. */ var Base64 = C_enc.Base64 = { /** * Converts a word array to a Base64 string. * * @param {WordArray} wordArray The word array. * * @return {string} The Base64 string. * * @static * * @example * * var base64String = CryptoJS.enc.Base64.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; var map = this._map; // Clamp excess bits wordArray.clamp(); // Convert var base64Chars = []; for (var i = 0; i < sigBytes; i += 3) { var byte1 = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; var byte2 = (words[(i + 1) >>> 2] >>> (24 - ((i + 1) % 4) * 8)) & 0xff; var byte3 = (words[(i + 2) >>> 2] >>> (24 - ((i + 2) % 4) * 8)) & 0xff; var triplet = (byte1 << 16) | (byte2 << 8) | byte3; for (var j = 0; (j < 4) && (i + j * 0.75 < sigBytes); j++) { base64Chars.push(map.charAt((triplet >>> (6 * (3 - j))) & 0x3f)); } } // Add padding var paddingChar = map.charAt(64); if (paddingChar) { while (base64Chars.length % 4) { base64Chars.push(paddingChar); } } return base64Chars.join(''); }, /** * Converts a Base64 string to a word array. * * @param {string} base64Str The Base64 string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Base64.parse(base64String); */ parse: function (base64Str) { // Shortcuts var base64StrLength = base64Str.length; var map = this._map; // Ignore padding var paddingChar = map.charAt(64); if (paddingChar) { var paddingIndex = base64Str.indexOf(paddingChar); if (paddingIndex != -1) { base64StrLength = paddingIndex; } } // Convert var words = []; var nBytes = 0; for (var i = 0; i < base64StrLength; i++) { if (i % 4) { var bits1 = map.indexOf(base64Str.charAt(i - 1)) << ((i % 4) * 2); var bits2 = map.indexOf(base64Str.charAt(i)) >>> (6 - (i % 4) * 2); words[nBytes >>> 2] |= (bits1 | bits2) << (24 - (nBytes % 4) * 8); nBytes++; } } return WordArray.create(words, nBytes); }, _map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=' }; }());
(function ($) { /* -------- * * DOM LOAD * * -------- */ $(document).ready(function() { // Slider $('.slider').slider({full_width: true}); // Carousel $('.carousel.carousel-slider').carousel({full_width: true}); $('.carousel').carousel(); }); }(jQuery));
app.config(function($stateProvider, $urlRouterProvider) { $stateProvider //sidebar .state('news', { url: "/news", abstract: true, templateUrl: "templates/sidebar-menu.html" }) // Blog page .state('news.home', { url: "/home", cache : false, views: { 'menuWorPress' :{ templateUrl: "templates/home.html", controller: "HomeCtrl" } } }) // articles page wordpress .state('news.post', { url: "/post/:catId/:offset/:index/:type", views: { 'menuWorPress' :{ templateUrl: "templates/post.html", controller: "PostCtrl" } } }) // Blog page .state('news.categories', { url: "/categories", views: { 'menuWorPress' :{ templateUrl: "templates/categories.html", controller: "CategoriesCtrl" } } }) // Blog page .state('news.category', { url: "/category/:category/:categoryName", cache : false, views: { 'menuWorPress' :{ templateUrl: "templates/home.html", controller: "CategoryCtrl" } } }) // Blog page .state('news.search', { url: "/search", cache : false, views: { 'menuWorPress' :{ templateUrl: "templates/search.html", controller: "SearchCtrl" } } }) .state('news.settings', { url: "/settings", views: { 'menuWorPress' :{ templateUrl: "templates/settings.html", controller: "SettingsCtrl" } } }) .state('news.contact', { url: "/contact", views: { 'menuWorPress' :{ templateUrl: "templates/contact.html", controller: "ContactCtrl" } } }) .state('news.about', { url: "/about", views: { 'menuWorPress' :{ templateUrl: "templates/about.html", controller: "AboutCtrl" } } }) .state('news.admob', { url: "/admob", views: { 'menuWorPress' :{ templateUrl: "templates/admob.html", controller: "AdmobCtrl" } } }) $urlRouterProvider.otherwise("/news/home"); })
import { expect } from 'chai'; import votesReducer from './'; describe('votesReducer', () => { describe('#votesReducer()', () => { it('should increment party votes by 1', () => { const newState = votesReducer({ PARTY_CODE: 25 }, { type: 'VOTE', partyCode: 'PARTY_CODE' }); expect(newState).to.deep.equal({ PARTY_CODE: 26 }); }); }); });
var S_ITER$0 = typeof Symbol!=='undefined'&&Symbol&&Symbol.iterator||'@@iterator';var S_MARK$0 = typeof Symbol!=='undefined'&&Symbol&&Symbol["__setObjectSetter__"];function ITER$0(v,f){if(v){if(Array.isArray(v))return f?v.slice():v;var i,r;if(S_MARK$0)S_MARK$0(v);if(typeof v==='object'&&typeof (f=v[S_ITER$0])==='function'){i=f.call(v);r=[];}else if((v+'')==='[object Generator]'){i=v;r=[];};if(S_MARK$0)S_MARK$0(void 0);if(r) {while((f=i['next']()),f['done']!==true)r.push(f['value']);return r;}}throw new Error(v+' is not iterable')};var SLICE$0 = Array.prototype.slice;var $D$0; { var test11 = [1, 2, 3]; var test12 = SLICE$0.call(test11, 0); test11.push(4); console.log(test11.join("|") === "1|2|3|4", test12.join("|") === "1|2|3"); } { var test21 = SLICE$0.call(([1, 2, 3]), 0); console.log(test21.join("|") === "1|2|3"); } { var test31; test31 = SLICE$0.call(($D$0 = [1, 2, 3]), 0), $D$0; console.log(test31.join("|") === "1|2|3"); { var test321, test322, test323; test322 = (test321 = SLICE$0.call(($D$0 = test323 = [1, 2, 3]), 0), $D$0); test322.push(4); console.log(test31.join("|") === "1|2|3", test322.join("|") === "1|2|3|4", test322 === test323); } } { var test41 = [1, 2, 3]; var test42; test42 = SLICE$0.call(test41, 0), test41; test41.push(4); console.log(test41.join("|") === "1|2|3|4", test42.join("|") === "1|2|3"); { var test43 = [1, 2, 3]; var test44 = ITER$0(test43 ); console.log(test44.join("|") === "1|2|3"); } } { var test51 = [0, 1, 2, 3]; var test52, test53; test53 = test51[0], test52 = SLICE$0.call(test51, 1), test51; test51.shift(); test51.push(4); console.log(test51.join("|") === "1|2|3|4", test52.join("|") === "1|2|3"); } { var test61 = [3, 2, 1], test63 = test61; var test62 = SLICE$0.call(([test61.reverse()])[0], 0); test61.push(4); console.log(test61.join("|") === "1|2|3|4", test62.join("|") === "1|2|3", test63 === test61); } { var test71 = [3, 2, 1]; var test72 = SLICE$0.call(([test71.reverse()])[0], 0); console.log(test72.join("|") === "1|2|3"); { test72 = SLICE$0.call(($D$0 = [test71.reverse()])[0], 0), $D$0; console.log(test72.join("|") === "3|2|1"); ;$D$0 = void 0} }
$(document).ready(function() { $(".issue-list").on("click", "div", function() { $(".issue-list .selected").removeClass("selected"); $(this).addClass("selected"); }); $('[data-behaviour="issue-view"]').on("click", "button", function() { var view = "issue-" + $(this).data("view"); $(".issue-list").removeClass("issue-minimal").removeClass("issue-compact").removeClass("issue-detailed") .addClass(view); }); });
/** * ag-grid-community - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v21.1.1 * @link http://www.ag-grid.com/ * @license MIT */ "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; Object.defineProperty(exports, "__esModule", { value: true }); var context_1 = require("../../context/context"); var componentMetadataProvider_1 = require("./componentMetadataProvider"); var utils_1 = require("../../utils"); var AgComponentUtils = /** @class */ (function () { function AgComponentUtils() { } AgComponentUtils.prototype.adaptFunction = function (propertyName, hardcodedJsFunction, componentFromFramework, source) { if (hardcodedJsFunction == null) { return { component: null, componentFromFramework: componentFromFramework, source: source, paramsFromSelector: null }; } var metadata = this.componentMetadataProvider.retrieve(propertyName); if (metadata && metadata.functionAdapter) { return { componentFromFramework: componentFromFramework, component: metadata.functionAdapter(hardcodedJsFunction), source: source, paramsFromSelector: null }; } return null; }; AgComponentUtils.prototype.adaptCellRendererFunction = function (callback) { var Adapter = /** @class */ (function () { function Adapter() { } Adapter.prototype.refresh = function (params) { return false; }; Adapter.prototype.getGui = function () { var callbackResult = callback(this.params); var type = typeof callbackResult; if (type === 'string' || type === 'number' || type === 'boolean') { return utils_1._.loadTemplate('<span>' + callbackResult + '</span>'); } else { return callbackResult; } }; Adapter.prototype.init = function (params) { this.params = params; }; return Adapter; }()); return Adapter; }; AgComponentUtils.prototype.doesImplementIComponent = function (candidate) { if (!candidate) { return false; } return candidate.prototype && 'getGui' in candidate.prototype; }; __decorate([ context_1.Autowired("componentMetadataProvider"), __metadata("design:type", componentMetadataProvider_1.ComponentMetadataProvider) ], AgComponentUtils.prototype, "componentMetadataProvider", void 0); AgComponentUtils = __decorate([ context_1.Bean("agComponentUtils") ], AgComponentUtils); return AgComponentUtils; }()); exports.AgComponentUtils = AgComponentUtils;
// Next-generation ES6 module bundler var gulp = require('gulp'), paths = require('./config/paths'), plumber = require('gulp-plumber'), rollup = require('gulp-rollup'), babel = require('rollup-plugin-babel'), rename = require('gulp-rename'); // Bundle ES6 modules. gulp.task('rollup:main', function() { return gulp.src(paths.dev.js + '/**/*.js') .pipe(plumber()) .pipe(rollup({ format: 'umd', entry: [ paths.dev.js + '/body.js', paths.dev.js + '/head.js' ], plugins: [ babel({ exclude: 'node_modules/**', presets: ['@babel/preset-env'], babelrc: false }) ] })) .pipe(rename({suffix: '.min'})) .pipe(gulp.dest(paths.build.js)); });
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ 'use strict'; var util = require('util'); /** * @class * Initializes a new instance of the ApplicationGatewaySslPolicy class. * @constructor * Application gateway SSL policy * * @member {array} [disabledSslProtocols] SSL protocols to be disabled on * Application Gateway * */ function ApplicationGatewaySslPolicy() { } /** * Defines the metadata of ApplicationGatewaySslPolicy * * @returns {object} metadata of ApplicationGatewaySslPolicy * */ ApplicationGatewaySslPolicy.prototype.mapper = function () { return { required: false, serializedName: 'ApplicationGatewaySslPolicy', type: { name: 'Composite', className: 'ApplicationGatewaySslPolicy', modelProperties: { disabledSslProtocols: { required: false, serializedName: 'disabledSslProtocols', type: { name: 'Sequence', element: { required: false, serializedName: 'StringElementType', type: { name: 'String' } } } } } } }; }; module.exports = ApplicationGatewaySslPolicy;
(function(){$(function(){return console.log("hello")})}).call(this);
/*! * Bootstrap-select v1.13.9 (https://developer.snapappointments.com/bootstrap-select) * * Copyright 2012-2019 SnapAppointments, LLC * Licensed under MIT (https://github.com/snapappointments/bootstrap-select/blob/master/LICENSE) */ (function (root, factory) { if (root === undefined && window !== undefined) root = window; if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module unless amdModuleId is set define(["jquery"], function (a0) { return (factory(a0)); }); } else if (typeof module === 'object' && module.exports) { // Node. Does not work with strict CommonJS, but // only CommonJS-like environments that support module.exports, // like Node. module.exports = factory(require("jquery")); } else { factory(root["jQuery"]); } }(this, function (jQuery) { (function ($) { $.fn.selectpicker.defaults = { noneSelectedText: 'Chưa chọn', noneResultsText: 'Không có kết quả cho {0}', countSelectedText: function (numSelected, numTotal) { return '{0} mục đã chọn'; }, maxOptionsText: function (numAll, numGroup) { return [ 'Không thể chọn (giới hạn {n} mục)', 'Không thể chọn (giới hạn {n} mục)' ]; }, selectAllText: 'Chọn tất cả', deselectAllText: 'Bỏ chọn', multipleSeparator: ', ' }; })(jQuery); })); //# sourceMappingURL=defaults-vi_VN.js.map
/** * Created by patricepaquette on 12/17/2013. */ angular.module("common") .directive('lazyLoad', ['$window', '$q', function ($window, $q) { function load_script(src) { var s = document.createElement('script'); // use global document since Angular's $document is weak s.src = src; document.body.appendChild(s); } function lazyLoadApi(src) { var deferred = $q.defer(); $window.initialize = function () { deferred.resolve(); }; // thanks to Emil Stenström: http://friendlybit.com/js/lazy-loading-asyncronous-javascript/ if ($window.attachEvent) { $window.attachEvent('onload', function(){ load_script(src); }); } else { $window.addEventListener('load', function(){ load_script(src); }, false); } return deferred.promise; } return { restrict: 'E', scope: { src: "@src" }, link: function (scope, element, attrs) { // function content is optional // in this example, it shows how and when the promises are resolved if ($window.google && $window.google.maps) { } else { lazyLoadApi().then(function () { //console.log('promise resolved'); if ($window.google && $window.google.maps) { //console.log('gmaps loaded'); } else { //console.log('gmaps not loaded'); } }, function () { //console.log('promise rejected'); }); } } }; }]);
/** * $Id: editor_plugin_src.js,v 1.1 2012/11/16 23:22:25 delara Exp $ * * @author Moxiecode * @copyright Copyright © 2004-2008, Moxiecode Systems AB, All rights reserved. */ (function() { tinymce.create('tinymce.plugins.Preview', { init : function(ed, url) { var t = this; t.editor = ed; ed.addCommand('mcePreview', t._preview, t); ed.addButton('preview', {title : 'preview.preview_desc', cmd : 'mcePreview'}); }, getInfo : function() { return { longname : 'Preview', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/preview', version : tinymce.majorVersion + "." + tinymce.minorVersion }; }, // Private methods _preview : function() { var ed = this.editor, win, html, c, pos, pos2, css, i, page = ed.getParam("plugin_preview_pageurl", null), w = ed.getParam("plugin_preview_width", "550"), h = ed.getParam("plugin_preview_height", "600"); // Use a custom preview page if (page) { ed.windowManager.open({ file : ed.getParam("plugin_preview_pageurl", null), width : w, height : h }, { resizable : "yes", scrollbars : "yes", inline : 1 }); } else { win = window.open("", "mcePreview", "menubar=no,toolbar=no,scrollbars=yes,resizable=yes,left=20,top=20,width=" + w + ",height=" + h); html = ""; c = ed.getContent(); pos = c.indexOf('<body'); css = ed.getParam("content_css", '').split(','); tinymce.map(css, function(u) { return ed.documentBaseURI.toAbsolute(u); }); if (pos != -1) { pos = c.indexOf('>', pos); pos2 = c.lastIndexOf('</body>'); c = c.substring(pos + 1, pos2); } html += ed.getParam('doctype'); html += '<html xmlns="http://www.w3.org/1999/xhtml">'; html += '<head>'; html += '<title>' + ed.getLang('preview.preview_desc') + '</title>'; html += '<base href="' + ed.documentBaseURI.getURI() + '" />'; html += '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />'; for (i=0; i<css.length; i++) html += '<link href="' + css[i] + '" rel="stylesheet" type="text/css" />'; html += '</head>'; html += '<body dir="' + ed.getParam("directionality") + '" onload="window.opener.tinymce.EditorManager.get(\'' + ed.id + '\').plugins[\'preview\']._onLoad(window,document);">'; html += c; html += '</body>'; html += '</html>'; win.document.write(html); win.document.close(); } }, _onLoad : function(w, d) { var t = this, nl, i, el = [], sv, ne; t._doc = d; w.writeFlash = t._writeFlash; w.writeShockWave = t._writeShockWave; w.writeQuickTime = t._writeQuickTime; w.writeRealMedia = t._writeRealMedia; w.writeWindowsMedia = t._writeWindowsMedia; w.writeEmbed = t._writeEmbed; nl = d.getElementsByTagName("script"); for (i=0; i<nl.length; i++) { sv = tinymce.isIE ? nl[i].innerHTML : nl[i].firstChild.nodeValue; if (new RegExp('write(Flash|ShockWave|WindowsMedia|QuickTime|RealMedia)\\(.*', 'g').test(sv)) el[el.length] = nl[i]; } for (i=0; i<el.length; i++) { ne = d.createElement("div"); ne.innerHTML = d._embeds[i]; el[i].parentNode.insertBefore(ne.firstChild, el[i]); } }, _writeFlash : function(p) { p.src = this.editor.documentBaseURI.toAbsolute(p.src); TinyMCE_PreviewPlugin._writeEmbed( 'D27CDB6E-AE6D-11cf-96B8-444553540000', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0', 'application/x-shockwave-flash', p ); }, _writeShockWave : function(p) { this.editor.documentBaseURI.toAbsolute(p.src); TinyMCE_PreviewPlugin._writeEmbed( '166B1BCA-3F9C-11CF-8075-444553540000', 'http://download.macromedia.com/pub/shockwave/cabs/director/sw.cab#version=8,5,1,0', 'application/x-director', p ); }, _writeQuickTime : function(p) { this.editor.documentBaseURI.toAbsolute(p.src); TinyMCE_PreviewPlugin._writeEmbed( '02BF25D5-8C17-4B23-BC80-D3488ABDDC6B', 'http://www.apple.com/qtactivex/qtplugin.cab#version=6,0,2,0', 'video/quicktime', p ); }, _writeRealMedia : function(p) { this.editor.documentBaseURI.toAbsolute(p.src); TinyMCE_PreviewPlugin._writeEmbed( 'CFCDAA03-8BE4-11cf-B84B-0020AFBBCCFA', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0', 'audio/x-pn-realaudio-plugin', p ); }, _writeWindowsMedia : function(p) { this.editor.documentBaseURI.toAbsolute(p.src); p.url = p.src; TinyMCE_PreviewPlugin._writeEmbed( '6BF52A52-394A-11D3-B153-00C04F79FAA6', 'http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701', 'application/x-mplayer2', p ); }, _writeEmbed : function(cls, cb, mt, p) { var h = '', n, d = t._doc, ne, c; h += '<object classid="clsid:' + cls + '" codebase="' + cb + '"'; h += typeof(p.id) != "undefined" ? 'id="' + p.id + '"' : ''; h += typeof(p.name) != "undefined" ? 'name="' + p.name + '"' : ''; h += typeof(p.width) != "undefined" ? 'width="' + p.width + '"' : ''; h += typeof(p.height) != "undefined" ? 'height="' + p.height + '"' : ''; h += typeof(p.align) != "undefined" ? 'align="' + p.align + '"' : ''; h += '>'; for (n in p) h += '<param name="' + n + '" value="' + p[n] + '">'; h += '<embed type="' + mt + '"'; for (n in p) h += n + '="' + p[n] + '" '; h += '></embed></object>'; d._embeds[d._embeds.length] = h; } }); // Register plugin tinymce.PluginManager.add('preview', tinymce.plugins.Preview); })();
// jsonCall: a jQuery plugin that makes it easy to make an API // request to a URL with JSON in BOTH directions. // // Copyright 2013 P'unk Avenue LLC // // Please see: // // https://github.com/punkave/jquery-json-call // // For complete documentation. (function( $ ) { // This is correct - we're adding a function called directly // like $.get or $.ajax, not a function that operates on // elements $.jsonCall = function(url, options, data, success, failure) { if (typeof(data) === 'function') { // No options argument passed, shift the others over failure = success; success = data; data = options; options = undefined; } options = options || {}; var ajax = $.ajax({ type: 'POST', url: url, processData: false, contentType: 'application/json', data: JSON.stringify(data), dataType: options.dataType || 'json', success: success, async: options.async, }); if (failure) { ajax.fail(failure); } }; })( jQuery );
// # ngReact // ### Use React Components inside of your Angular applications // // Composed of // - reactComponent (generic directive for delegating off to React Components) // - reactDirective (factory for creating specific directives that correspond to reactComponent directives) (function(React, angular) { 'use strict'; // get a react component from name (components can be an angular injectable e.g. value, factory or // available on window function getReactComponent( name, $injector ) { // if name is a function assume it is component and return it if (angular.isFunction(name)) { return name; } // a React component name must be specified if (!name) { throw new Error('ReactComponent name attribute must be specified'); } // ensure the specified React component is accessible, and fail fast if it's not var reactComponent; try { reactComponent = $injector.get(name); } catch(e) { } reactComponent = reactComponent || window[name]; if (!reactComponent) { throw Error('Cannot find react component ' + name); } return reactComponent; } // wraps a function with scope.$apply, if already applied just return function applied(fn, scope) { if (fn.wrappedInApply) { return fn; } return function() { var args = arguments; scope.$apply(function() { fn.wrappedInApply = true; fn.apply( null, args ); }); }; } // wraps all functions on obj in scope.$apply function applyFunctions(obj, scope) { return Object.keys(obj || {}).reduce(function(prev,key) { var value = obj[key]; // wrap functions in a function that ensures they are scope.$applied // ensures that when function is called from a React component // the Angular digest cycle is run prev[key] = angular.isFunction(value) ? applied(value, scope) : value; return prev; }, {}); } // render React component, with scope[attrs.props] being passed in as the component props function renderComponent(component, props, $timeout, elem) { $timeout(function() { React.render(React.createElement(component, props), elem[0]); }); } // # reactComponent // Directive that allows React components to be used in Angular templates. // // Usage: // <react-component name="Hello" props="name"/> // // This requires that there exists an injectable or globally available 'Hello' React component. // The 'props' attribute is optional and is passed to the component. // // The following would would create and register the component: // // /** @jsx React.DOM */ // var module = angular.module('ace.react.components'); // module.value('Hello', React.createClass({ // render: function() { // return <div>Hello {this.props.name}</div>; // } // })); // var reactComponent = function($timeout, $injector) { return { restrict: 'E', replace: true, link: function(scope, elem, attrs) { var reactComponent = getReactComponent(attrs.name, $injector); var renderMyComponent = function() { var scopeProps = scope[attrs.props]; var props = applyFunctions(scopeProps, scope); renderComponent(reactComponent, props, $timeout, elem); }; // If there are props, re-render when they change attrs.props ? scope.$watch(attrs.props, renderMyComponent, true) : renderMyComponent(); // cleanup when scope is destroyed scope.$on('$destroy', function() { React.unmountComponentAtNode(elem[0]); }); } }; }; // # reactDirective // Factory function to create directives for React components. // // With a component like this: // // /** @jsx React.DOM */ // var module = angular.module('ace.react.components'); // module.value('Hello', React.createClass({ // render: function() { // return <div>Hello {this.props.name}</div>; // } // })); // // A directive can be created and registered with: // // module.directive('hello', function(reactDirective) { // return reactDirective('Hello', ['name']); // }); // // Where the first argument is the injectable or globally accessible name of the React component // and the second argument is an array of property names to be watched and passed to the React component // as props. // // This directive can then be used like this: // // <hello name="name"/> // var reactDirective = function($timeout, $injector) { return function(reactComponentName, propNames) { return { restrict: 'E', replace: true, link: function(scope, elem, attrs) { var reactComponent = getReactComponent(reactComponentName, $injector); // if propNames is not defined, fall back to use the React component's propTypes if present propNames = propNames || Object.keys(reactComponent.propTypes || {}); // for each of the properties, get their scope value and set it to scope.props var renderMyComponent = function() { var props = {}; propNames.forEach(function(propName) { props[propName] = scope.$eval(attrs[propName]); }); renderComponent(reactComponent, applyFunctions(props, scope), $timeout, elem); }; // watch each property name and trigger an update whenever something changes, // to update scope.props with new values propNames.forEach(function(k) { scope.$watch(attrs[k], renderMyComponent, true); }); renderMyComponent(); // cleanup when scope is destroyed scope.$on('$destroy', function() { React.unmountComponentAtNode(elem[0]); }); } }; }; }; // create the end module without any dependencies, including reactComponent and reactDirective angular.module('react', []) .directive('reactComponent', ['$timeout', '$injector', reactComponent]) .factory('reactDirective', ['$timeout','$injector', reactDirective]); })(window.React, window.angular);
registerTest ('Has a UTF-8 meta tag', function () { this .test('Do we have a UTF8 meta tag?', function($) { var sourceCode = this.page.source.toLowerCase(); // do we have an utf8 metatag ? notEqual(sourceCode.indexOf('<meta charset="utf-8">'),-1,'Has UTF-8 meta tag'); }); });
angular.module('ngCordova.plugins.deviceOrientation', []) .factory('$cordovaDeviceOrientation', ['$q', function($q) { return { getCurrentHeading: function() { var q = $q.defer(); navigator.compass.getCurrentHeading(function(heading) { q.resolve(heading); }, function(err) { q.reject(err); }); return q.promise; }, watchHeading: function(options) { var q = $q.defer(); var watchId = navigator.compass.watchHeading(function(result) { q.notify(result); }, function(err) { q.reject(err); }, options); return { watchId: watchId, promise: q.promise } }, clearWatch: function(watchID) { navigator.compass.clearWatch(); } } }]);
/* * modified version of https://github.com/valor-software/prismjs-loader * * The MIT License (MIT) * * Copyright (c) 2015-2016 Valor Software * Copyright (c) 2015-2016 Dmitriy Shekhovtsov<valorkin@gmail.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ "use strict"; const Prism = require("prismjs"); module.exports = function loader(content) { const query = this.query; if (!query.lang) { throw new Error("You need to provide `lang` query parameter"); } if (!Prism.languages[query.lang]) { /* eslint-disable */ require(`prismjs/components/prism-${query.lang}.js`); /* eslint-enable */ } const lang = Prism.languages[query.lang]; const value = Prism.highlight(content, lang); const str = JSON.stringify(value); return `module.exports = ${str}`; }; module.exports.seperable = true;
/* global suite, test */ 'use strict'; var assert = require('assert'); var Table = require(__dirname + '/../lib/table'); var Column = require(__dirname + '/../lib/column'); suite('table', function() { var table = new Table({ name: 'bang' }); test('has name', function() { assert.equal(table.getName(), 'bang'); }); test('has no columns', function() { assert.equal(table.columns.length, 0); }); test('can add column', function() { var col = new Column({ table: table, name: 'boom' }); assert.equal(col.name, 'boom'); assert.equal(col.table.getName(), 'bang'); table.addColumn(col); assert.equal(table.columns.length, 1); assert.equal(table.boom, col); }); test('creates query node', function() { var sel = table.select(table.boom); assert.equal(sel.type, 'QUERY'); }); test('creates *-query if no args is provided to select()', function() { var sel = table.select(); assert.ok(sel.nodes[0].nodes[0].star); }); test('can be defined', function() { var user = Table.define({ name: 'user', columns: ['id', 'name'] }); assert.equal(user.getName(), 'user'); assert.equal(user.columns.length, 2); assert.equal(user.columns[0].name, 'id'); assert.equal(user.columns[1].name, 'name'); assert.equal(user.columns[0].name, user.id.name); assert.equal(user.id.table, user); assert.equal(user.name.table, user); }); }); test('table with user-defined column property names', function () { var table = Table.define({ name: 'blah', columns: [{ name: 'id', property: 'theId' }, { name: 'email', property: 'uniqueEmail' }] }); var cols = table.columns; assert.equal(cols.length, 2); assert.equal(cols[0].name, 'id'); assert(cols[0] === table.theId, 'Expected table.theId to be the first column'); assert(table.id === undefined, 'Expected table.id to not exist'); assert.equal(cols[1].name, 'email'); assert(cols[1] === table.uniqueEmail, 'Expected table.uniqueEmail to be the second column'); assert(table.email === undefined, 'Expected table.email to not exist'); }); test('table with fancier column definitions', function() { var table = Table.define({ name: 'blah', columns: [{ name: 'id', type: 'serial', notNull: true, primaryKey: true }, { name: 'email', type: 'text', notNull: true, unique: true, anythingYouWant: 'awesome' }] }); var cols = table.columns; assert.equal(cols.length, 2); var id = cols[0]; assert.equal(id.name, 'id'); assert.equal(id.type, 'serial'); assert.equal(id.notNull, true); assert.equal(id.primaryKey, true); var email = cols[1]; assert.equal(email.name, 'email'); assert.equal(email.type, 'text'); assert.equal(email.notNull, true); assert.equal(email.unique, true); assert.equal(email.anythingYouWant, 'awesome'); }); test('table with object structured column definitions', function() { var table = Table.define({ name: 'blah', columns: { id: { type: 'serial', notNull: true, primaryKey: true }, email: { type: 'text', notNull: true, unique: true, anythingYouWant: 'awesome' } } }); var cols = table.columns; assert.equal(cols.length, 2); var id = cols[0]; assert.equal(id.name, 'id'); assert.equal(id.type, 'serial'); assert.equal(id.notNull, true); assert.equal(id.primaryKey, true); var email = cols[1]; assert.equal(email.name, 'email'); assert.equal(email.type, 'text'); assert.equal(email.notNull, true); assert.equal(email.unique, true); assert.equal(email.anythingYouWant, 'awesome'); }); test('table with dynamic column definition', function() { var table = Table.define({ name: 'foo', columns: [] }); assert.equal(table.columns.length, 0); table.addColumn('foo'); assert.equal(table.columns.length, 1); var error = null; assert.throws(function() { table.addColumn('foo'); }); assert.doesNotThrow(function() { table.addColumn('foo', { noisy: false }); }); assert.equal(table.columns.length, 1); }); test('hasColumn', function() { var table = Table.define({ name: 'foo', columns: [] }); assert.equal(table.hasColumn('baz'), false); table.addColumn('baz'); assert.equal(table.hasColumn('baz'), true); }); test('the column "from" does not overwrite the from method', function() { var table = Table.define({ name: 'foo', columns: [] }); table.addColumn('from'); assert.equal(typeof table.from, 'function'); }); test('getColumn returns the from column', function() { var table = Table.define({ name: 'foo', columns: [] }); table.addColumn('from'); assert(table.getColumn('from') instanceof Column); assert(table.get('from') instanceof Column); });
(function($) { /** * Example module implementation. * * @author * @namespace Tc.Module * @class Default * @extends Tc.Module */ Tc.Module.Example = Tc.Module.extend({ /** * Initializes the Example module. * * @method init * @constructor * @param {jQuery|Zepto} $ctx the jquery context * @param {Sandbox} sandbox the sandbox to get the resources from * @param {String} modId the unique module id */ init: function($ctx, sandbox, modId) { // call base constructor this._super($ctx, sandbox, modId); }, /** * Hook function to do all of your module stuff. * * @method on * @param {Function} callback function * @return void */ on: function(callback) { this.$ctx.append('\n<br><span class="debug">JS Module &quot;example&quot; started</span>'); callback(); }, /** * Hook function to trigger your events. * * @method after * @return void */ after: function() { } }); })(Tc.$);
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /** * @constructor * @extends {WebInspector.TimelineUIUtils} */ WebInspector.TimelineUIUtilsImpl = function() { WebInspector.TimelineUIUtils.call(this); } WebInspector.TimelineUIUtilsImpl.prototype = { /** * @param {!WebInspector.TimelineModel.Record} record * @return {boolean} */ isBeginFrame: function(record) { return record.type() === WebInspector.TimelineModel.RecordType.BeginFrame; }, /** * @param {!WebInspector.TimelineModel.Record} record * @return {boolean} */ isProgram: function(record) { return record.type() === WebInspector.TimelineModel.RecordType.Program; }, /** * @param {string} recordType * @return {boolean} */ isCoalescable: function(recordType) { return !!WebInspector.TimelineUIUtilsImpl._coalescableRecordTypes[recordType]; }, /** * @param {!WebInspector.TimelineModel.Record} record * @return {boolean} */ isEventDivider: function(record) { return WebInspector.TimelineUIUtilsImpl.isEventDivider(record); }, /** * @param {!WebInspector.TimelineModel.Record} record * @return {?Object} */ countersForRecord: function(record) { return record.type() === WebInspector.TimelineModel.RecordType.UpdateCounters ? record.data() : null; }, /** * @param {!WebInspector.TimelineModel.Record} record * @return {?Object} */ highlightQuadForRecord: function(record) { var recordTypes = WebInspector.TimelineModel.RecordType; switch(record.type()) { case recordTypes.Layout: return record.data().root; case recordTypes.Paint: return record.data().clip; default: return null; } }, /** * @param {!WebInspector.TimelineModel.Record} record * @return {string} */ titleForRecord: function(record) { return WebInspector.TimelineUIUtilsImpl._recordTitle(record); }, /** * @param {!WebInspector.TimelineModel.Record} record * @return {!WebInspector.TimelineCategory} */ categoryForRecord: function(record) { return WebInspector.TimelineUIUtilsImpl.recordStyle(record).category; }, /** * @param {!WebInspector.TimelineModel.Record} record * @param {!WebInspector.Linkifier} linkifier * @return {?Node} */ buildDetailsNode: function(record, linkifier) { return WebInspector.TimelineUIUtilsImpl.buildDetailsNode(record, linkifier); }, /** * @param {!WebInspector.TimelineModel.Record} record * @param {!WebInspector.TimelineModel} model * @param {!WebInspector.Linkifier} linkifier * @param {function(!DocumentFragment)} callback */ generateDetailsContent: function(record, model, linkifier, callback) { WebInspector.TimelineUIUtilsImpl.generateDetailsContent(record, model, linkifier, callback); }, /** * @return {!Element} */ createBeginFrameDivider: function() { return this.createEventDivider(WebInspector.TimelineModel.RecordType.BeginFrame); }, /** * @param {string} recordType * @param {string=} title * @return {!Element} */ createEventDivider: function(recordType, title) { return WebInspector.TimelineUIUtilsImpl._createEventDivider(recordType, title); }, /** * @param {!WebInspector.TimelineModel.Record} record * @param {!RegExp} regExp * @return {boolean} */ testContentMatching: function(record, regExp) { var tokens = [WebInspector.TimelineUIUtilsImpl._recordTitle(record)]; var data = record.data(); for (var key in data) tokens.push(data[key]) return regExp.test(tokens.join("|")); }, /** * @param {!Object} total * @param {!WebInspector.TimelineModel.Record} record */ aggregateTimeForRecord: function(total, record) { WebInspector.TimelineUIUtilsImpl.aggregateTimeForRecord(total, record); }, /** * @return {!WebInspector.TimelineModel.Filter} */ hiddenRecordsFilter: function() { var recordTypes = WebInspector.TimelineModel.RecordType; var hiddenRecords = [ recordTypes.ActivateLayerTree, recordTypes.BeginFrame, recordTypes.DrawFrame, recordTypes.GPUTask, recordTypes.InvalidateLayout, recordTypes.MarkDOMContent, recordTypes.MarkFirstPaint, recordTypes.MarkLoad, recordTypes.RequestMainThreadFrame, recordTypes.ScheduleStyleRecalculation, recordTypes.UpdateCounters ]; return new WebInspector.TimelineRecordHiddenTypeFilter(hiddenRecords); }, __proto__: WebInspector.TimelineUIUtils.prototype } WebInspector.TimelineUIUtilsImpl._coalescableRecordTypes = {}; WebInspector.TimelineUIUtilsImpl._coalescableRecordTypes[WebInspector.TimelineModel.RecordType.Layout] = 1; WebInspector.TimelineUIUtilsImpl._coalescableRecordTypes[WebInspector.TimelineModel.RecordType.Paint] = 1; WebInspector.TimelineUIUtilsImpl._coalescableRecordTypes[WebInspector.TimelineModel.RecordType.Rasterize] = 1; WebInspector.TimelineUIUtilsImpl._coalescableRecordTypes[WebInspector.TimelineModel.RecordType.DecodeImage] = 1; WebInspector.TimelineUIUtilsImpl._coalescableRecordTypes[WebInspector.TimelineModel.RecordType.ResizeImage] = 1; /** * @return {!Object.<string, !{title: string, category: !WebInspector.TimelineCategory}>} */ WebInspector.TimelineUIUtils._initRecordStyles = function() { if (WebInspector.TimelineUIUtils._recordStylesMap) return WebInspector.TimelineUIUtils._recordStylesMap; var recordTypes = WebInspector.TimelineModel.RecordType; var categories = WebInspector.TimelineUIUtils.categories(); var recordStyles = {}; recordStyles[recordTypes.Root] = { title: "#root", category: categories["loading"] }; recordStyles[recordTypes.Program] = { title: WebInspector.UIString("Other"), category: categories["other"] }; recordStyles[recordTypes.EventDispatch] = { title: WebInspector.UIString("Event"), category: categories["scripting"] }; recordStyles[recordTypes.BeginFrame] = { title: WebInspector.UIString("Frame Start"), category: categories["rendering"] }; recordStyles[recordTypes.ScheduleStyleRecalculation] = { title: WebInspector.UIString("Schedule Style Recalculation"), category: categories["rendering"] }; recordStyles[recordTypes.RecalculateStyles] = { title: WebInspector.UIString("Recalculate Style"), category: categories["rendering"] }; recordStyles[recordTypes.InvalidateLayout] = { title: WebInspector.UIString("Invalidate Layout"), category: categories["rendering"] }; recordStyles[recordTypes.Layout] = { title: WebInspector.UIString("Layout"), category: categories["rendering"] }; recordStyles[recordTypes.UpdateLayerTree] = { title: WebInspector.UIString("Update Layer Tree"), category: categories["rendering"] }; recordStyles[recordTypes.PaintSetup] = { title: WebInspector.UIString("Paint Setup"), category: categories["painting"] }; recordStyles[recordTypes.Paint] = { title: WebInspector.UIString("Paint"), category: categories["painting"] }; recordStyles[recordTypes.Rasterize] = { title: WebInspector.UIString("Paint"), category: categories["painting"] }; recordStyles[recordTypes.ScrollLayer] = { title: WebInspector.UIString("Scroll"), category: categories["rendering"] }; recordStyles[recordTypes.DecodeImage] = { title: WebInspector.UIString("Image Decode"), category: categories["painting"] }; recordStyles[recordTypes.ResizeImage] = { title: WebInspector.UIString("Image Resize"), category: categories["painting"] }; recordStyles[recordTypes.CompositeLayers] = { title: WebInspector.UIString("Composite Layers"), category: categories["painting"] }; recordStyles[recordTypes.ParseHTML] = { title: WebInspector.UIString("Parse HTML"), category: categories["loading"] }; recordStyles[recordTypes.TimerInstall] = { title: WebInspector.UIString("Install Timer"), category: categories["scripting"] }; recordStyles[recordTypes.TimerRemove] = { title: WebInspector.UIString("Remove Timer"), category: categories["scripting"] }; recordStyles[recordTypes.TimerFire] = { title: WebInspector.UIString("Timer Fired"), category: categories["scripting"] }; recordStyles[recordTypes.XHRReadyStateChange] = { title: WebInspector.UIString("XHR Ready State Change"), category: categories["scripting"] }; recordStyles[recordTypes.XHRLoad] = { title: WebInspector.UIString("XHR Load"), category: categories["scripting"] }; recordStyles[recordTypes.EvaluateScript] = { title: WebInspector.UIString("Evaluate Script"), category: categories["scripting"] }; recordStyles[recordTypes.ResourceSendRequest] = { title: WebInspector.UIString("Send Request"), category: categories["loading"] }; recordStyles[recordTypes.ResourceReceiveResponse] = { title: WebInspector.UIString("Receive Response"), category: categories["loading"] }; recordStyles[recordTypes.ResourceFinish] = { title: WebInspector.UIString("Finish Loading"), category: categories["loading"] }; recordStyles[recordTypes.FunctionCall] = { title: WebInspector.UIString("Function Call"), category: categories["scripting"] }; recordStyles[recordTypes.ResourceReceivedData] = { title: WebInspector.UIString("Receive Data"), category: categories["loading"] }; recordStyles[recordTypes.GCEvent] = { title: WebInspector.UIString("GC Event"), category: categories["scripting"] }; recordStyles[recordTypes.JSFrame] = { title: WebInspector.UIString("JS Frame"), category: categories["scripting"] }; recordStyles[recordTypes.MarkDOMContent] = { title: WebInspector.UIString("DOMContentLoaded event"), category: categories["scripting"] }; recordStyles[recordTypes.MarkLoad] = { title: WebInspector.UIString("Load event"), category: categories["scripting"] }; recordStyles[recordTypes.MarkFirstPaint] = { title: WebInspector.UIString("First paint"), category: categories["painting"] }; recordStyles[recordTypes.TimeStamp] = { title: WebInspector.UIString("Stamp"), category: categories["scripting"] }; recordStyles[recordTypes.ConsoleTime] = { title: WebInspector.UIString("Console Time"), category: categories["scripting"] }; recordStyles[recordTypes.RequestAnimationFrame] = { title: WebInspector.UIString("Request Animation Frame"), category: categories["scripting"] }; recordStyles[recordTypes.CancelAnimationFrame] = { title: WebInspector.UIString("Cancel Animation Frame"), category: categories["scripting"] }; recordStyles[recordTypes.FireAnimationFrame] = { title: WebInspector.UIString("Animation Frame Fired"), category: categories["scripting"] }; recordStyles[recordTypes.WebSocketCreate] = { title: WebInspector.UIString("Create WebSocket"), category: categories["scripting"] }; recordStyles[recordTypes.WebSocketSendHandshakeRequest] = { title: WebInspector.UIString("Send WebSocket Handshake"), category: categories["scripting"] }; recordStyles[recordTypes.WebSocketReceiveHandshakeResponse] = { title: WebInspector.UIString("Receive WebSocket Handshake"), category: categories["scripting"] }; recordStyles[recordTypes.WebSocketDestroy] = { title: WebInspector.UIString("Destroy WebSocket"), category: categories["scripting"] }; recordStyles[recordTypes.EmbedderCallback] = { title: WebInspector.UIString("Embedder Callback"), category: categories["scripting"] }; WebInspector.TimelineUIUtils._recordStylesMap = recordStyles; return recordStyles; } /** * @param {!WebInspector.TimelineModel.Record} record * @return {!{title: string, category: !WebInspector.TimelineCategory}} */ WebInspector.TimelineUIUtilsImpl.recordStyle = function(record) { var type = record.type(); var recordStyles = WebInspector.TimelineUIUtils._initRecordStyles(); var result = recordStyles[type]; if (!result) { result = { title: WebInspector.UIString("Unknown: %s", type), category: WebInspector.TimelineUIUtils.categories()["other"] }; recordStyles[type] = result; } return result; } /** * @param {!WebInspector.TimelineModel.Record} record * @return {string} */ WebInspector.TimelineUIUtilsImpl._recordTitle = function(record) { var recordData = record.data(); if (record.type() === WebInspector.TimelineModel.RecordType.TimeStamp) return recordData["message"]; if (record.type() === WebInspector.TimelineModel.RecordType.JSFrame) return recordData["functionName"]; var title = WebInspector.TimelineUIUtilsImpl.recordStyle(record).title; if (WebInspector.TimelineUIUtilsImpl.isEventDivider(record)) { var startTime = Number.millisToString(record.startTime() - record._model.minimumRecordTime()); return WebInspector.UIString("%s at %s", title, startTime); } return title; } /** * @param {!WebInspector.TimelineModel.Record} record * @return {boolean} */ WebInspector.TimelineUIUtilsImpl.isEventDivider = function(record) { var recordTypes = WebInspector.TimelineModel.RecordType; if (record.type() === recordTypes.TimeStamp) return true; if (record.type() === recordTypes.MarkFirstPaint) return true; if (record.type() === recordTypes.MarkDOMContent || record.type() === recordTypes.MarkLoad) return record.data()["isMainFrame"]; return false; } /** * @param {!Object} total * @param {!WebInspector.TimelineModel.Record} record */ WebInspector.TimelineUIUtilsImpl.aggregateTimeForRecord = function(total, record) { var children = record.children(); for (var i = 0; i < children.length; ++i) WebInspector.TimelineUIUtilsImpl.aggregateTimeForRecord(total, children[i]); var categoryName = WebInspector.TimelineUIUtilsImpl.recordStyle(record).category.name; total[categoryName] = (total[categoryName] || 0) + record.selfTime(); } /** * @param {!WebInspector.TimelineModel.Record} record * @param {!WebInspector.Linkifier} linkifier * @return {?Node} */ WebInspector.TimelineUIUtilsImpl.buildDetailsNode = function(record, linkifier) { var details; var detailsText; var recordData = record.data(); switch (record.type()) { case WebInspector.TimelineModel.RecordType.GCEvent: detailsText = WebInspector.UIString("%s collected", Number.bytesToString(recordData["usedHeapSizeDelta"])); break; case WebInspector.TimelineModel.RecordType.TimerFire: detailsText = recordData["timerId"]; break; case WebInspector.TimelineModel.RecordType.FunctionCall: details = linkifyLocation(recordData["scriptId"], recordData["scriptName"], recordData["scriptLine"], 0); break; case WebInspector.TimelineModel.RecordType.FireAnimationFrame: detailsText = recordData["id"]; break; case WebInspector.TimelineModel.RecordType.EventDispatch: detailsText = recordData ? recordData["type"] : null; break; case WebInspector.TimelineModel.RecordType.Paint: var width = WebInspector.TimelineUIUtils.quadWidth(recordData.clip); var height = WebInspector.TimelineUIUtils.quadHeight(recordData.clip); if (width && height) detailsText = WebInspector.UIString("%d\u2009\u00d7\u2009%d", width, height); break; case WebInspector.TimelineModel.RecordType.TimerInstall: case WebInspector.TimelineModel.RecordType.TimerRemove: details = linkifyTopCallFrame(); detailsText = recordData["timerId"]; break; case WebInspector.TimelineModel.RecordType.RequestAnimationFrame: case WebInspector.TimelineModel.RecordType.CancelAnimationFrame: details = linkifyTopCallFrame(); detailsText = recordData["id"]; break; case WebInspector.TimelineModel.RecordType.ParseHTML: case WebInspector.TimelineModel.RecordType.RecalculateStyles: details = linkifyTopCallFrame(); break; case WebInspector.TimelineModel.RecordType.EvaluateScript: var url = recordData["url"]; if (url) details = linkifyLocation("", url, recordData["lineNumber"], 0); break; case WebInspector.TimelineModel.RecordType.XHRReadyStateChange: case WebInspector.TimelineModel.RecordType.XHRLoad: case WebInspector.TimelineModel.RecordType.ResourceSendRequest: case WebInspector.TimelineModel.RecordType.DecodeImage: case WebInspector.TimelineModel.RecordType.ResizeImage: var url = recordData["url"]; if (url) detailsText = WebInspector.displayNameForURL(url); break; case WebInspector.TimelineModel.RecordType.ResourceReceivedData: case WebInspector.TimelineModel.RecordType.ResourceReceiveResponse: case WebInspector.TimelineModel.RecordType.ResourceFinish: var initiator = record.initiator(); if (initiator) { var url = initiator.data()["url"]; if (url) detailsText = WebInspector.displayNameForURL(url); } break; case WebInspector.TimelineModel.RecordType.ConsoleTime: detailsText = recordData["message"]; break; case WebInspector.TimelineModel.RecordType.EmbedderCallback: detailsText = recordData["callbackName"]; break; default: details = linkifyTopCallFrame(); break; } if (!details && detailsText) details = document.createTextNode(detailsText); return details; /** * @param {string} scriptId * @param {string} url * @param {number} lineNumber * @param {number=} columnNumber */ function linkifyLocation(scriptId, url, lineNumber, columnNumber) { if (!url) return null; // FIXME(62725): stack trace line/column numbers are one-based. columnNumber = columnNumber ? columnNumber - 1 : 0; return linkifier.linkifyScriptLocation(record.target(), scriptId, url, lineNumber - 1, columnNumber, "timeline-details"); } /** * @return {?Element} */ function linkifyTopCallFrame() { if (record.stackTrace()) return linkifier.linkifyConsoleCallFrame(record.target(), record.stackTrace()[0], "timeline-details"); if (record.callSiteStackTrace()) return linkifier.linkifyConsoleCallFrame(record.target(), record.callSiteStackTrace()[0], "timeline-details"); return null; } } /** * @param {string=} recordType * @return {boolean} */ WebInspector.TimelineUIUtilsImpl._needsPreviewElement = function(recordType) { if (!recordType) return false; const recordTypes = WebInspector.TimelineModel.RecordType; switch (recordType) { case recordTypes.ResourceSendRequest: case recordTypes.ResourceReceiveResponse: case recordTypes.ResourceReceivedData: case recordTypes.ResourceFinish: return true; default: return false; } } /** * @param {!WebInspector.TimelineModel.Record} record * @param {!WebInspector.TimelineModel} model * @param {!WebInspector.Linkifier} linkifier * @param {function(!DocumentFragment)} callback */ WebInspector.TimelineUIUtilsImpl.generateDetailsContent = function(record, model, linkifier, callback) { var imageElement = /** @type {?Element} */ (record.getUserObject("TimelineUIUtils::preview-element") || null); var relatedNode = null; var recordData = record.data(); var barrier = new CallbackBarrier(); var target = record.target(); if (!imageElement && WebInspector.TimelineUIUtilsImpl._needsPreviewElement(record.type()) && target) WebInspector.DOMPresentationUtils.buildImagePreviewContents(target, recordData["url"], false, barrier.createCallback(saveImage)); if (recordData["backendNodeId"] && target) target.domModel.pushNodesByBackendIdsToFrontend([recordData["backendNodeId"]], barrier.createCallback(setRelatedNode)); barrier.callWhenDone(callbackWrapper); /** * @param {!Element=} element */ function saveImage(element) { imageElement = element || null; record.setUserObject("TimelineUIUtils::preview-element", element); } /** * @param {?Array.<!DOMAgent.NodeId>} nodeIds */ function setRelatedNode(nodeIds) { if (nodeIds && target) relatedNode = target.domModel.nodeForId(nodeIds[0]); } function callbackWrapper() { callback(WebInspector.TimelineUIUtilsImpl._generateDetailsContentSynchronously(record, model, linkifier, imageElement, relatedNode)); } } /** * @param {!WebInspector.TimelineModel.Record} record * @param {!WebInspector.TimelineModel} model * @param {!WebInspector.Linkifier} linkifier * @param {?Element} imagePreviewElement * @param {?WebInspector.DOMNode} relatedNode * @return {!DocumentFragment} */ WebInspector.TimelineUIUtilsImpl._generateDetailsContentSynchronously = function(record, model, linkifier, imagePreviewElement, relatedNode) { var fragment = document.createDocumentFragment(); var aggregatedStats = {}; WebInspector.TimelineUIUtilsImpl.aggregateTimeForRecord(aggregatedStats, record); if (record.children().length) fragment.appendChild(WebInspector.TimelineUIUtils.generatePieChart(aggregatedStats, WebInspector.TimelineUIUtilsImpl.recordStyle(record).category, record.selfTime())); else fragment.appendChild(WebInspector.TimelineUIUtils.generatePieChart(aggregatedStats)); const recordTypes = WebInspector.TimelineModel.RecordType; // The messages may vary per record.type(); var callSiteStackTraceLabel; var callStackLabel; var relatedNodeLabel; var contentHelper = new WebInspector.TimelineDetailsContentHelper(record.target(), linkifier, true); contentHelper.appendTextRow(WebInspector.UIString("Self Time"), Number.millisToString(record.selfTime(), true)); contentHelper.appendTextRow(WebInspector.UIString("Start Time"), Number.millisToString(record.startTime() - model.minimumRecordTime())); var recordData = record.data(); switch (record.type()) { case recordTypes.GCEvent: contentHelper.appendTextRow(WebInspector.UIString("Collected"), Number.bytesToString(recordData["usedHeapSizeDelta"])); break; case recordTypes.TimerFire: callSiteStackTraceLabel = WebInspector.UIString("Timer installed"); // Fall-through intended. case recordTypes.TimerInstall: case recordTypes.TimerRemove: contentHelper.appendTextRow(WebInspector.UIString("Timer ID"), recordData["timerId"]); if (record.type() === recordTypes.TimerInstall) { contentHelper.appendTextRow(WebInspector.UIString("Timeout"), Number.millisToString(recordData["timeout"])); contentHelper.appendTextRow(WebInspector.UIString("Repeats"), !recordData["singleShot"]); } break; case recordTypes.FireAnimationFrame: callSiteStackTraceLabel = WebInspector.UIString("Animation frame requested"); contentHelper.appendTextRow(WebInspector.UIString("Callback ID"), recordData["id"]); break; case recordTypes.FunctionCall: if (recordData["scriptName"]) contentHelper.appendLocationRow(WebInspector.UIString("Location"), recordData["scriptName"], recordData["scriptLine"]); break; case recordTypes.ResourceSendRequest: case recordTypes.ResourceReceiveResponse: case recordTypes.ResourceReceivedData: case recordTypes.ResourceFinish: var url; if (record.type() === recordTypes.ResourceSendRequest) url = recordData["url"]; else if (record.initiator()) url = record.initiator().data()["url"]; if (url) contentHelper.appendElementRow(WebInspector.UIString("Resource"), WebInspector.linkifyResourceAsNode(url)); if (imagePreviewElement) contentHelper.appendElementRow(WebInspector.UIString("Preview"), imagePreviewElement); if (recordData["requestMethod"]) contentHelper.appendTextRow(WebInspector.UIString("Request Method"), recordData["requestMethod"]); if (typeof recordData["statusCode"] === "number") contentHelper.appendTextRow(WebInspector.UIString("Status Code"), recordData["statusCode"]); if (recordData["mimeType"]) contentHelper.appendTextRow(WebInspector.UIString("MIME Type"), recordData["mimeType"]); if (recordData["encodedDataLength"]) contentHelper.appendTextRow(WebInspector.UIString("Encoded Data Length"), WebInspector.UIString("%d Bytes", recordData["encodedDataLength"])); break; case recordTypes.EvaluateScript: var url = recordData["url"]; if (url) contentHelper.appendLocationRow(WebInspector.UIString("Script"), url, recordData["lineNumber"]); break; case recordTypes.Paint: var clip = recordData["clip"]; contentHelper.appendTextRow(WebInspector.UIString("Location"), WebInspector.UIString("(%d, %d)", clip[0], clip[1])); var clipWidth = WebInspector.TimelineUIUtils.quadWidth(clip); var clipHeight = WebInspector.TimelineUIUtils.quadHeight(clip); contentHelper.appendTextRow(WebInspector.UIString("Dimensions"), WebInspector.UIString("%d × %d", clipWidth, clipHeight)); // Fall-through intended. case recordTypes.PaintSetup: case recordTypes.Rasterize: case recordTypes.ScrollLayer: relatedNodeLabel = WebInspector.UIString("Layer root"); break; case recordTypes.DecodeImage: case recordTypes.ResizeImage: relatedNodeLabel = WebInspector.UIString("Image element"); var url = recordData["url"]; if (url) contentHelper.appendElementRow(WebInspector.UIString("Image URL"), WebInspector.linkifyResourceAsNode(url)); break; case recordTypes.RecalculateStyles: // We don't want to see default details. if (recordData["elementCount"]) contentHelper.appendTextRow(WebInspector.UIString("Elements affected"), recordData["elementCount"]); callStackLabel = WebInspector.UIString("Styles recalculation forced"); break; case recordTypes.Layout: if (recordData["dirtyObjects"]) contentHelper.appendTextRow(WebInspector.UIString("Nodes that need layout"), recordData["dirtyObjects"]); if (recordData["totalObjects"]) contentHelper.appendTextRow(WebInspector.UIString("Layout tree size"), recordData["totalObjects"]); if (typeof recordData["partialLayout"] === "boolean") { contentHelper.appendTextRow(WebInspector.UIString("Layout scope"), recordData["partialLayout"] ? WebInspector.UIString("Partial") : WebInspector.UIString("Whole document")); } callSiteStackTraceLabel = WebInspector.UIString("Layout invalidated"); callStackLabel = WebInspector.UIString("Layout forced"); relatedNodeLabel = WebInspector.UIString("Layout root"); break; case recordTypes.ConsoleTime: contentHelper.appendTextRow(WebInspector.UIString("Message"), recordData["message"]); break; case recordTypes.WebSocketCreate: case recordTypes.WebSocketSendHandshakeRequest: case recordTypes.WebSocketReceiveHandshakeResponse: case recordTypes.WebSocketDestroy: var initiatorData = record.initiator() ? record.initiator().data() : recordData; if (typeof initiatorData["webSocketURL"] !== "undefined") contentHelper.appendTextRow(WebInspector.UIString("URL"), initiatorData["webSocketURL"]); if (typeof initiatorData["webSocketProtocol"] !== "undefined") contentHelper.appendTextRow(WebInspector.UIString("WebSocket Protocol"), initiatorData["webSocketProtocol"]); if (typeof recordData["message"] !== "undefined") contentHelper.appendTextRow(WebInspector.UIString("Message"), recordData["message"]); break; case recordTypes.EmbedderCallback: contentHelper.appendTextRow(WebInspector.UIString("Callback Function"), recordData["callbackName"]); break; default: var detailsNode = WebInspector.TimelineUIUtilsImpl.buildDetailsNode(record, linkifier); if (detailsNode) contentHelper.appendElementRow(WebInspector.UIString("Details"), detailsNode); break; } if (relatedNode) contentHelper.appendElementRow(relatedNodeLabel || WebInspector.UIString("Related node"), WebInspector.DOMPresentationUtils.linkifyNodeReference(relatedNode)); if (recordData["scriptName"] && record.type() !== recordTypes.FunctionCall) contentHelper.appendLocationRow(WebInspector.UIString("Function Call"), recordData["scriptName"], recordData["scriptLine"]); var callSiteStackTrace = record.callSiteStackTrace(); if (callSiteStackTrace) contentHelper.appendStackTrace(callSiteStackTraceLabel || WebInspector.UIString("Call Site stack"), callSiteStackTrace); var recordStackTrace = record.stackTrace(); if (recordStackTrace) contentHelper.appendStackTrace(callStackLabel || WebInspector.UIString("Call Stack"), recordStackTrace); if (record.warnings()) { var ul = document.createElement("ul"); for (var i = 0; i < record.warnings().length; ++i) ul.createChild("li").textContent = record.warnings()[i]; contentHelper.appendElementRow(WebInspector.UIString("Warning"), ul); } fragment.appendChild(contentHelper.element); return fragment; } /** * @param {string} recordType * @param {string=} title * @return {!Element} */ WebInspector.TimelineUIUtilsImpl._createEventDivider = function(recordType, title) { var eventDivider = document.createElement("div"); eventDivider.className = "resources-event-divider"; var recordTypes = WebInspector.TimelineModel.RecordType; if (recordType === recordTypes.MarkDOMContent) eventDivider.className += " resources-blue-divider"; else if (recordType === recordTypes.MarkLoad) eventDivider.className += " resources-red-divider"; else if (recordType === recordTypes.MarkFirstPaint) eventDivider.className += " resources-green-divider"; else if (recordType === recordTypes.TimeStamp) eventDivider.className += " resources-orange-divider"; else if (recordType === recordTypes.BeginFrame) eventDivider.className += " timeline-frame-divider"; if (title) eventDivider.title = title; return eventDivider; }
'use strict'; // copied from http://www.broofa.com/Tools/Math.uuid.js var CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' .split(''); exports.uuid = function () { var chars = CHARS, uuid = new Array(36), rnd=0, r; for (var i = 0; i < 36; i++) { if (i===8 || i===13 || i===18 || i===23) { uuid[i] = '-'; } else if (i===14) { uuid[i] = '4'; } else { if (rnd <= 0x02) rnd = 0x2000000 + (Math.random()*0x1000000)|0; r = rnd & 0xf; rnd = rnd >> 4; uuid[i] = chars[(i === 19) ? (r & 0x3) | 0x8 : r]; } } return uuid.join(''); }; exports.in_array = function (item, array) { if (!array) return false; if (!Array.isArray(array)) return false; return (array.indexOf(item) !== -1); }; exports.to_object = function (array) { if (typeof array === 'string') { array = array.split(/[\s,;]+/); } if (!Array.isArray(array)) { throw "arguments to to_object must be a string or array"; } var rv = {}; for (var i = 0; i < array.length; i++) { if (array[i] === undefined) { continue; } rv[array[i]] = true; } return rv; }; exports.sort_keys = function (obj) { return Object.keys(obj).sort(); }; exports.uniq = function (arr) { var out = []; var o = 0; for (var i=0,l=arr.length; i < l; i++) { if (out.length === 0) { out.push(arr[i]); } else if (out[o] !== arr[i]) { out.push(arr[i]); o++; } } return out; }; exports.extend = function (target) { // http://stackoverflow.com/questions/14974864/ var sources = [].slice.call(arguments, 1); sources.forEach(function (source) { for (var prop in source) { target[prop] = source[prop]; } }); return target; }; exports.ISODate = function (d) { function pad(n) { return n<10 ? '0'+n : n; } return d.getUTCFullYear()+'-' + pad(d.getUTCMonth()+1)+'-' + pad(d.getUTCDate())+'T' + pad(d.getUTCHours())+':' + pad(d.getUTCMinutes())+':' + pad(d.getUTCSeconds())+'Z' ; }; var _daynames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; var _monnames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; function _pad (num, n, p) { var s = '' + num; p = p || '0'; while (s.length < n) s = p + s; return s; } exports.pad = _pad; exports.date_to_str = function (d) { return _daynames[d.getDay()] + ', ' + _pad(d.getDate(),2) + ' ' + _monnames[d.getMonth()] + ' ' + d.getFullYear() + ' ' + _pad(d.getHours(),2) + ':' + _pad(d.getMinutes(),2) + ':' + _pad(d.getSeconds(),2) + ' ' + d.toString().match(/\sGMT([+-]\d+)/)[1]; }; exports.decode_qp = function (line) { line = line.replace(/\r\n/g,"\n").replace(/[ \t]+\r?\n/g,"\n"); if (! /=/.test(line)) { // this may be a pointless optimisation... return new Buffer(line); } line = line.replace(/=\n/mg, ''); var buf = new Buffer(line.length); var pos = 0; for (var i=0,l=line.length; i < l; i++) { if (line[i] === '=' && /=[0-9a-fA-F]{2}/.test(line[i] + line[i+1] + line[i+2])) { i++; buf[pos] = parseInt(line[i] + line[i+1], 16); i++; } else { buf[pos] = line.charCodeAt(i); } pos++; } return buf.slice(0, pos); }; function _char_to_qp (ch) { return "=" + _pad(ch.charCodeAt(0).toString(16).toUpperCase(), 2); } // Shameless attempt to copy from Perl's MIME::QuotedPrint::Perl code. exports.encode_qp = function (str) { str = str.replace( /([^\ \t\n!"#\$%&'()*+,\-.\/0-9:;<>?\@A-Z\[\\\]^_`a-z{|}~])/g, function (orig, p1) { return _char_to_qp(p1); } ).replace(/([ \t]+)$/gm, function (orig, p1) { return p1.split('').map(_char_to_qp).join(''); }); // Now shorten lines to 76 chars, but don't break =XX encodes. // Method: iterate over to char 73. // If char 74, 75 or 76 is = we need to break before the =. // Otherwise break at 76. var cur_length = 0; var out = ''; for (var i=0; i<str.length; i++) { if (str[i] === '\n') { out += '\n'; cur_length = 0; continue; } cur_length++; if (cur_length <= 73) { out += str[i]; } else if (cur_length > 73 && cur_length < 76) { if (str[i] === '=') { out += '=\n='; cur_length = 1; } else { out += str[i]; } } else { // Otherwise got to char 76 // Don't insert '=\n' if end of string or next char is already \n: if ((i === (str.length - 1)) || (str[i+1] === '\n')) { out += str[i]; } else { out += '=\n' + str[i]; cur_length = 1; } } } return out; }; exports.node_min = function (min, cur) { var wants = min.split('.'); var has = (cur || process.version.substring(1)).split('.'); for (var i=0; i<=3; i++) { // note use of unary + for fast type conversion to num if (+has[i] > +wants[i]) { return true; } if (+has[i] < +wants[i]) { return false; } } // they're identical return true; }; exports.existsSync = require(exports.node_min('0.8') ? 'fs' : 'path').existsSync; exports.indexOfLF = function (buf, maxlength) { for (var i=0; i<buf.length; i++) { if (maxlength && (i === maxlength)) break; if (buf[i] === 0x0a) return i; } return -1; }; exports.prettySize = function (size) { if (size === 0 || !size) return 0; var i = Math.floor(Math.log(size)/Math.log(1024)); var units = ['B', 'kB', 'MB', 'GB', 'TB']; return (size/Math.pow(1024,i)).toFixed(2) * 1 + '' + units[i]; }; exports.valid_regexes = function (list, file) { // list: an array of regexes. file: the file name containing the regex list var valid = []; for (var i=0; i<list.length; i++) { try { new RegExp(list[i]); } catch (e) { require('./logger') .logerror("invalid regex in " + file + ", " + list[i]); continue; } valid.push(list[i]); } return valid; // returns a list of valid regexes }; exports.regexp_escape = function(text) { return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); }; exports.base64 = function (str) { return new Buffer(str, "UTF-8").toString("base64"); }; exports.unbase64 = function (str) { return new Buffer(str, "base64").toString("UTF-8"); }; // Fisher-Yates shuffle // http://bost.ocks.org/mike/shuffle/ exports.shuffle = function(array) { var m = array.length, t, i; // While there remain elements to shuffle… while (m) { // Pick a remaining element… i = Math.floor(Math.random() * m--); // And swap it with the current element. t = array[m]; array[m] = array[i]; array[i] = t; } return array; }; exports.elapsed = function (start, decimal_places) { var diff = (Date.now() - start) / 1000; // in seconds if (decimal_places === undefined) { decimal_places = diff > 5 ? 0 : diff > 2 ? 1 : 2; } else { decimal_places = parseInt(decimal_places); if (isNaN(decimal_places)) { decimal_places = 2; } } return diff.toFixed(decimal_places); }; exports.wildcard_to_regexp = function (str) { return str .replace(/[-\[\]\/{}()*+?.,\\^$|#\s]/g, "\\$&") .replace('\\*', '.*') .replace('\\?', '.') + '$'; };
"use strict"; /*! * Copyright 2016 The ANTLR Project. All rights reserved. * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. */ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.BasicBlockStartState = void 0; // ConvertTo-TS run at 2016-10-04T11:26:27.7669801-07:00 const ATNStateType_1 = require("./ATNStateType"); const BlockStartState_1 = require("./BlockStartState"); const Decorators_1 = require("../Decorators"); /** * * @author Sam Harwell */ class BasicBlockStartState extends BlockStartState_1.BlockStartState { get stateType() { return ATNStateType_1.ATNStateType.BLOCK_START; } } __decorate([ Decorators_1.Override ], BasicBlockStartState.prototype, "stateType", null); exports.BasicBlockStartState = BasicBlockStartState; //# sourceMappingURL=BasicBlockStartState.js.map
/*! jQuery UI - v1.10.3 - 2013-09-04 * http://jqueryui.com * Copyright 2013 jQuery Foundation and other contributors; Licensed MIT */ jQuery(function(e){e.datepicker.regional.sk={closeText:"Zavrieť",prevText:"&#x3C;Predchádzajúci",nextText:"Nasledujúci&#x3E;",currentText:"Dnes",monthNames:["január","február","marec","apríl","máj","jún","júl","august","september","október","november","december"],monthNamesShort:["Jan","Feb","Mar","Apr","Máj","Jún","Júl","Aug","Sep","Okt","Nov","Dec"],dayNames:["nedeľa","pondelok","utorok","streda","štvrtok","piatok","sobota"],dayNamesShort:["Ned","Pon","Uto","Str","Štv","Pia","Sob"],dayNamesMin:["Ne","Po","Ut","St","Št","Pia","So"],weekHeader:"Ty",dateFormat:"dd.mm.yy",firstDay:1,isRTL:!1,showMonthAfterYear:!1,yearSuffix:""},e.datepicker.setDefaults(e.datepicker.regional.sk)});
// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var tape = require('tape'); var zlib = require('../'); tape('zero byte', function(t) { t.plan(2); var gz = zlib.Gzip() var emptyBuffer = new Buffer(0); var received = 0; gz.on('data', function(c) { received += c.length; }); gz.on('end', function() { t.equal(received, 20); }); gz.on('finish', function() { t.ok(true); }); gz.write(emptyBuffer); gz.end(); });
/** * $Id: learning_path_item.js 216 2009-11-13 14:08:06Z kariboe $ * @package application.lib.weblcms.tool.learning_path.javascript */ /** * @author Sven Vanpoucke */ (function($) { $(window).bind('beforeunload', function(e) { var ajaxUri = getPath('WEB_PATH') + 'index.php'; var parameters = { 'application' : trackerContext, 'go' : 'leave_item', 'tracker_id' : trackerId }; var response = $.ajax({ type : "POST", url : ajaxUri, data : parameters, async : false }); }); })(jQuery);
// Flags: --expose-internals 'use strict'; const common = require('../common'); if (!common.hasCrypto) common.skip('missing crypto'); const fixtures = require('../common/fixtures'); // Test --trace-tls CLI flag. const assert = require('assert'); const { fork } = require('child_process'); if (process.argv[2] === 'test') return test(); const binding = require('internal/test/binding').internalBinding; if (!binding('tls_wrap').HAVE_SSL_TRACE) return common.skip('no SSL_trace() compiled into openssl'); const child = fork(__filename, ['test'], { silent: true, execArgv: ['--trace-tls'] }); let stdout = ''; let stderr = ''; child.stdout.setEncoding('utf8'); child.stderr.setEncoding('utf8'); child.stdout.on('data', (data) => stdout += data); child.stderr.on('data', (data) => stderr += data); child.on('close', common.mustCall((code, signal) => { // For debugging and observation of actual trace output. console.log(stderr); assert.strictEqual(code, 0); assert.strictEqual(signal, null); assert.strictEqual(stdout.trim(), ''); assert(/Warning: Enabling --trace-tls can expose sensitive/.test(stderr)); assert(/Sent Record/.test(stderr)); })); function test() { const { connect, keys } = require(fixtures.path('tls-connect')); connect({ client: { checkServerIdentity: (servername, cert) => { }, ca: `${keys.agent1.cert}\n${keys.agent6.ca}`, }, server: { cert: keys.agent6.cert, key: keys.agent6.key }, }, common.mustCall((err, pair, cleanup) => { if (pair.server.err) { console.trace('server', pair.server.err); } if (pair.client.err) { console.trace('client', pair.client.err); } assert.ifError(pair.server.err); assert.ifError(pair.client.err); return cleanup(); })); }
'use strict'; var fs = require('fs'); var Promise = require('../ext/promise'); var readFile = Promise.denodeify(fs.readFile); var lstat = Promise.denodeify(fs.stat); var chalk = require('chalk'); var EditFileDiff = require('./edit-file-diff'); var EOL = require('os').EOL; var isBinaryFile = require('isbinaryfile').sync; var canEdit = require('../utilities/open-editor').canEdit; function processTemplate(content, context) { var options = { evaluate: /<%([\s\S]+?)%>/g, interpolate: /<%=([\s\S]+?)%>/g, escape: /<%-([\s\S]+?)%>/g }; return require('lodash.template')(content, options)(context); } function diffHighlight(line) { if (line[0] === '+') { return chalk.green(line); } else if (line[0] === '-') { return chalk.red(line); } else if (line.match(/^@@/)) { return chalk.cyan(line); } else { return line; } } FileInfo.prototype.confirmOverwrite = function(path) { var promptOptions = { type: 'expand', name: 'answer', default: false, message: chalk.red('Overwrite') + ' ' + path + '?', choices: [ { key: 'y', name: 'Yes, overwrite', value: 'overwrite' }, { key: 'n', name: 'No, skip', value: 'skip' } ] }; var outputPathIsFile = false; try { outputPathIsFile = fs.statSync(this.outputPath).isFile(); } catch (err) { /* ignore */ } var canDiff = ( !isBinaryFile(this.inputPath) && ( !outputPathIsFile || !isBinaryFile(this.outputPath) ) ); if (canDiff) { promptOptions.choices.push({ key: 'd', name: 'Diff', value: 'diff' }); if (canEdit()) { promptOptions.choices.push({ key: 'e', name: 'Edit', value: 'edit' }); } } return this.ui.prompt(promptOptions) .then(function(response) { return response.answer; }); }; FileInfo.prototype.displayDiff = function() { var info = this, jsdiff = require('diff'); return Promise.hash({ input: this.render(), output: readFile(info.outputPath) }).then(function(result) { var diff = jsdiff.createPatch( info.outputPath, result.output.toString(), result.input ); var lines = diff.split('\n'); for (var i = 0; i < lines.length; i++) { info.ui.write( diffHighlight(lines[i] + EOL) ); } }); }; function FileInfo(options) { this.action = options.action; this.outputBasePath = options.outputBasePath; this.outputPath = options.outputPath; this.displayPath = options.displayPath; this.inputPath = options.inputPath; this.templateVariables = options.templateVariables; this.ui = options.ui; } FileInfo.prototype.render = function() { var path = this.inputPath, context = this.templateVariables; if (!this.rendered) { this.rendered = readFile(path).then(function(content) { return lstat(path).then(function(fileStat) { if (isBinaryFile(content, fileStat.size)) { return content; } else { try { return processTemplate(content.toString(), context); } catch (err) { err.message += ' (Error in blueprint template: ' + path + ')'; throw err; } } }); }); } return this.rendered; }; FileInfo.prototype.checkForConflict = function() { return new Promise(function (resolve, reject) { fs.exists(this.outputPath, function (doesExist, error) { if (error) { reject(error); return; } var result; if (doesExist) { result = Promise.hash({ input: this.render(), output: readFile(this.outputPath) }).then(function(result) { var type; if (result.input.toString() === result.output.toString()) { type = 'identical'; } else { type = 'confirm'; } return type; }.bind(this)); } else { result = 'none'; } resolve(result); }.bind(this)); }.bind(this)); }; FileInfo.prototype.confirmOverwriteTask = function() { var info = this; return function() { return new Promise(function(resolve, reject) { function doConfirm() { info.confirmOverwrite(info.displayPath).then(function(action) { if (action === 'diff') { info.displayDiff().then(doConfirm, reject); } else if (action === 'edit') { var editFileDiff = new EditFileDiff({info: info}); editFileDiff.edit().then(function() { info.action = action; resolve(info); }).catch(function() { doConfirm() .finally(function() { resolve(info); }); }); } else { info.action = action; resolve(info); } }, reject); } doConfirm(); }); }.bind(this); }; module.exports = FileInfo;
/** @license React v16.8.2 * react-dom-unstable-fizz.node.production.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict';function d(a,b){var c="<"+a+">";"string"===typeof b.children&&(c+=b.children);return Buffer.from(c+("</"+a+">"),"utf8")}var e="function"===typeof Symbol&&Symbol.for?Symbol.for("react.element"):60103;function f(a){var b=a.destination,c=a.completedChunks;a.completedChunks=[];b.cork();try{for(a=0;a<c.length;a++)b.write(c[a])}finally{b.uncork()}b.end()} function g(a){a.flowing=!0;setImmediate(function(){var b=a.children;a.children=null;if(!b||b.$$typeof===e){var c=b.type;b=b.props;"string"===typeof c&&(a.completedChunks.push(d(c,b)),a.flowing&&f(a),c=a.destination,"function"===typeof c.flush&&c.flush())}})}function h(a,b){return function(){b.flowing=!1;f(b)}}var k={pipeToNodeWritable:function(a,b){a={destination:b,children:a,completedChunks:[],flowing:!1};b.on("drain",h(b,a));g(a)}},l={default:k},m=l&&k||l;module.exports=m.default||m;
!function(){function t(t){return function(e,i){e=d3.hsl(e),i=d3.hsl(i);var r=(e.h+120)*a,h=(i.h+120)*a-r,s=e.s,l=i.s-s,o=e.l,u=i.l-o;return isNaN(l)&&(l=0,s=isNaN(s)?i.s:s),isNaN(h)&&(h=0,r=isNaN(r)?i.h:r),function(a){var e=r+h*a,i=Math.pow(o+u*a,t),c=(s+l*a)*i*(1-i);return"#"+n(i+c*(-.14861*Math.cos(e)+1.78277*Math.sin(e)))+n(i+c*(-.29227*Math.cos(e)-.90649*Math.sin(e)))+n(i+c*1.97294*Math.cos(e))}}}function n(t){var n=(t=0>=t?0:t>=1?255:0|255*t).toString(16);return 16>t?"0"+n:n}var a=Math.PI/180;d3.scale.cubehelix=function(){return d3.scale.linear().range([d3.hsl(300,.5,0),d3.hsl(-240,.5,1)]).interpolate(d3.interpolateCubehelix)},d3.interpolateCubehelix=t(1),d3.interpolateCubehelix.gamma=t}();
export * as ns from 'mod'; export v from 'mod'; export a, * as b from 'mod'; export c, { foo } from 'mod'; export * as d, { bar } from 'mod'; export { fooooooooooooooooooooooooooooooooooooooooooooooooo } from "fooooooooooooooooooooooooooooo"; export Bar, { barrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr } from "barrrrrrrrrrrrrrrrrrrrrrrrrrrr"; export { foooooooooooooooooooooooooooooooooooooooooooooo, fooooooooooooooooooooooooooooooooooooooooooooooo } from "fooooooooooooooooooooooooooooo";
import * as THREE from 'three'; import { UIRow, UIText, UIInteger, UINumber } from './libs/ui.js'; import { SetGeometryCommand } from './commands/SetGeometryCommand.js'; function GeometryParametersPanel( editor, object ) { const strings = editor.strings; const signals = editor.signals; const container = new UIRow(); const geometry = object.geometry; const parameters = geometry.parameters; // radius const radiusRow = new UIRow(); const radius = new UINumber( parameters.radius ).onChange( update ); radiusRow.add( new UIText( strings.getKey( 'sidebar/geometry/tetrahedron_geometry/radius' ) ).setWidth( '90px' ) ); radiusRow.add( radius ); container.add( radiusRow ); // detail const detailRow = new UIRow(); const detail = new UIInteger( parameters.detail ).setRange( 0, Infinity ).onChange( update ); detailRow.add( new UIText( strings.getKey( 'sidebar/geometry/tetrahedron_geometry/detail' ) ).setWidth( '90px' ) ); detailRow.add( detail ); container.add( detailRow ); // function update() { editor.execute( new SetGeometryCommand( editor, object, new THREE.TetrahedronGeometry( radius.getValue(), detail.getValue() ) ) ); signals.objectChanged.dispatch( object ); } return container; } export { GeometryParametersPanel };
var Utils = require("../../utils") , sqlite3 = require('sqlite3').verbose() , Query = require("./query") module.exports = (function() { var ConnectorManager = function(sequelize) { this.sequelize = sequelize this.database = db = new sqlite3.Database(sequelize.options.storage || ':memory:', function(err) { if(!err && sequelize.options.foreignKeys !== false) { // Make it possible to define and use foreign key constraints unless // explicitly disallowed. It's still opt-in per relation db.run('PRAGMA FOREIGN_KEYS=ON') } }) } Utils._.extend(ConnectorManager.prototype, require("../connector-manager").prototype) ConnectorManager.prototype.query = function(sql, callee, options) { return new Query(this.database, this.sequelize, callee, options).run(sql) } return ConnectorManager })()
//------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. //------------------------------------------------------------------------------------------------------- var a = []; for(var i = 0; i < 1024*500*10; ++i) a[i] = i;
/*! * jQuery JavaScript Library v2.0.1 -sizzle,-css,-event-alias,-ajax,-ajax/script,-ajax/jsonp,-ajax/xhr,-effects,-offset,-dimensions * http://jquery.com/ * * Includes Sizzle.js * http://sizzlejs.com/ * * Copyright 2005, 2013 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2013-05-27T00:57Z */ (function( window, undefined ) { // Can't do this because several apps including ASP.NET trace // the stack via arguments.caller.callee and Firefox dies if // you try to trace through "use strict" call chains. (#13335) // Support: Firefox 18+ //"use strict"; var // A central reference to the root jQuery(document) rootjQuery, // The deferred used on DOM ready readyList, // Support: IE9 // For `typeof xmlNode.method` instead of `xmlNode.method !== undefined` core_strundefined = typeof undefined, // Use the correct document accordingly with window argument (sandbox) location = window.location, document = window.document, docElem = document.documentElement, // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$, // [[Class]] -> type pairs class2type = {}, // List of deleted data cache ids, so we can reuse them core_deletedIds = [], core_version = "2.0.1 -sizzle,-css,-event-alias,-ajax,-ajax/script,-ajax/jsonp,-ajax/xhr,-effects,-offset,-dimensions", // Save a reference to some core methods core_concat = core_deletedIds.concat, core_push = core_deletedIds.push, core_slice = core_deletedIds.slice, core_indexOf = core_deletedIds.indexOf, core_toString = class2type.toString, core_hasOwn = class2type.hasOwnProperty, core_trim = core_version.trim, // Define a local copy of jQuery jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context, rootjQuery ); }, // Used for matching numbers core_pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source, // Used for splitting on whitespace core_rnotwhite = /\S+/g, // A simple way to check for HTML strings // Prioritize #id over <tag> to avoid XSS via location.hash (#9521) // Strict HTML recognition (#11290: must start with <) rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/, // Match a standalone tag rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/, // Matches dashed string for camelizing rmsPrefix = /^-ms-/, rdashAlpha = /-([\da-z])/gi, // Used by jQuery.camelCase as callback to replace() fcamelCase = function( all, letter ) { return letter.toUpperCase(); }, // The ready event handler and self cleanup method completed = function() { document.removeEventListener( "DOMContentLoaded", completed, false ); window.removeEventListener( "load", completed, false ); jQuery.ready(); }; jQuery.fn = jQuery.prototype = { // The current version of jQuery being used jquery: core_version, constructor: jQuery, init: function( selector, context, rootjQuery ) { var match, elem; // HANDLE: $(""), $(null), $(undefined), $(false) if ( !selector ) { return this; } // Handle HTML strings if ( typeof selector === "string" ) { if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [ null, selector, null ]; } else { match = rquickExpr.exec( selector ); } // Match html or make sure no context is specified for #id if ( match && (match[1] || !context) ) { // HANDLE: $(html) -> $(array) if ( match[1] ) { context = context instanceof jQuery ? context[0] : context; // scripts is true for back-compat jQuery.merge( this, jQuery.parseHTML( match[1], context && context.nodeType ? context.ownerDocument || context : document, true ) ); // HANDLE: $(html, props) if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { for ( match in context ) { // Properties of context are called as methods if possible if ( jQuery.isFunction( this[ match ] ) ) { this[ match ]( context[ match ] ); // ...and otherwise set as attributes } else { this.attr( match, context[ match ] ); } } } return this; // HANDLE: $(#id) } else { elem = document.getElementById( match[2] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Inject the element directly into the jQuery object this.length = 1; this[0] = elem; } this.context = document; this.selector = selector; return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return ( context || rootjQuery ).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } // HANDLE: $(DOMElement) } else if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return rootjQuery.ready( selector ); } if ( selector.selector !== undefined ) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }, // Start with an empty selector selector: "", // The default length of a jQuery object is 0 length: 0, toArray: function() { return core_slice.call( this ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num == null ? // Return a 'clean' array this.toArray() : // Return just the object ( num < 0 ? this[ this.length + num ] : this[ num ] ); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems ) { // Build a new jQuery matched element set var ret = jQuery.merge( this.constructor(), elems ); // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. // (You can seed the arguments with an array of args, but this is // only used internally.) each: function( callback, args ) { return jQuery.each( this, callback, args ); }, ready: function( fn ) { // Add the callback jQuery.ready.promise().done( fn ); return this; }, slice: function() { return this.pushStack( core_slice.apply( this, arguments ) ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, eq: function( i ) { var len = this.length, j = +i + ( i < 0 ? len : 0 ); return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] ); }, map: function( callback ) { return this.pushStack( jQuery.map(this, function( elem, i ) { return callback.call( elem, i, elem ); })); }, end: function() { return this.prevObject || this.constructor(null); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: core_push, sort: [].sort, splice: [].splice }; // Give the init function the jQuery prototype for later instantiation jQuery.fn.init.prototype = jQuery.fn; jQuery.extend = jQuery.fn.extend = function() { var options, name, src, copy, copyIsArray, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction(target) ) { target = {}; } // extend jQuery itself if only one argument is passed if ( length === i ) { target = this; --i; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && jQuery.isArray(src) ? src : []; } else { clone = src && jQuery.isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend({ // Unique for each copy of jQuery on the page expando: "jQuery" + ( core_version + Math.random() ).replace( /\D/g, "" ), noConflict: function( deep ) { if ( window.$ === jQuery ) { window.$ = _$; } if ( deep && window.jQuery === jQuery ) { window.jQuery = _jQuery; } return jQuery; }, // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Hold (or release) the ready event holdReady: function( hold ) { if ( hold ) { jQuery.readyWait++; } else { jQuery.ready( true ); } }, // Handle when the DOM is ready ready: function( wait ) { // Abort if there are pending holds or we're already ready if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { return; } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.resolveWith( document, [ jQuery ] ); // Trigger any bound ready events if ( jQuery.fn.trigger ) { jQuery( document ).trigger("ready").off("ready"); } }, // See test/unit/core.js for details concerning isFunction. // Since version 1.3, DOM methods and functions like alert // aren't supported. They return false on IE (#2968). isFunction: function( obj ) { return jQuery.type(obj) === "function"; }, isArray: Array.isArray, isWindow: function( obj ) { return obj != null && obj === obj.window; }, isNumeric: function( obj ) { return !isNaN( parseFloat(obj) ) && isFinite( obj ); }, type: function( obj ) { if ( obj == null ) { return String( obj ); } // Support: Safari <= 5.1 (functionish RegExp) return typeof obj === "object" || typeof obj === "function" ? class2type[ core_toString.call(obj) ] || "object" : typeof obj; }, isPlainObject: function( obj ) { // Not plain objects: // - Any object or value whose internal [[Class]] property is not "[object Object]" // - DOM nodes // - window if ( jQuery.type( obj ) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { return false; } // Support: Firefox <20 // The try/catch suppresses exceptions thrown when attempting to access // the "constructor" property of certain host objects, ie. |window.location| // https://bugzilla.mozilla.org/show_bug.cgi?id=814622 try { if ( obj.constructor && !core_hasOwn.call( obj.constructor.prototype, "isPrototypeOf" ) ) { return false; } } catch ( e ) { return false; } // If the function hasn't returned already, we're confident that // |obj| is a plain object, created by {} or constructed with new Object return true; }, isEmptyObject: function( obj ) { var name; for ( name in obj ) { return false; } return true; }, error: function( msg ) { throw new Error( msg ); }, // data: string of html // context (optional): If specified, the fragment will be created in this context, defaults to document // keepScripts (optional): If true, will include scripts passed in the html string parseHTML: function( data, context, keepScripts ) { if ( !data || typeof data !== "string" ) { return null; } if ( typeof context === "boolean" ) { keepScripts = context; context = false; } context = context || document; var parsed = rsingleTag.exec( data ), scripts = !keepScripts && []; // Single tag if ( parsed ) { return [ context.createElement( parsed[1] ) ]; } parsed = jQuery.buildFragment( [ data ], context, scripts ); if ( scripts ) { jQuery( scripts ).remove(); } return jQuery.merge( [], parsed.childNodes ); }, parseJSON: JSON.parse, // Cross-browser xml parsing parseXML: function( data ) { var xml, tmp; if ( !data || typeof data !== "string" ) { return null; } // Support: IE9 try { tmp = new DOMParser(); xml = tmp.parseFromString( data , "text/xml" ); } catch ( e ) { xml = undefined; } if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) { jQuery.error( "Invalid XML: " + data ); } return xml; }, noop: function() {}, // Evaluates a script in a global context globalEval: function( code ) { var script, indirect = eval; code = jQuery.trim( code ); if ( code ) { // If the code includes a valid, prologue position // strict mode pragma, execute code by injecting a // script tag into the document. if ( code.indexOf("use strict") === 1 ) { script = document.createElement("script"); script.text = code; document.head.appendChild( script ).parentNode.removeChild( script ); } else { // Otherwise, avoid the DOM node creation, insertion // and removal by using an indirect global eval indirect( code ); } } }, // Convert dashed to camelCase; used by the css and data modules // Microsoft forgot to hump their vendor prefix (#9572) camelCase: function( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); }, // args is for internal usage only each: function( obj, callback, args ) { var value, i = 0, length = obj.length, isArray = isArraylike( obj ); if ( args ) { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } } return obj; }, trim: function( text ) { return text == null ? "" : core_trim.call( text ); }, // results is for internal usage only makeArray: function( arr, results ) { var ret = results || []; if ( arr != null ) { if ( isArraylike( Object(arr) ) ) { jQuery.merge( ret, typeof arr === "string" ? [ arr ] : arr ); } else { core_push.call( ret, arr ); } } return ret; }, inArray: function( elem, arr, i ) { return arr == null ? -1 : core_indexOf.call( arr, elem, i ); }, merge: function( first, second ) { var l = second.length, i = first.length, j = 0; if ( typeof l === "number" ) { for ( ; j < l; j++ ) { first[ i++ ] = second[ j ]; } } else { while ( second[j] !== undefined ) { first[ i++ ] = second[ j++ ]; } } first.length = i; return first; }, grep: function( elems, callback, inv ) { var retVal, ret = [], i = 0, length = elems.length; inv = !!inv; // Go through the array, only saving the items // that pass the validator function for ( ; i < length; i++ ) { retVal = !!callback( elems[ i ], i ); if ( inv !== retVal ) { ret.push( elems[ i ] ); } } return ret; }, // arg is for internal usage only map: function( elems, callback, arg ) { var value, i = 0, length = elems.length, isArray = isArraylike( elems ), ret = []; // Go through the array, translating each of the items to their if ( isArray ) { for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } // Go through every key on the object, } else { for ( i in elems ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } } // Flatten any nested arrays return core_concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, // Bind a function to a context, optionally partially applying any // arguments. proxy: function( fn, context ) { var tmp, args, proxy; if ( typeof context === "string" ) { tmp = fn[ context ]; context = fn; fn = tmp; } // Quick check to determine if target is callable, in the spec // this throws a TypeError, but we will just return undefined. if ( !jQuery.isFunction( fn ) ) { return undefined; } // Simulated bind args = core_slice.call( arguments, 2 ); proxy = function() { return fn.apply( context || this, args.concat( core_slice.call( arguments ) ) ); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || jQuery.guid++; return proxy; }, // Multifunctional method to get and set values of a collection // The value/s can optionally be executed if it's a function access: function( elems, fn, key, value, chainable, emptyGet, raw ) { var i = 0, length = elems.length, bulk = key == null; // Sets many values if ( jQuery.type( key ) === "object" ) { chainable = true; for ( i in key ) { jQuery.access( elems, fn, i, key[i], true, emptyGet, raw ); } // Sets one value } else if ( value !== undefined ) { chainable = true; if ( !jQuery.isFunction( value ) ) { raw = true; } if ( bulk ) { // Bulk operations run against the entire set if ( raw ) { fn.call( elems, value ); fn = null; // ...except when executing function values } else { bulk = fn; fn = function( elem, key, value ) { return bulk.call( jQuery( elem ), value ); }; } } if ( fn ) { for ( ; i < length; i++ ) { fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) ); } } } return chainable ? elems : // Gets bulk ? fn.call( elems ) : length ? fn( elems[0], key ) : emptyGet; }, now: Date.now, // A method for quickly swapping in/out CSS properties to get correct calculations. // Note: this method belongs to the css module but it's needed here for the support module. // If support gets modularized, this method should be moved back to the css module. swap: function( elem, options, callback, args ) { var ret, name, old = {}; // Remember the old values, and insert the new ones for ( name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } ret = callback.apply( elem, args || [] ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } return ret; } }); jQuery.ready.promise = function( obj ) { if ( !readyList ) { readyList = jQuery.Deferred(); // Catch cases where $(document).ready() is called after the browser event has already occurred. // we once tried to use readyState "interactive" here, but it caused issues like the one // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 if ( document.readyState === "complete" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready setTimeout( jQuery.ready ); } else { // Use the handy event callback document.addEventListener( "DOMContentLoaded", completed, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", completed, false ); } } return readyList.promise( obj ); }; // Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); function isArraylike( obj ) { var length = obj.length, type = jQuery.type( obj ); if ( jQuery.isWindow( obj ) ) { return false; } if ( obj.nodeType === 1 && length ) { return true; } return type === "array" || type !== "function" && ( length === 0 || typeof length === "number" && length > 0 && ( length - 1 ) in obj ); } // All jQuery objects should point back to these rootjQuery = jQuery(document); /* * Optional (non-Sizzle) selector module for custom builds. * * Note that this DOES NOT SUPPORT many documented jQuery * features in exchange for its smaller size: * * Attribute not equal selector * Positional selectors (:first; :eq(n); :odd; etc.) * Type selectors (:input; :checkbox; :button; etc.) * State-based selectors (:animated; :visible; :hidden; etc.) * :has(selector) * :not(complex selector) * custom selectors via Sizzle extensions * Leading combinators (e.g., $collection.find("> *")) * Reliable functionality on XML fragments * Requiring all parts of a selector to match elements under context * (e.g., $div.find("div > *") now matches children of $div) * Matching against non-elements * Reliable sorting of disconnected nodes * querySelectorAll bug fixes (e.g., unreliable :focus on WebKit) * * If any of these are unacceptable tradeoffs, either use Sizzle or * customize this stub for the project's specific needs. */ var selector_hasDuplicate, matches = docElem.webkitMatchesSelector || docElem.mozMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector, selector_sortOrder = function( a, b ) { // Flag for duplicate removal if ( a === b ) { selector_hasDuplicate = true; return 0; } var compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b ); if ( compare ) { // Disconnected nodes if ( compare & 1 ) { // Choose the first element that is related to our document if ( a === document || jQuery.contains(document, a) ) { return -1; } if ( b === document || jQuery.contains(document, b) ) { return 1; } // Maintain original order return 0; } return compare & 4 ? -1 : 1; } // Not directly comparable, sort on existence of method return a.compareDocumentPosition ? -1 : 1; }; jQuery.extend({ find: function( selector, context, results, seed ) { var elem, nodeType, i = 0; results = results || []; context = context || document; // Same basic safeguard as Sizzle if ( !selector || typeof selector !== "string" ) { return results; } // Early return if context is not an element or document if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) { return []; } if ( seed ) { while ( (elem = seed[i++]) ) { if ( jQuery.find.matchesSelector(elem, selector) ) { results.push( elem ); } } } else { jQuery.merge( results, context.querySelectorAll(selector) ); } return results; }, unique: function( results ) { var elem, duplicates = [], i = 0, j = 0; selector_hasDuplicate = false; results.sort( selector_sortOrder ); if ( selector_hasDuplicate ) { while ( (elem = results[i++]) ) { if ( elem === results[ i ] ) { j = duplicates.push( i ); } } while ( j-- ) { results.splice( duplicates[ j ], 1 ); } } return results; }, text: function( elem ) { var node, ret = "", i = 0, nodeType = elem.nodeType; if ( !nodeType ) { // If no nodeType, this is expected to be an array while ( (node = elem[i++]) ) { // Do not traverse comment nodes ret += jQuery.text( node ); } } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent for elements return elem.textContent; } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } // Do not include comment or processing instruction nodes return ret; }, contains: function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && adown.contains(bup) ); }, isXMLDoc: function( elem ) { return (elem.ownerDocument || elem).documentElement.nodeName !== "HTML"; }, expr: { attrHandle: {}, match: { bool: /^(?:checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped)$/i, needsContext: /^[\x20\t\r\n\f]*[>+~]/ } } }); jQuery.extend( jQuery.find, { matches: function( expr, elements ) { return jQuery.find( expr, null, null, elements ); }, matchesSelector: function( elem, expr ) { return matches.call( elem, expr ); }, attr: function( elem, name ) { return elem.getAttribute( name ); } }); // String to Object options format cache var optionsCache = {}; // Convert String-formatted options into Object-formatted ones and store in cache function createOptions( options ) { var object = optionsCache[ options ] = {}; jQuery.each( options.match( core_rnotwhite ) || [], function( _, flag ) { object[ flag ] = true; }); return object; } /* * Create a callback list using the following parameters: * * options: an optional list of space-separated options that will change how * the callback list behaves or a more traditional option object * * By default a callback list will act like an event callback list and can be * "fired" multiple times. * * Possible options: * * once: will ensure the callback list can only be fired once (like a Deferred) * * memory: will keep track of previous values and will call any callback added * after the list has been fired right away with the latest "memorized" * values (like a Deferred) * * unique: will ensure a callback can only be added once (no duplicate in the list) * * stopOnFalse: interrupt callings when a callback returns false * */ jQuery.Callbacks = function( options ) { // Convert options from String-formatted to Object-formatted if needed // (we check in cache first) options = typeof options === "string" ? ( optionsCache[ options ] || createOptions( options ) ) : jQuery.extend( {}, options ); var // Last fire value (for non-forgettable lists) memory, // Flag to know if list was already fired fired, // Flag to know if list is currently firing firing, // First callback to fire (used internally by add and fireWith) firingStart, // End of the loop when firing firingLength, // Index of currently firing callback (modified by remove if needed) firingIndex, // Actual callback list list = [], // Stack of fire calls for repeatable lists stack = !options.once && [], // Fire callbacks fire = function( data ) { memory = options.memory && data; fired = true; firingIndex = firingStart || 0; firingStart = 0; firingLength = list.length; firing = true; for ( ; list && firingIndex < firingLength; firingIndex++ ) { if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { memory = false; // To prevent further calls using add break; } } firing = false; if ( list ) { if ( stack ) { if ( stack.length ) { fire( stack.shift() ); } } else if ( memory ) { list = []; } else { self.disable(); } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { // First, we save the current length var start = list.length; (function add( args ) { jQuery.each( args, function( _, arg ) { var type = jQuery.type( arg ); if ( type === "function" ) { if ( !options.unique || !self.has( arg ) ) { list.push( arg ); } } else if ( arg && arg.length && type !== "string" ) { // Inspect recursively add( arg ); } }); })( arguments ); // Do we need to add the callbacks to the // current firing batch? if ( firing ) { firingLength = list.length; // With memory, if we're not firing then // we should call right away } else if ( memory ) { firingStart = start; fire( memory ); } } return this; }, // Remove a callback from the list remove: function() { if ( list ) { jQuery.each( arguments, function( _, arg ) { var index; while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { list.splice( index, 1 ); // Handle firing indexes if ( firing ) { if ( index <= firingLength ) { firingLength--; } if ( index <= firingIndex ) { firingIndex--; } } } }); } return this; }, // Check if a given callback is in the list. // If no argument is given, return whether or not list has callbacks attached. has: function( fn ) { return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length ); }, // Remove all callbacks from the list empty: function() { list = []; firingLength = 0; return this; }, // Have the list do nothing anymore disable: function() { list = stack = memory = undefined; return this; }, // Is it disabled? disabled: function() { return !list; }, // Lock the list in its current state lock: function() { stack = undefined; if ( !memory ) { self.disable(); } return this; }, // Is it locked? locked: function() { return !stack; }, // Call all callbacks with the given context and arguments fireWith: function( context, args ) { args = args || []; args = [ context, args.slice ? args.slice() : args ]; if ( list && ( !fired || stack ) ) { if ( firing ) { stack.push( args ); } else { fire( args ); } } return this; }, // Call all the callbacks with the given arguments fire: function() { self.fireWith( this, arguments ); return this; }, // To know if the callbacks have already been called at least once fired: function() { return !!fired; } }; return self; }; jQuery.extend({ Deferred: function( func ) { var tuples = [ // action, add listener, listener list, final state [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], [ "notify", "progress", jQuery.Callbacks("memory") ] ], state = "pending", promise = { state: function() { return state; }, always: function() { deferred.done( arguments ).fail( arguments ); return this; }, then: function( /* fnDone, fnFail, fnProgress */ ) { var fns = arguments; return jQuery.Deferred(function( newDefer ) { jQuery.each( tuples, function( i, tuple ) { var action = tuple[ 0 ], fn = jQuery.isFunction( fns[ i ] ) && fns[ i ]; // deferred[ done | fail | progress ] for forwarding actions to newDefer deferred[ tuple[1] ](function() { var returned = fn && fn.apply( this, arguments ); if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise() .done( newDefer.resolve ) .fail( newDefer.reject ) .progress( newDefer.notify ); } else { newDefer[ action + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments ); } }); }); fns = null; }).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { return obj != null ? jQuery.extend( obj, promise ) : promise; } }, deferred = {}; // Keep pipe for back-compat promise.pipe = promise.then; // Add list-specific methods jQuery.each( tuples, function( i, tuple ) { var list = tuple[ 2 ], stateString = tuple[ 3 ]; // promise[ done | fail | progress ] = list.add promise[ tuple[1] ] = list.add; // Handle state if ( stateString ) { list.add(function() { // state = [ resolved | rejected ] state = stateString; // [ reject_list | resolve_list ].disable; progress_list.lock }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); } // deferred[ resolve | reject | notify ] deferred[ tuple[0] ] = function() { deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments ); return this; }; deferred[ tuple[0] + "With" ] = list.fireWith; }); // Make the deferred a promise promise.promise( deferred ); // Call given func if any if ( func ) { func.call( deferred, deferred ); } // All done! return deferred; }, // Deferred helper when: function( subordinate /* , ..., subordinateN */ ) { var i = 0, resolveValues = core_slice.call( arguments ), length = resolveValues.length, // the count of uncompleted subordinates remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, // the master Deferred. If resolveValues consist of only a single Deferred, just use that. deferred = remaining === 1 ? subordinate : jQuery.Deferred(), // Update function for both resolve and progress values updateFunc = function( i, contexts, values ) { return function( value ) { contexts[ i ] = this; values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value; if( values === progressValues ) { deferred.notifyWith( contexts, values ); } else if ( !( --remaining ) ) { deferred.resolveWith( contexts, values ); } }; }, progressValues, progressContexts, resolveContexts; // add listeners to Deferred subordinates; treat others as resolved if ( length > 1 ) { progressValues = new Array( length ); progressContexts = new Array( length ); resolveContexts = new Array( length ); for ( ; i < length; i++ ) { if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { resolveValues[ i ].promise() .done( updateFunc( i, resolveContexts, resolveValues ) ) .fail( deferred.reject ) .progress( updateFunc( i, progressContexts, progressValues ) ); } else { --remaining; } } } // if we're not waiting on anything, resolve the master if ( !remaining ) { deferred.resolveWith( resolveContexts, resolveValues ); } return deferred.promise(); } }); jQuery.support = (function( support ) { var input = document.createElement("input"), fragment = document.createDocumentFragment(), div = document.createElement("div"), select = document.createElement("select"), opt = select.appendChild( document.createElement("option") ); // Finish early in limited environments if ( !input.type ) { return support; } input.type = "checkbox"; // Support: Safari 5.1, iOS 5.1, Android 4.x, Android 2.3 // Check the default checkbox/radio value ("" on old WebKit; "on" elsewhere) support.checkOn = input.value !== ""; // Must access the parent to make an option select properly // Support: IE9, IE10 support.optSelected = opt.selected; // Will be defined later support.reliableMarginRight = true; support.boxSizingReliable = true; support.pixelPosition = false; // Make sure checked status is properly cloned // Support: IE9, IE10 input.checked = true; support.noCloneChecked = input.cloneNode( true ).checked; // Make sure that the options inside disabled selects aren't marked as disabled // (WebKit marks them as disabled) select.disabled = true; support.optDisabled = !opt.disabled; // Check if an input maintains its value after becoming a radio // Support: IE9, IE10 input = document.createElement("input"); input.value = "t"; input.type = "radio"; support.radioValue = input.value === "t"; // #11217 - WebKit loses check when the name is after the checked attribute input.setAttribute( "checked", "t" ); input.setAttribute( "name", "t" ); fragment.appendChild( input ); // Support: Safari 5.1, Android 4.x, Android 2.3 // old WebKit doesn't clone checked state correctly in fragments support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; // Support: Firefox, Chrome, Safari // Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP) support.focusinBubbles = "onfocusin" in window; div.style.backgroundClip = "content-box"; div.cloneNode( true ).style.backgroundClip = ""; support.clearCloneStyle = div.style.backgroundClip === "content-box"; // Run tests that need a body at doc ready jQuery(function() { var container, marginDiv, // Support: Firefox, Android 2.3 (Prefixed box-sizing versions). divReset = "padding:0;margin:0;border:0;display:block;-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box", body = document.getElementsByTagName("body")[ 0 ]; if ( !body ) { // Return for frameset docs that don't have a body return; } container = document.createElement("div"); container.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px"; // Check box-sizing and margin behavior. body.appendChild( container ).appendChild( div ); div.innerHTML = ""; // Support: Firefox, Android 2.3 (Prefixed box-sizing versions). div.style.cssText = "-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%"; // Workaround failing boxSizing test due to offsetWidth returning wrong value // with some non-1 values of body zoom, ticket #13543 jQuery.swap( body, body.style.zoom != null ? { zoom: 1 } : {}, function() { support.boxSizing = div.offsetWidth === 4; }); // Use window.getComputedStyle because jsdom on node.js will break without it. if ( window.getComputedStyle ) { support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%"; support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px"; // Support: Android 2.3 // Check if div with explicit width and no margin-right incorrectly // gets computed margin-right based on width of container. (#3333) // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right marginDiv = div.appendChild( document.createElement("div") ); marginDiv.style.cssText = div.style.cssText = divReset; marginDiv.style.marginRight = marginDiv.style.width = "0"; div.style.width = "1px"; support.reliableMarginRight = !parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight ); } body.removeChild( container ); }); return support; })( {} ); /* Implementation Summary 1. Enforce API surface and semantic compatibility with 1.9.x branch 2. Improve the module's maintainability by reducing the storage paths to a single mechanism. 3. Use the same single mechanism to support "private" and "user" data. 4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData) 5. Avoid exposing implementation details on user objects (eg. expando properties) 6. Provide a clear path for implementation upgrade to WeakMap in 2014 */ var data_user, data_priv, rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/, rmultiDash = /([A-Z])/g; function Data() { // Support: Android < 4, // Old WebKit does not have Object.preventExtensions/freeze method, // return new empty object instead with no [[set]] accessor Object.defineProperty( this.cache = {}, 0, { get: function() { return {}; } }); this.expando = jQuery.expando + Math.random(); } Data.uid = 1; Data.accepts = function( owner ) { // Accepts only: // - Node // - Node.ELEMENT_NODE // - Node.DOCUMENT_NODE // - Object // - Any return owner.nodeType ? owner.nodeType === 1 || owner.nodeType === 9 : true; }; Data.prototype = { key: function( owner ) { // We can accept data for non-element nodes in modern browsers, // but we should not, see #8335. // Always return the key for a frozen object. if ( !Data.accepts( owner ) ) { return 0; } var descriptor = {}, // Check if the owner object already has a cache key unlock = owner[ this.expando ]; // If not, create one if ( !unlock ) { unlock = Data.uid++; // Secure it in a non-enumerable, non-writable property try { descriptor[ this.expando ] = { value: unlock }; Object.defineProperties( owner, descriptor ); // Support: Android < 4 // Fallback to a less secure definition } catch ( e ) { descriptor[ this.expando ] = unlock; jQuery.extend( owner, descriptor ); } } // Ensure the cache object if ( !this.cache[ unlock ] ) { this.cache[ unlock ] = {}; } return unlock; }, set: function( owner, data, value ) { var prop, // There may be an unlock assigned to this node, // if there is no entry for this "owner", create one inline // and set the unlock as though an owner entry had always existed unlock = this.key( owner ), cache = this.cache[ unlock ]; // Handle: [ owner, key, value ] args if ( typeof data === "string" ) { cache[ data ] = value; // Handle: [ owner, { properties } ] args } else { // Fresh assignments by object are shallow copied if ( jQuery.isEmptyObject( cache ) ) { jQuery.extend( this.cache[ unlock ], data ); // Otherwise, copy the properties one-by-one to the cache object } else { for ( prop in data ) { cache[ prop ] = data[ prop ]; } } } return cache; }, get: function( owner, key ) { // Either a valid cache is found, or will be created. // New caches will be created and the unlock returned, // allowing direct access to the newly created // empty data object. A valid owner object must be provided. var cache = this.cache[ this.key( owner ) ]; return key === undefined ? cache : cache[ key ]; }, access: function( owner, key, value ) { // In cases where either: // // 1. No key was specified // 2. A string key was specified, but no value provided // // Take the "read" path and allow the get method to determine // which value to return, respectively either: // // 1. The entire cache object // 2. The data stored at the key // if ( key === undefined || ((key && typeof key === "string") && value === undefined) ) { return this.get( owner, key ); } // [*]When the key is not a string, or both a key and value // are specified, set or extend (existing objects) with either: // // 1. An object of properties // 2. A key and value // this.set( owner, key, value ); // Since the "set" path can have two possible entry points // return the expected data based on which path was taken[*] return value !== undefined ? value : key; }, remove: function( owner, key ) { var i, name, camel, unlock = this.key( owner ), cache = this.cache[ unlock ]; if ( key === undefined ) { this.cache[ unlock ] = {}; } else { // Support array or space separated string of keys if ( jQuery.isArray( key ) ) { // If "name" is an array of keys... // When data is initially created, via ("key", "val") signature, // keys will be converted to camelCase. // Since there is no way to tell _how_ a key was added, remove // both plain key and camelCase key. #12786 // This will only penalize the array argument path. name = key.concat( key.map( jQuery.camelCase ) ); } else { camel = jQuery.camelCase( key ); // Try the string as a key before any manipulation if ( key in cache ) { name = [ key, camel ]; } else { // If a key with the spaces exists, use it. // Otherwise, create an array by matching non-whitespace name = camel; name = name in cache ? [ name ] : ( name.match( core_rnotwhite ) || [] ); } } i = name.length; while ( i-- ) { delete cache[ name[ i ] ]; } } }, hasData: function( owner ) { return !jQuery.isEmptyObject( this.cache[ owner[ this.expando ] ] || {} ); }, discard: function( owner ) { if ( owner[ this.expando ] ) { delete this.cache[ owner[ this.expando ] ]; } } }; // These may be used throughout the jQuery core codebase data_user = new Data(); data_priv = new Data(); jQuery.extend({ acceptData: Data.accepts, hasData: function( elem ) { return data_user.hasData( elem ) || data_priv.hasData( elem ); }, data: function( elem, name, data ) { return data_user.access( elem, name, data ); }, removeData: function( elem, name ) { data_user.remove( elem, name ); }, // TODO: Now that all calls to _data and _removeData have been replaced // with direct calls to data_priv methods, these can be deprecated. _data: function( elem, name, data ) { return data_priv.access( elem, name, data ); }, _removeData: function( elem, name ) { data_priv.remove( elem, name ); } }); jQuery.fn.extend({ data: function( key, value ) { var attrs, name, elem = this[ 0 ], i = 0, data = null; // Gets all values if ( key === undefined ) { if ( this.length ) { data = data_user.get( elem ); if ( elem.nodeType === 1 && !data_priv.get( elem, "hasDataAttrs" ) ) { attrs = elem.attributes; for ( ; i < attrs.length; i++ ) { name = attrs[ i ].name; if ( name.indexOf( "data-" ) === 0 ) { name = jQuery.camelCase( name.slice(5) ); dataAttr( elem, name, data[ name ] ); } } data_priv.set( elem, "hasDataAttrs", true ); } } return data; } // Sets multiple values if ( typeof key === "object" ) { return this.each(function() { data_user.set( this, key ); }); } return jQuery.access( this, function( value ) { var data, camelKey = jQuery.camelCase( key ); // The calling jQuery object (element matches) is not empty // (and therefore has an element appears at this[ 0 ]) and the // `value` parameter was not undefined. An empty jQuery object // will result in `undefined` for elem = this[ 0 ] which will // throw an exception if an attempt to read a data cache is made. if ( elem && value === undefined ) { // Attempt to get data from the cache // with the key as-is data = data_user.get( elem, key ); if ( data !== undefined ) { return data; } // Attempt to get data from the cache // with the key camelized data = data_user.get( elem, camelKey ); if ( data !== undefined ) { return data; } // Attempt to "discover" the data in // HTML5 custom data-* attrs data = dataAttr( elem, camelKey, undefined ); if ( data !== undefined ) { return data; } // We tried really hard, but the data doesn't exist. return; } // Set the data... this.each(function() { // First, attempt to store a copy or reference of any // data that might've been store with a camelCased key. var data = data_user.get( this, camelKey ); // For HTML5 data-* attribute interop, we have to // store property names with dashes in a camelCase form. // This might not apply to all properties...* data_user.set( this, camelKey, value ); // *... In the case of properties that might _actually_ // have dashes, we need to also store a copy of that // unchanged property. if ( key.indexOf("-") !== -1 && data !== undefined ) { data_user.set( this, key, value ); } }); }, null, value, arguments.length > 1, null, true ); }, removeData: function( key ) { return this.each(function() { data_user.remove( this, key ); }); } }); function dataAttr( elem, key, data ) { var name; // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : // Only convert to a number if it doesn't change the string +data + "" === data ? +data : rbrace.test( data ) ? JSON.parse( data ) : data; } catch( e ) {} // Make sure we set the data so it isn't changed later data_user.set( elem, key, data ); } else { data = undefined; } } return data; } jQuery.extend({ queue: function( elem, type, data ) { var queue; if ( elem ) { type = ( type || "fx" ) + "queue"; queue = data_priv.get( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !queue || jQuery.isArray( data ) ) { queue = data_priv.access( elem, type, jQuery.makeArray(data) ); } else { queue.push( data ); } } return queue || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), startLength = queue.length, fn = queue.shift(), hooks = jQuery._queueHooks( elem, type ), next = function() { jQuery.dequeue( elem, type ); }; // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); startLength--; } hooks.cur = fn; if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift( "inprogress" ); } // clear up the last queue stop function delete hooks.stop; fn.call( elem, next, hooks ); } if ( !startLength && hooks ) { hooks.empty.fire(); } }, // not intended for public consumption - generates a queueHooks object, or returns the current one _queueHooks: function( elem, type ) { var key = type + "queueHooks"; return data_priv.get( elem, key ) || data_priv.access( elem, key, { empty: jQuery.Callbacks("once memory").add(function() { data_priv.remove( elem, [ type + "queue", key ] ); }) }); } }); jQuery.fn.extend({ queue: function( type, data ) { var setter = 2; if ( typeof type !== "string" ) { data = type; type = "fx"; setter--; } if ( arguments.length < setter ) { return jQuery.queue( this[0], type ); } return data === undefined ? this : this.each(function() { var queue = jQuery.queue( this, type, data ); // ensure a hooks for this queue jQuery._queueHooks( this, type ); if ( type === "fx" && queue[0] !== "inprogress" ) { jQuery.dequeue( this, type ); } }); }, dequeue: function( type ) { return this.each(function() { jQuery.dequeue( this, type ); }); }, // Based off of the plugin by Clint Helfers, with permission. // http://blindsignals.com/index.php/2009/07/jquery-delay/ delay: function( time, type ) { time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; type = type || "fx"; return this.queue( type, function( next, hooks ) { var timeout = setTimeout( next, time ); hooks.stop = function() { clearTimeout( timeout ); }; }); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); }, // Get a promise resolved when queues of a certain type // are emptied (fx is the type by default) promise: function( type, obj ) { var tmp, count = 1, defer = jQuery.Deferred(), elements = this, i = this.length, resolve = function() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } }; if ( typeof type !== "string" ) { obj = type; type = undefined; } type = type || "fx"; while( i-- ) { tmp = data_priv.get( elements[ i ], type + "queueHooks" ); if ( tmp && tmp.empty ) { count++; tmp.empty.add( resolve ); } } resolve(); return defer.promise( obj ); } }); var nodeHook, boolHook, rclass = /[\t\r\n\f]/g, rreturn = /\r/g, rfocusable = /^(?:input|select|textarea|button)$/i; jQuery.fn.extend({ attr: function( name, value ) { return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 ); }, removeAttr: function( name ) { return this.each(function() { jQuery.removeAttr( this, name ); }); }, prop: function( name, value ) { return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 ); }, removeProp: function( name ) { return this.each(function() { delete this[ jQuery.propFix[ name ] || name ]; }); }, addClass: function( value ) { var classes, elem, cur, clazz, j, i = 0, len = this.length, proceed = typeof value === "string" && value; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).addClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { // The disjunction here is for better compressibility (see removeClass) classes = ( value || "" ).match( core_rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : " " ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { if ( cur.indexOf( " " + clazz + " " ) < 0 ) { cur += clazz + " "; } } elem.className = jQuery.trim( cur ); } } } return this; }, removeClass: function( value ) { var classes, elem, cur, clazz, j, i = 0, len = this.length, proceed = arguments.length === 0 || typeof value === "string" && value; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).removeClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { classes = ( value || "" ).match( core_rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; // This expression is here for better compressibility (see addClass) cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : "" ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { // Remove *all* instances while ( cur.indexOf( " " + clazz + " " ) >= 0 ) { cur = cur.replace( " " + clazz + " ", " " ); } } elem.className = value ? jQuery.trim( cur ) : ""; } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value, isBool = typeof stateVal === "boolean"; if ( jQuery.isFunction( value ) ) { return this.each(function( i ) { jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); }); } return this.each(function() { if ( type === "string" ) { // toggle individual class names var className, i = 0, self = jQuery( this ), state = stateVal, classNames = value.match( core_rnotwhite ) || []; while ( (className = classNames[ i++ ]) ) { // check each className given, space separated list state = isBool ? state : !self.hasClass( className ); self[ state ? "addClass" : "removeClass" ]( className ); } // Toggle whole class name } else if ( type === core_strundefined || type === "boolean" ) { if ( this.className ) { // store className if set data_priv.set( this, "__className__", this.className ); } // If the element has a class name or if we're passed "false", // then remove the whole classname (if there was one, the above saved it). // Otherwise bring back whatever was previously saved (if anything), // falling back to the empty string if nothing was stored. this.className = this.className || value === false ? "" : data_priv.get( this, "__className__" ) || ""; } }); }, hasClass: function( selector ) { var className = " " + selector + " ", i = 0, l = this.length; for ( ; i < l; i++ ) { if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) { return true; } } return false; }, val: function( value ) { var hooks, ret, isFunction, elem = this[0]; if ( !arguments.length ) { if ( elem ) { hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { return ret; } ret = elem.value; return typeof ret === "string" ? // handle most common string cases ret.replace(rreturn, "") : // handle cases where value is null/undef or number ret == null ? "" : ret; } return; } isFunction = jQuery.isFunction( value ); return this.each(function( i ) { var val; if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call( this, i, jQuery( this ).val() ); } else { val = value; } // Treat null/undefined as ""; convert numbers to string if ( val == null ) { val = ""; } else if ( typeof val === "number" ) { val += ""; } else if ( jQuery.isArray( val ) ) { val = jQuery.map(val, function ( value ) { return value == null ? "" : value + ""; }); } hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; // If set returns undefined, fall back to normal setting if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { this.value = val; } }); } }); jQuery.extend({ valHooks: { option: { get: function( elem ) { // attributes.value is undefined in Blackberry 4.7 but // uses .value. See #6932 var val = elem.attributes.value; return !val || val.specified ? elem.value : elem.text; } }, select: { get: function( elem ) { var value, option, options = elem.options, index = elem.selectedIndex, one = elem.type === "select-one" || index < 0, values = one ? null : [], max = one ? index + 1 : options.length, i = index < 0 ? max : one ? index : 0; // Loop through all the selected options for ( ; i < max; i++ ) { option = options[ i ]; // IE6-9 doesn't update selected after form reset (#2551) if ( ( option.selected || i === index ) && // Don't return options that are disabled or in a disabled optgroup ( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) && ( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) { // Get the specific value for the option value = jQuery( option ).val(); // We don't need an array for one selects if ( one ) { return value; } // Multi-Selects return an array values.push( value ); } } return values; }, set: function( elem, value ) { var optionSet, option, options = elem.options, values = jQuery.makeArray( value ), i = options.length; while ( i-- ) { option = options[ i ]; if ( (option.selected = jQuery.inArray( jQuery(option).val(), values ) >= 0) ) { optionSet = true; } } // force browsers to behave consistently when non-matching value is set if ( !optionSet ) { elem.selectedIndex = -1; } return values; } } }, attr: function( elem, name, value ) { var hooks, ret, nType = elem.nodeType; // don't get/set attributes on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } // Fallback to prop when attributes are not supported if ( typeof elem.getAttribute === core_strundefined ) { return jQuery.prop( elem, name, value ); } // All attributes are lowercase // Grab necessary hook if one is defined if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { name = name.toLowerCase(); hooks = jQuery.attrHooks[ name ] || ( jQuery.expr.match.bool.test( name ) ? boolHook : nodeHook ); } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); } else if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { elem.setAttribute( name, value + "" ); return value; } } else if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { ret = jQuery.find.attr( elem, name ); // Non-existent attributes return null, we normalize to undefined return ret == null ? undefined : ret; } }, removeAttr: function( elem, value ) { var name, propName, i = 0, attrNames = value && value.match( core_rnotwhite ); if ( attrNames && elem.nodeType === 1 ) { while ( (name = attrNames[i++]) ) { propName = jQuery.propFix[ name ] || name; // Boolean attributes get special treatment (#10870) if ( jQuery.expr.match.bool.test( name ) ) { // Set corresponding property to false elem[ propName ] = false; } elem.removeAttribute( name ); } } }, attrHooks: { type: { set: function( elem, value ) { if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { // Setting the type on a radio button after the value resets the value in IE6-9 // Reset value to default in case type is set after value during creation var val = elem.value; elem.setAttribute( "type", value ); if ( val ) { elem.value = val; } return value; } } } }, propFix: { "for": "htmlFor", "class": "className" }, prop: function( elem, name, value ) { var ret, hooks, notxml, nType = elem.nodeType; // don't get/set properties on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); if ( notxml ) { // Fix name and attach hooks name = jQuery.propFix[ name ] || name; hooks = jQuery.propHooks[ name ]; } if ( value !== undefined ) { return hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ? ret : ( elem[ name ] = value ); } else { return hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ? ret : elem[ name ]; } }, propHooks: { tabIndex: { get: function( elem ) { return elem.hasAttribute( "tabindex" ) || rfocusable.test( elem.nodeName ) || elem.href ? elem.tabIndex : -1; } } } }); // Hooks for boolean attributes boolHook = { set: function( elem, value, name ) { if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else { elem.setAttribute( name, name ); } return name; } }; jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) { var getter = jQuery.expr.attrHandle[ name ] || jQuery.find.attr; jQuery.expr.attrHandle[ name ] = function( elem, name, isXML ) { var fn = jQuery.expr.attrHandle[ name ], ret = isXML ? undefined : /* jshint eqeqeq: false */ // Temporarily disable this handler to check existence (jQuery.expr.attrHandle[ name ] = undefined) != getter( elem, name, isXML ) ? name.toLowerCase() : null; // Restore handler jQuery.expr.attrHandle[ name ] = fn; return ret; }; }); // Support: IE9+ // Selectedness for an option in an optgroup can be inaccurate if ( !jQuery.support.optSelected ) { jQuery.propHooks.selected = { get: function( elem ) { var parent = elem.parentNode; if ( parent && parent.parentNode ) { parent.parentNode.selectedIndex; } return null; } }; } jQuery.each([ "tabIndex", "readOnly", "maxLength", "cellSpacing", "cellPadding", "rowSpan", "colSpan", "useMap", "frameBorder", "contentEditable" ], function() { jQuery.propFix[ this.toLowerCase() ] = this; }); // Radios and checkboxes getter/setter jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = { set: function( elem, value ) { if ( jQuery.isArray( value ) ) { return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); } } }; if ( !jQuery.support.checkOn ) { jQuery.valHooks[ this ].get = function( elem ) { // Support: Webkit // "" is returned instead of "on" if a value isn't specified return elem.getAttribute("value") === null ? "on" : elem.value; }; } }); var rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|contextmenu)|click/, rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, rtypenamespace = /^([^.]*)(?:\.(.+)|)$/; function returnTrue() { return true; } function returnFalse() { return false; } function safeActiveElement() { try { return document.activeElement; } catch ( err ) { } } /* * Helper functions for managing events -- not part of the public interface. * Props to Dean Edwards' addEvent library for many of the ideas. */ jQuery.event = { global: {}, add: function( elem, types, handler, data, selector ) { var handleObjIn, eventHandle, tmp, events, t, handleObj, special, handlers, type, namespaces, origType, elemData = data_priv.get( elem ); // Don't attach events to noData or text/comment nodes (but allow plain objects) if ( !elemData ) { return; } // Caller can pass in an object of custom data in lieu of the handler if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; selector = handleObjIn.selector; } // Make sure that the handler has a unique ID, used to find/remove it later if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure and main handler, if this is the first if ( !(events = elemData.events) ) { events = elemData.events = {}; } if ( !(eventHandle = elemData.handle) ) { eventHandle = elemData.handle = function( e ) { // Discard the second event of a jQuery.event.trigger() and // when an event is called after a page has unloaded return typeof jQuery !== core_strundefined && (!e || jQuery.event.triggered !== e.type) ? jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : undefined; }; // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events eventHandle.elem = elem; } // Handle multiple events separated by a space types = ( types || "" ).match( core_rnotwhite ) || [""]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // There *must* be a type, no attaching namespace-only handlers if ( !type ) { continue; } // If event changes its type, use the special event handlers for the changed type special = jQuery.event.special[ type ] || {}; // If selector defined, determine special event api type, otherwise given type type = ( selector ? special.delegateType : special.bindType ) || type; // Update special based on newly reset type special = jQuery.event.special[ type ] || {}; // handleObj is passed to all event handlers handleObj = jQuery.extend({ type: type, origType: origType, data: data, handler: handler, guid: handler.guid, selector: selector, needsContext: selector && jQuery.expr.match.needsContext.test( selector ), namespace: namespaces.join(".") }, handleObjIn ); // Init the event handler queue if we're the first if ( !(handlers = events[ type ]) ) { handlers = events[ type ] = []; handlers.delegateCount = 0; // Only use addEventListener if the special events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle, false ); } } } if ( special.add ) { special.add.call( elem, handleObj ); if ( !handleObj.handler.guid ) { handleObj.handler.guid = handler.guid; } } // Add to the element's handler list, delegates in front if ( selector ) { handlers.splice( handlers.delegateCount++, 0, handleObj ); } else { handlers.push( handleObj ); } // Keep track of which events have ever been used, for event optimization jQuery.event.global[ type ] = true; } // Nullify elem to prevent memory leaks in IE elem = null; }, // Detach an event or set of events from an element remove: function( elem, types, handler, selector, mappedTypes ) { var j, origCount, tmp, events, t, handleObj, special, handlers, type, namespaces, origType, elemData = data_priv.hasData( elem ) && data_priv.get( elem ); if ( !elemData || !(events = elemData.events) ) { return; } // Once for each type.namespace in types; type may be omitted types = ( types || "" ).match( core_rnotwhite ) || [""]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // Unbind all events (on this namespace, if provided) for the element if ( !type ) { for ( type in events ) { jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); } continue; } special = jQuery.event.special[ type ] || {}; type = ( selector ? special.delegateType : special.bindType ) || type; handlers = events[ type ] || []; tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ); // Remove matching events origCount = j = handlers.length; while ( j-- ) { handleObj = handlers[ j ]; if ( ( mappedTypes || origType === handleObj.origType ) && ( !handler || handler.guid === handleObj.guid ) && ( !tmp || tmp.test( handleObj.namespace ) ) && ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { handlers.splice( j, 1 ); if ( handleObj.selector ) { handlers.delegateCount--; } if ( special.remove ) { special.remove.call( elem, handleObj ); } } } // Remove generic event handler if we removed something and no more handlers exist // (avoids potential for endless recursion during removal of special event handlers) if ( origCount && !handlers.length ) { if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } delete events[ type ]; } } // Remove the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { delete elemData.handle; data_priv.remove( elem, "events" ); } }, trigger: function( event, data, elem, onlyHandlers ) { var i, cur, tmp, bubbleType, ontype, handle, special, eventPath = [ elem || document ], type = core_hasOwn.call( event, "type" ) ? event.type : event, namespaces = core_hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : []; cur = tmp = elem = elem || document; // Don't do events on text and comment nodes if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } // focus/blur morphs to focusin/out; ensure we're not firing them right now if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { return; } if ( type.indexOf(".") >= 0 ) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split("."); type = namespaces.shift(); namespaces.sort(); } ontype = type.indexOf(":") < 0 && "on" + type; // Caller can pass in a jQuery.Event object, Object, or just an event type string event = event[ jQuery.expando ] ? event : new jQuery.Event( type, typeof event === "object" && event ); // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) event.isTrigger = onlyHandlers ? 2 : 3; event.namespace = namespaces.join("."); event.namespace_re = event.namespace ? new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) : null; // Clean up the event in case it is being reused event.result = undefined; if ( !event.target ) { event.target = elem; } // Clone any incoming data and prepend the event, creating the handler arg list data = data == null ? [ event ] : jQuery.makeArray( data, [ event ] ); // Allow special events to draw outside the lines special = jQuery.event.special[ type ] || {}; if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { return; } // Determine event propagation path in advance, per W3C events spec (#9951) // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { bubbleType = special.delegateType || type; if ( !rfocusMorph.test( bubbleType + type ) ) { cur = cur.parentNode; } for ( ; cur; cur = cur.parentNode ) { eventPath.push( cur ); tmp = cur; } // Only add window if we got to document (e.g., not plain obj or detached DOM) if ( tmp === (elem.ownerDocument || document) ) { eventPath.push( tmp.defaultView || tmp.parentWindow || window ); } } // Fire handlers on the event path i = 0; while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) { event.type = i > 1 ? bubbleType : special.bindType || type; // jQuery handler handle = ( data_priv.get( cur, "events" ) || {} )[ event.type ] && data_priv.get( cur, "handle" ); if ( handle ) { handle.apply( cur, data ); } // Native handler handle = ontype && cur[ ontype ]; if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) { event.preventDefault(); } } event.type = type; // If nobody prevented the default action, do it now if ( !onlyHandlers && !event.isDefaultPrevented() ) { if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) && jQuery.acceptData( elem ) ) { // Call a native DOM method on the target with the same name name as the event. // Don't do default actions on window, that's where global variables be (#6170) if ( ontype && jQuery.isFunction( elem[ type ] ) && !jQuery.isWindow( elem ) ) { // Don't re-trigger an onFOO event when we call its FOO() method tmp = elem[ ontype ]; if ( tmp ) { elem[ ontype ] = null; } // Prevent re-triggering of the same event, since we already bubbled it above jQuery.event.triggered = type; elem[ type ](); jQuery.event.triggered = undefined; if ( tmp ) { elem[ ontype ] = tmp; } } } } return event.result; }, dispatch: function( event ) { // Make a writable jQuery.Event from the native event object event = jQuery.event.fix( event ); var i, j, ret, matched, handleObj, handlerQueue = [], args = core_slice.call( arguments ), handlers = ( data_priv.get( this, "events" ) || {} )[ event.type ] || [], special = jQuery.event.special[ event.type ] || {}; // Use the fix-ed jQuery.Event rather than the (read-only) native event args[0] = event; event.delegateTarget = this; // Call the preDispatch hook for the mapped type, and let it bail if desired if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { return; } // Determine handlers handlerQueue = jQuery.event.handlers.call( this, event, handlers ); // Run delegates first; they may want to stop propagation beneath us i = 0; while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) { event.currentTarget = matched.elem; j = 0; while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) { // Triggered event must either 1) have no namespace, or // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) { event.handleObj = handleObj; event.data = handleObj.data; ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) .apply( matched.elem, args ); if ( ret !== undefined ) { if ( (event.result = ret) === false ) { event.preventDefault(); event.stopPropagation(); } } } } } // Call the postDispatch hook for the mapped type if ( special.postDispatch ) { special.postDispatch.call( this, event ); } return event.result; }, handlers: function( event, handlers ) { var i, matches, sel, handleObj, handlerQueue = [], delegateCount = handlers.delegateCount, cur = event.target; // Find delegate handlers // Black-hole SVG <use> instance trees (#13180) // Avoid non-left-click bubbling in Firefox (#3861) if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) { for ( ; cur !== this; cur = cur.parentNode || this ) { // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) if ( cur.disabled !== true || event.type !== "click" ) { matches = []; for ( i = 0; i < delegateCount; i++ ) { handleObj = handlers[ i ]; // Don't conflict with Object.prototype properties (#13203) sel = handleObj.selector + " "; if ( matches[ sel ] === undefined ) { matches[ sel ] = handleObj.needsContext ? jQuery( sel, this ).index( cur ) >= 0 : jQuery.find( sel, this, null, [ cur ] ).length; } if ( matches[ sel ] ) { matches.push( handleObj ); } } if ( matches.length ) { handlerQueue.push({ elem: cur, handlers: matches }); } } } } // Add the remaining (directly-bound) handlers if ( delegateCount < handlers.length ) { handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) }); } return handlerQueue; }, // Includes some event props shared by KeyEvent and MouseEvent props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), fixHooks: {}, keyHooks: { props: "char charCode key keyCode".split(" "), filter: function( event, original ) { // Add which for key events if ( event.which == null ) { event.which = original.charCode != null ? original.charCode : original.keyCode; } return event; } }, mouseHooks: { props: "button buttons clientX clientY offsetX offsetY pageX pageY screenX screenY toElement".split(" "), filter: function( event, original ) { var eventDoc, doc, body, button = original.button; // Calculate pageX/Y if missing and clientX/Y available if ( event.pageX == null && original.clientX != null ) { eventDoc = event.target.ownerDocument || document; doc = eventDoc.documentElement; body = eventDoc.body; event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); } // Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if ( !event.which && button !== undefined ) { event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); } return event; } }, fix: function( event ) { if ( event[ jQuery.expando ] ) { return event; } // Create a writable copy of the event object and normalize some properties var i, prop, copy, type = event.type, originalEvent = event, fixHook = this.fixHooks[ type ]; if ( !fixHook ) { this.fixHooks[ type ] = fixHook = rmouseEvent.test( type ) ? this.mouseHooks : rkeyEvent.test( type ) ? this.keyHooks : {}; } copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; event = new jQuery.Event( originalEvent ); i = copy.length; while ( i-- ) { prop = copy[ i ]; event[ prop ] = originalEvent[ prop ]; } // Support: Cordova 2.5 (WebKit) (#13255) // All events should have a target; Cordova deviceready doesn't if ( !event.target ) { event.target = document; } // Support: Safari 6.0+, Chrome < 28 // Target should not be a text node (#504, #13143) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } return fixHook.filter? fixHook.filter( event, originalEvent ) : event; }, special: { load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, focus: { // Fire native event if possible so blur/focus sequence is correct trigger: function() { if ( this !== safeActiveElement() && this.focus ) { this.focus(); return false; } }, delegateType: "focusin" }, blur: { trigger: function() { if ( this === safeActiveElement() && this.blur ) { this.blur(); return false; } }, delegateType: "focusout" }, click: { // For checkbox, fire native event so checked state will be right trigger: function() { if ( this.type === "checkbox" && this.click && jQuery.nodeName( this, "input" ) ) { this.click(); return false; } }, // For cross-browser consistency, don't fire native .click() on links _default: function( event ) { return jQuery.nodeName( event.target, "a" ); } }, beforeunload: { postDispatch: function( event ) { // Support: Firefox 20+ // Firefox doesn't alert if the returnValue field is not set. if ( event.result !== undefined ) { event.originalEvent.returnValue = event.result; } } } }, simulate: function( type, elem, event, bubble ) { // Piggyback on a donor event to simulate a different one. // Fake originalEvent to avoid donor's stopPropagation, but if the // simulated event prevents default then we do the same on the donor. var e = jQuery.extend( new jQuery.Event(), event, { type: type, isSimulated: true, originalEvent: {} } ); if ( bubble ) { jQuery.event.trigger( e, null, elem ); } else { jQuery.event.dispatch.call( elem, e ); } if ( e.isDefaultPrevented() ) { event.preventDefault(); } } }; jQuery.removeEvent = function( elem, type, handle ) { if ( elem.removeEventListener ) { elem.removeEventListener( type, handle, false ); } }; jQuery.Event = function( src, props ) { // Allow instantiation without the 'new' keyword if ( !(this instanceof jQuery.Event) ) { return new jQuery.Event( src, props ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Events bubbling up the document may have been marked as prevented // by a handler lower down the tree; reflect the correct value. this.isDefaultPrevented = ( src.defaultPrevented || src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse; // Event type } else { this.type = src; } // Put explicitly provided properties onto the event object if ( props ) { jQuery.extend( this, props ); } // Create a timestamp if incoming event doesn't have one this.timeStamp = src && src.timeStamp || jQuery.now(); // Mark it as fixed this[ jQuery.expando ] = true; }; // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse, preventDefault: function() { var e = this.originalEvent; this.isDefaultPrevented = returnTrue; if ( e && e.preventDefault ) { e.preventDefault(); } }, stopPropagation: function() { var e = this.originalEvent; this.isPropagationStopped = returnTrue; if ( e && e.stopPropagation ) { e.stopPropagation(); } }, stopImmediatePropagation: function() { this.isImmediatePropagationStopped = returnTrue; this.stopPropagation(); } }; // Create mouseenter/leave events using mouseover/out and event-time checks // Support: Chrome 15+ jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { delegateType: fix, bindType: fix, handle: function( event ) { var ret, target = this, related = event.relatedTarget, handleObj = event.handleObj; // For mousenter/leave call the handler if related is outside the target. // NB: No relatedTarget if the mouse left/entered the browser window if ( !related || (related !== target && !jQuery.contains( target, related )) ) { event.type = handleObj.origType; ret = handleObj.handler.apply( this, arguments ); event.type = fix; } return ret; } }; }); // Create "bubbling" focus and blur events // Support: Firefox, Chrome, Safari if ( !jQuery.support.focusinBubbles ) { jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { // Attach a single capturing handler while someone wants focusin/focusout var attaches = 0, handler = function( event ) { jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); }; jQuery.event.special[ fix ] = { setup: function() { if ( attaches++ === 0 ) { document.addEventListener( orig, handler, true ); } }, teardown: function() { if ( --attaches === 0 ) { document.removeEventListener( orig, handler, true ); } } }; }); } jQuery.fn.extend({ on: function( types, selector, data, fn, /*INTERNAL*/ one ) { var origFn, type; // Types can be a map of types/handlers if ( typeof types === "object" ) { // ( types-Object, selector, data ) if ( typeof selector !== "string" ) { // ( types-Object, data ) data = data || selector; selector = undefined; } for ( type in types ) { this.on( type, selector, data, types[ type ], one ); } return this; } if ( data == null && fn == null ) { // ( types, fn ) fn = selector; data = selector = undefined; } else if ( fn == null ) { if ( typeof selector === "string" ) { // ( types, selector, fn ) fn = data; data = undefined; } else { // ( types, data, fn ) fn = data; data = selector; selector = undefined; } } if ( fn === false ) { fn = returnFalse; } else if ( !fn ) { return this; } if ( one === 1 ) { origFn = fn; fn = function( event ) { // Can use an empty set, since event contains the info jQuery().off( event ); return origFn.apply( this, arguments ); }; // Use same guid so caller can remove using origFn fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); } return this.each( function() { jQuery.event.add( this, types, fn, data, selector ); }); }, one: function( types, selector, data, fn ) { return this.on( types, selector, data, fn, 1 ); }, off: function( types, selector, fn ) { var handleObj, type; if ( types && types.preventDefault && types.handleObj ) { // ( event ) dispatched jQuery.Event handleObj = types.handleObj; jQuery( types.delegateTarget ).off( handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler ); return this; } if ( typeof types === "object" ) { // ( types-object [, selector] ) for ( type in types ) { this.off( type, selector, types[ type ] ); } return this; } if ( selector === false || typeof selector === "function" ) { // ( types [, fn] ) fn = selector; selector = undefined; } if ( fn === false ) { fn = returnFalse; } return this.each(function() { jQuery.event.remove( this, types, fn, selector ); }); }, trigger: function( type, data ) { return this.each(function() { jQuery.event.trigger( type, data, this ); }); }, triggerHandler: function( type, data ) { var elem = this[0]; if ( elem ) { return jQuery.event.trigger( type, data, elem, true ); } } }); var isSimple = /^.[^:#\[\.,]*$/, rparentsprev = /^(?:parents|prev(?:Until|All))/, rneedsContext = jQuery.expr.match.needsContext, // methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.fn.extend({ find: function( selector ) { var i, ret = [], self = this, len = self.length; if ( typeof selector !== "string" ) { return this.pushStack( jQuery( selector ).filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } }) ); } for ( i = 0; i < len; i++ ) { jQuery.find( selector, self[ i ], ret ); } // Needed because $( selector, context ) becomes $( context ).find( selector ) ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret ); ret.selector = this.selector ? this.selector + " " + selector : selector; return ret; }, has: function( target ) { var targets = jQuery( target, this ), l = targets.length; return this.filter(function() { var i = 0; for ( ; i < l; i++ ) { if ( jQuery.contains( this, targets[i] ) ) { return true; } } }); }, not: function( selector ) { return this.pushStack( winnow(this, selector || [], true) ); }, filter: function( selector ) { return this.pushStack( winnow(this, selector || [], false) ); }, is: function( selector ) { return !!winnow( this, // If this is a positional/relative selector, check membership in the returned set // so $("p:first").is("p:last") won't return true for a doc with two "p". typeof selector === "string" && rneedsContext.test( selector ) ? jQuery( selector ) : selector || [], false ).length; }, closest: function( selectors, context ) { var cur, i = 0, l = this.length, matched = [], pos = ( rneedsContext.test( selectors ) || typeof selectors !== "string" ) ? jQuery( selectors, context || this.context ) : 0; for ( ; i < l; i++ ) { for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) { // Always skip document fragments if ( cur.nodeType < 11 && (pos ? pos.index(cur) > -1 : // Don't pass non-elements to Sizzle cur.nodeType === 1 && jQuery.find.matchesSelector(cur, selectors)) ) { cur = matched.push( cur ); break; } } } return this.pushStack( matched.length > 1 ? jQuery.unique( matched ) : matched ); }, // Determine the position of an element within // the matched set of elements index: function( elem ) { // No argument, return index in parent if ( !elem ) { return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1; } // index in selector if ( typeof elem === "string" ) { return core_indexOf.call( jQuery( elem ), this[ 0 ] ); } // Locate the position of the desired element return core_indexOf.call( this, // If it receives a jQuery object, the first element is used elem.jquery ? elem[ 0 ] : elem ); }, add: function( selector, context ) { var set = typeof selector === "string" ? jQuery( selector, context ) : jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ), all = jQuery.merge( this.get(), set ); return this.pushStack( jQuery.unique(all) ); }, addBack: function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter(selector) ); } }); function sibling( cur, dir ) { while ( (cur = cur[dir]) && cur.nodeType !== 1 ) {} return cur; } jQuery.each({ parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return jQuery.dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return jQuery.dir( elem, "parentNode", until ); }, next: function( elem ) { return sibling( elem, "nextSibling" ); }, prev: function( elem ) { return sibling( elem, "previousSibling" ); }, nextAll: function( elem ) { return jQuery.dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return jQuery.dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return jQuery.dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return jQuery.dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); }, children: function( elem ) { return jQuery.sibling( elem.firstChild ); }, contents: function( elem ) { return jQuery.nodeName( elem, "iframe" ) ? elem.contentDocument || elem.contentWindow.document : jQuery.merge( [], elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var matched = jQuery.map( this, fn, until ); if ( name.slice( -5 ) !== "Until" ) { selector = until; } if ( selector && typeof selector === "string" ) { matched = jQuery.filter( selector, matched ); } if ( this.length > 1 ) { // Remove duplicates if ( !guaranteedUnique[ name ] ) { jQuery.unique( matched ); } // Reverse order for parents* and prev-derivatives if ( rparentsprev.test( name ) ) { matched.reverse(); } } return this.pushStack( matched ); }; }); jQuery.extend({ filter: function( expr, elems, not ) { var elem = elems[ 0 ]; if ( not ) { expr = ":not(" + expr + ")"; } return elems.length === 1 && elem.nodeType === 1 ? jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] : jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { return elem.nodeType === 1; })); }, dir: function( elem, dir, until ) { var matched = [], truncate = until !== undefined; while ( (elem = elem[ dir ]) && elem.nodeType !== 9 ) { if ( elem.nodeType === 1 ) { if ( truncate && jQuery( elem ).is( until ) ) { break; } matched.push( elem ); } } return matched; }, sibling: function( n, elem ) { var matched = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { matched.push( n ); } } return matched; } }); // Implement the identical functionality for filter and not function winnow( elements, qualifier, not ) { if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep( elements, function( elem, i ) { /* jshint -W018 */ return !!qualifier.call( elem, i, elem ) !== not; }); } if ( qualifier.nodeType ) { return jQuery.grep( elements, function( elem ) { return ( elem === qualifier ) !== not; }); } if ( typeof qualifier === "string" ) { if ( isSimple.test( qualifier ) ) { return jQuery.filter( qualifier, elements, not ); } qualifier = jQuery.filter( qualifier, elements ); } return jQuery.grep( elements, function( elem ) { return ( core_indexOf.call( qualifier, elem ) >= 0 ) !== not; }); } var rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, rtagName = /<([\w:]+)/, rhtml = /<|&#?\w+;/, rnoInnerhtml = /<(?:script|style|link)/i, manipulation_rcheckableType = /^(?:checkbox|radio)$/i, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptType = /^$|\/(?:java|ecma)script/i, rscriptTypeMasked = /^true\/(.*)/, rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g, // We have to close these tags to support XHTML (#13200) wrapMap = { // Support: IE 9 option: [ 1, "<select multiple='multiple'>", "</select>" ], thead: [ 1, "<table>", "</table>" ], col: [ 2, "<table><colgroup>", "</colgroup></table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], _default: [ 0, "", "" ] }; // Support: IE 9 wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; jQuery.fn.extend({ text: function( value ) { return jQuery.access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().append( ( this[ 0 ] && this[ 0 ].ownerDocument || document ).createTextNode( value ) ); }, null, value, arguments.length ); }, append: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.appendChild( elem ); } }); }, prepend: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.insertBefore( elem, target.firstChild ); } }); }, before: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this ); } }); }, after: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this.nextSibling ); } }); }, // keepData is for internal use only--do not document remove: function( selector, keepData ) { var elem, elems = selector ? jQuery.filter( selector, this ) : this, i = 0; for ( ; (elem = elems[i]) != null; i++ ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem ) ); } if ( elem.parentNode ) { if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) { setGlobalEval( getAll( elem, "script" ) ); } elem.parentNode.removeChild( elem ); } } return this; }, empty: function() { var elem, i = 0; for ( ; (elem = this[i]) != null; i++ ) { if ( elem.nodeType === 1 ) { // Prevent memory leaks jQuery.cleanData( getAll( elem, false ) ); // Remove any remaining nodes elem.textContent = ""; } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map( function () { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); }); }, html: function( value ) { return jQuery.access( this, function( value ) { var elem = this[ 0 ] || {}, i = 0, l = this.length; if ( value === undefined && elem.nodeType === 1 ) { return elem.innerHTML; } // See if we can take a shortcut and just use innerHTML if ( typeof value === "string" && !rnoInnerhtml.test( value ) && !wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) { value = value.replace( rxhtmlTag, "<$1></$2>" ); try { for ( ; i < l; i++ ) { elem = this[ i ] || {}; // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch( e ) {} } if ( elem ) { this.empty().append( value ); } }, null, value, arguments.length ); }, replaceWith: function() { var // Snapshot the DOM in case .domManip sweeps something relevant into its fragment args = jQuery.map( this, function( elem ) { return [ elem.nextSibling, elem.parentNode ]; }), i = 0; // Make the changes, replacing each context element with the new content this.domManip( arguments, function( elem ) { var next = args[ i++ ], parent = args[ i++ ]; if ( parent ) { // Don't use the snapshot next if it has moved (#13810) if ( next && next.parentNode !== parent ) { next = this.nextSibling; } jQuery( this ).remove(); parent.insertBefore( elem, next ); } // Allow new content to include elements from the context set }, true ); // Force removal if there was no new content (e.g., from empty arguments) return i ? this : this.remove(); }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, callback, allowIntersection ) { // Flatten any nested arrays args = core_concat.apply( [], args ); var fragment, first, scripts, hasScripts, node, doc, i = 0, l = this.length, set = this, iNoClone = l - 1, value = args[ 0 ], isFunction = jQuery.isFunction( value ); // We can't cloneNode fragments that contain checked, in WebKit if ( isFunction || !( l <= 1 || typeof value !== "string" || jQuery.support.checkClone || !rchecked.test( value ) ) ) { return this.each(function( index ) { var self = set.eq( index ); if ( isFunction ) { args[ 0 ] = value.call( this, index, self.html() ); } self.domManip( args, callback, allowIntersection ); }); } if ( l ) { fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, !allowIntersection && this ); first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } if ( first ) { scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); hasScripts = scripts.length; // Use the original fragment for the last item instead of the first because it can end up // being emptied incorrectly in certain situations (#8070). for ( ; i < l; i++ ) { node = fragment; if ( i !== iNoClone ) { node = jQuery.clone( node, true, true ); // Keep references to cloned scripts for later restoration if ( hasScripts ) { // Support: QtWebKit // jQuery.merge because core_push.apply(_, arraylike) throws jQuery.merge( scripts, getAll( node, "script" ) ); } } callback.call( this[ i ], node, i ); } if ( hasScripts ) { doc = scripts[ scripts.length - 1 ].ownerDocument; // Reenable scripts jQuery.map( scripts, restoreScript ); // Evaluate executable scripts on first document insertion for ( i = 0; i < hasScripts; i++ ) { node = scripts[ i ]; if ( rscriptType.test( node.type || "" ) && !data_priv.access( node, "globalEval" ) && jQuery.contains( doc, node ) ) { if ( node.src ) { // Hope ajax is available... jQuery._evalUrl( node.src ); } else { jQuery.globalEval( node.textContent.replace( rcleanScript, "" ) ); } } } } } } return this; } }); jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var elems, ret = [], insert = jQuery( selector ), last = insert.length - 1, i = 0; for ( ; i <= last; i++ ) { elems = i === last ? this : this.clone( true ); jQuery( insert[ i ] )[ original ]( elems ); // Support: QtWebKit // .get() because core_push.apply(_, arraylike) throws core_push.apply( ret, elems.get() ); } return this.pushStack( ret ); }; }); jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var i, l, srcElements, destElements, clone = elem.cloneNode( true ), inPage = jQuery.contains( elem.ownerDocument, elem ); // Support: IE >= 9 // Fix Cloning issues if ( !jQuery.support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) && !jQuery.isXMLDoc( elem ) ) { // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 destElements = getAll( clone ); srcElements = getAll( elem ); for ( i = 0, l = srcElements.length; i < l; i++ ) { fixInput( srcElements[ i ], destElements[ i ] ); } } // Copy the events from the original to the clone if ( dataAndEvents ) { if ( deepDataAndEvents ) { srcElements = srcElements || getAll( elem ); destElements = destElements || getAll( clone ); for ( i = 0, l = srcElements.length; i < l; i++ ) { cloneCopyEvent( srcElements[ i ], destElements[ i ] ); } } else { cloneCopyEvent( elem, clone ); } } // Preserve script evaluation history destElements = getAll( clone, "script" ); if ( destElements.length > 0 ) { setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); } // Return the cloned set return clone; }, buildFragment: function( elems, context, scripts, selection ) { var elem, tmp, tag, wrap, contains, j, i = 0, l = elems.length, fragment = context.createDocumentFragment(), nodes = []; for ( ; i < l; i++ ) { elem = elems[ i ]; if ( elem || elem === 0 ) { // Add nodes directly if ( jQuery.type( elem ) === "object" ) { // Support: QtWebKit // jQuery.merge because core_push.apply(_, arraylike) throws jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); // Convert non-html into a text node } else if ( !rhtml.test( elem ) ) { nodes.push( context.createTextNode( elem ) ); // Convert html into DOM nodes } else { tmp = tmp || fragment.appendChild( context.createElement("div") ); // Deserialize a standard representation tag = ( rtagName.exec( elem ) || ["", ""] )[ 1 ].toLowerCase(); wrap = wrapMap[ tag ] || wrapMap._default; tmp.innerHTML = wrap[ 1 ] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[ 2 ]; // Descend through wrappers to the right content j = wrap[ 0 ]; while ( j-- ) { tmp = tmp.firstChild; } // Support: QtWebKit // jQuery.merge because core_push.apply(_, arraylike) throws jQuery.merge( nodes, tmp.childNodes ); // Remember the top-level container tmp = fragment.firstChild; // Fixes #12346 // Support: Webkit, IE tmp.textContent = ""; } } } // Remove wrapper from fragment fragment.textContent = ""; i = 0; while ( (elem = nodes[ i++ ]) ) { // #4087 - If origin and destination elements are the same, and this is // that element, do not do anything if ( selection && jQuery.inArray( elem, selection ) !== -1 ) { continue; } contains = jQuery.contains( elem.ownerDocument, elem ); // Append to fragment tmp = getAll( fragment.appendChild( elem ), "script" ); // Preserve script evaluation history if ( contains ) { setGlobalEval( tmp ); } // Capture executables if ( scripts ) { j = 0; while ( (elem = tmp[ j++ ]) ) { if ( rscriptType.test( elem.type || "" ) ) { scripts.push( elem ); } } } } return fragment; }, cleanData: function( elems ) { var data, elem, events, type, key, j, special = jQuery.event.special, i = 0; for ( ; (elem = elems[ i ]) !== undefined; i++ ) { if ( Data.accepts( elem ) ) { key = elem[ data_priv.expando ]; if ( key && (data = data_priv.cache[ key ]) ) { events = Object.keys( data.events || {} ); if ( events.length ) { for ( j = 0; (type = events[j]) !== undefined; j++ ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } } if ( data_priv.cache[ key ] ) { // Discard any remaining `private` data delete data_priv.cache[ key ]; } } } // Discard any remaining `user` data delete data_user.cache[ elem[ data_user.expando ] ]; } }, _evalUrl: function( url ) { return jQuery.ajax({ url: url, type: "GET", dataType: "script", async: false, global: false, "throws": true }); } }); // Support: 1.x compatibility // Manipulating tables requires a tbody function manipulationTarget( elem, content ) { return jQuery.nodeName( elem, "table" ) && jQuery.nodeName( content.nodeType === 1 ? content : content.firstChild, "tr" ) ? elem.getElementsByTagName("tbody")[0] || elem.appendChild( elem.ownerDocument.createElement("tbody") ) : elem; } // Replace/restore the type attribute of script elements for safe DOM manipulation function disableScript( elem ) { elem.type = (elem.getAttribute("type") !== null) + "/" + elem.type; return elem; } function restoreScript( elem ) { var match = rscriptTypeMasked.exec( elem.type ); if ( match ) { elem.type = match[ 1 ]; } else { elem.removeAttribute("type"); } return elem; } // Mark scripts as having already been evaluated function setGlobalEval( elems, refElements ) { var l = elems.length, i = 0; for ( ; i < l; i++ ) { data_priv.set( elems[ i ], "globalEval", !refElements || data_priv.get( refElements[ i ], "globalEval" ) ); } } function cloneCopyEvent( src, dest ) { var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events; if ( dest.nodeType !== 1 ) { return; } // 1. Copy private data: events, handlers, etc. if ( data_priv.hasData( src ) ) { pdataOld = data_priv.access( src ); pdataCur = data_priv.set( dest, pdataOld ); events = pdataOld.events; if ( events ) { delete pdataCur.handle; pdataCur.events = {}; for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type, events[ type ][ i ] ); } } } } // 2. Copy user data if ( data_user.hasData( src ) ) { udataOld = data_user.access( src ); udataCur = jQuery.extend( {}, udataOld ); data_user.set( dest, udataCur ); } } function getAll( context, tag ) { var ret = context.getElementsByTagName ? context.getElementsByTagName( tag || "*" ) : context.querySelectorAll ? context.querySelectorAll( tag || "*" ) : []; return tag === undefined || tag && jQuery.nodeName( context, tag ) ? jQuery.merge( [ context ], ret ) : ret; } // Support: IE >= 9 function fixInput( src, dest ) { var nodeName = dest.nodeName.toLowerCase(); // Fails to persist the checked state of a cloned checkbox or radio button. if ( nodeName === "input" && manipulation_rcheckableType.test( src.type ) ) { dest.checked = src.checked; // Fails to return the selected option to the default selected state when cloning options } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; } } jQuery.fn.extend({ wrapAll: function( html ) { var wrap; if ( jQuery.isFunction( html ) ) { return this.each(function( i ) { jQuery( this ).wrapAll( html.call(this, i) ); }); } if ( this[ 0 ] ) { // The elements to wrap the target around wrap = jQuery( html, this[ 0 ].ownerDocument ).eq( 0 ).clone( true ); if ( this[ 0 ].parentNode ) { wrap.insertBefore( this[ 0 ] ); } wrap.map(function() { var elem = this; while ( elem.firstElementChild ) { elem = elem.firstElementChild; } return elem; }).append( this ); } return this; }, wrapInner: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function( i ) { jQuery( this ).wrapInner( html.call(this, i) ); }); } return this.each(function() { var self = jQuery( this ), contents = self.contents(); if ( contents.length ) { contents.wrapAll( html ); } else { self.append( html ); } }); }, wrap: function( html ) { var isFunction = jQuery.isFunction( html ); return this.each(function( i ) { jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html ); }); }, unwrap: function() { return this.parent().each(function() { if ( !jQuery.nodeName( this, "body" ) ) { jQuery( this ).replaceWith( this.childNodes ); } }).end(); } }); var r20 = /%20/g, rbracket = /\[\]$/, rCRLF = /\r?\n/g, rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, rsubmittable = /^(?:input|select|textarea|keygen)/i; jQuery.fn.extend({ serialize: function() { return jQuery.param( this.serializeArray() ); }, serializeArray: function() { return this.map(function(){ // Can add propHook for "elements" to filter or add form elements var elements = jQuery.prop( this, "elements" ); return elements ? jQuery.makeArray( elements ) : this; }) .filter(function(){ var type = this.type; // Use .is(":disabled") so that fieldset[disabled] works return this.name && !jQuery( this ).is( ":disabled" ) && rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) && ( this.checked || !manipulation_rcheckableType.test( type ) ); }) .map(function( i, elem ){ var val = jQuery( this ).val(); return val == null ? null : jQuery.isArray( val ) ? jQuery.map( val, function( val ){ return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }) : { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }).get(); } }); //Serialize an array of form elements or a set of //key/values into a query string jQuery.param = function( a, traditional ) { var prefix, s = [], add = function( key, value ) { // If value is a function, invoke it and return its value value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value ); s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); }; // Set traditional to true for jQuery <= 1.3.2 behavior. if ( traditional === undefined ) { traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional; } // If an array was passed in, assume that it is an array of form elements. if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); }); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( prefix in a ) { buildParams( prefix, a[ prefix ], traditional, add ); } } // Return the resulting serialization return s.join( "&" ).replace( r20, "+" ); }; function buildParams( prefix, obj, traditional, add ) { var name; if ( jQuery.isArray( obj ) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || rbracket.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // Item is non-scalar (array or object), encode its numeric index. buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add ); } }); } else if ( !traditional && jQuery.type( obj ) === "object" ) { // Serialize object item. for ( name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } else { // Serialize scalar item. add( prefix, obj ); } } // Limit scope pollution from any deprecated API // (function() { // The number of elements contained in the matched element set jQuery.fn.size = function() { return this.length; }; jQuery.fn.andSelf = jQuery.fn.addBack; // })(); if ( typeof module === "object" && module && typeof module.exports === "object" ) { // Expose jQuery as module.exports in loaders that implement the Node // module pattern (including browserify). Do not create the global, since // the user will be storing it themselves locally, and globals are frowned // upon in the Node module world. module.exports = jQuery; } else { // Register as a named AMD module, since jQuery can be concatenated with other // files that may use define, but not via a proper concatenation script that // understands anonymous AMD modules. A named AMD is safest and most robust // way to register. Lowercase jquery is used because AMD module names are // derived from file names, and jQuery is normally delivered in a lowercase // file name. Do this after creating the global so that if an AMD module wants // to call noConflict to hide this version of jQuery, it will work. if ( typeof define === "function" && define.amd ) { define( "jquery", [], function () { return jQuery; } ); } } // If there is a window object, that at least has a document property, // define jQuery and $ identifiers if ( typeof window === "object" && typeof window.document === "object" ) { window.jQuery = window.$ = jQuery; } })( window );
'use strict'; describe('Loading 0202-layers-overlays-simple-example.html', function() { beforeEach(function() { browser.get('0202-layers-overlays-simple-example.html'); browser.wait(function() { return element(by.css('img.leaflet-tile-loaded')).isPresent(); }, 5000); }); it('should change the layer tiles if clicked on the leaflet control switch layer', function() { expect(element(by.xpath('//img[contains(@src, "http://c.tile.openstreetmap.org/")]')).isPresent()).toBe(true); browser.actions().mouseMove(element(by.xpath('//a[contains(@class, "leaflet-control-layers-toggle")][1]'))).perform(); browser.wait(function() { return element(by.xpath('//img[contains(@src, "http://suite.opengeo.org/geoserver/usa/wms")]')).isPresent(); }, 5000); expect(element(by.xpath('//img[contains(@src, "http://suite.opengeo.org/geoserver/usa/wms")]')).isPresent()).toBe(true); var overlayButton = element(by.xpath('//input[@type=\'checkbox\'][1]')); overlayButton.click(); browser.driver.sleep(300); expect(element(by.xpath('//img[contains(@src, "http://suite.opengeo.org/geoserver/usa/wms")]')).isPresent()).toBe(false); }); });
/* Ractive.js v1.3.0-edge Build: 3c34b67ed6ee7e3072fccc80bb50bfb9ef90f3bd Date: Fri Jan 04 2019 18:04:51 GMT+0000 (UTC) Website: https://ractive.js.org License: MIT */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (function() { var current = global.Ractive; var exports = factory(); global.Ractive = exports; exports.noConflict = function() { global.Ractive = current; return exports; }; })(); }(this, (function () { 'use strict'; /* istanbul ignore if */ if (!Object.assign) { Object.assign = function(target) { var sources = [], len = arguments.length - 1; while ( len-- > 0 ) sources[ len ] = arguments[ len + 1 ]; if (target == null) { throw new TypeError('Cannot convert undefined or null to object'); } var to = Object(target); var sourcesLength = sources.length; for (var index = 0; index < sourcesLength; index++) { var nextSource = sources[index]; for (var nextKey in nextSource) { if (!Object.prototype.hasOwnProperty.call(nextSource, nextKey)) { continue; } to[nextKey] = nextSource[nextKey]; } } return to; }; } function hasOwn(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } function fillGaps(target) { var sources = [], len = arguments.length - 1; while ( len-- > 0 ) sources[ len ] = arguments[ len + 1 ]; for (var i = 0; i < sources.length; i++) { var source = sources[i]; for (var key in source) { // Source can be a prototype-less object. if (key in target || !hasOwn(source, key)) { continue; } target[key] = source[key]; } } return target; } function toPairs(obj) { if ( obj === void 0 ) obj = {}; var pairs = []; for (var key in obj) { // Source can be a prototype-less object. if (!hasOwn(obj, key)) { continue; } pairs.push([key, obj[key]]); } return pairs; } var obj = Object; var assign = obj.assign; var create = obj.create; var defineProperty = obj.defineProperty; var defineProperties = obj.defineProperties; var keys = obj.keys; var toString = Object.prototype.toString; var isArray = Array.isArray; function isEqual(a, b) { if (a === null && b === null) { return true; } if (isObjectType(a) || isObjectType(b)) { return false; } return a === b; } // http://stackoverflow.com/questions/18082/validate-numbers-in-javascript-isnumeric function isNumeric(thing) { return !isNaN(parseFloat(thing)) && isFinite(thing); } function isObject(thing) { return thing && toString.call(thing) === '[object Object]'; } function isObjectLike(thing) { return !!(thing && (isObjectType(thing) || isFunction(thing))); } function isObjectType(thing) { return typeof thing === 'object'; } function isFunction(thing) { return typeof thing === 'function'; } function isString(thing) { return typeof thing === 'string'; } function isNumber(thing) { return typeof thing === 'number'; } /* istanbul ignore if */ if (!Array.prototype.find) { defineProperty(Array.prototype, 'find', { value: function value(callback, thisArg) { if (this === null || this === undefined) { throw new TypeError('Array.prototype.find called on null or undefined'); } if (!isFunction(callback)) { throw new TypeError((callback + " is not a function")); } var array = Object(this); var arrayLength = array.length >>> 0; for (var index = 0; index < arrayLength; index++) { if (!hasOwn(array, index)) { continue; } if (!callback.call(thisArg, array[index], index, array)) { continue; } return array[index]; } return undefined; }, configurable: true, writable: true }); } // NOTE: Node doesn't exist in IE8. Nothing can be done. /* istanbul ignore if */ if ( typeof window !== 'undefined' && window.Node && window.Node.prototype && !window.Node.prototype.contains ) { Node.prototype.contains = function(node) { var this$1 = this; if (!node) { throw new TypeError('node required'); } do { if (this$1 === node) { return true; } } while ((node = node && node.parentNode)); return false; }; } /* istanbul ignore if */ if (typeof window !== 'undefined' && window.performance && !window.performance.now) { window.performance = window.performance || {}; var nowOffset = Date.now(); window.performance.now = function() { return Date.now() - nowOffset; }; } /* eslint no-console:"off" */ var win = typeof window !== 'undefined' ? window : null; var doc = win ? document : null; var isClient = !!doc; var base = typeof global !== 'undefined' ? global : win; var hasConsole = typeof console !== 'undefined' && isFunction(console.warn) && isFunction(console.warn.apply); var svg = doc ? doc.implementation.hasFeature('http://www.w3.org/TR/SVG11/feature#BasicStructure', '1.1') : false; var vendors = ['o', 'ms', 'moz', 'webkit']; /* istanbul ignore if */ if (!base.Promise) { var PENDING = {}; var FULFILLED = {}; var REJECTED = {}; var Promise$1 = (base.Promise = function(callback) { var fulfilledHandlers = []; var rejectedHandlers = []; var state = PENDING; var result; var dispatchHandlers; var makeResolver = function (newState) { return function(value) { if (state !== PENDING) { return; } result = value; state = newState; dispatchHandlers = makeDispatcher( state === FULFILLED ? fulfilledHandlers : rejectedHandlers, result ); wait(dispatchHandlers); }; }; var fulfill = makeResolver(FULFILLED); var reject = makeResolver(REJECTED); try { callback(fulfill, reject); } catch (err) { reject(err); } return { // `then()` returns a Promise - 2.2.7 then: function then(onFulfilled, onRejected) { var promise2 = new Promise$1(function (fulfill, reject) { var processResolutionHandler = function (handler, handlers, forward) { if (isFunction(handler)) { handlers.push(function (p1result) { try { resolve$1(promise2, handler(p1result), fulfill, reject); } catch (err) { reject(err); } }); } else { handlers.push(forward); } }; processResolutionHandler(onFulfilled, fulfilledHandlers, fulfill); processResolutionHandler(onRejected, rejectedHandlers, reject); if (state !== PENDING) { wait(dispatchHandlers); } }); return promise2; }, catch: function catch$1(onRejected) { return this.then(null, onRejected); }, finally: function finally$1(callback) { return this.then( function (v) { callback(); return v; }, function (e) { callback(); throw e; } ); } }; }); Promise$1.all = function(promises) { return new Promise$1(function (fulfill, reject) { var result = []; var pending; var i; if (!promises.length) { fulfill(result); return; } var processPromise = function (promise, i) { if (promise && isFunction(promise.then)) { promise.then(function (value) { result[i] = value; --pending || fulfill(result); }, reject); } else { result[i] = promise; --pending || fulfill(result); } }; pending = i = promises.length; while (i--) { processPromise(promises[i], i); } }); }; Promise$1.race = function(promises) { return new Promise$1(function (fulfill, reject) { var pending = true; function ok(v) { if (!pending) { return; } pending = false; fulfill(v); } function fail(e) { if (!pending) { return; } pending = false; reject(e); } for (var i = 0; i < promises.length; i++) { if (promises[i] && isFunction(promises[i].then)) { promises[i].then(ok, fail); } } }); }; Promise$1.resolve = function(value) { if (value && isFunction(value.then)) { return value; } return new Promise$1(function (fulfill) { fulfill(value); }); }; Promise$1.reject = function(reason) { if (reason && isFunction(reason.then)) { return reason; } return new Promise$1(function (fulfill, reject) { reject(reason); }); }; // TODO use MutationObservers or something to simulate setImmediate var wait = function(callback) { setTimeout(callback, 0); }; var makeDispatcher = function(handlers, result) { return function() { for (var handler = (void 0); (handler = handlers.shift()); ) { handler(result); } }; }; var resolve$1 = function(promise, x, fulfil, reject) { var then; if (x === promise) { throw new TypeError("A promise's fulfillment handler cannot return the same promise"); } if (x instanceof Promise$1) { x.then(fulfil, reject); } else if (x && (isObjectType(x) || isFunction(x))) { try { then = x.then; } catch (e) { reject(e); return; } if (isFunction(then)) { var called; var resolvePromise = function(y) { if (called) { return; } called = true; resolve$1(promise, y, fulfil, reject); }; var rejectPromise = function(r) { if (called) { return; } called = true; reject(r); }; try { then.call(x, resolvePromise, rejectPromise); } catch (e) { if (!called) { reject(e); called = true; return; } } } else { fulfil(x); } } else { fulfil(x); } }; } /* istanbul ignore if */ if ( typeof window !== 'undefined' && !(window.requestAnimationFrame && window.cancelAnimationFrame) ) { var lastTime = 0; window.requestAnimationFrame = function(callback) { var currentTime = Date.now(); var timeToNextCall = Math.max(0, 16 - (currentTime - lastTime)); var id = window.setTimeout(function () { callback(currentTime + timeToNextCall); }, timeToNextCall); lastTime = currentTime + timeToNextCall; return id; }; window.cancelAnimationFrame = function(id) { clearTimeout(id); }; } var defaults = { // render placement: el: void 0, append: false, delegate: true, enhance: false, // template: template: null, // parse: allowExpressions: true, delimiters: ['{{', '}}'], tripleDelimiters: ['{{{', '}}}'], staticDelimiters: ['[[', ']]'], staticTripleDelimiters: ['[[[', ']]]'], csp: true, interpolate: false, preserveWhitespace: false, sanitize: false, stripComments: true, contextLines: 0, // data & binding: data: create(null), helpers: create(null), computed: create(null), syncComputedChildren: false, resolveInstanceMembers: false, warnAboutAmbiguity: false, adapt: [], isolated: true, twoway: true, lazy: false, // transitions: noIntro: false, noOutro: false, transitionsEnabled: true, complete: void 0, nestedTransitions: true, // css: css: null, noCSSTransform: false }; // These are a subset of the easing equations found at // https://raw.github.com/danro/easing-js - license info // follows: // -------------------------------------------------- // easing.js v0.5.4 // Generic set of easing functions with AMD support // https://github.com/danro/easing-js // This code may be freely distributed under the MIT license // http://danro.mit-license.org/ // -------------------------------------------------- // All functions adapted from Thomas Fuchs & Jeremy Kahn // Easing Equations (c) 2003 Robert Penner, BSD license // https://raw.github.com/danro/easing-js/master/LICENSE // -------------------------------------------------- // In that library, the functions named easeIn, easeOut, and // easeInOut below are named easeInCubic, easeOutCubic, and // (you guessed it) easeInOutCubic. // // You can add additional easing functions to this list, and they // will be globally available. var easing = { linear: function linear(pos) { return pos; }, easeIn: function easeIn(pos) { /* istanbul ignore next */ return Math.pow(pos, 3); }, easeOut: function easeOut(pos) { return Math.pow(pos - 1, 3) + 1; }, easeInOut: function easeInOut(pos) { /* istanbul ignore next */ if ((pos /= 0.5) < 1) { return 0.5 * Math.pow(pos, 3); } /* istanbul ignore next */ return 0.5 * (Math.pow(pos - 2, 3) + 2); } }; function noop() {} /* global console */ /* eslint no-console:"off" */ var alreadyWarned = {}; var log; var printWarning; var welcome; if (hasConsole) { var welcomeIntro = [ "%cRactive.js %c1.3.0-edge %cin debug mode, %cmore...", 'color: rgb(114, 157, 52); font-weight: normal;', 'color: rgb(85, 85, 85); font-weight: normal;', 'color: rgb(85, 85, 85); font-weight: normal;', 'color: rgb(82, 140, 224); font-weight: normal; text-decoration: underline;' ]; var welcomeMessage = "You're running Ractive 1.3.0-edge in debug mode - messages will be printed to the console to help you fix problems and optimise your application.\n\nTo disable debug mode, add this line at the start of your app:\n Ractive.DEBUG = false;\n\nTo disable debug mode when your app is minified, add this snippet:\n Ractive.DEBUG = /unminified/.test(function(){/*unminified*/});\n\nGet help and support:\n http://ractive.js.org\n http://stackoverflow.com/questions/tagged/ractivejs\n http://groups.google.com/forum/#!forum/ractive-js\n http://twitter.com/ractivejs\n\nFound a bug? Raise an issue:\n https://github.com/ractivejs/ractive/issues\n\n"; welcome = function () { if (Ractive.WELCOME_MESSAGE === false) { welcome = noop; return; } var message = 'WELCOME_MESSAGE' in Ractive ? Ractive.WELCOME_MESSAGE : welcomeMessage; var hasGroup = !!console.groupCollapsed; if (hasGroup) { console.groupCollapsed.apply(console, welcomeIntro); } console.log(message); if (hasGroup) { console.groupEnd(welcomeIntro); } welcome = noop; }; printWarning = function (message, args) { welcome(); // extract information about the instance this message pertains to, if applicable if (isObjectType(args[args.length - 1])) { var options = args.pop(); var ractive = options ? options.ractive : null; if (ractive) { // if this is an instance of a component that we know the name of, add // it to the message var name; if (ractive.component && (name = ractive.component.name)) { message = "<" + name + "> " + message; } var node; if ( (node = options.node || (ractive.fragment && ractive.fragment.rendered && ractive.find('*'))) ) { args.push(node); } } } console.warn.apply( console, ['%cRactive.js: %c' + message, 'color: rgb(114, 157, 52);', 'color: rgb(85, 85, 85);'].concat( args ) ); }; log = function() { console.log.apply(console, arguments); }; } else { printWarning = log = welcome = noop; } function format(message, args) { return message.replace(/%s/g, function () { return args.shift(); }); } function fatal(message) { var args = [], len = arguments.length - 1; while ( len-- > 0 ) args[ len ] = arguments[ len + 1 ]; message = format(message, args); throw new Error(message); } function logIfDebug() { if (Ractive.DEBUG) { log.apply(null, arguments); } } function warn(message) { var args = [], len = arguments.length - 1; while ( len-- > 0 ) args[ len ] = arguments[ len + 1 ]; message = format(message, args); printWarning(message, args); } function warnOnce(message) { var args = [], len = arguments.length - 1; while ( len-- > 0 ) args[ len ] = arguments[ len + 1 ]; message = format(message, args); if (alreadyWarned[message]) { return; } alreadyWarned[message] = true; printWarning(message, args); } function warnIfDebug() { if (Ractive.DEBUG) { warn.apply(null, arguments); } } function warnOnceIfDebug() { if (Ractive.DEBUG) { warnOnce.apply(null, arguments); } } // Error messages that are used (or could be) in multiple places var badArguments = 'Bad arguments'; var noRegistryFunctionReturn = 'A function was specified for "%s" %s, but no %s was returned'; var missingPlugin = function (name, type) { return ("Missing \"" + name + "\" " + type + " plugin. You may need to download a plugin via http://ractive.js.org/integrations/#" + type + "s"); }; function findInViewHierarchy(registryName, ractive, name) { var instance = findInstance(registryName, ractive, name); return instance ? instance[registryName][name] : null; } function findInstance(registryName, ractive, name) { while (ractive) { if (name in ractive[registryName]) { return ractive; } if (ractive.isolated) { return null; } ractive = ractive.parent; } } function interpolate(from, to, ractive, type) { if (from === to) { return null; } if (type) { var interpol = findInViewHierarchy('interpolators', ractive, type); if (interpol) { return interpol(from, to) || null; } fatal(missingPlugin(type, 'interpolator')); } return ( interpolators.number(from, to) || interpolators.array(from, to) || interpolators.object(from, to) || null ); } var interpolators = { number: function number(from, to) { if (!isNumeric(from) || !isNumeric(to)) { return null; } from = +from; to = +to; var delta = to - from; if (!delta) { return function() { return from; }; } return function(t) { return from + t * delta; }; }, array: function array(from, to) { var len, i; if (!isArray(from) || !isArray(to)) { return null; } var intermediate = []; var interpolators = []; i = len = Math.min(from.length, to.length); while (i--) { interpolators[i] = interpolate(from[i], to[i]); } // surplus values - don't interpolate, but don't exclude them either for (i = len; i < from.length; i += 1) { intermediate[i] = from[i]; } for (i = len; i < to.length; i += 1) { intermediate[i] = to[i]; } return function(t) { var i = len; while (i--) { intermediate[i] = interpolators[i](t); } return intermediate; }; }, object: function object(from, to) { if (!isObject(from) || !isObject(to)) { return null; } var properties = []; var intermediate = {}; var interpolators = {}; var loop = function ( prop ) { if (hasOwn(from, prop)) { if (hasOwn(to, prop)) { properties.push(prop); interpolators[prop] = interpolate(from[prop], to[prop]) || (function () { return to[prop]; }); } else { intermediate[prop] = from[prop]; } } }; for (var prop in from) loop( prop ); for (var prop$1 in to) { if (hasOwn(to, prop$1) && !hasOwn(from, prop$1)) { intermediate[prop$1] = to[prop$1]; } } var len = properties.length; return function(t) { var i = len; while (i--) { var prop = properties[i]; intermediate[prop] = interpolators[prop](t); } return intermediate; }; } }; var refPattern = /\[\s*(\*|[0-9]|[1-9][0-9]+)\s*\]/g; var splitPattern = /([^\\](?:\\\\)*)\./; var escapeKeyPattern = /\\|\./g; var unescapeKeyPattern = /((?:\\)+)\1|\\(\.)/g; function escapeKey(key) { if (isString(key)) { return key.replace(escapeKeyPattern, '\\$&'); } return key; } function normalise(ref) { return ref ? ref.replace(refPattern, '.$1') : ''; } function splitKeypath(keypath) { var result = []; var match; keypath = normalise(keypath); while ((match = splitPattern.exec(keypath))) { var index = match.index + match[1].length; result.push(keypath.substr(0, index)); keypath = keypath.substr(index + 1); } result.push(keypath); return result; } function unescapeKey(key) { if (isString(key)) { return key.replace(unescapeKeyPattern, '$1$2'); } return key; } function addToArray(array, value) { var index = array.indexOf(value); if (index === -1) { array.push(value); } } function arrayContains(array, value) { for (var i = 0, c = array.length; i < c; i++) { if (array[i] == value) { return true; } } return false; } function arrayContentsMatch(a, b) { var i; if (!isArray(a) || !isArray(b)) { return false; } if (a.length !== b.length) { return false; } i = a.length; while (i--) { if (a[i] !== b[i]) { return false; } } return true; } function ensureArray(x) { if (isString(x)) { return [x]; } if (x === undefined) { return []; } return x; } function lastItem(array) { return array[array.length - 1]; } function removeFromArray(array, member) { if (!array) { return; } var index = array.indexOf(member); if (index !== -1) { array.splice(index, 1); } } function combine() { var arrays = [], len = arguments.length; while ( len-- ) arrays[ len ] = arguments[ len ]; var res = arrays.concat.apply([], arrays); var i = res.length; while (i--) { var idx = res.indexOf(res[i]); if (~idx && idx < i) { res.splice(i, 1); } } return res; } function toArray(arrayLike) { var array = []; var i = arrayLike.length; while (i--) { array[i] = arrayLike[i]; } return array; } function findMap(array, fn) { var len = array.length; for (var i = 0; i < len; i++) { var result = fn(array[i]); if (result) { return result; } } } function buildNewIndices(one, two, comparator) { var oldArray = one; var newArray = two; if (comparator) { oldArray = oldArray.map(comparator); newArray = newArray.map(comparator); } var oldLength = oldArray.length; var usedIndices = {}; var firstUnusedIndex = 0; return oldArray.map(function (item) { var index; var start = firstUnusedIndex; do { index = newArray.indexOf(item, start); if (index === -1) { return -1; } start = index + 1; } while (usedIndices[index] === true && start < oldLength); // keep track of the first unused index, so we don't search // the whole of newArray for each item in oldArray unnecessarily if (index === firstUnusedIndex) { firstUnusedIndex += 1; } // allow next instance of next "equal" to be found item usedIndices[index] = true; return index; }); } var fnBind = Function.prototype.bind; function bind(fn, context) { if (!/this/.test(fn.toString())) { return fn; } var bound = fnBind.call(fn, context); for (var prop in fn) { bound[prop] = fn[prop]; } return bound; } var shuffleTasks = { early: [], mark: [] }; var registerQueue = { early: [], mark: [] }; var noVirtual = { virtual: false }; var ModelBase = function ModelBase(parent) { this.deps = []; this.children = []; this.childByKey = {}; this.links = []; this.bindings = []; if (parent) { this.parent = parent; this.root = parent.root; } }; var ModelBase__proto__ = ModelBase.prototype; ModelBase__proto__.addShuffleTask = function addShuffleTask (task, stage) { if ( stage === void 0 ) stage = 'early'; shuffleTasks[stage].push(task); }; ModelBase__proto__.addShuffleRegister = function addShuffleRegister (item, stage) { if ( stage === void 0 ) stage = 'early'; registerQueue[stage].push({ model: this, item: item }); }; ModelBase__proto__.downstreamChanged = function downstreamChanged () {}; ModelBase__proto__.findMatches = function findMatches (keys$$1) { var len = keys$$1.length; var existingMatches = [this]; var matches; var i; var loop = function ( ) { var key = keys$$1[i]; if (key === '*') { matches = []; existingMatches.forEach(function (model) { matches.push.apply(matches, model.getValueChildren(model.get())); }); } else { matches = existingMatches.map(function (model) { return model.joinKey(key); }); } existingMatches = matches; }; for (i = 0; i < len; i += 1) loop( ); return matches; }; ModelBase__proto__.getKeypath = function getKeypath (ractive) { if (ractive !== this.ractive && this._link) { return this._link.target.getKeypath(ractive); } if (!this.keypath) { var parent = this.parent && this.parent.getKeypath(ractive); this.keypath = parent ? ((this.parent.getKeypath(ractive)) + "." + (escapeKey(this.key))) : escapeKey(this.key); } return this.keypath; }; ModelBase__proto__.getValueChildren = function getValueChildren (value) { var this$1 = this; var children; if (isArray(value)) { children = []; if ('length' in this && this.length !== value.length) { children.push(this.joinKey('length')); } value.forEach(function (m, i) { children.push(this$1.joinKey(i)); }); } else if (isObject(value) || isFunction(value)) { children = keys(value).map(function (key) { return this$1.joinKey(key); }); } else if (value != null) { children = []; } var computed = this.computed; if (computed) { children.push.apply(children, keys(computed).map(function (k) { return this$1.joinKey(k); })); } return children; }; ModelBase__proto__.getVirtual = function getVirtual (shouldCapture) { var this$1 = this; var value = this.get(shouldCapture, { virtual: false }); if (isObject(value)) { var result = isArray(value) ? [] : create(null); var keys$$1 = keys(value); var i = keys$$1.length; while (i--) { var child = this$1.childByKey[keys$$1[i]]; if (!child) { result[keys$$1[i]] = value[keys$$1[i]]; } else if (child._link) { result[keys$$1[i]] = child._link.getVirtual(); } else { result[keys$$1[i]] = child.getVirtual(); } } i = this.children.length; while (i--) { var child$1 = this$1.children[i]; if (!(child$1.key in result) && child$1._link) { result[child$1.key] = child$1._link.getVirtual(); } } if (this.computed) { keys$$1 = keys(this.computed); i = keys$$1.length; while (i--) { result[keys$$1[i]] = this$1.computed[keys$$1[i]].get(); } } return result; } else { return value; } }; ModelBase__proto__.has = function has (key) { var this$1 = this; if (this._link) { return this._link.has(key); } var value = this.get(false, noVirtual); if (!value) { return false; } key = unescapeKey(key); if ((isFunction(value) || isObject(value)) && key in value) { return true; } var computed = this.computed; if (computed && key in this.computed) { return true; } computed = this.root.ractive && this.root.ractive.computed; if (computed) { keys(computed).forEach(function (k) { if (computed[k].pattern && computed[k].pattern.test(this$1.getKeypath())) { return true; } }); } return false; }; ModelBase__proto__.joinAll = function joinAll (keys$$1, opts) { var model = this; for (var i = 0; i < keys$$1.length; i += 1) { if ( opts && opts.lastLink === false && i + 1 === keys$$1.length && model.childByKey[keys$$1[i]] && model.childByKey[keys$$1[i]]._link ) { return model.childByKey[keys$$1[i]]; } model = model.joinKey(keys$$1[i], opts); } return model; }; ModelBase__proto__.notifyUpstream = function notifyUpstream (startPath) { var this$1 = this; var parent = this.parent; var path = startPath || [this.key]; while (parent) { if (parent.patterns) { parent.patterns.forEach(function (o) { return o.notify(path.slice()); }); } path.unshift(parent.key); parent.links.forEach(function (l) { return l.notifiedUpstream(path, this$1.root); }); parent.deps.forEach(function (d) { return d.handleChange(path); }); parent.downstreamChanged(startPath); parent = parent.parent; } }; ModelBase__proto__.rebind = function rebind (next, previous, safe) { var this$1 = this; if (this._link) { this._link.rebind(next, previous, false); } // tell the deps to move to the new target var i = this.deps.length; while (i--) { if (this$1.deps[i].rebind) { this$1.deps[i].rebind(next, previous, safe); } } i = this.links.length; while (i--) { var link = this$1.links[i]; // only relink the root of the link tree if (link.owner && link.owner._link) { link.relinking(next, safe); } } i = this.children.length; while (i--) { var child = this$1.children[i]; child.rebind(next ? next.joinKey(child.key) : undefined, child, safe); } i = this.bindings.length; while (i--) { this$1.bindings[i].rebind(next, previous, safe); } }; ModelBase__proto__.reference = function reference () { 'refs' in this ? this.refs++ : (this.refs = 1); }; ModelBase__proto__.register = function register (dep) { this.deps.push(dep); }; ModelBase__proto__.registerLink = function registerLink (link) { addToArray(this.links, link); }; ModelBase__proto__.registerPatternObserver = function registerPatternObserver (observer) { (this.patterns || (this.patterns = [])).push(observer); this.register(observer); }; ModelBase__proto__.registerTwowayBinding = function registerTwowayBinding (binding) { this.bindings.push(binding); }; ModelBase__proto__.unreference = function unreference () { if ('refs' in this) { this.refs--; } }; ModelBase__proto__.unregister = function unregister (dep) { removeFromArray(this.deps, dep); }; ModelBase__proto__.unregisterLink = function unregisterLink (link) { removeFromArray(this.links, link); }; ModelBase__proto__.unregisterPatternObserver = function unregisterPatternObserver (observer) { removeFromArray(this.patterns, observer); this.unregister(observer); }; ModelBase__proto__.unregisterTwowayBinding = function unregisterTwowayBinding (binding) { removeFromArray(this.bindings, binding); }; ModelBase__proto__.updateFromBindings = function updateFromBindings$1 (cascade) { var this$1 = this; var i = this.bindings.length; while (i--) { var value = this$1.bindings[i].getValue(); if (value !== this$1.value) { this$1.set(value); } } // check for one-way bindings if there are no two-ways if (!this.bindings.length) { var oneway = findBoundValue(this.deps); if (oneway && oneway.value !== this.value) { this.set(oneway.value); } } if (cascade) { this.children.forEach(updateFromBindings); this.links.forEach(updateFromBindings); if (this._link) { this._link.updateFromBindings(cascade); } } }; // TODO: this may be better handled by overriding `get` on models with a parent that isRoot function maybeBind(model, value, shouldBind) { if (shouldBind && isFunction(value) && model.parent && model.parent.isRoot) { if (!model.boundValue) { model.boundValue = bind(value._r_unbound || value, model.parent.ractive); } return model.boundValue; } return value; } function updateFromBindings(model) { model.updateFromBindings(true); } function findBoundValue(list) { var i = list.length; while (i--) { if (list[i].bound) { var owner = list[i].owner; if (owner) { var value = owner.name === 'checked' ? owner.node.checked : owner.node.value; return { value: value }; } } } } function fireShuffleTasks(stage) { if (!stage) { fireShuffleTasks('early'); fireShuffleTasks('mark'); } else { var tasks = shuffleTasks[stage]; shuffleTasks[stage] = []; var i = tasks.length; while (i--) { tasks[i](); } var register = registerQueue[stage]; registerQueue[stage] = []; i = register.length; while (i--) { register[i].model.register(register[i].item); } } } function shuffle(model, newIndices, link, unsafe) { model.shuffling = true; var i = newIndices.length; while (i--) { var idx = newIndices[i]; // nothing is actually changing, so move in the index and roll on if (i === idx) { continue; } // rebind the children on i to idx if (i in model.childByKey) { model.childByKey[i].rebind( !~idx ? undefined : model.joinKey(idx), model.childByKey[i], !unsafe ); } } var upstream = model.source().length !== model.source().value.length; model.links.forEach(function (l) { return l.shuffle(newIndices); }); if (!link) { fireShuffleTasks('early'); } i = model.deps.length; while (i--) { if (model.deps[i].shuffle) { model.deps[i].shuffle(newIndices); } } model[link ? 'marked' : 'mark'](); if (!link) { fireShuffleTasks('mark'); } if (upstream) { model.notifyUpstream(); } model.shuffling = false; } var stack = []; var captureGroup; function startCapturing() { stack.push((captureGroup = [])); } function stopCapturing() { var dependencies = stack.pop(); captureGroup = stack[stack.length - 1]; return dependencies; } function capture(model) { if (captureGroup) { captureGroup.push(model); } } function bind$1(x) { x.bind(); } function cancel(x) { x.cancel(); } function destroyed(x) { x.destroyed(); } function handleChange(x) { x.handleChange(); } function mark(x) { x.mark(); } function markForce(x) { x.mark(true); } function marked(x) { x.marked(); } function markedAll(x) { x.markedAll(); } function render(x) { x.render(); } function shuffled(x) { x.shuffled(); } function teardown(x) { x.teardown(); } function unbind(x) { x.unbind(); } function unrender(x) { x.unrender(); } function update(x) { x.update(); } function toString$1(x) { return x.toString(); } function toEscapedString(x) { return x.toString(true); } // this is the dry method of checking to see if a rebind applies to // a particular keypath because in some cases, a dep may be bound // directly to a particular keypath e.g. foo.bars.0.baz and need // to avoid getting kicked to foo.bars.1.baz if foo.bars is unshifted function rebindMatch(template, next, previous, fragment) { var keypath = template.r || template; // no valid keypath, go with next if (!keypath || !isString(keypath)) { return next; } // completely contextual ref, go with next if ( keypath === '.' || keypath[0] === '@' || (next || previous).isKey || (next || previous).isKeypath ) { return next; } var parts = keypath.split('/'); var keys = splitKeypath(parts[parts.length - 1]); var last = keys[keys.length - 1]; // check the keypath against the model keypath to see if it matches var model = next || previous; // check to see if this was an alias if (model && keys.length === 1 && last !== model.key && fragment) { keys = findAlias(last, fragment) || keys; } var i = keys.length; var match = true; var shuffling = false; while (model && i--) { if (model.shuffling) { shuffling = true; } // non-strict comparison to account for indices in keypaths if (keys[i] != model.key) { match = false; } model = model.parent; } // next is undefined, but keypath is shuffling and previous matches if (!next && match && shuffling) { return previous; } else if (next && !match && shuffling) // next is defined, but doesn't match the keypath { return previous; } else { return next; } } function findAlias(name, fragment) { while (fragment) { var z = fragment.aliases; if (z && z[name]) { var aliases = (fragment.owner.iterations ? fragment.owner : fragment).owner.template.z; for (var i = 0; i < aliases.length; i++) { if (aliases[i].n === name) { var alias = aliases[i].x; if (!alias.r) { return false; } var parts = alias.r.split('/'); return splitKeypath(parts[parts.length - 1]); } } return; } fragment = fragment.componentParent || fragment.parent; } } // temporary placeholder target for detached implicit links var Missing = { key: '@missing', animate: noop, applyValue: noop, get: noop, getKeypath: function getKeypath() { return this.key; }, joinAll: function joinAll() { return this; }, joinKey: function joinKey() { return this; }, mark: noop, registerLink: noop, shufle: noop, set: noop, unregisterLink: noop }; Missing.parent = Missing; var LinkModel = (function (ModelBase) { function LinkModel(parent, owner, target, key) { ModelBase.call(this, parent); this.owner = owner; this.target = target; this.key = key === undefined ? owner.key : key; if (owner && owner.isLink) { this.sourcePath = (owner.sourcePath) + "." + (this.key); } if (target) { target.registerLink(this); } if (parent) { this.isReadonly = parent.isReadonly; } this.isLink = true; } if ( ModelBase ) LinkModel.__proto__ = ModelBase; var LinkModel__proto__ = LinkModel.prototype = Object.create( ModelBase && ModelBase.prototype ); LinkModel__proto__.constructor = LinkModel; LinkModel__proto__.animate = function animate (from, to, options, interpolator) { return this.target.animate(from, to, options, interpolator); }; LinkModel__proto__.applyValue = function applyValue (value) { if (this.boundValue) { this.boundValue = null; } this.target.applyValue(value); }; LinkModel__proto__.attach = function attach (fragment) { var model = resolveReference(fragment, this.key); if (model) { this.relinking(model, false); } else { // if there is no link available, move everything here to real models this.owner.unlink(); } }; LinkModel__proto__.detach = function detach () { this.relinking(Missing, false); }; LinkModel__proto__.get = function get (shouldCapture, opts) { if ( opts === void 0 ) opts = {}; if (shouldCapture) { capture(this); // may need to tell the target to unwrap opts.unwrap = 'unwrap' in opts ? opts.unwrap : true; } var bind = 'shouldBind' in opts ? opts.shouldBind : true; opts.shouldBind = this.mapping && this.target.parent && this.target.parent.isRoot; return maybeBind(this, this.target.get(false, opts), bind); }; LinkModel__proto__.getKeypath = function getKeypath (ractive) { if (ractive && ractive !== this.root.ractive) { return this.target.getKeypath(ractive); } return ModelBase.prototype.getKeypath.call(this, ractive); }; LinkModel__proto__.handleChange = function handleChange$1 () { this.deps.forEach(handleChange); this.links.forEach(handleChange); this.notifyUpstream(); }; LinkModel__proto__.isDetached = function isDetached () { return this.virtual && this.target === Missing; }; LinkModel__proto__.joinKey = function joinKey (key) { // TODO: handle nested links if (key === undefined || key === '') { return this; } if (!hasOwn(this.childByKey, key)) { var child = new LinkModel(this, this, this.target.joinKey(key), key); this.children.push(child); this.childByKey[key] = child; } return this.childByKey[key]; }; LinkModel__proto__.mark = function mark (force) { this.target.mark(force); }; LinkModel__proto__.marked = function marked$1 () { if (this.boundValue) { this.boundValue = null; } this.links.forEach(marked); this.deps.forEach(handleChange); }; LinkModel__proto__.markedAll = function markedAll$1 () { this.children.forEach(markedAll); this.marked(); }; LinkModel__proto__.notifiedUpstream = function notifiedUpstream (startPath, root) { var this$1 = this; this.links.forEach(function (l) { return l.notifiedUpstream(startPath, this$1.root); }); this.deps.forEach(handleChange); if (startPath && this.rootLink && this.root !== root) { var path = startPath.slice(1); path.unshift(this.key); this.notifyUpstream(path); } }; LinkModel__proto__.relinked = function relinked () { this.target.registerLink(this); this.children.forEach(function (c) { return c.relinked(); }); }; LinkModel__proto__.relinking = function relinking (target, safe) { var this$1 = this; if (this.rootLink && this.sourcePath) { target = rebindMatch(this.sourcePath, target, this.target); } if (!target || this.target === target) { return; } this.target && this.target.unregisterLink(this); this.target = target; this.children.forEach(function (c) { c.relinking(target.joinKey(c.key), safe); }); if (this.rootLink) { this.addShuffleTask(function () { this$1.relinked(); if (!safe) { this$1.markedAll(); this$1.notifyUpstream(); } }); } }; LinkModel__proto__.set = function set (value) { if (this.boundValue) { this.boundValue = null; } this.target.set(value); }; LinkModel__proto__.shuffle = function shuffle$1 (newIndices) { // watch for extra shuffles caused by a shuffle in a downstream link if (this.shuffling) { return; } // let the real model handle firing off shuffles if (!this.target.shuffling) { if (this.target.shuffle) { this.target.shuffle(newIndices); } else { // the target is a computation, which can't shuffle this.target.mark(); } } else { shuffle(this, newIndices, true); } }; LinkModel__proto__.source = function source () { if (this.target.source) { return this.target.source(); } else { return this.target; } }; LinkModel__proto__.teardown = function teardown$3 () { if (this._link) { this._link.teardown(); } this.target.unregisterLink(this); this.children.forEach(teardown); }; return LinkModel; }(ModelBase)); ModelBase.prototype.link = function link(model, keypath, options) { var lnk = this._link || new LinkModel(this.parent, this, model, this.key); lnk.implicit = options && options.implicit; lnk.mapping = options && options.mapping; lnk.sourcePath = keypath; lnk.rootLink = true; if (this._link) { this._link.relinking(model, false); } this.rebind(lnk, this, false); fireShuffleTasks(); this._link = lnk; lnk.markedAll(); this.notifyUpstream(); return lnk; }; ModelBase.prototype.unlink = function unlink() { if (this._link) { var ln = this._link; this._link = undefined; ln.rebind(this, ln, false); fireShuffleTasks(); ln.teardown(); this.notifyUpstream(); } }; function fromExpression(body, length) { if ( length === void 0 ) length = 0; var args = new Array(length); while (length--) { args[length] = "_" + length; } // Functions created directly with new Function() look like this: // function anonymous (_0 /**/) { return _0*2 } // // With this workaround, we get a little more compact: // function (_0){return _0*2} return new Function([], ("return function (" + (args.join(',')) + "){return(" + body + ");};"))(); } var functions = create(null); function getFunction(str, i) { if (functions[str]) { return functions[str]; } return (functions[str] = createFunction(str, i)); } function addFunctions(template) { if (!template) { return; } var exp = template.e; if (!exp) { return; } keys(exp).forEach(function (str) { if (functions[str]) { return; } functions[str] = exp[str]; }); } var TEMPLATE_VERSION = 4; var leadingWhitespace = /^\s+/; var ParseError = function(message) { this.name = 'ParseError'; this.message = message; try { throw new Error(message); } catch (e) { this.stack = e.stack; } }; ParseError.prototype = Error.prototype; var Parser = function(str, options) { var item; var lineStart = 0; this.str = str; this.options = options || {}; this.pos = 0; this.lines = this.str.split('\n'); this.lineEnds = this.lines.map(function (line) { var lineEnd = lineStart + line.length + 1; // +1 for the newline lineStart = lineEnd; return lineEnd; }, 0); // Custom init logic if (this.init) { this.init(str, options); } var items = []; while (this.pos < this.str.length && (item = this.read())) { items.push(item); } this.leftover = this.remaining(); this.result = this.postProcess ? this.postProcess(items, options) : items; }; Parser.prototype = { read: function read(converters) { var this$1 = this; var i, item; if (!converters) { converters = this.converters; } var pos = this.pos; var len = converters.length; for (i = 0; i < len; i += 1) { this$1.pos = pos; // reset for each attempt if ((item = converters[i](this$1))) { return item; } } return null; }, getContextMessage: function getContextMessage(pos, message) { var ref = this.getLinePos(pos); var lineNum = ref[0]; var columnNum = ref[1]; if (this.options.contextLines === -1) { return [lineNum, columnNum, (message + " at line " + lineNum + " character " + columnNum)]; } var line = this.lines[lineNum - 1]; var contextUp = ''; var contextDown = ''; if (this.options.contextLines) { var start = lineNum - 1 - this.options.contextLines < 0 ? 0 : lineNum - 1 - this.options.contextLines; contextUp = this.lines .slice(start, lineNum - 1 - start) .join('\n') .replace(/\t/g, ' '); contextDown = this.lines .slice(lineNum, lineNum + this.options.contextLines) .join('\n') .replace(/\t/g, ' '); if (contextUp) { contextUp += '\n'; } if (contextDown) { contextDown = '\n' + contextDown; } } var numTabs = 0; var annotation = contextUp + line.replace(/\t/g, function (match, char) { if (char < columnNum) { numTabs += 1; } return ' '; }) + '\n' + new Array(columnNum + numTabs).join(' ') + '^----' + contextDown; return [ lineNum, columnNum, (message + " at line " + lineNum + " character " + columnNum + ":\n" + annotation) ]; }, getLinePos: function getLinePos(char) { var this$1 = this; var lineNum = 0; var lineStart = 0; while (char >= this.lineEnds[lineNum]) { lineStart = this$1.lineEnds[lineNum]; lineNum += 1; } var columnNum = char - lineStart; return [lineNum + 1, columnNum + 1, char]; // line/col should be one-based, not zero-based! }, error: function error(message) { var ref = this.getContextMessage(this.pos, message); var lineNum = ref[0]; var columnNum = ref[1]; var msg = ref[2]; var error = new ParseError(msg); error.line = lineNum; error.character = columnNum; error.shortMessage = message; throw error; }, matchString: function matchString(string) { if (this.str.substr(this.pos, string.length) === string) { this.pos += string.length; return string; } }, matchPattern: function matchPattern(pattern) { var match; if ((match = pattern.exec(this.remaining()))) { this.pos += match[0].length; return match[1] || match[0]; } }, sp: function sp() { this.matchPattern(leadingWhitespace); }, remaining: function remaining() { return this.str.substring(this.pos); }, nextChar: function nextChar() { return this.str.charAt(this.pos); }, warn: function warn(message) { var msg = this.getContextMessage(this.pos, message)[2]; warnIfDebug(msg); } }; Parser.extend = function(proto) { var Parent = this; var Child = function(str, options) { Parser.call(this, str, options); }; Child.prototype = create(Parent.prototype); for (var key in proto) { if (hasOwn(proto, key)) { Child.prototype[key] = proto[key]; } } Child.extend = Parser.extend; return Child; }; var TEXT = 1; var INTERPOLATOR = 2; var TRIPLE = 3; var SECTION = 4; var INVERTED = 5; var CLOSING = 6; var ELEMENT = 7; var PARTIAL = 8; var COMMENT = 9; var DELIMCHANGE = 10; var ANCHOR = 11; var ATTRIBUTE = 13; var CLOSING_TAG = 14; var COMPONENT = 15; var YIELDER = 16; var INLINE_PARTIAL = 17; var DOCTYPE = 18; var ALIAS = 19; var AWAIT = 55; var NUMBER_LITERAL = 20; var STRING_LITERAL = 21; var ARRAY_LITERAL = 22; var OBJECT_LITERAL = 23; var BOOLEAN_LITERAL = 24; var REGEXP_LITERAL = 25; var GLOBAL = 26; var KEY_VALUE_PAIR = 27; var REFERENCE = 30; var REFINEMENT = 31; var MEMBER = 32; var PREFIX_OPERATOR = 33; var BRACKETED = 34; var CONDITIONAL = 35; var INFIX_OPERATOR = 36; var INVOCATION = 40; var SECTION_IF = 50; var SECTION_UNLESS = 51; var SECTION_EACH = 52; var SECTION_WITH = 53; var SECTION_IF_WITH = 54; var ELSE = 60; var ELSEIF = 61; var THEN = 62; var CATCH = 63; var EVENT = 70; var DECORATOR = 71; var TRANSITION = 72; var BINDING_FLAG = 73; var DELEGATE_FLAG = 74; var delimiterChangePattern = /^[^\s=]+/; var whitespacePattern = /^\s+/; function readDelimiterChange(parser) { if (!parser.matchString('=')) { return null; } var start = parser.pos; // allow whitespace before new opening delimiter parser.sp(); var opening = parser.matchPattern(delimiterChangePattern); if (!opening) { parser.pos = start; return null; } // allow whitespace (in fact, it's necessary...) if (!parser.matchPattern(whitespacePattern)) { return null; } var closing = parser.matchPattern(delimiterChangePattern); if (!closing) { parser.pos = start; return null; } // allow whitespace before closing '=' parser.sp(); if (!parser.matchString('=')) { parser.pos = start; return null; } return [opening, closing]; } var regexpPattern = /^(\/(?:[^\n\r\u2028\u2029/\\[]|\\.|\[(?:[^\n\r\u2028\u2029\]\\]|\\.)*])+\/(?:([gimuy])(?![a-z]*\2))*(?![a-zA-Z_$0-9]))/; function readNumberLiteral(parser) { var result; if ((result = parser.matchPattern(regexpPattern))) { return { t: REGEXP_LITERAL, v: result }; } return null; } var pattern = /[-/\\^$*+?.()|[\]{}]/g; function escapeRegExp(str) { return str.replace(pattern, '\\$&'); } var regExpCache = {}; function getLowestIndex(haystack, needles) { return haystack.search( regExpCache[needles.join()] || (regExpCache[needles.join()] = new RegExp(needles.map(escapeRegExp).join('|'))) ); } // https://github.com/kangax/html-minifier/issues/63#issuecomment-37763316 //export const booleanAttributes = /^(allowFullscreen|async|autofocus|autoplay|checked|compact|controls|declare|default|defaultChecked|defaultMuted|defaultSelected|defer|disabled|enabled|formNoValidate|hidden|indeterminate|inert|isMap|itemScope|loop|multiple|muted|noHref|noResize|noShade|noValidate|noWrap|open|pauseOnExit|readOnly|required|reversed|scoped|seamless|selected|sortable|translate|trueSpeed|typeMustMatch|visible)$/i; var booleanAttributes = { allowfullscreen: 1, async: 1, autofocus: 1, autoplay: 1, checked: 1, compact: 1, controls: 1, declare: 1, default: 1, defaultchecked: 1, defaultmuted: 1, defaultselected: 1, defer: 1, disabled: 1, enabled: 1, formnovalidate: 1, hidden: 1, indeterminate: 1, inert: 1, ismap: 1, itemscope: 1, loop: 1, multiple: 1, muted: 1, nohref: 1, noresize: 1, noshade: 1, novalidate: 1, nowrap: 1, open: 1, pauseonexit: 1, readonly: 1, required: 1, reversed: 1, scoped: 1, seamless: 1, selected: 1, sortable: 1, translate: 1, truespeed: 1, typemustmatch: 1, visible: 1 }; var voidElements = { area: 1, base: 1, br: 1, col: 1, command: 1, doctype: 1, embed: 1, hr: 1, img: 1, input: 1, keygen: 1, link: 1, meta: 1, param: 1, source: 1, track: 1, wbr: 1 }; var htmlEntities = { quot: 34, amp: 38, apos: 39, lt: 60, gt: 62, nbsp: 160, iexcl: 161, cent: 162, pound: 163, curren: 164, yen: 165, brvbar: 166, sect: 167, uml: 168, copy: 169, ordf: 170, laquo: 171, not: 172, shy: 173, reg: 174, macr: 175, deg: 176, plusmn: 177, sup2: 178, sup3: 179, acute: 180, micro: 181, para: 182, middot: 183, cedil: 184, sup1: 185, ordm: 186, raquo: 187, frac14: 188, frac12: 189, frac34: 190, iquest: 191, Agrave: 192, Aacute: 193, Acirc: 194, Atilde: 195, Auml: 196, Aring: 197, AElig: 198, Ccedil: 199, Egrave: 200, Eacute: 201, Ecirc: 202, Euml: 203, Igrave: 204, Iacute: 205, Icirc: 206, Iuml: 207, ETH: 208, Ntilde: 209, Ograve: 210, Oacute: 211, Ocirc: 212, Otilde: 213, Ouml: 214, times: 215, Oslash: 216, Ugrave: 217, Uacute: 218, Ucirc: 219, Uuml: 220, Yacute: 221, THORN: 222, szlig: 223, agrave: 224, aacute: 225, acirc: 226, atilde: 227, auml: 228, aring: 229, aelig: 230, ccedil: 231, egrave: 232, eacute: 233, ecirc: 234, euml: 235, igrave: 236, iacute: 237, icirc: 238, iuml: 239, eth: 240, ntilde: 241, ograve: 242, oacute: 243, ocirc: 244, otilde: 245, ouml: 246, divide: 247, oslash: 248, ugrave: 249, uacute: 250, ucirc: 251, uuml: 252, yacute: 253, thorn: 254, yuml: 255, OElig: 338, oelig: 339, Scaron: 352, scaron: 353, Yuml: 376, fnof: 402, circ: 710, tilde: 732, Alpha: 913, Beta: 914, Gamma: 915, Delta: 916, Epsilon: 917, Zeta: 918, Eta: 919, Theta: 920, Iota: 921, Kappa: 922, Lambda: 923, Mu: 924, Nu: 925, Xi: 926, Omicron: 927, Pi: 928, Rho: 929, Sigma: 931, Tau: 932, Upsilon: 933, Phi: 934, Chi: 935, Psi: 936, Omega: 937, alpha: 945, beta: 946, gamma: 947, delta: 948, epsilon: 949, zeta: 950, eta: 951, theta: 952, iota: 953, kappa: 954, lambda: 955, mu: 956, nu: 957, xi: 958, omicron: 959, pi: 960, rho: 961, sigmaf: 962, sigma: 963, tau: 964, upsilon: 965, phi: 966, chi: 967, psi: 968, omega: 969, thetasym: 977, upsih: 978, piv: 982, ensp: 8194, emsp: 8195, thinsp: 8201, zwnj: 8204, zwj: 8205, lrm: 8206, rlm: 8207, ndash: 8211, mdash: 8212, lsquo: 8216, rsquo: 8217, sbquo: 8218, ldquo: 8220, rdquo: 8221, bdquo: 8222, dagger: 8224, Dagger: 8225, bull: 8226, hellip: 8230, permil: 8240, prime: 8242, Prime: 8243, lsaquo: 8249, rsaquo: 8250, oline: 8254, frasl: 8260, euro: 8364, image: 8465, weierp: 8472, real: 8476, trade: 8482, alefsym: 8501, larr: 8592, uarr: 8593, rarr: 8594, darr: 8595, harr: 8596, crarr: 8629, lArr: 8656, uArr: 8657, rArr: 8658, dArr: 8659, hArr: 8660, forall: 8704, part: 8706, exist: 8707, empty: 8709, nabla: 8711, isin: 8712, notin: 8713, ni: 8715, prod: 8719, sum: 8721, minus: 8722, lowast: 8727, radic: 8730, prop: 8733, infin: 8734, ang: 8736, and: 8743, or: 8744, cap: 8745, cup: 8746, int: 8747, there4: 8756, sim: 8764, cong: 8773, asymp: 8776, ne: 8800, equiv: 8801, le: 8804, ge: 8805, sub: 8834, sup: 8835, nsub: 8836, sube: 8838, supe: 8839, oplus: 8853, otimes: 8855, perp: 8869, sdot: 8901, lceil: 8968, rceil: 8969, lfloor: 8970, rfloor: 8971, lang: 9001, rang: 9002, loz: 9674, spades: 9824, clubs: 9827, hearts: 9829, diams: 9830 }; var controlCharacters = [ 8364, 129, 8218, 402, 8222, 8230, 8224, 8225, 710, 8240, 352, 8249, 338, 141, 381, 143, 144, 8216, 8217, 8220, 8221, 8226, 8211, 8212, 732, 8482, 353, 8250, 339, 157, 382, 376 ]; var entityPattern = new RegExp( '&(#?(?:x[\\w\\d]+|\\d+|' + keys(htmlEntities).join('|') + '));?', 'g' ); var codePointSupport = isFunction(String.fromCodePoint); var codeToChar = codePointSupport ? String.fromCodePoint : String.fromCharCode; function decodeCharacterReferences(html) { return html.replace(entityPattern, function (match, entity) { var code; // Handle named entities if (entity[0] !== '#') { code = htmlEntities[entity]; } else if (entity[1] === 'x') { code = parseInt(entity.substring(2), 16); } else { code = parseInt(entity.substring(1), 10); } if (!code) { return match; } return codeToChar(validateCode(code)); }); } var lessThan = /</g; var greaterThan = />/g; var amp = /&/g; var invalid = 65533; function escapeHtml(str) { return str .replace(amp, '&amp;') .replace(lessThan, '&lt;') .replace(greaterThan, '&gt;'); } // some code points are verboten. If we were inserting HTML, the browser would replace the illegal // code points with alternatives in some cases - since we're bypassing that mechanism, we need // to replace them ourselves // // Source: http://en.wikipedia.org/wiki/Character_encodings_in_HTML#Illegal_characters /* istanbul ignore next */ function validateCode(code) { if (!code) { return invalid; } // line feed becomes generic whitespace if (code === 10) { return 32; } // ASCII range. (Why someone would use HTML entities for ASCII characters I don't know, but...) if (code < 128) { return code; } // code points 128-159 are dealt with leniently by browsers, but they're incorrect. We need // to correct the mistake or we'll end up with missing € signs and so on if (code <= 159) { return controlCharacters[code - 128]; } // basic multilingual plane if (code < 55296) { return code; } // UTF-16 surrogate halves if (code <= 57343) { return invalid; } // rest of the basic multilingual plane if (code <= 65535) { return code; } else if (!codePointSupport) { return invalid; } // supplementary multilingual plane 0x10000 - 0x1ffff if (code >= 65536 && code <= 131071) { return code; } // supplementary ideographic plane 0x20000 - 0x2ffff if (code >= 131072 && code <= 196607) { return code; } return invalid; } var expectedExpression = 'Expected a JavaScript expression'; var expectedParen = 'Expected closing paren'; // bulletproof number regex from https://gist.github.com/Rich-Harris/7544330 var numberPattern = /^(?:[+-]?)0*(?:(?:(?:[1-9]\d*)?\.\d+)|(?:(?:0|[1-9]\d*)\.)|(?:0|[1-9]\d*))(?:[eE][+-]?\d+)?/; function readNumberLiteral$1(parser) { var result; if ((result = parser.matchPattern(numberPattern))) { return { t: NUMBER_LITERAL, v: result }; } return null; } function readBooleanLiteral(parser) { var remaining = parser.remaining(); if (remaining.substr(0, 4) === 'true') { parser.pos += 4; return { t: BOOLEAN_LITERAL, v: 'true' }; } if (remaining.substr(0, 5) === 'false') { parser.pos += 5; return { t: BOOLEAN_LITERAL, v: 'false' }; } return null; } // Match one or more characters until: ", ', \, or EOL/EOF. // EOL/EOF is written as (?!.) (meaning there's no non-newline char next). var stringMiddlePattern = /^(?=.)[^"'\\]+?(?:(?!.)|(?=["'\\]))/; // Match one escape sequence, including the backslash. var escapeSequencePattern = /^\\(?:[`'"\\bfnrt]|0(?![0-9])|x[0-9a-fA-F]{2}|u[0-9a-fA-F]{4}|(?=.)[^ux0-9])/; // Match one ES5 line continuation (backslash + line terminator). var lineContinuationPattern = /^\\(?:\r\n|[\u000A\u000D\u2028\u2029])/; // Helper for defining getDoubleQuotedString and getSingleQuotedString. function makeQuotedStringMatcher(okQuote) { return function(parser) { var literal = '"'; var done = false; var next; while (!done) { next = parser.matchPattern(stringMiddlePattern) || parser.matchPattern(escapeSequencePattern) || parser.matchString(okQuote); if (next) { if (next === "\"") { literal += "\\\""; } else if (next === "\\'") { literal += "'"; } else { literal += next; } } else { next = parser.matchPattern(lineContinuationPattern); if (next) { // convert \(newline-like) into a \u escape, which is allowed in JSON literal += '\\u' + ('000' + next.charCodeAt(1).toString(16)).slice(-4); } else { done = true; } } } literal += '"'; // use JSON.parse to interpret escapes return JSON.parse(literal); }; } var singleMatcher = makeQuotedStringMatcher("\""); var doubleMatcher = makeQuotedStringMatcher("'"); function readStringLiteral(parser) { var start = parser.pos; var quote = parser.matchString("'") || parser.matchString("\""); if (quote) { var string = (quote === "'" ? singleMatcher : doubleMatcher)(parser); if (!parser.matchString(quote)) { parser.pos = start; return null; } return { t: STRING_LITERAL, v: string }; } return null; } // Match one or more characters until: ", ', or \ var stringMiddlePattern$1 = /^[^`"\\\$]+?(?:(?=[`"\\\$]))/; var escapes = /[\r\n\t\b\f]/g; function getString(literal) { return JSON.parse(("\"" + (literal.replace(escapes, escapeChar)) + "\"")); } function escapeChar(c) { switch (c) { case '\n': return '\\n'; case '\r': return '\\r'; case '\t': return '\\t'; case '\b': return '\\b'; case '\f': return '\\f'; } } function readTemplateStringLiteral(parser) { if (!parser.matchString('`')) { return null; } var literal = ''; var done = false; var next; var parts = []; while (!done) { next = parser.matchPattern(stringMiddlePattern$1) || parser.matchPattern(escapeSequencePattern) || parser.matchString('$') || parser.matchString('"'); if (next) { if (next === "\"") { literal += "\\\""; } else if (next === '\\`') { literal += '`'; } else if (next === '$') { if (parser.matchString('{')) { parts.push({ t: STRING_LITERAL, v: getString(literal) }); literal = ''; parser.sp(); var expr = readExpression(parser); if (!expr) { parser.error('Expected valid expression'); } parts.push({ t: BRACKETED, x: expr }); parser.sp(); if (!parser.matchString('}')) { parser.error("Expected closing '}' after interpolated expression"); } } else { literal += '$'; } } else { literal += next; } } else { next = parser.matchPattern(lineContinuationPattern); if (next) { // convert \(newline-like) into a \u escape, which is allowed in JSON literal += '\\u' + ('000' + next.charCodeAt(1).toString(16)).slice(-4); } else { done = true; } } } if (literal.length) { parts.push({ t: STRING_LITERAL, v: getString(literal) }); } if (!parser.matchString('`')) { parser.error("Expected closing '`'"); } if (parts.length === 1) { return parts[0]; } else { var result = parts.pop(); var part; while ((part = parts.pop())) { result = { t: INFIX_OPERATOR, s: '+', o: [part, result] }; } return { t: BRACKETED, x: result }; } } var name = /^[a-zA-Z_$][a-zA-Z_$0-9]*/; var spreadPattern = /^\s*\.{3}/; var legalReference = /^(?:[a-zA-Z$_0-9]|\\\.)+(?:(?:\.(?:[a-zA-Z$_0-9]|\\\.)+)|(?:\[[0-9]+\]))*/; var relaxedName = /^[a-zA-Z_$][-\/a-zA-Z_$0-9]*(?:\.(?:[a-zA-Z_$][-\/a-zA-Z_$0-9]*))*/; var identifier = /^[a-zA-Z_$][a-zA-Z_$0-9]*$/; // http://mathiasbynens.be/notes/javascript-properties // can be any name, string literal, or number literal function readKey(parser) { var token; if ((token = readStringLiteral(parser))) { return identifier.test(token.v) ? token.v : '"' + token.v.replace(/"/g, '\\"') + '"'; } if ((token = readNumberLiteral$1(parser))) { return token.v; } if ((token = parser.matchPattern(name))) { return token; } return null; } function readKeyValuePair(parser) { var spread; var start = parser.pos; // allow whitespace between '{' and key parser.sp(); var refKey = parser.nextChar() !== "'" && parser.nextChar() !== '"'; if (refKey) { spread = parser.matchPattern(spreadPattern); } var key = spread ? readExpression(parser) : readKey(parser); if (key === null) { parser.pos = start; return null; } // allow whitespace between key and ':' parser.sp(); // es2015 shorthand property if (refKey && (parser.nextChar() === ',' || parser.nextChar() === '}')) { if (!spread && !name.test(key)) { parser.error(("Expected a valid reference, but found '" + key + "' instead.")); } var pair = { t: KEY_VALUE_PAIR, k: key, v: { t: REFERENCE, n: key } }; if (spread) { pair.p = true; } return pair; } // next character must be ':' if (!parser.matchString(':')) { parser.pos = start; return null; } // allow whitespace between ':' and value parser.sp(); // next expression must be a, well... expression var value = readExpression(parser); if (value === null) { parser.pos = start; return null; } return { t: KEY_VALUE_PAIR, k: key, v: value }; } function readKeyValuePairs(parser) { var start = parser.pos; var pair = readKeyValuePair(parser); if (pair === null) { return null; } var pairs = [pair]; if (parser.matchString(',')) { var keyValuePairs = readKeyValuePairs(parser); if (!keyValuePairs) { parser.pos = start; return null; } return pairs.concat(keyValuePairs); } return pairs; } function readObjectLiteral(parser) { var start = parser.pos; // allow whitespace parser.sp(); if (!parser.matchString('{')) { parser.pos = start; return null; } var keyValuePairs = readKeyValuePairs(parser); // allow whitespace between final value and '}' parser.sp(); if (!parser.matchString('}')) { parser.pos = start; return null; } return { t: OBJECT_LITERAL, m: keyValuePairs }; } function readArrayLiteral(parser) { var start = parser.pos; // allow whitespace before '[' parser.sp(); if (!parser.matchString('[')) { parser.pos = start; return null; } var expressionList = readExpressionList(parser, true); if (!parser.matchString(']')) { parser.pos = start; return null; } return { t: ARRAY_LITERAL, m: expressionList }; } function readLiteral(parser) { return ( readNumberLiteral$1(parser) || readBooleanLiteral(parser) || readStringLiteral(parser) || readTemplateStringLiteral(parser) || readObjectLiteral(parser) || readArrayLiteral(parser) || readNumberLiteral(parser) ); } // if a reference is a browser global, we don't deference it later, so it needs special treatment var globals = /^(?:Array|console|Date|RegExp|decodeURIComponent|decodeURI|encodeURIComponent|encodeURI|isFinite|isNaN|parseFloat|parseInt|JSON|Math|NaN|undefined|null|Object|Number|String|Boolean)\b/; // keywords are not valid references, with the exception of `this` var keywords = /^(?:break|case|catch|continue|debugger|default|delete|do|else|finally|for|function|if|in|instanceof|new|return|switch|throw|try|typeof|var|void|while|with)$/; var prefixPattern = /^(?:\@\.|\@|~\/|(?:\^\^\/(?:\^\^\/)*(?:\.\.\/)*)|(?:\.\.\/)+|\.\/(?:\.\.\/)*|\.)/; var specials = /^(key|index|keypath|rootpath|this|global|shared|context|event|node|local|style|helpers|last|macro)/; function readReference(parser) { var prefix, name$$1, global, reference, lastDotIndex; var startPos = parser.pos; prefix = parser.matchPattern(prefixPattern) || ''; name$$1 = (!prefix && parser.relaxedNames && parser.matchPattern(relaxedName)) || parser.matchPattern(legalReference); var actual = prefix.length + ((name$$1 && name$$1.length) || 0); if (prefix === '@.') { prefix = '@'; if (name$$1) { name$$1 = 'this.' + name$$1; } else { name$$1 = 'this'; } } if (!name$$1 && prefix) { name$$1 = prefix; prefix = ''; } if (!name$$1) { return null; } if (prefix === '@') { if (!specials.test(name$$1)) { parser.error(("Unrecognized special reference @" + name$$1)); } else if ((!name$$1.indexOf('event') || !name$$1.indexOf('node')) && !parser.inEvent) { parser.error("@event and @node are only valid references within an event directive"); } else if (~name$$1.indexOf('context')) { parser.pos = parser.pos - (name$$1.length - 7); return { t: BRACKETED, x: { t: REFERENCE, n: '@context' } }; } } // bug out if it's a keyword (exception for ancestor/restricted refs - see https://github.com/ractivejs/ractive/issues/1497) if (!prefix && !parser.relaxedNames && keywords.test(name$$1)) { parser.pos = startPos; return null; } // if this is a browser global, stop here if (!prefix && globals.test(name$$1)) { global = globals.exec(name$$1)[0]; parser.pos = startPos + global.length; return { t: GLOBAL, v: global }; } reference = (prefix || '') + normalise(name$$1); if (parser.matchString('(')) { // if this is a method invocation (as opposed to a function) we need // to strip the method name from the reference combo, else the context // will be wrong // but only if the reference was actually a member and not a refinement lastDotIndex = reference.lastIndexOf('.'); if (lastDotIndex !== -1 && name$$1[name$$1.length - 1] !== ']') { if (lastDotIndex === 0) { reference = '.'; parser.pos = startPos; } else { var refLength = reference.length; reference = reference.substr(0, lastDotIndex); parser.pos = startPos + (actual - (refLength - lastDotIndex)); } } else { parser.pos -= 1; } } return { t: REFERENCE, n: reference.replace(/^this\./, './').replace(/^this$/, '.') }; } function readBracketedExpression(parser) { if (!parser.matchString('(')) { return null; } parser.sp(); var expr = readExpression(parser); if (!expr) { parser.error(expectedExpression); } parser.sp(); if (!parser.matchString(')')) { parser.error(expectedParen); } return { t: BRACKETED, x: expr }; } function readPrimary(parser) { return readLiteral(parser) || readReference(parser) || readBracketedExpression(parser); } function readRefinement(parser) { // some things call for strict refinement (partial names), meaning no space between reference and refinement if (!parser.strictRefinement) { parser.sp(); } // "." name if (parser.matchString('.')) { parser.sp(); var name$$1 = parser.matchPattern(name); if (name$$1) { return { t: REFINEMENT, n: name$$1 }; } parser.error('Expected a property name'); } // "[" expression "]" if (parser.matchString('[')) { parser.sp(); var expr = readExpression(parser); if (!expr) { parser.error(expectedExpression); } parser.sp(); if (!parser.matchString(']')) { parser.error("Expected ']'"); } return { t: REFINEMENT, x: expr }; } return null; } function readMemberOrInvocation(parser) { var expression = readPrimary(parser); if (!expression) { return null; } while (expression) { var refinement = readRefinement(parser); if (refinement) { expression = { t: MEMBER, x: expression, r: refinement }; } else if (parser.matchString('(')) { parser.sp(); var expressionList = readExpressionList(parser, true); parser.sp(); if (!parser.matchString(')')) { parser.error(expectedParen); } expression = { t: INVOCATION, x: expression }; if (expressionList) { expression.o = expressionList; } } else { break; } } return expression; } var readTypeOf; var makePrefixSequenceMatcher = function(symbol, fallthrough) { return function(parser) { var expression; if ((expression = fallthrough(parser))) { return expression; } if (!parser.matchString(symbol)) { return null; } parser.sp(); expression = readExpression(parser); if (!expression) { parser.error(expectedExpression); } return { s: symbol, o: expression, t: PREFIX_OPERATOR }; }; }; // create all prefix sequence matchers, return readTypeOf (function() { var i, len, matcher, fallthrough; var prefixOperators = '! ~ + - typeof'.split(' '); fallthrough = readMemberOrInvocation; for (i = 0, len = prefixOperators.length; i < len; i += 1) { matcher = makePrefixSequenceMatcher(prefixOperators[i], fallthrough); fallthrough = matcher; } // typeof operator is higher precedence than multiplication, so provides the // fallthrough for the multiplication sequence matcher we're about to create // (we're skipping void and delete) readTypeOf = fallthrough; })(); var readTypeof = readTypeOf; var readLogicalOr; var makeInfixSequenceMatcher = function(symbol, fallthrough) { return function(parser) { // > and / have to be quoted if (parser.inUnquotedAttribute && (symbol === '>' || symbol === '/')) { return fallthrough(parser); } var start, left, right; left = fallthrough(parser); if (!left) { return null; } // Loop to handle left-recursion in a case like `a * b * c` and produce // left association, i.e. `(a * b) * c`. The matcher can't call itself // to parse `left` because that would be infinite regress. while (true) { start = parser.pos; parser.sp(); if (!parser.matchString(symbol)) { parser.pos = start; return left; } // special case - in operator must not be followed by [a-zA-Z_$0-9] if (symbol === 'in' && /[a-zA-Z_$0-9]/.test(parser.remaining().charAt(0))) { parser.pos = start; return left; } parser.sp(); // right operand must also consist of only higher-precedence operators right = fallthrough(parser); if (!right) { parser.pos = start; return left; } left = { t: INFIX_OPERATOR, s: symbol, o: [left, right] }; // Loop back around. If we don't see another occurrence of the symbol, // we'll return left. } }; }; // create all infix sequence matchers, and return readLogicalOr (function() { var i, len, matcher, fallthrough; // All the infix operators on order of precedence (source: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Operator_Precedence) // Each sequence matcher will initially fall through to its higher precedence // neighbour, and only attempt to match if one of the higher precedence operators // (or, ultimately, a literal, reference, or bracketed expression) already matched var infixOperators = '* / % + - << >> >>> < <= > >= in instanceof == != === !== & ^ | && ||'.split( ' ' ); // A typeof operator is higher precedence than multiplication fallthrough = readTypeof; for (i = 0, len = infixOperators.length; i < len; i += 1) { matcher = makeInfixSequenceMatcher(infixOperators[i], fallthrough); fallthrough = matcher; } // Logical OR is the fallthrough for the conditional matcher readLogicalOr = fallthrough; })(); var readLogicalOr$1 = readLogicalOr; // The conditional operator is the lowest precedence operator, so we start here function getConditional(parser) { var expression = readLogicalOr$1(parser); if (!expression) { return null; } var start = parser.pos; parser.sp(); if (!parser.matchString('?')) { parser.pos = start; return expression; } parser.sp(); var ifTrue = readExpression(parser); if (!ifTrue) { parser.error(expectedExpression); } parser.sp(); if (!parser.matchString(':')) { parser.error('Expected ":"'); } parser.sp(); var ifFalse = readExpression(parser); if (!ifFalse) { parser.error(expectedExpression); } return { t: CONDITIONAL, o: [expression, ifTrue, ifFalse] }; } function readExpression(parser) { // if eval is false, no expressions if (parser.allowExpressions === false) { var ref = readReference(parser); parser.sp(); return ref; } // The conditional operator is the lowest precedence operator (except yield, // assignment operators, and commas, none of which are supported), so we // start there. If it doesn't match, it 'falls through' to progressively // higher precedence operators, until it eventually matches (or fails to // match) a 'primary' - a literal or a reference. This way, the abstract syntax // tree has everything in its proper place, i.e. 2 + 3 * 4 === 14, not 20. return getConditional(parser); } function readExpressionList(parser, spread) { var isSpread; var expressions = []; var pos = parser.pos; do { parser.sp(); if (spread) { isSpread = parser.matchPattern(spreadPattern); } var expr = readExpression(parser); if (expr === null && expressions.length) { parser.error(expectedExpression); } else if (expr === null) { parser.pos = pos; return null; } if (isSpread) { expr.p = true; } expressions.push(expr); parser.sp(); } while (parser.matchString(',')); return expressions; } function readExpressionOrReference(parser, expectedFollowers) { var start = parser.pos; var expression = readExpression(parser); if (!expression) { // valid reference but invalid expression e.g. `{{new}}`? var ref = parser.matchPattern(/^(\w+)/); if (ref) { return { t: REFERENCE, n: ref }; } return null; } for (var i = 0; i < expectedFollowers.length; i += 1) { if (parser.remaining().substr(0, expectedFollowers[i].length) === expectedFollowers[i]) { return expression; } } parser.pos = start; return readReference(parser); } function flattenExpression(expression) { var refs; var count = 0; extractRefs(expression, (refs = [])); var stringified = stringify(expression); return { r: refs, s: getVars(stringified) }; function getVars(expr) { var vars = []; for (var i = count - 1; i >= 0; i--) { vars.push(("x$" + i)); } return vars.length ? ("(function(){var " + (vars.join(',')) + ";return(" + expr + ");})()") : expr; } function stringify(node) { if (isString(node)) { return node; } switch (node.t) { case BOOLEAN_LITERAL: case GLOBAL: case NUMBER_LITERAL: case REGEXP_LITERAL: return node.v; case STRING_LITERAL: return JSON.stringify(String(node.v)); case ARRAY_LITERAL: if (node.m && hasSpread(node.m)) { return ("[].concat(" + (makeSpread(node.m, '[', ']', stringify)) + ")"); } else { return '[' + (node.m ? node.m.map(stringify).join(',') : '') + ']'; } case OBJECT_LITERAL: if (node.m && hasSpread(node.m)) { return ("Object.assign({}," + (makeSpread(node.m, '{', '}', stringifyPair)) + ")"); } else { return '{' + (node.m ? node.m.map(function (n) { return ((n.k) + ":" + (stringify(n.v))); }).join(',') : '') + '}'; } case PREFIX_OPERATOR: return (node.s === 'typeof' ? 'typeof ' : node.s) + stringify(node.o); case INFIX_OPERATOR: return ( stringify(node.o[0]) + (node.s.substr(0, 2) === 'in' ? ' ' + node.s + ' ' : node.s) + stringify(node.o[1]) ); case INVOCATION: if (node.o && hasSpread(node.o)) { var id = count++; return ("(x$" + id + "=" + (stringify(node.x)) + ").apply(x$" + id + "," + (stringify({ t: ARRAY_LITERAL, m: node.o })) + ")"); } else { return stringify(node.x) + '(' + (node.o ? node.o.map(stringify).join(',') : '') + ')'; } case BRACKETED: return '(' + stringify(node.x) + ')'; case MEMBER: return stringify(node.x) + stringify(node.r); case REFINEMENT: return node.n ? '.' + node.n : '[' + stringify(node.x) + ']'; case CONDITIONAL: return stringify(node.o[0]) + '?' + stringify(node.o[1]) + ':' + stringify(node.o[2]); case REFERENCE: return '_' + refs.indexOf(node.n); default: throw new Error('Expected legal JavaScript'); } } function stringifyPair(node) { return node.p ? stringify(node.k) : ((node.k) + ":" + (stringify(node.v))); } function makeSpread(list, open, close, fn) { var out = list.reduce( function (a, c) { if (c.p) { a.str += "" + (a.open ? close + ',' : a.str.length ? ',' : '') + (fn(c)); } else { a.str += "" + (!a.str.length ? open : !a.open ? ',' + open : ',') + (fn(c)); } a.open = !c.p; return a; }, { open: false, str: '' } ); if (out.open) { out.str += close; } return out.str; } } function hasSpread(list) { for (var i = 0; i < list.length; i++) { if (list[i].p) { return true; } } return false; } // TODO maybe refactor this? function extractRefs(node, refs) { if (node.t === REFERENCE && isString(node.n)) { if (!~refs.indexOf(node.n)) { refs.unshift(node.n); } } var list = node.o || node.m; if (list) { if (isObject(list)) { extractRefs(list, refs); } else { var i = list.length; while (i--) { extractRefs(list[i], refs); } } } if (node.k && node.t === KEY_VALUE_PAIR && !isString(node.k)) { extractRefs(node.k, refs); } if (node.x) { extractRefs(node.x, refs); } if (node.r) { extractRefs(node.r, refs); } if (node.v) { extractRefs(node.v, refs); } } function refineExpression(expression, mustache) { var referenceExpression; if (expression) { while (expression.t === BRACKETED && expression.x) { expression = expression.x; } if (expression.t === REFERENCE) { var n = expression.n; if (!~n.indexOf('@context')) { mustache.r = expression.n; } else { mustache.x = flattenExpression(expression); } } else { if ((referenceExpression = getReferenceExpression(expression))) { mustache.rx = referenceExpression; } else { mustache.x = flattenExpression(expression); } } return mustache; } } // TODO refactor this! it's bewildering function getReferenceExpression(expression) { var members = []; var refinement; while (expression.t === MEMBER && expression.r.t === REFINEMENT) { refinement = expression.r; if (refinement.x) { if (refinement.x.t === REFERENCE) { members.unshift(refinement.x); } else { members.unshift(flattenExpression(refinement.x)); } } else { members.unshift(refinement.n); } expression = expression.x; } if (expression.t !== REFERENCE) { return null; } return { r: expression.n, m: members }; } var attributeNamePattern = /^[^\s"'>\/=(]+/; var onPattern = /^on/; var eventPattern = /^on-([a-zA-Z\*\.$_]((?:[a-zA-Z\*\.$_0-9\-]|\\-)+))$/; var reservedEventNames = /^(?:change|reset|teardown|update|construct|config|init|render|complete|unrender|detach|insert|destruct|attachchild|detachchild)$/; var decoratorPattern = /^as-([a-z-A-Z][-a-zA-Z_0-9]*)$/; var transitionPattern = /^([a-zA-Z](?:(?!-in-out)[-a-zA-Z_0-9])*)-(in|out|in-out)$/; var boundPattern = /^((bind|class)-(([-a-zA-Z0-9_])+))$/; var directives = { lazy: { t: BINDING_FLAG, v: 'l' }, twoway: { t: BINDING_FLAG, v: 't' }, 'no-delegation': { t: DELEGATE_FLAG } }; var unquotedAttributeValueTextPattern = /^[^\s"'=<>\/`]+/; var proxyEvent = /^[^\s"'=<>@\[\]()]*/; var whitespace = /^\s+/; var slashes = /\\/g; function splitEvent(str) { var result = []; var s = 0; for (var i = 0; i < str.length; i++) { if (str[i] === '-' && str[i - 1] !== '\\') { result.push(str.substring(s, i).replace(slashes, '')); s = i + 1; } } result.push(str.substring(s).replace(slashes, '')); return result; } function readAttribute(parser) { var name, i, nearest, idx; parser.sp(); name = parser.matchPattern(attributeNamePattern); if (!name) { return null; } // check for accidental delimiter consumption e.g. <tag bool{{>attrs}} /> nearest = name.length; for (i = 0; i < parser.tags.length; i++) { if (~(idx = name.indexOf(parser.tags[i].open))) { if (idx < nearest) { nearest = idx; } } } if (nearest < name.length) { parser.pos -= name.length - nearest; name = name.substr(0, nearest); if (!name) { return null; } } return { n: name }; } function readAttributeValue(parser) { var start = parser.pos; // next character must be `=`, `/`, `>` or whitespace if (!/[=\/>\s]/.test(parser.nextChar())) { parser.error('Expected `=`, `/`, `>` or whitespace'); } parser.sp(); if (!parser.matchString('=')) { parser.pos = start; return null; } parser.sp(); var valueStart = parser.pos; var startDepth = parser.sectionDepth; var value = readQuotedAttributeValue(parser, "'") || readQuotedAttributeValue(parser, "\"") || readUnquotedAttributeValue(parser); if (value === null) { parser.error('Expected valid attribute value'); } if (parser.sectionDepth !== startDepth) { parser.pos = valueStart; parser.error( 'An attribute value must contain as many opening section tags as closing section tags' ); } if (!value.length) { return ''; } if (value.length === 1 && isString(value[0])) { return decodeCharacterReferences(value[0]); } return value; } function readUnquotedAttributeValueToken(parser) { var text, index; var start = parser.pos; text = parser.matchPattern(unquotedAttributeValueTextPattern); if (!text) { return null; } var haystack = text; var needles = parser.tags.map(function (t) { return t.open; }); // TODO refactor... we do this in readText.js as well if ((index = getLowestIndex(haystack, needles)) !== -1) { text = text.substr(0, index); parser.pos = start + text.length; } return text; } function readUnquotedAttributeValue(parser) { parser.inAttribute = true; var tokens = []; var token = readMustache(parser) || readUnquotedAttributeValueToken(parser); while (token) { tokens.push(token); token = readMustache(parser) || readUnquotedAttributeValueToken(parser); } if (!tokens.length) { return null; } parser.inAttribute = false; return tokens; } function readQuotedAttributeValue(parser, quoteMark) { var start = parser.pos; if (!parser.matchString(quoteMark)) { return null; } parser.inAttribute = quoteMark; var tokens = []; var token = readMustache(parser) || readQuotedStringToken(parser, quoteMark); while (token !== null) { tokens.push(token); token = readMustache(parser) || readQuotedStringToken(parser, quoteMark); } if (!parser.matchString(quoteMark)) { parser.pos = start; return null; } parser.inAttribute = false; return tokens; } function readQuotedStringToken(parser, quoteMark) { var haystack = parser.remaining(); var needles = parser.tags.map(function (t) { return t.open; }); // TODO refactor... we do this in readText.js as well needles.push(quoteMark); var index = getLowestIndex(haystack, needles); if (index === -1) { parser.error('Quoted attribute value must have a closing quote'); } if (!index) { return null; } parser.pos += index; return haystack.substr(0, index); } function readAttributeOrDirective(parser) { var match, directive; var attribute = readAttribute(parser, false); if (!attribute) { return null; } // lazy, twoway if ((directive = directives[attribute.n])) { attribute.t = directive.t; if (directive.v) { attribute.v = directive.v; } delete attribute.n; // no name necessary parser.sp(); if (parser.nextChar() === '=') { attribute.f = readAttributeValue(parser); } } else if ((match = decoratorPattern.exec(attribute.n))) { // decorators attribute.n = match[1]; attribute.t = DECORATOR; readArguments(parser, attribute); } else if ((match = transitionPattern.exec(attribute.n))) { // transitions attribute.n = match[1]; attribute.t = TRANSITION; readArguments(parser, attribute); attribute.v = match[2] === 'in-out' ? 't0' : match[2] === 'in' ? 't1' : 't2'; } else if ((match = eventPattern.exec(attribute.n))) { // on-click etc attribute.n = splitEvent(match[1]); attribute.t = EVENT; if (parser.matchString('(')) { attribute.a = flattenExpression({ t: ARRAY_LITERAL, m: readExpressionList(parser) }); if (!parser.matchString(')')) { parser.error("Expected closing ')'"); } } parser.inEvent = true; // check for a proxy event if (!readProxyEvent(parser, attribute)) { // otherwise, it's an expression readArguments(parser, attribute, true); } else if (reservedEventNames.test(attribute.f)) { parser.pos -= attribute.f.length; parser.error( 'Cannot use reserved event names (change, reset, teardown, update, construct, config, init, render, unrender, complete, detach, insert, destruct, attachchild, detachchild)' ); } parser.inEvent = false; } else if ((match = boundPattern.exec(attribute.n))) { // bound directives var bind = match[2] === 'bind'; attribute.n = bind ? match[3] : match[1]; attribute.t = ATTRIBUTE; readArguments(parser, attribute, false, true); if (!attribute.f && bind) { attribute.f = [{ t: INTERPOLATOR, r: match[3] }]; } } else { parser.sp(); var value = parser.nextChar() === '=' ? readAttributeValue(parser) : null; attribute.f = value != null ? value : attribute.f; if (parser.sanitizeEventAttributes && onPattern.test(attribute.n)) { return { exclude: true }; } else { attribute.f = attribute.f || (attribute.f === '' ? '' : 0); attribute.t = ATTRIBUTE; } } return attribute; } function readProxyEvent(parser, attribute) { var start = parser.pos; if (!parser.matchString('=')) { parser.error("Missing required directive arguments"); } var quote = parser.matchString("'") || parser.matchString("\""); parser.sp(); var proxy = parser.matchPattern(proxyEvent); if (proxy !== undefined) { if (quote) { parser.sp(); if (!parser.matchString(quote)) { parser.pos = start; } else { return (attribute.f = proxy) || true; } } else if (!parser.matchPattern(whitespace)) { parser.pos = start; } else { return (attribute.f = proxy) || true; } } else { parser.pos = start; } } function readArguments(parser, attribute, required, single) { if ( required === void 0 ) required = false; if ( single === void 0 ) single = false; parser.sp(); if (!parser.matchString('=')) { if (required) { parser.error("Missing required directive arguments"); } return; } parser.sp(); var quote = parser.matchString('"') || parser.matchString("'"); var spread = parser.spreadArgs; parser.spreadArgs = true; parser.inUnquotedAttribute = !quote; var expr = single ? readExpressionOrReference(parser, [quote || ' ', '/', '>']) : { m: readExpressionList(parser), t: ARRAY_LITERAL }; parser.inUnquotedAttribute = false; parser.spreadArgs = spread; if (quote) { parser.sp(); if (parser.matchString(quote) !== quote) { parser.error(("Expected matching quote '" + quote + "'")); } } if (single) { var interpolator = { t: INTERPOLATOR }; refineExpression(expr, interpolator); attribute.f = [interpolator]; } else { attribute.f = flattenExpression(expr); } } var delimiterChangeToken = { t: DELIMCHANGE, exclude: true }; function readMustache(parser) { var mustache, i; // If we're inside a <script> or <style> tag, and we're not // interpolating, bug out if (parser.interpolate[parser.inside] === false) { return null; } for (i = 0; i < parser.tags.length; i += 1) { if ((mustache = readMustacheOfType(parser, parser.tags[i]))) { return mustache; } } if (parser.inTag && !parser.inAttribute) { mustache = readAttributeOrDirective(parser); if (mustache) { parser.sp(); return mustache; } } } function readMustacheOfType(parser, tag) { var mustache, reader, i; var start = parser.pos; if (parser.matchString('\\' + tag.open)) { if (start === 0 || parser.str[start - 1] !== '\\') { return tag.open; } } else if (!parser.matchString(tag.open)) { return null; } // delimiter change? if ((mustache = readDelimiterChange(parser))) { // find closing delimiter or abort... if (!parser.matchString(tag.close)) { return null; } // ...then make the switch tag.open = mustache[0]; tag.close = mustache[1]; parser.sortMustacheTags(); return delimiterChangeToken; } parser.sp(); // illegal section closer if (parser.matchString('/')) { parser.pos -= 1; var rewind = parser.pos; if (!readNumberLiteral(parser)) { parser.pos = rewind - tag.close.length; if (parser.inAttribute) { parser.pos = start; return null; } else { parser.error("Attempted to close a section that wasn't open"); } } else { parser.pos = rewind; } } for (i = 0; i < tag.readers.length; i += 1) { reader = tag.readers[i]; if ((mustache = reader(parser, tag))) { if (tag.isStatic) { mustache.s = 1; } if (parser.includeLinePositions) { mustache.q = parser.getLinePos(start); } return mustache; } } parser.pos = start; return null; } function readTriple(parser, tag) { var expression = readExpression(parser); if (!expression) { return null; } if (!parser.matchString(tag.close)) { parser.error(("Expected closing delimiter '" + (tag.close) + "'")); } var triple = { t: TRIPLE }; refineExpression(expression, triple); // TODO handle this differently - it's mysterious return triple; } function readUnescaped(parser, tag) { if (!parser.matchString('&')) { return null; } parser.sp(); var expression = readExpression(parser); if (!expression) { return null; } if (!parser.matchString(tag.close)) { parser.error(("Expected closing delimiter '" + (tag.close) + "'")); } var triple = { t: TRIPLE }; refineExpression(expression, triple); // TODO handle this differently - it's mysterious return triple; } var legalAlias = /^(?:[a-zA-Z$_0-9]|\\\.)+(?:(?:(?:[a-zA-Z$_0-9]|\\\.)+)|(?:\[[0-9]+\]))*/; var asRE = /^as/i; function readAliases(parser) { var aliases = []; var alias; var start = parser.pos; parser.sp(); alias = readAlias(parser); if (alias) { alias.x = refineExpression(alias.x, {}); aliases.push(alias); parser.sp(); while (parser.matchString(',')) { alias = readAlias(parser); if (!alias) { parser.error('Expected another alias.'); } alias.x = refineExpression(alias.x, {}); aliases.push(alias); parser.sp(); } return aliases; } parser.pos = start; return null; } function readAlias(parser) { var start = parser.pos; parser.sp(); var expr = readExpression(parser, []); if (!expr) { parser.pos = start; return null; } parser.sp(); parser.matchPattern(asRE); parser.sp(); var alias = parser.matchPattern(legalAlias); if (!alias) { parser.pos = start; return null; } return { n: alias, x: expr }; } function readPartial(parser, tag) { var type = parser.matchString('>') || parser.matchString('yield'); var partial = { t: type === '>' ? PARTIAL : YIELDER }; var aliases; if (!type) { return null; } parser.sp(); if (type === '>' || !(aliases = parser.matchString('with'))) { // Partial names can include hyphens, so we can't use readExpression // blindly. Instead, we use the `relaxedNames` flag to indicate that // `foo-bar` should be read as a single name, rather than 'subtract // bar from foo' parser.relaxedNames = parser.strictRefinement = true; var expression = readExpression(parser); parser.relaxedNames = parser.strictRefinement = false; if (!expression && type === '>') { return null; } if (expression) { refineExpression(expression, partial); // TODO... parser.sp(); if (type !== '>') { aliases = parser.matchString('with'); } } } parser.sp(); // check for alias context e.g. `{{>foo bar as bat, bip as bop}}` if (aliases || type === '>') { aliases = readAliases(parser); if (aliases && aliases.length) { partial.z = aliases; } else { // otherwise check for literal context e.g. `{{>foo bar}}` then // turn it into `{{#with bar}}{{>foo}}{{/with}}` var context = readExpression(parser); if (context) { partial.c = {}; refineExpression(context, partial.c); } } if (type !== '>' && (!partial.c && !partial.z)) { // {{yield with}} requires some aliases parser.error("Expected a context or one or more aliases"); } } parser.sp(); if (!parser.matchString(tag.close)) { parser.error(("Expected closing delimiter '" + (tag.close) + "'")); } return partial; } function readComment(parser, tag) { if (!parser.matchString('!')) { return null; } var index = parser.remaining().indexOf(tag.close); if (index !== -1) { parser.pos += index + tag.close.length; return { t: COMMENT }; } } function readInterpolator(parser, tag) { var expression, err; var start = parser.pos; // TODO would be good for perf if we could do away with the try-catch try { expression = readExpressionOrReference(parser, [tag.close]); } catch (e) { err = e; } if (!expression) { if (parser.str.charAt(start) === '!') { // special case - comment parser.pos = start; return null; } if (err) { throw err; } } if (!parser.matchString(tag.close)) { parser.error(("Expected closing delimiter '" + (tag.close) + "' after reference")); if (!expression) { // special case - comment if (parser.nextChar() === '!') { return null; } parser.error("Expected expression or legal reference"); } } var interpolator = { t: INTERPOLATOR }; refineExpression(expression, interpolator); // TODO handle this differently - it's mysterious return interpolator; } function readClosing(parser, tag) { var start = parser.pos; if (!parser.matchString(tag.open)) { return null; } parser.sp(); if (!parser.matchString('/')) { parser.pos = start; return null; } parser.sp(); var remaining = parser.remaining(); var index = remaining.indexOf(tag.close); if (index !== -1) { var closing = { t: CLOSING, r: remaining.substr(0, index).split(' ')[0] }; parser.pos += index; if (!parser.matchString(tag.close)) { parser.error(("Expected closing delimiter '" + (tag.close) + "'")); } return closing; } parser.pos = start; return null; } var patterns = { else: /^\s*else\s*/, elseif: /^\s*elseif\s+/, then: /^\s*then\s*/, catch: /^\s*catch\s*/ }; var types = { else: ELSE, elseif: ELSEIF, then: THEN, catch: CATCH }; function readInlineBlock(parser, tag, type) { var start = parser.pos; if (!parser.matchString(tag.open)) { return null; } if (!parser.matchPattern(patterns[type])) { parser.pos = start; return null; } var res = { t: types[type] }; if (type === 'elseif') { res.x = readExpression(parser); } else if (type === 'catch' || type === 'then') { var nm = parser.matchPattern(name); if (nm) { res.n = nm; } } if (!parser.matchString(tag.close)) { parser.error(("Expected closing delimiter '" + (tag.close) + "'")); } return res; } var handlebarsBlockCodes = { each: SECTION_EACH, if: SECTION_IF, with: SECTION_IF_WITH, unless: SECTION_UNLESS }; var indexRefPattern = /^\s*:\s*([a-zA-Z_$][a-zA-Z_$0-9]*)/; var keyIndexRefPattern = /^\s*,\s*([a-zA-Z_$][a-zA-Z_$0-9]*)/; var handlebarsBlockPattern = new RegExp('^(' + keys(handlebarsBlockCodes).join('|') + ')\\b'); function readSection(parser, tag) { var expression, section, child, children, hasElse, block, unlessBlock, closed, i, expectedClose, hasThen, hasCatch, inlineThen; var aliasOnly = false; var start = parser.pos; if (parser.matchString('^')) { // watch out for parent context refs - {{^^/^^/foo}} if (parser.matchString('^/')) { parser.pos = start; return null; } section = { t: SECTION, f: [], n: SECTION_UNLESS }; } else if (parser.matchString('#')) { section = { t: SECTION, f: [] }; if (parser.matchString('partial')) { parser.pos = start - parser.standardDelimiters[0].length; parser.error( 'Partial definitions can only be at the top level of the template, or immediately inside components' ); } if ((block = parser.matchString('await'))) { expectedClose = block; section.t = AWAIT; } else if ((block = parser.matchPattern(handlebarsBlockPattern))) { expectedClose = block; section.n = handlebarsBlockCodes[block]; } } else { return null; } parser.sp(); if (block === 'with') { var aliases = readAliases(parser); if (aliases) { aliasOnly = true; section.z = aliases; section.t = ALIAS; } } else if (block === 'each') { var alias = readAlias(parser); if (alias) { section.z = [{ n: alias.n, x: { r: '.' } }]; expression = alias.x; } } if (!aliasOnly) { if (!expression) { expression = readExpression(parser); } if (!expression) { parser.error('Expected expression'); } // extra each aliases if (block === 'each' && parser.matchString(',')) { var aliases$1 = readAliases(parser); if (aliases$1) { if (section.z) { aliases$1.unshift(section.z[0]); } section.z = aliases$1; } } // optional index and key references if ((block === 'each' || !block) && (i = parser.matchPattern(indexRefPattern))) { var extra; if ((extra = parser.matchPattern(keyIndexRefPattern))) { section.i = i + ',' + extra; } else { section.i = i; } } else if (block === 'await' && parser.matchString('then')) { parser.sp(); hasThen = true; inlineThen = parser.matchPattern(name); if (!inlineThen) { inlineThen = true; } } if (!block && expression.n) { expectedClose = expression.n; } } parser.sp(); if (!parser.matchString(tag.close)) { parser.error(("Expected closing delimiter '" + (tag.close) + "'")); } parser.sectionDepth += 1; children = section.f; var pos; do { pos = parser.pos; if ((child = readClosing(parser, tag))) { if (expectedClose && child.r !== expectedClose) { if (!block) { if (child.r) { parser.warn( ("Expected " + (tag.open) + "/" + expectedClose + (tag.close) + " but found " + (tag.open) + "/" + (child.r) + (tag.close)) ); } } else { parser.pos = pos; parser.error(("Expected " + (tag.open) + "/" + expectedClose + (tag.close))); } } parser.sectionDepth -= 1; closed = true; } else if ( !aliasOnly && ((child = readInlineBlock(parser, tag, 'elseif')) || (child = readInlineBlock(parser, tag, 'else')) || (block === 'await' && ((child = readInlineBlock(parser, tag, 'then')) || (child = readInlineBlock(parser, tag, 'catch'))))) ) { if (section.n === SECTION_UNLESS) { parser.error('{{else}} not allowed in {{#unless}}'); } if (hasElse) { if (child.t === ELSE) { parser.error('there can only be one {{else}} block, at the end of a section'); } else if (child.t === ELSEIF) { parser.error('illegal {{elseif...}} after {{else}}'); } } if (!unlessBlock && (inlineThen || !hasThen) && !hasCatch) { if (block === 'await') { var s = { f: children }; section.f = [s]; if (inlineThen) { s.t = THEN; inlineThen !== true && (s.n = inlineThen); } else { s.t = SECTION; } } else { unlessBlock = []; } } var mustache = { t: SECTION, f: (children = []) }; if (child.t === ELSE) { if (block === 'await') { section.f.push(mustache); mustache.t = ELSE; } else { mustache.n = SECTION_UNLESS; unlessBlock.push(mustache); } hasElse = true; } else if (child.t === ELSEIF) { mustache.n = SECTION_IF; refineExpression(child.x, mustache); unlessBlock.push(mustache); } else if (child.t === THEN) { if (hasElse) { parser.error('{{then}} block must appear before any {{else}} block'); } if (hasCatch) { parser.error('{{then}} block must appear before any {{catch}} block'); } if (hasThen) { parser.error('there can only be one {{then}} block per {{#await}}'); } mustache.t = THEN; hasThen = true; child.n && (mustache.n = child.n); section.f.push(mustache); } else if (child.t === CATCH) { if (hasElse) { parser.error('{{catch}} block must appear before any {{else}} block'); } if (hasCatch) { parser.error('there can only be one {{catch}} block per {{#await}}'); } mustache.t = CATCH; hasCatch = true; mustache.n = child.n; section.f.push(mustache); } } else { child = parser.read(READERS); if (!child) { break; } children.push(child); } } while (!closed); if (unlessBlock) { section.l = unlessBlock; } if (!aliasOnly) { refineExpression(expression, section); } if (block === 'await' && (inlineThen || !hasThen) && !hasCatch && !hasElse) { var s$1 = { f: section.f }; section.f = [s$1]; if (inlineThen) { s$1.t = THEN; inlineThen !== true && (s$1.n = inlineThen); } else { s$1.t = SECTION; } } // TODO if a section is empty it should be discarded. Don't do // that here though - we need to clean everything up first, as // it may contain removeable whitespace. As a temporary measure, // to pass the existing tests, remove empty `f` arrays if (!section.f.length) { delete section.f; } return section; } var OPEN_COMMENT = '<!--'; var CLOSE_COMMENT = '-->'; function readHtmlComment(parser) { var start = parser.pos; if (parser.textOnlyMode || !parser.matchString(OPEN_COMMENT)) { return null; } var remaining = parser.remaining(); var endIndex = remaining.indexOf(CLOSE_COMMENT); if (endIndex === -1) { parser.error("Illegal HTML - expected closing comment sequence ('-->')"); } var content = remaining.substr(0, endIndex); parser.pos += endIndex + 3; var comment = { t: COMMENT, c: content }; if (parser.includeLinePositions) { comment.q = parser.getLinePos(start); } return comment; } var leadingLinebreak = /^[ \t\f\r\n]*\r?\n/; var trailingLinebreak = /\r?\n[ \t\f\r\n]*$/; function stripStandalones(items) { var i, current, backOne, backTwo, lastSectionItem; for (i = 1; i < items.length; i += 1) { current = items[i]; backOne = items[i - 1]; backTwo = items[i - 2]; // if we're at the end of a [text][comment][text] sequence... if (isString(current) && isComment(backOne) && isString(backTwo)) { // ... and the comment is a standalone (i.e. line breaks either side)... if (trailingLinebreak.test(backTwo) && leadingLinebreak.test(current)) { // ... then we want to remove the whitespace after the first line break items[i - 2] = backTwo.replace(trailingLinebreak, '\n'); // and the leading line break of the second text token items[i] = current.replace(leadingLinebreak, ''); } } // if the current item is a section, and it is preceded by a linebreak, and // its first item is a linebreak... if (isSection(current) && isString(backOne)) { if ( trailingLinebreak.test(backOne) && isString(current.f[0]) && leadingLinebreak.test(current.f[0]) ) { items[i - 1] = backOne.replace(trailingLinebreak, '\n'); current.f[0] = current.f[0].replace(leadingLinebreak, ''); } } // if the last item was a section, and it is followed by a linebreak, and // its last item is a linebreak... if (isString(current) && isSection(backOne)) { lastSectionItem = lastItem(backOne.f); if ( isString(lastSectionItem) && trailingLinebreak.test(lastSectionItem) && leadingLinebreak.test(current) ) { backOne.f[backOne.f.length - 1] = lastSectionItem.replace(trailingLinebreak, '\n'); items[i] = current.replace(leadingLinebreak, ''); } } } return items; } function isComment(item) { return item.t === COMMENT || item.t === DELIMCHANGE; } function isSection(item) { return (item.t === SECTION || item.t === INVERTED) && item.f; } function trimWhitespace(items, leadingPattern, trailingPattern) { var item; if (leadingPattern) { item = items[0]; if (isString(item)) { item = item.replace(leadingPattern, ''); if (!item) { items.shift(); } else { items[0] = item; } } } if (trailingPattern) { item = lastItem(items); if (isString(item)) { item = item.replace(trailingPattern, ''); if (!item) { items.pop(); } else { items[items.length - 1] = item; } } } } var contiguousWhitespace = /[ \t\f\r\n]+/g; var leadingWhitespace$1 = /^[ \t\f\r\n]+/; var trailingWhitespace = /[ \t\f\r\n]+$/; var leadingNewLine = /^(?:\r\n|\r|\n)/; var trailingNewLine = /(?:\r\n|\r|\n)$/; function cleanup( items, stripComments, preserveWhitespace, removeLeadingWhitespace, removeTrailingWhitespace, whiteSpaceElements ) { if (isString(items)) { return; } var i, item, previousItem, nextItem, preserveWhitespaceInsideFragment, removeLeadingWhitespaceInsideFragment, removeTrailingWhitespaceInsideFragment; // First pass - remove standalones and comments etc stripStandalones(items); i = items.length; while (i--) { item = items[i]; // Remove delimiter changes, unsafe elements etc if (item.exclude) { items.splice(i, 1); } else if (stripComments && item.t === COMMENT) { // Remove comments, unless we want to keep them items.splice(i, 1); } } // If necessary, remove leading and trailing whitespace trimWhitespace( items, removeLeadingWhitespace ? leadingWhitespace$1 : null, removeTrailingWhitespace ? trailingWhitespace : null ); i = items.length; while (i--) { item = items[i]; removeLeadingWhitespaceInsideFragment = removeTrailingWhitespaceInsideFragment = false; // Recurse if (item.f) { var isPreserveWhitespaceElement = item.t === ELEMENT && (whiteSpaceElements[item.e.toLowerCase()] || whiteSpaceElements[item.e]); preserveWhitespaceInsideFragment = preserveWhitespace || isPreserveWhitespaceElement; if (!preserveWhitespace && isPreserveWhitespaceElement) { trimWhitespace(item.f, leadingNewLine, trailingNewLine); } if (!preserveWhitespaceInsideFragment) { previousItem = items[i - 1]; nextItem = items[i + 1]; // if the previous item was a text item with trailing whitespace, // remove leading whitespace inside the fragment if (!previousItem || (isString(previousItem) && trailingWhitespace.test(previousItem))) { removeLeadingWhitespaceInsideFragment = true; } // and vice versa if (!nextItem || (isString(nextItem) && leadingWhitespace$1.test(nextItem))) { removeTrailingWhitespaceInsideFragment = true; } } cleanup( item.f, stripComments, preserveWhitespaceInsideFragment, removeLeadingWhitespaceInsideFragment, removeTrailingWhitespaceInsideFragment, whiteSpaceElements ); } // Split if-else blocks into two (an if, and an unless) if (item.l) { cleanup( item.l, stripComments, preserveWhitespace, removeLeadingWhitespaceInsideFragment, removeTrailingWhitespaceInsideFragment, whiteSpaceElements ); item.l.forEach(function (s) { return (s.l = 1); }); item.l.unshift(i + 1, 0); items.splice.apply(items, item.l); delete item.l; // TODO would be nice if there was a way around this } // Clean up conditional attributes if (item.m) { cleanup( item.m, stripComments, preserveWhitespace, removeLeadingWhitespaceInsideFragment, removeTrailingWhitespaceInsideFragment, whiteSpaceElements ); if (item.m.length < 1) { delete item.m; } } } // final pass - fuse text nodes together i = items.length; while (i--) { if (isString(items[i])) { if (isString(items[i + 1])) { items[i] = items[i] + items[i + 1]; items.splice(i + 1, 1); } if (!preserveWhitespace) { items[i] = items[i].replace(contiguousWhitespace, ' '); } if (items[i] === '') { items.splice(i, 1); } } } } var closingTagPattern = /^([a-zA-Z]{1,}:?[a-zA-Z0-9\-]*)\s*\>/; function readClosingTag(parser) { var tag; var start = parser.pos; // are we looking at a closing tag? if (!parser.matchString('</')) { return null; } if ((tag = parser.matchPattern(closingTagPattern))) { if (parser.inside && tag !== parser.inside) { parser.pos = start; return null; } return { t: CLOSING_TAG, e: tag }; } // We have an illegal closing tag, report it parser.pos -= 2; parser.error('Illegal closing tag'); } function hyphenateCamel(camelCaseStr) { return camelCaseStr.replace(/([A-Z])/g, function (match, $1) { return '-' + $1.toLowerCase(); }); } var tagNamePattern = /^[a-zA-Z]{1,}:?[a-zA-Z0-9\-]*/; var anchorPattern = /^[a-zA-Z_$][-a-zA-Z0-9_$]*/; var validTagNameFollower = /^[\s\n\/>]/; var semiEnd = /;\s*$/; var exclude = { exclude: true }; // based on http://developers.whatwg.org/syntax.html#syntax-tag-omission var disallowedContents = { li: ['li'], dt: ['dt', 'dd'], dd: ['dt', 'dd'], p: 'address article aside blockquote div dl fieldset footer form h1 h2 h3 h4 h5 h6 header hgroup hr main menu nav ol p pre section table ul'.split( ' ' ), rt: ['rt', 'rp'], rp: ['rt', 'rp'], optgroup: ['optgroup'], option: ['option', 'optgroup'], thead: ['tbody', 'tfoot'], tbody: ['tbody', 'tfoot'], tfoot: ['tbody'], tr: ['tr', 'tbody'], td: ['td', 'th', 'tr'], th: ['td', 'th', 'tr'] }; function readElement$1(parser) { var attribute, selfClosing, children, partials, hasPartials, child, closed, pos, remaining, closingTag, anchor; var start = parser.pos; if (parser.inside || parser.inAttribute || parser.textOnlyMode) { return null; } if (!parser.matchString('<')) { return null; } // if this is a closing tag, abort straight away if (parser.nextChar() === '/') { return null; } var element = {}; if (parser.includeLinePositions) { element.q = parser.getLinePos(start); } // check for doctype decl if (parser.matchString('!')) { element.t = DOCTYPE; if (!parser.matchPattern(/^doctype/i)) { parser.error('Expected DOCTYPE declaration'); } element.a = parser.matchPattern(/^(.+?)>/); return element; } else if ((anchor = parser.matchString('#'))) { // check for anchor parser.sp(); element.t = ANCHOR; element.n = parser.matchPattern(anchorPattern); } else { // otherwise, it's an element/component element.t = ELEMENT; // element name element.e = parser.matchPattern(tagNamePattern); if (!element.e) { return null; } } // next character must be whitespace, closing solidus or '>' if (!validTagNameFollower.test(parser.nextChar())) { parser.error('Illegal tag name'); } parser.sp(); parser.inTag = true; // directives and attributes while ((attribute = readMustache(parser))) { if (attribute !== false) { if (!element.m) { element.m = []; } element.m.push(attribute); } parser.sp(); } parser.inTag = false; // allow whitespace before closing solidus parser.sp(); // self-closing solidus? if (parser.matchString('/')) { selfClosing = true; } // closing angle bracket if (!parser.matchString('>')) { return null; } var lowerCaseName = (element.e || element.n).toLowerCase(); var preserveWhitespace = parser.preserveWhitespace; if (!selfClosing && (anchor || !voidElements[element.e.toLowerCase()])) { if (!anchor) { parser.elementStack.push(lowerCaseName); // Special case - if we open a script element, further tags should // be ignored unless they're a closing script element if (lowerCaseName in parser.interpolate) { parser.inside = lowerCaseName; } } children = []; partials = create(null); do { pos = parser.pos; remaining = parser.remaining(); if (!remaining) { // if this happens to be a script tag and there's no content left, it's because // a closing script tag can't appear in a script if (parser.inside === 'script') { closed = true; break; } parser.error( ("Missing end " + (parser.elementStack.length > 1 ? 'tags' : 'tag') + " (" + (parser.elementStack .reverse() .map(function (x) { return ("</" + x + ">"); }) .join('')) + ")") ); } // if for example we're in an <li> element, and we see another // <li> tag, close the first so they become siblings if (!anchor && !canContain(lowerCaseName, remaining)) { closed = true; } else if (!anchor && (closingTag = readClosingTag(parser))) { // closing tag closed = true; var closingTagName = closingTag.e.toLowerCase(); // if this *isn't* the closing tag for the current element... if (closingTagName !== lowerCaseName) { // rewind parser parser.pos = pos; // if it doesn't close a parent tag, error if (!~parser.elementStack.indexOf(closingTagName)) { var errorMessage = 'Unexpected closing tag'; // add additional help for void elements, since component names // might clash with them if (voidElements[closingTagName.toLowerCase()]) { errorMessage += " (<" + closingTagName + "> is a void element - it cannot contain children)"; } parser.error(errorMessage); } } } else if (anchor && readAnchorClose(parser, element.n)) { closed = true; } else { // implicit close by closing section tag. TODO clean this up var tag = { open: parser.standardDelimiters[0], close: parser.standardDelimiters[1] }; if (readClosing(parser, tag) || readInline(parser, tag)) { closed = true; parser.pos = pos; } else if ((child = parser.read(PARTIAL_READERS))) { if (partials[child.n]) { parser.pos = pos; parser.error('Duplicate partial definition'); } cleanup( child.f, parser.stripComments, preserveWhitespace, !preserveWhitespace, !preserveWhitespace, parser.whiteSpaceElements ); partials[child.n] = child.f; hasPartials = true; } else { if ((child = parser.read(READERS))) { children.push(child); } else { closed = true; } } } } while (!closed); if (children.length) { element.f = children; } if (hasPartials) { element.p = partials; } parser.elementStack.pop(); } parser.inside = null; if (parser.sanitizeElements && parser.sanitizeElements.indexOf(lowerCaseName) !== -1) { return exclude; } if ( element.m && lowerCaseName !== 'input' && lowerCaseName !== 'select' && lowerCaseName !== 'textarea' && lowerCaseName !== 'option' ) { var attrs = element.m; var classes, styles, cls, style; var i = 0; var a; while (i < attrs.length) { a = attrs[i]; if (a.t !== ATTRIBUTE) { i++; continue; } if (a.n.indexOf('class-') === 0 && !a.f) { // static class directives (classes || (classes = [])).push(a.n.slice(6)); attrs.splice(i, 1); } else if (a.n.indexOf('style-') === 0 && isString(a.f)) { // static style directives (styles || (styles = [])).push(((hyphenateCamel(a.n.slice(6))) + ": " + (a.f) + ";")); attrs.splice(i, 1); } else if (a.n === 'class' && isString(a.f)) { // static class attrs (classes || (classes = [])).push(a.f); attrs.splice(i, 1); } else if (a.n === 'style' && isString(a.f)) { // static style attrs (styles || (styles = [])).push(a.f + (semiEnd.test(a.f) ? '' : ';')); attrs.splice(i, 1); } else if (a.n === 'class') { cls = a; i++; } else if (a.n === 'style') { style = a; i++; } else if ( !~a.n.indexOf(':') && a.n !== 'value' && a.n !== 'contenteditable' && isString(a.f) ) { a.g = 1; i++; } else { i++; } } if (classes) { if (!cls || !isString(cls.f)) { attrs.unshift({ t: ATTRIBUTE, n: 'class', f: classes.join(' '), g: 1 }); } else { cls.f += ' ' + classes.join(' '); } } else if (cls && isString(cls.f)) { cls.g = 1; } if (styles) { if (!style || !isString(style.f)) { attrs.unshift({ t: ATTRIBUTE, n: 'style', f: styles.join(' '), g: 1 }); } else { style.f += '; ' + styles.join(' '); } } else if (style && isString(style.f)) { style.g = 1; } } return element; } function canContain(name, remaining) { var match = /^<([a-zA-Z][a-zA-Z0-9]*)/.exec(remaining); var disallowed = disallowedContents[name]; if (!match || !disallowed) { return true; } return !~disallowed.indexOf(match[1].toLowerCase()); } function readAnchorClose(parser, name) { var pos = parser.pos; if (!parser.matchString('</')) { return null; } parser.matchString('#'); parser.sp(); if (!parser.matchString(name)) { parser.pos = pos; return null; } parser.sp(); if (!parser.matchString('>')) { parser.pos = pos; return null; } return true; } var inlines = /^\s*(elseif|else|then|catch)\s*/; function readInline(parser, tag) { var pos = parser.pos; if (!parser.matchString(tag.open)) { return; } if (parser.matchPattern(inlines)) { return true; } else { parser.pos = pos; } } function readText(parser) { var index, disallowed, barrier; var remaining = parser.remaining(); if (parser.textOnlyMode) { disallowed = parser.tags.map(function (t) { return t.open; }); disallowed = disallowed.concat(parser.tags.map(function (t) { return '\\' + t.open; })); index = getLowestIndex(remaining, disallowed); } else { barrier = parser.inside ? '</' + parser.inside : '<'; if (parser.inside && !parser.interpolate[parser.inside]) { index = remaining.indexOf(barrier); } else { disallowed = parser.tags.map(function (t) { return t.open; }); disallowed = disallowed.concat(parser.tags.map(function (t) { return '\\' + t.open; })); // http://developers.whatwg.org/syntax.html#syntax-attributes if (parser.inAttribute === true) { // we're inside an unquoted attribute value disallowed.push("\"", "'", "=", "<", ">", '`'); } else if (parser.inAttribute) { // quoted attribute value disallowed.push(parser.inAttribute); } else { disallowed.push(barrier); } index = getLowestIndex(remaining, disallowed); } } if (!index) { return null; } if (index === -1) { index = remaining.length; } parser.pos += index; if ((parser.inside && parser.inside !== 'textarea') || parser.textOnlyMode) { return remaining.substr(0, index); } else { return decodeCharacterReferences(remaining.substr(0, index)); } } var partialDefinitionSectionPattern = /^\s*#\s*partial\s+/; function readPartialDefinitionSection(parser) { var child, closed; var start = parser.pos; var delimiters = parser.standardDelimiters; if (!parser.matchString(delimiters[0])) { return null; } if (!parser.matchPattern(partialDefinitionSectionPattern)) { parser.pos = start; return null; } var name = parser.matchPattern(/^[a-zA-Z_$][a-zA-Z_$0-9\-\/]*/); if (!name) { parser.error('expected legal partial name'); } parser.sp(); if (!parser.matchString(delimiters[1])) { parser.error(("Expected closing delimiter '" + (delimiters[1]) + "'")); } var content = []; var open = delimiters[0]; var close = delimiters[1]; do { if ((child = readClosing(parser, { open: open, close: close }))) { if (child.r !== 'partial') { parser.error(("Expected " + open + "/partial" + close)); } closed = true; } else { child = parser.read(READERS); if (!child) { parser.error(("Expected " + open + "/partial" + close)); } content.push(child); } } while (!closed); return { t: INLINE_PARTIAL, n: name, f: content }; } function readTemplate(parser) { var fragment = []; var partials = create(null); var hasPartials = false; var preserveWhitespace = parser.preserveWhitespace; while (parser.pos < parser.str.length) { var pos = parser.pos; var item = (void 0), partial = (void 0); if ((partial = parser.read(PARTIAL_READERS))) { if (partials[partial.n]) { parser.pos = pos; parser.error('Duplicated partial definition'); } cleanup( partial.f, parser.stripComments, preserveWhitespace, !preserveWhitespace, !preserveWhitespace, parser.whiteSpaceElements ); partials[partial.n] = partial.f; hasPartials = true; } else if ((item = parser.read(READERS))) { fragment.push(item); } else { parser.error('Unexpected template content'); } } var result = { v: TEMPLATE_VERSION, t: fragment }; if (hasPartials) { result.p = partials; } return result; } function insertExpressions(obj, expr) { keys(obj).forEach(function (key) { if (isExpression(key, obj)) { return addTo(obj, expr); } var ref = obj[key]; if (hasChildren(ref)) { insertExpressions(ref, expr); } }); } function isExpression(key, obj) { return key === 's' && isArray(obj.r); } function addTo(obj, expr) { var s = obj.s; var r = obj.r; if (!expr[s]) { expr[s] = fromExpression(s, r.length); } } function hasChildren(ref) { return isArray(ref) || isObject(ref); } var shared = {}; // See https://github.com/ractivejs/template-spec for information // about the Ractive template specification var STANDARD_READERS = [ readPartial, readUnescaped, readSection, readInterpolator, readComment ]; var TRIPLE_READERS = [readTriple]; var READERS = [readMustache, readHtmlComment, readElement$1, readText]; var PARTIAL_READERS = [readPartialDefinitionSection]; var preserveWhitespaceElements = { pre: 1, script: 1, style: 1, textarea: 1 }; var defaultInterpolate = { textarea: true, script: true, style: true, template: true }; var StandardParser = Parser.extend({ init: function init(str, options) { var tripleDelimiters = options.tripleDelimiters || shared.defaults.tripleDelimiters; var staticDelimiters = options.staticDelimiters || shared.defaults.staticDelimiters; var staticTripleDelimiters = options.staticTripleDelimiters || shared.defaults.staticTripleDelimiters; this.standardDelimiters = options.delimiters || shared.defaults.delimiters; this.tags = [ { isStatic: false, isTriple: false, open: this.standardDelimiters[0], close: this.standardDelimiters[1], readers: STANDARD_READERS }, { isStatic: false, isTriple: true, open: tripleDelimiters[0], close: tripleDelimiters[1], readers: TRIPLE_READERS }, { isStatic: true, isTriple: false, open: staticDelimiters[0], close: staticDelimiters[1], readers: STANDARD_READERS }, { isStatic: true, isTriple: true, open: staticTripleDelimiters[0], close: staticTripleDelimiters[1], readers: TRIPLE_READERS } ]; this.contextLines = options.contextLines || shared.defaults.contextLines; this.sortMustacheTags(); this.sectionDepth = 0; this.elementStack = []; this.interpolate = assign( {}, defaultInterpolate, shared.defaults.interpolate, options.interpolate ); if (options.sanitize === true) { options.sanitize = { // blacklist from https://code.google.com/p/google-caja/source/browse/trunk/src/com/google/caja/lang/html/html4-elements-whitelist.json elements: 'applet base basefont body frame frameset head html isindex link meta noframes noscript object param script style title'.split( ' ' ), eventAttributes: true }; } this.stripComments = options.stripComments !== false; this.preserveWhitespace = isObjectType(options.preserveWhitespace) ? false : options.preserveWhitespace; this.sanitizeElements = options.sanitize && options.sanitize.elements; this.sanitizeEventAttributes = options.sanitize && options.sanitize.eventAttributes; this.includeLinePositions = options.includeLinePositions; this.textOnlyMode = options.textOnlyMode; this.csp = options.csp; this.allowExpressions = options.allowExpressions; if (options.expression) { this.converters = [readExpression]; } if (options.attributes) { this.inTag = true; } // special whitespace handling requested for certain elements this.whiteSpaceElements = assign({}, options.preserveWhitespace, preserveWhitespaceElements); }, postProcess: function postProcess(result, options) { var parserResult = result[0]; if (options.expression) { var expr = flattenExpression(parserResult); expr.e = fromExpression(expr.s, expr.r.length); return expr; } else { // special case - empty string if (!result.length) { return { t: [], v: TEMPLATE_VERSION }; } if (this.sectionDepth > 0) { this.error('A section was left open'); } cleanup( parserResult.t, this.stripComments, this.preserveWhitespace, !this.preserveWhitespace, !this.preserveWhitespace, this.whiteSpaceElements ); if (this.csp !== false) { var expr$1 = {}; insertExpressions(parserResult.t, expr$1); insertExpressions(parserResult.p || {}, expr$1); if (keys(expr$1).length) { parserResult.e = expr$1; } } return parserResult; } }, converters: [readTemplate], sortMustacheTags: function sortMustacheTags() { // Sort in order of descending opening delimiter length (longer first), // to protect against opening delimiters being substrings of each other this.tags.sort(function (a, b) { return b.open.length - a.open.length; }); } }); function parse(template, options) { return new StandardParser(template, options || {}).result; } var parseOptions = [ 'delimiters', 'tripleDelimiters', 'staticDelimiters', 'staticTripleDelimiters', 'csp', 'interpolate', 'preserveWhitespace', 'sanitize', 'stripComments', 'contextLines', 'allowExpressions', 'attributes' ]; var TEMPLATE_INSTRUCTIONS = "Either preparse or use a ractive runtime source that includes the parser. "; var COMPUTATION_INSTRUCTIONS = "Either include a version of Ractive that can parse or convert your computation strings to functions."; function throwNoParse(method, error, instructions) { if (!method) { fatal(("Missing Ractive.parse - cannot parse " + error + ". " + instructions)); } } function createFunction(body, length) { throwNoParse(fromExpression, 'new expression function', TEMPLATE_INSTRUCTIONS); return fromExpression(body, length); } function createFunctionFromString(str, bindTo) { throwNoParse(parse, 'compution string "${str}"', COMPUTATION_INSTRUCTIONS); var tpl = parse(str, { expression: true }); return function() { return tpl.e.apply(bindTo, tpl.r.map(function (r) { return bindTo.get(r); })); }; } var parser = { fromId: function fromId(id, options) { if (!doc) { if (options && options.noThrow) { return; } throw new Error(("Cannot retrieve template #" + id + " as Ractive is not running in a browser.")); } if (id) { id = id.replace(/^#/, ''); } var template; if (!(template = doc.getElementById(id))) { if (options && options.noThrow) { return; } throw new Error(("Could not find template element with id #" + id)); } if (template.tagName.toUpperCase() !== 'SCRIPT') { if (options && options.noThrow) { return; } throw new Error(("Template element with id #" + id + ", must be a <script> element")); } return 'textContent' in template ? template.textContent : template.innerHTML; }, isParsed: function isParsed(template) { return !isString(template); }, getParseOptions: function getParseOptions(ractive) { // Could be Ractive or a Component if (ractive.defaults) { ractive = ractive.defaults; } return parseOptions.reduce(function (val, key) { val[key] = ractive[key]; return val; }, {}); }, parse: function parse$1(template, options) { throwNoParse(parse, 'template', TEMPLATE_INSTRUCTIONS); var parsed = parse(template, options); addFunctions(parsed); return parsed; }, parseFor: function parseFor(template, ractive) { return this.parse(template, this.getParseOptions(ractive)); } }; function getComputationSignature(ractive, key, signature) { var getter; var setter; // useful for debugging var getterString; var getterUseStack; var setterString; if (isFunction(signature)) { getter = bind(signature, ractive); getterString = signature.toString(); getterUseStack = true; } if (isString(signature)) { getter = createFunctionFromString(signature, ractive); getterString = signature; } if (isObjectType(signature)) { if (isString(signature.get)) { getter = createFunctionFromString(signature.get, ractive); getterString = signature.get; } else if (isFunction(signature.get)) { getter = bind(signature.get, ractive); getterString = signature.get.toString(); getterUseStack = true; } else { fatal('`%s` computation must have a `get()` method', key); } if (isFunction(signature.set)) { setter = bind(signature.set, ractive); setterString = signature.set.toString(); } } return { getter: getter, setter: setter, getterString: getterString, setterString: setterString, getterUseStack: getterUseStack }; } var id = 0; var TransitionManager = function TransitionManager(callback, parent) { this.callback = callback; this.parent = parent; this.intros = []; this.outros = []; this.children = []; this.totalChildren = this.outroChildren = 0; this.detachQueue = []; this.outrosComplete = false; this.id = id++; if (parent) { parent.addChild(this); } }; var TransitionManager__proto__ = TransitionManager.prototype; TransitionManager__proto__.add = function add (transition) { var list = transition.isIntro ? this.intros : this.outros; transition.starting = true; list.push(transition); }; TransitionManager__proto__.addChild = function addChild (child) { this.children.push(child); this.totalChildren += 1; this.outroChildren += 1; }; TransitionManager__proto__.checkStart = function checkStart () { if (this.parent && this.parent.started) { this.start(); } }; TransitionManager__proto__.decrementOutros = function decrementOutros () { this.outroChildren -= 1; check(this); }; TransitionManager__proto__.decrementTotal = function decrementTotal () { this.totalChildren -= 1; check(this); }; TransitionManager__proto__.detachNodes = function detachNodes () { var this$1 = this; var len = this.detachQueue.length; for (var i = 0; i < len; i++) { this$1.detachQueue[i].detach(); } len = this.children.length; for (var i$1 = 0; i$1 < len; i$1++) { this$1.children[i$1].detachNodes(); } this.detachQueue = []; }; TransitionManager__proto__.ready = function ready () { if (this.detachQueue.length) { detachImmediate(this); } }; TransitionManager__proto__.remove = function remove (transition) { var list = transition.isIntro ? this.intros : this.outros; removeFromArray(list, transition); check(this); }; TransitionManager__proto__.start = function start () { this.started = true; this.children.forEach(function (c) { return c.start(); }); this.intros.concat(this.outros).forEach(function (t) { return t.start(); }); check(this); }; function check(tm) { if (!tm.started || tm.outros.length || tm.outroChildren) { return; } // If all outros are complete, and we haven't already done this, // we notify the parent if there is one, otherwise // start detaching nodes if (!tm.outrosComplete) { tm.outrosComplete = true; if (tm.parent) { tm.parent.decrementOutros(tm); } if (!tm.parent || tm.parent.outrosComplete) { tm.detachNodes(); } } // Once everything is done, we can notify parent transition // manager and call the callback if (!tm.intros.length && !tm.totalChildren) { if (isFunction(tm.callback)) { tm.callback(); } if (tm.parent && !tm.notifiedTotal) { tm.notifiedTotal = true; tm.parent.decrementTotal(); } } } // check through the detach queue to see if a node is up or downstream from a // transition and if not, go ahead and detach it function detachImmediate(manager) { var queue = manager.detachQueue; var outros = collectAllOutros(manager); if (!outros.length) { manager.detachNodes(); } else { var i = queue.length; var j = 0; var node, trans; var nqueue = (manager.detachQueue = []); start: while (i--) { node = queue[i].node; j = outros.length; while (j--) { trans = outros[j].element.node; // check to see if the node is, contains, or is contained by the transitioning node if (trans === node || trans.contains(node) || node.contains(trans)) { nqueue.push(queue[i]); continue start; } } // no match, we can drop it queue[i].detach(); } } } function collectAllOutros(manager, _list) { var list = _list; // if there's no list, we're starting at the root to build one if (!list) { list = []; var parent = manager; while (parent.parent) { parent = parent.parent; } return collectAllOutros(parent, list); } else { // grab all outros from child managers var i = manager.children.length; while (i--) { list = collectAllOutros(manager.children[i], list); } // grab any from this manager if there are any if (manager.outros.length) { list = list.concat(manager.outros); } return list; } } var batch; var runloop = { active: function active() { return !!batch; }, start: function start() { var fulfilPromise; var promise = new Promise(function (f) { return (fulfilPromise = f); }); batch = { previousBatch: batch, transitionManager: new TransitionManager(fulfilPromise, batch && batch.transitionManager), fragments: [], tasks: [], immediateObservers: [], deferredObservers: [], promise: promise }; return promise; }, end: function end() { flushChanges(); if (!batch.previousBatch) { batch.transitionManager.start(); } else { batch.transitionManager.checkStart(); } batch = batch.previousBatch; }, addFragment: function addFragment(fragment) { addToArray(batch.fragments, fragment); }, // TODO: come up with a better way to handle fragments that trigger their own update addFragmentToRoot: function addFragmentToRoot(fragment) { if (!batch) { return; } var b = batch; while (b.previousBatch) { b = b.previousBatch; } addToArray(b.fragments, fragment); }, addObserver: function addObserver(observer, defer) { if (!batch) { observer.dispatch(); } else { addToArray(defer ? batch.deferredObservers : batch.immediateObservers, observer); } }, registerTransition: function registerTransition(transition) { transition._manager = batch.transitionManager; batch.transitionManager.add(transition); }, // synchronise node detachments with transition ends detachWhenReady: function detachWhenReady(thing) { batch.transitionManager.detachQueue.push(thing); }, scheduleTask: function scheduleTask(task, postRender) { var _batch; if (!batch) { task(); } else { _batch = batch; while (postRender && _batch.previousBatch) { // this can't happen until the DOM has been fully updated // otherwise in some situations (with components inside elements) // transitions and decorators will initialise prematurely _batch = _batch.previousBatch; } _batch.tasks.push(task); } }, promise: function promise() { if (!batch) { return Promise.resolve(); } var target = batch; while (target.previousBatch) { target = target.previousBatch; } return target.promise || Promise.resolve(); } }; function dispatch(observer) { observer.dispatch(); } function flushChanges() { var which = batch.immediateObservers; batch.immediateObservers = []; which.forEach(dispatch); // Now that changes have been fully propagated, we can update the DOM // and complete other tasks var i = batch.fragments.length; var fragment; which = batch.fragments; batch.fragments = []; while (i--) { fragment = which[i]; fragment.update(); } batch.transitionManager.ready(); which = batch.deferredObservers; batch.deferredObservers = []; which.forEach(dispatch); var tasks = batch.tasks; batch.tasks = []; for (i = 0; i < tasks.length; i += 1) { tasks[i](); } // If updating the view caused some model blowback - e.g. a triple // containing <option> elements caused the binding on the <select> // to update - then we start over if ( batch.fragments.length || batch.immediateObservers.length || batch.deferredObservers.length || batch.tasks.length ) { return flushChanges(); } } // TODO what happens if a transition is aborted? var tickers = []; var running = false; function tick() { runloop.start(); var now = performance.now(); var i; var ticker; for (i = 0; i < tickers.length; i += 1) { ticker = tickers[i]; if (!ticker.tick(now)) { // ticker is complete, remove it from the stack, and decrement i so we don't miss one tickers.splice(i--, 1); } } runloop.end(); if (tickers.length) { requestAnimationFrame(tick); } else { running = false; } } var Ticker = function Ticker(options) { this.duration = options.duration; this.step = options.step; this.complete = options.complete; this.easing = options.easing; this.start = performance.now(); this.end = this.start + this.duration; this.running = true; tickers.push(this); if (!running) { requestAnimationFrame(tick); } }; var Ticker__proto__ = Ticker.prototype; Ticker__proto__.tick = function tick (now) { if (!this.running) { return false; } if (now > this.end) { if (this.step) { this.step(1); } if (this.complete) { this.complete(1); } return false; } var elapsed = now - this.start; var eased = this.easing(elapsed / this.duration); if (this.step) { this.step(eased); } return true; }; Ticker__proto__.stop = function stop () { if (this.abort) { this.abort(); } this.running = false; }; var prefixers = {}; // TODO this is legacy. sooner we can replace the old adaptor API the better /* istanbul ignore next */ function prefixKeypath(obj, prefix) { var prefixed = {}; if (!prefix) { return obj; } prefix += '.'; for (var key in obj) { if (hasOwn(obj, key)) { prefixed[prefix + key] = obj[key]; } } return prefixed; } function getPrefixer(rootKeypath) { var rootDot; if (!prefixers[rootKeypath]) { rootDot = rootKeypath ? rootKeypath + '.' : ''; /* istanbul ignore next */ prefixers[rootKeypath] = function(relativeKeypath, value) { var obj; if (isString(relativeKeypath)) { obj = {}; obj[rootDot + relativeKeypath] = value; return obj; } if (isObjectType(relativeKeypath)) { // 'relativeKeypath' is in fact a hash, not a keypath return rootDot ? prefixKeypath(relativeKeypath, rootKeypath) : relativeKeypath; } }; } return prefixers[rootKeypath]; } var shared$1 = {}; var Model = (function (ModelBase) { function Model(parent, key) { ModelBase.call(this, parent); this.ticker = null; if (parent) { this.key = unescapeKey(key); this.isReadonly = parent.isReadonly; if (parent.value) { this.value = parent.value[this.key]; if (isArray(this.value)) { this.length = this.value.length; } this.adapt(); } } } if ( ModelBase ) Model.__proto__ = ModelBase; var Model__proto__ = Model.prototype = Object.create( ModelBase && ModelBase.prototype ); Model__proto__.constructor = Model; Model__proto__.adapt = function adapt () { var this$1 = this; var adaptors = this.root.adaptors; var len = adaptors.length; this.rewrap = false; // Exit early if no adaptors if (len === 0) { return; } var value = this.wrapper ? 'newWrapperValue' in this ? this.newWrapperValue : this.wrapperValue : this.value; // TODO remove this legacy nonsense var ractive = this.root.ractive; var keypath = this.getKeypath(); // tear previous adaptor down if present if (this.wrapper) { var shouldTeardown = this.wrapperValue === value ? false : !this.wrapper.reset || this.wrapper.reset(value) === false; if (shouldTeardown) { this.wrapper.teardown(); delete this.wrapper; delete this.wrapperValue; delete this.newWrapperValue; // don't branch for undefined values if (this.value !== undefined) { var parentValue = this.parent.value || this.parent.createBranch(this.key); if (parentValue[this.key] !== value) { parentValue[this.key] = value; } this.value = value; } } else { delete this.newWrapperValue; this.value = this.wrapper.get(); return; } } var i; for (i = 0; i < len; i += 1) { var adaptor = adaptors[i]; if (adaptor.filter(value, keypath, ractive)) { this$1.wrapper = adaptor.wrap(ractive, value, keypath, getPrefixer(keypath)); this$1.wrapperValue = value; this$1.wrapper.__model = this$1; // massive temporary hack to enable array adaptor this$1.value = this$1.wrapper.get(); break; } } }; Model__proto__.animate = function animate (from, to, options, interpolator) { var this$1 = this; if (this.ticker) { this.ticker.stop(); } var fulfilPromise; var promise = new Promise(function (fulfil) { return (fulfilPromise = fulfil); }); this.ticker = new Ticker({ duration: options.duration, easing: options.easing, step: function (t) { var value = interpolator(t); this$1.applyValue(value); if (options.step) { options.step(t, value); } }, complete: function () { this$1.applyValue(to); if (options.complete) { options.complete(to); } this$1.ticker = null; fulfilPromise(to); } }); promise.stop = this.ticker.stop; return promise; }; Model__proto__.applyValue = function applyValue (value, notify) { if ( notify === void 0 ) notify = true; if (isEqual(value, this.value)) { return; } if (this.boundValue) { this.boundValue = null; } if (this.parent.wrapper && this.parent.wrapper.set) { this.parent.wrapper.set(this.key, value); this.parent.value = this.parent.wrapper.get(); this.value = this.parent.value[this.key]; if (this.wrapper) { this.newWrapperValue = this.value; } this.adapt(); } else if (this.wrapper) { this.newWrapperValue = value; this.adapt(); } else { var parentValue = this.parent.value || this.parent.createBranch(this.key); if (isObjectLike(parentValue)) { parentValue[this.key] = value; } else { warnIfDebug(("Attempted to set a property of a non-object '" + (this.getKeypath()) + "'")); return; } this.value = value; this.adapt(); } // keep track of array stuff if (isArray(value)) { this.length = value.length; this.isArray = true; } else { this.isArray = false; } // notify dependants this.links.forEach(handleChange); this.children.forEach(mark); this.deps.forEach(handleChange); if (notify) { this.notifyUpstream(); } if (this.parent.isArray) { if (this.key === 'length') { this.parent.length = value; } else { this.parent.joinKey('length').mark(); } } }; Model__proto__.compute = function compute (key, computed) { var registry = this.computed || (this.computed = {}); if (registry[key]) { registry[key].signature = getComputationSignature(this.root.ractive, key, computed); registry[key].mark(); } else { registry[key] = new shared$1.Computation( this, getComputationSignature(this.root.ractive, key, computed), key ); } return registry[key]; }; Model__proto__.createBranch = function createBranch (key) { var branch = isNumeric(key) ? [] : {}; this.applyValue(branch, false); return branch; }; Model__proto__.get = function get (shouldCapture, opts) { if (this._link) { return this._link.get(shouldCapture, opts); } if (shouldCapture) { capture(this); } // if capturing, this value needs to be unwrapped because it's for external use if (opts && opts.virtual) { return this.getVirtual(false); } return maybeBind( this, (opts && 'unwrap' in opts ? opts.unwrap !== false : shouldCapture) && this.wrapper ? this.wrapperValue : this.value, !opts || opts.shouldBind !== false ); }; Model__proto__.joinKey = function joinKey (key, opts) { var this$1 = this; if (this._link) { if (opts && opts.lastLink !== false && (key === undefined || key === '')) { return this; } return this._link.joinKey(key); } if (key === undefined || key === '') { return this; } var child; if (hasOwn(this.childByKey, key)) { child = this.childByKey[key]; } else { child = this.computed && this.computed[key]; } if (!child) { var computed; if (this.isRoot && this.ractive && (computed = this.ractive.computed[key])) { child = this.compute(key, computed); } else if (!this.isRoot && this.root.ractive) { var registry = this.root.ractive.computed; for (var k in registry) { computed = registry[k]; if (computed.pattern && computed.pattern.test(this$1.getKeypath() + '.' + key)) { child = this$1.compute(key, computed); } } } } if (!child) { child = new Model(this, key); this.children.push(child); this.childByKey[key] = child; } if (child._link && (!opts || opts.lastLink !== false)) { return child._link; } return child; }; Model__proto__.mark = function mark$1 (force) { if (this._link) { return this._link.mark(force); } var old = this.value; var value = this.retrieve(); if (force || !isEqual(value, old)) { this.value = value; if (this.boundValue) { this.boundValue = null; } // make sure the wrapper stays in sync if (old !== value || this.rewrap) { if (this.wrapper) { this.newWrapperValue = value; } this.adapt(); } // keep track of array stuff if (isArray(value)) { this.length = value.length; this.isArray = true; } else { this.isArray = false; } this.children.forEach(force ? markForce : mark); this.links.forEach(marked); this.deps.forEach(handleChange); } }; Model__proto__.merge = function merge (array, comparator) { var newIndices = buildNewIndices( this.value === array ? recreateArray(this) : this.value, array, comparator ); this.parent.value[this.key] = array; this.shuffle(newIndices, true); }; Model__proto__.retrieve = function retrieve () { return this.parent.value ? this.parent.value[this.key] : undefined; }; Model__proto__.set = function set (value) { if (this.ticker) { this.ticker.stop(); } this.applyValue(value); }; Model__proto__.shuffle = function shuffle$2 (newIndices, unsafe) { shuffle(this, newIndices, false, unsafe); }; Model__proto__.source = function source () { return this; }; Model__proto__.teardown = function teardown$4 () { var this$1 = this; if (this._link) { this._link.teardown(); this._link = null; } this.children.forEach(teardown); if (this.wrapper) { this.wrapper.teardown(); } if (this.computed) { keys(this.computed).forEach(function (k) { return this$1.computed[k].teardown(); }); } }; return Model; }(ModelBase)); function recreateArray(model) { var array = []; for (var i = 0; i < model.length; i++) { array[i] = (model.childByKey[i] || {}).value; } return array; } /* global global */ var data = {}; var SharedModel = (function (Model) { function SharedModel(value, name, ractive) { Model.call(this, null, ("@" + name)); this.key = "@" + name; this.value = value; this.isRoot = true; this.root = this; this.adaptors = []; this.ractive = ractive; } if ( Model ) SharedModel.__proto__ = Model; var SharedModel__proto__ = SharedModel.prototype = Object.create( Model && Model.prototype ); SharedModel__proto__.constructor = SharedModel; SharedModel__proto__.getKeypath = function getKeypath () { return this.key; }; SharedModel__proto__.retrieve = function retrieve () { return this.value; }; return SharedModel; }(Model)); var SharedModel$1 = new SharedModel(data, 'shared'); var GlobalModel = new SharedModel(base, 'global'); function findContext(fragment) { var frag = fragment; while (frag && !frag.context && !frag.aliases) { frag = frag.parent; } return frag; } function resolveReference(fragment, ref) { var initialFragment = fragment; // current context ref if (ref === '.') { return fragment.findContext(); } // ancestor references if (ref[0] === '~') { return fragment.ractive.viewmodel.joinAll(splitKeypath(ref.slice(2))); } // scoped references if (ref[0] === '.' || ref[0] === '^') { var frag = fragment; var parts = ref.split('/'); var explicitContext = parts[0] === '^^'; // find nearest context node while (frag && !frag.context) { frag = up(frag); } var context$1 = frag && frag.context; // walk up the context chain while (frag && parts[0] === '^^') { parts.shift(); // the current fragment should always be a context, // and if it happens to be an iteration, jump above the each block if (frag.isIteration) { frag = frag.parent.parent; } else { // otherwise jump above the current fragment frag = up(frag); } // walk to the next contexted fragment while (frag && !frag.context) { frag = up(frag); } context$1 = frag && frag.context; } if (!context$1 && explicitContext) { throw new Error( ("Invalid context parent reference ('" + ref + "'). There is not context at that level.") ); } // walk up the context path while (parts[0] === '.' || parts[0] === '..') { var part = parts.shift(); if (part === '..') { context$1 = context$1.parent; } } ref = parts.join('/'); // special case - `{{.foo}}` means the same as `{{./foo}}` if (ref[0] === '.') { ref = ref.slice(1); } return context$1.joinAll(splitKeypath(ref)); } var keys$$1 = splitKeypath(ref); if (!keys$$1.length) { return; } var base = keys$$1.shift(); // special refs if (base[0] === '@') { // shorthand from outside the template // @this referring to local ractive instance if (base === '@this' || base === '@') { return fragment.ractive.viewmodel.getRactiveModel().joinAll(keys$$1); } else if (base === '@index' || base === '@key') { // @index or @key referring to the nearest repeating index or key if (keys$$1.length) { badReference(base); } var repeater = findIter(fragment); return repeater && repeater[("get" + (base[1] === 'i' ? 'Index' : 'Key'))](); } else if (base === '@last') { var repeater$1 = findIter(fragment); return repeater$1 && repeater$1.parent.getLast(); } else if (base === '@global') { // @global referring to window or global return GlobalModel.joinAll(keys$$1); } else if (base === '@shared') { // @global referring to window or global return SharedModel$1.joinAll(keys$$1); } else if (base === '@keypath' || base === '@rootpath') { // @keypath or @rootpath, the current keypath string var root = ref[1] === 'r' ? fragment.ractive.root : null; var f = fragment; while ( f && (!f.context || (f.isRoot && f.ractive.component && (root || !f.ractive.isolated))) ) { f = f.isRoot ? f.componentParent : f.parent; } return f.getKeypath(root); } else if (base === '@context') { return new SharedModel(fragment.getContext(), 'context').joinAll(keys$$1); } else if (base === '@local') { // @context-local data return fragment.getContext()._data.joinAll(keys$$1); } else if (base === '@style') { // @style shared model return fragment.ractive.constructor._cssModel.joinAll(keys$$1); } else if (base === '@helpers') { // @helpers instance model return fragment.ractive.viewmodel.getHelpers().joinAll(keys$$1); } else if (base === '@macro') { var handle = findMacro(fragment); if (handle) { return new SharedModel(handle, 'macro').joinAll(keys$$1); } else { return; } } else { // nope throw new Error(("Invalid special reference '" + base + "'")); } } // helpers if (base && !keys$$1.length) { var helpers = fragment.ractive.viewmodel.getHelpers(); if (helpers.has(base)) { return helpers.joinKey(base); } } var context = findContext(fragment); // check immediate context for a match if (context) { if (context.context) { context = context.context; if (context.has(base)) { return context.joinKey(base).joinAll(keys$$1); } } else { // alias block, so get next full context for later context = fragment.findContext(); } } else { context = fragment.findContext(); } // walk up the fragment hierarchy looking for a matching ref, alias, or key in a context var createMapping = false; var shouldWarn = fragment.ractive.warnAboutAmbiguity; var crossed = 0; var model; while (fragment) { // repeated fragments if (fragment.isIteration) { if (base === fragment.parent.keyRef) { model = fragment.getKey(); } else if (base === fragment.parent.indexRef) { model = fragment.getIndex(); } if (model && keys$$1.length) { badReference(base); } } // alias node or iteration if (!model && fragment.aliases && hasOwn(fragment.aliases, base)) { model = fragment.aliases[base]; } // check fragment context to see if it has the key we need if (!model && fragment.context && fragment.context.has(base)) { model = fragment.context.joinKey(base); // this is an implicit mapping if (createMapping) { if (shouldWarn) { warnIfDebug( ("'" + ref + "' resolved but is ambiguous and will create a mapping to a parent component.") ); } } else if (shouldWarn && crossed) { warnIfDebug(("'" + ref + "' resolved but is ambiguous.")); } } if (model) { if (createMapping) { model = initialFragment.ractive.viewmodel.createLink(base, model, base, { implicit: true }); } if (keys$$1.length > 0 && isFunction(model.joinAll)) { model = model.joinAll(keys$$1); } return model; } // don't consider alias blocks when checking for ambiguity if (fragment.context && !fragment.aliases) { crossed = 1; } if ( (fragment.componentParent || (!fragment.parent && fragment.ractive.component)) && !fragment.ractive.isolated ) { // ascend through component boundary fragment = fragment.componentParent || fragment.ractive.component.up; createMapping = true; } else { fragment = fragment.parent; } } // if enabled, check the instance for a match var instance = initialFragment.ractive; if (instance.resolveInstanceMembers && base !== 'data' && base in instance) { return instance.viewmodel .getRactiveModel() .joinKey(base) .joinAll(keys$$1); } if (shouldWarn) { warnIfDebug(("'" + ref + "' is ambiguous and did not resolve.")); } // didn't find anything, so go ahead and create the key on the local model return context.joinKey(base).joinAll(keys$$1); } function up(fragment) { return fragment && ((!fragment.ractive.isolated && fragment.componentParent) || fragment.parent); } function findIter(start) { var fragment = start; var next; while (!fragment.isIteration && (next = up(fragment))) { fragment = next; } return fragment.isIteration && fragment; } function findMacro(start) { var fragment = start; while (fragment) { if (fragment.owner.handle) { return fragment.owner.handle; } fragment = up(fragment); } } function badReference(key) { throw new Error(("An index or key reference (" + key + ") cannot have child properties")); } var extern = {}; function getRactiveContext(ractive) { var assigns = [], len = arguments.length - 1; while ( len-- > 0 ) assigns[ len ] = arguments[ len + 1 ]; var fragment = ractive.fragment || ractive._fakeFragment || (ractive._fakeFragment = new FakeFragment(ractive)); return fragment.getContext.apply(fragment, assigns); } function getContext() { var assigns = [], len = arguments.length; while ( len-- ) assigns[ len ] = arguments[ len ]; if (!this.ctx) { this.ctx = new extern.Context(this); } assigns.unshift(create(this.ctx)); return assign.apply(null, assigns); } var FakeFragment = function FakeFragment(ractive) { this.ractive = ractive; }; FakeFragment.prototype.findContext = function findContext () { return this.ractive.viewmodel; }; var proto = FakeFragment.prototype; proto.getContext = getContext; proto.find = proto.findComponent = proto.findAll = proto.findAllComponents = noop; function findParentWithContext(fragment) { var frag = fragment; while (frag && !frag.context) { frag = frag.parent; } if (!frag) { return fragment && fragment.ractive.fragment; } else { return frag; } } var keep = false; function set(pairs, options) { var k = keep; var deep = options && options.deep; var shuffle = options && options.shuffle; var promise = runloop.start(); if (options && 'keep' in options) { keep = options.keep; } var i = pairs.length; while (i--) { var model = pairs[i][0]; var value = pairs[i][1]; var keypath = pairs[i][2]; if (!model) { runloop.end(); throw new Error(("Failed to set invalid keypath '" + keypath + "'")); } if (deep) { deepSet(model, value); } else if (shuffle) { var array = value; var target = model.get(); // shuffle target array with itself if (!array) { array = target; } // if there's not an array there yet, go ahead and set if (target === undefined) { model.set(array); } else { if (!isArray(target) || !isArray(array)) { runloop.end(); throw new Error('You cannot merge an array with a non-array'); } var comparator = getComparator(shuffle); model.merge(array, comparator); } } else { model.set(value); } } runloop.end(); keep = k; return promise; } var star = /\*/; function gather(ractive, keypath, base, isolated) { if (!base && (keypath[0] === '.' || keypath[1] === '^')) { warnIfDebug( "Attempted to set a relative keypath from a non-relative context. You can use a context object to set relative keypaths." ); return []; } var keys$$1 = splitKeypath(keypath); var model = base || ractive.viewmodel; if (star.test(keypath)) { return model.findMatches(keys$$1); } else { if (model === ractive.viewmodel) { // allow implicit mappings if ( ractive.component && !ractive.isolated && !model.has(keys$$1[0]) && keypath[0] !== '@' && keypath[0] && !isolated ) { return [resolveReference(ractive.fragment || new FakeFragment(ractive), keypath)]; } else { return [model.joinAll(keys$$1)]; } } else { return [model.joinAll(keys$$1)]; } } } function build(ractive, keypath, value, isolated) { var sets = []; // set multiple keypaths in one go if (isObject(keypath)) { var loop = function ( k ) { if (hasOwn(keypath, k)) { sets.push.apply(sets, gather(ractive, k, null, isolated).map(function (m) { return [m, keypath[k], k]; })); } }; for (var k in keypath) loop( k ); } else { // set a single keypath sets.push.apply(sets, gather(ractive, keypath, null, isolated).map(function (m) { return [m, value, keypath]; })); } return sets; } var deepOpts = { virtual: false }; function deepSet(model, value) { var dest = model.get(false, deepOpts); // if dest doesn't exist, just set it if (dest == null || !isObjectType(value)) { return model.set(value); } if (!isObjectType(dest)) { return model.set(value); } for (var k in value) { if (hasOwn(value, k)) { deepSet(model.joinKey(k), value[k]); } } } var comparators = {}; function getComparator(option) { if (option === true) { return null; } // use existing arrays if (isFunction(option)) { return option; } if (isString(option)) { return comparators[option] || (comparators[option] = function (thing) { return thing[option]; }); } throw new Error('If supplied, options.compare must be a string, function, or true'); // TODO link to docs } var errorMessage = 'Cannot add to a non-numeric value'; function add(ractive, keypath, d, options) { if (!isString(keypath) || !isNumeric(d)) { throw new Error('Bad arguments'); } var sets = build(ractive, keypath, d, options && options.isolated); return set( sets.map(function (pair) { var model = pair[0]; var add = pair[1]; var value = model.get(); if (!isNumeric(add) || !isNumeric(value)) { throw new Error(errorMessage); } return [model, value + add]; }) ); } function Ractive$add(keypath, d, options) { var num = isNumber(d) ? d : 1; var opts = isObjectType(d) ? d : options; return add(this, keypath, num, opts); } function immediate(value) { var result = Promise.resolve(value); defineProperty(result, 'stop', { value: noop }); return result; } var linear = easing.linear; function getOptions(options, instance) { options = options || {}; var easing$$1; if (options.easing) { easing$$1 = isFunction(options.easing) ? options.easing : instance.easing[options.easing]; } return { easing: easing$$1 || linear, duration: 'duration' in options ? options.duration : 400, complete: options.complete || noop, step: options.step || noop, interpolator: options.interpolator }; } function animate(ractive, model, to, options) { options = getOptions(options, ractive); var from = model.get(); // don't bother animating values that stay the same if (isEqual(from, to)) { options.complete(options.to); return immediate(to); } var interpolator = interpolate(from, to, ractive, options.interpolator); // if we can't interpolate the value, set it immediately if (!interpolator) { runloop.start(); model.set(to); runloop.end(); return immediate(to); } return model.animate(from, to, options, interpolator); } function Ractive$animate(keypath, to, options) { if (isObjectType(keypath)) { var keys$$1 = keys(keypath); throw new Error(("ractive.animate(...) no longer supports objects. Instead of ractive.animate({\n " + (keys$$1.map(function (key) { return ("'" + key + "': " + (keypath[key])); }).join('\n ')) + "\n}, {...}), do\n\n" + (keys$$1.map(function (key) { return ("ractive.animate('" + key + "', " + (keypath[key]) + ", {...});"); }).join('\n')) + "\n")); } return animate(this, this.viewmodel.joinAll(splitKeypath(keypath)), to, options); } function enqueue(ractive, event) { if (ractive.event) { ractive._eventQueue.push(ractive.event); } ractive.event = event; } function dequeue(ractive) { if (ractive._eventQueue.length) { ractive.event = ractive._eventQueue.pop(); } else { ractive.event = null; } } var initStars = {}; var bubbleStars = {}; // cartesian product of name parts and stars // adjusted appropriately for special cases function variants(name, initial) { var map = initial ? initStars : bubbleStars; if (map[name]) { return map[name]; } var parts = name.split('.'); var result = []; var base = false; // initial events the implicit namespace of 'this' if (initial) { parts.unshift('this'); base = true; } // use max - 1 bits as a bitmap to pick a part or a * // need to skip the full star case if the namespace is synthetic var max = Math.pow(2, parts.length) - (initial ? 1 : 0); for (var i = 0; i < max; i++) { var join = []; for (var j = 0; j < parts.length; j++) { join.push(1 & (i >> j) ? '*' : parts[j]); } result.unshift(join.join('.')); } if (base) { // include non-this-namespaced versions if (parts.length > 2) { result.push.apply(result, variants(name, false)); } else { result.push('*'); result.push(name); } } map[name] = result; return result; } function fireEvent(ractive, eventName, context, args) { if ( args === void 0 ) args = []; if (!eventName) { return; } context.name = eventName; args.unshift(context); var eventNames = ractive._nsSubs ? variants(eventName, true) : ['*', eventName]; return fireEventAs(ractive, eventNames, context, args, true); } function fireEventAs(ractive, eventNames, context, args, initialFire) { if ( initialFire === void 0 ) initialFire = false; var bubble = true; if (initialFire || ractive._nsSubs) { enqueue(ractive, context); var i = eventNames.length; while (i--) { if (eventNames[i] in ractive._subs) { bubble = notifySubscribers(ractive, ractive._subs[eventNames[i]], context, args) && bubble; } } dequeue(ractive); } if (ractive.parent && bubble) { if (initialFire && ractive.component) { var fullName = ractive.component.name + '.' + eventNames[eventNames.length - 1]; eventNames = variants(fullName, false); if (context && !context.component) { context.component = ractive; } } bubble = fireEventAs(ractive.parent, eventNames, context, args); } return bubble; } function notifySubscribers(ractive, subscribers, context, args) { var originalEvent = null; var stopEvent = false; // subscribers can be modified inflight, e.g. "once" functionality // so we need to copy to make sure everyone gets called subscribers = subscribers.slice(); for (var i = 0, len = subscribers.length; i < len; i += 1) { if (!subscribers[i].off && subscribers[i].handler.apply(ractive, args) === false) { stopEvent = true; } } if (context && stopEvent && (originalEvent = context.event)) { originalEvent.preventDefault && originalEvent.preventDefault(); originalEvent.stopPropagation && originalEvent.stopPropagation(); } return !stopEvent; } var Hook = function Hook(event) { this.event = event; this.method = 'on' + event; }; Hook.prototype.fire = function fire (ractive, arg) { var context = getRactiveContext(ractive); var method = this.method; if (ractive[method]) { arg ? ractive[method](context, arg) : ractive[method](context); } fireEvent(ractive, this.event, context, arg ? [arg, ractive] : [ractive]); }; function getChildQueue(queue, ractive) { return queue[ractive._guid] || (queue[ractive._guid] = []); } function fire(hookQueue, ractive) { var childQueue = getChildQueue(hookQueue.queue, ractive); hookQueue.hook.fire(ractive); // queue is "live" because components can end up being // added while hooks fire on parents that modify data values. while (childQueue.length) { fire(hookQueue, childQueue.shift()); } delete hookQueue.queue[ractive._guid]; } var HookQueue = function HookQueue(event) { this.hook = new Hook(event); this.inProcess = {}; this.queue = {}; }; var HookQueue__proto__ = HookQueue.prototype; HookQueue__proto__.begin = function begin (ractive) { this.inProcess[ractive._guid] = true; }; HookQueue__proto__.end = function end (ractive) { var parent = ractive.parent; // If this is *isn't* a child of a component that's in process, // it should call methods or fire at this point if (!parent || !this.inProcess[parent._guid]) { fire(this, ractive); } else { // elsewise, handoff to parent to fire when ready getChildQueue(this.queue, parent).push(ractive); } delete this.inProcess[ractive._guid]; }; var hooks = {}; [ 'construct', 'config', 'attachchild', 'detach', 'detachchild', 'insert', 'complete', 'reset', 'render', 'unrendering', 'unrender', 'teardown', 'destruct', 'update' ].forEach(function (hook) { hooks[hook] = new Hook(hook); }); hooks.init = new HookQueue('init'); function findAnchors(fragment, name) { if ( name === void 0 ) name = null; var res = []; findAnchorsIn(fragment, name, res); return res; } function findAnchorsIn(item, name, result) { if (item.isAnchor) { if (!name || item.name === name) { result.push(item); } } else if (item.items) { item.items.forEach(function (i) { return findAnchorsIn(i, name, result); }); } else if (item.iterations) { item.iterations.forEach(function (i) { return findAnchorsIn(i, name, result); }); } else if (item.fragment && !item.component) { findAnchorsIn(item.fragment, name, result); } } function updateAnchors(instance, name) { if ( name === void 0 ) name = null; var anchors = findAnchors(instance.fragment, name); var idxs = {}; var children = instance._children.byName; anchors.forEach(function (a) { var name = a.name; if (!(name in idxs)) { idxs[name] = 0; } var idx = idxs[name]; var child = (children[name] || [])[idx]; if (child && child.lastBound !== a) { if (child.lastBound) { child.lastBound.removeChild(child); } a.addChild(child); } idxs[name]++; }); } function unrenderChild(meta) { if (meta.instance.fragment.rendered) { meta.shouldDestroy = true; meta.instance.unrender(); } meta.instance.el = null; } function attachChild(child, options) { if ( options === void 0 ) options = {}; var children = this._children; var idx; if (child.parent && child.parent !== this) { throw new Error( ("Instance " + (child._guid) + " is already attached to a different instance " + (child.parent._guid) + ". Please detach it from the other instance using detachChild first.") ); } else if (child.parent) { throw new Error(("Instance " + (child._guid) + " is already attached to this instance.")); } var meta = { instance: child, ractive: this, name: options.name || child.constructor.name || 'Ractive', target: options.target || false, bubble: bubble, findNextNode: findNextNode }; meta.nameOption = options.name; // child is managing itself if (!meta.target) { meta.up = this.fragment; meta.external = true; } else { var list; if (!(list = children.byName[meta.target])) { list = []; this.set(("@this.children.byName." + (meta.target)), list); } idx = options.prepend ? 0 : options.insertAt !== undefined ? options.insertAt : list.length; } child.parent = this; child.root = this.root; child.component = meta; children.push(meta); var promise = runloop.start(); var rm = child.viewmodel.getRactiveModel(); rm.joinKey('parent', { lastLink: false }).link(this.viewmodel.getRactiveModel()); rm.joinKey('root', { lastLink: false }).link(this.root.viewmodel.getRactiveModel()); hooks.attachchild.fire(child); if (meta.target) { unrenderChild(meta); this.splice(("@this.children.byName." + (meta.target)), idx, 0, meta); updateAnchors(this, meta.target); } else { if (!child.isolated) { child.viewmodel.attached(this.fragment); } } runloop.end(); promise.ractive = child; return promise.then(function () { return child; }); } function bubble() { runloop.addFragment(this.instance.fragment); } function findNextNode() { if (this.anchor) { return this.anchor.findNextNode(); } } function compute(path, computed) { this.computed[path] = computed; if (isString(computed) || isFunction(computed)) { computed = this.computed[path] = { get: computed }; } var keys = splitKeypath(path); if (!~path.indexOf('*')) { var last = keys.pop(); return this.viewmodel.joinAll(keys).compute(last, computed); } else { computed.pattern = new RegExp( '^' + keys .map(function (k) { return k.replace(/\*\*/g, '(.+)').replace(/\*/g, '((?:\\\\.|[^\\.])+)'); }) .join('\\.') + '$' ); } } function Ractive$compute(path, computed) { var promise = runloop.start(); var comp = compute.call(this, path, computed); if (comp) { var keys = splitKeypath(path); if (keys.length === 1 && !comp.isReadonly) { comp.set(this.viewmodel.value[keys[0]]); } var first = keys.reduce(function (a, c) { return a && a.childByKey[c]; }, this.viewmodel); if (first) { first.rebind(comp, first, false); if (first.parent) { delete first.parent.childByKey[first.key]; } fireShuffleTasks(); } } runloop.end(); return promise; } function Ractive$detach() { if (this.isDetached) { return this.el; } if (this.el) { removeFromArray(this.el.__ractive_instances__, this); } this.el = this.fragment.detach(); this.isDetached = true; hooks.detach.fire(this); return this.el; } function detachChild(child) { var children = this._children; var meta, index; var i = children.length; while (i--) { if (children[i].instance === child) { index = i; meta = children[i]; break; } } if (!meta || child.parent !== this) { throw new Error(("Instance " + (child._guid) + " is not attached to this instance.")); } var promise = runloop.start(); if (meta.anchor) { meta.anchor.removeChild(meta); } if (!child.isolated) { child.viewmodel.detached(); } children.splice(index, 1); if (meta.target) { this.splice( ("@this.children.byName." + (meta.target)), children.byName[meta.target].indexOf(meta), 1 ); updateAnchors(this, meta.target); } var rm = child.viewmodel.getRactiveModel(); rm.joinKey('parent', { lastLink: false }).unlink(); rm.joinKey('root', { lastLink: false }).link(rm); child.root = child; child.parent = null; child.component = null; hooks.detachchild.fire(child); runloop.end(); promise.ractive = child; return promise.then(function () { return child; }); } function Ractive$find(selector, options) { var this$1 = this; if ( options === void 0 ) options = {}; if (!this.rendered) { throw new Error( ("Cannot call ractive.find('" + selector + "') unless instance is rendered to the DOM") ); } var node = this.fragment.find(selector, options); if (node) { return node; } if (options.remote) { for (var i = 0; i < this._children.length; i++) { if (!this$1._children[i].instance.fragment.rendered) { continue; } node = this$1._children[i].instance.find(selector, options); if (node) { return node; } } } } function Ractive$findAll(selector, options) { if ( options === void 0 ) options = {}; if (!this.rendered) { throw new Error( ("Cannot call ractive.findAll('" + selector + "', ...) unless instance is rendered to the DOM") ); } if (!isArray(options.result)) { options.result = []; } this.fragment.findAll(selector, options); if (options.remote) { // seach non-fragment children this._children.forEach(function (c) { if (!c.target && c.instance.fragment && c.instance.fragment.rendered) { c.instance.findAll(selector, options); } }); } return options.result; } function Ractive$findAllComponents(selector, options) { if (!options && isObjectType(selector)) { options = selector; selector = ''; } options = options || {}; if (!isArray(options.result)) { options.result = []; } this.fragment.findAllComponents(selector, options); if (options.remote) { // search non-fragment children this._children.forEach(function (c) { if (!c.target && c.instance.fragment && c.instance.fragment.rendered) { if (!selector || c.name === selector) { options.result.push(c.instance); } c.instance.findAllComponents(selector, options); } }); } return options.result; } function Ractive$findComponent(selector, options) { var this$1 = this; if ( options === void 0 ) options = {}; if (isObjectType(selector)) { options = selector; selector = ''; } var child = this.fragment.findComponent(selector, options); if (child) { return child; } if (options.remote) { if (!selector && this._children.length) { return this._children[0].instance; } for (var i = 0; i < this._children.length; i++) { // skip children that are or should be in an anchor if (this$1._children[i].target) { continue; } if (this$1._children[i].name === selector) { return this$1._children[i].instance; } child = this$1._children[i].instance.findComponent(selector, options); if (child) { return child; } } } } function Ractive$findContainer(selector) { if (this.container) { if (this.container.component && this.container.component.name === selector) { return this.container; } else { return this.container.findContainer(selector); } } return null; } function Ractive$findParent(selector) { if (this.parent) { if (this.parent.component && this.parent.component.name === selector) { return this.parent; } else { return this.parent.findParent(selector); } } return null; } function findElement(start, orComponent, name) { if ( orComponent === void 0 ) orComponent = true; while ( start && (start.type !== ELEMENT || (name && start.name !== name)) && (!orComponent || (start.type !== COMPONENT && start.type !== ANCHOR)) ) { // start is a fragment - look at the owner if (start.owner) { start = start.owner; } else if (start.component) // start is a component or yielder - look at the container { start = start.containerFragment || start.component.up; } else if (start.parent) // start is an item - look at the parent { start = start.parent; } else if (start.up) // start is an item without a parent - look at the parent fragment { start = start.up; } else { start = undefined; } } return start; } // This function takes an array, the name of a mutator method, and the // arguments to call that mutator method with, and returns an array that // maps the old indices to their new indices. // So if you had something like this... // // array = [ 'a', 'b', 'c', 'd' ]; // array.push( 'e' ); // // ...you'd get `[ 0, 1, 2, 3 ]` - in other words, none of the old indices // have changed. If you then did this... // // array.unshift( 'z' ); // // ...the indices would be `[ 1, 2, 3, 4, 5 ]` - every item has been moved // one higher to make room for the 'z'. If you removed an item, the new index // would be -1... // // array.splice( 2, 2 ); // // ...this would result in [ 0, 1, -1, -1, 2, 3 ]. // // This information is used to enable fast, non-destructive shuffling of list // sections when you do e.g. `ractive.splice( 'items', 2, 2 ); function getNewIndices(length, methodName, args) { var newIndices = []; var spliceArguments = getSpliceEquivalent(length, methodName, args); if (!spliceArguments) { return null; // TODO support reverse and sort? } var balance = spliceArguments.length - 2 - spliceArguments[1]; var removeStart = Math.min(length, spliceArguments[0]); var removeEnd = removeStart + spliceArguments[1]; newIndices.startIndex = removeStart; var i; for (i = 0; i < removeStart; i += 1) { newIndices.push(i); } for (; i < removeEnd; i += 1) { newIndices.push(-1); } for (; i < length; i += 1) { newIndices.push(i + balance); } // there is a net shift for the rest of the array starting with index + balance if (balance !== 0) { newIndices.touchedFrom = spliceArguments[0]; } else { newIndices.touchedFrom = length; } return newIndices; } // The pop, push, shift an unshift methods can all be represented // as an equivalent splice function getSpliceEquivalent(length, methodName, args) { switch (methodName) { case 'splice': if (args[0] !== undefined && args[0] < 0) { args[0] = length + Math.max(args[0], -length); } if (args[0] === undefined) { args[0] = 0; } while (args.length < 2) { args.push(length - args[0]); } if (!isNumber(args[1])) { args[1] = length - args[0]; } // ensure we only remove elements that exist args[1] = Math.min(args[1], length - args[0]); return args; case 'sort': case 'reverse': return null; case 'pop': if (length) { return [length - 1, 1]; } return [0, 0]; case 'push': return [length, 0].concat(args); case 'shift': return [0, length ? 1 : 0]; case 'unshift': return [0, 0].concat(args); } } var arrayProto = Array.prototype; function makeArrayMethod(methodName) { function path(keypath) { var args = [], len = arguments.length - 1; while ( len-- > 0 ) args[ len ] = arguments[ len + 1 ]; return model(this.viewmodel.joinAll(splitKeypath(keypath)), args); } function model(mdl, args) { var array = mdl.get(); if (!isArray(array)) { if (array === undefined) { array = []; var result$1 = arrayProto[methodName].apply(array, args); var promise$1 = runloop.start().then(function () { return result$1; }); mdl.set(array); runloop.end(); return promise$1; } else { throw new Error( ("shuffle array method " + methodName + " called on non-array at " + (mdl.getKeypath())) ); } } var newIndices = getNewIndices(array.length, methodName, args); var result = arrayProto[methodName].apply(array, args); var promise = runloop.start().then(function () { return result; }); promise.result = result; if (newIndices) { if (mdl.shuffle) { mdl.shuffle(newIndices); } else { // it's a computation, which don't have a shuffle, so just invalidate mdl.mark(); } } else { mdl.set(result); } runloop.end(); return promise; } return { path: path, model: model }; } function update$1(ractive, model, options) { // if the parent is wrapped, the adaptor will need to be updated before // updating on this keypath if (model.parent && model.parent.wrapper) { model.parent.adapt(); } var promise = runloop.start(); model.mark(options && options.force); // notify upstream of changes model.notifyUpstream(); runloop.end(); hooks.update.fire(ractive, model); return promise; } function Ractive$update(keypath, options) { var opts, path; if (isString(keypath)) { path = splitKeypath(keypath); opts = options; } else { opts = keypath; } return update$1(this, path ? this.viewmodel.joinAll(path) : this.viewmodel, opts); } var modelPush = makeArrayMethod('push').model; var modelPop = makeArrayMethod('pop').model; var modelShift = makeArrayMethod('shift').model; var modelUnshift = makeArrayMethod('unshift').model; var modelSort = makeArrayMethod('sort').model; var modelSplice = makeArrayMethod('splice').model; var modelReverse = makeArrayMethod('reverse').model; var ContextData = (function (Model) { function ContextData(options) { Model.call(this, null, null); this.isRoot = true; this.root = this; this.value = {}; this.ractive = options.ractive; this.adaptors = []; this.context = options.context; } if ( Model ) ContextData.__proto__ = Model; var ContextData__proto__ = ContextData.prototype = Object.create( Model && Model.prototype ); ContextData__proto__.constructor = ContextData; ContextData__proto__.getKeypath = function getKeypath () { return '@context.data'; }; ContextData__proto__.rebound = function rebound () {}; return ContextData; }(Model)); var Context = function Context(fragment, element) { this.fragment = fragment; this.element = element || findElement(fragment); this.node = this.element && this.element.node; this.ractive = fragment.ractive; this.root = this; }; var Context__proto__ = Context.prototype; var prototypeAccessors = { decorators: {},_data: {} }; prototypeAccessors.decorators.get = function () { var items = {}; if (!this.element) { return items; } this.element.decorators.forEach(function (d) { return (items[d.name] = d.handle); }); return items; }; prototypeAccessors._data.get = function () { return ( this.model || (this.root.model = new ContextData({ ractive: this.ractive, context: this.root })) ); }; // the usual mutation suspects Context__proto__.add = function add (keypath, d, options) { var num = isNumber(d) ? +d : 1; var opts = isObjectType(d) ? d : options; return set( build$1(this, keypath, num).map(function (pair) { var model = pair[0]; var val = pair[1]; var value = model.get(); if (!isNumeric(val) || !isNumeric(value)) { throw new Error('Cannot add non-numeric value'); } return [model, value + val]; }), opts ); }; Context__proto__.animate = function animate$1 (keypath, value, options) { var model = findModel(this, keypath).model; return animate(this.ractive, model, value, options); }; Context__proto__.find = function find (selector) { return this.fragment.find(selector); }; Context__proto__.findAll = function findAll (selector) { var result = []; this.fragment.findAll(selector, { result: result }); return result; }; Context__proto__.findAllComponents = function findAllComponents (selector) { var result = []; this.fragment.findAllComponents(selector, { result: result }); return result; }; Context__proto__.findComponent = function findComponent (selector) { return this.fragment.findComponent(selector); }; // get relative keypaths and values Context__proto__.get = function get (keypath) { if (!keypath) { return this.fragment.findContext().get(true); } var ref = findModel(this, keypath); var model = ref.model; return model ? model.get(true) : undefined; }; Context__proto__.getParent = function getParent (component) { var fragment = this.fragment; if (fragment.context) { fragment = findParentWithContext(fragment.parent || (component && fragment.componentParent)); } else { fragment = findParentWithContext(fragment.parent || (component && fragment.componentParent)); if (fragment) { fragment = findParentWithContext( fragment.parent || (component && fragment.componentParent) ); } } if (!fragment || fragment === this.fragment) { return; } else { return fragment.getContext(); } }; Context__proto__.hasListener = function hasListener (name, bubble) { // if the owner is a component, start there because the nearest element // may exist outside of the immediate context (yield) var el = this.fragment.owner.component ? this.fragment.owner : this.element || this.fragment.owner; var base; do { base = el.component || el; if (base.template.t === ELEMENT) { if (findEvent(base, name)) { return true; } } el = el.up && el.up.owner; if (el && el.component) { el = el.component; } } while (el && bubble); }; Context__proto__.link = function link (source, dest) { var there = findModel(this, source).model; var here = findModel(this, dest).model; var promise = runloop.start(); here.link(there, source); runloop.end(); return promise; }; Context__proto__.listen = function listen (event, handler) { var el = this.element; el.on(event, handler); return { cancel: function cancel() { el.off(event, handler); } }; }; Context__proto__.observe = function observe (keypath, callback, options) { if ( options === void 0 ) options = {}; if (isObject(keypath)) { options = callback || {}; } options.fragment = this.fragment; return this.ractive.observe(keypath, callback, options); }; Context__proto__.observeOnce = function observeOnce (keypath, callback, options) { if ( options === void 0 ) options = {}; if (isObject(keypath)) { options = callback || {}; } options.fragment = this.fragment; return this.ractive.observeOnce(keypath, callback, options); }; Context__proto__.pop = function pop (keypath) { return modelPop(findModel(this, keypath).model, []); }; Context__proto__.push = function push (keypath) { var values = [], len = arguments.length - 1; while ( len-- > 0 ) values[ len ] = arguments[ len + 1 ]; return modelPush(findModel(this, keypath).model, values); }; Context__proto__.raise = function raise (name, event) { var args = [], len = arguments.length - 2; while ( len-- > 0 ) args[ len ] = arguments[ len + 2 ]; var el = this.element; var ev; while (el) { if (el.component) { el = el.component; } ev = findEvent(el, name); if (ev) { return ev.fire( ev.element.getContext( event || {}, event && !('original' in event) ? { original: {} } : {} ), args ); } el = el.up && el.up.owner; } }; Context__proto__.readLink = function readLink (keypath, options) { return this.ractive.readLink(this.resolve(keypath), options); }; Context__proto__.resolve = function resolve (path, ractive) { var ref = findModel(this, path); var model = ref.model; var instance = ref.instance; return model ? model.getKeypath(ractive || instance) : path; }; Context__proto__.reverse = function reverse (keypath) { return modelReverse(findModel(this, keypath).model, []); }; Context__proto__.set = function set$2 (keypath, value, options) { return set(build$1(this, keypath, value), options); }; Context__proto__.shift = function shift (keypath) { return modelShift(findModel(this, keypath).model, []); }; Context__proto__.splice = function splice (keypath, index, drop) { var add = [], len = arguments.length - 3; while ( len-- > 0 ) add[ len ] = arguments[ len + 3 ]; add.unshift(index, drop); return modelSplice(findModel(this, keypath).model, add); }; Context__proto__.sort = function sort (keypath) { return modelSort(findModel(this, keypath).model, []); }; Context__proto__.subtract = function subtract (keypath, d, options) { var num = isNumber(d) ? d : 1; var opts = isObjectType(d) ? d : options; return set( build$1(this, keypath, num).map(function (pair) { var model = pair[0]; var val = pair[1]; var value = model.get(); if (!isNumeric(val) || !isNumeric(value)) { throw new Error('Cannot add non-numeric value'); } return [model, value - val]; }), opts ); }; Context__proto__.toggle = function toggle (keypath, options) { var ref = findModel(this, keypath); var model = ref.model; return set([[model, !model.get()]], options); }; Context__proto__.unlink = function unlink (dest) { var here = findModel(this, dest).model; var promise = runloop.start(); if (here.owner && here.owner._link) { here.owner.unlink(); } runloop.end(); return promise; }; Context__proto__.unlisten = function unlisten (event, handler) { this.element.off(event, handler); }; Context__proto__.unshift = function unshift (keypath) { var add = [], len = arguments.length - 1; while ( len-- > 0 ) add[ len ] = arguments[ len + 1 ]; return modelUnshift(findModel(this, keypath).model, add); }; Context__proto__.update = function update (keypath, options) { return update$1(this.ractive, findModel(this, keypath).model, options); }; Context__proto__.updateModel = function updateModel (keypath, cascade) { var ref = findModel(this, keypath); var model = ref.model; var promise = runloop.start(); model.updateFromBindings(cascade); runloop.end(); return promise; }; // two-way binding related helpers Context__proto__.isBound = function isBound () { var ref = this.getBindingModel(this); var model = ref.model; return !!model; }; Context__proto__.getBindingPath = function getBindingPath (ractive) { var ref = this.getBindingModel(this); var model = ref.model; var instance = ref.instance; if (model) { return model.getKeypath(ractive || instance); } }; Context__proto__.getBinding = function getBinding () { var ref = this.getBindingModel(this); var model = ref.model; if (model) { return model.get(true); } }; Context__proto__.getBindingModel = function getBindingModel (ctx) { var el = ctx.element; return { model: el.binding && el.binding.model, instance: el.up.ractive }; }; Context__proto__.setBinding = function setBinding (value) { var ref = this.getBindingModel(this); var model = ref.model; return set([[model, value]]); }; Object.defineProperties( Context__proto__, prototypeAccessors ); Context.forRactive = getRactiveContext; // circular deps are fun extern.Context = Context; // TODO: at some point perhaps this could support relative * keypaths? function build$1(ctx, keypath, value) { var sets = []; // set multiple keypaths in one go if (isObject(keypath)) { for (var k in keypath) { if (hasOwn(keypath, k)) { sets.push([findModel(ctx, k).model, keypath[k]]); } } } else { // set a single keypath sets.push([findModel(ctx, keypath).model, value]); } return sets; } function findModel(ctx, path) { var frag = ctx.fragment; if (!isString(path)) { return { model: frag.findContext(), instance: path }; } return { model: resolveReference(frag, path), instance: frag.ractive }; } function findEvent(el, name) { return el.events && el.events.find && el.events.find(function (e) { return ~e.template.n.indexOf(name); }); } function Ractive$fire(eventName) { var args = [], len = arguments.length - 1; while ( len-- > 0 ) args[ len ] = arguments[ len + 1 ]; var ctx; // watch for reproxy if (args[0] instanceof Context) { var proto = args.shift(); ctx = create(proto); assign(ctx, proto); } else if (isObjectType(args[0]) && (args[0] === null || args[0].constructor === Object)) { ctx = Context.forRactive(this, args.shift()); } else { ctx = Context.forRactive(this); } return fireEvent(this, eventName, ctx, args); } function Ractive$get(keypath, opts) { if (!isString(keypath)) { return this.viewmodel.get(true, keypath); } var keys = splitKeypath(keypath); var key = keys[0]; var model; if (!this.viewmodel.has(key)) { // if this is an inline component, we may need to create // an implicit mapping if (this.component && !this.isolated) { model = resolveReference(this.fragment || new FakeFragment(this), key); } } model = this.viewmodel.joinAll(keys); return model.get(true, opts); } var query = doc && doc.querySelector; function getContext$1(node) { if (isString(node) && query) { node = query.call(document, node); } var instances; if (node) { if (node._ractive) { return node._ractive.proxy.getContext(); } else if ((instances = node.__ractive_instances__)) { if (instances.length === 1) { return getRactiveContext(instances[0]); } } else { return getContext$1(node.parentNode); } } } function getContext$2(node, options) { if (!node) { return getRactiveContext(this); } if (isString(node)) { node = this.find(node, options); } return getContext$1(node); } var html = 'http://www.w3.org/1999/xhtml'; var mathml = 'http://www.w3.org/1998/Math/MathML'; var svg$1 = 'http://www.w3.org/2000/svg'; var xlink = 'http://www.w3.org/1999/xlink'; var xml = 'http://www.w3.org/XML/1998/namespace'; var xmlns = 'http://www.w3.org/2000/xmlns'; var namespaces = { html: html, mathml: mathml, svg: svg$1, xlink: xlink, xml: xml, xmlns: xmlns }; var createElement; var matches; var div; var methodNames; var unprefixed; var prefixed; var i; var j; var makeFunction; // Test for SVG support if (!svg) { /* istanbul ignore next */ createElement = function (type, ns, extend) { if (ns && ns !== html) { throw "This browser does not support namespaces other than http://www.w3.org/1999/xhtml. The most likely cause of this error is that you're trying to render SVG in an older browser. See http://ractive.js.org/support/#svgs for more information"; } return extend ? doc.createElement(type, extend) : doc.createElement(type); }; } else { createElement = function (type, ns, extend) { if (!ns || ns === html) { return extend ? doc.createElement(type, extend) : doc.createElement(type); } return extend ? doc.createElementNS(ns, type, extend) : doc.createElementNS(ns, type); }; } function createDocumentFragment() { return doc.createDocumentFragment(); } function getElement(input) { var output; if (!input || typeof input === 'boolean') { return; } /* istanbul ignore next */ if (!win || !doc || !input) { return null; } // We already have a DOM node - no work to do. (Duck typing alert!) if (input.nodeType) { return input; } // Get node from string if (isString(input)) { // try ID first output = doc.getElementById(input); // then as selector, if possible if (!output && doc.querySelector) { try { output = doc.querySelector(input); } catch (e) { /* this space intentionally left blank */ } } // did it work? if (output && output.nodeType) { return output; } } // If we've been given a collection (jQuery, Zepto etc), extract the first item if (input[0] && input[0].nodeType) { return input[0]; } return null; } if (!isClient) { matches = null; } else { div = createElement('div'); methodNames = ['matches', 'matchesSelector']; makeFunction = function(methodName) { return function(node, selector) { return node[methodName](selector); }; }; i = methodNames.length; while (i-- && !matches) { unprefixed = methodNames[i]; if (div[unprefixed]) { matches = makeFunction(unprefixed); } else { j = vendors.length; while (j--) { prefixed = vendors[i] + unprefixed.substr(0, 1).toUpperCase() + unprefixed.substring(1); if (div[prefixed]) { matches = makeFunction(prefixed); break; } } } } // IE8... and apparently phantom some? /* istanbul ignore next */ if (!matches) { matches = function(node, selector) { var parentNode, i; parentNode = node.parentNode; if (!parentNode) { // empty dummy <div> div.innerHTML = ''; parentNode = div; node = node.cloneNode(); div.appendChild(node); } var nodes = parentNode.querySelectorAll(selector); i = nodes.length; while (i--) { if (nodes[i] === node) { return true; } } return false; }; } } function detachNode(node) { // stupid ie // eslint-disable-next-line valid-typeof if (node && typeof node.parentNode !== 'unknown' && node.parentNode) { node.parentNode.removeChild(node); } return node; } function safeToStringValue(value) { return value == null || (isNumber(value) && isNaN(value)) || !value.toString ? '' : '' + value; } function safeAttributeString(string) { return safeToStringValue(string) .replace(/&/g, '&amp;') .replace(/"/g, '&quot;') .replace(/'/g, '&#39;'); } function Ractive$insert(target, anchor) { if (!this.fragment.rendered) { // TODO create, and link to, documentation explaining this throw new Error( 'The API has changed - you must call `ractive.render(target[, anchor])` to render your Ractive instance. Once rendered you can use `ractive.insert()`.' ); } target = getElement(target); anchor = getElement(anchor) || null; if (!target) { throw new Error('You must specify a valid target to insert into'); } target.insertBefore(this.detach(), anchor); this.el = target; (target.__ractive_instances__ || (target.__ractive_instances__ = [])).push(this); this.isDetached = false; fireInsertHook(this); } function fireInsertHook(ractive) { hooks.insert.fire(ractive); ractive.findAllComponents('*').forEach(function (child) { fireInsertHook(child.instance); }); } function link(there, here, options) { var model; var target = (options && (options.ractive || options.instance)) || this; // may need to allow a mapping to resolve implicitly var sourcePath = splitKeypath(there); if (!target.viewmodel.has(sourcePath[0]) && target.component) { model = resolveReference(target.component.up, sourcePath[0]); model = model.joinAll(sourcePath.slice(1)); } var src = model || target.viewmodel.joinAll(sourcePath); var dest = this.viewmodel.joinAll(splitKeypath(here), { lastLink: false }); if (isUpstream(src, dest) || isUpstream(dest, src)) { throw new Error('A keypath cannot be linked to itself.'); } var promise = runloop.start(); dest.link(src, (options && options.keypath) || there); runloop.end(); return promise; } function isUpstream(check, start) { var model = start; while (model) { if (model === check || model.owner === check) { return true; } model = model.target || model.parent; } } var Observer = function Observer(ractive, model, callback, options) { this.context = options.context || ractive; this.callback = callback; this.ractive = ractive; this.keypath = options.keypath; this.options = options; if (model) { this.resolved(model); } if (isFunction(options.old)) { this.oldContext = create(ractive); this.oldFn = options.old; } if (options.init !== false) { this.dirty = true; this.dispatch(); } else { updateOld(this); } this.dirty = false; }; var Observer__proto__ = Observer.prototype; Observer__proto__.cancel = function cancel () { this.cancelled = true; if (this.model) { this.model.unregister(this); } else { this.resolver.unbind(); } removeFromArray(this.ractive._observers, this); }; Observer__proto__.dispatch = function dispatch () { if (!this.cancelled) { this.callback.call(this.context, this.newValue, this.oldValue, this.keypath); updateOld(this, true); this.dirty = false; } }; Observer__proto__.handleChange = function handleChange () { var this$1 = this; if (!this.dirty) { var newValue = this.model.get(); if (isEqual(newValue, this.oldValue)) { return; } this.newValue = newValue; if (this.options.strict && this.newValue === this.oldValue) { return; } runloop.addObserver(this, this.options.defer); this.dirty = true; if (this.options.once) { runloop.scheduleTask(function () { return this$1.cancel(); }); } } else { // make sure the newValue stays updated in case this observer gets touched multiple times in one loop this.newValue = this.model.get(); } }; Observer__proto__.rebind = function rebind (next, previous) { var this$1 = this; next = rebindMatch(this.keypath, next, previous); if (next === this.model) { return false; } if (this.model) { this.model.unregister(this); } if (next) { next.addShuffleTask(function () { return this$1.resolved(next); }); } }; Observer__proto__.resolved = function resolved (model) { this.model = model; this.oldValue = undefined; this.newValue = model.get(); model.register(this); }; function updateOld(observer, fresh) { var next = fresh ? observer.model ? observer.model.get() : observer.newValue : observer.newValue; observer.oldValue = observer.oldFn ? observer.oldFn.call(observer.oldContext, undefined, next, observer.keypath) : next; } var star$1 = /\*+/g; var PatternObserver = function PatternObserver(ractive, baseModel, keys$$1, callback, options) { var this$1 = this; this.context = options.context || ractive; this.ractive = ractive; this.baseModel = baseModel; this.keys = keys$$1; this.callback = callback; var pattern = keys$$1.join('\\.').replace(star$1, '(.+)'); var baseKeypath = (this.baseKeypath = baseModel.getKeypath(ractive)); this.pattern = new RegExp(("^" + (baseKeypath ? baseKeypath + '\\.' : '') + pattern + "$")); this.recursive = keys$$1.length === 1 && keys$$1[0] === '**'; if (this.recursive) { this.keys = ['*']; } if (options.old) { this.oldContext = create(ractive); this.oldFn = options.old; } this.oldValues = {}; this.newValues = {}; this.defer = options.defer; this.once = options.once; this.strict = options.strict; this.dirty = false; this.changed = []; this.partial = false; this.links = options.links; var models = baseModel.findMatches(this.keys); models.forEach(function (model) { this$1.newValues[model.getKeypath(this$1.ractive)] = model.get(); }); if (options.init !== false) { this.dispatch(); } else { updateOld$1(this, this.newValues); } baseModel.registerPatternObserver(this); }; var PatternObserver__proto__ = PatternObserver.prototype; PatternObserver__proto__.cancel = function cancel () { this.baseModel.unregisterPatternObserver(this); removeFromArray(this.ractive._observers, this); }; PatternObserver__proto__.dispatch = function dispatch () { var this$1 = this; var newValues = this.newValues; this.newValues = {}; keys(newValues).forEach(function (keypath) { var newValue = newValues[keypath]; var oldValue = this$1.oldValues[keypath]; if (this$1.strict && newValue === oldValue) { return; } if (isEqual(newValue, oldValue)) { return; } var args = [newValue, oldValue, keypath]; if (keypath) { var wildcards = this$1.pattern.exec(keypath); if (wildcards) { args = args.concat(wildcards.slice(1)); } } this$1.callback.apply(this$1.context, args); }); updateOld$1(this, newValues, this.partial); this.dirty = false; }; PatternObserver__proto__.notify = function notify (key) { this.changed.push(key); }; PatternObserver__proto__.shuffle = function shuffle (newIndices) { var this$1 = this; if (!isArray(this.baseModel.value)) { return; } var max = this.baseModel.value.length; for (var i = 0; i < newIndices.length; i++) { if (newIndices[i] === -1 || newIndices[i] === i) { continue; } this$1.changed.push([i]); } for (var i$1 = newIndices.touchedFrom; i$1 < max; i$1++) { this$1.changed.push([i$1]); } }; PatternObserver__proto__.handleChange = function handleChange () { var this$1 = this; if (!this.dirty || this.changed.length) { if (!this.dirty) { this.newValues = {}; } if (!this.changed.length) { this.baseModel.findMatches(this.keys).forEach(function (model) { var keypath = model.getKeypath(this$1.ractive); this$1.newValues[keypath] = model.get(); }); this.partial = false; } else { var count = 0; if (this.recursive) { this.changed.forEach(function (keys$$1) { var model = this$1.baseModel.joinAll(keys$$1); if (model.isLink && !this$1.links) { return; } count++; this$1.newValues[model.getKeypath(this$1.ractive)] = model.get(); }); } else { var ok = this.baseModel.isRoot ? this.changed.map(function (keys$$1) { return keys$$1.map(escapeKey).join('.'); }) : this.changed.map(function (keys$$1) { return this$1.baseKeypath + '.' + keys$$1.map(escapeKey).join('.'); }); this.baseModel.findMatches(this.keys).forEach(function (model) { var keypath = model.getKeypath(this$1.ractive); var check = function (k) { return ( (k.indexOf(keypath) === 0 && (k.length === keypath.length || k[keypath.length] === '.')) || (keypath.indexOf(k) === 0 && (k.length === keypath.length || keypath[k.length] === '.')) ); }; // is this model on a changed keypath? if (ok.filter(check).length) { count++; this$1.newValues[keypath] = model.get(); } }); } // no valid change triggered, so bail to avoid breakage if (!count) { return; } this.partial = true; } runloop.addObserver(this, this.defer); this.dirty = true; this.changed.length = 0; if (this.once) { this.cancel(); } } }; function updateOld$1(observer, vals, partial) { var olds = observer.oldValues; if (observer.oldFn) { if (!partial) { observer.oldValues = {}; } keys(vals).forEach(function (k) { var args = [olds[k], vals[k], k]; var parts = observer.pattern.exec(k); if (parts) { args.push.apply(args, parts.slice(1)); } observer.oldValues[k] = observer.oldFn.apply(observer.oldContext, args); }); } else { if (partial) { keys(vals).forEach(function (k) { return (olds[k] = vals[k]); }); } else { observer.oldValues = vals; } } } function negativeOne() { return -1; } var ArrayObserver = function ArrayObserver(ractive, model, callback, options) { this.ractive = ractive; this.model = model; this.keypath = model.getKeypath(); this.callback = callback; this.options = options; this.pending = null; model.register(this); if (options.init !== false) { this.sliced = []; this.shuffle([]); this.dispatch(); } else { this.sliced = this.slice(); } }; var ArrayObserver__proto__ = ArrayObserver.prototype; ArrayObserver__proto__.cancel = function cancel () { this.model.unregister(this); removeFromArray(this.ractive._observers, this); }; ArrayObserver__proto__.dispatch = function dispatch () { this.callback(this.pending); this.pending = null; if (this.options.once) { this.cancel(); } }; ArrayObserver__proto__.handleChange = function handleChange (path) { if (this.pending) { // post-shuffle runloop.addObserver(this, this.options.defer); } else if (!path) { // entire array changed this.shuffle(this.sliced.map(negativeOne)); this.handleChange(); } }; ArrayObserver__proto__.shuffle = function shuffle (newIndices) { var this$1 = this; var newValue = this.slice(); var inserted = []; var deleted = []; var start; var hadIndex = {}; newIndices.forEach(function (newIndex, oldIndex) { hadIndex[newIndex] = true; if (newIndex !== oldIndex && start === undefined) { start = oldIndex; } if (newIndex === -1) { deleted.push(this$1.sliced[oldIndex]); } }); if (start === undefined) { start = newIndices.length; } var len = newValue.length; for (var i = 0; i < len; i += 1) { if (!hadIndex[i]) { inserted.push(newValue[i]); } } this.pending = { inserted: inserted, deleted: deleted, start: start }; this.sliced = newValue; }; ArrayObserver__proto__.slice = function slice () { var value = this.model.get(); return isArray(value) ? value.slice() : []; }; function observe(keypath, callback, options) { var this$1 = this; var observers = []; var map; var opts; if (isObject(keypath)) { map = keypath; opts = callback || {}; } else { if (isFunction(keypath)) { map = { '': keypath }; opts = callback || {}; } else { map = {}; map[keypath] = callback; opts = options || {}; } } var silent = false; keys(map).forEach(function (keypath) { var callback = map[keypath]; var caller = function() { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; if (silent) { return; } return callback.apply(this, args); }; var keypaths = keypath.split(' '); if (keypaths.length > 1) { keypaths = keypaths.filter(function (k) { return k; }); } keypaths.forEach(function (keypath) { opts.keypath = keypath; var observer = createObserver(this$1, keypath, caller, opts); if (observer) { observers.push(observer); } }); }); // add observers to the Ractive instance, so they can be // cancelled on ractive.teardown() this._observers.push.apply(this._observers, observers); return { cancel: function () { return observers.forEach(function (o) { return o.cancel(); }); }, isSilenced: function () { return silent; }, silence: function () { return (silent = true); }, resume: function () { return (silent = false); } }; } function createObserver(ractive, keypath, callback, options) { var keys$$1 = splitKeypath(keypath); var wildcardIndex = keys$$1.indexOf('*'); if (!~wildcardIndex) { wildcardIndex = keys$$1.indexOf('**'); } options.fragment = options.fragment || ractive.fragment; var model; if (!options.fragment) { model = ractive.viewmodel.joinKey(keys$$1[0]); } else { // .*.whatever relative wildcard is a special case because splitkeypath doesn't handle the leading . if (~keys$$1[0].indexOf('.*')) { model = options.fragment.findContext(); wildcardIndex = 0; keys$$1[0] = keys$$1[0].slice(1); } else { model = wildcardIndex === 0 ? options.fragment.findContext() : resolveReference(options.fragment, keys$$1[0]); } } // the model may not exist key if (!model) { model = ractive.viewmodel.joinKey(keys$$1[0]); } if (!~wildcardIndex) { model = model.joinAll(keys$$1.slice(1)); if (options.array) { return new ArrayObserver(ractive, model, callback, options); } else { return new Observer(ractive, model, callback, options); } } else { var double = keys$$1.indexOf('**'); if (~double) { if (double + 1 !== keys$$1.length || ~keys$$1.indexOf('*')) { warnOnceIfDebug( "Recursive observers may only specify a single '**' at the end of the path." ); return; } } model = model.joinAll(keys$$1.slice(1, wildcardIndex)); return new PatternObserver(ractive, model, keys$$1.slice(wildcardIndex), callback, options); } } var onceOptions = { init: false, once: true }; function observeOnce(keypath, callback, options) { if (isObject(keypath) || isFunction(keypath)) { options = assign(callback || {}, onceOptions); return this.observe(keypath, options); } options = assign(options || {}, onceOptions); return this.observe(keypath, callback, options); } var trim = function (str) { return str.trim(); }; var notEmptyString = function (str) { return str !== ''; }; function Ractive$off(eventName, callback) { var this$1 = this; // if no event is specified, remove _all_ event listeners if (!eventName) { this._subs = {}; } else { // Handle multiple space-separated event names var eventNames = eventName .split(' ') .map(trim) .filter(notEmptyString); eventNames.forEach(function (event) { var subs = this$1._subs[event]; // if given a specific callback to remove, remove only it if (subs && callback) { var entry = subs.find(function (s) { return s.callback === callback; }); if (entry) { removeFromArray(subs, entry); entry.off = true; if (event.indexOf('.')) { this$1._nsSubs--; } } } else if (subs) { // otherwise, remove all listeners for this event if (event.indexOf('.')) { this$1._nsSubs -= subs.length; } subs.length = 0; } }); } return this; } function Ractive$on(eventName, callback) { var this$1 = this; // eventName may already be a map var map = isObjectType(eventName) ? eventName : {}; // or it may be a string along with a callback if (isString(eventName)) { map[eventName] = callback; } var silent = false; var events = []; var loop = function ( k ) { var callback$1 = map[k]; var caller = function() { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; if (!silent) { return callback$1.apply(this, args); } }; var entry = { callback: callback$1, handler: caller }; if (hasOwn(map, k)) { var names = k .split(' ') .map(trim) .filter(notEmptyString); names.forEach(function (n) { (this$1._subs[n] || (this$1._subs[n] = [])).push(entry); if (n.indexOf('.')) { this$1._nsSubs++; } events.push([n, entry]); }); } }; for (var k in map) loop( k ); return { cancel: function () { return events.forEach(function (e) { return this$1.off(e[0], e[1].callback); }); }, isSilenced: function () { return silent; }, silence: function () { return (silent = true); }, resume: function () { return (silent = false); } }; } function Ractive$once(eventName, handler) { var listener = this.on(eventName, function() { handler.apply(this, arguments); listener.cancel(); }); // so we can still do listener.cancel() manually return listener; } var pop = makeArrayMethod('pop').path; var push = makeArrayMethod('push').path; function readLink(keypath, options) { if ( options === void 0 ) options = {}; var path = splitKeypath(keypath); if (this.viewmodel.has(path[0])) { var model = this.viewmodel.joinAll(path); if (!model.isLink) { return; } while ((model = model.target) && options.canonical !== false) { if (!model.isLink) { break; } } if (model) { return { ractive: model.root.ractive, keypath: model.getKeypath() }; } } } var PREFIX = '/* Ractive.js component styles */'; // Holds current definitions of styles. var styleDefinitions = []; // Flag to tell if we need to update the CSS var isDirty = false; // These only make sense on the browser. See additional setup below. var styleElement = null; var useCssText = null; function addCSS(styleDefinition) { styleDefinitions.push(styleDefinition); isDirty = true; } function applyCSS(force) { var styleElement = style(); // Apply only seems to make sense when we're in the DOM. Server-side renders // can call toCSS to get the updated CSS. if (!styleElement || (!force && !isDirty)) { return; } if (useCssText) { styleElement.styleSheet.cssText = getCSS(null); } else { styleElement.innerHTML = getCSS(null); } isDirty = false; } function getCSS(cssIds) { var filteredStyleDefinitions = cssIds ? styleDefinitions.filter(function (style) { return ~cssIds.indexOf(style.id); }) : styleDefinitions; filteredStyleDefinitions.forEach(function (d) { return (d.applied = true); }); return filteredStyleDefinitions.reduce( function (styles, style) { return ("" + (styles ? (styles + "\n\n/* {" + (style.id) + "} */\n" + (style.styles)) : '')); }, PREFIX ); } function style() { // If we're on the browser, additional setup needed. if (doc && !styleElement) { styleElement = doc.createElement('style'); styleElement.type = 'text/css'; styleElement.setAttribute('data-ractive-css', ''); doc.getElementsByTagName('head')[0].appendChild(styleElement); useCssText = !!styleElement.styleSheet; } return styleElement; } var adaptConfigurator = { extend: function (Parent, proto, options) { proto.adapt = combine(proto.adapt, ensureArray(options.adapt)); }, init: function init() {} }; var remove = /\/\*(?:[\s\S]*?)\*\//g; var escape = /url\(\s*(['"])(?:\\[\s\S]|(?!\1).)*\1\s*\)|url\((?:\\[\s\S]|[^)])*\)|(['"])(?:\\[\s\S]|(?!\2).)*\2/gi; var value = /\0(\d+)/g; // Removes comments and strings from the given CSS to make it easier to parse. // Callback receives the cleaned CSS and a function which can be used to put // the removed strings back in place after parsing is done. function cleanCss(css, callback, additionalReplaceRules) { if ( additionalReplaceRules === void 0 ) additionalReplaceRules = []; var values = []; var reconstruct = function (css) { return css.replace(value, function (match, n) { return values[n]; }); }; css = css.replace(escape, function (match) { return ("\u0000" + (values.push(match) - 1)); }).replace(remove, ''); additionalReplaceRules.forEach(function (pattern) { css = css.replace(pattern, function (match) { return ("\u0000" + (values.push(match) - 1)); }); }); return callback(css, reconstruct); } var selectorsPattern = /(?:^|\}|\{|\x01)\s*([^\{\}\0\x01]+)\s*(?=\{)/g; var importPattern = /@import\s*\([^)]*\)\s*;?/gi; var importEndPattern = /\x01/g; var keyframesDeclarationPattern = /@keyframes\s+[^\{\}]+\s*\{(?:[^{}]+|\{[^{}]+})*}/gi; var selectorUnitPattern = /((?:(?:\[[^\]]+\])|(?:[^\s\+\>~:]))+)((?:::?[^\s\+\>\~\(:]+(?:\([^\)]+\))?)*\s*[\s\+\>\~]?)\s*/g; var excludePattern = /^(?:@|\d+%)/; var dataRvcGuidPattern = /\[data-ractive-css~="\{[a-z0-9-]+\}"]/g; function trim$1(str) { return str.trim(); } function extractString(unit) { return unit.str; } function transformSelector(selector, parent) { var selectorUnits = []; var match; while ((match = selectorUnitPattern.exec(selector))) { selectorUnits.push({ str: match[0], base: match[1], modifiers: match[2] }); } // For each simple selector within the selector, we need to create a version // that a) combines with the id, and b) is inside the id var base = selectorUnits.map(extractString); var transformed = []; var i = selectorUnits.length; while (i--) { var appended = base.slice(); // Pseudo-selectors should go after the attribute selector var unit = selectorUnits[i]; appended[i] = unit.base + parent + unit.modifiers || ''; var prepended = base.slice(); prepended[i] = parent + ' ' + prepended[i]; transformed.push(appended.join(' '), prepended.join(' ')); } return transformed.join(', '); } function transformCss(css, id) { var dataAttr = "[data-ractive-css~=\"{" + id + "}\"]"; var transformed; if (dataRvcGuidPattern.test(css)) { transformed = css.replace(dataRvcGuidPattern, dataAttr); } else { transformed = cleanCss( css, function (css, reconstruct) { css = css .replace(importPattern, '$&\x01') .replace(selectorsPattern, function (match, $1) { // don't transform at-rules and keyframe declarations if (excludePattern.test($1)) { return match; } var selectors = $1.split(',').map(trim$1); var transformed = selectors.map(function (selector) { return transformSelector(selector, dataAttr); }).join(', ') + ' '; return match.replace($1, transformed); }) .replace(importEndPattern, ''); return reconstruct(css); }, [keyframesDeclarationPattern] ); } return transformed; } function s4() { return Math.floor((1 + Math.random()) * 0x10000) .toString(16) .substring(1); } function uuid() { return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4(); } function setCSSData(keypath, value, options) { var opts = isObjectType(keypath) ? value : options; var model = this._cssModel; model.locked = true; var promise = set(build({ viewmodel: model }, keypath, value, true), opts); model.locked = false; var cascade = runloop.start(); this.extensions.forEach(function (e) { var model = e._cssModel; model.mark(); model.downstreamChanged('', 1); }); runloop.end(); applyChanges(this, !opts || opts.apply !== false); return promise.then(function () { return cascade; }); } function applyChanges(component, apply) { var local = recomputeCSS(component); var child = component.extensions .map(function (e) { return applyChanges(e, false); }) .reduce(function (a, c) { return c || a; }, false); if (apply && (local || child)) { var def = component._cssDef; if (!def || (def && def.applied)) { applyCSS(true); } } return local || child; } function recomputeCSS(component) { var css = component.css; if (!isFunction(css)) { return; } var def = component._cssDef; var result = evalCSS(component, css); var styles = def.transform ? transformCss(result, def.id) : result; if (def.styles === styles) { return; } def.styles = styles; return true; } var CSSModel = (function (SharedModel) { function CSSModel(component) { SharedModel.call(this, component.cssData, '@style'); this.component = component; } if ( SharedModel ) CSSModel.__proto__ = SharedModel; var CSSModel__proto__ = CSSModel.prototype = Object.create( SharedModel && SharedModel.prototype ); CSSModel__proto__.constructor = CSSModel; CSSModel__proto__.downstreamChanged = function downstreamChanged (path, depth) { if (this.locked) { return; } var component = this.component; component.extensions.forEach(function (e) { var model = e._cssModel; model.mark(); model.downstreamChanged(path, depth || 1); }); if (!depth) { applyChanges(component, true); } }; return CSSModel; }(SharedModel)); var hasCurly = /\{/; var cssConfigurator = { name: 'css', // Called when creating a new component definition extend: function (Parent, proto, options, Child) { Child._cssIds = gatherIds(Parent); defineProperty(Child, 'cssData', { configurable: true, value: assign(create(Parent.cssData), options.cssData || {}) }); defineProperty(Child, '_cssModel', { configurable: true, value: new CSSModel(Child) }); if (options.css) { initCSS(options, Child, proto); } }, // Called when creating a new component instance init: function (Parent, target, options) { if (!options.css) { return; } warnIfDebug("\nThe css option is currently not supported on a per-instance basis and will be discarded. Instead, we recommend instantiating from a component definition with a css option.\n\nconst Component = Ractive.extend({\n\t...\n\tcss: '/* your css */',\n\t...\n});\n\nconst componentInstance = new Component({ ... })\n\t\t"); } }; function gatherIds(start) { var cmp = start; var ids = []; while (cmp) { if (cmp.prototype.cssId) { ids.push(cmp.prototype.cssId); } cmp = cmp.Parent; } return ids; } function evalCSS(component, css) { if (isString(css)) { return css; } var cssData = component.cssData; var model = component._cssModel; var data = function data(path) { return model.joinAll(splitKeypath(path)).get(); }; data.__proto__ = cssData; var result = css.call(component, data); return isString(result) ? result : ''; } function initCSS(options, target, proto) { var css = options.css === true ? '' : isString(options.css) && !hasCurly.test(options.css) ? getElement(options.css) || options.css : options.css; var cssProp = css; var id = options.cssId || uuid(); if (isObjectType(css)) { css = 'textContent' in css ? css.textContent : css.innerHTML; cssProp = css; } else if (isFunction(css)) { cssProp = css; css = evalCSS(target, css); } var def = { transform: 'noCSSTransform' in options ? !options.noCSSTransform : !options.noCssTransform }; defineProperty(target, '_cssDef', { configurable: true, value: def }); defineProperty(target, 'css', { get: function get() { return cssProp; }, set: function set(next) { cssProp = next; var css = evalCSS(target, cssProp); var styles = def.styles; def.styles = def.transform ? transformCss(css, id) : css; if (def.applied && styles !== def.styles) { applyCSS(true); } } }); def.styles = def.transform ? transformCss(css, id) : css; def.id = proto.cssId = id; target._cssIds.push(id); addCSS(target._cssDef); } function validate(data) { // Warn if userOptions.data is a non-POJO if (data && data.constructor !== Object) { if (isFunction(data)) { // TODO do we need to support this in the new Ractive() case? } else if (!isObjectType(data)) { fatal(("data option must be an object or a function, `" + data + "` is not valid")); } else { warnIfDebug( 'If supplied, options.data should be a plain JavaScript object - using a non-POJO as the root object may work, but is discouraged' ); } } } var dataConfigurator = { name: 'data', extend: function (Parent, proto, options) { var key; var value; // check for non-primitives, which could cause mutation-related bugs if (options.data && isObject(options.data)) { for (key in options.data) { value = options.data[key]; if (value && isObjectType(value)) { if (isObject(value) || isArray(value)) { warnIfDebug("Passing a `data` option with object and array properties to Ractive.extend() is discouraged, as mutating them is likely to cause bugs. Consider using a data function instead:\n\n // this...\n data: function () {\n return {\n myObject: {}\n };\n })\n\n // instead of this:\n data: {\n myObject: {}\n }"); } } } } proto.data = combine$1(proto.data, options.data); }, init: function (Parent, ractive, options) { var result = combine$1(Parent.prototype.data, options.data); if (isFunction(result)) { result = result.call(ractive); } // bind functions to the ractive instance at the top level, // unless it's a non-POJO (in which case alarm bells should ring) if (result && result.constructor === Object) { for (var prop in result) { if (isFunction(result[prop])) { var value = result[prop]; result[prop] = bind(value, ractive); result[prop]._r_unbound = value; } } } return result || {}; }, reset: function reset(ractive) { var result = this.init(ractive.constructor, ractive, ractive.viewmodel); ractive.viewmodel.root.set(result); return true; } }; function emptyData() { return {}; } function combine$1(parentValue, childValue) { validate(childValue); var parentIsFn = isFunction(parentValue); // Very important, otherwise child instance can become // the default data object on Ractive or a component. // then ractive.set() ends up setting on the prototype! if (!childValue && !parentIsFn) { // this needs to be a function so that it can still inherit parent defaults childValue = emptyData; } var childIsFn = isFunction(childValue); // Fast path, where we just need to copy properties from // parent to child if (!parentIsFn && !childIsFn) { return fromProperties(childValue, parentValue); } return function() { var child = childIsFn ? callDataFunction(childValue, this) : childValue; var parent = parentIsFn ? callDataFunction(parentValue, this) : parentValue; return fromProperties(child, parent); }; } function callDataFunction(fn, context) { var data = fn.call(context); if (!data) { return; } if (!isObjectType(data)) { fatal('Data function must return an object'); } if (data.constructor !== Object) { warnOnceIfDebug( 'Data function returned something other than a plain JavaScript object. This might work, but is strongly discouraged' ); } return data; } function fromProperties(primary, secondary) { if (primary && secondary) { for (var key in secondary) { if (!(key in primary)) { primary[key] = secondary[key]; } } return primary; } return primary || secondary; } var templateConfigurator = { name: 'template', extend: function extend(Parent, proto, options) { // only assign if exists if ('template' in options) { var template = options.template; if (isFunction(template)) { proto.template = template; } else { proto.template = parseTemplate(template, proto); } } }, init: function init(Parent, ractive, options) { // TODO because of prototypal inheritance, we might just be able to use // ractive.template, and not bother passing through the Parent object. // At present that breaks the test mocks' expectations var template = 'template' in options ? options.template : Parent.prototype.template; template = template || { v: TEMPLATE_VERSION, t: [] }; if (isFunction(template)) { var fn = template; template = getDynamicTemplate(ractive, fn); ractive._config.template = { fn: fn, result: template }; } template = parseTemplate(template, ractive); // TODO the naming of this is confusing - ractive.template refers to [...], // but Component.prototype.template refers to {v:1,t:[],p:[]}... // it's unnecessary, because the developer never needs to access // ractive.template ractive.template = template.t; if (template.p) { extendPartials(ractive.partials, template.p); } }, reset: function reset(ractive) { var result = resetValue(ractive); if (result) { var parsed = parseTemplate(result, ractive); ractive.template = parsed.t; extendPartials(ractive.partials, parsed.p, true); return true; } } }; function resetValue(ractive) { var initial = ractive._config.template; // If this isn't a dynamic template, there's nothing to do if (!initial || !initial.fn) { return; } var result = getDynamicTemplate(ractive, initial.fn); // TODO deep equality check to prevent unnecessary re-rendering // in the case of already-parsed templates if (result !== initial.result) { initial.result = result; return result; } } function getDynamicTemplate(ractive, fn) { return fn.call(ractive, { fromId: parser.fromId, isParsed: parser.isParsed, parse: function parse(template, options) { if ( options === void 0 ) options = parser.getParseOptions(ractive); return parser.parse(template, options); } }); } function parseTemplate(template, ractive) { if (isString(template)) { // parse will validate and add expression functions template = parseAsString(template, ractive); } else { // need to validate and add exp for already parsed template validate$1(template); addFunctions(template); } return template; } function parseAsString(template, ractive) { // ID of an element containing the template? if (template[0] === '#') { template = parser.fromId(template); } return parser.parseFor(template, ractive); } function validate$1(template) { // Check that the template even exists if (template == undefined) { throw new Error(("The template cannot be " + template + ".")); } else if (!isNumber(template.v)) { // Check the parsed template has a version at all throw new Error( "The template parser was passed a non-string template, but the template doesn't have a version. Make sure you're passing in the template you think you are." ); } else if (template.v !== TEMPLATE_VERSION) { // Check we're using the correct version throw new Error( ("Mismatched template version (expected " + TEMPLATE_VERSION + ", got " + (template.v) + ") Please ensure you are using the latest version of Ractive.js in your build process as well as in your app") ); } } function extendPartials(existingPartials, newPartials, overwrite) { if (!newPartials) { return; } // TODO there's an ambiguity here - we need to overwrite in the `reset()` // case, but not initially... for (var key in newPartials) { if (overwrite || !hasOwn(existingPartials, key)) { existingPartials[key] = newPartials[key]; } } } var registryNames = [ 'adaptors', 'components', 'computed', 'decorators', 'easing', 'events', 'helpers', 'interpolators', 'partials', 'transitions' ]; var registriesOnDefaults = ['computed', 'helpers']; var Registry = function Registry(name, useDefaults) { this.name = name; this.useDefaults = useDefaults; }; var Registry__proto__ = Registry.prototype; Registry__proto__.extend = function extend (Parent, proto, options) { var parent = this.useDefaults ? Parent.defaults : Parent; var target = this.useDefaults ? proto : proto.constructor; this.configure(parent, target, options); }; Registry__proto__.init = function init () { // noop }; Registry__proto__.configure = function configure (Parent, target, options) { var name = this.name; var option = options[name]; var registry = create(Parent[name]); assign(registry, option); target[name] = registry; if (name === 'partials' && target[name]) { keys(target[name]).forEach(function (key) { addFunctions(target[name][key]); }); } }; Registry__proto__.reset = function reset (ractive) { var registry = ractive[this.name]; var changed = false; keys(registry).forEach(function (key) { var item = registry[key]; if (item._fn) { if (item._fn.isOwner) { registry[key] = item._fn; } else { delete registry[key]; } changed = true; } }); return changed; }; var registries = registryNames.map(function (name) { var putInDefaults = registriesOnDefaults.indexOf(name) > -1; return new Registry(name, putInDefaults); }); function wrap(parent, name, method) { if (!/_super/.test(method)) { return method; } function wrapper() { var superMethod = getSuperMethod(wrapper._parent, name); var hasSuper = '_super' in this; var oldSuper = this._super; this._super = superMethod; var result = method.apply(this, arguments); if (hasSuper) { this._super = oldSuper; } else { delete this._super; } return result; } wrapper._parent = parent; wrapper._method = method; return wrapper; } function getSuperMethod(parent, name) { if (name in parent) { var value = parent[name]; return isFunction(value) ? value : function () { return value; }; } return noop; } function getMessage(deprecated, correct, isError) { return ( "options." + deprecated + " has been deprecated in favour of options." + correct + "." + (isError ? (" You cannot specify both options, please use options." + correct + ".") : '') ); } function deprecateOption(options, deprecatedOption, correct) { if (deprecatedOption in options) { if (!(correct in options)) { warnIfDebug(getMessage(deprecatedOption, correct)); options[correct] = options[deprecatedOption]; } else { throw new Error(getMessage(deprecatedOption, correct, true)); } } } function deprecate(options) { deprecateOption(options, 'beforeInit', 'onconstruct'); deprecateOption(options, 'init', 'onrender'); deprecateOption(options, 'complete', 'oncomplete'); deprecateOption(options, 'eventDefinitions', 'events'); // Using extend with Component instead of options, // like Human.extend( Spider ) means adaptors as a registry // gets copied to options. So we have to check if actually an array if (isArray(options.adaptors)) { deprecateOption(options, 'adaptors', 'adapt'); } } var config = { extend: function (Parent, proto, options, Child) { return configure('extend', Parent, proto, options, Child); }, init: function (Parent, ractive, options) { return configure('init', Parent, ractive, options); }, reset: function (ractive) { return order.filter(function (c) { return c.reset && c.reset(ractive); }).map(function (c) { return c.name; }); } }; var custom = { adapt: adaptConfigurator, computed: config, css: cssConfigurator, data: dataConfigurator, helpers: config, template: templateConfigurator }; var defaultKeys = keys(defaults); var isStandardKey = makeObj(defaultKeys.filter(function (key) { return !custom[key]; })); // blacklisted keys that we don't double extend var isBlacklisted = makeObj( defaultKeys.concat(registries.map(function (r) { return r.name; }), ['on', 'observe', 'attributes', 'cssData', 'use']) ); var order = [].concat( defaultKeys.filter(function (key) { return !registries[key] && !custom[key]; }), registries, //custom.data, custom.template, custom.css ); function configure(method, Parent, target, options, Child) { deprecate(options); for (var key in options) { if (hasOwn(isStandardKey, key)) { var value = options[key]; // warn the developer if they passed a function and ignore its value // NOTE: we allow some functions on "el" because we duck type element lists // and some libraries or ef'ed-up virtual browsers (phantomJS) return a // function object as the result of querySelector methods if (key !== 'el' && isFunction(value)) { warnIfDebug( (key + " is a Ractive option that does not expect a function and will be ignored"), method === 'init' ? target : null ); } else { target[key] = value; } } } // disallow combination of `append` and `enhance` if (target.append && target.enhance) { throw new Error('Cannot use append and enhance at the same time'); } registries.forEach(function (registry) { registry[method](Parent, target, options, Child); }); adaptConfigurator[method](Parent, target, options, Child); templateConfigurator[method](Parent, target, options, Child); cssConfigurator[method](Parent, target, options, Child); extendOtherMethods(Parent.prototype, target, options); } var _super = /\b_super\b/; function extendOtherMethods(parent, target, options) { for (var key in options) { if (!isBlacklisted[key] && hasOwn(options, key)) { var member = options[key]; // if this is a method that overwrites a method, wrap it: if (isFunction(member)) { if ( (key in proto$9 || (key.slice(0, 2) === 'on' && key.slice(2) in hooks && key in target)) && !_super.test(member.toString()) ) { warnIfDebug( ("Overriding Ractive prototype function '" + key + "' without calling the '" + _super + "' method can be very dangerous.") ); } member = wrap(parent, key, member); } target[key] = member; } } } function makeObj(array) { var obj = {}; array.forEach(function (x) { return (obj[x] = true); }); return obj; } var Item = function Item(options) { this.up = options.up; this.ractive = options.up.ractive; this.template = options.template; this.index = options.index; this.type = options.template.t; this.dirty = false; }; var Item__proto__ = Item.prototype; Item__proto__.bubble = function bubble () { if (!this.dirty) { this.dirty = true; this.up.bubble(); } }; Item__proto__.destroyed = function destroyed () { if (this.fragment) { this.fragment.destroyed(); } }; Item__proto__.find = function find () { return null; }; Item__proto__.findComponent = function findComponent () { return null; }; Item__proto__.findNextNode = function findNextNode () { return this.up.findNextNode(this); }; Item__proto__.rebound = function rebound (update) { if (this.fragment) { this.fragment.rebound(update); } }; Item__proto__.shuffled = function shuffled () { if (this.fragment) { this.fragment.shuffled(); } }; Item__proto__.valueOf = function valueOf () { return this.toString(); }; Item.prototype.findAll = noop; Item.prototype.findAllComponents = noop; var ContainerItem = (function (Item) { function ContainerItem(options) { Item.call(this, options); } if ( Item ) ContainerItem.__proto__ = Item; var ContainerItem__proto__ = ContainerItem.prototype = Object.create( Item && Item.prototype ); ContainerItem__proto__.constructor = ContainerItem; ContainerItem__proto__.detach = function detach () { return this.fragment ? this.fragment.detach() : createDocumentFragment(); }; ContainerItem__proto__.find = function find (selector) { if (this.fragment) { return this.fragment.find(selector); } }; ContainerItem__proto__.findAll = function findAll (selector, options) { if (this.fragment) { this.fragment.findAll(selector, options); } }; ContainerItem__proto__.findComponent = function findComponent (name) { if (this.fragment) { return this.fragment.findComponent(name); } }; ContainerItem__proto__.findAllComponents = function findAllComponents (name, options) { if (this.fragment) { this.fragment.findAllComponents(name, options); } }; ContainerItem__proto__.firstNode = function firstNode (skipParent) { return this.fragment && this.fragment.firstNode(skipParent); }; ContainerItem__proto__.toString = function toString (escape) { return this.fragment ? this.fragment.toString(escape) : ''; }; return ContainerItem; }(Item)); var ComputationChild = (function (Model) { function ComputationChild(parent, key) { Model.call(this, parent, key); this.isReadonly = !this.root.ractive.syncComputedChildren; this.dirty = true; this.isComputed = true; } if ( Model ) ComputationChild.__proto__ = Model; var ComputationChild__proto__ = ComputationChild.prototype = Object.create( Model && Model.prototype ); ComputationChild__proto__.constructor = ComputationChild; var prototypeAccessors$1 = { setRoot: {} }; prototypeAccessors$1.setRoot.get = function () { return this.parent.setRoot; }; ComputationChild__proto__.applyValue = function applyValue (value) { Model.prototype.applyValue.call(this, value); if (!this.isReadonly) { var source = this.parent; // computed models don't have a shuffle method while (source && source.shuffle) { source = source.parent; } if (source) { source.dependencies.forEach(mark); } } if (this.setRoot) { this.setRoot.set(this.setRoot.value); } }; ComputationChild__proto__.get = function get (shouldCapture, opts) { if (shouldCapture) { capture(this); } if (this.dirty) { this.dirty = false; var parentValue = this.parent.get(); this.value = parentValue ? parentValue[this.key] : undefined; if (this.wrapper) { this.newWrapperValue = this.value; } this.adapt(); } return (opts && 'unwrap' in opts ? opts.unwrap !== false : shouldCapture) && this.wrapper ? this.wrapperValue : this.value; }; ComputationChild__proto__.handleChange = function handleChange$2 () { if (this.dirty) { return; } this.dirty = true; if (this.boundValue) { this.boundValue = null; } this.links.forEach(marked); this.deps.forEach(handleChange); this.children.forEach(handleChange); }; ComputationChild__proto__.joinKey = function joinKey (key) { if (key === undefined || key === '') { return this; } if (!hasOwn(this.childByKey, key)) { var child = new ComputationChild(this, key); this.children.push(child); this.childByKey[key] = child; } return this.childByKey[key]; }; Object.defineProperties( ComputationChild__proto__, prototypeAccessors$1 ); return ComputationChild; }(Model)); /* global console */ /* eslint no-console:"off" */ var Computation = (function (Model) { function Computation(parent, signature, key) { Model.call(this, parent, key); this.signature = signature; this.isReadonly = !this.signature.setter; this.isComputed = true; this.dependencies = []; this.children = []; this.childByKey = {}; this.deps = []; this.dirty = true; // TODO: is there a less hackish way to do this? this.shuffle = undefined; } if ( Model ) Computation.__proto__ = Model; var Computation__proto__ = Computation.prototype = Object.create( Model && Model.prototype ); Computation__proto__.constructor = Computation; var prototypeAccessors$2 = { setRoot: {} }; prototypeAccessors$2.setRoot.get = function () { if (this.signature.setter) { return this; } }; Computation__proto__.get = function get (shouldCapture, opts) { if (shouldCapture) { capture(this); } if (this.dirty) { this.dirty = false; var old = this.value; this.value = this.getValue(); // this may cause a view somewhere to update, so it must be in a runloop if (!runloop.active()) { runloop.start(); if (!isEqual(old, this.value)) { this.notifyUpstream(); } runloop.end(); } else { if (!isEqual(old, this.value)) { this.notifyUpstream(); } } if (this.wrapper) { this.newWrapperValue = this.value; } this.adapt(); } // if capturing, this value needs to be unwrapped because it's for external use return maybeBind( this, // if unwrap is supplied, it overrides capture this.wrapper && (opts && 'unwrap' in opts ? opts.unwrap !== false : shouldCapture) ? this.wrapperValue : this.value, !opts || opts.shouldBind !== false ); }; Computation__proto__.getContext = function getContext () { return this.parent.isRoot ? this.root.ractive : this.parent.get(false, noVirtual); }; Computation__proto__.getValue = function getValue () { startCapturing(); var result; try { result = this.signature.getter.call(this.root.ractive, this.getContext()); } catch (err) { warnIfDebug(("Failed to compute " + (this.getKeypath()) + ": " + (err.message || err))); // TODO this is all well and good in Chrome, but... // ...also, should encapsulate this stuff better, and only // show it if Ractive.DEBUG if (hasConsole) { if (console.groupCollapsed) { console.groupCollapsed( '%cshow details', 'color: rgb(82, 140, 224); font-weight: normal; text-decoration: underline;' ); } var sig = this.signature; console.error( ((err.name) + ": " + (err.message) + "\n\n" + (sig.getterString) + (sig.getterUseStack ? '\n\n' + err.stack : '')) ); if (console.groupCollapsed) { console.groupEnd(); } } } var dependencies = stopCapturing(); this.setDependencies(dependencies); return result; }; Computation__proto__.mark = function mark () { this.handleChange(); }; Computation__proto__.rebind = function rebind (next, previous) { // computations will grab all of their deps again automagically if (next !== previous) { this.handleChange(); } }; Computation__proto__.set = function set (value) { if (this.isReadonly) { throw new Error(("Cannot set read-only computed value '" + (this.key) + "'")); } this.signature.setter(value); this.mark(); }; Computation__proto__.setDependencies = function setDependencies (dependencies) { var this$1 = this; // unregister any soft dependencies we no longer have var i = this.dependencies.length; while (i--) { var model = this$1.dependencies[i]; if (!~dependencies.indexOf(model)) { model.unregister(this$1); } } // and add any new ones i = dependencies.length; while (i--) { var model$1 = dependencies[i]; if (!~this$1.dependencies.indexOf(model$1)) { model$1.register(this$1); } } this.dependencies = dependencies; }; Computation__proto__.teardown = function teardown () { var this$1 = this; var i = this.dependencies.length; while (i--) { if (this$1.dependencies[i]) { this$1.dependencies[i].unregister(this$1); } } if (this.parent.computed[this.key] === this) { delete this.parent.computed[this.key]; } Model.prototype.teardown.call(this); }; Object.defineProperties( Computation__proto__, prototypeAccessors$2 ); return Computation; }(Model)); var prototype = Computation.prototype; var child = ComputationChild.prototype; prototype.handleChange = child.handleChange; prototype.joinKey = child.joinKey; shared$1.Computation = Computation; var ExpressionProxy = (function (Model) { function ExpressionProxy(fragment, template) { var this$1 = this; Model.call(this, fragment.ractive.viewmodel, null); this.fragment = fragment; this.template = template; this.isReadonly = true; this.isComputed = true; this.dirty = true; this.fn = fragment.ractive.allowExpressions === false ? noop : getFunction(template.s, template.r.length); this.models = this.template.r.map(function (ref) { return resolveReference(this$1.fragment, ref); }); this.dependencies = []; this.shuffle = undefined; this.bubble(); } if ( Model ) ExpressionProxy.__proto__ = Model; var ExpressionProxy__proto__ = ExpressionProxy.prototype = Object.create( Model && Model.prototype ); ExpressionProxy__proto__.constructor = ExpressionProxy; ExpressionProxy__proto__.bubble = function bubble (actuallyChanged) { if ( actuallyChanged === void 0 ) actuallyChanged = true; // refresh the keypath this.keypath = undefined; if (actuallyChanged) { this.handleChange(); } }; ExpressionProxy__proto__.getKeypath = function getKeypath () { var this$1 = this; if (!this.template) { return '@undefined'; } if (!this.keypath) { this.keypath = '@' + this.template.s.replace(/_(\d+)/g, function (match, i) { if (i >= this$1.models.length) { return match; } var model = this$1.models[i]; return model ? model.getKeypath() : '@undefined'; }); } return this.keypath; }; ExpressionProxy__proto__.getValue = function getValue () { var this$1 = this; startCapturing(); var result; try { var params = this.models.map(function (m) { return (m ? m.get(true) : undefined); }); result = this.fn.apply(this.fragment.ractive, params); } catch (err) { warnIfDebug(("Failed to compute " + (this.getKeypath()) + ": " + (err.message || err))); } var dependencies = stopCapturing(); // remove missing deps this.dependencies .filter(function (d) { return !~dependencies.indexOf(d); }) .forEach(function (d) { d.unregister(this$1); removeFromArray(this$1.dependencies, d); }); // register new deps dependencies .filter(function (d) { return !~this$1.dependencies.indexOf(d); }) .forEach(function (d) { d.register(this$1); this$1.dependencies.push(d); }); return result; }; ExpressionProxy__proto__.notifyUpstream = function notifyUpstream () {}; ExpressionProxy__proto__.rebind = function rebind (next, previous, safe) { var idx = this.models.indexOf(previous); if (~idx) { next = rebindMatch(this.template.r[idx], next, previous); if (next !== previous) { previous.unregister(this); this.models.splice(idx, 1, next); if (next) { next.addShuffleRegister(this, 'mark'); } } } this.bubble(!safe); }; ExpressionProxy__proto__.rebound = function rebound (update) { var this$1 = this; this.models = this.template.r.map(function (ref) { return resolveReference(this$1.fragment, ref); }); if (update) { this.bubble(true); } }; ExpressionProxy__proto__.retrieve = function retrieve () { return this.get(); }; ExpressionProxy__proto__.teardown = function teardown () { var this$1 = this; this.fragment = undefined; if (this.dependencies) { this.dependencies.forEach(function (d) { return d.unregister(this$1); }); } Model.prototype.teardown.call(this); }; ExpressionProxy__proto__.unreference = function unreference () { Model.prototype.unreference.call(this); collect(this); }; ExpressionProxy__proto__.unregister = function unregister (dep) { Model.prototype.unregister.call(this, dep); collect(this); }; ExpressionProxy__proto__.unregisterLink = function unregisterLink (link) { Model.prototype.unregisterLink.call(this, link); collect(this); }; return ExpressionProxy; }(Model)); var prototype$1 = ExpressionProxy.prototype; var computation = Computation.prototype; prototype$1.get = computation.get; prototype$1.handleChange = computation.handleChange; prototype$1.joinKey = computation.joinKey; prototype$1.mark = computation.mark; prototype$1.unbind = noop; function collect(model) { if (!model.deps.length && !model.refs && !model.links.length) { model.teardown(); } } var ReferenceExpressionProxy = (function (LinkModel) { function ReferenceExpressionProxy(fragment, template) { LinkModel.call(this, null, null, null, '@undefined'); this.root = fragment.ractive.viewmodel; this.template = template; this.rootLink = true; this.template = template; this.fragment = fragment; this.rebound(); } if ( LinkModel ) ReferenceExpressionProxy.__proto__ = LinkModel; var ReferenceExpressionProxy__proto__ = ReferenceExpressionProxy.prototype = Object.create( LinkModel && LinkModel.prototype ); ReferenceExpressionProxy__proto__.constructor = ReferenceExpressionProxy; ReferenceExpressionProxy__proto__.getKeypath = function getKeypath () { return this.model ? this.model.getKeypath() : '@undefined'; }; ReferenceExpressionProxy__proto__.rebound = function rebound () { var this$1 = this; var fragment = this.fragment; var template = this.template; var base = (this.base = resolve(fragment, template)); var idx; if (this.proxy) { teardown$1(this); } var proxy = (this.proxy = { rebind: function (next, previous) { if (previous === base) { next = rebindMatch(template, next, previous); if (next !== base) { this$1.base = base = next; } } else if (~(idx = members.indexOf(previous))) { next = rebindMatch(template.m[idx].n, next, previous); if (next !== members[idx]) { members.splice(idx, 1, next || Missing); } } if (next !== previous) { previous.unregister(proxy); if (next) { next.addShuffleTask(function () { return next.register(proxy); }); } } }, handleChange: function () { pathChanged(); } }); base.register(proxy); var members = (this.members = template.m.map(function (tpl) { if (isString(tpl)) { return { get: function () { return tpl; } }; } var model; if (tpl.t === REFERENCE) { model = resolveReference(fragment, tpl.n); model.register(proxy); return model; } model = new ExpressionProxy(fragment, tpl); model.register(proxy); return model; })); var pathChanged = function () { var model = base.joinAll( members.reduce(function (list, m) { var k = m.get(); if (isArray(k)) { return list.concat(k); } else { list.push(escapeKey(String(k))); } return list; }, []) ); if (model !== this$1.model) { this$1.model = model; this$1.relinking(model); fireShuffleTasks(); refreshPathDeps(this$1); } }; pathChanged(); }; ReferenceExpressionProxy__proto__.teardown = function teardown () { teardown$1(this); LinkModel.prototype.teardown.call(this); }; ReferenceExpressionProxy__proto__.unreference = function unreference () { LinkModel.prototype.unreference.call(this); if (!this.deps.length && !this.refs) { this.teardown(); } }; ReferenceExpressionProxy__proto__.unregister = function unregister (dep) { LinkModel.prototype.unregister.call(this, dep); if (!this.deps.length && !this.refs) { this.teardown(); } }; return ReferenceExpressionProxy; }(LinkModel)); function teardown$1(proxy) { if (proxy.base) { proxy.base.unregister(proxy.proxy); } if (proxy.models) { proxy.models.forEach(function (m) { if (m.unregister) { m.unregister(proxy); } }); } } function refreshPathDeps(proxy) { var len = proxy.deps.length; var i, v; for (i = 0; i < len; i++) { v = proxy.deps[i]; if (v.pathChanged) { v.pathChanged(); } if (v.fragment && v.fragment.pathModel) { v.fragment.pathModel.applyValue(proxy.getKeypath()); } } len = proxy.children.length; for (i = 0; i < len; i++) { refreshPathDeps(proxy.children[i]); } } var eproto = ExpressionProxy.prototype; var proto$1 = ReferenceExpressionProxy.prototype; proto$1.unreference = eproto.unreference; proto$1.unregister = eproto.unregister; proto$1.unregisterLink = eproto.unregisterLink; function resolve(fragment, template) { if (template.r) { return resolveReference(fragment, template.r); } else if (template.x) { return new ExpressionProxy(fragment, template.x); } else if (template.rx) { return new ReferenceExpressionProxy(fragment, template.rx); } } function resolveAliases(aliases, fragment, dest) { if ( dest === void 0 ) dest = {}; for (var i = 0; i < aliases.length; i++) { if (!dest[aliases[i].n]) { var m = resolve(fragment, aliases[i].x); dest[aliases[i].n] = m; m.reference(); } } return dest; } var Alias = (function (ContainerItem) { function Alias(options) { ContainerItem.call(this, options); this.fragment = null; } if ( ContainerItem ) Alias.__proto__ = ContainerItem; var Alias__proto__ = Alias.prototype = Object.create( ContainerItem && ContainerItem.prototype ); Alias__proto__.constructor = Alias; Alias__proto__.bind = function bind () { this.fragment = new Fragment({ owner: this, template: this.template.f }); this.fragment.aliases = resolveAliases(this.template.z, this.up); this.fragment.bind(); }; Alias__proto__.rebound = function rebound (update) { var aliases = this.fragment.aliases; for (var k in aliases) { if (aliases[k].rebound) { aliases[k].rebound(update); } else { aliases[k].unreference(); aliases[k] = 0; } } resolveAliases(this.template.z, this.up, aliases); if (this.fragment) { this.fragment.rebound(update); } }; Alias__proto__.render = function render (target, occupants) { this.rendered = true; if (this.fragment) { this.fragment.render(target, occupants); } }; Alias__proto__.unbind = function unbind (view) { var this$1 = this; for (var k in this$1.fragment.aliases) { this$1.fragment.aliases[k].unreference(); } this.fragment.aliases = {}; if (this.fragment) { this.fragment.unbind(view); } }; Alias__proto__.unrender = function unrender (shouldDestroy) { if (this.rendered && this.fragment) { this.fragment.unrender(shouldDestroy); } this.rendered = false; }; Alias__proto__.update = function update () { if (this.dirty) { this.dirty = false; this.fragment.update(); } }; return Alias; }(ContainerItem)); var space = /\s+/; function readStyle(css) { if (!isString(css)) { return {}; } return cleanCss(css, function (css, reconstruct) { return css .split(';') .filter(function (rule) { return !!rule.trim(); }) .map(reconstruct) .reduce(function (rules, rule) { var i = rule.indexOf(':'); var name = rule.substr(0, i).trim(); rules[name] = rule.substr(i + 1).trim(); return rules; }, {}); }); } function readClass(str) { var list = str.split(space); // remove any empty entries var i = list.length; while (i--) { if (!list[i]) { list.splice(i, 1); } } return list; } var textTypes = [ undefined, 'text', 'search', 'url', 'email', 'hidden', 'password', 'search', 'reset', 'submit' ]; function getUpdateDelegate(attribute) { var element = attribute.element; var name = attribute.name; if (name === 'value') { if (attribute.interpolator) { attribute.interpolator.bound = true; } // special case - selects if (element.name === 'select' && name === 'value') { return element.getAttribute('multiple') ? updateMultipleSelectValue : updateSelectValue; } if (element.name === 'textarea') { return updateStringValue; } // special case - contenteditable if (element.getAttribute('contenteditable') != null) { return updateContentEditableValue; } // special case - <input> if (element.name === 'input') { var type = element.getAttribute('type'); // type='file' value='{{fileList}}'> if (type === 'file') { return noop; } // read-only // type='radio' name='{{twoway}}' if (type === 'radio' && element.binding && element.binding.attribute.name === 'name') { return updateRadioValue; } if (~textTypes.indexOf(type)) { return updateStringValue; } } return updateValue; } var node = element.node; // special case - <input type='radio' name='{{twoway}}' value='foo'> if (attribute.isTwoway && name === 'name') { if (node.type === 'radio') { return updateRadioName; } if (node.type === 'checkbox') { return updateCheckboxName; } } if (name === 'style') { return updateStyleAttribute; } if (name.indexOf('style-') === 0) { return updateInlineStyle; } // special case - class names. IE fucks things up, again if (name === 'class' && (!node.namespaceURI || node.namespaceURI === html)) { return updateClassName; } if (name.indexOf('class-') === 0) { return updateInlineClass; } if (attribute.isBoolean) { var type$1 = element.getAttribute('type'); if (attribute.interpolator && name === 'checked' && (type$1 === 'checkbox' || type$1 === 'radio')) { attribute.interpolator.bound = true; } return updateBoolean; } if (attribute.namespace && attribute.namespace !== attribute.node.namespaceURI) { return updateNamespacedAttribute; } return updateAttribute; } function updateMultipleSelectValue(reset) { var value = this.getValue(); if (!isArray(value)) { value = [value]; } var options = this.node.options; var i = options.length; if (reset) { while (i--) { options[i].selected = false; } } else { while (i--) { var option = options[i]; var optionValue = option._ractive ? option._ractive.value : option.value; // options inserted via a triple don't have _ractive option.selected = arrayContains(value, optionValue); } } } function updateSelectValue(reset) { var value = this.getValue(); if (!this.locked) { // TODO is locked still a thing? this.node._ractive.value = value; var options = this.node.options; var i = options.length; var wasSelected = false; if (reset) { while (i--) { options[i].selected = false; } } else { while (i--) { var option = options[i]; var optionValue = option._ractive ? option._ractive.value : option.value; // options inserted via a triple don't have _ractive if (option.disabled && option.selected) { wasSelected = true; } if (optionValue == value) { // double equals as we may be comparing numbers with strings option.selected = true; return; } } } if (!wasSelected) { this.node.selectedIndex = -1; } } } function updateContentEditableValue(reset) { var value = this.getValue(); if (!this.locked) { if (reset) { this.node.innerHTML = ''; } else { this.node.innerHTML = value === undefined ? '' : value; } } } function updateRadioValue(reset) { var node = this.node; var wasChecked = node.checked; var value = this.getValue(); if (reset) { return (node.checked = false); } //node.value = this.element.getAttribute( 'value' ); node.value = this.node._ractive.value = value; node.checked = this.element.compare(value, this.element.getAttribute('name')); // This is a special case - if the input was checked, and the value // changed so that it's no longer checked, the twoway binding is // most likely out of date. To fix it we have to jump through some // hoops... this is a little kludgy but it works if (wasChecked && !node.checked && this.element.binding && this.element.binding.rendered) { this.element.binding.group.model.set(this.element.binding.group.getValue()); } } function updateValue(reset) { if (!this.locked) { if (reset) { this.node.removeAttribute('value'); this.node.value = this.node._ractive.value = null; } else { var value = this.getValue(); this.node.value = this.node._ractive.value = value; this.node.setAttribute('value', safeToStringValue(value)); } } } function updateStringValue(reset) { if (!this.locked) { if (reset) { this.node._ractive.value = ''; this.node.removeAttribute('value'); } else { var value = this.getValue(); this.node._ractive.value = value; var safeValue = safeToStringValue(value); // fixes #3281 – Safari moves caret position when setting an input value to the same value if (this.node.value !== safeValue) { this.node.value = safeValue; } this.node.setAttribute('value', safeValue); } } } function updateRadioName(reset) { if (reset) { this.node.checked = false; } else { this.node.checked = this.element.compare(this.getValue(), this.element.binding.getValue()); } } function updateCheckboxName(reset) { var ref = this; var element = ref.element; var node = ref.node; var binding = element.binding; var value = this.getValue(); var valueAttribute = element.getAttribute('value'); if (!isArray(value)) { binding.isChecked = node.checked = element.compare(value, valueAttribute); } else { var i = value.length; while (i--) { if (element.compare(valueAttribute, value[i])) { binding.isChecked = node.checked = true; return; } } binding.isChecked = node.checked = false; } } function updateStyleAttribute(reset) { var props = reset ? {} : readStyle(this.getValue() || ''); var style = this.node.style; var keys$$1 = keys(props); var prev = this.previous || []; var i = 0; while (i < keys$$1.length) { if (keys$$1[i] in style) { var safe = props[keys$$1[i]].replace('!important', ''); style.setProperty(keys$$1[i], safe, safe.length !== props[keys$$1[i]].length ? 'important' : ''); } i++; } // remove now-missing attrs i = prev.length; while (i--) { if (!~keys$$1.indexOf(prev[i]) && prev[i] in style) { style.setProperty(prev[i], '', ''); } } this.previous = keys$$1; } function updateInlineStyle(reset) { if (!this.style) { this.style = hyphenateCamel(this.name.substr(6)); } if (reset && this.node.style.getPropertyValue(this.style) !== this.last) { return; } var value = reset ? '' : safeToStringValue(this.getValue()); var safe = value.replace('!important', ''); this.node.style.setProperty(this.style, safe, safe.length !== value.length ? 'important' : ''); this.last = this.node.style.getPropertyValue(this.style); } function updateClassName(reset) { var value = reset ? [] : readClass(safeToStringValue(this.getValue())); // watch out for werdo svg elements var cls = this.node.className; cls = cls.baseVal !== undefined ? cls.baseVal : cls; var attr = readClass(cls); var prev = this.previous || []; var className = value.concat(attr.filter(function (c) { return !~prev.indexOf(c); })).join(' '); if (className !== cls) { if (!isString(this.node.className)) { this.node.className.baseVal = className; } else { this.node.className = className; } } this.previous = value; } function updateInlineClass(reset) { var name = this.name.substr(6); // watch out for werdo svg elements var cls = this.node.className; cls = cls.baseVal !== undefined ? cls.baseVal : cls; var attr = readClass(cls); var value = reset ? false : this.getValue(); if (!this.inlineClass) { this.inlineClass = name; } if (value && !~attr.indexOf(name)) { attr.push(name); } else if (!value && ~attr.indexOf(name)) { attr.splice(attr.indexOf(name), 1); } if (!isString(this.node.className)) { this.node.className.baseVal = attr.join(' '); } else { this.node.className = attr.join(' '); } } function updateBoolean(reset) { // with two-way binding, only update if the change wasn't initiated by the user // otherwise the cursor will often be sent to the wrong place if (!this.locked) { if (reset) { if (this.useProperty) { this.node[this.propertyName] = false; } this.node.removeAttribute(this.propertyName); } else { if (this.useProperty) { this.node[this.propertyName] = this.getValue(); } else { var val = this.getValue(); if (val) { this.node.setAttribute(this.propertyName, isString(val) ? val : ''); } else { this.node.removeAttribute(this.propertyName); } } } } } function updateAttribute(reset) { if (reset) { if (this.node.getAttribute(this.name) === this.value) { this.node.removeAttribute(this.name); } } else { this.value = safeToStringValue(this.getString()); this.node.setAttribute(this.name, this.value); } } function updateNamespacedAttribute(reset) { if (reset) { if ( this.value === this.node.getAttributeNS(this.namespace, this.name.slice(this.name.indexOf(':') + 1)) ) { this.node.removeAttributeNS(this.namespace, this.name.slice(this.name.indexOf(':') + 1)); } } else { this.value = safeToStringValue(this.getString()); this.node.setAttributeNS( this.namespace, this.name.slice(this.name.indexOf(':') + 1), this.value ); } } var propertyNames = { 'accept-charset': 'acceptCharset', accesskey: 'accessKey', bgcolor: 'bgColor', class: 'className', codebase: 'codeBase', colspan: 'colSpan', contenteditable: 'contentEditable', datetime: 'dateTime', dirname: 'dirName', for: 'htmlFor', 'http-equiv': 'httpEquiv', ismap: 'isMap', maxlength: 'maxLength', novalidate: 'noValidate', pubdate: 'pubDate', readonly: 'readOnly', rowspan: 'rowSpan', tabindex: 'tabIndex', usemap: 'useMap' }; var div$1 = doc ? createElement('div') : null; var attributes = false; function inAttributes() { return attributes; } var ConditionalAttribute = (function (Item) { function ConditionalAttribute(options) { Item.call(this, options); this.attributes = []; this.owner = options.owner; this.fragment = new Fragment({ ractive: this.ractive, owner: this, template: this.template }); // this fragment can't participate in node-y things this.fragment.findNextNode = noop; this.dirty = false; } if ( Item ) ConditionalAttribute.__proto__ = Item; var ConditionalAttribute__proto__ = ConditionalAttribute.prototype = Object.create( Item && Item.prototype ); ConditionalAttribute__proto__.constructor = ConditionalAttribute; ConditionalAttribute__proto__.bind = function bind () { this.fragment.bind(); }; ConditionalAttribute__proto__.bubble = function bubble () { if (!this.dirty) { this.dirty = true; this.owner.bubble(); } }; ConditionalAttribute__proto__.destroyed = function destroyed () { this.unrender(); }; ConditionalAttribute__proto__.render = function render () { this.node = this.owner.node; if (this.node) { this.isSvg = this.node.namespaceURI === svg$1; } attributes = true; if (!this.rendered) { this.fragment.render(); } this.rendered = true; this.dirty = true; // TODO this seems hacky, but necessary for tests to pass in browser AND node.js this.update(); attributes = false; }; ConditionalAttribute__proto__.toString = function toString () { return this.fragment.toString(); }; ConditionalAttribute__proto__.unbind = function unbind (view) { this.fragment.unbind(view); }; ConditionalAttribute__proto__.unrender = function unrender () { this.rendered = false; this.fragment.unrender(); }; ConditionalAttribute__proto__.update = function update () { var this$1 = this; var str; var attrs; if (this.dirty) { this.dirty = false; var current = attributes; attributes = true; this.fragment.update(); if (this.rendered && this.node) { str = this.fragment.toString(); attrs = parseAttributes(str, this.isSvg); // any attributes that previously existed but no longer do // must be removed this.attributes .filter(function (a) { return notIn(attrs, a); }) .forEach(function (a) { this$1.node.removeAttribute(a.name); }); attrs.forEach(function (a) { this$1.node.setAttribute(a.name, a.value); }); this.attributes = attrs; } attributes = current || false; } }; return ConditionalAttribute; }(Item)); var onlyWhitespace = /^\s*$/; function parseAttributes(str, isSvg) { if (onlyWhitespace.test(str)) { return []; } var tagName = isSvg ? 'svg' : 'div'; return str ? (div$1.innerHTML = "<" + tagName + " " + str + "></" + tagName + ">") && toArray(div$1.childNodes[0].attributes) : []; } function notIn(haystack, needle) { var i = haystack.length; while (i--) { if (haystack[i].name === needle.name) { return false; } } return true; } function lookupNamespace(node, prefix) { var qualified = "xmlns:" + prefix; while (node) { if (node.hasAttribute && node.hasAttribute(qualified)) { return node.getAttribute(qualified); } node = node.parentNode; } return namespaces[prefix]; } var attribute = false; function inAttribute() { return attribute; } var Attribute = (function (Item) { function Attribute(options) { Item.call(this, options); this.name = options.template.n; this.namespace = null; this.owner = options.owner || options.up.owner || options.element || findElement(options.up); this.element = options.element || (this.owner.attributeByName ? this.owner : findElement(options.up)); this.up = options.up; // shared this.ractive = this.up.ractive; this.rendered = false; this.updateDelegate = null; this.fragment = null; this.element.attributeByName[this.name] = this; if (!isArray(options.template.f)) { this.value = options.template.f; if (this.value === 0) { this.value = ''; } else if (this.value === undefined) { this.value = true; } return; } else { this.fragment = new Fragment({ owner: this, template: options.template.f }); } this.interpolator = this.fragment && this.fragment.items.length === 1 && this.fragment.items[0].type === INTERPOLATOR && this.fragment.items[0]; if (this.interpolator) { this.interpolator.owner = this; } } if ( Item ) Attribute.__proto__ = Item; var Attribute__proto__ = Attribute.prototype = Object.create( Item && Item.prototype ); Attribute__proto__.constructor = Attribute; Attribute__proto__.bind = function bind () { if (this.fragment) { this.fragment.bind(); } }; Attribute__proto__.bubble = function bubble () { if (!this.dirty) { this.up.bubble(); this.element.bubble(); this.dirty = true; } }; Attribute__proto__.firstNode = function firstNode () {}; Attribute__proto__.getString = function getString () { attribute = true; var value = this.fragment ? this.fragment.toString() : this.value != null ? '' + this.value : ''; attribute = false; return value; }; // TODO could getValue ever be called for a static attribute, // or can we assume that this.fragment exists? Attribute__proto__.getValue = function getValue () { attribute = true; var value = this.fragment ? this.fragment.valueOf() : booleanAttributes[this.name.toLowerCase()] ? true : this.value; attribute = false; return value; }; Attribute__proto__.render = function render () { var node = this.element.node; this.node = node; // should we use direct property access, or setAttribute? if (!node.namespaceURI || node.namespaceURI === namespaces.html) { this.propertyName = propertyNames[this.name] || this.name; if (node[this.propertyName] !== undefined) { this.useProperty = true; } // is attribute a boolean attribute or 'value'? If so we're better off doing e.g. // node.selected = true rather than node.setAttribute( 'selected', '' ) if (booleanAttributes[this.name.toLowerCase()] || this.isTwoway) { this.isBoolean = true; } if (this.propertyName === 'value') { node._ractive.value = this.value; } } if (node.namespaceURI) { var index = this.name.indexOf(':'); if (index !== -1) { this.namespace = lookupNamespace(node, this.name.slice(0, index)); } else { this.namespace = node.namespaceURI; } } this.rendered = true; this.updateDelegate = getUpdateDelegate(this); this.updateDelegate(); }; Attribute__proto__.toString = function toString () { if (inAttributes()) { return ''; } attribute = true; var value = this.getValue(); // Special case - select and textarea values (should not be stringified) if ( this.name === 'value' && (this.element.getAttribute('contenteditable') !== undefined || (this.element.name === 'select' || this.element.name === 'textarea')) ) { return; } // Special case – bound radio `name` attributes if ( this.name === 'name' && this.element.name === 'input' && this.interpolator && this.element.getAttribute('type') === 'radio' ) { return ("name=\"{{" + (this.interpolator.model.getKeypath()) + "}}\""); } // Special case - style and class attributes and directives if ( this.owner === this.element && (this.name === 'style' || this.name === 'class' || this.style || this.inlineClass) ) { return; } if ( !this.rendered && this.owner === this.element && (!this.name.indexOf('style-') || !this.name.indexOf('class-')) ) { if (!this.name.indexOf('style-')) { this.style = hyphenateCamel(this.name.substr(6)); } else { this.inlineClass = this.name.substr(6); } return; } if (booleanAttributes[this.name.toLowerCase()]) { return value ? isString(value) ? ((this.name) + "=\"" + (safeAttributeString(value)) + "\"") : this.name : ''; } if (value == null) { return ''; } var str = safeAttributeString(this.getString()); attribute = false; return str ? ((this.name) + "=\"" + str + "\"") : this.name; }; Attribute__proto__.unbind = function unbind (view) { if (this.fragment) { this.fragment.unbind(view); } }; Attribute__proto__.unrender = function unrender () { this.updateDelegate(true); this.rendered = false; }; Attribute__proto__.update = function update () { if (this.dirty) { var binding; this.dirty = false; if (this.fragment) { this.fragment.update(); } if (this.rendered) { this.updateDelegate(); } if (this.isTwoway && !this.locked) { this.interpolator.twowayBinding.lastVal(true, this.interpolator.model.get()); } else if (this.name === 'value' && (binding = this.element.binding)) { // special case: name bound element with dynamic value var attr = binding.attribute; if (attr && !attr.dirty && attr.rendered) { this.element.binding.attribute.updateDelegate(); } } } }; return Attribute; }(Item)); var BindingFlag = (function (Item) { function BindingFlag(options) { Item.call(this, options); this.owner = options.owner || options.up.owner || findElement(options.up); this.element = this.owner.attributeByName ? this.owner : findElement(options.up); this.flag = options.template.v === 'l' ? 'lazy' : 'twoway'; this.bubbler = this.owner === this.element ? this.element : this.up; if (this.element.type === ELEMENT) { if (isArray(options.template.f)) { this.fragment = new Fragment({ owner: this, template: options.template.f }); } this.interpolator = this.fragment && this.fragment.items.length === 1 && this.fragment.items[0].type === INTERPOLATOR && this.fragment.items[0]; } } if ( Item ) BindingFlag.__proto__ = Item; var BindingFlag__proto__ = BindingFlag.prototype = Object.create( Item && Item.prototype ); BindingFlag__proto__.constructor = BindingFlag; BindingFlag__proto__.bind = function bind () { if (this.fragment) { this.fragment.bind(); } set$1(this, this.getValue(), true); }; BindingFlag__proto__.bubble = function bubble () { if (!this.dirty) { this.bubbler.bubble(); this.dirty = true; } }; BindingFlag__proto__.getValue = function getValue () { if (this.fragment) { return this.fragment.valueOf(); } else if ('value' in this) { return this.value; } else if ('f' in this.template) { return this.template.f; } else { return true; } }; BindingFlag__proto__.render = function render () { set$1(this, this.getValue(), true); }; BindingFlag__proto__.toString = function toString () { return ''; }; BindingFlag__proto__.unbind = function unbind (view) { if (this.fragment) { this.fragment.unbind(view); } delete this.element[this.flag]; }; BindingFlag__proto__.unrender = function unrender () { if (this.element.rendered) { this.element.recreateTwowayBinding(); } }; BindingFlag__proto__.update = function update () { if (this.dirty) { this.dirty = false; if (this.fragment) { this.fragment.update(); } set$1(this, this.getValue(), true); } }; return BindingFlag; }(Item)); function set$1(flag, value, update) { if (value === 0) { flag.value = true; } else if (value === 'true') { flag.value = true; } else if (value === 'false' || value === '0') { flag.value = false; } else { flag.value = value; } var current = flag.element[flag.flag]; flag.element[flag.flag] = flag.value; if (update && !flag.element.attributes.binding && current !== flag.value) { flag.element.recreateTwowayBinding(); } return flag.value; } function Comment(options) { Item.call(this, options); } var proto$2 = create(Item.prototype); assign(proto$2, { bind: noop, unbind: noop, update: noop, detach: function detach() { return detachNode(this.node); }, firstNode: function firstNode() { return this.node; }, render: function render(target) { this.rendered = true; this.node = doc.createComment(this.template.c); target.appendChild(this.node); }, toString: function toString() { return ("<!-- " + (this.template.c) + " -->"); }, unrender: function unrender(shouldDestroy) { if (this.rendered && shouldDestroy) { this.detach(); } this.rendered = false; } }); Comment.prototype = proto$2; // Teardown. This goes through the root fragment and all its children, removing observers // and generally cleaning up after itself function Ractive$teardown() { var this$1 = this; if (this.torndown) { warnIfDebug('ractive.teardown() was called on a Ractive instance that was already torn down'); return Promise.resolve(); } this.shouldDestroy = true; return teardown$2(this, function () { return (this$1.fragment.rendered ? this$1.unrender() : Promise.resolve()); }); } function teardown$2(instance, getPromise) { instance.torndown = true; instance.fragment.unbind(); instance._observers.slice().forEach(cancel); if (instance.el && instance.el.__ractive_instances__) { removeFromArray(instance.el.__ractive_instances__, instance); } var promise = getPromise(); hooks.teardown.fire(instance); promise.then(function () { hooks.destruct.fire(instance); instance.viewmodel.teardown(); }); return promise; } var RactiveModel = (function (SharedModel) { function RactiveModel(ractive) { SharedModel.call(this, ractive, '@this'); this.ractive = ractive; } if ( SharedModel ) RactiveModel.__proto__ = SharedModel; var RactiveModel__proto__ = RactiveModel.prototype = Object.create( SharedModel && SharedModel.prototype ); RactiveModel__proto__.constructor = RactiveModel; RactiveModel__proto__.joinKey = function joinKey (key) { var model = SharedModel.prototype.joinKey.call(this, key); if ((key === 'root' || key === 'parent') && !model.isLink) { return initLink(model, key); } else if (key === 'data') { return this.ractive.viewmodel; } else if (key === 'cssData') { return this.ractive.constructor._cssModel; } return model; }; return RactiveModel; }(SharedModel)); function initLink(model, key) { model.applyValue = function(value) { this.parent.value[key] = value; if (value && value.viewmodel) { this.link(value.viewmodel.getRactiveModel(), key); this._link.markedAll(); } else { this.link(create(Missing), key); this._link.markedAll(); } }; if (key === 'root') { var mark = model.mark; model.mark = function(force) { if (this._marking) { return; } this._marking = true; mark.apply(this, force); this._marking = false; }; } model.applyValue(model.parent.ractive[key], key); model._link.set = function (v) { return model.applyValue(v); }; model._link.applyValue = function (v) { return model.applyValue(v); }; return model._link; } var specialModels = { '@this': function _this(root) { return root.getRactiveModel(); }, '@global': function _global() { return GlobalModel; }, '@shared': function _shared() { return SharedModel$1; }, '@style': function _style(root) { return root.getRactiveModel().joinKey('cssData'); }, '@helpers': function _helpers(root) { return root.getHelpers(); } }; specialModels['@'] = specialModels['@this']; var RootModel = (function (Model) { function RootModel(options) { Model.call(this, null, null); this.isRoot = true; this.root = this; this.ractive = options.ractive; // TODO sever this link this.value = options.data; this.adaptors = options.adapt; this.adapt(); } if ( Model ) RootModel.__proto__ = Model; var RootModel__proto__ = RootModel.prototype = Object.create( Model && Model.prototype ); RootModel__proto__.constructor = RootModel; RootModel__proto__.attached = function attached (fragment) { attachImplicits(this, fragment); }; RootModel__proto__.createLink = function createLink (keypath, target, targetPath, options) { var keys = splitKeypath(keypath); var model = this; while (keys.length) { var key = keys.shift(); model = model.childByKey[key] || model.joinKey(key); } return model.link(target, targetPath, options); }; RootModel__proto__.detached = function detached () { detachImplicits(this); }; RootModel__proto__.get = function get (shouldCapture, options) { if (shouldCapture) { capture(this); } if (!options || options.virtual !== false) { return this.getVirtual(); } else { return this.value; } }; RootModel__proto__.getHelpers = function getHelpers () { if (!this.helpers) { this.helpers = new SharedModel(this.ractive.helpers, 'helpers', this.ractive); } return this.helpers; }; RootModel__proto__.getKeypath = function getKeypath () { return ''; }; RootModel__proto__.getRactiveModel = function getRactiveModel () { return this.ractiveModel || (this.ractiveModel = new RactiveModel(this.ractive)); }; RootModel__proto__.getValueChildren = function getValueChildren () { var children = Model.prototype.getValueChildren.call(this, this.value); this.children.forEach(function (child) { if (child._link) { var idx = children.indexOf(child); if (~idx) { children.splice(idx, 1, child._link); } else { children.push(child._link); } } }); return children; }; RootModel__proto__.has = function has (key) { if (key[0] === '~' && key[1] === '/') { key = key.slice(2); } if (specialModels[key] || key === '') { return true; } if (Model.prototype.has.call(this, key)) { return true; } else { var unescapedKey = unescapeKey(key); // mappings/links and computations if (this.childByKey[unescapedKey] && this.childByKey[unescapedKey]._link) { return true; } } }; RootModel__proto__.joinKey = function joinKey (key, opts) { if (key[0] === '~' && key[1] === '/') { key = key.slice(2); } if (key[0] === '@') { var fn = specialModels[key]; if (fn) { return fn(this); } } else { return Model.prototype.joinKey.call(this, key, opts); } }; RootModel__proto__.set = function set (value) { // TODO wrapping root node is a baaaad idea. We should prevent this var wrapper = this.wrapper; if (wrapper) { var shouldTeardown = !wrapper.reset || wrapper.reset(value) === false; if (shouldTeardown) { wrapper.teardown(); this.wrapper = null; this.value = value; this.adapt(); } } else { this.value = value; this.adapt(); } this.deps.forEach(handleChange); this.children.forEach(mark); }; RootModel__proto__.retrieve = function retrieve () { return this.wrapper ? this.wrapper.get() : this.value; }; RootModel__proto__.teardown = function teardown () { Model.prototype.teardown.call(this); this.ractiveModel && this.ractiveModel.teardown(); }; return RootModel; }(Model)); RootModel.prototype.update = noop; function attachImplicits(model, fragment) { if (model._link && model._link.implicit && model._link.isDetached()) { model.attach(fragment); } // look for virtual children to relink and cascade for (var k in model.childByKey) { if (model.value) { if (k in model.value) { attachImplicits(model.childByKey[k], fragment); } else if (!model.childByKey[k]._link || model.childByKey[k]._link.isDetached()) { var mdl = resolveReference(fragment, k); if (mdl) { model.childByKey[k].link(mdl, k, { implicit: true }); } } } } } function detachImplicits(model) { if (model._link && model._link.implicit) { model.unlink(); } for (var k in model.childByKey) { detachImplicits(model.childByKey[k]); } } function subscribe(instance, options, type) { var subs = (instance.constructor[("_" + type)] || []).concat(toPairs(options[type] || [])); var single = type === 'on' ? 'once' : (type + "Once"); subs.forEach(function (ref) { var target = ref[0]; var config = ref[1]; if (isFunction(config)) { instance[type](target, config); } else if (isObjectType(config) && isFunction(config.handler)) { instance[config.once ? single : type](target, config.handler, create(config)); } }); } var registryNames$1 = [ 'adaptors', 'components', 'decorators', 'easing', 'events', 'interpolators', 'partials', 'transitions' ]; var protoRegistries = ['computed', 'helpers']; var uid = 0; function construct(ractive, options) { if (Ractive.DEBUG) { welcome(); } initialiseProperties(ractive); handleAttributes(ractive); // set up event subscribers subscribe(ractive, options, 'on'); // if there's not a delegation setting, inherit from parent if it's not default if ( !hasOwn(options, 'delegate') && ractive.parent && ractive.parent.delegate !== ractive.delegate ) { ractive.delegate = false; } // plugins that need to run at construct if (isArray(options.use)) { ractive.use.apply(ractive, options.use.filter(function (p) { return p.construct; })); } hooks.construct.fire(ractive, options); if (options.onconstruct) { options.onconstruct.call(ractive, getRactiveContext(ractive), options); } // Add registries var i = registryNames$1.length; while (i--) { var name = registryNames$1[i]; ractive[name] = assign(create(ractive.constructor[name] || null), options[name]); } i = protoRegistries.length; while (i--) { var name$1 = protoRegistries[i]; ractive[name$1] = assign(create(ractive.constructor.prototype[name$1]), options[name$1]); } if (ractive._attributePartial) { ractive.partials['extra-attributes'] = ractive._attributePartial; delete ractive._attributePartial; } // Create a viewmodel var viewmodel = new RootModel({ adapt: getAdaptors(ractive, ractive.adapt, options), data: dataConfigurator.init(ractive.constructor, ractive, options), ractive: ractive }); // once resolved, share the adaptors array between the root model and instance ractive.adapt = viewmodel.adaptors; ractive.viewmodel = viewmodel; for (var k in ractive.computed) { compute.call(ractive, k, ractive.computed[k]); } } function getAdaptors(ractive, protoAdapt, options) { protoAdapt = protoAdapt.map(lookup); var adapt = ensureArray(options.adapt).map(lookup); var srcs = [protoAdapt, adapt]; if (ractive.parent && !ractive.isolated) { srcs.push(ractive.parent.viewmodel.adaptors); } return combine.apply(null, srcs); function lookup(adaptor) { if (isString(adaptor)) { adaptor = findInViewHierarchy('adaptors', ractive, adaptor); if (!adaptor) { fatal(missingPlugin(adaptor, 'adaptor')); } } return adaptor; } } function initialiseProperties(ractive) { // Generate a unique identifier, for places where you'd use a weak map if it // existed ractive._guid = 'r-' + uid++; // events ractive._subs = create(null); ractive._nsSubs = 0; // storage for item configuration from instantiation to reset, // like dynamic functions or original values ractive._config = {}; // events ractive.event = null; ractive._eventQueue = []; // observers ractive._observers = []; // external children ractive._children = []; ractive._children.byName = {}; ractive.children = ractive._children; if (!ractive.component) { ractive.root = ractive; ractive.parent = ractive.container = null; // TODO container still applicable? } } function handleAttributes(ractive) { var component = ractive.component; var attributes = ractive.constructor.attributes; if (attributes && component) { var tpl = component.template; var attrs = tpl.m ? tpl.m.slice() : []; // grab all of the passed attribute names var props = attrs.filter(function (a) { return a.t === ATTRIBUTE; }).map(function (a) { return a.n; }); // warn about missing requireds attributes.required.forEach(function (p) { if (!~props.indexOf(p)) { warnIfDebug(("Component '" + (component.name) + "' requires attribute '" + p + "' to be provided")); } }); // set up a partial containing non-property attributes var all = attributes.optional.concat(attributes.required); var partial = []; var i = attrs.length; while (i--) { var a = attrs[i]; if (a.t === ATTRIBUTE && !~all.indexOf(a.n)) { if (attributes.mapAll) { // map the attribute if requested and make the extra attribute in the partial refer to the mapping partial.unshift({ t: ATTRIBUTE, n: a.n, f: [{ t: INTERPOLATOR, r: ("~/" + (a.n)) }] }); } else { // transfer the attribute to the extra attributes partal partial.unshift(attrs.splice(i, 1)[0]); } } else if ( !attributes.mapAll && (a.t === DECORATOR || a.t === TRANSITION || a.t === BINDING_FLAG) ) { partial.unshift(attrs.splice(i, 1)[0]); } } if (partial.length) { component.template = { t: tpl.t, e: tpl.e, f: tpl.f, m: attrs, p: tpl.p }; } ractive._attributePartial = partial; } } var Component = (function (Item) { function Component(options, ComponentConstructor) { var this$1 = this; Item.call(this, options); var template = options.template; this.isAnchor = template.t === ANCHOR; this.type = this.isAnchor ? ANCHOR : COMPONENT; // override ELEMENT from super var attrs = template.m; var partials = template.p || {}; if (!('content' in partials)) { partials.content = template.f || []; } this._partials = partials; // TEMP if (this.isAnchor) { this.name = template.n; this.addChild = addChild; this.removeChild = removeChild; } else { var instance = create(ComponentConstructor.prototype); this.instance = instance; this.name = template.e; if (instance.el || instance.target) { warnIfDebug( ("The <" + (this.name) + "> component has a default '" + (instance.el ? 'el' : 'target') + "' property; it has been disregarded") ); instance.el = instance.target = null; } // find container var fragment = options.up; var container; while (fragment) { if (fragment.owner.type === YIELDER) { container = fragment.owner.container; break; } fragment = fragment.parent; } // add component-instance-specific properties instance.parent = this.up.ractive; instance.container = container || null; instance.root = instance.parent.root; instance.component = this; construct(this.instance, { partials: partials }); // these can be modified during construction template = this.template; attrs = template.m; // allow components that are so inclined to add programmatic mappings if (isArray(this.mappings)) { attrs = (attrs || []).concat(this.mappings); } else if (isString(this.mappings)) { attrs = (attrs || []).concat(parser.parse(this.mappings, { attributes: true }).t); } // for hackability, this could be an open option // for any ractive instance, but for now, just // for components and just for ractive... instance._inlinePartials = partials; } this.attributeByName = {}; this.attributes = []; if (attrs) { var leftovers = []; attrs.forEach(function (template) { switch (template.t) { case ATTRIBUTE: case EVENT: this$1.attributes.push( createItem({ owner: this$1, up: this$1.up, template: template }) ); break; case TRANSITION: case BINDING_FLAG: case DECORATOR: break; default: leftovers.push(template); break; } }); if (leftovers.length) { this.attributes.push( new ConditionalAttribute({ owner: this, up: this.up, template: leftovers }) ); } } this.eventHandlers = []; } if ( Item ) Component.__proto__ = Item; var Component__proto__ = Component.prototype = Object.create( Item && Item.prototype ); Component__proto__.constructor = Component; Component__proto__.bind = function bind () { if (!this.isAnchor) { this.attributes.forEach(bind$1); this.eventHandlers.forEach(bind$1); initialise( this.instance, { partials: this._partials }, { cssIds: this.up.cssIds } ); if (this.instance.target || this.instance.el) { this.extern = true; } this.bound = true; } }; Component__proto__.bubble = function bubble () { if (!this.dirty) { this.dirty = true; this.up.bubble(); } }; Component__proto__.destroyed = function destroyed () { if (!this.isAnchor && this.instance.fragment) { this.instance.fragment.destroyed(); } }; Component__proto__.detach = function detach () { if (this.isAnchor) { if (this.instance) { return this.instance.fragment.detach(); } return createDocumentFragment(); } return this.instance.fragment.detach(); }; Component__proto__.find = function find (selector, options) { if (this.instance) { return this.instance.fragment.find(selector, options); } }; Component__proto__.findAll = function findAll (selector, options) { if (this.instance) { this.instance.fragment.findAll(selector, options); } }; Component__proto__.findComponent = function findComponent (name, options) { if (!name || this.name === name) { return this.instance; } if (this.instance.fragment) { return this.instance.fragment.findComponent(name, options); } }; Component__proto__.findAllComponents = function findAllComponents (name, options) { var result = options.result; if (this.instance && (!name || this.name === name)) { result.push(this.instance); } if (this.instance) { this.instance.findAllComponents(name, options); } }; Component__proto__.firstNode = function firstNode (skipParent) { if (this.instance) { return this.instance.fragment.firstNode(skipParent); } }; Component__proto__.getContext = function getContext () { var assigns = [], len = arguments.length; while ( len-- ) assigns[ len ] = arguments[ len ]; assigns.unshift(this.instance); return getRactiveContext.apply(null, assigns); }; Component__proto__.rebound = function rebound (update$$1) { this.attributes.forEach(function (x) { return x.rebound(update$$1); }); }; Component__proto__.render = function render$2 (target, occupants) { if (this.isAnchor) { this.rendered = true; this.target = target; if (!checking.length) { checking.push(this.ractive); if (occupants) { this.occupants = occupants; checkAnchors(); this.occupants = null; } else { runloop.scheduleTask(checkAnchors, true); } } } else { this.attributes.forEach(render); this.eventHandlers.forEach(render); if (this.extern) { this.instance.delegate = false; this.instance.render(); } else { render$1(this.instance, target, null, occupants); } this.rendered = true; } }; Component__proto__.shuffled = function shuffled () { Item.prototype.shuffled.call(this); this.instance && !this.instance.isolated && this.instance.fragment && this.instance.fragment.shuffled(); }; Component__proto__.toString = function toString () { if (this.instance) { return this.instance.toHTML(); } }; Component__proto__.unbind = function unbind$1 (view) { if (!this.isAnchor) { this.bound = false; this.attributes.forEach(unbind); if (view) { this.instance.fragment.unbind(); } else { teardown$2(this.instance, function () { return runloop.promise(); }); } } }; Component__proto__.unrender = function unrender$1 (shouldDestroy) { this.shouldDestroy = shouldDestroy; if (this.isAnchor) { if (this.item) { unrenderItem(this, this.item); } this.target = null; if (!checking.length) { checking.push(this.ractive); runloop.scheduleTask(checkAnchors, true); } } else { this.instance.unrender(); this.instance.el = this.instance.target = null; this.attributes.forEach(unrender); this.eventHandlers.forEach(unrender); } this.rendered = false; }; Component__proto__.update = function update$2 () { this.dirty = false; if (this.instance) { this.instance.fragment.update(); this.attributes.forEach(update); this.eventHandlers.forEach(update); } }; return Component; }(Item)); function addChild(meta) { if (this.item) { this.removeChild(this.item); } var child = meta.instance; meta.anchor = this; meta.up = this.up; meta.name = meta.nameOption || this.name; this.name = meta.name; if (!child.isolated) { child.viewmodel.attached(this.up); } // render as necessary if (this.rendered) { renderItem(this, meta); } } function removeChild(meta) { // unrender as necessary if (this.item === meta) { unrenderItem(this, meta); this.name = this.template.n; } } function renderItem(anchor, meta) { if (!anchor.rendered) { return; } meta.shouldDestroy = false; meta.up = anchor.up; anchor.item = meta; anchor.instance = meta.instance; var nextNode = anchor.up.findNextNode(anchor); if (meta.instance.fragment.rendered) { meta.instance.unrender(); } meta.partials = meta.instance.partials; meta.instance.partials = assign(create(meta.partials), meta.partials, anchor._partials); meta.instance.fragment.unbind(true); meta.instance.fragment.componentParent = anchor.up; meta.instance.fragment.bind(meta.instance.viewmodel); anchor.attributes.forEach(bind$1); anchor.eventHandlers.forEach(bind$1); anchor.attributes.forEach(render); anchor.eventHandlers.forEach(render); var target = anchor.up.findParentNode(); render$1(meta.instance, target, target.contains(nextNode) ? nextNode : null, anchor.occupants); if (meta.lastBound !== anchor) { meta.lastBound = anchor; } } function unrenderItem(anchor, meta) { if (!anchor.rendered) { return; } meta.shouldDestroy = true; meta.instance.unrender(); anchor.eventHandlers.forEach(unrender); anchor.attributes.forEach(unrender); anchor.eventHandlers.forEach(unbind); anchor.attributes.forEach(unbind); meta.instance.el = meta.instance.anchor = null; meta.instance.fragment.componentParent = null; meta.up = null; meta.anchor = null; anchor.item = null; anchor.instance = null; } var checking = []; function checkAnchors() { var list = checking; checking = []; list.forEach(updateAnchors); } function setupArgsFn(item, template, fragment, opts) { if ( opts === void 0 ) opts = {}; if (template && template.f && template.f.s) { item.fn = getFunction(template.f.s, template.f.r.length); if (opts.register === true) { item.models = resolveArgs(item, template, fragment, opts); } } } function resolveArgs(item, template, fragment, opts) { if ( opts === void 0 ) opts = {}; return template.f.r.map(function (ref, i) { var model; if (opts.specialRef && (model = opts.specialRef(ref, i))) { return model; } model = resolveReference(fragment, ref); if (opts.register === true) { model.register(item); } return model; }); } function teardownArgsFn(item, template) { if (template && template.f && template.f.s) { if (item.models) { item.models.forEach(function (m) { if (m && m.unregister) { m.unregister(item); } }); } item.models = null; } } var missingDecorator = { update: noop, teardown: noop }; var Decorator = function Decorator(options) { this.owner = options.owner || options.up.owner || findElement(options.up); this.element = this.owner.attributeByName ? this.owner : findElement(options.up); this.up = options.up || this.owner.up; this.ractive = this.owner.ractive; var template = (this.template = options.template); this.name = template.n; this.node = null; this.handle = null; this.element.decorators.push(this); }; var Decorator__proto__ = Decorator.prototype; Decorator__proto__.bind = function bind () { // if the owner is the elment, make sure the context includes the element var frag = this.element === this.owner ? new Fragment({ owner: this.owner }) : this.up; setupArgsFn(this, this.template, frag, { register: true }); }; Decorator__proto__.bubble = function bubble () { if (!this.dirty) { this.dirty = true; // decorators may be owned directly by an element or by a fragment if conditional this.owner.bubble(); this.up.bubble(); } }; Decorator__proto__.destroyed = function destroyed () { if (this.handle) { this.handle.teardown(); this.handle = null; } this.shouldDestroy = true; }; Decorator__proto__.handleChange = function handleChange () { this.bubble(); }; Decorator__proto__.rebind = function rebind (next, previous, safe) { var idx = this.models.indexOf(previous); if (!~idx) { return; } next = rebindMatch(this.template.f.r[idx], next, previous); if (next === previous) { return; } previous.unregister(this); this.models.splice(idx, 1, next); if (next) { next.addShuffleRegister(this, 'mark'); } if (!safe) { this.bubble(); } }; Decorator__proto__.rebound = function rebound (update) { teardownArgsFn(this, this.template); setupArgsFn(this, this.template, this.up, { register: true }); if (update) { this.bubble(); } }; Decorator__proto__.render = function render () { var this$1 = this; this.shouldDestroy = false; if (this.handle) { this.unrender(); } runloop.scheduleTask(function () { // bail if the host element has managed to become unrendered if (!this$1.element.rendered) { return; } var fn = findInViewHierarchy('decorators', this$1.ractive, this$1.name); if (!fn) { warnOnce(missingPlugin(this$1.name, 'decorator')); this$1.handle = missingDecorator; return; } this$1.node = this$1.element.node; var args; if (this$1.fn) { args = this$1.models.map(function (model) { if (!model) { return undefined; } return model.get(); }); args = this$1.fn.apply(this$1.ractive, args); } this$1.handle = fn.apply(this$1.ractive, [this$1.node].concat(args)); if (!this$1.handle || !this$1.handle.teardown) { throw new Error( ("The '" + (this$1.name) + "' decorator must return an object with a teardown method") ); } // watch out for decorators that cause their host element to be unrendered if (this$1.shouldDestroy) { this$1.destroyed(); } }, true); }; Decorator__proto__.toString = function toString () { return ''; }; Decorator__proto__.unbind = function unbind () { teardownArgsFn(this, this.template); }; Decorator__proto__.unrender = function unrender (shouldDestroy) { if ((!shouldDestroy || this.element.rendered) && this.handle) { this.handle.teardown(); this.handle = null; } }; Decorator__proto__.update = function update () { var instance = this.handle; if (!this.dirty) { if (instance && instance.invalidate) { runloop.scheduleTask(function () { return instance.invalidate(); }, true); } return; } this.dirty = false; if (instance) { if (!instance.update) { this.unrender(); this.render(); } else { var args = this.models.map(function (model) { return model && model.get(); }); instance.update.apply(this.ractive, this.fn.apply(this.ractive, args)); } } }; Decorator.prototype.firstNode = noop; var Doctype = (function (Item) { function Doctype () { Item.apply(this, arguments); } if ( Item ) Doctype.__proto__ = Item; var Doctype__proto__ = Doctype.prototype = Object.create( Item && Item.prototype ); Doctype__proto__.constructor = Doctype; Doctype__proto__.toString = function toString () { return '<!DOCTYPE' + this.template.a + '>'; }; return Doctype; }(Item)); var proto$3 = Doctype.prototype; proto$3.bind = proto$3.render = proto$3.teardown = proto$3.unbind = proto$3.unrender = proto$3.update = noop; var Binding = function Binding(element, name) { if ( name === void 0 ) name = 'value'; this.element = element; this.ractive = element.ractive; this.attribute = element.attributeByName[name]; var interpolator = this.attribute.interpolator; interpolator.twowayBinding = this; var model = interpolator.model; if (model.isReadonly && !model.setRoot) { var keypath = model.getKeypath().replace(/^@/, ''); warnOnceIfDebug( ("Cannot use two-way binding on <" + (element.name) + "> element: " + keypath + " is read-only. To suppress this warning use <" + (element.name) + " twoway='false'...>"), { ractive: this.ractive } ); return false; } this.attribute.isTwoway = true; this.model = model; // initialise value, if it's undefined var value = model.get(); this.wasUndefined = value === undefined; if (value === undefined && this.getInitialValue) { value = this.getInitialValue(); model.set(value); } this.lastVal(true, value); var parentForm = findElement(this.element, false, 'form'); if (parentForm) { this.resetValue = value; parentForm.formBindings.push(this); } }; var Binding__proto__ = Binding.prototype; Binding__proto__.bind = function bind () { this.model.registerTwowayBinding(this); }; Binding__proto__.handleChange = function handleChange () { var this$1 = this; var value = this.getValue(); if (this.lastVal() === value) { return; } runloop.start(); this.attribute.locked = true; this.model.set(value); this.lastVal(true, value); // if the value changes before observers fire, unlock to be updatable cause something weird and potentially freezy is up if (this.model.get() !== value) { this.attribute.locked = false; } else { runloop.scheduleTask(function () { return (this$1.attribute.locked = false); }); } runloop.end(); }; Binding__proto__.lastVal = function lastVal (setting, value) { if (setting) { this.lastValue = value; } else { return this.lastValue; } }; Binding__proto__.rebind = function rebind (next, previous) { var this$1 = this; if (this.model && this.model === previous) { previous.unregisterTwowayBinding(this); } if (next) { this.model = next; runloop.scheduleTask(function () { return next.registerTwowayBinding(this$1); }); } }; Binding__proto__.rebound = function rebound () { if (this.model) { this.model.unregisterTwowayBinding(this); } this.model = this.attribute.interpolator.model; this.model.registerTwowayBinding(this); }; Binding__proto__.render = function render () { this.node = this.element.node; this.node._ractive.binding = this; this.rendered = true; // TODO is this used anywhere? }; Binding__proto__.setFromNode = function setFromNode (node) { this.model.set(node.value); }; Binding__proto__.unbind = function unbind () { this.model.unregisterTwowayBinding(this); }; Binding.prototype.unrender = noop; // This is the handler for DOM events that would lead to a change in the model // (i.e. change, sometimes, input, and occasionally click and keyup) function handleDomEvent() { this._ractive.binding.handleChange(); } var CheckboxBinding = (function (Binding) { function CheckboxBinding(element) { Binding.call(this, element, 'checked'); } if ( Binding ) CheckboxBinding.__proto__ = Binding; var CheckboxBinding__proto__ = CheckboxBinding.prototype = Object.create( Binding && Binding.prototype ); CheckboxBinding__proto__.constructor = CheckboxBinding; CheckboxBinding__proto__.render = function render () { Binding.prototype.render.call(this); this.element.on('change', handleDomEvent); if (this.node.attachEvent) { this.element.on('click', handleDomEvent); } }; CheckboxBinding__proto__.unrender = function unrender () { this.element.off('change', handleDomEvent); this.element.off('click', handleDomEvent); }; CheckboxBinding__proto__.getInitialValue = function getInitialValue () { return !!this.element.getAttribute('checked'); }; CheckboxBinding__proto__.getValue = function getValue () { return this.node.checked; }; CheckboxBinding__proto__.setFromNode = function setFromNode (node) { this.model.set(node.checked); }; return CheckboxBinding; }(Binding)); function getBindingGroup(group, model, getValue) { var hash = group + "-bindingGroup"; return model[hash] || (model[hash] = new BindingGroup(hash, model, getValue)); } var BindingGroup = function BindingGroup(hash, model, getValue) { var this$1 = this; this.model = model; this.hash = hash; this.getValue = function () { this$1.value = getValue.call(this$1); return this$1.value; }; this.bindings = []; }; var BindingGroup__proto__ = BindingGroup.prototype; BindingGroup__proto__.add = function add (binding) { this.bindings.push(binding); }; BindingGroup__proto__.bind = function bind () { this.value = this.model.get(); this.model.registerTwowayBinding(this); this.bound = true; }; BindingGroup__proto__.remove = function remove (binding) { removeFromArray(this.bindings, binding); if (!this.bindings.length) { this.unbind(); } }; BindingGroup__proto__.unbind = function unbind () { this.model.unregisterTwowayBinding(this); this.bound = false; delete this.model[this.hash]; }; BindingGroup.prototype.rebind = Binding.prototype.rebind; var push$1 = [].push; function getValue() { var this$1 = this; var all = this.bindings .filter(function (b) { return b.node && b.node.checked; }) .map(function (b) { return b.element.getAttribute('value'); }); var res = []; all.forEach(function (v) { if (!this$1.bindings[0].arrayContains(res, v)) { res.push(v); } }); return res; } var CheckboxNameBinding = (function (Binding) { function CheckboxNameBinding(element) { Binding.call(this, element, 'name'); this.checkboxName = true; // so that ractive.updateModel() knows what to do with this // Each input has a reference to an array containing it and its // group, as two-way binding depends on being able to ascertain // the status of all inputs within the group this.group = getBindingGroup('checkboxes', this.model, getValue); this.group.add(this); if (this.noInitialValue) { this.group.noInitialValue = true; } // If no initial value was set, and this input is checked, we // update the model if (this.group.noInitialValue && this.element.getAttribute('checked')) { var existingValue = this.model.get(); var bindingValue = this.element.getAttribute('value'); if (!this.arrayContains(existingValue, bindingValue)) { push$1.call(existingValue, bindingValue); // to avoid triggering runloop with array adaptor } } } if ( Binding ) CheckboxNameBinding.__proto__ = Binding; var CheckboxNameBinding__proto__ = CheckboxNameBinding.prototype = Object.create( Binding && Binding.prototype ); CheckboxNameBinding__proto__.constructor = CheckboxNameBinding; CheckboxNameBinding__proto__.bind = function bind () { if (!this.group.bound) { this.group.bind(); } }; CheckboxNameBinding__proto__.getInitialValue = function getInitialValue () { // This only gets called once per group (of inputs that // share a name), because it only gets called if there // isn't an initial value. By the same token, we can make // a note of that fact that there was no initial value, // and populate it using any `checked` attributes that // exist (which users should avoid, but which we should // support anyway to avoid breaking expectations) this.noInitialValue = true; // TODO are noInitialValue and wasUndefined the same thing? return []; }; CheckboxNameBinding__proto__.getValue = function getValue () { return this.group.value; }; CheckboxNameBinding__proto__.handleChange = function handleChange () { this.isChecked = this.element.node.checked; this.group.value = this.model.get(); var value = this.element.getAttribute('value'); if (this.isChecked && !this.arrayContains(this.group.value, value)) { this.group.value.push(value); } else if (!this.isChecked && this.arrayContains(this.group.value, value)) { this.removeFromArray(this.group.value, value); } // make sure super knows there's a change this.lastValue = null; Binding.prototype.handleChange.call(this); }; CheckboxNameBinding__proto__.render = function render () { Binding.prototype.render.call(this); var node = this.node; var existingValue = this.model.get(); var bindingValue = this.element.getAttribute('value'); if (isArray(existingValue)) { this.isChecked = this.arrayContains(existingValue, bindingValue); } else { this.isChecked = this.element.compare(existingValue, bindingValue); } node.name = '{{' + this.model.getKeypath() + '}}'; node.checked = this.isChecked; this.element.on('change', handleDomEvent); // in case of IE emergency, bind to click event as well if (this.node.attachEvent) { this.element.on('click', handleDomEvent); } }; CheckboxNameBinding__proto__.setFromNode = function setFromNode (node) { this.group.bindings.forEach(function (binding) { return (binding.wasUndefined = true); }); if (node.checked) { var valueSoFar = this.group.getValue(); valueSoFar.push(this.element.getAttribute('value')); this.group.model.set(valueSoFar); } }; CheckboxNameBinding__proto__.unbind = function unbind () { this.group.remove(this); }; CheckboxNameBinding__proto__.unrender = function unrender () { var el = this.element; el.off('change', handleDomEvent); el.off('click', handleDomEvent); }; CheckboxNameBinding__proto__.arrayContains = function arrayContains (selectValue, optionValue) { var this$1 = this; var i = selectValue.length; while (i--) { if (this$1.element.compare(optionValue, selectValue[i])) { return true; } } return false; }; CheckboxNameBinding__proto__.removeFromArray = function removeFromArray (array, item) { var this$1 = this; if (!array) { return; } var i = array.length; while (i--) { if (this$1.element.compare(item, array[i])) { array.splice(i, 1); } } }; return CheckboxNameBinding; }(Binding)); var ContentEditableBinding = (function (Binding) { function ContentEditableBinding () { Binding.apply(this, arguments); } if ( Binding ) ContentEditableBinding.__proto__ = Binding; var ContentEditableBinding__proto__ = ContentEditableBinding.prototype = Object.create( Binding && Binding.prototype ); ContentEditableBinding__proto__.constructor = ContentEditableBinding; ContentEditableBinding__proto__.getInitialValue = function getInitialValue () { return this.element.fragment ? this.element.fragment.toString() : ''; }; ContentEditableBinding__proto__.getValue = function getValue () { return this.element.node.innerHTML; }; ContentEditableBinding__proto__.render = function render () { Binding.prototype.render.call(this); var el = this.element; el.on('change', handleDomEvent); el.on('blur', handleDomEvent); if (!this.ractive.lazy) { el.on('input', handleDomEvent); if (this.node.attachEvent) { el.on('keyup', handleDomEvent); } } }; ContentEditableBinding__proto__.setFromNode = function setFromNode (node) { this.model.set(node.innerHTML); }; ContentEditableBinding__proto__.unrender = function unrender () { var el = this.element; el.off('blur', handleDomEvent); el.off('change', handleDomEvent); el.off('input', handleDomEvent); el.off('keyup', handleDomEvent); }; return ContentEditableBinding; }(Binding)); function handleBlur() { handleDomEvent.call(this); var value = this._ractive.binding.model.get(); this.value = value == undefined ? '' : value; } function handleDelay(delay) { var timeout; return function() { var this$1 = this; if (timeout) { clearTimeout(timeout); } timeout = setTimeout(function () { var binding = this$1._ractive.binding; if (binding.rendered) { handleDomEvent.call(this$1); } timeout = null; }, delay); }; } var GenericBinding = (function (Binding) { function GenericBinding () { Binding.apply(this, arguments); } if ( Binding ) GenericBinding.__proto__ = Binding; var GenericBinding__proto__ = GenericBinding.prototype = Object.create( Binding && Binding.prototype ); GenericBinding__proto__.constructor = GenericBinding; GenericBinding__proto__.getInitialValue = function getInitialValue () { return ''; }; GenericBinding__proto__.getValue = function getValue () { return this.node.value; }; GenericBinding__proto__.render = function render () { Binding.prototype.render.call(this); // any lazy setting for this element overrides the root // if the value is a number, it's a timeout var lazy = this.ractive.lazy; var timeout = false; var el = this.element; if ('lazy' in this.element) { lazy = this.element.lazy; } if (isNumeric(lazy)) { timeout = +lazy; lazy = false; } this.handler = timeout ? handleDelay(timeout) : handleDomEvent; var node = this.node; el.on('change', handleDomEvent); if (node.type !== 'file') { if (!lazy) { el.on('input', this.handler); // IE is a special snowflake if (node.attachEvent) { el.on('keyup', this.handler); } } el.on('blur', handleBlur); } }; GenericBinding__proto__.unrender = function unrender () { var el = this.element; this.rendered = false; el.off('change', handleDomEvent); el.off('input', this.handler); el.off('keyup', this.handler); el.off('blur', handleBlur); }; return GenericBinding; }(Binding)); var FileBinding = (function (GenericBinding) { function FileBinding () { GenericBinding.apply(this, arguments); } if ( GenericBinding ) FileBinding.__proto__ = GenericBinding; var FileBinding__proto__ = FileBinding.prototype = Object.create( GenericBinding && GenericBinding.prototype ); FileBinding__proto__.constructor = FileBinding; FileBinding__proto__.getInitialValue = function getInitialValue () { /* istanbul ignore next */ return undefined; }; FileBinding__proto__.getValue = function getValue () { /* istanbul ignore next */ return this.node.files; }; FileBinding__proto__.render = function render () { /* istanbul ignore next */ this.element.lazy = false; /* istanbul ignore next */ GenericBinding.prototype.render.call(this); }; FileBinding__proto__.setFromNode = function setFromNode (node) { /* istanbul ignore next */ this.model.set(node.files); }; return FileBinding; }(GenericBinding)); function getSelectedOptions(select) { /* istanbul ignore next */ return select.selectedOptions ? toArray(select.selectedOptions) : select.options ? toArray(select.options).filter(function (option) { return option.selected; }) : []; } var MultipleSelectBinding = (function (Binding) { function MultipleSelectBinding () { Binding.apply(this, arguments); } if ( Binding ) MultipleSelectBinding.__proto__ = Binding; var MultipleSelectBinding__proto__ = MultipleSelectBinding.prototype = Object.create( Binding && Binding.prototype ); MultipleSelectBinding__proto__.constructor = MultipleSelectBinding; MultipleSelectBinding__proto__.getInitialValue = function getInitialValue () { return this.element.options .filter(function (option) { return option.getAttribute('selected'); }) .map(function (option) { return option.getAttribute('value'); }); }; MultipleSelectBinding__proto__.getValue = function getValue () { var options = this.element.node.options; var len = options.length; var selectedValues = []; for (var i = 0; i < len; i += 1) { var option = options[i]; if (option.selected) { var optionValue = option._ractive ? option._ractive.value : option.value; selectedValues.push(optionValue); } } return selectedValues; }; MultipleSelectBinding__proto__.handleChange = function handleChange () { var attribute = this.attribute; var previousValue = attribute.getValue(); var value = this.getValue(); if (previousValue === undefined || !arrayContentsMatch(value, previousValue)) { Binding.prototype.handleChange.call(this); } return this; }; MultipleSelectBinding__proto__.render = function render () { Binding.prototype.render.call(this); this.element.on('change', handleDomEvent); if (this.model.get() === undefined) { // get value from DOM, if possible this.handleChange(); } }; MultipleSelectBinding__proto__.setFromNode = function setFromNode (node) { var selectedOptions = getSelectedOptions(node); var i = selectedOptions.length; var result = new Array(i); while (i--) { var option = selectedOptions[i]; result[i] = option._ractive ? option._ractive.value : option.value; } this.model.set(result); }; MultipleSelectBinding__proto__.unrender = function unrender () { this.element.off('change', handleDomEvent); }; return MultipleSelectBinding; }(Binding)); var NumericBinding = (function (GenericBinding) { function NumericBinding () { GenericBinding.apply(this, arguments); } if ( GenericBinding ) NumericBinding.__proto__ = GenericBinding; var NumericBinding__proto__ = NumericBinding.prototype = Object.create( GenericBinding && GenericBinding.prototype ); NumericBinding__proto__.constructor = NumericBinding; NumericBinding__proto__.getInitialValue = function getInitialValue () { return undefined; }; NumericBinding__proto__.getValue = function getValue () { var value = parseFloat(this.node.value); return isNaN(value) ? undefined : value; }; NumericBinding__proto__.setFromNode = function setFromNode (node) { var value = parseFloat(node.value); if (!isNaN(value)) { this.model.set(value); } }; return NumericBinding; }(GenericBinding)); var siblings = {}; function getSiblings(hash) { return siblings[hash] || (siblings[hash] = []); } var RadioBinding = (function (Binding) { function RadioBinding(element) { Binding.call(this, element, 'checked'); this.siblings = getSiblings(this.ractive._guid + this.element.getAttribute('name')); this.siblings.push(this); } if ( Binding ) RadioBinding.__proto__ = Binding; var RadioBinding__proto__ = RadioBinding.prototype = Object.create( Binding && Binding.prototype ); RadioBinding__proto__.constructor = RadioBinding; RadioBinding__proto__.getValue = function getValue () { return this.node.checked; }; RadioBinding__proto__.handleChange = function handleChange () { runloop.start(); this.siblings.forEach(function (binding) { binding.model.set(binding.getValue()); }); runloop.end(); }; RadioBinding__proto__.render = function render () { Binding.prototype.render.call(this); this.element.on('change', handleDomEvent); if (this.node.attachEvent) { this.element.on('click', handleDomEvent); } }; RadioBinding__proto__.setFromNode = function setFromNode (node) { this.model.set(node.checked); }; RadioBinding__proto__.unbind = function unbind () { removeFromArray(this.siblings, this); }; RadioBinding__proto__.unrender = function unrender () { this.element.off('change', handleDomEvent); this.element.off('click', handleDomEvent); }; return RadioBinding; }(Binding)); function getValue$1() { var checked = this.bindings.filter(function (b) { return b.node.checked; }); if (checked.length > 0) { return checked[0].element.getAttribute('value'); } } var RadioNameBinding = (function (Binding) { function RadioNameBinding(element) { var this$1 = this; Binding.call(this, element, 'name'); this.group = getBindingGroup('radioname', this.model, getValue$1); this.group.add(this); if (element.checked) { this.group.value = this.getValue(); } this.attribute.interpolator.pathChanged = function () { return this$1.updateName(); }; } if ( Binding ) RadioNameBinding.__proto__ = Binding; var RadioNameBinding__proto__ = RadioNameBinding.prototype = Object.create( Binding && Binding.prototype ); RadioNameBinding__proto__.constructor = RadioNameBinding; RadioNameBinding__proto__.bind = function bind () { if (!this.group.bound) { this.group.bind(); } }; RadioNameBinding__proto__.getInitialValue = function getInitialValue () { if (this.element.getAttribute('checked')) { return this.element.getAttribute('value'); } }; RadioNameBinding__proto__.getValue = function getValue () { return this.element.getAttribute('value'); }; RadioNameBinding__proto__.handleChange = function handleChange () { // If this <input> is the one that's checked, then the value of its // `name` model gets set to its value if (this.node.checked) { this.group.value = this.getValue(); Binding.prototype.handleChange.call(this); } this.updateName(); }; RadioNameBinding__proto__.lastVal = function lastVal (setting, value) { if (!this.group) { return; } if (setting) { this.group.lastValue = value; } else { return this.group.lastValue; } }; RadioNameBinding__proto__.rebind = function rebind (next, previous) { Binding.prototype.rebind.call(this, next, previous); this.updateName(); }; RadioNameBinding__proto__.rebound = function rebound (update) { Binding.prototype.rebound.call(this, update); this.updateName(); }; RadioNameBinding__proto__.render = function render () { Binding.prototype.render.call(this); var node = this.node; this.updateName(); node.checked = this.element.compare(this.model.get(), this.element.getAttribute('value')); this.element.on('change', handleDomEvent); if (node.attachEvent) { this.element.on('click', handleDomEvent); } }; RadioNameBinding__proto__.setFromNode = function setFromNode (node) { if (node.checked) { this.group.model.set(this.element.getAttribute('value')); } }; RadioNameBinding__proto__.unbind = function unbind () { this.group.remove(this); }; RadioNameBinding__proto__.unrender = function unrender () { var el = this.element; el.off('change', handleDomEvent); el.off('click', handleDomEvent); }; RadioNameBinding__proto__.updateName = function updateName () { if (this.node) { this.node.name = "{{" + (this.model.getKeypath()) + "}}"; } }; return RadioNameBinding; }(Binding)); var SingleSelectBinding = (function (Binding) { function SingleSelectBinding () { Binding.apply(this, arguments); } if ( Binding ) SingleSelectBinding.__proto__ = Binding; var SingleSelectBinding__proto__ = SingleSelectBinding.prototype = Object.create( Binding && Binding.prototype ); SingleSelectBinding__proto__.constructor = SingleSelectBinding; SingleSelectBinding__proto__.forceUpdate = function forceUpdate () { var this$1 = this; var value = this.getValue(); if (value !== undefined) { this.attribute.locked = true; runloop.scheduleTask(function () { return (this$1.attribute.locked = false); }); this.model.set(value); } }; SingleSelectBinding__proto__.getInitialValue = function getInitialValue () { if (this.element.getAttribute('value') !== undefined) { return; } var options = this.element.options; var len = options.length; if (!len) { return; } var value; var optionWasSelected; var i = len; // take the final selected option... while (i--) { var option = options[i]; if (option.getAttribute('selected')) { if (!option.getAttribute('disabled')) { value = option.getAttribute('value'); } optionWasSelected = true; break; } } // or the first non-disabled option, if none are selected if (!optionWasSelected) { while (++i < len) { if (!options[i].getAttribute('disabled')) { value = options[i].getAttribute('value'); break; } } } // This is an optimisation (aka hack) that allows us to forgo some // other more expensive work // TODO does it still work? seems at odds with new architecture if (value !== undefined) { this.element.attributeByName.value.value = value; } return value; }; SingleSelectBinding__proto__.getValue = function getValue () { var options = this.node.options; var len = options.length; var i; for (i = 0; i < len; i += 1) { var option = options[i]; if (options[i].selected && !options[i].disabled) { return option._ractive ? option._ractive.value : option.value; } } }; SingleSelectBinding__proto__.render = function render () { Binding.prototype.render.call(this); this.element.on('change', handleDomEvent); }; SingleSelectBinding__proto__.setFromNode = function setFromNode (node) { var option = getSelectedOptions(node)[0]; this.model.set(option._ractive ? option._ractive.value : option.value); }; SingleSelectBinding__proto__.unrender = function unrender () { this.element.off('change', handleDomEvent); }; return SingleSelectBinding; }(Binding)); function isBindable(attribute) { // The fragment must be a single non-string fragment if ( !attribute || !attribute.template.f || attribute.template.f.length !== 1 || attribute.template.f[0].s ) { return false; } // A binding is an interpolator `{{ }}`, yey. if (attribute.template.f[0].t === INTERPOLATOR) { return true; } // The above is probably the only true case. For the rest, show an appropriate // warning before returning false. // You can't bind a triple curly. HTML values on an attribute makes no sense. if (attribute.template.f[0].t === TRIPLE) { warnIfDebug('It is not possible create a binding using a triple mustache.'); } return false; } function selectBinding(element) { var name = element.name; var attributes = element.attributeByName; if (name !== 'input' && name !== 'textarea' && name !== 'select' && !attributes.contenteditable) { return; } var isBindableByValue = isBindable(attributes.value); var isBindableByContentEditable = isBindable(attributes.contenteditable); var isContentEditable = element.getAttribute('contenteditable'); // contenteditable // Bind if the contenteditable is true or a binding that may become true. if ((isContentEditable || isBindableByContentEditable) && isBindableByValue) { return ContentEditableBinding; } // <input> if (name === 'input') { var type = element.getAttribute('type'); if (type === 'radio') { var isBindableByName = isBindable(attributes.name); var isBindableByChecked = isBindable(attributes.checked); // For radios we can either bind the name or checked, but not both. // Name binding is handed instead. if (isBindableByName && isBindableByChecked) { warnIfDebug( 'A radio input can have two-way binding on its name attribute, or its checked attribute - not both', { ractive: element.root } ); return RadioNameBinding; } if (isBindableByName) { return RadioNameBinding; } if (isBindableByChecked) { return RadioBinding; } // Dead end. Unknown binding on radio input. return null; } if (type === 'checkbox') { var isBindableByName$1 = isBindable(attributes.name); var isBindableByChecked$1 = isBindable(attributes.checked); // A checkbox with bindings for both name and checked. Checked treated as // the checkbox value, name is treated as a regular binding. // // See https://github.com/ractivejs/ractive/issues/1749 if (isBindableByName$1 && isBindableByChecked$1) { return CheckboxBinding; } if (isBindableByName$1) { return CheckboxNameBinding; } if (isBindableByChecked$1) { return CheckboxBinding; } // Dead end. Unknown binding on checkbox input. return null; } if (type === 'file' && isBindableByValue) { return FileBinding; } if (type === 'number' && isBindableByValue) { return NumericBinding; } if (type === 'range' && isBindableByValue) { return NumericBinding; } // Some input of unknown type (browser usually falls back to text). if (isBindableByValue) { return GenericBinding; } // Dead end. Some unknown input and an unbindable. return null; } // <select> if (name === 'select' && isBindableByValue) { return element.getAttribute('multiple') ? MultipleSelectBinding : SingleSelectBinding; } // <textarea> if (name === 'textarea' && isBindableByValue) { return GenericBinding; } // Dead end. Some unbindable element. return null; } var endsWithSemi = /;\s*$/; var Element = (function (ContainerItem) { function Element(options) { var this$1 = this; ContainerItem.call(this, options); this.name = options.template.e.toLowerCase(); // find parent element this.parent = findElement(this.up, false); if (this.parent && this.parent.name === 'option') { throw new Error( ("An <option> element cannot contain other elements (encountered <" + (this.name) + ">)") ); } this.decorators = []; // create attributes this.attributeByName = {}; var attrs; var n, attr, val, cls, name, template, leftovers; var m = this.template.m; var len = (m && m.length) || 0; for (var i = 0; i < len; i++) { template = m[i]; if (template.g) { (this$1.statics || (this$1.statics = {}))[template.n] = isString(template.f) ? template.f : template.n; } else { switch (template.t) { case ATTRIBUTE: case BINDING_FLAG: case DECORATOR: case EVENT: case TRANSITION: attr = createItem({ owner: this$1, up: this$1.up, template: template }); n = template.n; attrs = attrs || (attrs = this$1.attributes = []); if (n === 'value') { val = attr; } else if (n === 'name') { name = attr; } else if (n === 'class') { cls = attr; } else { attrs.push(attr); } break; case DELEGATE_FLAG: this$1.delegate = false; break; default: (leftovers || (leftovers = [])).push(template); break; } } } if (val) { attrs.push(val); } if (name) { attrs.push(name); } if (cls) { attrs.unshift(cls); } if (leftovers) { (attrs || (this.attributes = [])).push( new ConditionalAttribute({ owner: this, up: this.up, template: leftovers }) ); // empty leftovers array leftovers = []; } // create children if (options.template.f && !options.deferContent) { this.fragment = new Fragment({ template: options.template.f, owner: this, cssIds: null }); } this.binding = null; // filled in later } if ( ContainerItem ) Element.__proto__ = ContainerItem; var Element__proto__ = Element.prototype = Object.create( ContainerItem && ContainerItem.prototype ); Element__proto__.constructor = Element; Element__proto__.bind = function bind () { var attrs = this.attributes; if (attrs) { attrs.binding = true; var len = attrs.length; for (var i = 0; i < len; i++) { attrs[i].bind(); } attrs.binding = false; } if (this.fragment) { this.fragment.bind(); } // create two-way binding if necessary if (!this.binding) { this.recreateTwowayBinding(); } else { this.binding.bind(); } }; Element__proto__.createTwowayBinding = function createTwowayBinding () { if ('twoway' in this ? this.twoway : this.ractive.twoway) { var Binding = selectBinding(this); if (Binding) { var binding = new Binding(this); if (binding && binding.model) { return binding; } } } }; Element__proto__.destroyed = function destroyed$1 () { if (this.attributes) { this.attributes.forEach(destroyed); } if (this.fragment) { this.fragment.destroyed(); } }; Element__proto__.detach = function detach () { // if this element is no longer rendered, the transitions are complete and the attributes can be torn down if (!this.rendered) { this.destroyed(); } return detachNode(this.node); }; Element__proto__.find = function find (selector, options) { if (this.node && matches(this.node, selector)) { return this.node; } if (this.fragment) { return this.fragment.find(selector, options); } }; Element__proto__.findAll = function findAll (selector, options) { var result = options.result; if (matches(this.node, selector)) { result.push(this.node); } if (this.fragment) { this.fragment.findAll(selector, options); } }; Element__proto__.findNextNode = function findNextNode () { return null; }; Element__proto__.firstNode = function firstNode () { return this.node; }; Element__proto__.getAttribute = function getAttribute (name) { if (this.statics && name in this.statics) { return this.statics[name]; } var attribute = this.attributeByName[name]; return attribute ? attribute.getValue() : undefined; }; Element__proto__.getContext = function getContext () { var assigns = [], len = arguments.length; while ( len-- ) assigns[ len ] = arguments[ len ]; if (this.fragment) { return (ref = this.fragment).getContext.apply(ref, assigns); } if (!this.ctx) { this.ctx = new Context(this.up, this); } assigns.unshift(create(this.ctx)); return assign.apply(null, assigns); var ref; }; Element__proto__.off = function off (event, callback, capture) { if ( capture === void 0 ) capture = false; var delegate = this.up.delegate; var ref = this.listeners && this.listeners[event]; if (!ref) { return; } removeFromArray(ref, callback); if (delegate) { var listeners = (delegate.listeners || (delegate.listeners = [])) && (delegate.listeners[event] || (delegate.listeners[event] = [])); if (listeners.refs && !--listeners.refs) { delegate.off(event, delegateHandler, true); } } else if (this.rendered) { var n = this.node; var add = n.addEventListener; var rem = n.removeEventListener; if (!ref.length) { rem.call(n, event, handler, capture); } else if (ref.length && !ref.refs && capture) { rem.call(n, event, handler, true); add.call(n, event, handler, false); } } }; Element__proto__.on = function on (event, callback, capture) { if ( capture === void 0 ) capture = false; var delegate = this.up.delegate; var ref = (this.listeners || (this.listeners = {}))[event] || (this.listeners[event] = []); if (delegate) { var listeners = ((delegate.listeners || (delegate.listeners = [])) && delegate.listeners[event]) || (delegate.listeners[event] = []); if (!listeners.refs) { listeners.refs = 0; delegate.on(event, delegateHandler, true); listeners.refs++; } else { listeners.refs++; } } else if (this.rendered) { var n = this.node; var add = n.addEventListener; var rem = n.removeEventListener; if (!ref.length) { add.call(n, event, handler, capture); } else if (ref.length && !ref.refs && capture) { rem.call(n, event, handler, false); add.call(n, event, handler, true); } } addToArray(this.listeners[event], callback); }; Element__proto__.recreateTwowayBinding = function recreateTwowayBinding () { if (this.binding) { this.binding.unbind(); this.binding.unrender(); } if ((this.binding = this.createTwowayBinding())) { this.binding.bind(); if (this.rendered) { this.binding.render(); } } }; Element__proto__.rebound = function rebound (update$$1) { ContainerItem.prototype.rebound.call(this, update$$1); if (this.attributes) { this.attributes.forEach(function (x) { return x.rebound(update$$1); }); } if (this.binding) { this.binding.rebound(update$$1); } }; Element__proto__.render = function render (target, occupants) { var this$1 = this; // TODO determine correct namespace this.namespace = getNamespace(this); var node; var existing = false; if (occupants) { var n; while ((n = occupants.shift())) { if ( n.nodeName.toUpperCase() === this$1.template.e.toUpperCase() && n.namespaceURI === this$1.namespace ) { this$1.node = node = n; existing = true; break; } else { detachNode(n); } } } if (!existing && this.node) { node = this.node; target.appendChild(node); existing = true; } if (!node) { var name = this.template.e; node = createElement( this.namespace === html ? name.toLowerCase() : name, this.namespace, this.getAttribute('is') ); this.node = node; } // tie the node to this vdom element defineProperty(node, '_ractive', { value: { proxy: this }, configurable: true }); if (this.statics) { keys(this.statics).forEach(function (k) { node.setAttribute(k, this$1.statics[k]); }); } if (existing && this.foundNode) { this.foundNode(node); } // register intro before rendering content so children can find the intro var intro = this.intro; if (intro && intro.shouldFire('intro')) { intro.isIntro = true; intro.isOutro = false; runloop.registerTransition(intro); } if (this.fragment) { var children = existing ? toArray(node.childNodes) : undefined; this.fragment.render(node, children); // clean up leftover children if (children) { children.forEach(detachNode); } } if (existing) { // store initial values for two-way binding if (this.binding && this.binding.wasUndefined) { this.binding.setFromNode(node); } // remove unused attributes var i = node.attributes.length; while (i--) { var name$1 = node.attributes[i].name; if (!(name$1 in this$1.attributeByName) && (!this$1.statics || !(name$1 in this$1.statics))) { node.removeAttribute(name$1); } } } // Is this a top-level node of a component? If so, we may need to add // a data-ractive-css attribute, for CSS encapsulation if (this.up.cssIds) { node.setAttribute('data-ractive-css', this.up.cssIds.map(function (x) { return ("{" + x + "}"); }).join(' ')); } if (this.attributes) { var len = this.attributes.length; for (var i$1 = 0; i$1 < len; i$1++) { this$1.attributes[i$1].render(); } } if (this.binding) { this.binding.render(); } if (!this.up.delegate && this.listeners) { var ls = this.listeners; for (var k in ls) { if (ls[k] && ls[k].length) { this$1.node.addEventListener(k, handler, !!ls[k].refs); } } } if (!existing) { target.appendChild(node); } this.rendered = true; }; Element__proto__.toString = function toString () { var this$1 = this; var tagName = this.template.e; var attrs = (this.attributes && this.attributes.map(stringifyAttribute).join('')) || ''; if (this.statics) { keys(this.statics).forEach( function (k) { return k !== 'class' && k !== 'style' && (attrs = " " + k + "=\"" + (this$1.statics[k]) + "\"" + attrs); } ); } // Special case - selected options if (this.name === 'option' && this.isSelected()) { attrs += ' selected'; } // Special case - two-way radio name bindings if (this.name === 'input' && inputIsCheckedRadio(this)) { attrs += ' checked'; } // Special case style and class attributes and directives var style = this.statics ? this.statics.style : undefined; var cls = this.statics ? this.statics.class : undefined; this.attributes && this.attributes.forEach(function (attr) { if (attr.name === 'class') { cls = (cls || '') + (cls ? ' ' : '') + safeAttributeString(attr.getString()); } else if (attr.name === 'style') { style = (style || '') + (style ? ' ' : '') + safeAttributeString(attr.getString()); if (style && !endsWithSemi.test(style)) { style += ';'; } } else if (attr.style) { style = (style || '') + (style ? ' ' : '') + (attr.style) + ": " + (safeAttributeString(attr.getString())) + ";"; } else if (attr.inlineClass && attr.getValue()) { cls = (cls || '') + (cls ? ' ' : '') + attr.inlineClass; } }); // put classes first, then inline style if (style !== undefined) { attrs = ' style' + (style ? ("=\"" + style + "\"") : '') + attrs; } if (cls !== undefined) { attrs = ' class' + (cls ? ("=\"" + cls + "\"") : '') + attrs; } if (this.up.cssIds) { attrs += " data-ractive-css=\"" + (this.up.cssIds.map(function (x) { return ("{" + x + "}"); }).join(' ')) + "\""; } var str = "<" + tagName + attrs + ">"; if (voidElements[this.name.toLowerCase()]) { return str; } // Special case - textarea if (this.name === 'textarea' && this.getAttribute('value') !== undefined) { str += escapeHtml(this.getAttribute('value')); } else if (this.getAttribute('contenteditable') !== undefined) { // Special case - contenteditable str += this.getAttribute('value') || ''; } if (this.fragment) { str += this.fragment.toString(!/^(?:script|style)$/i.test(this.template.e)); // escape text unless script/style } str += "</" + tagName + ">"; return str; }; Element__proto__.unbind = function unbind (view) { var attrs = this.attributes; if (attrs) { attrs.unbinding = true; var len = attrs.length; for (var i = 0; i < len; i++) { attrs[i].unbind(view); } attrs.unbinding = false; } if (this.binding) { this.binding.unbind(view); } if (this.fragment) { this.fragment.unbind(view); } }; Element__proto__.unrender = function unrender (shouldDestroy) { if (!this.rendered) { return; } this.rendered = false; // unrendering before intro completed? complete it now // TODO should be an API for aborting transitions var transition = this.intro; if (transition && transition.complete) { transition.complete(); } // Detach as soon as we can if (this.name === 'option') { // <option> elements detach immediately, so that // their parent <select> element syncs correctly, and // since option elements can't have transitions anyway this.detach(); } else if (shouldDestroy) { runloop.detachWhenReady(this); } // outro transition var outro = this.outro; if (outro && outro.shouldFire('outro')) { outro.isIntro = false; outro.isOutro = true; runloop.registerTransition(outro); } if (this.fragment) { this.fragment.unrender(); } if (this.binding) { this.binding.unrender(); } }; Element__proto__.update = function update () { if (this.dirty) { this.dirty = false; var attrs = this.attributes; if (attrs) { var len = attrs.length; for (var i = 0; i < len; i++) { attrs[i].update(); } } if (this.fragment) { this.fragment.update(); } } }; return Element; }(ContainerItem)); function inputIsCheckedRadio(element) { var nameAttr = element.attributeByName.name; return ( element.getAttribute('type') === 'radio' && (nameAttr || {}).interpolator && element.getAttribute('value') === nameAttr.interpolator.model.get() ); } function stringifyAttribute(attribute) { var str = attribute.toString(); return str ? ' ' + str : ''; } function getNamespace(element) { // Use specified namespace... var xmlns$$1 = element.getAttribute('xmlns'); if (xmlns$$1) { return xmlns$$1; } // ...or SVG namespace, if this is an <svg> element if (element.name === 'svg') { return svg$1; } var parent = element.parent; if (parent) { // ...or HTML, if the parent is a <foreignObject> if (parent.name === 'foreignobject') { return html; } // ...or inherit from the parent node return parent.node.namespaceURI; } return element.ractive.el.namespaceURI; } function delegateHandler(ev) { var name = ev.type; var end = ev.currentTarget; var endEl = end._ractive && end._ractive.proxy; var node = ev.target; var bubble = true; var listeners; // starting with the origin node, walk up the DOM looking for ractive nodes with a matching event listener while (bubble && node && node !== end) { var proxy = node._ractive && node._ractive.proxy; if (proxy && proxy.up.delegate === endEl && shouldFire(ev, node, end)) { listeners = proxy.listeners && proxy.listeners[name]; if (listeners) { var len = listeners.length; for (var i = 0; i < len; i++) { bubble = listeners[i].call(node, ev) !== false && bubble; } } } node = node.parentNode || node.correspondingUseElement; // SVG with a <use> element in certain environments } return bubble; } var UIEvent = win !== null ? win.UIEvent : null; function shouldFire(event, start, end) { if (UIEvent && event instanceof UIEvent) { var node = start; while (node && node !== end) { if (node.disabled) { return false; } node = node.parentNode || node.correspondingUseElement; } } return true; } function handler(ev) { var this$1 = this; var el = this._ractive.proxy; var listeners; if (el.listeners && (listeners = el.listeners[ev.type])) { var len = listeners.length; for (var i = 0; i < len; i++) { listeners[i].call(this$1, ev); } } } var Form = (function (Element) { function Form(options) { Element.call(this, options); this.formBindings = []; } if ( Element ) Form.__proto__ = Element; var Form__proto__ = Form.prototype = Object.create( Element && Element.prototype ); Form__proto__.constructor = Form; Form__proto__.render = function render (target, occupants) { Element.prototype.render.call(this, target, occupants); this.on('reset', handleReset); }; Form__proto__.unrender = function unrender (shouldDestroy) { this.off('reset', handleReset); Element.prototype.unrender.call(this, shouldDestroy); }; return Form; }(Element)); function handleReset() { var element = this._ractive.proxy; runloop.start(); element.formBindings.forEach(updateModel); runloop.end(); } function updateModel(binding) { binding.model.set(binding.resetValue); } var DOMEvent = function DOMEvent(name, owner) { if (name.indexOf('*') !== -1) { fatal( ("Only component proxy-events may contain \"*\" wildcards, <" + (owner.name) + " on-" + name + "=\"...\"/> is not valid") ); } this.name = name; this.owner = owner; this.handler = null; }; var DOMEvent__proto__ = DOMEvent.prototype; DOMEvent__proto__.bind = function bind () {}; DOMEvent__proto__.render = function render (directive) { var this$1 = this; var name = this.name; var register = function () { var node = this$1.owner.node; this$1.owner.on( name, (this$1.handler = function (event) { return directive.fire({ node: node, original: event, event: event, name: name }); }) ); }; if (name !== 'load') { // schedule events so that they take place after twoway binding runloop.scheduleTask(register, true); } else { // unless its a load event register(); } }; DOMEvent__proto__.unbind = function unbind () {}; DOMEvent__proto__.unrender = function unrender () { if (this.handler) { this.owner.off(this.name, this.handler); } }; var CustomEvent = function CustomEvent(eventPlugin, owner, name, args) { this.eventPlugin = eventPlugin; this.owner = owner; this.name = name; this.handler = null; this.args = args; }; var CustomEvent__proto__ = CustomEvent.prototype; CustomEvent__proto__.bind = function bind () {}; CustomEvent__proto__.render = function render (directive) { var this$1 = this; runloop.scheduleTask(function () { var node = this$1.owner.node; this$1.handler = this$1.eventPlugin.apply( this$1.owner.ractive, [ node, function (event) { if ( event === void 0 ) event = {}; if (event.original) { event.event = event.original; } else { event.original = event.event; } event.name = this$1.name; event.node = event.node || node; return directive.fire(event); } ].concat(this$1.args || []) ); }); }; CustomEvent__proto__.unbind = function unbind () {}; CustomEvent__proto__.unrender = function unrender () { this.handler.teardown(); }; var RactiveEvent = function RactiveEvent(component, name) { this.component = component; this.name = name; this.handler = null; }; var RactiveEvent__proto__ = RactiveEvent.prototype; RactiveEvent__proto__.bind = function bind (directive) { var ractive = this.component.instance; this.handler = ractive.on(this.name, function () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; // watch for reproxy if (args[0] instanceof Context) { var ctx = args.shift(); ctx.component = ractive; directive.fire(ctx, args); } else { directive.fire({}, args); } // cancel bubbling return false; }); }; RactiveEvent__proto__.render = function render () {}; RactiveEvent__proto__.unbind = function unbind () { this.handler.cancel(); }; RactiveEvent__proto__.unrender = function unrender () {}; var specialPattern = /^(event|arguments|@node|@event|@context)(\..+)?$/; var dollarArgsPattern = /^\$(\d+)(\..+)?$/; var EventDirective = function EventDirective(options) { this.owner = options.owner || options.up.owner || findElement(options.up); this.element = this.owner.attributeByName ? this.owner : findElement(options.up, true); this.template = options.template; this.up = options.up; this.ractive = options.up.ractive; this.events = []; }; var EventDirective__proto__ = EventDirective.prototype; EventDirective__proto__.bind = function bind () { var this$1 = this; // sometimes anchors will cause an unbind without unrender if (this.events.length) { this.events.forEach(function (e) { return e.unrender(); }); this.events = []; } if (this.element.type === COMPONENT || this.element.type === ANCHOR) { this.template.n.forEach(function (n) { this$1.events.push(new RactiveEvent(this$1.element, n)); }); } else { var args; if ((args = this.template.a)) { var rs = args.r.map(function (r) { var model = resolveReference(this$1.up, r); return model ? model.get() : undefined; }); try { args = getFunction(args.s, rs.length).apply(null, rs); } catch (err) { args = null; warnIfDebug( ("Failed to compute args for event on-" + (this.template.n.join('- ')) + ": " + (err.message || err)) ); } } this.template.n.forEach(function (n) { var fn = findInViewHierarchy('events', this$1.ractive, n); if (fn) { this$1.events.push(new CustomEvent(fn, this$1.element, n, args)); } else { this$1.events.push(new DOMEvent(n, this$1.element)); } }); } // method calls this.models = null; addToArray(this.element.events || (this.element.events = []), this); setupArgsFn(this, this.template); if (!this.fn) { this.action = this.template.f; } this.events.forEach(function (e) { return e.bind(this$1); }); }; EventDirective__proto__.destroyed = function destroyed () { this.events.forEach(function (e) { return e.unrender(); }); }; EventDirective__proto__.fire = function fire (event, args) { var this$1 = this; if ( args === void 0 ) args = []; var context = event instanceof Context && event.refire ? event : this.element.getContext(event); if (this.fn) { var values = []; var models = resolveArgs(this, this.template, this.up, { specialRef: function specialRef(ref) { var specialMatch = specialPattern.exec(ref); if (specialMatch) { // on-click="foo(event.node)" return { special: specialMatch[1], keys: specialMatch[2] ? splitKeypath(specialMatch[2].substr(1)) : [] }; } var dollarMatch = dollarArgsPattern.exec(ref); if (dollarMatch) { // on-click="foo($1)" return { special: 'arguments', keys: [dollarMatch[1] - 1].concat( dollarMatch[2] ? splitKeypath(dollarMatch[2].substr(1)) : [] ) }; } } }); if (models) { models.forEach(function (model) { if (!model) { return values.push(undefined); } if (model.special) { var which = model.special; var obj; if (which === '@node') { obj = this$1.element.node; } else if (which === '@event') { obj = event && event.event; } else if (which === 'event') { warnOnceIfDebug( "The event reference available to event directives is deprecated and should be replaced with @context and @event" ); obj = context; } else if (which === '@context') { obj = context; } else { obj = args; } var keys = model.keys.slice(); while (obj && keys.length) { obj = obj[keys.shift()]; } return values.push(obj); } if (model.wrapper) { return values.push(model.wrapperValue); } values.push(model.get()); }); } // make event available as `this.event` var ractive = this.ractive; var oldEvent = ractive.event; ractive.event = context; var returned = this.fn.apply(ractive, values); var result = returned.pop(); // Auto prevent and stop if return is explicitly false if (result === false) { var original = event ? event.original : undefined; if (original) { original.preventDefault && original.preventDefault(); original.stopPropagation && original.stopPropagation(); } else { warnOnceIfDebug( ("handler '" + (this.template.n.join( ' ' )) + "' returned false, but there is no event available to cancel") ); } } else if (!returned.length && isArray(result) && isString(result[0])) { // watch for proxy events result = fireEvent(this.ractive, result.shift(), context, result); } ractive.event = oldEvent; return result; } else { return fireEvent(this.ractive, this.action, context, args); } }; EventDirective__proto__.handleChange = function handleChange () {}; EventDirective__proto__.render = function render () { var this$1 = this; this.events.forEach(function (e) { return e.render(this$1); }); }; EventDirective__proto__.toString = function toString () { return ''; }; EventDirective__proto__.unbind = function unbind (view) { removeFromArray(this.element.events, this); this.events.forEach(function (e) { return e.unbind(view); }); }; EventDirective__proto__.unrender = function unrender () { this.events.forEach(function (e) { return e.unrender(); }); }; var proto$4 = EventDirective.prototype; proto$4.firstNode = proto$4.rebound = proto$4.update = noop; function progressiveText(item, target, occupants, text) { if (occupants) { var n = occupants[0]; if (n && n.nodeType === 3) { var idx = n.nodeValue.indexOf(text); occupants.shift(); if (idx === 0) { if (n.nodeValue.length !== text.length) { occupants.unshift(n.splitText(text.length)); } } else { n.nodeValue = text; } } else { n = item.node = doc.createTextNode(text); if (occupants[0]) { target.insertBefore(n, occupants[0]); } else { target.appendChild(n); } } item.node = n; } else { if (!item.node) { item.node = doc.createTextNode(text); } target.appendChild(item.node); } } var Mustache = (function (Item) { function Mustache(options) { Item.call(this, options); if (options.owner) { this.parent = options.owner; } this.isStatic = !!options.template.s; this.model = null; this.dirty = false; } if ( Item ) Mustache.__proto__ = Item; var Mustache__proto__ = Mustache.prototype = Object.create( Item && Item.prototype ); Mustache__proto__.constructor = Mustache; Mustache__proto__.bind = function bind (pre) { // yield mustaches and inner contexts should resolve in container context var start = this.template.y ? this.template.y.containerFragment : this.containerFragment || this.up; // try to find a model for this view var model = pre || resolve(start, this.template); if (model) { var value = model.get(); if (this.isStatic) { this.model = { get: function () { return value; } }; model.unreference(); return; } model.register(this); this.model = model; } }; Mustache__proto__.handleChange = function handleChange () { this.bubble(); }; Mustache__proto__.rebind = function rebind (next, previous, safe) { if (this.isStatic) { return; } next = rebindMatch(this.template, next, previous, this.up); if (next === this.model) { return false; } if (this.model) { this.model.unregister(this); } if (next) { next.addShuffleRegister(this, 'mark'); } this.model = next; if (!safe) { this.handleChange(); } return true; }; Mustache__proto__.rebound = function rebound (update) { if (this.model) { if (this.model.rebound) { this.model.rebound(update); } else { // check to see if the model actually changed... // yield mustaches and inner contexts should resolve in container context var start = this.template.y ? this.template.y.containerFragment : this.containerFragment || this.up; // try to find a model for this view var model = resolve(start, this.template); if (model !== this.model) { this.model.unregister(this); this.bind(model); } } if (update) { this.bubble(); } } if (this.fragment) { this.fragment.rebound(update); } }; Mustache__proto__.unbind = function unbind () { if (!this.isStatic) { this.model && this.model.unregister(this); this.model = undefined; } }; return Mustache; }(Item)); function MustacheContainer(options) { Mustache.call(this, options); } var proto$5 = (MustacheContainer.prototype = Object.create(ContainerItem.prototype)); assign(proto$5, Mustache.prototype, { constructor: MustacheContainer }); var Interpolator = (function (Mustache) { function Interpolator () { Mustache.apply(this, arguments); } if ( Mustache ) Interpolator.__proto__ = Mustache; var Interpolator__proto__ = Interpolator.prototype = Object.create( Mustache && Mustache.prototype ); Interpolator__proto__.constructor = Interpolator; Interpolator__proto__.bubble = function bubble () { if (this.owner) { this.owner.bubble(); } Mustache.prototype.bubble.call(this); }; Interpolator__proto__.detach = function detach () { return detachNode(this.node); }; Interpolator__proto__.firstNode = function firstNode () { return this.node; }; Interpolator__proto__.getString = function getString () { return this.model ? safeToStringValue(this.model.get()) : ''; }; Interpolator__proto__.render = function render (target, occupants) { if (inAttributes()) { return; } var value = (this.value = this.getString()); this.rendered = true; progressiveText(this, target, occupants, value); }; Interpolator__proto__.toString = function toString (escape) { var string = this.getString(); return escape ? escapeHtml(string) : string; }; Interpolator__proto__.unrender = function unrender (shouldDestroy) { if (shouldDestroy) { this.detach(); } this.rendered = false; }; Interpolator__proto__.update = function update () { if (this.dirty) { this.dirty = false; if (this.rendered) { var value = this.getString(); if (value !== this.value) { this.node.data = this.value = value; } } } }; Interpolator__proto__.valueOf = function valueOf () { return this.model ? this.model.get() : undefined; }; return Interpolator; }(Mustache)); var Input = (function (Element) { function Input () { Element.apply(this, arguments); } if ( Element ) Input.__proto__ = Element; var Input__proto__ = Input.prototype = Object.create( Element && Element.prototype ); Input__proto__.constructor = Input; Input__proto__.render = function render (target, occupants) { Element.prototype.render.call(this, target, occupants); this.node.defaultValue = this.node.value; }; Input__proto__.compare = function compare (value, attrValue) { var comparator = this.getAttribute('value-comparator'); if (comparator) { if (isFunction(comparator)) { return comparator(value, attrValue); } if (value && attrValue) { return value[comparator] == attrValue[comparator]; } } return value == attrValue; }; return Input; }(Element)); // simple JSON parser, without the restrictions of JSON parse // (i.e. having to double-quote keys). // // If passed a hash of values as the second argument, ${placeholders} // will be replaced with those values var specials$1 = { true: true, false: false, null: null, undefined: undefined }; var specialsPattern = new RegExp('^(?:' + keys(specials$1).join('|') + ')'); var numberPattern$1 = /^(?:[+-]?)(?:(?:(?:0|[1-9]\d*)?\.\d+)|(?:(?:0|[1-9]\d*)\.)|(?:0|[1-9]\d*))(?:[eE][+-]?\d+)?/; var placeholderPattern = /\$\{([^\}]+)\}/g; var placeholderAtStartPattern = /^\$\{([^\}]+)\}/; var onlyWhitespace$1 = /^\s*$/; var JsonParser = Parser.extend({ init: function init(str, options) { this.values = options.values; this.sp(); }, postProcess: function postProcess(result) { if (result.length !== 1 || !onlyWhitespace$1.test(this.leftover)) { return null; } return { value: result[0].v }; }, converters: [ function getPlaceholder(parser) { if (!parser.values) { return null; } var placeholder = parser.matchPattern(placeholderAtStartPattern); if (placeholder && hasOwn(parser.values, placeholder)) { return { v: parser.values[placeholder] }; } }, function getSpecial(parser) { var special = parser.matchPattern(specialsPattern); if (special) { return { v: specials$1[special] }; } }, function getNumber(parser) { var number = parser.matchPattern(numberPattern$1); if (number) { return { v: +number }; } }, function getString(parser) { var stringLiteral = readStringLiteral(parser); var values = parser.values; if (stringLiteral && values) { return { v: stringLiteral.v.replace(placeholderPattern, function (match, $1) { return $1 in values ? values[$1] : $1; } ) }; } return stringLiteral; }, function getObject(parser) { if (!parser.matchString('{')) { return null; } var result = {}; parser.sp(); if (parser.matchString('}')) { return { v: result }; } var pair; while ((pair = getKeyValuePair(parser))) { result[pair.key] = pair.value; parser.sp(); if (parser.matchString('}')) { return { v: result }; } if (!parser.matchString(',')) { return null; } } return null; }, function getArray(parser) { if (!parser.matchString('[')) { return null; } var result = []; parser.sp(); if (parser.matchString(']')) { return { v: result }; } var valueToken; while ((valueToken = parser.read())) { result.push(valueToken.v); parser.sp(); if (parser.matchString(']')) { return { v: result }; } if (!parser.matchString(',')) { return null; } parser.sp(); } return null; } ] }); function getKeyValuePair(parser) { parser.sp(); var key = readKey(parser); if (!key) { return null; } var pair = { key: key }; parser.sp(); if (!parser.matchString(':')) { return null; } parser.sp(); var valueToken = parser.read(); if (!valueToken) { return null; } pair.value = valueToken.v; return pair; } function parseJSON(str, values) { var parser = new JsonParser(str, { values: values }); return parser.result; } var Mapping = (function (Item) { function Mapping(options) { Item.call(this, options); this.name = options.template.n; this.owner = options.owner || options.up.owner || options.element || findElement(options.up); this.element = options.element || (this.owner.attributeByName ? this.owner : findElement(options.up)); this.up = this.element.up; // shared this.ractive = this.up.ractive; this.element.attributeByName[this.name] = this; this.value = options.template.f; } if ( Item ) Mapping.__proto__ = Item; var Mapping__proto__ = Mapping.prototype = Object.create( Item && Item.prototype ); Mapping__proto__.constructor = Mapping; Mapping__proto__.bind = function bind () { var template = this.template.f; var viewmodel = this.element.instance.viewmodel; if (template === 0) { // empty attributes are `true` viewmodel.joinKey(this.name).set(true); } else if (isString(template)) { var parsed = parseJSON(template); viewmodel.joinKey(this.name).set(parsed ? parsed.value : template); } else if (isArray(template)) { createMapping(this, true); } }; Mapping__proto__.rebound = function rebound (update) { if (this.boundFragment) { this.boundFragment.rebound(update); } if (this.link) { this.model = resolve(this.up, this.template.f[0]); var model = this.element.instance.viewmodel.joinAll(splitKeypath(this.name)); model.link(this.model, this.name, { mapping: true }); } }; Mapping__proto__.render = function render () {}; Mapping__proto__.unbind = function unbind (view) { if (this.model) { this.model.unregister(this); } if (this.boundFragment) { this.boundFragment.unbind(view); } if (this.element.bound) { if (this.link.target === this.model) { this.link.owner.unlink(); } } }; Mapping__proto__.unrender = function unrender () {}; Mapping__proto__.update = function update () { if (this.dirty) { this.dirty = false; if (this.boundFragment) { this.boundFragment.update(); } } }; return Mapping; }(Item)); function createMapping(item) { var template = item.template.f; var viewmodel = item.element.instance.viewmodel; var childData = viewmodel.value; if (template.length === 1 && template[0].t === INTERPOLATOR) { var model = resolve(item.up, template[0]); var val = model.get(false); // if the interpolator is not static if (!template[0].s) { item.model = model; item.link = viewmodel.createLink(item.name, model, template[0].r, { mapping: true }); // initialize parent side of the mapping from child data if (val === undefined && !model.isReadonly && item.name in childData) { model.set(childData[item.name]); } } else if (!isObjectType(val) || template[0].x) { // copy non-object, non-computed vals through viewmodel.joinKey(splitKeypath(item.name)).set(val); } else { // warn about trying to copy an object warnIfDebug(("Cannot copy non-computed object value from static mapping '" + (item.name) + "'")); } // if the item isn't going to manage the model, give it a change to tear down if it's computed if (model !== item.model) { model.unregister(); } } else { item.boundFragment = new Fragment({ owner: item, template: template }).bind(); item.model = viewmodel.joinKey(splitKeypath(item.name)); item.model.set(item.boundFragment.valueOf()); // item is a *bit* of a hack item.boundFragment.bubble = function () { Fragment.prototype.bubble.call(item.boundFragment); // defer this to avoid mucking around model deps if there happens to be an expression involved runloop.scheduleTask(function () { item.boundFragment.update(); item.model.set(item.boundFragment.valueOf()); }); }; } } var Option = (function (Element) { function Option(options) { var template = options.template; if (!template.a) { template.a = {}; } // If the value attribute is missing, use the element's content, // as long as it isn't disabled if (template.a.value === undefined && !('disabled' in template.a)) { template.a.value = template.f || ''; } Element.call(this, options); this.select = findElement(this.parent || this.up, false, 'select'); } if ( Element ) Option.__proto__ = Element; var Option__proto__ = Option.prototype = Object.create( Element && Element.prototype ); Option__proto__.constructor = Option; Option__proto__.bind = function bind () { if (!this.select) { Element.prototype.bind.call(this); return; } // If the select has a value, it overrides the `selected` attribute on // this option - so we delete the attribute var selectedAttribute = this.attributeByName.selected; if (selectedAttribute && this.select.getAttribute('value') !== undefined) { var index = this.attributes.indexOf(selectedAttribute); this.attributes.splice(index, 1); delete this.attributeByName.selected; } Element.prototype.bind.call(this); this.select.options.push(this); }; Option__proto__.bubble = function bubble () { // if we're using content as value, may need to update here var value = this.getAttribute('value'); if (this.node && this.node.value !== value) { this.node._ractive.value = value; } Element.prototype.bubble.call(this); }; Option__proto__.getAttribute = function getAttribute (name) { var attribute = this.attributeByName[name]; return attribute ? attribute.getValue() : name === 'value' && this.fragment ? this.fragment.valueOf() : undefined; }; Option__proto__.isSelected = function isSelected () { var this$1 = this; var optionValue = this.getAttribute('value'); if (optionValue === undefined || !this.select) { return false; } var selectValue = this.select.getAttribute('value'); if (this.select.compare(selectValue, optionValue)) { return true; } if (this.select.getAttribute('multiple') && isArray(selectValue)) { var i = selectValue.length; while (i--) { if (this$1.select.compare(selectValue[i], optionValue)) { return true; } } } }; Option__proto__.render = function render (target, occupants) { Element.prototype.render.call(this, target, occupants); if (!this.attributeByName.value) { this.node._ractive.value = this.getAttribute('value'); } }; Option__proto__.unbind = function unbind (view) { Element.prototype.unbind.call(this, view); if (this.select) { removeFromArray(this.select.options, this); } }; return Option; }(Element)); function getPartialTemplate(ractive, name, up) { // If the partial in instance or view heirarchy instances, great var partial = getPartialFromRegistry(ractive, name, up || {}); if (partial) { return partial; } // Does it exist on the page as a script tag? partial = parser.fromId(name, { noThrow: true }); if (partial) { // parse and register to this ractive instance var parsed = parser.parseFor(partial, ractive); // register extra partials on the ractive instance if they don't already exist if (parsed.p) { fillGaps(ractive.partials, parsed.p); } // register (and return main partial if there are others in the template) return (ractive.partials[name] = parsed.t); } } function getPartialFromRegistry(ractive, name, up) { // if there was an instance up-hierarchy, cool var partial = findParentPartial(name, up.owner); if (partial) { return partial; } // find first instance in the ractive or view hierarchy that has this partial var instance = findInstance('partials', ractive, name); if (!instance) { return; } partial = instance.partials[name]; // partial is a function? var fn; if (isFunction(partial)) { fn = partial; // super partial if (fn.styleSet) { return fn; } fn = partial.bind(instance); fn.isOwner = hasOwn(instance.partials, name); partial = fn.call(ractive, parser); } if (!partial && partial !== '') { warnIfDebug(noRegistryFunctionReturn, name, 'partial', 'partial', { ractive: ractive }); return; } // If this was added manually to the registry, // but hasn't been parsed, parse it now if (!parser.isParsed(partial)) { // use the parseOptions of the ractive instance on which it was found var parsed = parser.parseFor(partial, instance); // Partials cannot contain nested partials! // TODO add a test for this if (parsed.p) { warnIfDebug('Partials ({{>%s}}) cannot contain nested inline partials', name, { ractive: ractive }); } // if fn, use instance to store result, otherwise needs to go // in the correct point in prototype chain on instance or constructor var target = fn ? instance : findOwner(instance, name); // may be a template with partials, which need to be registered and main template extracted target.partials[name] = partial = parsed.t; } // store for reset if (fn) { partial._fn = fn; } return partial.v ? partial.t : partial; } function findOwner(ractive, key) { return hasOwn(ractive.partials, key) ? ractive : findConstructor(ractive.constructor, key); } function findConstructor(constructor, key) { if (!constructor) { return; } return hasOwn(constructor.partials, key) ? constructor : findConstructor(constructor.Parent, key); } function findParentPartial(name, parent) { if (parent) { if ( parent.template && parent.template.p && !isArray(parent.template.p) && hasOwn(parent.template.p, name) ) { return parent.template.p[name]; } else if (parent.up && parent.up.owner) { return findParentPartial(name, parent.up.owner); } } } function Partial(options) { MustacheContainer.call(this, options); var tpl = options.template; // yielder is a special form of partial that will later require special handling if (tpl.t === YIELDER) { this.yielder = 1; } else if (tpl.t === ELEMENT) { // this is a macro partial, complete with macro constructor // leaving this as an element will confuse up-template searches this.type = PARTIAL; this.macro = options.macro; } } var proto$6 = (Partial.prototype = create(MustacheContainer.prototype)); assign(proto$6, { constructor: Partial, bind: function bind() { var template = this.template; if (this.yielder) { // the container is the instance that owns this node this.container = this.up.ractive; this.component = this.container.component; this.containerFragment = this.up; // normal component if (this.component) { // yields skip the owning instance and go straight to the surrounding context this.up = this.component.up; // {{yield}} is equivalent to {{yield content}} if (!template.r && !template.x && !template.rx) { this.refName = 'content'; } } else { // plain-ish instance that may be attached to a parent later this.fragment = new Fragment({ owner: this, template: [] }); this.fragment.bind(); return; } } // this is a macro/super partial if (this.macro) { this.fn = this.macro; } else { // this is a plain partial or yielder if (!this.refName) { this.refName = template.r; } // if the refName exists as a partial, this is a plain old partial reference where no model binding will happen if (this.refName) { partialFromValue(this, this.refName); } // this is a dynamic/inline partial if (!this.partial && !this.fn) { MustacheContainer.prototype.bind.call(this); if (this.model) { partialFromValue(this, this.model.get()); } } } if (!this.partial && !this.fn) { warnOnceIfDebug(("Could not find template for partial '" + (this.name) + "'")); } createFragment(this, this.partial || []); // macro/super partial if (this.fn) { initMacro(this); } this.fragment.bind(); }, bubble: function bubble() { if (!this.dirty) { this.dirty = true; if (this.yielder) { this.containerFragment.bubble(); } else { this.up.bubble(); } } }, findNextNode: function findNextNode() { return (this.containerFragment || this.up).findNextNode(this); }, handleChange: function handleChange() { this.dirtyTemplate = true; this.externalChange = true; this.bubble(); }, rebound: function rebound(update) { var this$1 = this; var aliases = this.fragment && this.fragment.aliases; if (aliases) { for (var k in aliases) { if (aliases[k].rebound) { aliases[k].rebound(update); } else { aliases[k].unreference(); aliases[k] = 0; } } if (this.template.z) { resolveAliases(this.template.z, this.containerFragment || this.up, aliases); } } if (this._attrs) { keys(this._attrs).forEach(function (k) { return this$1._attrs[k].rebound(update); }); } MustacheContainer.prototype.rebound.call(this, update); }, refreshAttrs: function refreshAttrs() { var this$1 = this; keys(this._attrs).forEach(function (k) { this$1.handle.attributes[k] = !this$1._attrs[k].items.length || this$1._attrs[k].valueOf(); }); }, resetTemplate: function resetTemplate() { var this$1 = this; if (this.fn && this.proxy) { if (this.externalChange) { if (isFunction(this.proxy.teardown)) { this.proxy.teardown(); } this.fn = this.proxy = null; } else { this.partial = this.fnTemplate; return true; } } var partial = this.partial; this.partial = null; if (this.refName) { this.partial = getPartialTemplate(this.ractive, this.refName, this.up); } if (!this.partial && this.model) { partialFromValue(this, this.model.get()); } if (!this.fn && partial === this.partial) { return false; } this.unbindAttrs(); if (this.fn) { initMacro(this); if (isFunction(this.proxy.render)) { runloop.scheduleTask(function () { return this$1.proxy.render(); }); } } else if (!this.partial) { warnOnceIfDebug(("Could not find template for partial '" + (this.name) + "'")); } return true; }, render: function render(target, occupants) { if (this.fn && this.fn._cssDef && !this.fn._cssDef.applied) { applyCSS(); } this.fragment.render(target, occupants); if (this.proxy && isFunction(this.proxy.render)) { this.proxy.render(); } }, unbind: function unbind(view) { this.fragment.unbind(view); this.fragment.aliases = null; this.unbindAttrs(view); MustacheContainer.prototype.unbind.call(this, view); }, unbindAttrs: function unbindAttrs(view) { var this$1 = this; if (this._attrs) { keys(this._attrs).forEach(function (k) { this$1._attrs[k].unbind(view); }); } }, unrender: function unrender(shouldDestroy) { if (this.proxy && isFunction(this.proxy.teardown)) { this.proxy.teardown(); } this.fragment.unrender(shouldDestroy); }, update: function update() { var this$1 = this; var proxy = this.proxy; this.updating = 1; if (this.dirtyAttrs) { this.dirtyAttrs = false; keys(this._attrs).forEach(function (k) { return this$1._attrs[k].update(); }); this.refreshAttrs(); if (isFunction(proxy.update)) { proxy.update(this.handle.attributes); } } if (this.dirtyTemplate) { this.dirtyTemplate = false; this.resetTemplate() && this.fragment.resetTemplate(this.partial || []); } if (this.dirty) { this.dirty = false; if (proxy && isFunction(proxy.invalidate)) { proxy.invalidate(); } this.fragment.update(); } this.externalChange = false; this.updating = 0; } }); function createFragment(self, partial) { self.partial = partial; contextifyTemplate(self); var options = { owner: self, template: self.partial }; if (self.yielder) { options.ractive = self.container.parent; } if (self.fn) { options.cssIds = self.fn._cssIds; } var fragment = (self.fragment = new Fragment(options)); // partials may have aliases that need to be in place before binding if (self.template.z) { fragment.aliases = resolveAliases(self.template.z, self.containerFragment || self.up); } } function contextifyTemplate(self) { if (self.template.c) { self.partial = [{ t: SECTION, n: SECTION_WITH, f: self.partial }]; assign(self.partial[0], self.template.c); if (self.yielder) { self.partial[0].y = self; } } } function partialFromValue(self, value, okToParse) { var tpl = value; if (isArray(tpl)) { self.partial = tpl; } else if (tpl && isObjectType(tpl)) { if (isArray(tpl.t)) { self.partial = tpl.t; } else if (isString(tpl.template)) { self.partial = parsePartial(tpl.template, tpl.template, self.ractive).t; } } else if (isFunction(tpl) && tpl.styleSet) { self.fn = tpl; if (self.fragment) { self.fragment.cssIds = tpl._cssIds; } } else if (tpl != null) { tpl = getPartialTemplate(self.ractive, '' + tpl, self.containerFragment || self.up); if (tpl) { self.name = value; if (tpl.styleSet) { self.fn = tpl; if (self.fragment) { self.fragment.cssIds = tpl._cssIds; } } else { self.partial = tpl; } } else if (okToParse) { self.partial = parsePartial('' + value, '' + value, self.ractive).t; } else { self.name = value; } } return self.partial; } function setTemplate(template) { partialFromValue(this, template, true); if (!this.initing) { this.dirtyTemplate = true; this.fnTemplate = this.partial; if (this.updating) { this.bubble(); runloop.promise(); } else { var promise = runloop.start(); this.bubble(); runloop.end(); return promise; } } } function aliasLocal(ref, name) { var aliases = this.fragment.aliases || (this.fragment.aliases = {}); if (!name) { aliases[ref] = this._data; } else { aliases[name] = this._data.joinAll(splitKeypath(ref)); } } var extras = 'extra-attributes'; function initMacro(self) { var fn = self.fn; var fragment = self.fragment; // defensively copy the template in case it changes var template = (self.template = assign({}, self.template)); var handle = (self.handle = fragment.getContext({ proxy: self, aliasLocal: aliasLocal, name: self.template.e || self.name, attributes: {}, setTemplate: setTemplate.bind(self), template: template, macro: fn })); if (!template.p) { template.p = {}; } template.p = handle.partials = assign({}, template.p); if (!hasOwn(template.p, 'content')) { template.p.content = template.f || []; } if (isArray(fn.attributes)) { self._attrs = {}; var invalidate = function() { this.dirty = true; self.dirtyAttrs = true; self.bubble(); }; if (isArray(template.m)) { var attrs = template.m; template.p[extras] = template.m = attrs.filter(function (a) { return !~fn.attributes.indexOf(a.n); }); attrs .filter(function (a) { return ~fn.attributes.indexOf(a.n); }) .forEach(function (a) { var fragment = new Fragment({ template: a.f, owner: self }); fragment.bubble = invalidate; fragment.findFirstNode = noop; self._attrs[a.n] = fragment; }); } else { template.p[extras] = []; } } else { template.p[extras] = template.m; } if (self._attrs) { keys(self._attrs).forEach(function (k) { self._attrs[k].bind(); }); self.refreshAttrs(); } self.initing = 1; self.proxy = fn.call(self.ractive, handle, handle.attributes) || {}; if (!self.partial) { self.partial = []; } self.fnTemplate = self.partial; self.initing = 0; contextifyTemplate(self); fragment.resetTemplate(self.partial); } function parsePartial(name, partial, ractive) { var parsed; try { parsed = parser.parse(partial, parser.getParseOptions(ractive)); } catch (e) { warnIfDebug(("Could not parse partial from expression '" + name + "'\n" + (e.message))); } return parsed || { t: [] }; } var KeyModel = function KeyModel(value, context, instance) { this.value = this.key = value; this.context = context; this.isReadonly = this.isKey = true; this.deps = []; this.links = []; this.children = []; this.instance = instance; }; var KeyModel__proto__ = KeyModel.prototype; KeyModel__proto__.applyValue = function applyValue (value) { if (value !== this.value) { this.value = this.key = value; this.deps.forEach(handleChange); this.links.forEach(handleChange); this.children.forEach(function (c) { c.applyValue(c.context.getKeypath(c.instance)); }); } }; KeyModel__proto__.destroyed = function destroyed () { if (this.upstream) { this.upstream.unregisterChild(this); } }; KeyModel__proto__.get = function get (shouldCapture) { if (shouldCapture) { capture(this); } return unescapeKey(this.value); }; KeyModel__proto__.getKeypath = function getKeypath () { return unescapeKey(this.value); }; KeyModel__proto__.has = function has () { return false; }; KeyModel__proto__.rebind = function rebind (next, previous) { var this$1 = this; var i = this.deps.length; while (i--) { this$1.deps[i].rebind(next, previous, false); } i = this.links.length; while (i--) { this$1.links[i].relinking(next, false); } }; KeyModel__proto__.register = function register (dependant) { this.deps.push(dependant); }; KeyModel__proto__.registerChild = function registerChild (child) { addToArray(this.children, child); child.upstream = this; }; KeyModel__proto__.registerLink = function registerLink (link) { addToArray(this.links, link); }; KeyModel__proto__.unregister = function unregister (dependant) { removeFromArray(this.deps, dependant); }; KeyModel__proto__.unregisterChild = function unregisterChild (child) { removeFromArray(this.children, child); }; KeyModel__proto__.unregisterLink = function unregisterLink (link) { removeFromArray(this.links, link); }; KeyModel.prototype.reference = noop; KeyModel.prototype.unreference = noop; var keypathString = /^"(\\"|[^"])+"$/; var RepeatedFragment = function RepeatedFragment(options) { this.parent = options.owner.up; // bit of a hack, so reference resolution works without another // layer of indirection this.up = this; this.owner = options.owner; this.ractive = this.parent.ractive; this.delegate = this.ractive.delegate !== false && (this.parent.delegate || findDelegate(this.parent)); // delegation disabled by directive if (this.delegate && this.delegate.delegate === false) { this.delegate = false; } // let the element know it's a delegate handler if (this.delegate) { this.delegate.delegate = this.delegate; } // encapsulated styles should be inherited until they get applied by an element this.cssIds = 'cssIds' in options ? options.cssIds : this.parent ? this.parent.cssIds : null; this.context = null; this.rendered = false; this.iterations = []; this.template = options.template; this.indexRef = options.indexRef; this.keyRef = options.keyRef; this.pendingNewIndices = null; this.previousIterations = null; // track array versus object so updates of type rest this.isArray = false; }; var RepeatedFragment__proto__ = RepeatedFragment.prototype; RepeatedFragment__proto__.bind = function bind (context) { var this$1 = this; this.context = context; this.bound = true; var value = context.get(); var aliases = (this.aliases = this.owner.template.z && this.owner.template.z.slice()); var shuffler = aliases && aliases.find(function (a) { return a.n === 'shuffle'; }); if (shuffler && shuffler.x && shuffler.x.x) { if (shuffler.x.x.s === 'true') { this.shuffler = true; } else if (keypathString.test(shuffler.x.x.s)) { this.shuffler = splitKeypath(shuffler.x.x.s.slice(1, -1)); } } if (this.shuffler) { this.values = shuffleValues(this, this.shuffler); } if (this.source) { this.source.model.unbind(this.source); } var source = context.isComputed && aliases && aliases.find(function (a) { return a.n === 'source'; }); if (source && source.x && source.x.r) { var model = resolve(this, source.x); this.source = { handleChange: function handleChange() {}, rebind: function rebind(next) { this.model.unregister(this); this.model = next; next.register(this); } }; this.source.model = model; model.register(this.source); } // {{#each array}}... if ((this.isArray = isArray(value))) { // we can't use map, because of sparse arrays this.iterations = []; var max = (this.length = value.length); for (var i = 0; i < max; i += 1) { this$1.iterations[i] = this$1.createIteration(i, i); } } else if (isObject(value)) { // {{#each object}}... this.isArray = false; // TODO this is a dreadful hack. There must be a neater way if (this.indexRef) { var refs = this.indexRef.split(','); this.keyRef = refs[0]; this.indexRef = refs[1]; } var ks = keys(value); this.length = ks.length; this.iterations = ks.map(function (key, index) { return this$1.createIteration(key, index); }); } return this; }; RepeatedFragment__proto__.bubble = function bubble (index) { if (!this.bubbled) { this.bubbled = []; } this.bubbled.push(index); if (!this.rebounding) { this.owner.bubble(); } }; RepeatedFragment__proto__.createIteration = function createIteration (key, index) { var fragment = new Fragment({ owner: this, template: this.template }); fragment.isIteration = true; fragment.delegate = this.delegate; if (this.aliases) { fragment.aliases = {}; } swizzleFragment(this, fragment, key, index); return fragment.bind(fragment.context); }; RepeatedFragment__proto__.destroyed = function destroyed () { var this$1 = this; var len = this.iterations.length; for (var i = 0; i < len; i++) { this$1.iterations[i].destroyed(); } if (this.pathModel) { this.pathModel.destroyed(); } if (this.rootModel) { this.rootModel.destroyed(); } }; RepeatedFragment__proto__.detach = function detach () { var docFrag = createDocumentFragment(); this.iterations.forEach(function (fragment) { return docFrag.appendChild(fragment.detach()); }); return docFrag; }; RepeatedFragment__proto__.find = function find (selector, options) { return findMap(this.iterations, function (i) { return i.find(selector, options); }); }; RepeatedFragment__proto__.findAll = function findAll (selector, options) { return this.iterations.forEach(function (i) { return i.findAll(selector, options); }); }; RepeatedFragment__proto__.findAllComponents = function findAllComponents (name, options) { return this.iterations.forEach(function (i) { return i.findAllComponents(name, options); }); }; RepeatedFragment__proto__.findComponent = function findComponent (name, options) { return findMap(this.iterations, function (i) { return i.findComponent(name, options); }); }; RepeatedFragment__proto__.findContext = function findContext () { return this.context; }; RepeatedFragment__proto__.findNextNode = function findNextNode (iteration) { var this$1 = this; if (iteration.index < this.iterations.length - 1) { for (var i = iteration.index + 1; i < this.iterations.length; i++) { var node = this$1.iterations[i].firstNode(true); if (node) { return node; } } } return this.owner.findNextNode(); }; RepeatedFragment__proto__.firstNode = function firstNode (skipParent) { return this.iterations[0] ? this.iterations[0].firstNode(skipParent) : null; }; RepeatedFragment__proto__.getLast = function getLast () { return this.lastModel || (this.lastModel = new KeyModel(this.length - 1)); }; RepeatedFragment__proto__.rebind = function rebind (next) { var this$1 = this; this.context = next; if (this.source) { return; } this.iterations.forEach(function (fragment) { swizzleFragment(this$1, fragment, fragment.key, fragment.index); }); }; RepeatedFragment__proto__.rebound = function rebound (update$$1) { var this$1 = this; this.context = this.owner.model; this.iterations.forEach(function (f, i) { f.context = contextFor(this$1, f, i); f.rebound(update$$1); }); }; RepeatedFragment__proto__.render = function render (target, occupants) { var xs = this.iterations; if (xs) { var len = xs.length; for (var i = 0; i < len; i++) { xs[i].render(target, occupants); } } this.rendered = true; }; RepeatedFragment__proto__.shuffle = function shuffle (newIndices, merge) { var this$1 = this; if (!this.pendingNewIndices) { this.previousIterations = this.iterations.slice(); } if (!this.pendingNewIndices) { this.pendingNewIndices = []; } this.pendingNewIndices.push(newIndices); var iterations = []; newIndices.forEach(function (newIndex, oldIndex) { if (newIndex === -1) { return; } var fragment = this$1.iterations[oldIndex]; iterations[newIndex] = fragment; if (newIndex !== oldIndex && fragment) { fragment.dirty = true; if (merge) { fragment.shouldRebind = 1; } } }); this.iterations = iterations; // if merging, we're in the midst of an update already if (!merge) { this.bubble(); } }; RepeatedFragment__proto__.shuffled = function shuffled$1 () { this.iterations.forEach(shuffled); }; RepeatedFragment__proto__.toString = function toString (escape) { return this.iterations ? this.iterations.map(escape ? toEscapedString : toString$1).join('') : ''; }; RepeatedFragment__proto__.unbind = function unbind (view) { this.bound = false; if (this.source) { this.source.model.unregister(this.source); } var iterations = this.pendingNewIndices ? this.previousIterations : this.iterations; var len = iterations.length; for (var i = 0; i < len; i++) { iterations[i].unbind(view); } return this; }; RepeatedFragment__proto__.unrender = function unrender (shouldDestroy) { var this$1 = this; var len = this.iterations.length; for (var i = 0; i < len; i++) { this$1.iterations[i].unrender(shouldDestroy); } if (this.pendingNewIndices && this.previousIterations) { len = this.previousIterations.length; for (var i$1 = 0; i$1 < len; i$1++) { this$1.previousIterations[i$1].unrender(shouldDestroy); } } this.rendered = false; }; RepeatedFragment__proto__.update = function update () { var this$1 = this; if (this.pendingNewIndices) { this.bubbled.length = 0; this.updatePostShuffle(); return; } if (this.updating) { return; } this.updating = true; if (this.shuffler) { var values = shuffleValues(this, this.shuffler); this.shuffle(buildNewIndices(this.values, values), true); this.updatePostShuffle(); } else { var len = this.iterations.length; for (var i = 0; i < len; i++) { var f = this$1.iterations[i]; f && f.idxModel && f.idxModel.applyValue(i); } var value = this.context.get(); var wasArray = this.isArray; var toRemove; var oldKeys; var reset = true; var i$1; if ((this.isArray = isArray(value))) { // if there's a source to map back to, make sure everything stays bound correctly if (this.source) { this.rebounding = 1; var source = this.source.model.get(); this.iterations.forEach(function (f, c) { if (c < value.length && f.lastValue !== value[c] && ~(i$1 = source.indexOf(value[c]))) { swizzleFragment(this$1, f, c, c); f.rebound(true); } }); this.rebounding = 0; } if (wasArray) { reset = false; if (this.iterations.length > value.length) { toRemove = this.iterations.splice(value.length); } } } else if (isObject(value) && !wasArray) { reset = false; toRemove = []; oldKeys = {}; i$1 = this.iterations.length; while (i$1--) { var fragment = this$1.iterations[i$1]; if (fragment.key in value) { oldKeys[fragment.key] = true; } else { this$1.iterations.splice(i$1, 1); toRemove.push(fragment); } } } var newLength = isArray(value) ? value.length : isObject(value) ? keys(value).length : 0; this.length = newLength; this.updateLast(); if (reset) { toRemove = this.iterations; this.iterations = []; } if (toRemove) { len = toRemove.length; for (var i$2 = 0; i$2 < len; i$2++) { toRemove[i$2].unbind().unrender(true); } } // update the remaining ones if (!reset && this.isArray && this.bubbled && this.bubbled.length) { var bubbled = this.bubbled; this.bubbled = []; len = bubbled.length; for (var i$3 = 0; i$3 < len; i$3++) { this$1.iterations[bubbled[i$3]] && this$1.iterations[bubbled[i$3]].update(); } } else { len = this.iterations.length; for (var i$4 = 0; i$4 < len; i$4++) { this$1.iterations[i$4].update(); } } // add new iterations var docFrag; var fragment$1; if (newLength > this.iterations.length) { docFrag = this.rendered ? createDocumentFragment() : null; i$1 = this.iterations.length; if (isArray(value)) { while (i$1 < value.length) { fragment$1 = this$1.createIteration(i$1, i$1); this$1.iterations.push(fragment$1); if (this$1.rendered) { fragment$1.render(docFrag); } i$1 += 1; } } else if (isObject(value)) { // TODO this is a dreadful hack. There must be a neater way if (this.indexRef && !this.keyRef) { var refs = this.indexRef.split(','); this.keyRef = refs[0]; this.indexRef = refs[1]; } keys(value).forEach(function (key) { if (!oldKeys || !(key in oldKeys)) { fragment$1 = this$1.createIteration(key, i$1); this$1.iterations.push(fragment$1); if (this$1.rendered) { fragment$1.render(docFrag); } i$1 += 1; } }); } if (this.rendered) { var parentNode = this.parent.findParentNode(); var anchor = this.parent.findNextNode(this.owner); parentNode.insertBefore(docFrag, anchor); } } } this.updating = false; }; RepeatedFragment__proto__.updateLast = function updateLast () { if (this.lastModel) { this.lastModel.applyValue(this.length - 1); } }; RepeatedFragment__proto__.updatePostShuffle = function updatePostShuffle () { var this$1 = this; var newIndices = this.pendingNewIndices[0]; var parentNode = this.rendered ? this.parent.findParentNode() : null; var nextNode = parentNode && this.owner.findNextNode(); var docFrag = parentNode ? createDocumentFragment() : null; // map first shuffle through this.pendingNewIndices.slice(1).forEach(function (indices) { newIndices.forEach(function (newIndex, oldIndex) { newIndices[oldIndex] = indices[newIndex]; }); }); var len = (this.length = this.context.get().length); var prev = this.previousIterations; var iters = this.iterations; var value = this.context.get(); var stash = {}; var idx, dest, pos, next, anchor, rebound; var map = new Array(newIndices.length); newIndices.forEach(function (e, i) { return (map[e] = i); }); this.updateLast(); idx = pos = 0; while (idx < len) { dest = newIndices[pos]; next = null; rebound = false; if (dest === -1) { // drop it like it's hot prev[pos].unbind().unrender(true); prev[pos++] = 0; } else if (dest > idx) { // need to stash or pull one up next = newIndices[pos + 1]; // TODO: maybe a shouldMove function that tracks multiple entries? if (next <= dest) { stash[dest] = prev[pos]; prev[pos++] = null; } else { next = stash[idx] || prev[map[idx]]; prev[map[idx]] = null; anchor = prev[nextRendered(pos, newIndices, prev)]; anchor = (anchor && parentNode && anchor.firstNode()) || nextNode; if (next) { rebound = this$1.source && next.lastValue !== value[idx]; swizzleFragment(this$1, next, idx, idx); if (parentNode) { parentNode.insertBefore(next.detach(), anchor); } } else { next = iters[idx] = this$1.createIteration(idx, idx); if (parentNode) { next.render(docFrag); parentNode.insertBefore(docFrag, anchor); } } idx++; } } else { // all is well next = iters[idx]; anchor = prev[nextRendered(pos, newIndices, prev)]; anchor = (anchor && parentNode && anchor.firstNode()) || nextNode; if (!next) { next = iters[idx] = this$1.createIteration(idx, idx); if (parentNode) { next.render(docFrag); parentNode.insertBefore(docFrag, anchor); } } else if (pos !== idx || stash[idx]) { rebound = this$1.source && next.lastValue !== value[idx]; swizzleFragment(this$1, next, idx, idx); if (stash[idx] && parentNode) { parentNode.insertBefore(next.detach(), anchor); } } idx++; prev[pos++] = null; } if (next && isObjectType(next)) { if (next.shouldRebind || rebound) { next.rebound(rebound); next.shouldRebind = 0; } next.update(); next.shuffled(); } } // clean up any stragglers var plen = prev.length; for (var i = 0; i < plen; i++) { prev[i] && prev[i].unbind().unrender(true); } if (this.shuffler) { this.values = shuffleValues(this, this.shuffler); } this.pendingNewIndices = null; this.previousIterations = null; }; RepeatedFragment.prototype.getContext = getContext; RepeatedFragment.prototype.getKeypath = getKeypath; // find the topmost delegate function findDelegate(start) { var frag = start; var delegate, el; out: while (frag) { // find next element el = 0; while (!el && frag) { if (frag.owner.type === ELEMENT) { el = frag.owner; } if (frag.owner.ractive && frag.owner.ractive.delegate === false) { break out; } frag = frag.parent || frag.componentParent; } if (el.delegate === false) { break out; } delegate = el.delegate || el; // find next repeated fragment while (frag) { if (frag.iterations) { break; } if (frag.owner.ractive && frag.owner.ractive.delegate === false) { break out; } frag = frag.parent || frag.componentParent; } } return delegate; } function nextRendered(start, newIndices, frags) { var len = newIndices.length; for (var i = start; i < len; i++) { if (~newIndices[i] && frags[i] && frags[i].rendered) { return i; } } } function swizzleFragment(section, fragment, key, idx) { var model = section.context ? contextFor(section, fragment, key) : undefined; fragment.key = key; fragment.index = idx; fragment.context = model; if (section.source) { fragment.lastValue = model && model.get(); } if (fragment.idxModel) { fragment.idxModel.applyValue(idx); } if (fragment.keyModel) { fragment.keyModel.applyValue(key); } if (fragment.pathModel) { fragment.pathModel.context = model; fragment.pathModel.applyValue(model.getKeypath()); } if (fragment.rootModel) { fragment.rootModel.context = model; fragment.rootModel.applyValue(model.getKeypath(fragment.ractive.root)); } // handle any aliases var aliases = fragment.aliases; section.aliases && section.aliases.forEach(function (a) { if (a.x.r === '.') { aliases[a.n] = model; } else if (a.x.r === '@index') { aliases[a.n] = fragment.getIndex(); } else if (a.x.r === '@key') { aliases[a.n] = fragment.getKey(); } else if (a.x.r === '@keypath') { aliases[a.n] = fragment.getKeypath(); } else if (a.x.r === '@rootpath') { aliases[a.n] = fragment.getKeypath(true); } }); } function shuffleValues(section, shuffler) { if (shuffler === true) { return section.context.get().slice(); } else { return section.context.get().map(function (v) { return shuffler.reduce(function (a, c) { return a && a[c]; }, v); }); } } function contextFor(section, fragment, key) { if (section.source) { var idx; var source = section.source.model.get(); if (source.indexOf && ~(idx = source.indexOf(section.context.joinKey(key).get()))) { return section.source.model.joinKey(idx); } } return section.context.joinKey(key); } function isEmpty(value) { return ( !value || (isArray(value) && value.length === 0) || (isObject(value) && keys(value).length === 0) ); } function getType(value, hasIndexRef) { if (hasIndexRef || isArray(value)) { return SECTION_EACH; } if (isObjectLike(value)) { return SECTION_IF_WITH; } if (value === undefined) { return null; } return SECTION_IF; } var Section = (function (MustacheContainer) { function Section(options) { MustacheContainer.call(this, options); this.sectionType = options.template.n || null; this.templateSectionType = this.sectionType; this.subordinate = options.template.l === 1; this.fragment = null; } if ( MustacheContainer ) Section.__proto__ = MustacheContainer; var Section__proto__ = Section.prototype = Object.create( MustacheContainer && MustacheContainer.prototype ); Section__proto__.constructor = Section; Section__proto__.bind = function bind () { MustacheContainer.prototype.bind.call(this); if (this.subordinate) { this.sibling = this.up.items[this.up.items.indexOf(this) - 1]; this.sibling.nextSibling = this; } // if we managed to bind, we need to create children if (this.model) { this.dirty = true; this.update(); } else if ( this.sectionType && this.sectionType === SECTION_UNLESS && (!this.sibling || !this.sibling.isTruthy()) ) { this.fragment = new Fragment({ owner: this, template: this.template.f }).bind(); } }; Section__proto__.bubble = function bubble () { if (!this.dirty && this.yield) { this.dirty = true; this.containerFragment.bubble(); } else { MustacheContainer.prototype.bubble.call(this); } }; Section__proto__.detach = function detach () { var frag = this.fragment || this.detached; return frag ? frag.detach() : MustacheContainer.prototype.detach.call(this); }; Section__proto__.isTruthy = function isTruthy () { if (this.subordinate && this.sibling.isTruthy()) { return true; } var value = !this.model ? undefined : this.model.isRoot ? this.model.value : this.model.get(); return !!value && (this.templateSectionType === SECTION_IF_WITH || !isEmpty(value)); }; Section__proto__.rebind = function rebind (next, previous, safe) { if (MustacheContainer.prototype.rebind.call(this, next, previous, safe)) { if (this.fragment && this.sectionType !== SECTION_IF && this.sectionType !== SECTION_UNLESS) { this.fragment.rebind(next); } } }; Section__proto__.rebound = function rebound (update) { if (this.model) { if (this.model.rebound) { this.model.rebound(update); } else { MustacheContainer.prototype.unbind.call(this); MustacheContainer.prototype.bind.call(this); if ( this.sectionType === SECTION_WITH || this.sectionType === SECTION_IF_WITH || this.sectionType === SECTION_EACH ) { if (this.fragment) { this.fragment.rebind(this.model); } } if (update) { this.bubble(); } } } if (this.fragment) { this.fragment.rebound(update); } }; Section__proto__.render = function render (target, occupants) { this.rendered = true; if (this.fragment) { this.fragment.render(target, occupants); } }; Section__proto__.shuffle = function shuffle (newIndices) { if (this.fragment && this.sectionType === SECTION_EACH) { this.fragment.shuffle(newIndices); } }; Section__proto__.unbind = function unbind (view) { MustacheContainer.prototype.unbind.call(this, view); if (this.fragment) { this.fragment.unbind(view); } }; Section__proto__.unrender = function unrender (shouldDestroy) { if (this.rendered && this.fragment) { this.fragment.unrender(shouldDestroy); } this.rendered = false; }; Section__proto__.update = function update () { var this$1 = this; if (!this.dirty) { return; } if (this.fragment && this.sectionType !== SECTION_IF && this.sectionType !== SECTION_UNLESS) { this.fragment.context = this.model; } if (!this.model && this.sectionType !== SECTION_UNLESS) { return; } this.dirty = false; var value = !this.model ? undefined : this.model.isRoot ? this.model.value : this.model.get(); var siblingFalsey = !this.subordinate || !this.sibling.isTruthy(); var lastType = this.sectionType; if (this.yield && this.yield !== value) { this.up = this.containerFragment; this.container = null; this.yield = null; if (this.rendered) { this.fragment.unbind().unrender(true); } this.fragment = null; } else if (this.rendered && !this.yield && value instanceof Context) { if (this.rendered) { this.fragment.unbind().unrender(true); } this.fragment = null; } // watch for switching section types if (this.sectionType === null || this.templateSectionType === null) { this.sectionType = getType(value, this.template.i); } if (lastType && lastType !== this.sectionType && this.fragment) { if (this.rendered) { this.fragment.unbind().unrender(true); } this.fragment = null; } var newFragment; var fragmentShouldExist = this.sectionType === SECTION_EACH || // each always gets a fragment, which may have no iterations this.sectionType === SECTION_WITH || // with (partial context) always gets a fragment (siblingFalsey && (this.sectionType === SECTION_UNLESS ? !this.isTruthy() : this.isTruthy())); // if, unless, and if-with depend on siblings and the condition if (fragmentShouldExist) { if (!this.fragment) { this.fragment = this.detached; } if (this.fragment) { // check for detached fragment if (this.detached) { attach(this, this.fragment); this.detached = false; this.rendered = true; } if (!this.fragment.bound) { this.fragment.bind(this.model); } this.fragment.update(); } else { if (this.sectionType === SECTION_EACH) { newFragment = new RepeatedFragment({ owner: this, template: this.template.f, indexRef: this.template.i }).bind(this.model); } else { // only with and if-with provide context - if and unless do not var context = this.sectionType !== SECTION_IF && this.sectionType !== SECTION_UNLESS ? this.model : null; if (value instanceof Context) { this.yield = value; this.containerFragment = this.up; this.up = value.fragment; this.container = value.ractive; context = undefined; } newFragment = new Fragment({ owner: this, template: this.template.f }).bind(context); } } } else { if (this.fragment && this.rendered) { if (keep !== true) { this.fragment.unbind().unrender(true); } else { this.unrender(false); this.detached = this.fragment; runloop.promise().then(function () { if (this$1.detached) { this$1.detach(); } }); } } else if (this.fragment) { this.fragment.unbind(); } this.fragment = null; } if (newFragment) { if (this.rendered) { attach(this, newFragment); } this.fragment = newFragment; } if (this.nextSibling) { this.nextSibling.dirty = true; this.nextSibling.update(); } }; return Section; }(MustacheContainer)); function attach(section, fragment) { var anchor = (section.containerFragment || section.up).findNextNode(section); if (anchor) { var docFrag = createDocumentFragment(); fragment.render(docFrag); anchor.parentNode.insertBefore(docFrag, anchor); } else { fragment.render(section.up.findParentNode()); } } var Select = (function (Element) { function Select(options) { Element.call(this, options); this.options = []; } if ( Element ) Select.__proto__ = Element; var Select__proto__ = Select.prototype = Object.create( Element && Element.prototype ); Select__proto__.constructor = Select; Select__proto__.foundNode = function foundNode (node) { if (this.binding) { var selectedOptions = getSelectedOptions(node); if (selectedOptions.length > 0) { this.selectedOptions = selectedOptions; } } }; Select__proto__.render = function render (target, occupants) { Element.prototype.render.call(this, target, occupants); this.sync(); var node = this.node; var i = node.options.length; while (i--) { node.options[i].defaultSelected = node.options[i].selected; } this.rendered = true; }; Select__proto__.sync = function sync () { var this$1 = this; var selectNode = this.node; if (!selectNode) { return; } var options = toArray(selectNode.options); if (this.selectedOptions) { options.forEach(function (o) { if (this$1.selectedOptions.indexOf(o) >= 0) { o.selected = true; } else { o.selected = false; } }); this.binding.setFromNode(selectNode); delete this.selectedOptions; return; } var selectValue = this.getAttribute('value'); var isMultiple = this.getAttribute('multiple'); var array = isMultiple && isArray(selectValue); // If the <select> has a specified value, that should override // these options if (selectValue !== undefined) { var optionWasSelected; options.forEach(function (o) { var optionValue = o._ractive ? o._ractive.value : o.value; var shouldSelect = isMultiple ? array && this$1.valueContains(selectValue, optionValue) : this$1.compare(selectValue, optionValue); if (shouldSelect) { optionWasSelected = true; } o.selected = shouldSelect; }); if (!optionWasSelected && !isMultiple) { if (this.binding) { this.binding.forceUpdate(); } } } else if (this.binding && this.binding.forceUpdate) { // Otherwise the value should be initialised according to which // <option> element is selected, if twoway binding is in effect this.binding.forceUpdate(); } }; Select__proto__.valueContains = function valueContains (selectValue, optionValue) { var this$1 = this; var i = selectValue.length; while (i--) { if (this$1.compare(optionValue, selectValue[i])) { return true; } } }; Select__proto__.compare = function compare (optionValue, selectValue) { var comparator = this.getAttribute('value-comparator'); if (comparator) { if (isFunction(comparator)) { return comparator(selectValue, optionValue); } if (selectValue && optionValue) { return selectValue[comparator] == optionValue[comparator]; } } return selectValue == optionValue; }; Select__proto__.update = function update () { var dirty = this.dirty; Element.prototype.update.call(this); if (dirty) { this.sync(); } }; return Select; }(Element)); var Textarea = (function (Input) { function Textarea(options) { var template = options.template; options.deferContent = true; Input.call(this, options); // check for single interpolator binding if (!this.attributeByName.value) { if (template.f && isBindable({ template: template })) { (this.attributes || (this.attributes = [])).push( createItem({ owner: this, template: { t: ATTRIBUTE, f: template.f, n: 'value' }, up: this.up }) ); } else { this.fragment = new Fragment({ owner: this, cssIds: null, template: template.f }); } } } if ( Input ) Textarea.__proto__ = Input; var Textarea__proto__ = Textarea.prototype = Object.create( Input && Input.prototype ); Textarea__proto__.constructor = Textarea; Textarea__proto__.bubble = function bubble () { var this$1 = this; if (!this.dirty) { this.dirty = true; if (this.rendered && !this.binding && this.fragment) { runloop.scheduleTask(function () { this$1.dirty = false; this$1.node.value = this$1.fragment.toString(); }); } this.up.bubble(); // default behaviour } }; return Textarea; }(Input)); var Text = (function (Item) { function Text(options) { Item.call(this, options); this.type = TEXT; } if ( Item ) Text.__proto__ = Item; var Text__proto__ = Text.prototype = Object.create( Item && Item.prototype ); Text__proto__.constructor = Text; Text__proto__.detach = function detach () { return detachNode(this.node); }; Text__proto__.firstNode = function firstNode () { return this.node; }; Text__proto__.render = function render (target, occupants) { if (inAttributes()) { return; } this.rendered = true; progressiveText(this, target, occupants, this.template); }; Text__proto__.toString = function toString (escape) { return escape ? escapeHtml(this.template) : this.template; }; Text__proto__.unrender = function unrender (shouldDestroy) { if (this.rendered && shouldDestroy) { this.detach(); } this.rendered = false; }; Text__proto__.valueOf = function valueOf () { return this.template; }; return Text; }(Item)); var proto$7 = Text.prototype; proto$7.bind = proto$7.unbind = proto$7.update = noop; var visible; var hidden = 'hidden'; if (doc) { var prefix$2; /* istanbul ignore next */ if (hidden in doc) { prefix$2 = ''; } else { var i$1 = vendors.length; while (i$1--) { var vendor = vendors[i$1]; hidden = vendor + 'Hidden'; if (hidden in doc) { prefix$2 = vendor; break; } } } /* istanbul ignore else */ if (prefix$2 !== undefined) { doc.addEventListener(prefix$2 + 'visibilitychange', onChange); onChange(); } else { // gah, we're in an old browser if ('onfocusout' in doc) { doc.addEventListener('focusout', onHide); doc.addEventListener('focusin', onShow); } else { win.addEventListener('pagehide', onHide); win.addEventListener('blur', onHide); win.addEventListener('pageshow', onShow); win.addEventListener('focus', onShow); } visible = true; // until proven otherwise. Not ideal but hey } } function onChange() { visible = !doc[hidden]; } /* istanbul ignore next */ function onHide() { visible = false; } /* istanbul ignore next */ function onShow() { visible = true; } var prefix; /* istanbul ignore next */ if (!isClient) { prefix = null; } else { var prefixCache = {}; var testStyle = createElement('div').style; // technically this also normalizes on hyphenated styles as well prefix = function(prop) { if (!prefixCache[prop]) { var name = hyphenateCamel(prop); if (testStyle[prop] !== undefined) { prefixCache[prop] = name; } else { /* istanbul ignore next */ // test vendors... var i = vendors.length; while (i--) { var vendor = "-" + (vendors[i]) + "-" + name; if (testStyle[vendor] !== undefined) { prefixCache[prop] = vendor; break; } } } } return prefixCache[prop]; }; } var prefix$1 = prefix; var vendorPattern = new RegExp('^(?:' + vendors.join('|') + ')([A-Z])'); function hyphenate(str) { /* istanbul ignore next */ if (!str) { return ''; } // edge case /* istanbul ignore next */ if (vendorPattern.test(str)) { str = '-' + str; } return str.replace(/[A-Z]/g, function (match) { return '-' + match.toLowerCase(); }); } var createTransitions; if (!isClient) { createTransitions = null; } else { var testStyle$1 = createElement('div').style; var linear$1 = function (x) { return x; }; var canUseCssTransitions = {}; var cannotUseCssTransitions = {}; // determine some facts about our environment var TRANSITION$1; var TRANSITIONEND; var CSS_TRANSITIONS_ENABLED; var TRANSITION_DURATION; var TRANSITION_PROPERTY; var TRANSITION_TIMING_FUNCTION; if (testStyle$1.transition !== undefined) { TRANSITION$1 = 'transition'; TRANSITIONEND = 'transitionend'; CSS_TRANSITIONS_ENABLED = true; } else if (testStyle$1.webkitTransition !== undefined) { TRANSITION$1 = 'webkitTransition'; TRANSITIONEND = 'webkitTransitionEnd'; CSS_TRANSITIONS_ENABLED = true; } else { CSS_TRANSITIONS_ENABLED = false; } if (TRANSITION$1) { TRANSITION_DURATION = TRANSITION$1 + 'Duration'; TRANSITION_PROPERTY = TRANSITION$1 + 'Property'; TRANSITION_TIMING_FUNCTION = TRANSITION$1 + 'TimingFunction'; } createTransitions = function(t, to, options, changedProperties, resolve) { // Wait a beat (otherwise the target styles will be applied immediately) // TODO use a fastdom-style mechanism? setTimeout(function () { var jsTransitionsComplete; var cssTransitionsComplete; var cssTimeout; // eslint-disable-line prefer-const function transitionDone() { clearTimeout(cssTimeout); } function checkComplete() { if (jsTransitionsComplete && cssTransitionsComplete) { t.unregisterCompleteHandler(transitionDone); // will changes to events and fire have an unexpected consequence here? t.ractive.fire(t.name + ':end', t.node, t.isIntro); resolve(); } } // this is used to keep track of which elements can use CSS to animate // which properties var hashPrefix = (t.node.namespaceURI || '') + t.node.tagName; // need to reset transition properties var style = t.node.style; var previous = { property: style[TRANSITION_PROPERTY], timing: style[TRANSITION_TIMING_FUNCTION], duration: style[TRANSITION_DURATION] }; function transitionEndHandler(event) { var index = changedProperties.indexOf(event.propertyName); if (index !== -1) { changedProperties.splice(index, 1); } if (changedProperties.length) { // still transitioning... return; } clearTimeout(cssTimeout); cssTransitionsDone(); } function cssTransitionsDone() { style[TRANSITION_PROPERTY] = previous.property; style[TRANSITION_TIMING_FUNCTION] = previous.duration; style[TRANSITION_DURATION] = previous.timing; t.node.removeEventListener(TRANSITIONEND, transitionEndHandler, false); cssTransitionsComplete = true; checkComplete(); } t.node.addEventListener(TRANSITIONEND, transitionEndHandler, false); // safety net in case transitionend never fires cssTimeout = setTimeout(function () { changedProperties = []; cssTransitionsDone(); }, options.duration + (options.delay || 0) + 50); t.registerCompleteHandler(transitionDone); style[TRANSITION_PROPERTY] = changedProperties.join(','); var easingName = hyphenate(options.easing || 'linear'); style[TRANSITION_TIMING_FUNCTION] = easingName; var cssTiming = style[TRANSITION_TIMING_FUNCTION] === easingName; style[TRANSITION_DURATION] = options.duration / 1000 + 's'; setTimeout(function () { var i = changedProperties.length; var hash; var originalValue = null; var index; var propertiesToTransitionInJs = []; var prop; var suffix; var interpolator; while (i--) { prop = changedProperties[i]; hash = hashPrefix + prop; if (cssTiming && CSS_TRANSITIONS_ENABLED && !cannotUseCssTransitions[hash]) { var initial = style[prop]; style[prop] = to[prop]; // If we're not sure if CSS transitions are supported for // this tag/property combo, find out now if (!(hash in canUseCssTransitions)) { originalValue = t.getStyle(prop); // if this property is transitionable in this browser, // the current style will be different from the target style canUseCssTransitions[hash] = t.getStyle(prop) != to[prop]; cannotUseCssTransitions[hash] = !canUseCssTransitions[hash]; // Reset, if we're going to use timers after all if (cannotUseCssTransitions[hash]) { style[prop] = initial; } } } if (!cssTiming || !CSS_TRANSITIONS_ENABLED || cannotUseCssTransitions[hash]) { // we need to fall back to timer-based stuff if (originalValue === null) { originalValue = t.getStyle(prop); } // need to remove this from changedProperties, otherwise transitionEndHandler // will get confused index = changedProperties.indexOf(prop); if (index === -1) { warnIfDebug( 'Something very strange happened with transitions. Please raise an issue at https://github.com/ractivejs/ractive/issues - thanks!', { node: t.node } ); } else { changedProperties.splice(index, 1); } // TODO Determine whether this property is animatable at all suffix = /[^\d]*$/.exec(originalValue)[0]; interpolator = interpolate(parseFloat(originalValue), parseFloat(to[prop])); // ...then kick off a timer-based transition if (interpolator) { propertiesToTransitionInJs.push({ name: prop, interpolator: interpolator, suffix: suffix }); } else { style[prop] = to[prop]; } originalValue = null; } } // javascript transitions if (propertiesToTransitionInJs.length) { var easing; if (isString(options.easing)) { easing = t.ractive.easing[options.easing]; if (!easing) { warnOnceIfDebug(missingPlugin(options.easing, 'easing')); easing = linear$1; } } else if (isFunction(options.easing)) { easing = options.easing; } else { easing = linear$1; } new Ticker({ duration: options.duration, easing: easing, step: function step(pos) { var i = propertiesToTransitionInJs.length; while (i--) { var prop = propertiesToTransitionInJs[i]; style[prop.name] = prop.interpolator(pos) + prop.suffix; } }, complete: function complete() { jsTransitionsComplete = true; checkComplete(); } }); } else { jsTransitionsComplete = true; } if (changedProperties.length) { style[TRANSITION_PROPERTY] = changedProperties.join(','); } else { style[TRANSITION_PROPERTY] = 'none'; // We need to cancel the transitionEndHandler, and deal with // the fact that it will never fire t.node.removeEventListener(TRANSITIONEND, transitionEndHandler, false); cssTransitionsComplete = true; checkComplete(); } }, 0); }, options.delay || 0); }; } var createTransitions$1 = createTransitions; var getComputedStyle = win && win.getComputedStyle; var resolved = Promise.resolve(); var names = { t0: 'intro-outro', t1: 'intro', t2: 'outro' }; var Transition = function Transition(options) { this.owner = options.owner || options.up.owner || findElement(options.up); this.element = this.owner.attributeByName ? this.owner : findElement(options.up); this.ractive = this.owner.ractive; this.template = options.template; this.up = options.up; this.options = options; this.onComplete = []; }; var Transition__proto__ = Transition.prototype; Transition__proto__.animateStyle = function animateStyle (style, value, options) { var this$1 = this; if (arguments.length === 4) { throw new Error( 't.animateStyle() returns a promise - use .then() instead of passing a callback' ); } // Special case - page isn't visible. Don't animate anything, because // that way you'll never get CSS transitionend events if (!visible) { this.setStyle(style, value); return resolved; } var to; if (isString(style)) { to = {}; to[style] = value; } else { to = style; // shuffle arguments options = value; } return new Promise(function (fulfil) { // Edge case - if duration is zero, set style synchronously and complete if (!options.duration) { this$1.setStyle(to); fulfil(); return; } // Get a list of the properties we're animating var propertyNames = keys(to); var changedProperties = []; // Store the current styles var computedStyle = getComputedStyle(this$1.node); var i = propertyNames.length; while (i--) { var prop = propertyNames[i]; var name = prefix$1(prop); var current = computedStyle[prefix$1(prop)]; // record the starting points var init = this$1.node.style[name]; if (!(name in this$1.originals)) { this$1.originals[name] = this$1.node.style[name]; } this$1.node.style[name] = to[prop]; this$1.targets[name] = this$1.node.style[name]; this$1.node.style[name] = init; // we need to know if we're actually changing anything if (current != to[prop]) { // use != instead of !==, so we can compare strings with numbers changedProperties.push(name); // if we happened to prefix, make sure there is a properly prefixed value to[name] = to[prop]; // make the computed style explicit, so we can animate where // e.g. height='auto' this$1.node.style[name] = current; } } // If we're not actually changing anything, the transitionend event // will never fire! So we complete early if (!changedProperties.length) { fulfil(); return; } createTransitions$1(this$1, to, options, changedProperties, fulfil); }); }; Transition__proto__.bind = function bind () { var options = this.options; var type = options.template && options.template.v; if (type) { if (type === 't0' || type === 't1') { this.element.intro = this; } if (type === 't0' || type === 't2') { this.element.outro = this; } this.eventName = names[type]; } var ractive = this.owner.ractive; this.name = options.name || options.template.n; if (options.params) { this.params = options.params; } if (isFunction(this.name)) { this._fn = this.name; this.name = this._fn.name; } else { this._fn = findInViewHierarchy('transitions', ractive, this.name); } if (!this._fn) { warnOnceIfDebug(missingPlugin(this.name, 'transition'), { ractive: ractive }); } setupArgsFn(this, options.template); }; Transition__proto__.getParams = function getParams () { if (this.params) { return this.params; } // get expression args if supplied if (this.fn) { var values = resolveArgs(this, this.template, this.up).map(function (model) { if (!model) { return undefined; } return model.get(); }); return this.fn.apply(this.ractive, values); } }; Transition__proto__.getStyle = function getStyle (props) { var computedStyle = getComputedStyle(this.node); if (isString(props)) { return computedStyle[prefix$1(props)]; } if (!isArray(props)) { throw new Error( 'Transition$getStyle must be passed a string, or an array of strings representing CSS properties' ); } var styles = {}; var i = props.length; while (i--) { var prop = props[i]; var value = computedStyle[prefix$1(prop)]; if (value === '0px') { value = 0; } styles[prop] = value; } return styles; }; Transition__proto__.processParams = function processParams (params, defaults) { if (isNumber(params)) { params = { duration: params }; } else if (isString(params)) { if (params === 'slow') { params = { duration: 600 }; } else if (params === 'fast') { params = { duration: 200 }; } else { params = { duration: 400 }; } } else if (!params) { params = {}; } return assign({}, defaults, params); }; Transition__proto__.registerCompleteHandler = function registerCompleteHandler (fn) { addToArray(this.onComplete, fn); }; Transition__proto__.setStyle = function setStyle (style, value) { var this$1 = this; if (isString(style)) { var name = prefix$1(style); if (!hasOwn(this.originals, name)) { this.originals[name] = this.node.style[name]; } this.node.style[name] = value; this.targets[name] = this.node.style[name]; } else { var prop; for (prop in style) { if (hasOwn(style, prop)) { this$1.setStyle(prop, style[prop]); } } } return this; }; Transition__proto__.shouldFire = function shouldFire (type) { if (!this.ractive.transitionsEnabled) { return false; } // check for noIntro and noOutro cases, which only apply when the owner ractive is rendering and unrendering, respectively if (type === 'intro' && this.ractive.rendering && nearestProp('noIntro', this.ractive, true)) { return false; } if (type === 'outro' && this.ractive.unrendering && nearestProp('noOutro', this.ractive, false)) { return false; } var params = this.getParams(); // this is an array, the params object should be the first member // if there's not a parent element, this can't be nested, so roll on if (!this.element.parent) { return true; } // if there is a local param, it takes precedent if (params && params[0] && isObject(params[0]) && 'nested' in params[0]) { if (params[0].nested !== false) { return true; } } else { // use the nearest instance setting // find the nearest instance that actually has a nested setting if (nearestProp('nestedTransitions', this.ractive) !== false) { return true; } } // check to see if this is actually a nested transition var el = this.element.parent; while (el) { if (el[type] && el[type].starting) { return false; } el = el.parent; } return true; }; Transition__proto__.start = function start () { var this$1 = this; var node = (this.node = this.element.node); var originals = (this.originals = {}); //= node.getAttribute( 'style' ); var targets = (this.targets = {}); var completed; var args = this.getParams(); // create t.complete() - we don't want this on the prototype, // because we don't want `this` silliness when passing it as // an argument this.complete = function (noReset) { this$1.starting = false; if (completed) { return; } this$1.onComplete.forEach(function (fn) { return fn(); }); if (!noReset && this$1.isIntro) { for (var k in targets) { if (node.style[k] === targets[k]) { node.style[k] = originals[k]; } } } this$1._manager.remove(this$1); completed = true; }; // If the transition function doesn't exist, abort if (!this._fn) { this.complete(); return; } var promise = this._fn.apply(this.ractive, [this].concat(args)); if (promise) { promise.then(this.complete); } }; Transition__proto__.toString = function toString () { return ''; }; Transition__proto__.unbind = function unbind () { if (!this.element.attributes.unbinding) { var type = this.options && this.options.template && this.options.template.v; if (type === 't0' || type === 't1') { this.element.intro = null; } if (type === 't0' || type === 't2') { this.element.outro = null; } } }; Transition__proto__.unregisterCompleteHandler = function unregisterCompleteHandler (fn) { removeFromArray(this.onComplete, fn); }; var proto$8 = Transition.prototype; proto$8.destroyed = proto$8.firstNode = proto$8.rebound = proto$8.render = proto$8.unrender = proto$8.update = noop; function nearestProp(prop, ractive, rendering) { var instance = ractive; while (instance) { if ( hasOwn(instance, prop) && (rendering === undefined || rendering ? instance.rendering : instance.unrendering) ) { return instance[prop]; } instance = instance.component && instance.component.ractive; } return ractive[prop]; } var elementCache = {}; var ieBug; var ieBlacklist; try { createElement('table').innerHTML = 'foo'; } catch (/* istanbul ignore next */ err) { ieBug = true; ieBlacklist = { TABLE: ['<table class="x">', '</table>'], THEAD: ['<table><thead class="x">', '</thead></table>'], TBODY: ['<table><tbody class="x">', '</tbody></table>'], TR: ['<table><tr class="x">', '</tr></table>'], SELECT: ['<select class="x">', '</select>'] }; } function insertHtml(html$$1, node) { var nodes = []; // render 0 and false if (html$$1 == null || html$$1 === '') { return nodes; } var container; var wrapper; var selectedOption; /* istanbul ignore if */ if (ieBug && (wrapper = ieBlacklist[node.tagName])) { container = element('DIV'); container.innerHTML = wrapper[0] + html$$1 + wrapper[1]; container = container.querySelector('.x'); if (container.tagName === 'SELECT') { selectedOption = container.options[container.selectedIndex]; } } else if (node.namespaceURI === svg$1) { container = element('DIV'); container.innerHTML = '<svg class="x">' + html$$1 + '</svg>'; container = container.querySelector('.x'); } else if (node.tagName === 'TEXTAREA') { container = createElement('div'); if (typeof container.textContent !== 'undefined') { container.textContent = html$$1; } else { container.innerHTML = html$$1; } } else { container = element(node.tagName); container.innerHTML = html$$1; if (container.tagName === 'SELECT') { selectedOption = container.options[container.selectedIndex]; } } var child; while ((child = container.firstChild)) { nodes.push(child); container.removeChild(child); } // This is really annoying. Extracting <option> nodes from the // temporary container <select> causes the remaining ones to // become selected. So now we have to deselect them. IE8, you // amaze me. You really do // ...and now Chrome too var i; if (node.tagName === 'SELECT') { i = nodes.length; while (i--) { if (nodes[i] !== selectedOption) { nodes[i].selected = false; } } } return nodes; } function element(tagName) { return elementCache[tagName] || (elementCache[tagName] = createElement(tagName)); } var Triple = (function (Mustache) { function Triple(options) { Mustache.call(this, options); } if ( Mustache ) Triple.__proto__ = Mustache; var Triple__proto__ = Triple.prototype = Object.create( Mustache && Mustache.prototype ); Triple__proto__.constructor = Triple; Triple__proto__.detach = function detach () { var docFrag = createDocumentFragment(); if (this.nodes) { this.nodes.forEach(function (node) { return docFrag.appendChild(node); }); } return docFrag; }; Triple__proto__.find = function find (selector) { var this$1 = this; var len = this.nodes.length; var i; for (i = 0; i < len; i += 1) { var node = this$1.nodes[i]; if (node.nodeType !== 1) { continue; } if (matches(node, selector)) { return node; } var queryResult = node.querySelector(selector); if (queryResult) { return queryResult; } } return null; }; Triple__proto__.findAll = function findAll (selector, options) { var this$1 = this; var result = options.result; var len = this.nodes.length; var i; for (i = 0; i < len; i += 1) { var node = this$1.nodes[i]; if (node.nodeType !== 1) { continue; } if (matches(node, selector)) { result.push(node); } var queryAllResult = node.querySelectorAll(selector); if (queryAllResult) { result.push.apply(result, queryAllResult); } } }; Triple__proto__.findComponent = function findComponent () { return null; }; Triple__proto__.firstNode = function firstNode () { return this.rendered && this.nodes[0]; }; Triple__proto__.render = function render (target, occupants, anchor) { var this$1 = this; if (!this.nodes) { var html = this.model ? this.model.get() : ''; this.nodes = insertHtml(html, target); } var nodes = this.nodes; // progressive enhancement if (occupants) { var i = -1; var next; // start with the first node that should be rendered while (occupants.length && (next = this.nodes[i + 1])) { var n = (void 0); // look through the occupants until a matching node is found while ((n = occupants.shift())) { var t = n.nodeType; if ( t === next.nodeType && ((t === 1 && n.outerHTML === next.outerHTML) || ((t === 3 || t === 8) && n.nodeValue === next.nodeValue)) ) { this$1.nodes.splice(++i, 1, n); // replace the generated node with the existing one break; } else { target.removeChild(n); // remove the non-matching existing node } } } if (i >= 0) { // update the list of remaining nodes to attach, excluding any that were replaced by existing nodes nodes = this.nodes.slice(i); } // update the anchor to be the next occupant if (occupants.length) { anchor = occupants[0]; } } // attach any remainging nodes to the parent if (nodes.length) { var frag = createDocumentFragment(); nodes.forEach(function (n) { return frag.appendChild(n); }); if (anchor) { target.insertBefore(frag, anchor); } else { target.appendChild(frag); } } this.rendered = true; }; Triple__proto__.toString = function toString () { var value = this.model && this.model.get(); value = value != null ? '' + value : ''; return inAttribute() ? decodeCharacterReferences(value) : value; }; Triple__proto__.unrender = function unrender () { if (this.nodes) { this.nodes.forEach(function (node) { // defer detachment until all relevant outros are done runloop.detachWhenReady({ node: node, detach: function detach() { detachNode(node); } }); }); } this.rendered = false; this.nodes = null; }; Triple__proto__.update = function update () { if (this.rendered && this.dirty) { this.dirty = false; this.unrender(); this.render(this.up.findParentNode(), null, this.up.findNextNode(this)); } else { // make sure to reset the dirty flag even if not rendered this.dirty = false; } }; return Triple; }(Mustache)); // finds the component constructor in the registry or view hierarchy registries function getComponentConstructor(ractive, name) { var instance = findInstance('components', ractive, name); var Component; if (instance) { Component = instance.components[name]; if (Component && !Component.isInstance) { if (Component.default && Component.default.isInstance) { Component = Component.default; } else if (!Component.then && isFunction(Component)) { // function option, execute and store for reset var fn = Component.bind(instance); fn.isOwner = hasOwn(instance.components, name); Component = fn(); if (!Component) { warnIfDebug(noRegistryFunctionReturn, name, 'component', 'component', { ractive: ractive }); return; } if (isString(Component)) { // allow string lookup Component = getComponentConstructor(ractive, Component); } Component._fn = fn; instance.components[name] = Component; } } } return Component; } function asyncProxy(promise, options) { var partials = options.template.p || {}; var name = options.template.e; var opts = assign({}, options, { template: { t: ELEMENT, e: name }, macro: function macro(handle) { handle.setTemplate(partials['async-loading'] || []); promise.then( function (cmp) { options.up.ractive.components[name] = cmp; if (partials['async-loaded']) { handle.partials.component = [options.template]; handle.setTemplate(partials['async-loaded']); } else { handle.setTemplate([options.template]); } }, function (err) { if (partials['async-failed']) { handle.aliasLocal('error', 'error'); handle.set('@local.error', err); handle.setTemplate(partials['async-failed']); } else { handle.setTemplate([]); } } ); } }); return new Partial(opts); } function extract(tpl, type, name) { var p = tpl.f.find(function (s) { return s.t === type; }); if (p) { if (p.n) { return [ { t: 19, n: 54, f: p.f || [], z: [{ n: p.n, x: { r: ("__await." + name) } }] } ]; } else { return p.f || []; } } else { return []; } } function Await(options) { var tpl = options.template; var success = extract(tpl, THEN, 'value'); var error = extract(tpl, CATCH, 'error'); var pending = extract(tpl, SECTION); var undef = extract(tpl, ELSE); var opts = assign({}, options, { template: { t: ELEMENT, m: [ { t: ATTRIBUTE, n: 'for', f: [{ t: INTERPOLATOR, r: tpl.r, rx: tpl.rx, x: tpl.x }] } ] }, macro: function macro(handle, attrs) { handle.aliasLocal('__await'); function update(attrs) { if (attrs.for && isFunction(attrs.for.then)) { handle.setTemplate(pending); attrs.for.then( function (v) { handle.set('@local.value', v); handle.setTemplate(success); }, function (e) { handle.set('@local.error', e); handle.setTemplate(error); } ); } else if (attrs.for === undefined) { handle.setTemplate(undef); } else { handle.set('@local.value', attrs.for); handle.setTemplate(success); } } update(attrs); return { update: update }; } }); opts.macro.attributes = ['for']; return new Partial(opts); } var constructors = {}; constructors[ALIAS] = Alias; constructors[ANCHOR] = Component; constructors[AWAIT] = Await; constructors[DOCTYPE] = Doctype; constructors[INTERPOLATOR] = Interpolator; constructors[PARTIAL] = Partial; constructors[SECTION] = Section; constructors[TRIPLE] = Triple; constructors[YIELDER] = Partial; constructors[ATTRIBUTE] = Attribute; constructors[BINDING_FLAG] = BindingFlag; constructors[DECORATOR] = Decorator; constructors[EVENT] = EventDirective; constructors[TRANSITION] = Transition; constructors[COMMENT] = Comment; var specialElements = { doctype: Doctype, form: Form, input: Input, option: Option, select: Select, textarea: Textarea }; function createItem(options) { if (isString(options.template)) { return new Text(options); } var ctor; var name; var type = options.template.t; if (type === ELEMENT) { name = options.template.e; // could be a macro partial ctor = findInstance('partials', options.up.ractive, name); if (ctor) { ctor = ctor.partials[name]; if (ctor.styleSet) { options.macro = ctor; return new Partial(options); } } // could be component or element ctor = getComponentConstructor(options.up.ractive, name); if (ctor) { if (isFunction(ctor.then)) { return asyncProxy(ctor, options); } else if (isFunction(ctor)) { return new Component(options, ctor); } } ctor = specialElements[name.toLowerCase()] || Element; return new ctor(options); } var Item; // component mappings are a special case of attribute if (type === ATTRIBUTE) { var el = options.owner; if (!el || (el.type !== ANCHOR && el.type !== COMPONENT && el.type !== ELEMENT)) { el = findElement(options.up); } options.element = el; Item = el.type === COMPONENT || el.type === ANCHOR ? Mapping : Attribute; } else { Item = constructors[type]; } if (!Item) { throw new Error(("Unrecognised item type " + type)); } return new Item(options); } // TODO all this code needs to die function processItems(items, values, guid, counter) { if ( counter === void 0 ) counter = 0; return items .map(function (item) { if (item.type === TEXT) { return item.template; } if (item.fragment) { if (item.fragment.iterations) { return item.fragment.iterations .map(function (fragment) { return processItems(fragment.items, values, guid, counter); }) .join(''); } else { return processItems(item.fragment.items, values, guid, counter); } } var placeholderId = guid + "-" + (counter++); var model = item.model || item.newModel; values[placeholderId] = model ? model.wrapper ? model.wrapperValue : model.get() : undefined; return '${' + placeholderId + '}'; }) .join(''); } var Fragment = function Fragment(options) { this.owner = options.owner; // The item that owns this fragment - an element, section, partial, or attribute this.isRoot = !options.owner.up; this.parent = this.isRoot ? null : this.owner.up; this.ractive = options.ractive || (this.isRoot ? options.owner : this.parent.ractive); this.componentParent = this.isRoot && this.ractive.component ? this.ractive.component.up : null; if (!this.isRoot || this.ractive.delegate) { this.delegate = this.owner.containerFragment ? this.owner.containerFragment && this.owner.containerFragment.delegate : (this.componentParent && this.componentParent.delegate) || (this.parent && this.parent.delegate); } else { this.delegate = false; } this.context = null; this.rendered = false; // encapsulated styles should be inherited until they get applied by an element if ('cssIds' in options) { this.cssIds = options.cssIds && options.cssIds.length && options.cssIds; } else { this.cssIds = this.parent ? this.parent.cssIds : null; } this.dirty = false; this.dirtyValue = true; // used for attribute values this.template = options.template || []; this.createItems(); }; var Fragment__proto__ = Fragment.prototype; Fragment__proto__.bind = function bind (context) { var this$1 = this; this.context = context; var len = this.items.length; for (var i = 0; i < len; i++) { this$1.items[i].bind(); } this.bound = true; // in rare cases, a forced resolution (or similar) will cause the // fragment to be dirty before it's even finished binding. In those // cases we update immediately if (this.dirty) { this.update(); } return this; }; Fragment__proto__.bubble = function bubble () { this.dirtyValue = true; if (!this.dirty) { this.dirty = true; if (this.isRoot) { // TODO encapsulate 'is component root, but not overall root' check? if (this.ractive.component) { this.ractive.component.bubble(); } else if (this.bound) { runloop.addFragment(this); } } else { this.owner.bubble(this.index); } } }; Fragment__proto__.createItems = function createItems () { var this$1 = this; // this is a hot code path var max = this.template.length; this.items = []; for (var i = 0; i < max; i++) { this$1.items[i] = createItem({ up: this$1, template: this$1.template[i], index: i }); } }; Fragment__proto__.destroyed = function destroyed () { var this$1 = this; var len = this.items.length; for (var i = 0; i < len; i++) { this$1.items[i].destroyed(); } if (this.pathModel) { this.pathModel.destroyed(); } if (this.rootModel) { this.rootModel.destroyed(); } }; Fragment__proto__.detach = function detach () { var docFrag = createDocumentFragment(); var xs = this.items; var len = xs.length; for (var i = 0; i < len; i++) { docFrag.appendChild(xs[i].detach()); } return docFrag; }; Fragment__proto__.find = function find (selector, options) { return findMap(this.items, function (i) { return i.find(selector, options); }); }; Fragment__proto__.findAll = function findAll (selector, options) { if (this.items) { this.items.forEach(function (i) { return i.findAll && i.findAll(selector, options); }); } }; Fragment__proto__.findComponent = function findComponent (name, options) { return findMap(this.items, function (i) { return i.findComponent(name, options); }); }; Fragment__proto__.findAllComponents = function findAllComponents (name, options) { if (this.items) { this.items.forEach(function (i) { return i.findAllComponents && i.findAllComponents(name, options); }); } }; Fragment__proto__.findContext = function findContext () { var base = findParentWithContext(this); if (!base || !base.context) { return this.ractive.viewmodel; } else { return base.context; } }; Fragment__proto__.findNextNode = function findNextNode (item) { var this$1 = this; // search for the next node going forward if (item) { var it; for (var i = item.index + 1; i < this.items.length; i++) { it = this$1.items[i]; if (!it || !it.firstNode) { continue; } var node = it.firstNode(true); if (node) { return node; } } } // if this is the root fragment, and there are no more items, // it means we're at the end... if (this.isRoot) { if (this.ractive.component) { return this.ractive.component.up.findNextNode(this.ractive.component); } // TODO possible edge case with other content // appended to this.ractive.el? return null; } if (this.parent) { return this.owner.findNextNode(this); } // the argument is in case the parent is a RepeatedFragment }; Fragment__proto__.findParentNode = function findParentNode () { var fragment = this; do { if (fragment.owner.type === ELEMENT) { return fragment.owner.node; } if (fragment.isRoot && !fragment.ractive.component) { // TODO encapsulate check return fragment.ractive.el; } if (fragment.owner.type === YIELDER) { fragment = fragment.owner.containerFragment; } else { fragment = fragment.componentParent || fragment.parent; // TODO ugh } } while (fragment); throw new Error('Could not find parent node'); // TODO link to issue tracker }; Fragment__proto__.firstNode = function firstNode (skipParent) { var node = findMap(this.items, function (i) { return i.firstNode(true); }); if (node) { return node; } if (skipParent) { return null; } return this.parent.findNextNode(this.owner); }; Fragment__proto__.getKey = function getKey () { return this.keyModel || (this.keyModel = new KeyModel(this.key)); }; Fragment__proto__.getIndex = function getIndex () { return this.idxModel || (this.idxModel = new KeyModel(this.index)); }; Fragment__proto__.rebind = function rebind (next) { this.context = next; if (this.rootModel) { this.rootModel.context = this.context; } if (this.pathModel) { this.pathModel.context = this.context; } }; Fragment__proto__.rebound = function rebound (update$$1) { this.items.forEach(function (x) { return x.rebound(update$$1); }); if (update$$1) { if (this.rootModel) { this.rootModel.applyValue(this.context.getKeypath(this.ractive.root)); } if (this.pathModel) { this.pathModel.applyValue(this.context.getKeypath()); } } }; Fragment__proto__.render = function render (target, occupants) { if (this.rendered) { throw new Error('Fragment is already rendered!'); } this.rendered = true; var xs = this.items; var len = xs.length; for (var i = 0; i < len; i++) { xs[i].render(target, occupants); } }; Fragment__proto__.resetTemplate = function resetTemplate (template) { var wasBound = this.bound; var wasRendered = this.rendered; // TODO ensure transitions are disabled globally during reset if (wasBound) { if (wasRendered) { this.unrender(true); } this.unbind(); } this.template = template; this.createItems(); if (wasBound) { this.bind(this.context); if (wasRendered) { var parentNode = this.findParentNode(); var anchor = this.findNextNode(); if (anchor) { var docFrag = createDocumentFragment(); this.render(docFrag); parentNode.insertBefore(docFrag, anchor); } else { this.render(parentNode); } } } }; Fragment__proto__.shuffled = function shuffled$2 () { this.items.forEach(shuffled); if (this.rootModel) { this.rootModel.applyValue(this.context.getKeypath(this.ractive.root)); } if (this.pathModel) { this.pathModel.applyValue(this.context.getKeypath()); } }; Fragment__proto__.toString = function toString (escape) { return this.items.map(escape ? toEscapedString : toString$1).join(''); }; Fragment__proto__.unbind = function unbind (view) { var this$1 = this; this.context = null; var len = this.items.length; for (var i = 0; i < len; i++) { this$1.items[i].unbind(view); } this.bound = false; return this; }; Fragment__proto__.unrender = function unrender (shouldDestroy) { var this$1 = this; var len = this.items.length; for (var i = 0; i < len; i++) { this$1.items[i].unrender(shouldDestroy); } this.rendered = false; }; Fragment__proto__.update = function update () { var this$1 = this; if (this.dirty) { if (!this.updating) { this.dirty = false; this.updating = true; var len = this.items.length; for (var i = 0; i < len; i++) { this$1.items[i].update(); } this.updating = false; } else if (this.isRoot) { runloop.addFragmentToRoot(this); } } }; Fragment__proto__.valueOf = function valueOf () { if (this.items.length === 1) { return this.items[0].valueOf(); } if (this.dirtyValue) { var values = {}; var source = processItems(this.items, values, this.ractive._guid); var parsed = parseJSON(source, values); this.value = parsed ? parsed.value : this.toString(); this.dirtyValue = false; } return this.value; }; Fragment.prototype.getContext = getContext; Fragment.prototype.getKeypath = getKeypath; function getKeypath(root) { var base = findParentWithContext(this); var model; if (root) { if (!this.rootModel) { this.rootModel = new KeyModel( this.context.getKeypath(this.ractive.root), this.context, this.ractive.root ); model = this.rootModel; } else { return this.rootModel; } } else { if (!this.pathModel) { this.pathModel = new KeyModel(this.context.getKeypath(), this.context); model = this.pathModel; } else { return this.pathModel; } } if (base && base.context) { base.getKeypath(root).registerChild(model); } return model; } function initialise(ractive, userOptions, options) { // initialize settable computeds var computed = ractive.viewmodel.computed; if (computed) { for (var k in computed) { if (k in ractive.viewmodel.value && computed[k] && !computed[k].isReadonly) { computed[k].set(ractive.viewmodel.value[k]); } } } // init config from Parent and options config.init(ractive.constructor, ractive, userOptions); // call any passed in plugins if (isArray(userOptions.use)) { ractive.use.apply(ractive, userOptions.use.filter(function (p) { return !p.construct; })); } hooks.config.fire(ractive); hooks.init.begin(ractive); var fragment = (ractive.fragment = createFragment$1(ractive, options)); if (fragment) { fragment.bind(ractive.viewmodel); } hooks.init.end(ractive); // general config done, set up observers subscribe(ractive, userOptions, 'observe'); if (fragment) { // render automatically ( if `el` is specified ) var el = (ractive.el = ractive.target = getElement(ractive.el || ractive.target)); if (el && !ractive.component) { var promise = ractive.render(el, ractive.append); if (Ractive.DEBUG_PROMISES) { promise.catch(function (err) { warnOnceIfDebug( 'Promise debugging is enabled, to help solve errors that happen asynchronously. Some browsers will log unhandled promise rejections, in which case you can safely disable promise debugging:\n Ractive.DEBUG_PROMISES = false;' ); warnIfDebug('An error happened during rendering', { ractive: ractive }); logIfDebug(err); throw err; }); } } } } function createFragment$1(ractive, options) { if ( options === void 0 ) options = {}; if (ractive.template) { var cssIds = [].concat(ractive.constructor._cssIds || [], options.cssIds || []); return new Fragment({ owner: ractive, template: ractive.template, cssIds: cssIds }); } } function render$1(ractive, target, anchor, occupants) { // set a flag to let any transitions know that this instance is currently rendering ractive.rendering = true; var promise = runloop.start(); runloop.scheduleTask(function () { return hooks.render.fire(ractive); }, true); if (ractive.fragment.rendered) { throw new Error( 'You cannot call ractive.render() on an already rendered instance! Call ractive.unrender() first' ); } if (ractive.destroyed) { ractive.destroyed = false; ractive.fragment = createFragment$1(ractive).bind(ractive.viewmodel); } anchor = getElement(anchor) || ractive.anchor; ractive.el = ractive.target = target; ractive.anchor = anchor; // ensure encapsulated CSS is up-to-date if (ractive.cssId) { applyCSS(); } if (target) { (target.__ractive_instances__ || (target.__ractive_instances__ = [])).push(ractive); if (anchor) { var docFrag = doc.createDocumentFragment(); ractive.fragment.render(docFrag); target.insertBefore(docFrag, anchor); } else { ractive.fragment.render(target, occupants); } } runloop.end(); ractive.rendering = false; return promise.then(function () { if (ractive.torndown) { return; } hooks.complete.fire(ractive); }); } function Ractive$render(target, anchor) { if (this.torndown) { warnIfDebug('ractive.render() was called on a Ractive instance that was already torn down'); return Promise.resolve(); } target = getElement(target) || this.el; if (!this.append && target) { // Teardown any existing instances *before* trying to set up the new one - // avoids certain weird bugs var others = target.__ractive_instances__; if (others) { others.forEach(teardown); } // make sure we are the only occupants if (!this.enhance) { target.innerHTML = ''; // TODO is this quicker than removeChild? Initial research inconclusive } } var occupants = this.enhance ? toArray(target.childNodes) : null; var promise = render$1(this, target, anchor, occupants); if (occupants) { while (occupants.length) { target.removeChild(occupants.pop()); } } return promise; } var shouldRerender = ['template', 'partials', 'components', 'decorators', 'events']; function Ractive$reset(data) { data = data || {}; if (!isObjectType(data)) { throw new Error('The reset method takes either no arguments, or an object containing new data'); } // TEMP need to tidy this up data = dataConfigurator.init(this.constructor, this, { data: data }); var promise = runloop.start(); // If the root object is wrapped, try and use the wrapper's reset value var wrapper = this.viewmodel.wrapper; if (wrapper && wrapper.reset) { if (wrapper.reset(data) === false) { // reset was rejected, we need to replace the object this.viewmodel.set(data); } } else { this.viewmodel.set(data); } // reset config items and track if need to rerender var changes = config.reset(this); var rerender; var i = changes.length; while (i--) { if (shouldRerender.indexOf(changes[i]) > -1) { rerender = true; break; } } if (rerender) { hooks.unrender.fire(this); this.fragment.resetTemplate(this.template); hooks.render.fire(this); hooks.complete.fire(this); } runloop.end(); hooks.reset.fire(this, data); return promise; } function collect$1(source, name, attr, dest) { source.forEach(function (item) { // queue to rerender if the item is a partial and the current name matches if (item.type === PARTIAL && (item.refName === name || item.name === name)) { item.inAttribute = attr; dest.push(item); return; // go no further } // if it has a fragment, process its items if (item.fragment) { collect$1(item.fragment.iterations || item.fragment.items, name, attr, dest); } else if (isArray(item.items)) { // or if it is itself a fragment, process its items collect$1(item.items, name, attr, dest); } else if (item.type === COMPONENT && item.instance) { // or if it is a component, step in and process its items // ...unless the partial is shadowed if (item.instance.partials[name]) { return; } collect$1(item.instance.fragment.items, name, attr, dest); } // if the item is an element, process its attributes too if (item.type === ELEMENT) { if (isArray(item.attributes)) { collect$1(item.attributes, name, true, dest); } } }); } function resetPartial(name, partial) { var collection = []; collect$1(this.fragment.items, name, false, collection); var promise = runloop.start(); this.partials[name] = partial; collection.forEach(handleChange); runloop.end(); return promise; } // TODO should resetTemplate be asynchronous? i.e. should it be a case // of outro, update template, intro? I reckon probably not, since that // could be achieved with unrender-resetTemplate-render. Also, it should // conceptually be similar to resetPartial, which couldn't be async function Ractive$resetTemplate(template) { templateConfigurator.init(null, this, { template: template }); var transitionsEnabled = this.transitionsEnabled; this.transitionsEnabled = false; // Is this is a component, we need to set the `shouldDestroy` // flag, otherwise it will assume by default that a parent node // will be detached, and therefore it doesn't need to bother // detaching its own nodes var component = this.component; if (component) { component.shouldDestroy = true; } this.unrender(); if (component) { component.shouldDestroy = false; } var promise = runloop.start(); // remove existing fragment and create new one this.fragment.unbind().unrender(true); this.fragment = new Fragment({ template: this.template, root: this, owner: this }); var docFrag = createDocumentFragment(); this.fragment.bind(this.viewmodel).render(docFrag); // if this is a component, its el may not be valid, so find a // target based on the component container if (component && !component.external) { this.fragment.findParentNode().insertBefore(docFrag, component.findNextNode()); } else { this.el.insertBefore(docFrag, this.anchor); } runloop.end(); this.transitionsEnabled = transitionsEnabled; return promise; } var reverse = makeArrayMethod('reverse').path; function Ractive$set(keypath, value, options) { var ractive = this; var opts = isObjectType(keypath) ? value : options; return set(build(ractive, keypath, value, opts && opts.isolated), opts); } var shift = makeArrayMethod('shift').path; var sort = makeArrayMethod('sort').path; var splice = makeArrayMethod('splice').path; function Ractive$subtract(keypath, d, options) { var num = isNumber(d) ? -d : -1; var opts = isObjectType(d) ? d : options; return add(this, keypath, num, opts); } function Ractive$toggle(keypath, options) { if (!isString(keypath)) { throw new TypeError(badArguments); } return set( gather(this, keypath, null, options && options.isolated).map(function (m) { return [m, !m.get()]; }), options ); } function Ractive$toCSS() { var cssIds = [this.cssId ].concat( this.findAllComponents().map(function (c) { return c.cssId; })); var uniqueCssIds = keys(cssIds.reduce(function (ids, id) { return (ids[id] = true, ids); }, {})); return getCSS(uniqueCssIds); } function Ractive$toHTML() { return this.fragment.toString(true); } function toText() { return this.fragment.toString(false); } function Ractive$transition(name, node, params) { if (node instanceof HTMLElement) { // good to go } else if (isObject(node)) { // omitted, use event node params = node; } // if we allow query selector, then it won't work // simple params like "fast" // else if ( typeof node === 'string' ) { // // query selector // node = this.find( node ) // } node = node || this.event.node; if (!node || !node._ractive) { fatal(("No node was supplied for transition " + name)); } params = params || {}; var owner = node._ractive.proxy; var transition = new Transition({ owner: owner, up: owner.up, name: name, params: params }); transition.bind(); var promise = runloop.start(); runloop.registerTransition(transition); runloop.end(); promise.then(function () { return transition.unbind(); }); return promise; } function unlink(here) { var promise = runloop.start(); this.viewmodel.joinAll(splitKeypath(here), { lastLink: false }).unlink(); runloop.end(); return promise; } function Ractive$unrender() { if (!this.fragment.rendered) { warnIfDebug('ractive.unrender() was called on a Ractive instance that was not rendered'); return Promise.resolve(); } this.unrendering = true; var promise = runloop.start(); hooks.unrendering.fire(this); // If this is a component, and the component isn't marked for destruction, // don't detach nodes from the DOM unnecessarily var shouldDestroy = !this.component || (this.component.anchor || {}).shouldDestroy || this.component.shouldDestroy || this.shouldDestroy; this.fragment.unrender(shouldDestroy); if (shouldDestroy) { this.destroyed = true; } removeFromArray(this.el.__ractive_instances__, this); hooks.unrender.fire(this); runloop.end(); this.unrendering = false; return promise; } var unshift = makeArrayMethod('unshift').path; function Ractive$updateModel(keypath, cascade) { var promise = runloop.start(); if (!keypath) { this.viewmodel.updateFromBindings(true); } else { this.viewmodel.joinAll(splitKeypath(keypath)).updateFromBindings(cascade !== false); } runloop.end(); return promise; } function use() { var this$1 = this; var plugins = [], len = arguments.length; while ( len-- ) plugins[ len ] = arguments[ len ]; plugins.forEach(function (p) { p({ proto: this$1, Ractive: this$1.constructor.Ractive, instance: this$1 }); }); return this; } var proto$9 = { add: Ractive$add, animate: Ractive$animate, attachChild: attachChild, compute: Ractive$compute, detach: Ractive$detach, detachChild: detachChild, find: Ractive$find, findAll: Ractive$findAll, findAllComponents: Ractive$findAllComponents, findComponent: Ractive$findComponent, findContainer: Ractive$findContainer, findParent: Ractive$findParent, fire: Ractive$fire, get: Ractive$get, getContext: getContext$2, insert: Ractive$insert, link: link, observe: observe, observeOnce: observeOnce, off: Ractive$off, on: Ractive$on, once: Ractive$once, pop: pop, push: push, readLink: readLink, render: Ractive$render, reset: Ractive$reset, resetPartial: resetPartial, resetTemplate: Ractive$resetTemplate, reverse: reverse, set: Ractive$set, shift: shift, sort: sort, splice: splice, subtract: Ractive$subtract, teardown: Ractive$teardown, toggle: Ractive$toggle, toCSS: Ractive$toCSS, toCss: Ractive$toCSS, toHTML: Ractive$toHTML, toHtml: Ractive$toHTML, toText: toText, transition: Ractive$transition, unlink: unlink, unrender: Ractive$unrender, unshift: unshift, update: Ractive$update, updateModel: Ractive$updateModel, use: use }; function isInstance(object) { return object && object instanceof this; } function styleGet(keypath, opts) { return this._cssModel.joinAll(splitKeypath(keypath)).get(true, opts); } var styles = []; function addStyle(id, css) { if (styles.find(function (s) { return s.id === id; })) { throw new Error(("Extra styles with the id '" + id + "' have already been added.")); } styles.push({ id: id, css: css }); if (!this.css) { Object.defineProperty(this, 'css', { configurable: false, writable: false, value: buildCSS }); } if (!this._cssDef) { Object.defineProperty(this, '_cssDef', { configurable: true, writable: false, value: { transform: false, id: 'Ractive.addStyle' } }); addCSS(this._cssDef); } recomputeCSS(this); applyCSS(true); } function buildCSS(data) { return styles .map(function (s) { return "\n/* ---- extra style " + (s.id) + " */\n" + (isFunction(s.css) ? s.css(data) : s.css); }) .join(''); } function hasStyle(id) { return !!styles.find(function (s) { return s.id === id; }); } function sharedSet(keypath, value, options) { var opts = isObjectType(keypath) ? value : options; var model = SharedModel$1; return set(build({ viewmodel: model }, keypath, value, true), opts); } function sharedGet(keypath, opts) { return SharedModel$1.joinAll(splitKeypath(keypath)).get(true, opts); } function use$1() { var this$1 = this; var plugins = [], len = arguments.length; while ( len-- ) plugins[ len ] = arguments[ len ]; plugins.forEach(function (p) { isFunction(p) && p({ proto: this$1.prototype, Ractive: this$1.Ractive, instance: this$1 }); }); return this; } var callsSuper = /super\s*\(|\.call\s*\(\s*this/; function extend() { var options = [], len = arguments.length; while ( len-- ) options[ len ] = arguments[ len ]; if (!options.length) { return extendOne(this); } else { return options.reduce(extendOne, this); } } function extendWith(Class, options) { if ( options === void 0 ) options = {}; return extendOne(this, options, Class); } function extendOne(Parent, options, Target) { if ( options === void 0 ) options = {}; var proto; var Child = isFunction(Target) && Target; if (options.prototype instanceof Ractive) { throw new Error("Ractive no longer supports multiple inheritance."); } if (Child) { if (!(Child.prototype instanceof Parent)) { throw new Error( "Only classes that inherit the appropriate prototype may be used with extend" ); } if (!callsSuper.test(Child.toString())) { throw new Error("Only classes that call super in their constructor may be used with extend"); } proto = Child.prototype; } else { Child = function(options) { if (!(this instanceof Child)) { return new Child(options); } construct(this, options || {}); initialise(this, options || {}, {}); }; proto = create(Parent.prototype); proto.constructor = Child; Child.prototype = proto; } // Static properties defineProperties(Child, { // alias prototype as defaults defaults: { value: proto }, extend: { value: extend, writable: true, configurable: true }, extendWith: { value: extendWith, writable: true, configurable: true }, extensions: { value: [] }, use: { value: use$1 }, isInstance: { value: isInstance }, Parent: { value: Parent }, Ractive: { value: Ractive }, styleGet: { value: styleGet.bind(Child), configurable: true }, styleSet: { value: setCSSData.bind(Child), configurable: true } }); // extend configuration config.extend(Parent, proto, options, Child); // store event and observer registries on the constructor when extending Child._on = (Parent._on || []).concat(toPairs(options.on)); Child._observe = (Parent._observe || []).concat(toPairs(options.observe)); Parent.extensions.push(Child); // attribute defs are not inherited, but they need to be stored if (options.attributes) { var attrs; // allow an array of optional props or an object with arrays for optional and required props if (isArray(options.attributes)) { attrs = { optional: options.attributes, required: [] }; } else { attrs = options.attributes; } // make sure the requisite keys actually store arrays if (!isArray(attrs.required)) { attrs.required = []; } if (!isArray(attrs.optional)) { attrs.optional = []; } Child.attributes = attrs; } dataConfigurator.extend(Parent, proto, options, Child); defineProperty(Child, 'helpers', { writable: true, value: proto.helpers }); if (isArray(options.use)) { Child.use.apply(Child, options.use); } return Child; } defineProperties(Ractive, { sharedGet: { value: sharedGet }, sharedSet: { value: sharedSet }, styleGet: { configurable: true, value: styleGet.bind(Ractive) }, styleSet: { configurable: true, value: setCSSData.bind(Ractive) }, addCSS: { configurable: false, value: addStyle.bind(Ractive) }, hasCSS: { configurable: false, value: hasStyle.bind(Ractive) } }); function macro(fn, opts) { if (!isFunction(fn)) { throw new Error("The macro must be a function"); } assign(fn, opts); defineProperties(fn, { extensions: { value: [] }, _cssIds: { value: [] }, cssData: { value: assign(create(this.cssData), fn.cssData || {}) }, styleGet: { value: styleGet.bind(fn) }, styleSet: { value: setCSSData.bind(fn) } }); defineProperty(fn, '_cssModel', { value: new CSSModel(fn) }); if (fn.css) { initCSS(fn, fn, fn); } this.extensions.push(fn); return fn; } function joinKeys() { var keys = [], len = arguments.length; while ( len-- ) keys[ len ] = arguments[ len ]; return keys.map(escapeKey).join('.'); } function splitKeypath$1(keypath) { return splitKeypath(keypath).map(unescapeKey); } function findPlugin(name, type, instance) { return findInViewHierarchy(type, instance, name); } function Ractive(options) { if (!(this instanceof Ractive)) { return new Ractive(options); } construct(this, options || {}); initialise(this, options || {}, {}); } // check to see if we're being asked to force Ractive as a global for some weird environments if (win && !win.Ractive) { var opts$1 = ''; var script = document.currentScript || /* istanbul ignore next */ document.querySelector('script[data-ractive-options]'); if (script) { opts$1 = script.getAttribute('data-ractive-options') || ''; } /* istanbul ignore next */ if (~opts$1.indexOf('ForceGlobal')) { win.Ractive = Ractive; } } else if (win) { warn("Ractive already appears to be loaded while loading 1.3.0-edge."); } assign(Ractive.prototype, proto$9, defaults); Ractive.prototype.constructor = Ractive; // alias prototype as `defaults` Ractive.defaults = Ractive.prototype; // share defaults with the parser shared.defaults = Ractive.defaults; shared.Ractive = Ractive; // static properties defineProperties(Ractive, { // debug flag DEBUG: { writable: true, value: true }, DEBUG_PROMISES: { writable: true, value: true }, // static methods: extend: { value: extend }, extendWith: { value: extendWith }, escapeKey: { value: escapeKey }, evalObjectString: { value: parseJSON }, findPlugin: { value: findPlugin }, getContext: { value: getContext$1 }, getCSS: { value: getCSS }, isInstance: { value: isInstance }, joinKeys: { value: joinKeys }, macro: { value: macro }, normaliseKeypath: { value: normalise }, parse: { value: parse }, splitKeypath: { value: splitKeypath$1 }, // sharedSet and styleSet are in _extend because circular refs unescapeKey: { value: unescapeKey }, use: { value: use$1 }, // support enhance: { writable: true, value: false }, svg: { value: svg }, // version VERSION: { value: '1.3.0-edge' }, // plugins adaptors: { writable: true, value: {} }, components: { writable: true, value: {} }, decorators: { writable: true, value: {} }, easing: { writable: true, value: easing }, events: { writable: true, value: {} }, extensions: { value: [] }, helpers: { writable: true, value: defaults.helpers }, interpolators: { writable: true, value: interpolators }, partials: { writable: true, value: {} }, transitions: { writable: true, value: {} }, // CSS variables cssData: { configurable: true, value: {} }, // access to @shared without an instance sharedData: { value: data }, // for getting the source Ractive lib from a constructor Ractive: { value: Ractive }, // to allow extending contexts Context: { value: extern.Context.prototype } }); // cssData must already be in place defineProperty(Ractive, '_cssModel', { configurable: true, value: new CSSModel(Ractive) }); defineProperty(Ractive.prototype, 'rendered', { get: function get() { return this.fragment && this.fragment.rendered; } }); return Ractive; }))); //# sourceMappingURL=ractive.js.map
import HasManyHelper from './has-many-helper'; import {module, test} from 'qunit'; module('Integration | ORM | hasMany #accessor'); /* #association behavior works regardless of the state of the parent */ HasManyHelper.forEachScenario((scenario) => { test(`the references of a ${scenario.title} are correct`, function(assert) { let { parent, children, accessor, idsAccessor } = scenario.go(); assert.equal(parent[accessor].models.length, children.length, 'parent has correct number of children'); assert.equal(parent[idsAccessor].length, children.length, 'parent has correct number of child ids'); children.forEach(function(child, i) { assert.deepEqual(parent[accessor].models[i], children[i], 'each child is in parent.children array'); if (!child.isNew()) { assert.ok(parent[idsAccessor].indexOf(child.id) > -1, 'each saved child id is in parent.childrenIds array'); } }); }); });
/** * (c) 2010-2019 Torstein Honsi * * License: www.highcharts.com/license */ /** * Gets fired when the legend item belonging to a point is clicked. The default * action is to toggle the visibility of the point. This can be prevented by * returning `false` or calling `event.preventDefault()`. * * @callback Highcharts.PointLegendItemClickCallbackFunction * * @param {Highcharts.Point} this * The point on which the event occured. * * @param {Highcharts.PointLegendItemClickEventObject} event * The event that occured. */ /** * Information about the legend click event. * * @interface Highcharts.PointLegendItemClickEventObject *//** * Related browser event. * @name Highcharts.PointLegendItemClickEventObject#browserEvent * @type {Highcharts.PointerEvent} *//** * Prevent the default action of toggle the visibility of the point. * @name Highcharts.PointLegendItemClickEventObject#preventDefault * @type {Function} *//** * Related point. * @name Highcharts.PointLegendItemClickEventObject#target * @type {Highcharts.Point} *//** * Event type. * @name Highcharts.PointLegendItemClickEventObject#type * @type {"legendItemClick"} */ /** * Gets fired when the legend item belonging to a series is clicked. The default * action is to toggle the visibility of the series. This can be prevented by * returning `false` or calling `event.preventDefault()`. * * @callback Highcharts.SeriesLegendItemClickCallbackFunction * * @param {Highcharts.Series} this * The series where the event occured. * * @param {Highcharts.SeriesLegendItemClickEventObject} event * The event that occured. */ /** * Information about the legend click event. * * @interface Highcharts.SeriesLegendItemClickEventObject *//** * Related browser event. * @name Highcharts.SeriesLegendItemClickEventObject#browserEvent * @type {Highcharts.PointerEvent} *//** * Prevent the default action of toggle the visibility of the series. * @name Highcharts.SeriesLegendItemClickEventObject#preventDefault * @type {Function} *//** * Related series. * @name Highcharts.SeriesLegendItemClickEventObject#target * @type {Highcharts.Series} *//** * Event type. * @name Highcharts.SeriesLegendItemClickEventObject#type * @type {"legendItemClick"} */ 'use strict'; import Highcharts from './Globals.js'; import './Utilities.js'; var H = Highcharts, addEvent = H.addEvent, css = H.css, discardElement = H.discardElement, defined = H.defined, fireEvent = H.fireEvent, isFirefox = H.isFirefox, marginNames = H.marginNames, merge = H.merge, pick = H.pick, setAnimation = H.setAnimation, stableSort = H.stableSort, win = H.win, wrap = H.wrap; /** * The overview of the chart's series. The legend object is instanciated * internally in the chart constructor, and is available from the `chart.legend` * property. Each chart has only one legend. * * @class * @name Highcharts.Legend * * @param {Highcharts.Chart} chart * The chart instance. * * @param {Highcharts.LegendOptions} options * Legend options. */ Highcharts.Legend = function (chart, options) { this.init(chart, options); }; Highcharts.Legend.prototype = { /** * Initialize the legend. * * @private * @function Highcharts.Legend#init * * @param {Highcharts.Chart} chart * The chart instance. * * @param {Highcharts.LegendOptions} options * Legend options. */ init: function (chart, options) { /** * Chart of this legend. * * @readonly * @name Highcharts.Legend#chart * @type {Highcharts.Chart} */ this.chart = chart; this.setOptions(options); if (options.enabled) { // Render it this.render(); // move checkboxes addEvent(this.chart, 'endResize', function () { this.legend.positionCheckboxes(); }); if (this.proximate) { this.unchartrender = addEvent( this.chart, 'render', function () { this.legend.proximatePositions(); this.legend.positionItems(); } ); } else if (this.unchartrender) { this.unchartrender(); } } }, /** * @private * @function Highcharts.Legend#setOptions * * @param {Highcharts.LegendOptions} options */ setOptions: function (options) { var padding = pick(options.padding, 8); /** * Legend options. * * @readonly * @name Highcharts.Legend#options * @type {Highcharts.LegendOptions} */ this.options = options; if (!this.chart.styledMode) { this.itemStyle = options.itemStyle; this.itemHiddenStyle = merge( this.itemStyle, options.itemHiddenStyle ); } this.itemMarginTop = options.itemMarginTop || 0; this.padding = padding; this.initialItemY = padding - 5; // 5 is pixels above the text this.symbolWidth = pick(options.symbolWidth, 16); this.pages = []; this.proximate = options.layout === 'proximate' && !this.chart.inverted; }, /** * Update the legend with new options. Equivalent to running `chart.update` * with a legend configuration option. * * @sample highcharts/legend/legend-update/ * Legend update * * @function Highcharts.Legend#update * * @param {Highcharts.LegendOptions} options * Legend options. * * @param {boolean} [redraw=true] * Whether to redraw the chart after the axis is altered. If doing * more operations on the chart, it is a good idea to set redraw to * false and call {@link Chart#redraw} after. * Whether to redraw the chart. * * @fires Highcharts.Legends#event:afterUpdate */ update: function (options, redraw) { var chart = this.chart; this.setOptions(merge(true, this.options, options)); this.destroy(); chart.isDirtyLegend = chart.isDirtyBox = true; if (pick(redraw, true)) { chart.redraw(); } fireEvent(this, 'afterUpdate'); }, /** * Set the colors for the legend item. * * @private * @function Highcharts.Legend#colorizeItem * * @param {Highcharts.Point|Highcharts.Series} item * A Series or Point instance * * @param {boolean} [visible=false] * Dimmed or colored * * @todo * Make events official: Fires the event `afterColorizeItem`. */ colorizeItem: function (item, visible) { item.legendGroup[visible ? 'removeClass' : 'addClass']( 'highcharts-legend-item-hidden' ); if (!this.chart.styledMode) { var legend = this, options = legend.options, legendItem = item.legendItem, legendLine = item.legendLine, legendSymbol = item.legendSymbol, hiddenColor = legend.itemHiddenStyle.color, textColor = visible ? options.itemStyle.color : hiddenColor, symbolColor = visible ? (item.color || hiddenColor) : hiddenColor, markerOptions = item.options && item.options.marker, symbolAttr = { fill: symbolColor }; if (legendItem) { legendItem.css({ fill: textColor, color: textColor // #1553, oldIE }); } if (legendLine) { legendLine.attr({ stroke: symbolColor }); } if (legendSymbol) { // Apply marker options if (markerOptions && legendSymbol.isMarker) { // #585 symbolAttr = item.pointAttribs(); if (!visible) { // #6769 symbolAttr.stroke = symbolAttr.fill = hiddenColor; } } legendSymbol.attr(symbolAttr); } } fireEvent(this, 'afterColorizeItem', { item: item, visible: visible }); }, /** * @private * @function Highcharts.Legend#positionItems */ positionItems: function () { // Now that the legend width and height are established, put the items // in the final position this.allItems.forEach(this.positionItem, this); if (!this.chart.isResizing) { this.positionCheckboxes(); } }, /** * Position the legend item. * * @private * @function Highcharts.Legend#positionItem * * @param {Highcharts.Point|Highcharts.Series} item * The item to position */ positionItem: function (item) { var legend = this, options = legend.options, symbolPadding = options.symbolPadding, ltr = !options.rtl, legendItemPos = item._legendItemPos, itemX = legendItemPos[0], itemY = legendItemPos[1], checkbox = item.checkbox, legendGroup = item.legendGroup; if (legendGroup && legendGroup.element) { legendGroup[defined(legendGroup.translateY) ? 'animate' : 'attr']({ translateX: ltr ? itemX : legend.legendWidth - itemX - 2 * symbolPadding - 4, translateY: itemY }); } if (checkbox) { checkbox.x = itemX; checkbox.y = itemY; } }, /** * Destroy a single legend item, used internally on removing series items. * * @private * @function Highcharts.Legend#destroyItem * * @param {Highcharts.Point|Highcharts.Series} item * The item to remove */ destroyItem: function (item) { var checkbox = item.checkbox; // destroy SVG elements ['legendItem', 'legendLine', 'legendSymbol', 'legendGroup'].forEach( function (key) { if (item[key]) { item[key] = item[key].destroy(); } } ); if (checkbox) { discardElement(item.checkbox); } }, /** * Destroy the legend. Used internally. To reflow objects, `chart.redraw` * must be called after destruction. * * @private * @function Highcharts.Legend#destroy */ destroy: function () { function destroyItems(key) { if (this[key]) { this[key] = this[key].destroy(); } } // Destroy items this.getAllItems().forEach(function (item) { ['legendItem', 'legendGroup'].forEach(destroyItems, item); }); // Destroy legend elements [ 'clipRect', 'up', 'down', 'pager', 'nav', 'box', 'title', 'group' ].forEach(destroyItems, this); this.display = null; // Reset in .render on update. }, /** * Position the checkboxes after the width is determined. * * @private * @function Highcharts.Legend#positionCheckboxes */ positionCheckboxes: function () { var alignAttr = this.group && this.group.alignAttr, translateY, clipHeight = this.clipHeight || this.legendHeight, titleHeight = this.titleHeight; if (alignAttr) { translateY = alignAttr.translateY; this.allItems.forEach(function (item) { var checkbox = item.checkbox, top; if (checkbox) { top = translateY + titleHeight + checkbox.y + (this.scrollOffset || 0) + 3; css(checkbox, { left: (alignAttr.translateX + item.checkboxOffset + checkbox.x - 20) + 'px', top: top + 'px', display: this.proximate || ( top > translateY - 6 && top < translateY + clipHeight - 6 ) ? '' : 'none' }); } }, this); } }, /** * Render the legend title on top of the legend. * * @private * @function Highcharts.Legend#renderTitle */ renderTitle: function () { var options = this.options, padding = this.padding, titleOptions = options.title, titleHeight = 0, bBox; if (titleOptions.text) { if (!this.title) { /** * SVG element of the legend title. * * @readonly * @name Highcharts.Legend#title * @type {Highcharts.SVGElement} */ this.title = this.chart.renderer.label( titleOptions.text, padding - 3, padding - 4, null, null, null, options.useHTML, null, 'legend-title' ) .attr({ zIndex: 1 }); if (!this.chart.styledMode) { this.title.css(titleOptions.style); } this.title.add(this.group); } // Set the max title width (#7253) if (!titleOptions.width) { this.title.css({ width: this.maxLegendWidth + 'px' }); } bBox = this.title.getBBox(); titleHeight = bBox.height; this.offsetWidth = bBox.width; // #1717 this.contentGroup.attr({ translateY: titleHeight }); } this.titleHeight = titleHeight; }, /** * Set the legend item text. * * @function Highcharts.Legend#setText * * @param {Highcharts.Point|Highcharts.Series} item * The item for which to update the text in the legend. */ setText: function (item) { var options = this.options; item.legendItem.attr({ text: options.labelFormat ? H.format(options.labelFormat, item, this.chart.time) : options.labelFormatter.call(item) }); }, /** * Render a single specific legend item. Called internally from the `render` * function. * * @private * @function Highcharts.Legend#renderItem * * @param {Highcharts.Point|Highcharts.Series} item * The item to render. */ renderItem: function (item) { var legend = this, chart = legend.chart, renderer = chart.renderer, options = legend.options, horizontal = options.layout === 'horizontal', symbolWidth = legend.symbolWidth, symbolPadding = options.symbolPadding, itemStyle = legend.itemStyle, itemHiddenStyle = legend.itemHiddenStyle, itemDistance = horizontal ? pick(options.itemDistance, 20) : 0, ltr = !options.rtl, bBox, li = item.legendItem, isSeries = !item.series, series = !isSeries && item.series.drawLegendSymbol ? item.series : item, seriesOptions = series.options, showCheckbox = legend.createCheckboxForItem && seriesOptions && seriesOptions.showCheckbox, // full width minus text width itemExtraWidth = symbolWidth + symbolPadding + itemDistance + (showCheckbox ? 20 : 0), useHTML = options.useHTML, itemClassName = item.options.className; if (!li) { // generate it once, later move it // Generate the group box, a group to hold the symbol and text. Text // is to be appended in Legend class. item.legendGroup = renderer.g('legend-item') .addClass( 'highcharts-' + series.type + '-series ' + 'highcharts-color-' + item.colorIndex + (itemClassName ? ' ' + itemClassName : '') + (isSeries ? ' highcharts-series-' + item.index : '') ) .attr({ zIndex: 1 }) .add(legend.scrollGroup); // Generate the list item text and add it to the group item.legendItem = li = renderer.text( '', ltr ? symbolWidth + symbolPadding : -symbolPadding, legend.baseline || 0, useHTML ); if (!chart.styledMode) { // merge to prevent modifying original (#1021) li.css(merge(item.visible ? itemStyle : itemHiddenStyle)); } li.attr({ align: ltr ? 'left' : 'right', zIndex: 2 }) .add(item.legendGroup); // Get the baseline for the first item - the font size is equal for // all if (!legend.baseline) { legend.fontMetrics = renderer.fontMetrics( chart.styledMode ? 12 : itemStyle.fontSize, li ); legend.baseline = legend.fontMetrics.f + 3 + legend.itemMarginTop; li.attr('y', legend.baseline); } // Draw the legend symbol inside the group box legend.symbolHeight = options.symbolHeight || legend.fontMetrics.f; series.drawLegendSymbol(legend, item); if (legend.setItemEvents) { legend.setItemEvents(item, li, useHTML); } } // Add the HTML checkbox on top if (showCheckbox && !item.checkbox) { legend.createCheckboxForItem(item); } // Colorize the items legend.colorizeItem(item, item.visible); // Take care of max width and text overflow (#6659) if (chart.styledMode || !itemStyle.width) { li.css({ width: ( options.itemWidth || legend.widthOption || chart.spacingBox.width ) - itemExtraWidth }); } // Always update the text legend.setText(item); // calculate the positions for the next line bBox = li.getBBox(); item.itemWidth = item.checkboxOffset = options.itemWidth || item.legendItemWidth || bBox.width + itemExtraWidth; legend.maxItemWidth = Math.max(legend.maxItemWidth, item.itemWidth); legend.totalItemWidth += item.itemWidth; legend.itemHeight = item.itemHeight = Math.round( item.legendItemHeight || bBox.height || legend.symbolHeight ); }, /** * Get the position of the item in the layout. We now know the * maxItemWidth from the previous loop. * * @private * @function Highcharts.Legend#layoutItem * * @param {Highcharts.Point|Highcharts.Series} item */ layoutItem: function (item) { var options = this.options, padding = this.padding, horizontal = options.layout === 'horizontal', itemHeight = item.itemHeight, itemMarginBottom = options.itemMarginBottom || 0, itemMarginTop = this.itemMarginTop, itemDistance = horizontal ? pick(options.itemDistance, 20) : 0, maxLegendWidth = this.maxLegendWidth, itemWidth = ( options.alignColumns && this.totalItemWidth > maxLegendWidth ) ? this.maxItemWidth : item.itemWidth; // If the item exceeds the width, start a new line if ( horizontal && this.itemX - padding + itemWidth > maxLegendWidth ) { this.itemX = padding; if (this.lastLineHeight) { // Not for the first line (#10167) this.itemY += ( itemMarginTop + this.lastLineHeight + itemMarginBottom ); } this.lastLineHeight = 0; // reset for next line (#915, #3976) } // Set the edge positions this.lastItemY = itemMarginTop + this.itemY + itemMarginBottom; this.lastLineHeight = Math.max( // #915 itemHeight, this.lastLineHeight ); // cache the position of the newly generated or reordered items item._legendItemPos = [this.itemX, this.itemY]; // advance if (horizontal) { this.itemX += itemWidth; } else { this.itemY += itemMarginTop + itemHeight + itemMarginBottom; this.lastLineHeight = itemHeight; } // the width of the widest item this.offsetWidth = this.widthOption || Math.max( ( horizontal ? this.itemX - padding - (item.checkbox ? // decrease by itemDistance only when no checkbox #4853 0 : itemDistance ) : itemWidth ) + padding, this.offsetWidth ); }, /** * Get all items, which is one item per series for most series and one * item per point for pie series and its derivatives. * * @private * @function Highcharts.Legend#getAllItems * * @return {Array<Highcharts.Point|Highcharts.Series>} * The current items in the legend. * * @fires Highcharts.Legend#event:afterGetAllItems * * @todo * Make events official: Fires the event `afterGetAllItems`. */ getAllItems: function () { var allItems = []; this.chart.series.forEach(function (series) { var seriesOptions = series && series.options; // Handle showInLegend. If the series is linked to another series, // defaults to false. if (series && pick( seriesOptions.showInLegend, !defined(seriesOptions.linkedTo) ? undefined : false, true )) { // Use points or series for the legend item depending on // legendType allItems = allItems.concat( series.legendItems || ( seriesOptions.legendType === 'point' ? series.data : series ) ); } }); fireEvent(this, 'afterGetAllItems', { allItems: allItems }); return allItems; }, /** * Get a short, three letter string reflecting the alignment and layout. * * @private * @function Highcharts.Legend#getAlignment * * @return {string} * The alignment, empty string if floating */ getAlignment: function () { var options = this.options; // Use the first letter of each alignment option in order to detect // the side. (#4189 - use charAt(x) notation instead of [x] for IE7) if (this.proximate) { return options.align.charAt(0) + 'tv'; } return options.floating ? '' : ( options.align.charAt(0) + options.verticalAlign.charAt(0) + options.layout.charAt(0) ); }, /** * Adjust the chart margins by reserving space for the legend on only one * side of the chart. If the position is set to a corner, top or bottom is * reserved for horizontal legends and left or right for vertical ones. * * @private * @function Highcharts.Legend#adjustMargins * * @param {Array<number>} margin * * @param {number} spacing */ adjustMargins: function (margin, spacing) { var chart = this.chart, options = this.options, alignment = this.getAlignment(), titleMargin = chart.options.title.margin !== undefined ? chart.titleOffset + chart.options.title.margin : 0; if (alignment) { ([ /(lth|ct|rth)/, /(rtv|rm|rbv)/, /(rbh|cb|lbh)/, /(lbv|lm|ltv)/ ]).forEach(function (alignments, side) { if (alignments.test(alignment) && !defined(margin[side])) { // Now we have detected on which side of the chart we should // reserve space for the legend chart[marginNames[side]] = Math.max( chart[marginNames[side]], ( chart.legend[ (side + 1) % 2 ? 'legendHeight' : 'legendWidth' ] + [1, -1, -1, 1][side] * options[ (side % 2) ? 'x' : 'y' ] + pick(options.margin, 12) + spacing[side] + ( side === 0 && (chart.titleOffset === 0 ? 0 : titleMargin) ) // #7428, #7894 ) ); } }); } }, /** * @private * @function Highcharts.Legend#proximatePositions */ proximatePositions: function () { var chart = this.chart, boxes = [], alignLeft = this.options.align === 'left'; this.allItems.forEach(function (item) { var lastPoint, height, useFirstPoint = alignLeft, target, top; if (item.yAxis && item.points) { if (item.xAxis.options.reversed) { useFirstPoint = !useFirstPoint; } lastPoint = H.find( useFirstPoint ? item.points : item.points.slice(0).reverse(), function (item) { return H.isNumber(item.plotY); } ); height = item.legendGroup.getBBox().height; top = item.yAxis.top - chart.plotTop; if (item.visible) { target = lastPoint ? lastPoint.plotY : item.yAxis.height; target += top - 0.3 * height; } else { target = top + item.yAxis.height; } boxes.push({ target: target, size: height, item: item }); } }, this); H.distribute(boxes, chart.plotHeight); boxes.forEach(function (box) { box.item._legendItemPos[1] = chart.plotTop - chart.spacing[0] + box.pos; }); }, /** * Render the legend. This method can be called both before and after * `chart.render`. If called after, it will only rearrange items instead * of creating new ones. Called internally on initial render and after * redraws. * * @private * @function Highcharts.Legend#render */ render: function () { var legend = this, chart = legend.chart, renderer = chart.renderer, legendGroup = legend.group, allItems, display, legendWidth, legendHeight, box = legend.box, options = legend.options, padding = legend.padding, alignTo, allowedWidth, y; legend.itemX = padding; legend.itemY = legend.initialItemY; legend.offsetWidth = 0; legend.lastItemY = 0; legend.widthOption = H.relativeLength( options.width, chart.spacingBox.width - padding ); // Compute how wide the legend is allowed to be allowedWidth = chart.spacingBox.width - 2 * padding - options.x; if (['rm', 'lm'].indexOf(legend.getAlignment().substring(0, 2)) > -1) { allowedWidth /= 2; } legend.maxLegendWidth = legend.widthOption || allowedWidth; if (!legendGroup) { /** * SVG group of the legend. * * @readonly * @name Highcharts.Legend#group * @type {Highcharts.SVGElement} */ legend.group = legendGroup = renderer.g('legend') .attr({ zIndex: 7 }) .add(); legend.contentGroup = renderer.g() .attr({ zIndex: 1 }) // above background .add(legendGroup); legend.scrollGroup = renderer.g() .add(legend.contentGroup); } legend.renderTitle(); // add each series or point allItems = legend.getAllItems(); // sort by legendIndex stableSort(allItems, function (a, b) { return ((a.options && a.options.legendIndex) || 0) - ((b.options && b.options.legendIndex) || 0); }); // reversed legend if (options.reversed) { allItems.reverse(); } /** * All items for the legend, which is an array of series for most series * and an array of points for pie series and its derivatives. * * @readonly * @name Highcharts.Legend#allItems * @type {Array<Highcharts.Point|Highcharts.Series>} */ legend.allItems = allItems; legend.display = display = !!allItems.length; // Render the items. First we run a loop to set the text and properties // and read all the bounding boxes. The next loop computes the item // positions based on the bounding boxes. legend.lastLineHeight = 0; legend.maxItemWidth = 0; legend.totalItemWidth = 0; legend.itemHeight = 0; allItems.forEach(legend.renderItem, legend); allItems.forEach(legend.layoutItem, legend); // Get the box legendWidth = (legend.widthOption || legend.offsetWidth) + padding; legendHeight = legend.lastItemY + legend.lastLineHeight + legend.titleHeight; legendHeight = legend.handleOverflow(legendHeight); legendHeight += padding; // Draw the border and/or background if (!box) { /** * SVG element of the legend box. * * @readonly * @name Highcharts.Legend#box * @type {Highcharts.SVGElement} */ legend.box = box = renderer.rect() .addClass('highcharts-legend-box') .attr({ r: options.borderRadius }) .add(legendGroup); box.isNew = true; } // Presentational if (!chart.styledMode) { box .attr({ stroke: options.borderColor, 'stroke-width': options.borderWidth || 0, fill: options.backgroundColor || 'none' }) .shadow(options.shadow); } if (legendWidth > 0 && legendHeight > 0) { box[box.isNew ? 'attr' : 'animate']( box.crisp.call({}, { // #7260 x: 0, y: 0, width: legendWidth, height: legendHeight }, box.strokeWidth()) ); box.isNew = false; } // hide the border if no items box[display ? 'show' : 'hide'](); // Open for responsiveness if (chart.styledMode && legendGroup.getStyle('display') === 'none') { legendWidth = legendHeight = 0; } legend.legendWidth = legendWidth; legend.legendHeight = legendHeight; if (display) { // If aligning to the top and the layout is horizontal, adjust for // the title (#7428) alignTo = chart.spacingBox; if (/(lth|ct|rth)/.test(legend.getAlignment())) { y = alignTo.y + chart.titleOffset; alignTo = merge(alignTo, { y: chart.titleOffset > 0 ? y += chart.options.title.margin : y }); } legendGroup.align(merge(options, { width: legendWidth, height: legendHeight, verticalAlign: this.proximate ? 'top' : options.verticalAlign }), true, alignTo); } if (!this.proximate) { this.positionItems(); } fireEvent(this, 'afterRender'); }, /** * Set up the overflow handling by adding navigation with up and down arrows * below the legend. * * @private * @function Highcharts.Legend#handleOverflow * * @param {number} legendHeight * * @return {number} */ handleOverflow: function (legendHeight) { var legend = this, chart = this.chart, renderer = chart.renderer, options = this.options, optionsY = options.y, alignTop = options.verticalAlign === 'top', padding = this.padding, spaceHeight = chart.spacingBox.height + (alignTop ? -optionsY : optionsY) - padding, maxHeight = options.maxHeight, clipHeight, clipRect = this.clipRect, navOptions = options.navigation, animation = pick(navOptions.animation, true), arrowSize = navOptions.arrowSize || 12, nav = this.nav, pages = this.pages, lastY, allItems = this.allItems, clipToHeight = function (height) { if (typeof height === 'number') { clipRect.attr({ height: height }); } else if (clipRect) { // Reset (#5912) legend.clipRect = clipRect.destroy(); legend.contentGroup.clip(); } // useHTML if (legend.contentGroup.div) { legend.contentGroup.div.style.clip = height ? 'rect(' + padding + 'px,9999px,' + (padding + height) + 'px,0)' : 'auto'; } }, addTracker = function (key) { legend[key] = renderer .circle(0, 0, arrowSize * 1.3) .translate(arrowSize / 2, arrowSize / 2) .add(nav); if (!chart.styledMode) { legend[key].attr('fill', 'rgba(0,0,0,0.0001)'); } return legend[key]; }; // Adjust the height if ( options.layout === 'horizontal' && options.verticalAlign !== 'middle' && !options.floating ) { spaceHeight /= 2; } if (maxHeight) { spaceHeight = Math.min(spaceHeight, maxHeight); } // Reset the legend height and adjust the clipping rectangle pages.length = 0; if (legendHeight > spaceHeight && navOptions.enabled !== false) { this.clipHeight = clipHeight = Math.max(spaceHeight - 20 - this.titleHeight - padding, 0); this.currentPage = pick(this.currentPage, 1); this.fullHeight = legendHeight; // Fill pages with Y positions so that the top of each a legend item // defines the scroll top for each page (#2098) allItems.forEach(function (item, i) { var y = item._legendItemPos[1], h = Math.round(item.legendItem.getBBox().height), len = pages.length; if (!len || (y - pages[len - 1] > clipHeight && (lastY || y) !== pages[len - 1])) { pages.push(lastY || y); len++; } // Keep track of which page each item is on item.pageIx = len - 1; if (lastY) { allItems[i - 1].pageIx = len - 1; } if ( i === allItems.length - 1 && y + h - pages[len - 1] > clipHeight && y !== lastY // #2617 ) { pages.push(y); item.pageIx = len; } if (y !== lastY) { lastY = y; } }); // Only apply clipping if needed. Clipping causes blurred legend in // PDF export (#1787) if (!clipRect) { clipRect = legend.clipRect = renderer.clipRect(0, padding, 9999, 0); legend.contentGroup.clip(clipRect); } clipToHeight(clipHeight); // Add navigation elements if (!nav) { this.nav = nav = renderer.g() .attr({ zIndex: 1 }) .add(this.group); this.up = renderer .symbol( 'triangle', 0, 0, arrowSize, arrowSize ) .add(nav); addTracker('upTracker') .on('click', function () { legend.scroll(-1, animation); }); this.pager = renderer.text('', 15, 10) .addClass('highcharts-legend-navigation'); if (!chart.styledMode) { this.pager.css(navOptions.style); } this.pager.add(nav); this.down = renderer .symbol( 'triangle-down', 0, 0, arrowSize, arrowSize ) .add(nav); addTracker('downTracker') .on('click', function () { legend.scroll(1, animation); }); } // Set initial position legend.scroll(0); legendHeight = spaceHeight; // Reset } else if (nav) { clipToHeight(); this.nav = nav.destroy(); // #6322 this.scrollGroup.attr({ translateY: 1 }); this.clipHeight = 0; // #1379 } return legendHeight; }, /** * Scroll the legend by a number of pages. * * @private * @function Highcharts.Legend#scroll * * @param {number} scrollBy * The number of pages to scroll. * * @param {Highcharts.AnimationOptionsObject} animation * Whether and how to apply animation. */ scroll: function (scrollBy, animation) { var pages = this.pages, pageCount = pages.length, currentPage = this.currentPage + scrollBy, clipHeight = this.clipHeight, navOptions = this.options.navigation, pager = this.pager, padding = this.padding; // When resizing while looking at the last page if (currentPage > pageCount) { currentPage = pageCount; } if (currentPage > 0) { if (animation !== undefined) { setAnimation(animation, this.chart); } this.nav.attr({ translateX: padding, translateY: clipHeight + this.padding + 7 + this.titleHeight, visibility: 'visible' }); [this.up, this.upTracker].forEach(function (elem) { elem.attr({ 'class': currentPage === 1 ? 'highcharts-legend-nav-inactive' : 'highcharts-legend-nav-active' }); }); pager.attr({ text: currentPage + '/' + pageCount }); [this.down, this.downTracker].forEach(function (elem) { elem.attr({ // adjust to text width 'x': 18 + this.pager.getBBox().width, 'class': currentPage === pageCount ? 'highcharts-legend-nav-inactive' : 'highcharts-legend-nav-active' }); }, this); if (!this.chart.styledMode) { this.up .attr({ fill: currentPage === 1 ? navOptions.inactiveColor : navOptions.activeColor }); this.upTracker .css({ cursor: currentPage === 1 ? 'default' : 'pointer' }); this.down .attr({ fill: currentPage === pageCount ? navOptions.inactiveColor : navOptions.activeColor }); this.downTracker .css({ cursor: currentPage === pageCount ? 'default' : 'pointer' }); } this.scrollOffset = -pages[currentPage - 1] + this.initialItemY; this.scrollGroup.animate({ translateY: this.scrollOffset }); this.currentPage = currentPage; this.positionCheckboxes(); } } }; /** * Legend symbol mixin. * * @private * @mixin Highcharts.LegendSymbolMixin */ H.LegendSymbolMixin = { /** * Get the series' symbol in the legend * * @private * @function Highcharts.LegendSymbolMixin.drawRectangle * * @param {Highcharts.Legend} legend * The legend object * * @param {Highcharts.Point|Highcharts.Series} item * The series (this) or point */ drawRectangle: function (legend, item) { var options = legend.options, symbolHeight = legend.symbolHeight, square = options.squareSymbol, symbolWidth = square ? symbolHeight : legend.symbolWidth; item.legendSymbol = this.chart.renderer.rect( square ? (legend.symbolWidth - symbolHeight) / 2 : 0, legend.baseline - symbolHeight + 1, // #3988 symbolWidth, symbolHeight, pick(legend.options.symbolRadius, symbolHeight / 2) ) .addClass('highcharts-point') .attr({ zIndex: 3 }).add(item.legendGroup); }, /** * Get the series' symbol in the legend. This method should be overridable * to create custom symbols through * Highcharts.seriesTypes[type].prototype.drawLegendSymbols. * * @private * @function Highcharts.LegendSymbolMixin.drawLineMarker * * @param {Highcharts.Legend} legend * The legend object. */ drawLineMarker: function (legend) { var options = this.options, markerOptions = options.marker, radius, legendSymbol, symbolWidth = legend.symbolWidth, symbolHeight = legend.symbolHeight, generalRadius = symbolHeight / 2, renderer = this.chart.renderer, legendItemGroup = this.legendGroup, verticalCenter = legend.baseline - Math.round(legend.fontMetrics.b * 0.3), attr = {}; // Draw the line if (!this.chart.styledMode) { attr = { 'stroke-width': options.lineWidth || 0 }; if (options.dashStyle) { attr.dashstyle = options.dashStyle; } } this.legendLine = renderer.path([ 'M', 0, verticalCenter, 'L', symbolWidth, verticalCenter ]) .addClass('highcharts-graph') .attr(attr) .add(legendItemGroup); // Draw the marker if (markerOptions && markerOptions.enabled !== false && symbolWidth) { // Do not allow the marker to be larger than the symbolHeight radius = Math.min( pick(markerOptions.radius, generalRadius), generalRadius ); // Restrict symbol markers size if (this.symbol.indexOf('url') === 0) { markerOptions = merge(markerOptions, { width: symbolHeight, height: symbolHeight }); radius = 0; } this.legendSymbol = legendSymbol = renderer.symbol( this.symbol, (symbolWidth / 2) - radius, verticalCenter - radius, 2 * radius, 2 * radius, markerOptions ) .addClass('highcharts-point') .add(legendItemGroup); legendSymbol.isMarker = true; } } }; // Workaround for #2030, horizontal legend items not displaying in IE11 Preview, // and for #2580, a similar drawing flaw in Firefox 26. // Explore if there's a general cause for this. The problem may be related // to nested group elements, as the legend item texts are within 4 group // elements. if ( /Trident\/7\.0/.test(win.navigator && win.navigator.userAgent) || isFirefox ) { wrap(Highcharts.Legend.prototype, 'positionItem', function (proceed, item) { var legend = this, // If chart destroyed in sync, this is undefined (#2030) runPositionItem = function () { if (item._legendItemPos) { proceed.call(legend, item); } }; // Do it now, for export and to get checkbox placement runPositionItem(); // Do it after to work around the core issue if (!legend.bubbleLegend) { setTimeout(runPositionItem); } }); }
/*! * # Semantic UI 2.7.1 - Checkbox * http://github.com/semantic-org/semantic-ui/ * * * Released under the MIT license * http://opensource.org/licenses/MIT * */ ;(function ($, window, document, undefined) { 'use strict'; $.isFunction = $.isFunction || function(obj) { return typeof obj === "function" && typeof obj.nodeType !== "number"; }; window = (typeof window != 'undefined' && window.Math == Math) ? window : (typeof self != 'undefined' && self.Math == Math) ? self : Function('return this')() ; $.fn.checkbox = function(parameters) { var $allModules = $(this), moduleSelector = $allModules.selector || '', time = new Date().getTime(), performance = [], query = arguments[0], methodInvoked = (typeof query == 'string'), queryArguments = [].slice.call(arguments, 1), returnedValue ; $allModules .each(function() { var settings = $.extend(true, {}, $.fn.checkbox.settings, parameters), className = settings.className, namespace = settings.namespace, selector = settings.selector, error = settings.error, eventNamespace = '.' + namespace, moduleNamespace = 'module-' + namespace, $module = $(this), $label = $(this).children(selector.label), $input = $(this).children(selector.input), input = $input[0], initialLoad = false, shortcutPressed = false, instance = $module.data(moduleNamespace), observer, element = this, module ; module = { initialize: function() { module.verbose('Initializing checkbox', settings); module.create.label(); module.bind.events(); module.set.tabbable(); module.hide.input(); module.observeChanges(); module.instantiate(); module.setup(); }, instantiate: function() { module.verbose('Storing instance of module', module); instance = module; $module .data(moduleNamespace, module) ; }, destroy: function() { module.verbose('Destroying module'); module.unbind.events(); module.show.input(); $module.removeData(moduleNamespace); }, fix: { reference: function() { if( $module.is(selector.input) ) { module.debug('Behavior called on <input> adjusting invoked element'); $module = $module.closest(selector.checkbox); module.refresh(); } } }, setup: function() { module.set.initialLoad(); if( module.is.indeterminate() ) { module.debug('Initial value is indeterminate'); module.indeterminate(); } else if( module.is.checked() ) { module.debug('Initial value is checked'); module.check(); } else { module.debug('Initial value is unchecked'); module.uncheck(); } module.remove.initialLoad(); }, refresh: function() { $label = $module.children(selector.label); $input = $module.children(selector.input); input = $input[0]; }, hide: { input: function() { module.verbose('Modifying <input> z-index to be unselectable'); $input.addClass(className.hidden); } }, show: { input: function() { module.verbose('Modifying <input> z-index to be selectable'); $input.removeClass(className.hidden); } }, observeChanges: function() { if('MutationObserver' in window) { observer = new MutationObserver(function(mutations) { module.debug('DOM tree modified, updating selector cache'); module.refresh(); }); observer.observe(element, { childList : true, subtree : true }); module.debug('Setting up mutation observer', observer); } }, attachEvents: function(selector, event) { var $element = $(selector) ; event = $.isFunction(module[event]) ? module[event] : module.toggle ; if($element.length > 0) { module.debug('Attaching checkbox events to element', selector, event); $element .on('click' + eventNamespace, event) ; } else { module.error(error.notFound); } }, event: { change: function(event) { if( !module.should.ignoreCallbacks() ) { settings.onChange.call(input); } }, click: function(event) { var $target = $(event.target) ; if( $target.is(selector.input) ) { module.verbose('Using default check action on initialized checkbox'); return; } if( $target.is(selector.link) ) { module.debug('Clicking link inside checkbox, skipping toggle'); return; } module.toggle(); $input.focus(); event.preventDefault(); }, keydown: function(event) { var key = event.which, keyCode = { enter : 13, space : 32, escape : 27, left : 37, up : 38, right : 39, down : 40 } ; var r = module.get.radios(), rIndex = r.index($module), rLen = r.length, checkIndex = false; if(key == keyCode.left || key == keyCode.up) { checkIndex = (rIndex === 0 ? rLen : rIndex) - 1; } else if(key == keyCode.right || key == keyCode.down) { checkIndex = rIndex === rLen-1 ? 0 : rIndex+1; } if (!module.should.ignoreCallbacks() && checkIndex !== false) { if(!settings.beforeUnchecked.apply(input)) { module.verbose('Option not allowed to be unchecked, cancelling key navigation'); return false; } if (!settings.beforeChecked.apply($(r[checkIndex]).children(selector.input)[0])) { module.verbose('Next option should not allow check, cancelling key navigation'); return false; } } if(key == keyCode.escape) { module.verbose('Escape key pressed blurring field'); $input.blur(); shortcutPressed = true; } else if(!event.ctrlKey && ( key == keyCode.space || key == keyCode.enter) ) { module.verbose('Enter/space key pressed, toggling checkbox'); module.toggle(); shortcutPressed = true; } else { shortcutPressed = false; } }, keyup: function(event) { if(shortcutPressed) { event.preventDefault(); } } }, check: function() { if( !module.should.allowCheck() ) { return; } module.debug('Checking checkbox', $input); module.set.checked(); if( !module.should.ignoreCallbacks() ) { settings.onChecked.call(input); settings.onChange.call(input); } }, uncheck: function() { if( !module.should.allowUncheck() ) { return; } module.debug('Unchecking checkbox'); module.set.unchecked(); if( !module.should.ignoreCallbacks() ) { settings.onUnchecked.call(input); settings.onChange.call(input); } }, indeterminate: function() { if( module.should.allowIndeterminate() ) { module.debug('Checkbox is already indeterminate'); return; } module.debug('Making checkbox indeterminate'); module.set.indeterminate(); if( !module.should.ignoreCallbacks() ) { settings.onIndeterminate.call(input); settings.onChange.call(input); } }, determinate: function() { if( module.should.allowDeterminate() ) { module.debug('Checkbox is already determinate'); return; } module.debug('Making checkbox determinate'); module.set.determinate(); if( !module.should.ignoreCallbacks() ) { settings.onDeterminate.call(input); settings.onChange.call(input); } }, enable: function() { if( module.is.enabled() ) { module.debug('Checkbox is already enabled'); return; } module.debug('Enabling checkbox'); module.set.enabled(); settings.onEnable.call(input); // preserve legacy callbacks settings.onEnabled.call(input); }, disable: function() { if( module.is.disabled() ) { module.debug('Checkbox is already disabled'); return; } module.debug('Disabling checkbox'); module.set.disabled(); settings.onDisable.call(input); // preserve legacy callbacks settings.onDisabled.call(input); }, get: { radios: function() { var name = module.get.name() ; return $('input[name="' + name + '"]').closest(selector.checkbox); }, otherRadios: function() { return module.get.radios().not($module); }, name: function() { return $input.attr('name'); } }, is: { initialLoad: function() { return initialLoad; }, radio: function() { return ($input.hasClass(className.radio) || $input.attr('type') == 'radio'); }, indeterminate: function() { return $input.prop('indeterminate') !== undefined && $input.prop('indeterminate'); }, checked: function() { return $input.prop('checked') !== undefined && $input.prop('checked'); }, disabled: function() { return $input.prop('disabled') !== undefined && $input.prop('disabled'); }, enabled: function() { return !module.is.disabled(); }, determinate: function() { return !module.is.indeterminate(); }, unchecked: function() { return !module.is.checked(); } }, should: { allowCheck: function() { if(module.is.determinate() && module.is.checked() && !module.is.initialLoad() ) { module.debug('Should not allow check, checkbox is already checked'); return false; } if(!module.should.ignoreCallbacks() && settings.beforeChecked.apply(input) === false) { module.debug('Should not allow check, beforeChecked cancelled'); return false; } return true; }, allowUncheck: function() { if(module.is.determinate() && module.is.unchecked() && !module.is.initialLoad() ) { module.debug('Should not allow uncheck, checkbox is already unchecked'); return false; } if(!module.should.ignoreCallbacks() && settings.beforeUnchecked.apply(input) === false) { module.debug('Should not allow uncheck, beforeUnchecked cancelled'); return false; } return true; }, allowIndeterminate: function() { if(module.is.indeterminate() && !module.is.initialLoad() ) { module.debug('Should not allow indeterminate, checkbox is already indeterminate'); return false; } if(!module.should.ignoreCallbacks() && settings.beforeIndeterminate.apply(input) === false) { module.debug('Should not allow indeterminate, beforeIndeterminate cancelled'); return false; } return true; }, allowDeterminate: function() { if(module.is.determinate() && !module.is.initialLoad() ) { module.debug('Should not allow determinate, checkbox is already determinate'); return false; } if(!module.should.ignoreCallbacks() && settings.beforeDeterminate.apply(input) === false) { module.debug('Should not allow determinate, beforeDeterminate cancelled'); return false; } return true; }, ignoreCallbacks: function() { return (initialLoad && !settings.fireOnInit); } }, can: { change: function() { return !( $module.hasClass(className.disabled) || $module.hasClass(className.readOnly) || $input.prop('disabled') || $input.prop('readonly') ); }, uncheck: function() { return (typeof settings.uncheckable === 'boolean') ? settings.uncheckable : !module.is.radio() ; } }, set: { initialLoad: function() { initialLoad = true; }, checked: function() { module.verbose('Setting class to checked'); $module .removeClass(className.indeterminate) .addClass(className.checked) ; if( module.is.radio() ) { module.uncheckOthers(); } if(!module.is.indeterminate() && module.is.checked()) { module.debug('Input is already checked, skipping input property change'); return; } module.verbose('Setting state to checked', input); $input .prop('indeterminate', false) .prop('checked', true) ; module.trigger.change(); }, unchecked: function() { module.verbose('Removing checked class'); $module .removeClass(className.indeterminate) .removeClass(className.checked) ; if(!module.is.indeterminate() && module.is.unchecked() ) { module.debug('Input is already unchecked'); return; } module.debug('Setting state to unchecked'); $input .prop('indeterminate', false) .prop('checked', false) ; module.trigger.change(); }, indeterminate: function() { module.verbose('Setting class to indeterminate'); $module .addClass(className.indeterminate) ; if( module.is.indeterminate() ) { module.debug('Input is already indeterminate, skipping input property change'); return; } module.debug('Setting state to indeterminate'); $input .prop('indeterminate', true) ; module.trigger.change(); }, determinate: function() { module.verbose('Removing indeterminate class'); $module .removeClass(className.indeterminate) ; if( module.is.determinate() ) { module.debug('Input is already determinate, skipping input property change'); return; } module.debug('Setting state to determinate'); $input .prop('indeterminate', false) ; }, disabled: function() { module.verbose('Setting class to disabled'); $module .addClass(className.disabled) ; if( module.is.disabled() ) { module.debug('Input is already disabled, skipping input property change'); return; } module.debug('Setting state to disabled'); $input .prop('disabled', 'disabled') ; module.trigger.change(); }, enabled: function() { module.verbose('Removing disabled class'); $module.removeClass(className.disabled); if( module.is.enabled() ) { module.debug('Input is already enabled, skipping input property change'); return; } module.debug('Setting state to enabled'); $input .prop('disabled', false) ; module.trigger.change(); }, tabbable: function() { module.verbose('Adding tabindex to checkbox'); if( $input.attr('tabindex') === undefined) { $input.attr('tabindex', 0); } } }, remove: { initialLoad: function() { initialLoad = false; } }, trigger: { change: function() { var events = document.createEvent('HTMLEvents'), inputElement = $input[0] ; if(inputElement) { module.verbose('Triggering native change event'); events.initEvent('change', true, false); inputElement.dispatchEvent(events); } } }, create: { label: function() { if($input.prevAll(selector.label).length > 0) { $input.prev(selector.label).detach().insertAfter($input); module.debug('Moving existing label', $label); } else if( !module.has.label() ) { $label = $('<label>').insertAfter($input); module.debug('Creating label', $label); } } }, has: { label: function() { return ($label.length > 0); } }, bind: { events: function() { module.verbose('Attaching checkbox events'); $module .on('click' + eventNamespace, module.event.click) .on('change' + eventNamespace, module.event.change) .on('keydown' + eventNamespace, selector.input, module.event.keydown) .on('keyup' + eventNamespace, selector.input, module.event.keyup) ; } }, unbind: { events: function() { module.debug('Removing events'); $module .off(eventNamespace) ; } }, uncheckOthers: function() { var $radios = module.get.otherRadios() ; module.debug('Unchecking other radios', $radios); $radios.removeClass(className.checked); }, toggle: function() { if( !module.can.change() ) { if(!module.is.radio()) { module.debug('Checkbox is read-only or disabled, ignoring toggle'); } return; } if( module.is.indeterminate() || module.is.unchecked() ) { module.debug('Currently unchecked'); module.check(); } else if( module.is.checked() && module.can.uncheck() ) { module.debug('Currently checked'); module.uncheck(); } }, setting: function(name, value) { module.debug('Changing setting', name, value); if( $.isPlainObject(name) ) { $.extend(true, settings, name); } else if(value !== undefined) { if($.isPlainObject(settings[name])) { $.extend(true, settings[name], value); } else { settings[name] = value; } } else { return settings[name]; } }, internal: function(name, value) { if( $.isPlainObject(name) ) { $.extend(true, module, name); } else if(value !== undefined) { module[name] = value; } else { return module[name]; } }, debug: function() { if(!settings.silent && settings.debug) { if(settings.performance) { module.performance.log(arguments); } else { module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':'); module.debug.apply(console, arguments); } } }, verbose: function() { if(!settings.silent && settings.verbose && settings.debug) { if(settings.performance) { module.performance.log(arguments); } else { module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':'); module.verbose.apply(console, arguments); } } }, error: function() { if(!settings.silent) { module.error = Function.prototype.bind.call(console.error, console, settings.name + ':'); module.error.apply(console, arguments); } }, performance: { log: function(message) { var currentTime, executionTime, previousTime ; if(settings.performance) { currentTime = new Date().getTime(); previousTime = time || currentTime; executionTime = currentTime - previousTime; time = currentTime; performance.push({ 'Name' : message[0], 'Arguments' : [].slice.call(message, 1) || '', 'Element' : element, 'Execution Time' : executionTime }); } clearTimeout(module.performance.timer); module.performance.timer = setTimeout(module.performance.display, 500); }, display: function() { var title = settings.name + ':', totalTime = 0 ; time = false; clearTimeout(module.performance.timer); $.each(performance, function(index, data) { totalTime += data['Execution Time']; }); title += ' ' + totalTime + 'ms'; if(moduleSelector) { title += ' \'' + moduleSelector + '\''; } if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) { console.groupCollapsed(title); if(console.table) { console.table(performance); } else { $.each(performance, function(index, data) { console.log(data['Name'] + ': ' + data['Execution Time']+'ms'); }); } console.groupEnd(); } performance = []; } }, invoke: function(query, passedArguments, context) { var object = instance, maxDepth, found, response ; passedArguments = passedArguments || queryArguments; context = element || context; if(typeof query == 'string' && object !== undefined) { query = query.split(/[\. ]/); maxDepth = query.length - 1; $.each(query, function(depth, value) { var camelCaseValue = (depth != maxDepth) ? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1) : query ; if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) { object = object[camelCaseValue]; } else if( object[camelCaseValue] !== undefined ) { found = object[camelCaseValue]; return false; } else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) { object = object[value]; } else if( object[value] !== undefined ) { found = object[value]; return false; } else { module.error(error.method, query); return false; } }); } if ( $.isFunction( found ) ) { response = found.apply(context, passedArguments); } else if(found !== undefined) { response = found; } if(Array.isArray(returnedValue)) { returnedValue.push(response); } else if(returnedValue !== undefined) { returnedValue = [returnedValue, response]; } else if(response !== undefined) { returnedValue = response; } return found; } }; if(methodInvoked) { if(instance === undefined) { module.initialize(); } module.invoke(query); } else { if(instance !== undefined) { instance.invoke('destroy'); } module.initialize(); } }) ; return (returnedValue !== undefined) ? returnedValue : this ; }; $.fn.checkbox.settings = { name : 'Checkbox', namespace : 'checkbox', silent : false, debug : false, verbose : true, performance : true, // delegated event context uncheckable : 'auto', fireOnInit : false, onChange : function(){}, beforeChecked : function(){}, beforeUnchecked : function(){}, beforeDeterminate : function(){}, beforeIndeterminate : function(){}, onChecked : function(){}, onUnchecked : function(){}, onDeterminate : function() {}, onIndeterminate : function() {}, onEnable : function(){}, onDisable : function(){}, // preserve misspelled callbacks (will be removed in 3.0) onEnabled : function(){}, onDisabled : function(){}, className : { checked : 'checked', indeterminate : 'indeterminate', disabled : 'disabled', hidden : 'hidden', radio : 'radio', readOnly : 'read-only' }, error : { method : 'The method you called is not defined' }, selector : { checkbox : '.ui.checkbox', label : 'label, .box', input : 'input[type="checkbox"], input[type="radio"]', link : 'a[href]' } }; })( jQuery, window, document );
/* Tabulator v4.2.3 (c) Oliver Folkerd */ /* * This file is part of the Tabulator package. * * (c) Oliver Folkerd <oliver.folkerd@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * Full Documentation & Demos can be found at: http://olifolkerd.github.io/tabulator/ * */ (function (factory) { "use strict"; if (typeof define === 'function' && define.amd) { define(['jquery'], factory); } else if (typeof module !== 'undefined' && module.exports) { module.exports = factory(require('jquery')); } else { factory(jQuery); } })(function ($, undefined) { $.widget("ui.tabulator", { _create: function _create() { this.table = new Tabulator(this.element[0], this.options); //map tabulator functions to jquery wrapper for (var key in Tabulator.prototype) { if (typeof Tabulator.prototype[key] === "function" && key.charAt(0) !== "_") { this[key] = this.table[key].bind(this.table); } } }, _setOption: function _setOption(option, value) { console.error("Tabulator jQuery wrapper does not support setting options after the table has been instantiated"); }, _destroy: function _destroy(option, value) { this.table.destroy(); } }); });
'use strict'; module.exports = { name: 'ember-cli-legacy-blueprints' };
GLOBAL.DEBUG = true; sys = require("sys"); test = require("assert"); var Db = require('../lib/mongodb').Db, Connection = require('../lib/mongodb').Connection, Server = require('../lib/mongodb').Server; var host = process.env['MONGO_NODE_DRIVER_HOST'] != null ? process.env['MONGO_NODE_DRIVER_HOST'] : 'localhost'; var port = process.env['MONGO_NODE_DRIVER_PORT'] != null ? process.env['MONGO_NODE_DRIVER_PORT'] : Connection.DEFAULT_PORT; sys.puts("Connecting to " + host + ":" + port); var db = new Db('node-mongo-examples', new Server(host, port, {}), {native_parser:true}); db.open(function(err, db) { db.collection('test', function(err, collection) { // Erase all records from collection, if any collection.remove(function(err, result) { // Insert 3 records for(var i = 0; i < 3; i++) { collection.insert({'a':i}); } // Cursors don't run their queries until you actually attempt to retrieve data // from them. // Find returns a Cursor, which is Enumerable. You can iterate: collection.find(function(err, cursor) { cursor.each(function(err, item) { if(item != null) sys.puts(sys.inspect(item)); }); }); // You can turn it into an array collection.find(function(err, cursor) { cursor.toArray(function(err, items) { sys.puts("count: " + items.length); }); }); // You can iterate after turning it into an array (the cursor will iterate over // the copy of the array that it saves internally.) collection.find(function(err, cursor) { cursor.toArray(function(err, items) { cursor.each(function(err, item) { if(item != null) sys.puts(sys.inspect(item)); }); }); }); // You can get the next object collection.find(function(err, cursor) { cursor.nextObject(function(err, item) { if(item != null) sys.puts(sys.inspect(item)); }); }); // next_object returns null if there are no more objects that match collection.find(function(err, cursor) { cursor.nextObject(function(err, item) { cursor.nextObject(function(err, item) { cursor.nextObject(function(err, item) { cursor.nextObject(function(err, item) { sys.puts("nextObject returned: " + sys.inspect(item)); db.close(); }); }); }); }); }); }); }); });
'use strict'; module.exports = { up: function (queryInterface, Sequelize) { return queryInterface.bulkInsert('UserMeetings', [ { user_id: 1, meeting_id: 2 }, { user_id: 2, meeting_id: 2 }, { user_id: 3, meeting_id: 2 }, { user_id: 4, meeting_id: 2 }, { user_id: 1, meeting_id: 4 }, { user_id: 2, meeting_id: 4 }, { user_id: 3, meeting_id: 4 }, { user_id: 4, meeting_id: 4 }, { user_id: 1, meeting_id: 6 }, { user_id: 2, meeting_id: 6 }, { user_id: 3, meeting_id: 6 }, { user_id: 4, meeting_id: 6 }, { user_id: 1, meeting_id: 8 }, { user_id: 2, meeting_id: 8 }, { user_id: 3, meeting_id: 8 }, { user_id: 4, meeting_id: 8 } ], {}); }, down: function (queryInterface, Sequelize) { return queryInterface.bulkDelete('UserMeetings', null, {}); } };
/* hashids http://www.hashids.org/node-js/ (c) 2013 Ivan Akimov https://github.com/ivanakimov/hashids.node.js hashids may be freely distributed under the MIT license. */ /*jslint node: true, white: true, plusplus: true */ "use strict"; function Hashids(salt, minHashLength, alphabet) { var uniqueAlphabet, i, j, len, sepsLength, diff, guardCount; this.version = "0.3.3"; /* internal settings */ this.minAlphabetLength = 16; this.sepDiv = 3.5; this.guardDiv = 12; /* error messages */ this.errorAlphabetLength = "error: alphabet must contain at least X unique characters"; this.errorAlphabetSpace = "error: alphabet cannot contain spaces"; /* alphabet vars */ this.alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; this.seps = "cfhistuCFHISTU"; this.minHashLength = parseInt(minHashLength, 10) > 0 ? minHashLength : 0; this.salt = (typeof salt === "string") ? salt : ""; if (typeof alphabet === "string") { this.alphabet = alphabet; } for (uniqueAlphabet = "", i = 0, len = this.alphabet.length; i !== len; i++) { if (uniqueAlphabet.indexOf(this.alphabet[i]) === -1) { uniqueAlphabet += this.alphabet[i]; } } this.alphabet = uniqueAlphabet; if (this.alphabet.length < this.minAlphabetLength) { throw this.errorAlphabetLength.replace("X", this.minAlphabetLength); } if (this.alphabet.search(" ") !== -1) { throw this.errorAlphabetSpace; } /* seps should contain only characters present in alphabet; alphabet should not contains seps */ for (i = 0, len = this.seps.length; i !== len; i++) { j = this.alphabet.indexOf(this.seps[i]); if (j === -1) { this.seps = this.seps.substr(0, i) + " " + this.seps.substr(i + 1); } else { this.alphabet = this.alphabet.substr(0, j) + " " + this.alphabet.substr(j + 1); } } this.alphabet = this.alphabet.replace(/ /g, ""); this.seps = this.seps.replace(/ /g, ""); this.seps = this.consistentShuffle(this.seps, this.salt); if (!this.seps.length || (this.alphabet.length / this.seps.length) > this.sepDiv) { sepsLength = Math.ceil(this.alphabet.length / this.sepDiv); if (sepsLength === 1) { sepsLength++; } if (sepsLength > this.seps.length) { diff = sepsLength - this.seps.length; this.seps += this.alphabet.substr(0, diff); this.alphabet = this.alphabet.substr(diff); } else { this.seps = this.seps.substr(0, sepsLength); } } this.alphabet = this.consistentShuffle(this.alphabet, this.salt); guardCount = Math.ceil(this.alphabet.length / this.guardDiv); if (this.alphabet.length < 3) { this.guards = this.seps.substr(0, guardCount); this.seps = this.seps.substr(guardCount); } else { this.guards = this.alphabet.substr(0, guardCount); this.alphabet = this.alphabet.substr(guardCount); } } Hashids.prototype.encrypt = function() { var ret = "", i, len, numbers = Array.prototype.slice.call(arguments); if (!numbers.length) { return ret; } if (numbers[0] instanceof Array) { numbers = numbers[0]; } for (i = 0, len = numbers.length; i !== len; i++) { if (typeof numbers[i] !== "number" || numbers[i] % 1 !== 0 || numbers[i] < 0) { return ret; } } return this.encode(numbers); }; Hashids.prototype.decrypt = function(hash) { var ret = []; if (!hash.length || typeof hash !== "string") { return ret; } return this.decode(hash, this.alphabet); }; Hashids.prototype.encryptHex = function(str) { var i, len, numbers, str = str.toString(); if (!/^[0-9a-fA-F]+$/.test(str)) { return ""; } numbers = str.match(/[\w\W]{1,12}/g); for (i = 0, len = numbers.length; i !== len; i++) { numbers[i] = parseInt("1" + numbers[i], 16); } return this.encrypt.apply(this, numbers); }; Hashids.prototype.decryptHex = function(hash) { var ret = "", i, len, numbers = this.decrypt(hash); for (i = 0, len = numbers.length; i !== len; i++) { ret += (numbers[i]).toString(16).substr(1); } return ret; }; Hashids.prototype.encode = function(numbers) { var ret, lottery, i, len, number, buffer, last, sepsIndex, guardIndex, guard, halfLength, excess, alphabet = this.alphabet, numbersSize = numbers.length, numbersHashInt = 0; for (i = 0, len = numbers.length; i !== len; i++) { numbersHashInt += (numbers[i] % (i + 100)); } lottery = ret = alphabet[numbersHashInt % alphabet.length]; for (i = 0, len = numbers.length; i !== len; i++) { number = numbers[i]; buffer = lottery + this.salt + alphabet; alphabet = this.consistentShuffle(alphabet, buffer.substr(0, alphabet.length)); last = this.hash(number, alphabet); ret += last; if (i + 1 < numbersSize) { number %= (last.charCodeAt(0) + i); sepsIndex = number % this.seps.length; ret += this.seps[sepsIndex]; } } if (ret.length < this.minHashLength) { guardIndex = (numbersHashInt + ret[0].charCodeAt(0)) % this.guards.length; guard = this.guards[guardIndex]; ret = guard + ret; if (ret.length < this.minHashLength) { guardIndex = (numbersHashInt + ret[2].charCodeAt(0)) % this.guards.length; guard = this.guards[guardIndex]; ret += guard; } } halfLength = parseInt(alphabet.length / 2, 10); while (ret.length < this.minHashLength) { alphabet = this.consistentShuffle(alphabet, alphabet); ret = alphabet.substr(halfLength) + ret + alphabet.substr(0, halfLength); excess = ret.length - this.minHashLength; if (excess > 0) { ret = ret.substr(excess / 2, this.minHashLength); } } return ret; }; Hashids.prototype.decode = function(hash, alphabet) { var ret = [], i = 0, lottery, len, subHash, buffer, r = new RegExp("[" + this.guards + "]", "g"), hashBreakdown = hash.replace(r, " "), hashArray = hashBreakdown.split(" "); if (hashArray.length === 3 || hashArray.length === 2) { i = 1; } hashBreakdown = hashArray[i]; if (typeof hashBreakdown[0] !== "undefined") { lottery = hashBreakdown[0]; hashBreakdown = hashBreakdown.substr(1); r = new RegExp("[" + this.seps + "]", "g"); hashBreakdown = hashBreakdown.replace(r, " "); hashArray = hashBreakdown.split(" "); for (i = 0, len = hashArray.length; i !== len; i++) { subHash = hashArray[i]; buffer = lottery + this.salt + alphabet; alphabet = this.consistentShuffle(alphabet, buffer.substr(0, alphabet.length)); ret.push(this.unhash(subHash, alphabet)); } if (this.encode(ret) !== hash) { ret = []; } } return ret; }; Hashids.prototype.consistentShuffle = function(alphabet, salt) { var integer, j, temp, i, v, p; if (!salt.length) { return alphabet; } for (i = alphabet.length - 1, v = 0, p = 0; i > 0; i--, v++) { v %= salt.length; p += integer = salt[v].charCodeAt(0); j = (integer + v + p) % i; temp = alphabet[j]; alphabet = alphabet.substr(0, j) + alphabet[i] + alphabet.substr(j + 1); alphabet = alphabet.substr(0, i) + temp + alphabet.substr(i + 1); } return alphabet; }; Hashids.prototype.hash = function(input, alphabet) { var hash = "", alphabetLength = alphabet.length; do { hash = alphabet[input % alphabetLength] + hash; input = parseInt(input / alphabetLength, 10); } while (input); return hash; }; Hashids.prototype.unhash = function(input, alphabet) { var number = 0, pos, i; for (i = 0; i < input.length; i++) { pos = alphabet.indexOf(input[i]); number += pos * Math.pow(alphabet.length, input.length - i - 1); } return number; }; module.exports = Hashids;
/* TimerManager.js KC3改 Sortie Manager Container object for timers for expedition, construction, and repair */ (function(){ "use strict"; window.KC3TimerManager = { _exped: [], _repair: [], _build: [], init :function(eMap, rMap, bMap){ this._exped = [ new KC3Timer(eMap[0], 0, 0), new KC3Timer(eMap[1], 0, 1), new KC3Timer(eMap[2], 0, 2) ]; this._repair = [ new KC3Timer(rMap[0], 1, 0), new KC3Timer(rMap[1], 1, 1), new KC3Timer(rMap[2], 1, 2), new KC3Timer(rMap[3], 1, 3) ]; this._build = [ new KC3Timer(bMap[0], 2, 0), new KC3Timer(bMap[1], 2, 1), new KC3Timer(bMap[2], 2, 2), new KC3Timer(bMap[3], 2, 3) ]; }, exped :function(num){ return this._exped[num-2]; }, repair :function(num){ return this._repair[num-1]; }, build :function(num){ return this._build[num-1]; }, updateTimerElement : function(eMap, rMap, bMap){ this._exped[0].updateElement(eMap[0]); this._exped[1].updateElement(eMap[1]); this._exped[2].updateElement(eMap[2]); this._repair[0].updateElement(rMap[0]); this._repair[1].updateElement(rMap[1]); this._repair[2].updateElement(rMap[2]); this._repair[3].updateElement(rMap[3]); this._build[0].updateElement(bMap[0]); this._build[1].updateElement(bMap[1]); this._build[2].updateElement(bMap[2]); this._build[3].updateElement(bMap[3]); }, update: function(){ this._exped[0].time(); this._exped[1].time(); this._exped[2].time(); this._repair[0].time(); this._repair[1].time(); this._repair[2].time(); this._repair[3].time(); this._build[0].time(); this._build[1].time(); this._build[2].time(); this._build[3].time(); } }; })();
import React from 'react'; import TestUtils from 'react-addons-test-utils'; import { expect } from 'chai'; import { Hello } from 'client/components/Hello'; const setup = () => { const props = { message: 'hello' }; const renderer = TestUtils.createRenderer(); renderer.render(<Hello {...props} />); const output = renderer.getRenderOutput(); return { output }; }; describe('tests Hello component', () => { it('renders correctly', () => { const { output } = setup(); expect(output.type).to.eql('div'); expect(output.props.children).to.eql('hello'); }); });
import { rebind } from '@d3fc/d3fc-rebind'; import _slidingWindow from './slidingWindow'; import exponentialMovingAverage from './exponentialMovingAverage'; import { convertNaN } from './fn'; export default function() { let volumeValue = (d, i) => d.volume; let closeValue = (d, i) => d.close; const emaComputer = exponentialMovingAverage() .period(13); const slidingWindow = _slidingWindow() .period(2) .defined(d => closeValue(d) != null && volumeValue(d) != null) .accumulator(values => values && convertNaN((closeValue(values[1]) - closeValue(values[0])) * volumeValue(values[1]))); const force = data => { const forceIndex = slidingWindow(data); return emaComputer(forceIndex); }; force.volumeValue = (...args) => { if (!args.length) { return volumeValue; } volumeValue = args[0]; return force; }; force.closeValue = (...args) => { if (!args.length) { return closeValue; } closeValue = args[0]; return force; }; rebind(force, emaComputer, 'period'); return force; }
var format = require('util').format; var hl = require('highlight.js'); var escape = function(html) { return html. replace(/</g, '&lt;'). replace(/>/g, '&gt;'). replace(/"/g, '&quot;'). replace(/'/g, '&#39;'); }; try { var rs = require('robotskirt'); escape = rs.houdini.escapeHTML; } catch (e) { } exports.render = function(code, language) { language = exports.language(language); if (!language) { return '<pre>' + escape(code) + '</pre>'; } if (language === 'html') { language = 'xml'; } code = hl.highlight(language, code).value; return format( '<div class="highlight"><pre><code class="%s">%s</code></pre></div>', language, code ); }; exports.language = function(language) { if (!language) { return null; } if (language === 'html') { return 'html'; } var shortcuts = { 'js': 'javascript', 'json': 'javascript', 'py': 'python', 'rb': 'ruby', 'md': 'markdown', 'mkd': 'markdown', 'c++': 'cpp' }; if (language && shortcuts[language]) { language = shortcuts[language]; } if (!language || !hl.LANGUAGES[language]) { return null; } return language; };
/* * Copyright (c) 2013 Adobe Systems Incorporated. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * */ /*jslint vars: true, plusplus: true, devel: true, browser: true, nomen: true, indent: 4, maxerr: 50 */ /*global define, describe, it, expect, beforeEach, afterEach, waits, waitsFor, waitsForDone, runs, $, brackets, waitsForDone, spyOn */ define(function (require, exports, module) { "use strict"; var main = require("main"), FileUtils = brackets.getModule("file/FileUtils"), StaticServer = require("StaticServer"); var testFolder = FileUtils.getNativeModuleDirectoryPath(module) + "/unittest-files"; var CONNECT_TIMEOUT = 20000; function makeBaseUrl(serverInfo) { return "http://" + serverInfo.address + ":" + serverInfo.port; } function getUrl(serverInfo, path) { return $.get(makeBaseUrl(serverInfo) + path); } describe("StaticServer", function () { // Unit tests for the underlying node server. describe("StaticServerDomain", function () { var nodeConnection, nodeDomain, logs; beforeEach(function () { logs = []; if (!nodeConnection) { runs(function () { // wait for StaticServer/main to connect and load the StaticServerDomain nodeDomain = main._nodeDomain; nodeConnection = nodeDomain.connection; waitsFor(function () { return nodeDomain.ready(); }, "NodeConnection connected", CONNECT_TIMEOUT); }); runs(function () { $(nodeConnection).on("base.log", function (event, level, timestamp, message) { logs.push({level: level, message: message}); }); }); } }); afterEach(function () { runs(function () { // reset StaticServerDomain waitsForDone(nodeConnection.domains.staticServer._setRequestFilterTimeout(), "restore request filter timeout"); }); }); function onRequestFilter(callback) { // only handle the first event $(nodeConnection).one("staticServer.requestFilter", function cb(event, request) { callback(request); }); } it("should start a static server on the given folder", function () { var serverInfo, path = testFolder + "/folder1"; runs(function () { nodeConnection.domains.staticServer.getServer(path, 0) .done(function (info) { serverInfo = info; }); }); waitsFor(function () { return serverInfo; }, "waiting for static server to start"); runs(function () { expect(serverInfo.address).toBe("127.0.0.1"); expect(Number(serverInfo.port)).toBeGreaterThan(0); waitsForDone(nodeConnection.domains.staticServer.closeServer(path), "waiting for static server to close"); }); }); it("should start the server on the given port", function () { var serverInfo, path = testFolder + "/folder1"; runs(function () { nodeConnection.domains.staticServer.getServer(path, 54321) .done(function (info) { serverInfo = info; }); }); waitsFor(function () { return serverInfo; }, "waiting for static server to start"); runs(function () { expect(serverInfo.port).toBe(54321); waitsForDone(nodeConnection.domains.staticServer.closeServer(path), "waiting for static server to close"); }); }); it("should start a static server using a random port when the given port is already in use", function () { var serverInfo1, serverInfo2, path1 = testFolder + "/folder1", path2 = testFolder + "/folder2"; runs(function () { nodeConnection.domains.staticServer.getServer(path1, 54321) .done(function (info) { serverInfo1 = info; }); nodeConnection.domains.staticServer.getServer(path2, 54321) .done(function (info) { serverInfo2 = info; }); }); waitsFor(function () { return serverInfo1 && serverInfo2; }, "waiting for static servers to start"); runs(function () { expect(serverInfo1.port).toBe(54321); expect(serverInfo2.port).not.toBe(54321); expect(serverInfo2.port).toBeGreaterThan(0); waitsForDone(nodeConnection.domains.staticServer.closeServer(path1), "waiting for static server 1 to close"); waitsForDone(nodeConnection.domains.staticServer.closeServer(path2), "waiting for static server 2 to close"); }); }); it("should serve the text of a file in the given folder", function () { var serverInfo, text, path = testFolder + "/folder1"; runs(function () { nodeConnection.domains.staticServer.getServer(path, 0) .done(function (info) { serverInfo = info; }); }); waitsFor(function () { return serverInfo; }, "waiting for static server to start"); runs(function () { getUrl(serverInfo, "/index.txt").done(function (data) { text = data; }); }); waitsFor(function () { return text; }, "waiting for text from server"); runs(function () { expect(text).toBe("This is a file in folder 1."); waitsForDone(nodeConnection.domains.staticServer.closeServer(path), "waiting for static server to close"); }); }); it("should create separate servers for different folders", function () { var serverInfo1, serverInfo2, path1 = testFolder + "/folder1", path2 = testFolder + "/folder2"; runs(function () { nodeConnection.domains.staticServer.getServer(path1, 0) .done(function (info) { serverInfo1 = info; }); nodeConnection.domains.staticServer.getServer(path2, 0) .done(function (info) { serverInfo2 = info; }); }); waitsFor(function () { return serverInfo1 && serverInfo2; }, "waiting for static servers to start"); runs(function () { expect(serverInfo1.port).not.toBe(serverInfo2.port); waitsForDone(nodeConnection.domains.staticServer.closeServer(path1), "waiting for static server 1 to close"); waitsForDone(nodeConnection.domains.staticServer.closeServer(path2), "waiting for static server 2 to close"); }); }); it("should keep a previous server alive after creating a new server", function () { var serverInfo1, serverInfo2, path1 = testFolder + "/folder1", path2 = testFolder + "/folder2", text1, text2; runs(function () { nodeConnection.domains.staticServer.getServer(path1, 0) .done(function (info) { serverInfo1 = info; }); nodeConnection.domains.staticServer.getServer(path2, 0) .done(function (info) { serverInfo2 = info; }); }); waitsFor(function () { return serverInfo1 && serverInfo2; }, "waiting for static servers to start"); runs(function () { getUrl(serverInfo1, "/index.txt").done(function (data) { text1 = data; }); getUrl(serverInfo2, "/index.txt").done(function (data) { text2 = data; }); }); waitsFor(function () { return text1 && text2; }, "waiting for text from servers"); runs(function () { expect(text1).toBe("This is a file in folder 1."); expect(text2).toBe("This is a file in folder 2."); waitsForDone(nodeConnection.domains.staticServer.closeServer(path1), "waiting for static server 1 to close"); waitsForDone(nodeConnection.domains.staticServer.closeServer(path2), "waiting for static server 2 to close"); }); }); it("should trigger an event when a file path is requested", function () { var serverInfo, path = testFolder + "/folder1", text, location, elapsed, requestId, timeout = 500; runs(function () { nodeConnection.domains.staticServer.getServer(path, 0) .done(function (info) { serverInfo = info; }); }); waitsFor(function () { return serverInfo; }, "waiting for static server to start"); runs(function () { onRequestFilter(function (request) { location = request.location; requestId = request.id; // Do not call writeFilteredResponse in order to hit timeout }); // listen for /index.txt requests waitsForDone(nodeConnection.domains.staticServer.setRequestFilterPaths(path, ["/index.txt"])); // set a custom timeout waitsForDone(nodeConnection.domains.staticServer._setRequestFilterTimeout(timeout)); }); runs(function () { // it should take longer than the StaticServerDomain timeout to get a response elapsed = new Date(); // request /index.txt getUrl(serverInfo, "/index.txt").done(function (data) { elapsed = new Date() - elapsed; text = data; }); }); waitsFor(function () { return location && text; }, "waiting for request event to fire"); runs(function () { expect(requestId).toBeGreaterThan(-1); expect(location.pathname).toBe("/index.txt"); expect(text).toBe("This is a file in folder 1."); // we should hit the timeout since we filtered this path and did not respond expect(elapsed).toBeGreaterThan(timeout); waitsForDone(nodeConnection.domains.staticServer.closeServer(path), "waiting for static server to close"); }); }); it("should send static file contents after canceling a filter request", function () { var serverInfo, path = testFolder + "/folder1", text, location, requestId; runs(function () { nodeConnection.domains.staticServer.getServer(path, 0) .done(function (info) { serverInfo = info; }); }); waitsFor(function () { return serverInfo; }, "waiting for static server to start"); runs(function () { // listen for request event onRequestFilter(function (request) { location = request.location; requestId = request.id; nodeConnection.domains.staticServer.writeFilteredResponse(request.root, request.pathname, {id: requestId}); // a second call to send does nothing nodeConnection.domains.staticServer.writeFilteredResponse(request.root, request.pathname, {id : requestId, body: "custom response"}); }); // listen for /index.txt requests waitsForDone(nodeConnection.domains.staticServer.setRequestFilterPaths(path, ["/index.txt"])); }); runs(function () { // request /index.txt getUrl(serverInfo, "/index.txt").done(function (data) { text = data; }); }); waitsFor(function () { return location && text; }, "waiting for request event to fire"); runs(function () { expect(requestId).toBeGreaterThan(-1); expect(location.pathname).toBe("/index.txt"); expect(text).toBe("This is a file in folder 1."); waitsForDone(nodeConnection.domains.staticServer.closeServer(path), "waiting for static server to close"); }); }); it("should override the static file server response with a new response body", function () { var serverInfo, path = testFolder + "/folder1", text, location, requestId; runs(function () { nodeConnection.domains.staticServer.getServer(path, 0) .done(function (info) { serverInfo = info; }); }); waitsFor(function () { return serverInfo; }, "waiting for static server to start"); runs(function () { // listen for request event onRequestFilter(function (request) { location = request.location; requestId = request.id; nodeConnection.domains.staticServer.writeFilteredResponse(location.root, location.pathname, {id: requestId, body: "custom response"}); }); // listen for /index.txt requests waitsForDone(nodeConnection.domains.staticServer.setRequestFilterPaths(path, ["/index.txt"])); }); runs(function () { // request /index.txt getUrl(serverInfo, "/index.txt").done(function (data) { text = data; }); }); waitsFor(function () { return location && text; }, "waiting for text from server"); runs(function () { expect(requestId).toBeGreaterThan(-1); expect(location.pathname).toBe("/index.txt"); expect(text).toBe("custom response"); waitsForDone(nodeConnection.domains.staticServer.closeServer(path), "waiting for static server to close"); }); }); it("should ignore multiple responses for the same request", function () { var serverInfo, path = testFolder + "/folder1", text, location, requestId; runs(function () { nodeConnection.domains.staticServer.getServer(path, 0) .done(function (info) { serverInfo = info; }); }); waitsFor(function () { return serverInfo; }, "waiting for static server to start"); runs(function () { // listen for request event onRequestFilter(function (request) { location = request.location; requestId = request.id; nodeConnection.domains.staticServer.writeFilteredResponse(location.root, location.pathname, {id: requestId, body: "good response"}); nodeConnection.domains.staticServer.writeFilteredResponse(location.root, location.pathname, {id: requestId, body: "bad response"}); }); // listen for /index.txt requests waitsForDone(nodeConnection.domains.staticServer.setRequestFilterPaths(path, ["/index.txt"])); }); runs(function () { // request /index.txt getUrl(serverInfo, "/index.txt").done(function (data) { text = data; }); }); waitsFor( function () { return location && text && (logs.length > 0); }, "waiting for text from server and warning in log" ); runs(function () { expect(logs.length).toBe(1); expect(logs[0].level).toBe("warn"); expect(logs[0].message.indexOf("writeFilteredResponse")).toBe(0); expect(requestId).toBeGreaterThan(-1); expect(location.pathname).toBe("/index.txt"); expect(text).toBe("good response"); // cleanup waitsForDone(nodeConnection.domains.staticServer.closeServer(path), "waiting for static server to close"); }); }); it("should log a warning when writing to a non-existant request", function () { var serverInfo, path = testFolder + "/folder1", text, requestId = -1; spyOn(console, "warn").andCallThrough(); onRequestFilter(function (request) { requestId = request.id; }); runs(function () { nodeConnection.domains.staticServer.getServer(path, 0) .done(function (info) { serverInfo = info; }); }); waitsFor(function () { return serverInfo; }, "waiting for static server to start"); runs(function () { // write response before the request waitsForDone(nodeConnection.domains.staticServer.writeFilteredResponse(path, "/index.txt", {id: requestId, body: "custom response"})); }); runs(function () { // request /index.txt getUrl(serverInfo, "/index.txt").done(function (data) { text = data; }); }); runs(function () { // write response after the request waitsForDone(nodeConnection.domains.staticServer.writeFilteredResponse(path, "/index.txt", {id: requestId, body: "custom response"})); }); waitsFor(function () { return text; }, "waiting for text from server"); runs(function () { // verify console warning expect(logs.length).toBe(2); logs.forEach(function (log) { expect(log.level).toBe("warn"); expect(log.message.indexOf("writeFilteredResponse")).toBe(0); }); // verify original file content expect(text).toBe("This is a file in folder 1."); expect(requestId).toBe(-1); // cleanup waitsForDone(nodeConnection.domains.staticServer.closeServer(path), "waiting for static server to close"); }); }); it("should should require paths to be filtered for events to fire", function () { var serverInfo, path = testFolder + "/folder1", text = null, location = null, requestId = -1, elapsed, timeout = 500; runs(function () { nodeConnection.domains.staticServer.getServer(path, 0) .done(function (info) { serverInfo = info; }); }); waitsFor(function () { return serverInfo; }, "waiting for static server to start"); runs(function () { onRequestFilter(function (request) { location = request.location; requestId = request.id; }); // set a custom timeout waitsForDone(nodeConnection.domains.staticServer._setRequestFilterTimeout(timeout)); }); runs(function () { // it should take less than the 500ms timeout to get a response elapsed = new Date(); // request /index.txt getUrl(serverInfo, "/index.txt").done(function (data) { elapsed = new Date() - elapsed; text = data; }); }); waits(timeout); runs(function () { // requestFilter should never fire, location is never returned expect(location).toBeNull(); // original content expect(text).toBe("This is a file in folder 1."); // server should respond with original content before the timeout lapses expect(elapsed).toBeLessThan(timeout); expect(requestId).toBe(-1); waitsForDone(nodeConnection.domains.staticServer.closeServer(path), "waiting for static server to close"); }); }); }); // Unit tests for the StaticServerProvider that wraps the underlying node server. describe("StaticServer", function () { var projectPath = testFolder + "/", mockNodeDomain = { ready: function () { return true; } }, pathResolver = function (path) { if (path.indexOf(projectPath) === 0) { return path.slice(projectPath.length); } return path; }, config = { baseUrl: "http://localhost/", nodeDomain: mockNodeDomain, pathResolver: pathResolver, root: projectPath, port: 0 }; it("should translate local paths to server paths", function () { var outsidePath = testFolder.substr(0, testFolder.lastIndexOf("/") + 1), fileProtocol = (brackets.platform === "win") ? "file:///" : "file://", fileRelPath = "subdir/index.html", file1Path = projectPath + fileRelPath, file2Path = outsidePath + fileRelPath, file2FileUrl = encodeURI(fileProtocol + outsidePath + fileRelPath), file1ServerUrl = config.baseUrl + encodeURI(fileRelPath), server = new StaticServer(config); // Should use server url with base url expect(server.pathToUrl(file1Path)).toBe(file1ServerUrl); expect(server.urlToPath(file1ServerUrl)).toBe(file1Path); // File outside project should still use file url expect(server.pathToUrl(file2Path)).toBe(null); expect(server.urlToPath(file2FileUrl)).toBe(null); }); it("should only serve html files that are in the project file hierarchy", function () { var server = new StaticServer(config); // should not serve files outside project hierarchy expect(server.canServe("/foo.html")).toBe(false); // should not serve non-HTML files inside hierarchy expect(server.canServe(testFolder + "/foo.jpg")).toBe(false); // should serve .htm files inside hierarchy expect(server.canServe(testFolder + "/foo.htm")).toBe(true); // should serve .html files inside hierarchy expect(server.canServe(testFolder + "/foo.html")).toBe(true); // should serve .HTML files inside hierarchy expect(server.canServe(testFolder + "/foo.HTML")).toBe(true); // should serve root of hierarchy expect(server.canServe(testFolder + "/")).toBe(true); }); it("should decline serving if not connected to node", function () { // mock NodeConnection state to be disconnected config.nodeDomain = { ready: function () { return false; } }; var server = new StaticServer(config); expect(server.canServe(testFolder + "foo.html")).toBe(false); }); }); }); });
import BasePlugin from './../_base'; import {arrayEach} from './../../helpers/array'; import {CommandExecutor} from './commandExecutor'; import {EventManager} from './../../eventManager'; import {hasClass} from './../../helpers/dom/element'; import {ItemsFactory} from './itemsFactory'; import {Menu} from './menu'; import {objectEach, mixin} from './../../helpers/object'; import {registerPlugin} from './../../plugins'; import {stopPropagation, pageX, pageY} from './../../helpers/dom/event'; import {getWindowScrollLeft, getWindowScrollTop} from './../../helpers/dom/element'; import { ROW_ABOVE, ROW_BELOW, COLUMN_LEFT, COLUMN_RIGHT, REMOVE_ROW, REMOVE_COLUMN, UNDO, REDO, READ_ONLY, ALIGNMENT, SEPARATOR, predefinedItems } from './predefinedItems'; /** * @description * This plugin creates the Handsontable Context Menu. It allows to create new row or * column at any place in the grid among [other features](http://docs.handsontable.com/demo-context-menu.html). * Possible values: * * `true` (to enable default options), * * `false` (to disable completely) * * or array of any available strings: * * `["row_above", "row_below", "col_left", "col_right", * "remove_row", "remove_col", "---------", "undo", "redo"]`. * * See [the context menu demo](http://docs.handsontable.com/demo-context-menu.html) for examples. * * @example * ```js * ... * // as a boolean * contextMenu: true * ... * // as a array * contextMenu: ['row_above', 'row_below', '--------', 'undo', 'redo'] * ... * ``` * * @plugin ContextMenu */ class ContextMenu extends BasePlugin { /** * Default menu items order when `contextMenu` is enabled by `true`. * * @returns {Array} */ static get DEFAULT_ITEMS() { return [ ROW_ABOVE, ROW_BELOW, SEPARATOR, COLUMN_LEFT, COLUMN_RIGHT, SEPARATOR, REMOVE_ROW, REMOVE_COLUMN, SEPARATOR, UNDO, REDO, SEPARATOR, READ_ONLY, SEPARATOR, ALIGNMENT, ]; } constructor(hotInstance) { super(hotInstance); /** * Instance of {@link EventManager}. * * @type {EventManager} */ this.eventManager = new EventManager(this); /** * Instance of {@link CommandExecutor}. * * @type {CommandExecutor} */ this.commandExecutor = new CommandExecutor(this.hot); /** * Instance of {@link ItemsFactory}. * * @type {ItemsFactory} */ this.itemsFactory = null; /** * Instance of {@link Menu}. * * @type {Menu} */ this.menu = null; } /** * Check if the plugin is enabled in the Handsontable settings. * * @returns {Boolean} */ isEnabled() { return this.hot.getSettings().contextMenu; } /** * Enable plugin for this Handsontable instance. */ enablePlugin() { if (this.enabled) { return; } this.itemsFactory = new ItemsFactory(this.hot, ContextMenu.DEFAULT_ITEMS); const settings = this.hot.getSettings().contextMenu; let predefinedItems = { items: this.itemsFactory.getVisibleItems(settings) }; this.registerEvents(); if (typeof settings.callback === 'function') { this.commandExecutor.setCommonCallback(settings.callback); } super.enablePlugin(); this.callOnPluginsReady(() => { this.hot.runHooks('afterContextMenuDefaultOptions', predefinedItems); this.itemsFactory.setPredefinedItems(predefinedItems.items); let menuItems = this.itemsFactory.getVisibleItems(settings); this.menu = new Menu(this.hot, {className: 'htContextMenu', keepInViewport: true}); this.menu.setMenuItems(menuItems); this.menu.addLocalHook('afterOpen', () => this.onMenuAfterOpen()); this.menu.addLocalHook('afterClose', () => this.onMenuAfterClose()); this.menu.addLocalHook('executeCommand', (...params) => this.executeCommand.apply(this, params)); // Register all commands. Predefined and added by user or by plugins arrayEach(menuItems, (command) => this.commandExecutor.registerCommand(command.key, command)); }); } /** * Update the plugin according to Handsontable settings. */ updatePlugin() { this.disablePlugin(); this.enablePlugin(); super.updatePlugin(); } /** * Disable plugin for this Handsontable instance. */ disablePlugin() { this.close(); if (this.menu) { this.menu.destroy(); this.menu = null; } super.disablePlugin(); } /** * Register dom listeners. * * @private */ registerEvents() { this.eventManager.addEventListener(this.hot.rootElement, 'contextmenu', (event) => this.onContextMenu(event)); } /** * Open menu and re-position it based on dom event object. * * @param {Event} event The event object. */ open(event) { if (!this.menu) { return; } this.menu.open(); this.menu.setPosition({ top: parseInt(pageY(event), 10) - getWindowScrollTop(), left: parseInt(pageX(event), 10) - getWindowScrollLeft(), }); // ContextMenu is not detected HotTableEnv correctly because is injected outside hot-table this.menu.hotMenu.isHotTableEnv = this.hot.isHotTableEnv; Handsontable.eventManager.isHotTableEnv = this.hot.isHotTableEnv; } /** * Close menu. */ close() { if (!this.menu) { return; } this.menu.close(); } /** * Execute context menu command. * * You can execute all predefined commands: * * `'row_above'` - Insert row above * * `'row_below'` - Insert row below * * `'col_left'` - Insert column on the left * * `'col_right'` - Insert column on the right * * `'clear_column'` - Clear selected column * * `'remove_row'` - Remove row * * `'remove_col'` - Remove column * * `'undo'` - Undo last action * * `'redo'` - Redo last action * * `'make_read_only'` - Make cell read only * * `'alignment:left'` - Alignment to the left * * `'alignment:top'` - Alignment to the top * * `'alignment:right'` - Alignment to the right * * `'alignment:bottom'` - Alignment to the bottom * * `'alignment:middle'` - Alignment to the middle * * `'alignment:center'` - Alignment to the center (justify) * * Or you can execute command registered in settings where `key` is your command name. * * @param {String} commandName * @param {*} params */ executeCommand(...params) { this.commandExecutor.execute.apply(this.commandExecutor, params); } /** * On context menu listener. * * @private * @param {Event} event */ onContextMenu(event) { let settings = this.hot.getSettings(); let showRowHeaders = settings.rowHeaders; let showColHeaders = settings.colHeaders; function isValidElement(element) { return element.nodeName === 'TD' || element.parentNode.nodeName === 'TD'; } // if event is from hot-table we must get web component element not element inside him let element = event.realTarget; this.close(); event.preventDefault(); stopPropagation(event); if (!(showRowHeaders || showColHeaders)) { if (!isValidElement(element) && !(hasClass(element, 'current') && hasClass(element, 'wtBorder'))) { return; } } else if (showRowHeaders && showColHeaders) { // do nothing after right-click on corner header let containsCornerHeader = element.parentNode.querySelectorAll('.cornerHeader').length > 0; if (containsCornerHeader) { return; } } this.open(event); } /** * On menu after open listener. * * @private */ onMenuAfterOpen() { this.hot.runHooks('afterContextMenuShow', this); } /** * On menu after close listener. * * @private */ onMenuAfterClose() { this.hot.listen(); this.hot.runHooks('afterContextMenuHide', this); } /** * Destroy instance. */ destroy() { this.close(); if (this.menu) { this.menu.destroy(); } super.destroy(); } } ContextMenu.SEPARATOR = { name: SEPARATOR }; Handsontable.hooks.register('afterContextMenuDefaultOptions'); Handsontable.hooks.register('afterContextMenuShow'); Handsontable.hooks.register('afterContextMenuHide'); Handsontable.hooks.register('afterContextMenuExecute'); export {ContextMenu}; registerPlugin('contextMenu', ContextMenu);
/* * The MIT License * * Copyright (c) 2015, Sebastian Sdorra * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ 'use strict'; angular.module('adf') .directive('adfWidget', function($log, $modal, dashboard, adfTemplatePath) { function preLink($scope) { var definition = $scope.definition; if (definition) { var w = dashboard.widgets[definition.type]; if (w) { // pass title if (!definition.title) { definition.title = w.title; } if (!definition.titleTemplateUrl) { definition.titleTemplateUrl = adfTemplatePath + 'widget-title.html'; if (w.titleTemplateUrl) { definition.titleTemplateUrl = w.titleTemplateUrl; } } if (!definition.titleTemplateUrl) { definition.frameless = w.frameless; } // set id for sortable if (!definition.wid) { definition.wid = dashboard.id(); } // pass copy of widget to scope $scope.widget = angular.copy(w); // create config object var config = definition.config; if (config) { if (angular.isString(config)) { config = angular.fromJson(config); } } else { config = {}; } // pass config to scope $scope.config = config; // collapse exposed $scope.widgetState property if (!$scope.widgetState) { $scope.widgetState = {}; $scope.widgetState.isCollapsed = false; } } else { $log.warn('could not find widget ' + definition.type); } } else { $log.debug('definition not specified, widget was probably removed'); } } function postLink($scope, $element) { var definition = $scope.definition; if (definition) { // bind close function var deleteWidget = function() { var column = $scope.col; if (column) { var index = column.widgets.indexOf(definition); if (index >= 0) { column.widgets.splice(index, 1); } } $element.remove(); }; $scope.remove = function() { if ($scope.options.enableConfirmDelete) { var deleteScope = $scope.$new(); var deleteTemplateUrl = adfTemplatePath + 'widget-delete.html'; if (definition.deleteTemplateUrl) { deleteTemplateUrl = definition.deleteTemplateUrl; } var opts = { scope: deleteScope, templateUrl: deleteTemplateUrl, backdrop: 'static' }; var instance = $modal.open(opts); deleteScope.closeDialog = function() { instance.close(); deleteScope.$destroy(); }; deleteScope.deleteDialog = function() { deleteWidget(); deleteScope.closeDialog(); }; } else { deleteWidget(); } }; // bind reload function $scope.reload = function() { $scope.$broadcast('widgetReload'); }; // bind edit function $scope.edit = function() { var editScope = $scope.$new(); editScope.definition = angular.copy(definition); var adfEditTemplatePath = adfTemplatePath + 'widget-edit.html'; if (definition.editTemplateUrl) { adfEditTemplatePath = definition.editTemplateUrl; } var opts = { scope: editScope, templateUrl: adfEditTemplatePath, backdrop: 'static' }; var instance = $modal.open(opts); editScope.closeDialog = function() { instance.close(); editScope.$destroy(); }; editScope.saveDialog = function() { definition.title = editScope.definition.title; angular.extend(definition.config, editScope.definition.config); var widget = $scope.widget; if (widget.edit && widget.edit.reload) { // reload content after edit dialog is closed $scope.$broadcast('widgetConfigChanged'); } editScope.closeDialog(); }; }; } else { $log.debug('widget not found'); } } return { replace: true, restrict: 'EA', transclude: false, templateUrl: adfTemplatePath + 'widget.html', scope: { definition: '=', col: '=column', editMode: '=', options: '=', widgetState: '=' }, controller: function($scope) { $scope.$on('adfDashboardCollapseExapand', function(event, args) { $scope.widgetState.isCollapsed = args.collapseExpandStatus; }); $scope.openFullScreen = function() { var definition = $scope.definition; var fullScreenScope = $scope.$new(); var opts = { scope: fullScreenScope, templateUrl: adfTemplatePath + 'widget-fullscreen.html', size: definition.modalSize || 'lg', // 'sm', 'lg' backdrop: 'static', windowClass: (definition.fullScreen) ? 'dashboard-modal widget-fullscreen' : 'dashboard-modal' }; var instance = $modal.open(opts); fullScreenScope.closeDialog = function() { instance.close(); fullScreenScope.$destroy(); }; }; }, compile: function() { /** * use pre link, because link of widget-content * is executed before post link widget */ return { pre: preLink, post: postLink }; } }; });
'use strict'; // Check that main thread handles an unknown message type from a worker thread // as expected. require('../common'); const assert = require('assert'); const { spawnSync } = require('child_process'); const { Worker } = require('worker_threads'); if (process.argv[2] !== 'spawned') { const result = spawnSync(process.execPath, [ '--expose-internals', __filename, 'spawned'], { encoding: 'utf8' }); assert.ok(result.stderr.includes('Unknown worker message type FHQWHGADS'), `Expected error not found in: ${result.stderr}`); } else { new Worker(` const { internalBinding } = require('internal/test/binding'); const { getEnvMessagePort } = internalBinding('worker'); const messagePort = getEnvMessagePort(); messagePort.postMessage({ type: 'FHQWHGADS' }); `, { eval: true }); }
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _reactAddonsPureRenderMixin = require('react-addons-pure-render-mixin'); var _reactAddonsPureRenderMixin2 = _interopRequireDefault(_reactAddonsPureRenderMixin); var _svgIcon = require('../../svg-icon'); var _svgIcon2 = _interopRequireDefault(_svgIcon); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var PlacesSmokingRooms = _react2.default.createClass({ displayName: 'PlacesSmokingRooms', mixins: [_reactAddonsPureRenderMixin2.default], render: function render() { return _react2.default.createElement( _svgIcon2.default, this.props, _react2.default.createElement('path', { d: 'M2 16h15v3H2zm18.5 0H22v3h-1.5zM18 16h1.5v3H18zm.85-8.27c.62-.61 1-1.45 1-2.38C19.85 3.5 18.35 2 16.5 2v1.5c1.02 0 1.85.83 1.85 1.85S17.52 7.2 16.5 7.2v1.5c2.24 0 4 1.83 4 4.07V15H22v-2.24c0-2.22-1.28-4.14-3.15-5.03zm-2.82 2.47H14.5c-1.02 0-1.85-.98-1.85-2s.83-1.75 1.85-1.75v-1.5c-1.85 0-3.35 1.5-3.35 3.35s1.5 3.35 3.35 3.35h1.53c1.05 0 1.97.74 1.97 2.05V15h1.5v-1.64c0-1.81-1.6-3.16-3.47-3.16z' }) ); } }); exports.default = PlacesSmokingRooms; module.exports = exports['default'];
'use strict'; var angular = require('angular'); angular .module('mwl.calendar') .controller('MwlDragSelectCtrl', function($scope, $element, $parse, $attrs) { function handleMouseEvent(callbackName) { return function(event) { if (callbackName) { $parse(callbackName)($scope); $scope.$apply(); } event.preventDefault(); }; } var onMouseDown = handleMouseEvent($attrs.onDragSelectStart); var onMouseMove = handleMouseEvent($attrs.onDragSelectMove); var onMouseUp = handleMouseEvent($attrs.onDragSelectEnd); function enableMouseListeners() { $element.on('mousedown', onMouseDown); $element.on('mousemove', onMouseMove); $element.on('mouseup', onMouseUp); } function disableMouseListeners() { $element.off('mousedown', onMouseDown); $element.off('mousemove', onMouseMove); $element.off('mouseup', onMouseUp); } $scope.$watch($attrs.mwlDragSelect, function(isEnabled) { if (isEnabled) { enableMouseListeners(); } else { disableMouseListeners(); } }); $scope.$on('$destroy', function() { disableMouseListeners(); }); }) .directive('mwlDragSelect', function() { return { restrict: 'A', controller: 'MwlDragSelectCtrl' }; });
export default class BatchDeleteController { constructor($scope, $state, WriteQueries, notification, view) { this.$scope = $scope; this.$state = $state; this.WriteQueries = WriteQueries; this.notification = notification; this.view = view; this.entity = view.getEntity(); this.entityIds = $state.params.ids; this.selection = []; // fixme: query db to get selection this.title = view.title(); this.description = view.description(); this.actions = view.actions(); this.loadingPage = false; this.fields = view.fields(); $scope.$on('$destroy', this.destroy.bind(this)); } batchDelete() { var notification = this.notification, $state = this.$state, entityName = this.entity.name(); this.WriteQueries.batchDelete(this.view, this.entityIds).then(function () { $state.go($state.get('list'), angular.extend({ entity: entityName }, $state.params)); notification.log('Elements successfully deleted.', { addnCls: 'humane-flatty-success' }); }, function (response) { // @TODO: share this method when splitting controllers var body = response.data; if (typeof body === 'object') { body = JSON.stringify(body); } notification.log('Oops, an error occured : (code: ' + response.status + ') ' + body, {addnCls: 'humane-flatty-error'}); }); } back() { this.$state.go(this.$state.get('list'), angular.extend({ entity: this.entity.name() }, this.$state.params)); } destroy() { this.$scope = undefined; this.$state = undefined; this.WriteQueries = undefined; } } BatchDeleteController.$inject = ['$scope', '$state', 'WriteQueries', 'notification', 'view'];
const helpers = require("./global-setup"); const path = require("path"); const request = require("request"); const expect = require("chai").expect; const describe = global.describe; const it = global.it; const beforeEach = global.beforeEach; const afterEach = global.afterEach; describe("Position of modules", function () { helpers.setupTimeout(this); var app = null; describe("Using helloworld", function () { after(function () { return helpers.stopApplication(app); }); before(function () { // Set config sample for use in test process.env.MM_CONFIG_FILE = "tests/configs/modules/positions.js"; return helpers.startApplication({ args: ["js/electron.js"] }).then(function (startedApp) { app = startedApp; }) }); var positions = ["top_bar", "top_left", "top_center", "top_right", "upper_third", "middle_center", "lower_third", "bottom_left", "bottom_center", "bottom_right", "bottom_bar", "fullscreen_above", "fullscreen_below"]; var position; var className; for (idx in positions) { position = positions[idx]; className = position.replace("_", "."); it("show text in " + position, function () { return app.client.waitUntilWindowLoaded() .getText("." + className).should.eventually.equal("Text in " + position); }); } }); });
'use strict'; const assert = require('./../../assert'); const common = require('./../../common'); let battle; describe(`Pursuit`, function () { afterEach(() => battle.destroy()); it(`should execute before the target switches out and after the user mega evolves`, function () { battle = common.createBattle(); battle.join('p1', 'Guest 1', 1, [{species: "Beedrill", ability: 'swarm', item: 'beedrillite', moves: ['pursuit']}]); battle.join('p2', 'Guest 2', 1, [{species: "Alakazam", ability: 'magicguard', moves: ['psyshock']}, {species: "Clefable", ability: 'unaware', moves: ['calmmind']}]); battle.p1.chooseMove('pursuit', null, true); battle.p2.chooseSwitch(2); assert.species(battle.p1.active[0], "Beedrill-Mega"); assert.fainted(battle.p2.active[0]); }); });
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /** * @name: S15.10.1_A1_T4; * @section: 15.10.1; * @assertion: RegExp syntax errors must be caught when matcher(s) compiles; * @description: Tested RegExp is "a+++"; */ //CHECK#1 try { $ERROR('#1.1: new RegExp("a+++") throw SyntaxError. Actual: ' + (new RegExp("a+++"))); } catch (e) { if ((e instanceof SyntaxError) !== true) { $ERROR('#1.2: new RegExp("a+++") throw SyntaxError. Actual: ' + (e)); } }
version https://git-lfs.github.com/spec/v1 oid sha256:7bb2ff95b5b5b8b9381c3164c00724bbcf60a5e3a249bffc29cd3c7030ebda2a size 5862
import Stream from "./stream"; /* Check whether an object is a stream or not @public @for Ember.stream @function isStream @param {Object|Stream} object object to check whether it is a stream @return {Boolean} `true` if the object is a stream, `false` otherwise */ export function isStream(object) { return object && object.isStream; } /* A method of subscribing to a stream which is safe for use with a non-stream object. If a non-stream object is passed, the function does nothing. @public @for Ember.stream @function subscribe @param {Object|Stream} object object or stream to potentially subscribe to @param {Function} callback function to run when stream value changes @param {Object} [context] the callback will be executed with this context if it is provided */ export function subscribe(object, callback, context) { if (object && object.isStream) { return object.subscribe(callback, context); } } /* A method of unsubscribing from a stream which is safe for use with a non-stream object. If a non-stream object is passed, the function does nothing. @public @for Ember.stream @function unsubscribe @param {Object|Stream} object object or stream to potentially unsubscribe from @param {Function} callback function originally passed to `subscribe()` @param {Object} [context] object originally passed to `subscribe()` */ export function unsubscribe(object, callback, context) { if (object && object.isStream) { object.unsubscribe(callback, context); } } /* Retrieve the value of a stream, or in the case a non-stream object is passed, return the object itself. @public @for Ember.stream @function read @param {Object|Stream} object object to return the value of @return the stream's current value, or the non-stream object itself */ export function read(object) { if (object && object.isStream) { return object.value(); } else { return object; } } /* Map an array, replacing any streams with their values. @public @for Ember.stream @function readArray @param {Array} array The array to read values from @return {Array} a new array of the same length with the values of non-stream objects mapped from their original positions untouched, and the values of stream objects retaining their original position and replaced with the stream's current value. */ export function readArray(array) { var length = array.length; var ret = new Array(length); for (var i = 0; i < length; i++) { ret[i] = read(array[i]); } return ret; } /* Map a hash, replacing any stream property values with the current value of that stream. @public @for Ember.stream @function readHash @param {Object} object The hash to read keys and values from @return {Object} a new object with the same keys as the passed object. The property values in the new object are the original values in the case of non-stream objects, and the streams' current values in the case of stream objects. */ export function readHash(object) { var ret = {}; for (var key in object) { ret[key] = read(object[key]); } return ret; } /* Check whether an array contains any stream values @public @for Ember.stream @function scanArray @param {Array} array array given to a handlebars helper @return {Boolean} `true` if the array contains a stream/bound value, `false` otherwise */ export function scanArray(array) { var length = array.length; var containsStream = false; for (var i = 0; i < length; i++) { if (isStream(array[i])) { containsStream = true; break; } } return containsStream; } /* Check whether a hash has any stream property values @public @for Ember.stream @function scanHash @param {Object} hash "hash" argument given to a handlebars helper @return {Boolean} `true` if the object contains a stream/bound value, `false` otherwise */ export function scanHash(hash) { var containsStream = false; for (var prop in hash) { if (isStream(hash[prop])) { containsStream = true; break; } } return containsStream; } /* Join an array, with any streams replaced by their current values @public @for Ember.stream @function concat @param {Array} array An array containing zero or more stream objects and zero or more non-stream objects @param {String} separator string to be used to join array elements @return {String} String with array elements concatenated and joined by the provided separator, and any stream array members having been replaced by the current value of the stream */ export function concat(array, separator) { // TODO: Create subclass ConcatStream < Stream. Defer // subscribing to streams until the value() is called. var hasStream = scanArray(array); if (hasStream) { var i, l; var stream = new Stream(function() { return concat(readArray(array), separator); }, function() { var labels = labelsFor(array); return `concat([${labels.join(', ')}]; separator=${inspect(separator)})`; }); for (i = 0, l=array.length; i < l; i++) { subscribe(array[i], stream.notify, stream); } // used by angle bracket components to detect an attribute was provided // as a string literal stream.isConcat = true; return stream; } else { return array.join(separator); } } export function labelsFor(streams) { var labels = []; for (var i=0, l=streams.length; i<l; i++) { var stream = streams[i]; labels.push(labelFor(stream)); } return labels; } export function labelsForObject(streams) { var labels = []; for (var prop in streams) { labels.push(`${prop}: ${inspect(streams[prop])}`); } return labels.length ? `{ ${labels.join(', ')} }` : "{}"; } export function labelFor(maybeStream) { if (isStream(maybeStream)) { var stream = maybeStream; return typeof stream.label === 'function' ? stream.label() : stream.label; } else { return inspect(maybeStream); } } function inspect(value) { switch (typeof value) { case 'string': return `"${value}"`; case 'object': return "{ ... }"; case 'function': return "function() { ... }"; default: return String(value); } } export function or(first, second) { var stream = new Stream(function() { return first.value() || second.value(); }, function() { return `${labelFor(first)} || ${labelFor(second)}`; }); stream.addDependency(first); stream.addDependency(second); return stream; } export function addDependency(stream, dependency) { Ember.assert("Cannot add a stream as a dependency to a non-stream", isStream(stream) || !isStream(dependency)); if (isStream(stream)) { stream.addDependency(dependency); } } export function zip(streams, callback, label) { Ember.assert("Must call zip with a label", !!label); var stream = new Stream(function() { var array = readArray(streams); return callback ? callback(array) : array; }, function() { return `${label}(${labelsFor(streams)})`; }); for (var i=0, l=streams.length; i<l; i++) { stream.addDependency(streams[i]); } return stream; } export function zipHash(object, callback, label) { Ember.assert("Must call zipHash with a label", !!label); var stream = new Stream(function() { var hash = readHash(object); return callback ? callback(hash) : hash; }, function() { return `${label}(${labelsForObject(object)})`; }); for (var prop in object) { stream.addDependency(object[prop]); } return stream; } /** Generate a new stream by providing a source stream and a function that can be used to transform the stream's value. In the case of a non-stream object, returns the result of the function. The value to transform would typically be available to the function you pass to `chain()` via scope. For example: ```javascript var source = ...; // stream returning a number // or a numeric (non-stream) object var result = chain(source, function() { var currentValue = read(source); return currentValue + 1; }); ``` In the example, result is a stream if source is a stream, or a number of source was numeric. @public @for Ember.stream @function chain @param {Object|Stream} value A stream or non-stream object @param {Function} fn function to be run when the stream value changes, or to be run once in the case of a non-stream object @return {Object|Stream} In the case of a stream `value` parameter, a new stream that will be updated with the return value of the provided function `fn`. In the case of a non-stream object, the return value of the provided function `fn`. */ export function chain(value, fn, label) { Ember.assert("Must call chain with a label", !!label); if (isStream(value)) { var stream = new Stream(fn, function() { return `${label}(${labelFor(value)})`; }); stream.addDependency(value); return stream; } else { return fn(); } } export function setValue(object, value) { if (object && object.isStream) { object.setValue(value); } }
/************************************************************* * * MathJax/jax/output/HTML-CSS/fonts/TeX/AMS/Regular/Arrows.js * * Copyright (c) 2009-2016 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.Insert( MathJax.OutputJax['HTML-CSS'].FONTDATA.FONTS['MathJax_AMS'], { 0x2190: [437,-64,500,64,422], // LEFTWARDS ARROW 0x2192: [437,-64,500,58,417], // RIGHTWARDS ARROW 0x219A: [437,-60,1000,56,942], // LEFTWARDS ARROW WITH STROKE 0x219B: [437,-60,1000,54,942], // RIGHTWARDS ARROW WITH STROKE 0x219E: [417,-83,1000,56,944], // LEFTWARDS TWO HEADED ARROW 0x21A0: [417,-83,1000,55,943], // RIGHTWARDS TWO HEADED ARROW 0x21A2: [417,-83,1111,56,1031], // LEFTWARDS ARROW WITH TAIL 0x21A3: [417,-83,1111,79,1054], // RIGHTWARDS ARROW WITH TAIL 0x21AB: [575,41,1000,56,964], // LEFTWARDS ARROW WITH LOOP 0x21AC: [575,41,1000,35,943], // RIGHTWARDS ARROW WITH LOOP 0x21AD: [417,-83,1389,57,1331], // LEFT RIGHT WAVE ARROW 0x21AE: [437,-60,1000,56,942], // LEFT RIGHT ARROW WITH STROKE 0x21B0: [722,0,500,56,444], // UPWARDS ARROW WITH TIP LEFTWARDS 0x21B1: [722,0,500,55,443], // UPWARDS ARROW WITH TIP RIGHTWARDS 0x21B6: [461,1,1000,17,950], // ANTICLOCKWISE TOP SEMICIRCLE ARROW 0x21B7: [460,1,1000,46,982], // CLOCKWISE TOP SEMICIRCLE ARROW 0x21BA: [650,83,778,56,722], // ANTICLOCKWISE OPEN CIRCLE ARROW 0x21BB: [650,83,778,56,721], // CLOCKWISE OPEN CIRCLE ARROW 0x21BE: [694,194,417,188,375], // UPWARDS HARPOON WITH BARB RIGHTWARDS 0x21BF: [694,194,417,41,228], // UPWARDS HARPOON WITH BARB LEFTWARDS 0x21C2: [694,194,417,188,375], // DOWNWARDS HARPOON WITH BARB RIGHTWARDS 0x21C3: [694,194,417,41,228], // DOWNWARDS HARPOON WITH BARB LEFTWARDS 0x21C4: [667,0,1000,55,944], // RIGHTWARDS ARROW OVER LEFTWARDS ARROW 0x21C6: [667,0,1000,55,944], // LEFTWARDS ARROW OVER RIGHTWARDS ARROW 0x21C7: [583,83,1000,55,944], // LEFTWARDS PAIRED ARROWS 0x21C8: [694,193,833,83,749], // UPWARDS PAIRED ARROWS 0x21C9: [583,83,1000,55,944], // RIGHTWARDS PAIRED ARROWS 0x21CA: [694,194,833,83,749], // DOWNWARDS PAIRED ARROWS 0x21CB: [514,14,1000,55,944], // LEFTWARDS HARPOON OVER RIGHTWARDS HARPOON 0x21CC: [514,14,1000,55,944], // RIGHTWARDS HARPOON OVER LEFTWARDS HARPOON 0x21CD: [534,35,1000,54,942], // LEFTWARDS DOUBLE ARROW WITH STROKE 0x21CE: [534,37,1000,32,965], // LEFT RIGHT DOUBLE ARROW WITH STROKE 0x21CF: [534,35,1000,55,943], // RIGHTWARDS DOUBLE ARROW WITH STROKE 0x21DA: [611,111,1000,76,944], // LEFTWARDS TRIPLE ARROW 0x21DB: [611,111,1000,55,923], // RIGHTWARDS TRIPLE ARROW 0x21DD: [417,-83,1000,56,943], // RIGHTWARDS SQUIGGLE ARROW 0x21E0: [437,-64,1334,64,1251], // LEFTWARDS DASHED ARROW 0x21E2: [437,-64,1334,84,1251] // RIGHTWARDS DASHED ARROW } ); MathJax.Ajax.loadComplete(MathJax.OutputJax["HTML-CSS"].fontDir + "/AMS/Regular/Arrows.js");
/* * Copyright 2010 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Externs for the Google Maps v3 API. * @see http://code.google.com/apis/maps/documentation/javascript/reference.html * @externs */ google.maps = {}; /** * @enum {number|string} */ google.maps.Animation = { BOUNCE: '', DROP: '' }; /** * @extends {google.maps.MVCObject} * @constructor */ google.maps.BicyclingLayer = function() {}; /** * @nosideeffects * @return {google.maps.Map} */ google.maps.BicyclingLayer.prototype.getMap = function() {}; /** * @param {google.maps.Map} map * @return {undefined} */ google.maps.BicyclingLayer.prototype.setMap = function(map) {}; /** * @param {(google.maps.CircleOptions|Object.<string>)=} opt_opts * @extends {google.maps.MVCObject} * @constructor */ google.maps.Circle = function(opt_opts) {}; /** * @nosideeffects * @return {google.maps.LatLngBounds} */ google.maps.Circle.prototype.getBounds = function() {}; /** * @nosideeffects * @return {google.maps.LatLng} */ google.maps.Circle.prototype.getCenter = function() {}; /** * @nosideeffects * @return {boolean} */ google.maps.Circle.prototype.getEditable = function() {}; /** * @nosideeffects * @return {google.maps.Map} */ google.maps.Circle.prototype.getMap = function() {}; /** * @nosideeffects * @return {number} */ google.maps.Circle.prototype.getRadius = function() {}; /** * @nosideeffects * @return {boolean} */ google.maps.Circle.prototype.getVisible = function() {}; /** * @param {google.maps.LatLng} center * @return {undefined} */ google.maps.Circle.prototype.setCenter = function(center) {}; /** * @param {boolean} editable * @return {undefined} */ google.maps.Circle.prototype.setEditable = function(editable) {}; /** * @param {google.maps.Map} map * @return {undefined} */ google.maps.Circle.prototype.setMap = function(map) {}; /** * @param {google.maps.CircleOptions|Object.<string>} options * @return {undefined} */ google.maps.Circle.prototype.setOptions = function(options) {}; /** * @param {number} radius * @return {undefined} */ google.maps.Circle.prototype.setRadius = function(radius) {}; /** * @param {boolean} visible * @return {undefined} */ google.maps.Circle.prototype.setVisible = function(visible) {}; /** * @constructor */ google.maps.CircleOptions = function() {}; /** * @type {google.maps.LatLng} */ google.maps.CircleOptions.prototype.center; /** * @type {boolean} */ google.maps.CircleOptions.prototype.clickable; /** * @type {boolean} */ google.maps.CircleOptions.prototype.editable; /** * @type {string} */ google.maps.CircleOptions.prototype.fillColor; /** * @type {number} */ google.maps.CircleOptions.prototype.fillOpacity; /** * @type {google.maps.Map} */ google.maps.CircleOptions.prototype.map; /** * @type {number} */ google.maps.CircleOptions.prototype.radius; /** * @type {string} */ google.maps.CircleOptions.prototype.strokeColor; /** * @type {number} */ google.maps.CircleOptions.prototype.strokeOpacity; /** * @type {number} */ google.maps.CircleOptions.prototype.strokeWeight; /** * @type {boolean} */ google.maps.CircleOptions.prototype.visible; /** * @type {number} */ google.maps.CircleOptions.prototype.zIndex; /** * @enum {number|string} */ google.maps.ControlPosition = { BOTTOM_CENTER: '', BOTTOM_LEFT: '', BOTTOM_RIGHT: '', LEFT_BOTTOM: '', LEFT_CENTER: '', LEFT_TOP: '', RIGHT_BOTTOM: '', RIGHT_CENTER: '', RIGHT_TOP: '', TOP_CENTER: '', TOP_LEFT: '', TOP_RIGHT: '' }; /** * @constructor */ google.maps.DirectionsLeg = function() {}; /** * @type {google.maps.Distance} */ google.maps.DirectionsLeg.prototype.arrival_time; /** * @type {google.maps.Duration} */ google.maps.DirectionsLeg.prototype.departure_time; /** * @type {google.maps.Distance} */ google.maps.DirectionsLeg.prototype.distance; /** * @type {google.maps.Duration} */ google.maps.DirectionsLeg.prototype.duration; /** * @type {string} */ google.maps.DirectionsLeg.prototype.end_address; /** * @type {google.maps.LatLng} */ google.maps.DirectionsLeg.prototype.end_location; /** * @type {string} */ google.maps.DirectionsLeg.prototype.start_address; /** * @type {google.maps.LatLng} */ google.maps.DirectionsLeg.prototype.start_location; /** * @type {Array.<google.maps.DirectionsStep>} */ google.maps.DirectionsLeg.prototype.steps; /** * @type {Array.<google.maps.LatLng>} */ google.maps.DirectionsLeg.prototype.via_waypoints; /** * @param {(google.maps.DirectionsRendererOptions|Object.<string>)=} opt_opts * @extends {google.maps.MVCObject} * @constructor */ google.maps.DirectionsRenderer = function(opt_opts) {}; /** * @nosideeffects * @return {google.maps.DirectionsResult} */ google.maps.DirectionsRenderer.prototype.getDirections = function() {}; /** * @nosideeffects * @return {google.maps.Map} */ google.maps.DirectionsRenderer.prototype.getMap = function() {}; /** * @nosideeffects * @return {Node} */ google.maps.DirectionsRenderer.prototype.getPanel = function() {}; /** * @nosideeffects * @return {number} */ google.maps.DirectionsRenderer.prototype.getRouteIndex = function() {}; /** * @param {google.maps.DirectionsResult} directions * @return {undefined} */ google.maps.DirectionsRenderer.prototype.setDirections = function(directions) {}; /** * @param {google.maps.Map} map * @return {undefined} */ google.maps.DirectionsRenderer.prototype.setMap = function(map) {}; /** * @param {google.maps.DirectionsRendererOptions|Object.<string>} options * @return {undefined} */ google.maps.DirectionsRenderer.prototype.setOptions = function(options) {}; /** * @param {Node} panel * @return {undefined} */ google.maps.DirectionsRenderer.prototype.setPanel = function(panel) {}; /** * @param {number} routeIndex * @return {undefined} */ google.maps.DirectionsRenderer.prototype.setRouteIndex = function(routeIndex) {}; /** * @constructor */ google.maps.DirectionsRendererOptions = function() {}; /** * @type {google.maps.DirectionsResult} */ google.maps.DirectionsRendererOptions.prototype.directions; /** * @type {boolean} */ google.maps.DirectionsRendererOptions.prototype.draggable; /** * @type {boolean} */ google.maps.DirectionsRendererOptions.prototype.hideRouteList; /** * @type {google.maps.InfoWindow} */ google.maps.DirectionsRendererOptions.prototype.infoWindow; /** * @type {google.maps.Map} */ google.maps.DirectionsRendererOptions.prototype.map; /** * @type {google.maps.MarkerOptions|Object.<string>} */ google.maps.DirectionsRendererOptions.prototype.markerOptions; /** * @type {Node} */ google.maps.DirectionsRendererOptions.prototype.panel; /** * @type {google.maps.PolylineOptions|Object.<string>} */ google.maps.DirectionsRendererOptions.prototype.polylineOptions; /** * @type {boolean} */ google.maps.DirectionsRendererOptions.prototype.preserveViewport; /** * @type {number} */ google.maps.DirectionsRendererOptions.prototype.routeIndex; /** * @type {boolean} */ google.maps.DirectionsRendererOptions.prototype.suppressBicyclingLayer; /** * @type {boolean} */ google.maps.DirectionsRendererOptions.prototype.suppressInfoWindows; /** * @type {boolean} */ google.maps.DirectionsRendererOptions.prototype.suppressMarkers; /** * @type {boolean} */ google.maps.DirectionsRendererOptions.prototype.suppressPolylines; /** * @constructor */ google.maps.DirectionsRequest = function() {}; /** * @type {boolean} */ google.maps.DirectionsRequest.prototype.avoidHighways; /** * @type {boolean} */ google.maps.DirectionsRequest.prototype.avoidTolls; /** * @type {google.maps.LatLng|string} */ google.maps.DirectionsRequest.prototype.destination; /** * @type {boolean} */ google.maps.DirectionsRequest.prototype.optimizeWaypoints; /** * @type {google.maps.LatLng|string} */ google.maps.DirectionsRequest.prototype.origin; /** * @type {boolean} */ google.maps.DirectionsRequest.prototype.provideRouteAlternatives; /** * @type {string} */ google.maps.DirectionsRequest.prototype.region; /** * @type {google.maps.TransitOptions|Object.<string>} */ google.maps.DirectionsRequest.prototype.transitOptions; /** * @type {google.maps.TravelMode} */ google.maps.DirectionsRequest.prototype.travelMode; /** * @type {google.maps.UnitSystem} */ google.maps.DirectionsRequest.prototype.unitSystem; /** * @type {Array.<google.maps.DirectionsWaypoint>} */ google.maps.DirectionsRequest.prototype.waypoints; /** * @constructor */ google.maps.DirectionsResult = function() {}; /** * @type {Array.<google.maps.DirectionsRoute>} */ google.maps.DirectionsResult.prototype.routes; /** * @constructor */ google.maps.DirectionsRoute = function() {}; /** * @type {google.maps.LatLngBounds} */ google.maps.DirectionsRoute.prototype.bounds; /** * @type {string} */ google.maps.DirectionsRoute.prototype.copyrights; /** * @type {Array.<google.maps.DirectionsLeg>} */ google.maps.DirectionsRoute.prototype.legs; /** * @type {Array.<google.maps.LatLng>} */ google.maps.DirectionsRoute.prototype.overview_path; /** * @type {Array.<string>} */ google.maps.DirectionsRoute.prototype.warnings; /** * @type {Array.<number>} */ google.maps.DirectionsRoute.prototype.waypoint_order; /** * @constructor */ google.maps.DirectionsService = function() {}; /** * @param {google.maps.DirectionsRequest|Object.<string>} request * @param {function(google.maps.DirectionsResult, google.maps.DirectionsStatus)} callback * @return {undefined} */ google.maps.DirectionsService.prototype.route = function(request, callback) {}; /** * @enum {number|string} */ google.maps.DirectionsStatus = { INVALID_REQUEST: '', MAX_WAYPOINTS_EXCEEDED: '', NOT_FOUND: '', OK: '', OVER_QUERY_LIMIT: '', REQUEST_DENIED: '', UNKNOWN_ERROR: '', ZERO_RESULTS: '' }; /** * @constructor */ google.maps.DirectionsStep = function() {}; /** * @type {google.maps.Distance} */ google.maps.DirectionsStep.prototype.distance; /** * @type {google.maps.Duration} */ google.maps.DirectionsStep.prototype.duration; /** * @type {google.maps.LatLng} */ google.maps.DirectionsStep.prototype.end_location; /** * @type {string} */ google.maps.DirectionsStep.prototype.instructions; /** * @type {Array.<google.maps.LatLng>} */ google.maps.DirectionsStep.prototype.path; /** * @type {google.maps.LatLng} */ google.maps.DirectionsStep.prototype.start_location; /** * @type {google.maps.DirectionsStep} */ google.maps.DirectionsStep.prototype.steps; /** * @type {google.maps.TransitDetails} */ google.maps.DirectionsStep.prototype.transit; /** * @type {google.maps.TravelMode} */ google.maps.DirectionsStep.prototype.travel_mode; /** * @constructor */ google.maps.DirectionsWaypoint = function() {}; /** * @type {google.maps.LatLng|string} */ google.maps.DirectionsWaypoint.prototype.location; /** * @type {boolean} */ google.maps.DirectionsWaypoint.prototype.stopover; /** * @constructor */ google.maps.Distance = function() {}; /** * @type {string} */ google.maps.Distance.prototype.text; /** * @type {number} */ google.maps.Distance.prototype.value; /** * @enum {number|string} */ google.maps.DistanceMatrixElementStatus = { NOT_FOUND: '', OK: '', ZERO_RESULTS: '' }; /** * @constructor */ google.maps.DistanceMatrixRequest = function() {}; /** * @type {boolean} */ google.maps.DistanceMatrixRequest.prototype.avoidHighways; /** * @type {boolean} */ google.maps.DistanceMatrixRequest.prototype.avoidTolls; /** * @type {Array.<google.maps.LatLng>|Array.<string>} */ google.maps.DistanceMatrixRequest.prototype.destinations; /** * @type {Array.<google.maps.LatLng>|Array.<string>} */ google.maps.DistanceMatrixRequest.prototype.origins; /** * @type {string} */ google.maps.DistanceMatrixRequest.prototype.region; /** * @type {google.maps.TravelMode} */ google.maps.DistanceMatrixRequest.prototype.travelMode; /** * @type {google.maps.UnitSystem} */ google.maps.DistanceMatrixRequest.prototype.unitSystem; /** * @constructor */ google.maps.DistanceMatrixResponse = function() {}; /** * @type {Array.<string>} */ google.maps.DistanceMatrixResponse.prototype.destinationAddresses; /** * @type {Array.<string>} */ google.maps.DistanceMatrixResponse.prototype.originAddresses; /** * @type {Array.<google.maps.DistanceMatrixResponseRow>} */ google.maps.DistanceMatrixResponse.prototype.rows; /** * @constructor */ google.maps.DistanceMatrixResponseElement = function() {}; /** * @type {google.maps.Distance} */ google.maps.DistanceMatrixResponseElement.prototype.distance; /** * @type {google.maps.Duration} */ google.maps.DistanceMatrixResponseElement.prototype.duration; /** * @type {google.maps.DistanceMatrixElementStatus} */ google.maps.DistanceMatrixResponseElement.prototype.status; /** * @constructor */ google.maps.DistanceMatrixResponseRow = function() {}; /** * @type {Array.<google.maps.DistanceMatrixResponseElement>} */ google.maps.DistanceMatrixResponseRow.prototype.elements; /** * @constructor */ google.maps.DistanceMatrixService = function() {}; /** * @param {google.maps.DistanceMatrixRequest|Object.<string>} request * @param {function(google.maps.DistanceMatrixResponse, google.maps.DistanceMatrixStatus)} callback * @return {undefined} */ google.maps.DistanceMatrixService.prototype.getDistanceMatrix = function(request, callback) {}; /** * @enum {number|string} */ google.maps.DistanceMatrixStatus = { INVALID_REQUEST: '', MAX_DIMENSIONS_EXCEEDED: '', MAX_ELEMENTS_EXCEEDED: '', OK: '', OVER_QUERY_LIMIT: '', REQUEST_DENIED: '', UNKNOWN_ERROR: '' }; /** * @constructor */ google.maps.Duration = function() {}; /** * @type {string} */ google.maps.Duration.prototype.text; /** * @type {number} */ google.maps.Duration.prototype.value; /** * @constructor */ google.maps.ElevationResult = function() {}; /** * @type {number} */ google.maps.ElevationResult.prototype.elevation; /** * @type {google.maps.LatLng} */ google.maps.ElevationResult.prototype.location; /** * @type {number} */ google.maps.ElevationResult.prototype.resolution; /** * @constructor */ google.maps.ElevationService = function() {}; /** * @param {google.maps.PathElevationRequest|Object.<string>} request * @param {function(Array.<google.maps.ElevationResult>, google.maps.ElevationStatus)} callback * @return {undefined} */ google.maps.ElevationService.prototype.getElevationAlongPath = function(request, callback) {}; /** * @param {google.maps.LocationElevationRequest|Object.<string>} request * @param {function(Array.<google.maps.ElevationResult>, google.maps.ElevationStatus)} callback * @return {undefined} */ google.maps.ElevationService.prototype.getElevationForLocations = function(request, callback) {}; /** * @enum {number|string} */ google.maps.ElevationStatus = { INVALID_REQUEST: '', OK: '', OVER_QUERY_LIMIT: '', REQUEST_DENIED: '', UNKNOWN_ERROR: '' }; /** * @constructor */ google.maps.FusionTablesCell = function() {}; /** * @type {string} */ google.maps.FusionTablesCell.prototype.columnName; /** * @type {string} */ google.maps.FusionTablesCell.prototype.value; /** * @constructor */ google.maps.FusionTablesHeatmap = function() {}; /** * @type {boolean} */ google.maps.FusionTablesHeatmap.prototype.enabled; /** * @param {google.maps.FusionTablesLayerOptions|Object.<string>} options * @extends {google.maps.MVCObject} * @constructor */ google.maps.FusionTablesLayer = function(options) {}; /** * @nosideeffects * @return {google.maps.Map} */ google.maps.FusionTablesLayer.prototype.getMap = function() {}; /** * @param {google.maps.Map} map * @return {undefined} */ google.maps.FusionTablesLayer.prototype.setMap = function(map) {}; /** * @param {google.maps.FusionTablesLayerOptions|Object.<string>} options * @return {undefined} */ google.maps.FusionTablesLayer.prototype.setOptions = function(options) {}; /** * @constructor */ google.maps.FusionTablesLayerOptions = function() {}; /** * @type {boolean} */ google.maps.FusionTablesLayerOptions.prototype.clickable; /** * @type {google.maps.FusionTablesHeatmap} */ google.maps.FusionTablesLayerOptions.prototype.heatmap; /** * @type {google.maps.Map} */ google.maps.FusionTablesLayerOptions.prototype.map; /** * @type {google.maps.FusionTablesQuery} */ google.maps.FusionTablesLayerOptions.prototype.query; /** * @type {Array.<google.maps.FusionTablesStyle>} */ google.maps.FusionTablesLayerOptions.prototype.styles; /** * @type {boolean} */ google.maps.FusionTablesLayerOptions.prototype.suppressInfoWindows; /** * @constructor */ google.maps.FusionTablesMarkerOptions = function() {}; /** * @type {string} */ google.maps.FusionTablesMarkerOptions.prototype.iconName; /** * @constructor */ google.maps.FusionTablesMouseEvent = function() {}; /** * @type {string} */ google.maps.FusionTablesMouseEvent.prototype.infoWindowHtml; /** * @type {google.maps.LatLng} */ google.maps.FusionTablesMouseEvent.prototype.latLng; /** * @type {google.maps.Size} */ google.maps.FusionTablesMouseEvent.prototype.pixelOffset; /** * @type {Object} */ google.maps.FusionTablesMouseEvent.prototype.row; /** * @constructor */ google.maps.FusionTablesPolygonOptions = function() {}; /** * @type {string} */ google.maps.FusionTablesPolygonOptions.prototype.fillColor; /** * @type {number} */ google.maps.FusionTablesPolygonOptions.prototype.fillOpacity; /** * @type {string} */ google.maps.FusionTablesPolygonOptions.prototype.strokeColor; /** * @type {number} */ google.maps.FusionTablesPolygonOptions.prototype.strokeOpacity; /** * @type {number} */ google.maps.FusionTablesPolygonOptions.prototype.strokeWeight; /** * @constructor */ google.maps.FusionTablesPolylineOptions = function() {}; /** * @type {string} */ google.maps.FusionTablesPolylineOptions.prototype.strokeColor; /** * @type {number} */ google.maps.FusionTablesPolylineOptions.prototype.strokeOpacity; /** * @type {number} */ google.maps.FusionTablesPolylineOptions.prototype.strokeWeight; /** * @constructor */ google.maps.FusionTablesQuery = function() {}; /** * @type {string} */ google.maps.FusionTablesQuery.prototype.from; /** * @type {number} */ google.maps.FusionTablesQuery.prototype.limit; /** * @type {number} */ google.maps.FusionTablesQuery.prototype.offset; /** * @type {string} */ google.maps.FusionTablesQuery.prototype.orderBy; /** * @type {string} */ google.maps.FusionTablesQuery.prototype.select; /** * @type {string} */ google.maps.FusionTablesQuery.prototype.where; /** * @constructor */ google.maps.FusionTablesStyle = function() {}; /** * @type {google.maps.FusionTablesMarkerOptions|Object.<string>} */ google.maps.FusionTablesStyle.prototype.markerOptions; /** * @type {google.maps.FusionTablesPolygonOptions|Object.<string>} */ google.maps.FusionTablesStyle.prototype.polygonOptions; /** * @type {google.maps.FusionTablesPolylineOptions|Object.<string>} */ google.maps.FusionTablesStyle.prototype.polylineOptions; /** * @type {string} */ google.maps.FusionTablesStyle.prototype.where; /** * @constructor */ google.maps.Geocoder = function() {}; /** * @param {google.maps.GeocoderRequest|Object.<string>} request * @param {function(Array.<google.maps.GeocoderResult>, google.maps.GeocoderStatus)} callback * @return {undefined} */ google.maps.Geocoder.prototype.geocode = function(request, callback) {}; /** * @constructor */ google.maps.GeocoderAddressComponent = function() {}; /** * @type {string} */ google.maps.GeocoderAddressComponent.prototype.long_name; /** * @type {string} */ google.maps.GeocoderAddressComponent.prototype.short_name; /** * @type {Array.<string>} */ google.maps.GeocoderAddressComponent.prototype.types; /** * @constructor */ google.maps.GeocoderGeometry = function() {}; /** * @type {google.maps.LatLngBounds} */ google.maps.GeocoderGeometry.prototype.bounds; /** * @type {google.maps.LatLng} */ google.maps.GeocoderGeometry.prototype.location; /** * @type {google.maps.GeocoderLocationType} */ google.maps.GeocoderGeometry.prototype.location_type; /** * @type {google.maps.LatLngBounds} */ google.maps.GeocoderGeometry.prototype.viewport; /** * @enum {number|string} */ google.maps.GeocoderLocationType = { APPROXIMATE: '', GEOMETRIC_CENTER: '', RANGE_INTERPOLATED: '', ROOFTOP: '' }; /** * @constructor */ google.maps.GeocoderRequest = function() {}; /** * @type {string} */ google.maps.GeocoderRequest.prototype.address; /** * @type {google.maps.LatLngBounds} */ google.maps.GeocoderRequest.prototype.bounds; /** * @type {google.maps.LatLng} */ google.maps.GeocoderRequest.prototype.location; /** * @type {string} */ google.maps.GeocoderRequest.prototype.region; /** * @constructor */ google.maps.GeocoderResult = function() {}; /** * @type {Array.<google.maps.GeocoderAddressComponent>} */ google.maps.GeocoderResult.prototype.address_components; /** * @type {string} */ google.maps.GeocoderResult.prototype.formatted_address; /** * @type {google.maps.GeocoderGeometry} */ google.maps.GeocoderResult.prototype.geometry; /** * @type {Array.<string>} */ google.maps.GeocoderResult.prototype.types; /** * @enum {number|string} */ google.maps.GeocoderStatus = { ERROR: '', INVALID_REQUEST: '', OK: '', OVER_QUERY_LIMIT: '', REQUEST_DENIED: '', UNKNOWN_ERROR: '', ZERO_RESULTS: '' }; /** * @param {string} url * @param {google.maps.LatLngBounds} bounds * @param {(google.maps.GroundOverlayOptions|Object.<string>)=} opt_opts * @extends {google.maps.MVCObject} * @constructor */ google.maps.GroundOverlay = function(url, bounds, opt_opts) {}; /** * @nosideeffects * @return {google.maps.LatLngBounds} */ google.maps.GroundOverlay.prototype.getBounds = function() {}; /** * @nosideeffects * @return {google.maps.Map} */ google.maps.GroundOverlay.prototype.getMap = function() {}; /** * @nosideeffects * @return {number} */ google.maps.GroundOverlay.prototype.getOpacity = function() {}; /** * @nosideeffects * @return {string} */ google.maps.GroundOverlay.prototype.getUrl = function() {}; /** * @param {google.maps.Map} map * @return {undefined} */ google.maps.GroundOverlay.prototype.setMap = function(map) {}; /** * @param {number} opacity * @return {undefined} */ google.maps.GroundOverlay.prototype.setOpacity = function(opacity) {}; /** * @constructor */ google.maps.GroundOverlayOptions = function() {}; /** * @type {boolean} */ google.maps.GroundOverlayOptions.prototype.clickable; /** * @type {google.maps.Map} */ google.maps.GroundOverlayOptions.prototype.map; /** * @type {number} */ google.maps.GroundOverlayOptions.prototype.opacity; /** * @constructor */ google.maps.IconSequence = function() {}; /** * @type {google.maps.Symbol} */ google.maps.IconSequence.prototype.icon; /** * @type {string} */ google.maps.IconSequence.prototype.offset; /** * @type {string} */ google.maps.IconSequence.prototype.repeat; /** * @param {google.maps.ImageMapTypeOptions|Object.<string>} opts * @extends {google.maps.MVCObject} * @constructor */ google.maps.ImageMapType = function(opts) {}; /** * @nosideeffects * @return {number} */ google.maps.ImageMapType.prototype.getOpacity = function() {}; /** * @param {number} opacity * @return {undefined} */ google.maps.ImageMapType.prototype.setOpacity = function(opacity) {}; /** * @constructor */ google.maps.ImageMapTypeOptions = function() {}; /** * @type {string} */ google.maps.ImageMapTypeOptions.prototype.alt; /** * @type {function(google.maps.Point, number):string} */ google.maps.ImageMapTypeOptions.prototype.getTileUrl; /** * @type {number} */ google.maps.ImageMapTypeOptions.prototype.maxZoom; /** * @type {number} */ google.maps.ImageMapTypeOptions.prototype.minZoom; /** * @type {string} */ google.maps.ImageMapTypeOptions.prototype.name; /** * @type {number} */ google.maps.ImageMapTypeOptions.prototype.opacity; /** * @type {google.maps.Size} */ google.maps.ImageMapTypeOptions.prototype.tileSize; /** * @param {(google.maps.InfoWindowOptions|Object.<string>)=} opt_opts * @extends {google.maps.MVCObject} * @constructor */ google.maps.InfoWindow = function(opt_opts) {}; /** * @return {undefined} */ google.maps.InfoWindow.prototype.close = function() {}; /** * @nosideeffects * @return {string|Node} */ google.maps.InfoWindow.prototype.getContent = function() {}; /** * @nosideeffects * @return {google.maps.LatLng} */ google.maps.InfoWindow.prototype.getPosition = function() {}; /** * @nosideeffects * @return {number} */ google.maps.InfoWindow.prototype.getZIndex = function() {}; /** * @param {(google.maps.Map|google.maps.StreetViewPanorama)=} opt_map * @param {google.maps.MVCObject=} opt_anchor * @return {undefined} */ google.maps.InfoWindow.prototype.open = function(opt_map, opt_anchor) {}; /** * @param {string|Node} content * @return {undefined} */ google.maps.InfoWindow.prototype.setContent = function(content) {}; /** * @param {google.maps.InfoWindowOptions|Object.<string>} options * @return {undefined} */ google.maps.InfoWindow.prototype.setOptions = function(options) {}; /** * @param {google.maps.LatLng} position * @return {undefined} */ google.maps.InfoWindow.prototype.setPosition = function(position) {}; /** * @param {number} zIndex * @return {undefined} */ google.maps.InfoWindow.prototype.setZIndex = function(zIndex) {}; /** * @constructor */ google.maps.InfoWindowOptions = function() {}; /** * @type {string|Node} */ google.maps.InfoWindowOptions.prototype.content; /** * @type {boolean} */ google.maps.InfoWindowOptions.prototype.disableAutoPan; /** * @type {number} */ google.maps.InfoWindowOptions.prototype.maxWidth; /** * @type {google.maps.Size} */ google.maps.InfoWindowOptions.prototype.pixelOffset; /** * @type {google.maps.LatLng} */ google.maps.InfoWindowOptions.prototype.position; /** * @type {number} */ google.maps.InfoWindowOptions.prototype.zIndex; /** * @constructor */ google.maps.KmlAuthor = function() {}; /** * @type {string} */ google.maps.KmlAuthor.prototype.email; /** * @type {string} */ google.maps.KmlAuthor.prototype.name; /** * @type {string} */ google.maps.KmlAuthor.prototype.uri; /** * @constructor */ google.maps.KmlFeatureData = function() {}; /** * @type {google.maps.KmlAuthor} */ google.maps.KmlFeatureData.prototype.author; /** * @type {string} */ google.maps.KmlFeatureData.prototype.description; /** * @type {string} */ google.maps.KmlFeatureData.prototype.id; /** * @type {string} */ google.maps.KmlFeatureData.prototype.infoWindowHtml; /** * @type {string} */ google.maps.KmlFeatureData.prototype.name; /** * @type {string} */ google.maps.KmlFeatureData.prototype.snippet; /** * @param {string} url * @param {(google.maps.KmlLayerOptions|Object.<string>)=} opt_opts * @extends {google.maps.MVCObject} * @constructor */ google.maps.KmlLayer = function(url, opt_opts) {}; /** * @nosideeffects * @return {google.maps.LatLngBounds} */ google.maps.KmlLayer.prototype.getDefaultViewport = function() {}; /** * @nosideeffects * @return {google.maps.Map} */ google.maps.KmlLayer.prototype.getMap = function() {}; /** * @nosideeffects * @return {google.maps.KmlLayerMetadata} */ google.maps.KmlLayer.prototype.getMetadata = function() {}; /** * @nosideeffects * @return {google.maps.KmlLayerStatus} */ google.maps.KmlLayer.prototype.getStatus = function() {}; /** * @nosideeffects * @return {string} */ google.maps.KmlLayer.prototype.getUrl = function() {}; /** * @param {google.maps.Map} map * @return {undefined} */ google.maps.KmlLayer.prototype.setMap = function(map) {}; /** * @constructor */ google.maps.KmlLayerMetadata = function() {}; /** * @type {google.maps.KmlAuthor} */ google.maps.KmlLayerMetadata.prototype.author; /** * @type {string} */ google.maps.KmlLayerMetadata.prototype.description; /** * @type {string} */ google.maps.KmlLayerMetadata.prototype.name; /** * @type {string} */ google.maps.KmlLayerMetadata.prototype.snippet; /** * @constructor */ google.maps.KmlLayerOptions = function() {}; /** * @type {boolean} */ google.maps.KmlLayerOptions.prototype.clickable; /** * @type {google.maps.Map} */ google.maps.KmlLayerOptions.prototype.map; /** * @type {boolean} */ google.maps.KmlLayerOptions.prototype.preserveViewport; /** * @type {boolean} */ google.maps.KmlLayerOptions.prototype.suppressInfoWindows; /** * @enum {number|string} */ google.maps.KmlLayerStatus = { DOCUMENT_NOT_FOUND: '', DOCUMENT_TOO_LARGE: '', FETCH_ERROR: '', INVALID_DOCUMENT: '', INVALID_REQUEST: '', LIMITS_EXCEEDED: '', OK: '', TIMED_OUT: '', UNKNOWN: '' }; /** * @constructor */ google.maps.KmlMouseEvent = function() {}; /** * @type {google.maps.KmlFeatureData} */ google.maps.KmlMouseEvent.prototype.featureData; /** * @type {google.maps.LatLng} */ google.maps.KmlMouseEvent.prototype.latLng; /** * @type {google.maps.Size} */ google.maps.KmlMouseEvent.prototype.pixelOffset; /** * @param {number} lat * @param {number} lng * @param {boolean=} opt_noWrap * @constructor */ google.maps.LatLng = function(lat, lng, opt_noWrap) {}; /** * @param {google.maps.LatLng} other * @return {boolean} */ google.maps.LatLng.prototype.equals = function(other) {}; /** * @return {number} */ google.maps.LatLng.prototype.lat = function() {}; /** * @return {number} */ google.maps.LatLng.prototype.lng = function() {}; /** * @return {string} */ google.maps.LatLng.prototype.toString = function() {}; /** * @param {number=} opt_precision * @return {string} */ google.maps.LatLng.prototype.toUrlValue = function(opt_precision) {}; /** * @param {google.maps.LatLng=} opt_sw * @param {google.maps.LatLng=} opt_ne * @constructor */ google.maps.LatLngBounds = function(opt_sw, opt_ne) {}; /** * @param {google.maps.LatLng} latLng * @return {boolean} */ google.maps.LatLngBounds.prototype.contains = function(latLng) {}; /** * @param {google.maps.LatLngBounds} other * @return {boolean} */ google.maps.LatLngBounds.prototype.equals = function(other) {}; /** * @param {google.maps.LatLng} point * @return {google.maps.LatLngBounds} */ google.maps.LatLngBounds.prototype.extend = function(point) {}; /** * @nosideeffects * @return {google.maps.LatLng} */ google.maps.LatLngBounds.prototype.getCenter = function() {}; /** * @nosideeffects * @return {google.maps.LatLng} */ google.maps.LatLngBounds.prototype.getNorthEast = function() {}; /** * @nosideeffects * @return {google.maps.LatLng} */ google.maps.LatLngBounds.prototype.getSouthWest = function() {}; /** * @param {google.maps.LatLngBounds} other * @return {boolean} */ google.maps.LatLngBounds.prototype.intersects = function(other) {}; /** * @return {boolean} */ google.maps.LatLngBounds.prototype.isEmpty = function() {}; /** * @return {google.maps.LatLng} */ google.maps.LatLngBounds.prototype.toSpan = function() {}; /** * @return {string} */ google.maps.LatLngBounds.prototype.toString = function() {}; /** * @param {number=} opt_precision * @return {string} */ google.maps.LatLngBounds.prototype.toUrlValue = function(opt_precision) {}; /** * @param {google.maps.LatLngBounds} other * @return {google.maps.LatLngBounds} */ google.maps.LatLngBounds.prototype.union = function(other) {}; /** * @constructor */ google.maps.LocationElevationRequest = function() {}; /** * @type {Array.<google.maps.LatLng>} */ google.maps.LocationElevationRequest.prototype.locations; /** * @param {Array=} opt_array * @extends {google.maps.MVCObject} * @constructor */ google.maps.MVCArray = function(opt_array) {}; /** * @return {undefined} */ google.maps.MVCArray.prototype.clear = function() {}; /** * @param {function(?, number)} callback * @return {undefined} */ google.maps.MVCArray.prototype.forEach = function(callback) {}; /** * @nosideeffects * @return {Array} */ google.maps.MVCArray.prototype.getArray = function() {}; /** * @param {number} i * @return {*} */ google.maps.MVCArray.prototype.getAt = function(i) {}; /** * @nosideeffects * @return {number} */ google.maps.MVCArray.prototype.getLength = function() {}; /** * @param {number} i * @param {*} elem * @return {undefined} */ google.maps.MVCArray.prototype.insertAt = function(i, elem) {}; /** * @return {*} */ google.maps.MVCArray.prototype.pop = function() {}; /** * @param {*} elem * @return {number} */ google.maps.MVCArray.prototype.push = function(elem) {}; /** * @param {number} i * @return {*} */ google.maps.MVCArray.prototype.removeAt = function(i) {}; /** * @param {number} i * @param {*} elem * @return {undefined} */ google.maps.MVCArray.prototype.setAt = function(i, elem) {}; /** * @constructor */ google.maps.MVCObject = function() {}; /** * @param {string} key * @param {google.maps.MVCObject} target * @param {?string=} opt_targetKey * @param {boolean=} opt_noNotify * @return {undefined} */ google.maps.MVCObject.prototype.bindTo = function(key, target, opt_targetKey, opt_noNotify) {}; /** * @param {string} key * @return {undefined} */ google.maps.MVCObject.prototype.changed = function(key) {}; /** * @param {string} key * @return {*} */ google.maps.MVCObject.prototype.get = function(key) {}; /** * @param {string} key * @return {undefined} */ google.maps.MVCObject.prototype.notify = function(key) {}; /** * @param {string} key * @param {?} value * @return {undefined} */ google.maps.MVCObject.prototype.set = function(key, value) {}; /** * @param {Object|undefined} values * @return {undefined} */ google.maps.MVCObject.prototype.setValues = function(values) {}; /** * @param {string} key * @return {undefined} */ google.maps.MVCObject.prototype.unbind = function(key) {}; /** * @return {undefined} */ google.maps.MVCObject.prototype.unbindAll = function() {}; /** * @param {Node} mapDiv * @param {(google.maps.MapOptions|Object.<string>)=} opt_opts * @extends {google.maps.MVCObject} * @constructor */ google.maps.Map = function(mapDiv, opt_opts) {}; /** * @type {Array.<google.maps.MVCArray.<Node>>} */ google.maps.Map.prototype.controls; /** * @type {google.maps.MapTypeRegistry} */ google.maps.Map.prototype.mapTypes; /** * @type {google.maps.MVCArray.<google.maps.MapType>} */ google.maps.Map.prototype.overlayMapTypes; /** * @param {google.maps.LatLngBounds} bounds * @return {undefined} */ google.maps.Map.prototype.fitBounds = function(bounds) {}; /** * @nosideeffects * @return {google.maps.LatLngBounds} */ google.maps.Map.prototype.getBounds = function() {}; /** * @nosideeffects * @return {google.maps.LatLng} */ google.maps.Map.prototype.getCenter = function() {}; /** * @nosideeffects * @return {Node} */ google.maps.Map.prototype.getDiv = function() {}; /** * @nosideeffects * @return {number} */ google.maps.Map.prototype.getHeading = function() {}; /** * @nosideeffects * @return {google.maps.MapTypeId|string} */ google.maps.Map.prototype.getMapTypeId = function() {}; /** * @nosideeffects * @return {google.maps.Projection} */ google.maps.Map.prototype.getProjection = function() {}; /** * @nosideeffects * @return {google.maps.StreetViewPanorama} */ google.maps.Map.prototype.getStreetView = function() {}; /** * @nosideeffects * @return {number} */ google.maps.Map.prototype.getTilt = function() {}; /** * @nosideeffects * @return {number} */ google.maps.Map.prototype.getZoom = function() {}; /** * @param {number} x * @param {number} y * @return {undefined} */ google.maps.Map.prototype.panBy = function(x, y) {}; /** * @param {google.maps.LatLng} latLng * @return {undefined} */ google.maps.Map.prototype.panTo = function(latLng) {}; /** * @param {google.maps.LatLngBounds} latLngBounds * @return {undefined} */ google.maps.Map.prototype.panToBounds = function(latLngBounds) {}; /** * @param {google.maps.LatLng} latlng * @return {undefined} */ google.maps.Map.prototype.setCenter = function(latlng) {}; /** * @param {number} heading * @return {undefined} */ google.maps.Map.prototype.setHeading = function(heading) {}; /** * @param {google.maps.MapTypeId|string} mapTypeId * @return {undefined} */ google.maps.Map.prototype.setMapTypeId = function(mapTypeId) {}; /** * @param {google.maps.MapOptions|Object.<string>} options * @return {undefined} */ google.maps.Map.prototype.setOptions = function(options) {}; /** * @param {google.maps.StreetViewPanorama} panorama * @return {undefined} */ google.maps.Map.prototype.setStreetView = function(panorama) {}; /** * @param {number} tilt * @return {undefined} */ google.maps.Map.prototype.setTilt = function(tilt) {}; /** * @param {number} zoom * @return {undefined} */ google.maps.Map.prototype.setZoom = function(zoom) {}; /** * @extends {google.maps.MVCObject} * @constructor */ google.maps.MapCanvasProjection = function() {}; /** * @param {google.maps.Point} pixel * @param {boolean=} opt_nowrap * @return {google.maps.LatLng} */ google.maps.MapCanvasProjection.prototype.fromContainerPixelToLatLng = function(pixel, opt_nowrap) {}; /** * @param {google.maps.Point} pixel * @param {boolean=} opt_nowrap * @return {google.maps.LatLng} */ google.maps.MapCanvasProjection.prototype.fromDivPixelToLatLng = function(pixel, opt_nowrap) {}; /** * @param {google.maps.LatLng} latLng * @return {google.maps.Point} */ google.maps.MapCanvasProjection.prototype.fromLatLngToContainerPixel = function(latLng) {}; /** * @param {google.maps.LatLng} latLng * @return {google.maps.Point} */ google.maps.MapCanvasProjection.prototype.fromLatLngToDivPixel = function(latLng) {}; /** * @nosideeffects * @return {number} */ google.maps.MapCanvasProjection.prototype.getWorldWidth = function() {}; /** * @constructor */ google.maps.MapOptions = function() {}; /** * @type {string} */ google.maps.MapOptions.prototype.backgroundColor; /** * @type {google.maps.LatLng} */ google.maps.MapOptions.prototype.center; /** * @type {boolean} */ google.maps.MapOptions.prototype.disableDefaultUI; /** * @type {boolean} */ google.maps.MapOptions.prototype.disableDoubleClickZoom; /** * @type {boolean} */ google.maps.MapOptions.prototype.draggable; /** * @type {string} */ google.maps.MapOptions.prototype.draggableCursor; /** * @type {string} */ google.maps.MapOptions.prototype.draggingCursor; /** * @type {number} */ google.maps.MapOptions.prototype.heading; /** * @type {boolean} */ google.maps.MapOptions.prototype.keyboardShortcuts; /** * @type {boolean} */ google.maps.MapOptions.prototype.mapMaker; /** * @type {boolean} */ google.maps.MapOptions.prototype.mapTypeControl; /** * @type {google.maps.MapTypeControlOptions|Object.<string>} */ google.maps.MapOptions.prototype.mapTypeControlOptions; /** * @type {google.maps.MapTypeId} */ google.maps.MapOptions.prototype.mapTypeId; /** * @type {number} */ google.maps.MapOptions.prototype.maxZoom; /** * @type {number} */ google.maps.MapOptions.prototype.minZoom; /** * @type {boolean} */ google.maps.MapOptions.prototype.noClear; /** * @type {boolean} */ google.maps.MapOptions.prototype.overviewMapControl; /** * @type {google.maps.OverviewMapControlOptions|Object.<string>} */ google.maps.MapOptions.prototype.overviewMapControlOptions; /** * @type {boolean} */ google.maps.MapOptions.prototype.panControl; /** * @type {google.maps.PanControlOptions|Object.<string>} */ google.maps.MapOptions.prototype.panControlOptions; /** * @type {boolean} */ google.maps.MapOptions.prototype.rotateControl; /** * @type {google.maps.RotateControlOptions|Object.<string>} */ google.maps.MapOptions.prototype.rotateControlOptions; /** * @type {boolean} */ google.maps.MapOptions.prototype.scaleControl; /** * @type {google.maps.ScaleControlOptions|Object.<string>} */ google.maps.MapOptions.prototype.scaleControlOptions; /** * @type {boolean} */ google.maps.MapOptions.prototype.scrollwheel; /** * @type {google.maps.StreetViewPanorama} */ google.maps.MapOptions.prototype.streetView; /** * @type {boolean} */ google.maps.MapOptions.prototype.streetViewControl; /** * @type {google.maps.StreetViewControlOptions|Object.<string>} */ google.maps.MapOptions.prototype.streetViewControlOptions; /** * @type {Array.<google.maps.MapTypeStyle>} */ google.maps.MapOptions.prototype.styles; /** * @type {number} */ google.maps.MapOptions.prototype.tilt; /** * @type {number} */ google.maps.MapOptions.prototype.zoom; /** * @type {boolean} */ google.maps.MapOptions.prototype.zoomControl; /** * @type {google.maps.ZoomControlOptions|Object.<string>} */ google.maps.MapOptions.prototype.zoomControlOptions; /** * @constructor */ google.maps.MapPanes = function() {}; /** * @type {Node} */ google.maps.MapPanes.prototype.floatPane; /** * @type {Node} */ google.maps.MapPanes.prototype.floatShadow; /** * @type {Node} */ google.maps.MapPanes.prototype.mapPane; /** * @type {Node} */ google.maps.MapPanes.prototype.overlayImage; /** * @type {Node} */ google.maps.MapPanes.prototype.overlayLayer; /** * @type {Node} */ google.maps.MapPanes.prototype.overlayMouseTarget; /** * @type {Node} */ google.maps.MapPanes.prototype.overlayShadow; /** * @constructor */ google.maps.MapType = function() {}; /** * @type {string} */ google.maps.MapType.prototype.alt; /** * @type {number} */ google.maps.MapType.prototype.maxZoom; /** * @type {number} */ google.maps.MapType.prototype.minZoom; /** * @type {string} */ google.maps.MapType.prototype.name; /** * @type {google.maps.Projection} */ google.maps.MapType.prototype.projection; /** * @type {number} */ google.maps.MapType.prototype.radius; /** * @type {google.maps.Size} */ google.maps.MapType.prototype.tileSize; /** * @param {google.maps.Point} tileCoord * @param {number} zoom * @param {Document} ownerDocument * @return {Node} */ google.maps.MapType.prototype.getTile = function(tileCoord, zoom, ownerDocument) {}; /** * @param {Node} tile * @return {undefined} */ google.maps.MapType.prototype.releaseTile = function(tile) {}; /** * @constructor */ google.maps.MapTypeControlOptions = function() {}; /** * @type {Array.<google.maps.MapTypeId>|Array.<string>} */ google.maps.MapTypeControlOptions.prototype.mapTypeIds; /** * @type {google.maps.ControlPosition} */ google.maps.MapTypeControlOptions.prototype.position; /** * @type {google.maps.MapTypeControlStyle} */ google.maps.MapTypeControlOptions.prototype.style; /** * @enum {number|string} */ google.maps.MapTypeControlStyle = { DEFAULT: '', DROPDOWN_MENU: '', HORIZONTAL_BAR: '' }; /** * @enum {number|string} */ google.maps.MapTypeId = { HYBRID: '', ROADMAP: '', SATELLITE: '', TERRAIN: '' }; /** * @extends {google.maps.MVCObject} * @constructor */ google.maps.MapTypeRegistry = function() {}; /** * @param {string} id * @param {google.maps.MapType} mapType * @return {undefined} * @override */ google.maps.MapTypeRegistry.prototype.set = function(id, mapType) {}; /** * @constructor */ google.maps.MapTypeStyle = function() {}; /** * @type {string} */ google.maps.MapTypeStyle.prototype.elementType; /** * @type {string} */ google.maps.MapTypeStyle.prototype.featureType; /** * @type {Array.<google.maps.MapTypeStyler>} */ google.maps.MapTypeStyle.prototype.stylers; /** * @constructor */ google.maps.MapTypeStyler = function() {}; /** * @type {number} */ google.maps.MapTypeStyler.prototype.gamma; /** * @type {string} */ google.maps.MapTypeStyler.prototype.hue; /** * @type {boolean} */ google.maps.MapTypeStyler.prototype.invert_lightness; /** * @type {number} */ google.maps.MapTypeStyler.prototype.lightness; /** * @type {number} */ google.maps.MapTypeStyler.prototype.saturation; /** * @type {string} */ google.maps.MapTypeStyler.prototype.visibility; /** * @constructor */ google.maps.MapsEventListener = function() {}; /** * @param {(google.maps.MarkerOptions|Object.<string>)=} opt_opts * @extends {google.maps.MVCObject} * @constructor */ google.maps.Marker = function(opt_opts) {}; /** * @nosideeffects * @return {?google.maps.Animation} */ google.maps.Marker.prototype.getAnimation = function() {}; /** * @nosideeffects * @return {boolean} */ google.maps.Marker.prototype.getClickable = function() {}; /** * @nosideeffects * @return {string} */ google.maps.Marker.prototype.getCursor = function() {}; /** * @nosideeffects * @return {boolean} */ google.maps.Marker.prototype.getDraggable = function() {}; /** * @nosideeffects * @return {boolean} */ google.maps.Marker.prototype.getFlat = function() {}; /** * @nosideeffects * @return {string|google.maps.MarkerImage} */ google.maps.Marker.prototype.getIcon = function() {}; /** * @nosideeffects * @return {google.maps.Map|google.maps.StreetViewPanorama} */ google.maps.Marker.prototype.getMap = function() {}; /** * @nosideeffects * @return {google.maps.LatLng} */ google.maps.Marker.prototype.getPosition = function() {}; /** * @nosideeffects * @return {string|google.maps.MarkerImage} */ google.maps.Marker.prototype.getShadow = function() {}; /** * @nosideeffects * @return {google.maps.MarkerShape} */ google.maps.Marker.prototype.getShape = function() {}; /** * @nosideeffects * @return {string} */ google.maps.Marker.prototype.getTitle = function() {}; /** * @nosideeffects * @return {boolean} */ google.maps.Marker.prototype.getVisible = function() {}; /** * @nosideeffects * @return {number} */ google.maps.Marker.prototype.getZIndex = function() {}; /** * @param {?google.maps.Animation} animation * @return {undefined} */ google.maps.Marker.prototype.setAnimation = function(animation) {}; /** * @param {boolean} flag * @return {undefined} */ google.maps.Marker.prototype.setClickable = function(flag) {}; /** * @param {string} cursor * @return {undefined} */ google.maps.Marker.prototype.setCursor = function(cursor) {}; /** * @param {?boolean} flag * @return {undefined} */ google.maps.Marker.prototype.setDraggable = function(flag) {}; /** * @param {boolean} flag * @return {undefined} */ google.maps.Marker.prototype.setFlat = function(flag) {}; /** * @param {string|google.maps.MarkerImage} icon * @return {undefined} */ google.maps.Marker.prototype.setIcon = function(icon) {}; /** * @param {google.maps.Map|google.maps.StreetViewPanorama} map * @return {undefined} */ google.maps.Marker.prototype.setMap = function(map) {}; /** * @param {google.maps.MarkerOptions|Object.<string>} options * @return {undefined} */ google.maps.Marker.prototype.setOptions = function(options) {}; /** * @param {google.maps.LatLng} latlng * @return {undefined} */ google.maps.Marker.prototype.setPosition = function(latlng) {}; /** * @param {string|google.maps.MarkerImage} shadow * @return {undefined} */ google.maps.Marker.prototype.setShadow = function(shadow) {}; /** * @param {google.maps.MarkerShape} shape * @return {undefined} */ google.maps.Marker.prototype.setShape = function(shape) {}; /** * @param {string} title * @return {undefined} */ google.maps.Marker.prototype.setTitle = function(title) {}; /** * @param {boolean} visible * @return {undefined} */ google.maps.Marker.prototype.setVisible = function(visible) {}; /** * @param {number} zIndex * @return {undefined} */ google.maps.Marker.prototype.setZIndex = function(zIndex) {}; /** * @constant * @type {number|string} */ google.maps.Marker.MAX_ZINDEX; /** * @param {string} url * @param {google.maps.Size=} opt_size * @param {google.maps.Point=} opt_origin * @param {google.maps.Point=} opt_anchor * @param {google.maps.Size=} opt_scaledSize * @constructor */ google.maps.MarkerImage = function(url, opt_size, opt_origin, opt_anchor, opt_scaledSize) {}; /** * @type {google.maps.Point} */ google.maps.MarkerImage.prototype.anchor; /** * @type {google.maps.Point} */ google.maps.MarkerImage.prototype.origin; /** * @type {google.maps.Size} */ google.maps.MarkerImage.prototype.scaledSize; /** * @type {google.maps.Size} */ google.maps.MarkerImage.prototype.size; /** * @type {string} */ google.maps.MarkerImage.prototype.url; /** * @constructor */ google.maps.MarkerOptions = function() {}; /** * @type {google.maps.Animation} */ google.maps.MarkerOptions.prototype.animation; /** * @type {boolean} */ google.maps.MarkerOptions.prototype.clickable; /** * @type {string} */ google.maps.MarkerOptions.prototype.cursor; /** * @type {boolean} */ google.maps.MarkerOptions.prototype.draggable; /** * @type {boolean} */ google.maps.MarkerOptions.prototype.flat; /** * @type {string|google.maps.MarkerImage|google.maps.Symbol} */ google.maps.MarkerOptions.prototype.icon; /** * @type {google.maps.Map|google.maps.StreetViewPanorama} */ google.maps.MarkerOptions.prototype.map; /** * @type {boolean} */ google.maps.MarkerOptions.prototype.optimized; /** * @type {google.maps.LatLng} */ google.maps.MarkerOptions.prototype.position; /** * @type {boolean} */ google.maps.MarkerOptions.prototype.raiseOnDrag; /** * @type {string|google.maps.MarkerImage|google.maps.Symbol} */ google.maps.MarkerOptions.prototype.shadow; /** * @type {google.maps.MarkerShape} */ google.maps.MarkerOptions.prototype.shape; /** * @type {string} */ google.maps.MarkerOptions.prototype.title; /** * @type {boolean} */ google.maps.MarkerOptions.prototype.visible; /** * @type {number} */ google.maps.MarkerOptions.prototype.zIndex; /** * @constructor */ google.maps.MarkerShape = function() {}; /** * @type {Array.<number>} */ google.maps.MarkerShape.prototype.coords; /** * @type {string} */ google.maps.MarkerShape.prototype.type; /** * @constructor */ google.maps.MaxZoomResult = function() {}; /** * @type {google.maps.MaxZoomStatus} */ google.maps.MaxZoomResult.prototype.status; /** * @type {number} */ google.maps.MaxZoomResult.prototype.zoom; /** * @constructor */ google.maps.MaxZoomService = function() {}; /** * @param {google.maps.LatLng} latlng * @param {function(google.maps.MaxZoomResult)} callback * @return {undefined} */ google.maps.MaxZoomService.prototype.getMaxZoomAtLatLng = function(latlng, callback) {}; /** * @enum {number|string} */ google.maps.MaxZoomStatus = { ERROR: '', OK: '' }; /** * @constructor */ google.maps.MouseEvent = function() {}; /** * @type {google.maps.LatLng} */ google.maps.MouseEvent.prototype.latLng; /** * @return {undefined} */ google.maps.MouseEvent.prototype.stop = function() {}; /** * @extends {google.maps.MVCObject} * @constructor */ google.maps.OverlayView = function() {}; /** * @return {undefined} */ google.maps.OverlayView.prototype.draw = function() {}; /** * @nosideeffects * @return {google.maps.Map} */ google.maps.OverlayView.prototype.getMap = function() {}; /** * @nosideeffects * @return {google.maps.MapPanes} */ google.maps.OverlayView.prototype.getPanes = function() {}; /** * @nosideeffects * @return {google.maps.MapCanvasProjection} */ google.maps.OverlayView.prototype.getProjection = function() {}; /** * @return {undefined} */ google.maps.OverlayView.prototype.onAdd = function() {}; /** * @return {undefined} */ google.maps.OverlayView.prototype.onRemove = function() {}; /** * @param {google.maps.Map|google.maps.StreetViewPanorama} map * @return {undefined} */ google.maps.OverlayView.prototype.setMap = function(map) {}; /** * @constructor */ google.maps.OverviewMapControlOptions = function() {}; /** * @type {boolean} */ google.maps.OverviewMapControlOptions.prototype.opened; /** * @constructor */ google.maps.PanControlOptions = function() {}; /** * @type {google.maps.ControlPosition} */ google.maps.PanControlOptions.prototype.position; /** * @constructor */ google.maps.PathElevationRequest = function() {}; /** * @type {Array.<google.maps.LatLng>} */ google.maps.PathElevationRequest.prototype.path; /** * @type {number} */ google.maps.PathElevationRequest.prototype.samples; /** * @param {number} x * @param {number} y * @constructor */ google.maps.Point = function(x, y) {}; /** * @type {number} */ google.maps.Point.prototype.x; /** * @type {number} */ google.maps.Point.prototype.y; /** * @param {google.maps.Point} other * @return {boolean} */ google.maps.Point.prototype.equals = function(other) {}; /** * @return {string} */ google.maps.Point.prototype.toString = function() {}; /** * @extends {google.maps.MouseEvent} * @constructor */ google.maps.PolyMouseEvent = function() {}; /** * @type {number} */ google.maps.PolyMouseEvent.prototype.edge; /** * @type {number} */ google.maps.PolyMouseEvent.prototype.path; /** * @type {number} */ google.maps.PolyMouseEvent.prototype.vertex; /** * @param {(google.maps.PolygonOptions|Object.<string>)=} opt_opts * @extends {google.maps.MVCObject} * @constructor */ google.maps.Polygon = function(opt_opts) {}; /** * @nosideeffects * @return {boolean} */ google.maps.Polygon.prototype.getEditable = function() {}; /** * @nosideeffects * @return {google.maps.Map} */ google.maps.Polygon.prototype.getMap = function() {}; /** * @nosideeffects * @return {google.maps.MVCArray.<google.maps.LatLng>} */ google.maps.Polygon.prototype.getPath = function() {}; /** * @nosideeffects * @return {google.maps.MVCArray.<google.maps.MVCArray.<google.maps.LatLng>>} */ google.maps.Polygon.prototype.getPaths = function() {}; /** * @nosideeffects * @return {boolean} */ google.maps.Polygon.prototype.getVisible = function() {}; /** * @param {boolean} editable * @return {undefined} */ google.maps.Polygon.prototype.setEditable = function(editable) {}; /** * @param {google.maps.Map} map * @return {undefined} */ google.maps.Polygon.prototype.setMap = function(map) {}; /** * @param {google.maps.PolygonOptions|Object.<string>} options * @return {undefined} */ google.maps.Polygon.prototype.setOptions = function(options) {}; /** * @param {google.maps.MVCArray.<google.maps.LatLng>|Array.<google.maps.LatLng>} path * @return {undefined} */ google.maps.Polygon.prototype.setPath = function(path) {}; /** * @param {google.maps.MVCArray.<google.maps.MVCArray.<google.maps.LatLng>>|google.maps.MVCArray.<google.maps.LatLng>|Array.<Array.<google.maps.LatLng>>|Array.<google.maps.LatLng>} paths * @return {undefined} */ google.maps.Polygon.prototype.setPaths = function(paths) {}; /** * @param {boolean} visible * @return {undefined} */ google.maps.Polygon.prototype.setVisible = function(visible) {}; /** * @constructor */ google.maps.PolygonOptions = function() {}; /** * @type {boolean} */ google.maps.PolygonOptions.prototype.clickable; /** * @type {boolean} */ google.maps.PolygonOptions.prototype.editable; /** * @type {string} */ google.maps.PolygonOptions.prototype.fillColor; /** * @type {number} */ google.maps.PolygonOptions.prototype.fillOpacity; /** * @type {boolean} */ google.maps.PolygonOptions.prototype.geodesic; /** * @type {google.maps.Map} */ google.maps.PolygonOptions.prototype.map; /** * @type {google.maps.MVCArray.<google.maps.MVCArray.<google.maps.LatLng>>|google.maps.MVCArray.<google.maps.LatLng>|Array.<Array.<google.maps.LatLng>>|Array.<google.maps.LatLng>} */ google.maps.PolygonOptions.prototype.paths; /** * @type {string} */ google.maps.PolygonOptions.prototype.strokeColor; /** * @type {number} */ google.maps.PolygonOptions.prototype.strokeOpacity; /** * @type {number} */ google.maps.PolygonOptions.prototype.strokeWeight; /** * @type {boolean} */ google.maps.PolygonOptions.prototype.visible; /** * @type {number} */ google.maps.PolygonOptions.prototype.zIndex; /** * @param {(google.maps.PolylineOptions|Object.<string>)=} opt_opts * @extends {google.maps.MVCObject} * @constructor */ google.maps.Polyline = function(opt_opts) {}; /** * @nosideeffects * @return {boolean} */ google.maps.Polyline.prototype.getEditable = function() {}; /** * @nosideeffects * @return {google.maps.Map} */ google.maps.Polyline.prototype.getMap = function() {}; /** * @nosideeffects * @return {google.maps.MVCArray.<google.maps.LatLng>} */ google.maps.Polyline.prototype.getPath = function() {}; /** * @nosideeffects * @return {boolean} */ google.maps.Polyline.prototype.getVisible = function() {}; /** * @param {boolean} editable * @return {undefined} */ google.maps.Polyline.prototype.setEditable = function(editable) {}; /** * @param {google.maps.Map} map * @return {undefined} */ google.maps.Polyline.prototype.setMap = function(map) {}; /** * @param {google.maps.PolylineOptions|Object.<string>} options * @return {undefined} */ google.maps.Polyline.prototype.setOptions = function(options) {}; /** * @param {google.maps.MVCArray.<google.maps.LatLng>|Array.<google.maps.LatLng>} path * @return {undefined} */ google.maps.Polyline.prototype.setPath = function(path) {}; /** * @param {boolean} visible * @return {undefined} */ google.maps.Polyline.prototype.setVisible = function(visible) {}; /** * @constructor */ google.maps.PolylineOptions = function() {}; /** * @type {boolean} */ google.maps.PolylineOptions.prototype.clickable; /** * @type {boolean} */ google.maps.PolylineOptions.prototype.editable; /** * @type {boolean} */ google.maps.PolylineOptions.prototype.geodesic; /** * @type {Array.<google.maps.IconSequence>} */ google.maps.PolylineOptions.prototype.icons; /** * @type {google.maps.Map} */ google.maps.PolylineOptions.prototype.map; /** * @type {google.maps.MVCArray.<google.maps.LatLng>|Array.<google.maps.LatLng>} */ google.maps.PolylineOptions.prototype.path; /** * @type {string} */ google.maps.PolylineOptions.prototype.strokeColor; /** * @type {number} */ google.maps.PolylineOptions.prototype.strokeOpacity; /** * @type {number} */ google.maps.PolylineOptions.prototype.strokeWeight; /** * @type {boolean} */ google.maps.PolylineOptions.prototype.visible; /** * @type {number} */ google.maps.PolylineOptions.prototype.zIndex; /** * @constructor */ google.maps.Projection = function() {}; /** * @param {google.maps.LatLng} latLng * @param {google.maps.Point=} opt_point * @return {google.maps.Point} */ google.maps.Projection.prototype.fromLatLngToPoint = function(latLng, opt_point) {}; /** * @param {google.maps.Point} pixel * @param {boolean=} opt_nowrap * @return {google.maps.LatLng} */ google.maps.Projection.prototype.fromPointToLatLng = function(pixel, opt_nowrap) {}; /** * @param {(google.maps.RectangleOptions|Object.<string>)=} opt_opts * @extends {google.maps.MVCObject} * @constructor */ google.maps.Rectangle = function(opt_opts) {}; /** * @nosideeffects * @return {google.maps.LatLngBounds} */ google.maps.Rectangle.prototype.getBounds = function() {}; /** * @nosideeffects * @return {boolean} */ google.maps.Rectangle.prototype.getEditable = function() {}; /** * @nosideeffects * @return {google.maps.Map} */ google.maps.Rectangle.prototype.getMap = function() {}; /** * @nosideeffects * @return {boolean} */ google.maps.Rectangle.prototype.getVisible = function() {}; /** * @param {google.maps.LatLngBounds} bounds * @return {undefined} */ google.maps.Rectangle.prototype.setBounds = function(bounds) {}; /** * @param {boolean} editable * @return {undefined} */ google.maps.Rectangle.prototype.setEditable = function(editable) {}; /** * @param {google.maps.Map} map * @return {undefined} */ google.maps.Rectangle.prototype.setMap = function(map) {}; /** * @param {google.maps.RectangleOptions|Object.<string>} options * @return {undefined} */ google.maps.Rectangle.prototype.setOptions = function(options) {}; /** * @param {boolean} visible * @return {undefined} */ google.maps.Rectangle.prototype.setVisible = function(visible) {}; /** * @constructor */ google.maps.RectangleOptions = function() {}; /** * @type {google.maps.LatLngBounds} */ google.maps.RectangleOptions.prototype.bounds; /** * @type {boolean} */ google.maps.RectangleOptions.prototype.clickable; /** * @type {boolean} */ google.maps.RectangleOptions.prototype.editable; /** * @type {string} */ google.maps.RectangleOptions.prototype.fillColor; /** * @type {number} */ google.maps.RectangleOptions.prototype.fillOpacity; /** * @type {google.maps.Map} */ google.maps.RectangleOptions.prototype.map; /** * @type {string} */ google.maps.RectangleOptions.prototype.strokeColor; /** * @type {number} */ google.maps.RectangleOptions.prototype.strokeOpacity; /** * @type {number} */ google.maps.RectangleOptions.prototype.strokeWeight; /** * @type {boolean} */ google.maps.RectangleOptions.prototype.visible; /** * @type {number} */ google.maps.RectangleOptions.prototype.zIndex; /** * @constructor */ google.maps.RotateControlOptions = function() {}; /** * @type {google.maps.ControlPosition} */ google.maps.RotateControlOptions.prototype.position; /** * @constructor */ google.maps.ScaleControlOptions = function() {}; /** * @type {google.maps.ControlPosition} */ google.maps.ScaleControlOptions.prototype.position; /** * @type {google.maps.ScaleControlStyle} */ google.maps.ScaleControlOptions.prototype.style; /** * @enum {number|string} */ google.maps.ScaleControlStyle = { DEFAULT: '' }; /** * @param {number} width * @param {number} height * @param {string=} opt_widthUnit * @param {string=} opt_heightUnit * @constructor */ google.maps.Size = function(width, height, opt_widthUnit, opt_heightUnit) {}; /** * @type {number} */ google.maps.Size.prototype.height; /** * @type {number} */ google.maps.Size.prototype.width; /** * @param {google.maps.Size} other * @return {boolean} */ google.maps.Size.prototype.equals = function(other) {}; /** * @return {string} */ google.maps.Size.prototype.toString = function() {}; /** * @constructor */ google.maps.StreetViewAddressControlOptions = function() {}; /** * @type {google.maps.ControlPosition} */ google.maps.StreetViewAddressControlOptions.prototype.position; /** * @constructor */ google.maps.StreetViewControlOptions = function() {}; /** * @type {google.maps.ControlPosition} */ google.maps.StreetViewControlOptions.prototype.position; /** * @constructor */ google.maps.StreetViewLink = function() {}; /** * @type {string} */ google.maps.StreetViewLink.prototype.description; /** * @type {number} */ google.maps.StreetViewLink.prototype.heading; /** * @type {string} */ google.maps.StreetViewLink.prototype.pano; /** * @constructor */ google.maps.StreetViewLocation = function() {}; /** * @type {string} */ google.maps.StreetViewLocation.prototype.description; /** * @type {google.maps.LatLng} */ google.maps.StreetViewLocation.prototype.latLng; /** * @type {string} */ google.maps.StreetViewLocation.prototype.pano; /** * @param {Node} container * @param {(google.maps.StreetViewPanoramaOptions|Object.<string>)=} opt_opts * @extends {google.maps.MVCObject} * @constructor */ google.maps.StreetViewPanorama = function(container, opt_opts) {}; /** * @type {Array.<google.maps.MVCArray.<Node>>} */ google.maps.StreetViewPanorama.prototype.controls; /** * @nosideeffects * @return {Array.<google.maps.StreetViewLink>} */ google.maps.StreetViewPanorama.prototype.getLinks = function() {}; /** * @nosideeffects * @return {string} */ google.maps.StreetViewPanorama.prototype.getPano = function() {}; /** * @nosideeffects * @return {google.maps.LatLng} */ google.maps.StreetViewPanorama.prototype.getPosition = function() {}; /** * @nosideeffects * @return {google.maps.StreetViewPov} */ google.maps.StreetViewPanorama.prototype.getPov = function() {}; /** * @nosideeffects * @return {boolean} */ google.maps.StreetViewPanorama.prototype.getVisible = function() {}; /** * @param {function(string):google.maps.StreetViewPanoramaData} provider * @return {undefined} */ google.maps.StreetViewPanorama.prototype.registerPanoProvider = function(provider) {}; /** * @param {string} pano * @return {undefined} */ google.maps.StreetViewPanorama.prototype.setPano = function(pano) {}; /** * @param {google.maps.LatLng} latLng * @return {undefined} */ google.maps.StreetViewPanorama.prototype.setPosition = function(latLng) {}; /** * @param {google.maps.StreetViewPov} pov * @return {undefined} */ google.maps.StreetViewPanorama.prototype.setPov = function(pov) {}; /** * @param {boolean} flag * @return {undefined} */ google.maps.StreetViewPanorama.prototype.setVisible = function(flag) {}; /** * @constructor */ google.maps.StreetViewPanoramaData = function() {}; /** * @type {string} */ google.maps.StreetViewPanoramaData.prototype.copyright; /** * @type {string} */ google.maps.StreetViewPanoramaData.prototype.imageDate; /** * @type {Array.<google.maps.StreetViewLink>} */ google.maps.StreetViewPanoramaData.prototype.links; /** * @type {google.maps.StreetViewLocation} */ google.maps.StreetViewPanoramaData.prototype.location; /** * @type {google.maps.StreetViewTileData} */ google.maps.StreetViewPanoramaData.prototype.tiles; /** * @constructor */ google.maps.StreetViewPanoramaOptions = function() {}; /** * @type {boolean} */ google.maps.StreetViewPanoramaOptions.prototype.addressControl; /** * @type {google.maps.StreetViewAddressControlOptions|Object.<string>} */ google.maps.StreetViewPanoramaOptions.prototype.addressControlOptions; /** * @type {boolean} */ google.maps.StreetViewPanoramaOptions.prototype.clickToGo; /** * @type {boolean} */ google.maps.StreetViewPanoramaOptions.prototype.disableDoubleClickZoom; /** * @type {boolean} */ google.maps.StreetViewPanoramaOptions.prototype.enableCloseButton; /** * @type {boolean} */ google.maps.StreetViewPanoramaOptions.prototype.imageDateControl; /** * @type {boolean} */ google.maps.StreetViewPanoramaOptions.prototype.linksControl; /** * @type {boolean} */ google.maps.StreetViewPanoramaOptions.prototype.panControl; /** * @type {google.maps.PanControlOptions|Object.<string>} */ google.maps.StreetViewPanoramaOptions.prototype.panControlOptions; /** * @type {string} */ google.maps.StreetViewPanoramaOptions.prototype.pano; /** * @type {function(string):google.maps.StreetViewPanoramaData} */ google.maps.StreetViewPanoramaOptions.prototype.panoProvider; /** * @type {google.maps.LatLng} */ google.maps.StreetViewPanoramaOptions.prototype.position; /** * @type {google.maps.StreetViewPov} */ google.maps.StreetViewPanoramaOptions.prototype.pov; /** * @type {boolean} */ google.maps.StreetViewPanoramaOptions.prototype.scrollwheel; /** * @type {boolean} */ google.maps.StreetViewPanoramaOptions.prototype.visible; /** * @type {boolean} */ google.maps.StreetViewPanoramaOptions.prototype.zoomControl; /** * @type {google.maps.ZoomControlOptions|Object.<string>} */ google.maps.StreetViewPanoramaOptions.prototype.zoomControlOptions; /** * @constructor */ google.maps.StreetViewPov = function() {}; /** * @type {number} */ google.maps.StreetViewPov.prototype.heading; /** * @type {number} */ google.maps.StreetViewPov.prototype.pitch; /** * @type {number} */ google.maps.StreetViewPov.prototype.zoom; /** * @constructor */ google.maps.StreetViewService = function() {}; /** * @param {string} pano * @param {function(google.maps.StreetViewPanoramaData, google.maps.StreetViewStatus)} callback * @return {undefined} */ google.maps.StreetViewService.prototype.getPanoramaById = function(pano, callback) {}; /** * @param {google.maps.LatLng} latlng * @param {number} radius * @param {function(google.maps.StreetViewPanoramaData, google.maps.StreetViewStatus)} callback * @return {undefined} */ google.maps.StreetViewService.prototype.getPanoramaByLocation = function(latlng, radius, callback) {}; /** * @enum {number|string} */ google.maps.StreetViewStatus = { OK: '', UNKNOWN_ERROR: '', ZERO_RESULTS: '' }; /** * @constructor */ google.maps.StreetViewTileData = function() {}; /** * @type {number} */ google.maps.StreetViewTileData.prototype.centerHeading; /** * @type {google.maps.Size} */ google.maps.StreetViewTileData.prototype.tileSize; /** * @type {google.maps.Size} */ google.maps.StreetViewTileData.prototype.worldSize; /** * @param {string} pano * @param {number} tileZoom * @param {number} tileX * @param {number} tileY * @return {string} */ google.maps.StreetViewTileData.prototype.getTileUrl = function(pano, tileZoom, tileX, tileY) {}; /** * @param {Array.<google.maps.MapTypeStyle>} styles * @param {(google.maps.StyledMapTypeOptions|Object.<string>)=} opt_options * @constructor */ google.maps.StyledMapType = function(styles, opt_options) {}; /** * @constructor */ google.maps.StyledMapTypeOptions = function() {}; /** * @type {string} */ google.maps.StyledMapTypeOptions.prototype.alt; /** * @type {number} */ google.maps.StyledMapTypeOptions.prototype.maxZoom; /** * @type {number} */ google.maps.StyledMapTypeOptions.prototype.minZoom; /** * @type {string} */ google.maps.StyledMapTypeOptions.prototype.name; /** * @constructor */ google.maps.Symbol = function() {}; /** * @type {google.maps.Point} */ google.maps.Symbol.prototype.anchor; /** * @type {string} */ google.maps.Symbol.prototype.fillColor; /** * @type {number} */ google.maps.Symbol.prototype.fillOpacity; /** * @type {google.maps.SymbolPath|string} */ google.maps.Symbol.prototype.path; /** * @type {number} */ google.maps.Symbol.prototype.rotation; /** * @type {number} */ google.maps.Symbol.prototype.scale; /** * @type {string} */ google.maps.Symbol.prototype.strokeColor; /** * @type {number} */ google.maps.Symbol.prototype.strokeOpacity; /** * @type {number} */ google.maps.Symbol.prototype.strokeWeight; /** * @enum {number|string} */ google.maps.SymbolPath = { BACKWARD_CLOSED_ARROW: '', BACKWARD_OPEN_ARROW: '', CIRCLE: '', FORWARD_CLOSED_ARROW: '', FORWARD_OPEN_ARROW: '' }; /** * @constructor */ google.maps.Time = function() {}; /** * @type {string} */ google.maps.Time.prototype.text; /** * @type {string} */ google.maps.Time.prototype.time_zone; /** * @type {Date} */ google.maps.Time.prototype.value; /** * @extends {google.maps.MVCObject} * @constructor */ google.maps.TrafficLayer = function() {}; /** * @nosideeffects * @return {google.maps.Map} */ google.maps.TrafficLayer.prototype.getMap = function() {}; /** * @param {google.maps.Map} map * @return {undefined} */ google.maps.TrafficLayer.prototype.setMap = function(map) {}; /** * @constructor */ google.maps.TransitAgency = function() {}; /** * @type {string} */ google.maps.TransitAgency.prototype.name; /** * @type {string} */ google.maps.TransitAgency.prototype.phone; /** * @type {string} */ google.maps.TransitAgency.prototype.url; /** * @constructor */ google.maps.TransitDetails = function() {}; /** * @type {google.maps.TransitStop} */ google.maps.TransitDetails.prototype.arrival_stop; /** * @type {google.maps.Time} */ google.maps.TransitDetails.prototype.arrival_time; /** * @type {google.maps.TransitStop} */ google.maps.TransitDetails.prototype.departure_stop; /** * @type {google.maps.Time} */ google.maps.TransitDetails.prototype.departure_time; /** * @type {string} */ google.maps.TransitDetails.prototype.headsign; /** * @type {number} */ google.maps.TransitDetails.prototype.headway; /** * @type {google.maps.TransitLine} */ google.maps.TransitDetails.prototype.line; /** * @type {number} */ google.maps.TransitDetails.prototype.num_stops; /** * @extends {google.maps.MVCObject} * @constructor */ google.maps.TransitLayer = function() {}; /** * @nosideeffects * @return {google.maps.Map} */ google.maps.TransitLayer.prototype.getMap = function() {}; /** * @param {google.maps.Map} map * @return {undefined} */ google.maps.TransitLayer.prototype.setMap = function(map) {}; /** * @constructor */ google.maps.TransitLine = function() {}; /** * @type {Array.<google.maps.TransitAgency>} */ google.maps.TransitLine.prototype.agencies; /** * @type {string} */ google.maps.TransitLine.prototype.color; /** * @type {string} */ google.maps.TransitLine.prototype.icon; /** * @type {string} */ google.maps.TransitLine.prototype.name; /** * @type {string} */ google.maps.TransitLine.prototype.short_name; /** * @type {string} */ google.maps.TransitLine.prototype.text_color; /** * @type {string} */ google.maps.TransitLine.prototype.url; /** * @type {google.maps.TransitVehicle} */ google.maps.TransitLine.prototype.vehicle; /** * @constructor */ google.maps.TransitOptions = function() {}; /** * @type {Date} */ google.maps.TransitOptions.prototype.arrivalTime; /** * @type {Date} */ google.maps.TransitOptions.prototype.departureTime; /** * @constructor */ google.maps.TransitStop = function() {}; /** * @type {google.maps.LatLng} */ google.maps.TransitStop.prototype.location; /** * @type {string} */ google.maps.TransitStop.prototype.name; /** * @constructor */ google.maps.TransitVehicle = function() {}; /** * @type {string} */ google.maps.TransitVehicle.prototype.icon; /** * @type {string} */ google.maps.TransitVehicle.prototype.local_icon; /** * @type {string} */ google.maps.TransitVehicle.prototype.name; /** * @enum {number|string} */ google.maps.TravelMode = { BICYCLING: '', DRIVING: '', TRANSIT: '', WALKING: '' }; /** * @enum {number|string} */ google.maps.UnitSystem = { IMPERIAL: '', METRIC: '' }; /** * @constructor */ google.maps.ZoomControlOptions = function() {}; /** * @type {google.maps.ControlPosition} */ google.maps.ZoomControlOptions.prototype.position; /** * @type {google.maps.ZoomControlStyle} */ google.maps.ZoomControlOptions.prototype.style; /** * @enum {number|string} */ google.maps.ZoomControlStyle = { DEFAULT: '', LARGE: '', SMALL: '' }; // Namespace google.maps.adsense = {}; /** * @enum {number|string} */ google.maps.adsense.AdFormat = { BANNER: '', BUTTON: '', HALF_BANNER: '', LARGE_RECTANGLE: '', LEADERBOARD: '', MEDIUM_RECTANGLE: '', SKYSCRAPER: '', SMALL_RECTANGLE: '', SMALL_SQUARE: '', SQUARE: '', VERTICAL_BANNER: '', WIDE_SKYSCRAPER: '' }; /** * @param {Node} container * @param {google.maps.adsense.AdUnitOptions|Object.<string>} opts * @extends {google.maps.MVCObject} * @constructor */ google.maps.adsense.AdUnit = function(container, opts) {}; /** * @nosideeffects * @return {string} */ google.maps.adsense.AdUnit.prototype.getChannelNumber = function() {}; /** * @nosideeffects * @return {Node} */ google.maps.adsense.AdUnit.prototype.getContainer = function() {}; /** * @nosideeffects * @return {google.maps.adsense.AdFormat} */ google.maps.adsense.AdUnit.prototype.getFormat = function() {}; /** * @nosideeffects * @return {google.maps.Map} */ google.maps.adsense.AdUnit.prototype.getMap = function() {}; /** * @nosideeffects * @return {google.maps.ControlPosition} */ google.maps.adsense.AdUnit.prototype.getPosition = function() {}; /** * @nosideeffects * @return {string} */ google.maps.adsense.AdUnit.prototype.getPublisherId = function() {}; /** * @param {string} channelNumber * @return {undefined} */ google.maps.adsense.AdUnit.prototype.setChannelNumber = function(channelNumber) {}; /** * @param {google.maps.adsense.AdFormat} format * @return {undefined} */ google.maps.adsense.AdUnit.prototype.setFormat = function(format) {}; /** * @param {google.maps.Map} map * @return {undefined} */ google.maps.adsense.AdUnit.prototype.setMap = function(map) {}; /** * @param {google.maps.ControlPosition} position * @return {undefined} */ google.maps.adsense.AdUnit.prototype.setPosition = function(position) {}; /** * @constructor */ google.maps.adsense.AdUnitOptions = function() {}; /** * @type {string} */ google.maps.adsense.AdUnitOptions.prototype.channelNumber; /** * @type {google.maps.adsense.AdFormat} */ google.maps.adsense.AdUnitOptions.prototype.format; /** * @type {google.maps.Map} */ google.maps.adsense.AdUnitOptions.prototype.map; /** * @type {google.maps.ControlPosition} */ google.maps.adsense.AdUnitOptions.prototype.position; /** * @type {string} */ google.maps.adsense.AdUnitOptions.prototype.publisherId; // Namespace google.maps.drawing = {}; /** * @constructor */ google.maps.drawing.DrawingControlOptions = function() {}; /** * @type {Array.<google.maps.drawing.OverlayType>} */ google.maps.drawing.DrawingControlOptions.prototype.drawingModes; /** * @type {google.maps.ControlPosition} */ google.maps.drawing.DrawingControlOptions.prototype.position; /** * @param {(google.maps.drawing.DrawingManagerOptions|Object.<string>)=} opt_options * @extends {google.maps.MVCObject} * @constructor */ google.maps.drawing.DrawingManager = function(opt_options) {}; /** * @nosideeffects * @return {?google.maps.drawing.OverlayType} */ google.maps.drawing.DrawingManager.prototype.getDrawingMode = function() {}; /** * @nosideeffects * @return {google.maps.Map} */ google.maps.drawing.DrawingManager.prototype.getMap = function() {}; /** * @param {?google.maps.drawing.OverlayType} drawingMode * @return {undefined} */ google.maps.drawing.DrawingManager.prototype.setDrawingMode = function(drawingMode) {}; /** * @param {google.maps.Map} map * @return {undefined} */ google.maps.drawing.DrawingManager.prototype.setMap = function(map) {}; /** * @param {google.maps.drawing.DrawingManagerOptions|Object.<string>} options * @return {undefined} */ google.maps.drawing.DrawingManager.prototype.setOptions = function(options) {}; /** * @constructor */ google.maps.drawing.DrawingManagerOptions = function() {}; /** * @type {google.maps.CircleOptions|Object.<string>} */ google.maps.drawing.DrawingManagerOptions.prototype.circleOptions; /** * @type {boolean} */ google.maps.drawing.DrawingManagerOptions.prototype.drawingControl; /** * @type {google.maps.drawing.DrawingControlOptions|Object.<string>} */ google.maps.drawing.DrawingManagerOptions.prototype.drawingControlOptions; /** * @type {google.maps.drawing.OverlayType} */ google.maps.drawing.DrawingManagerOptions.prototype.drawingMode; /** * @type {google.maps.Map} */ google.maps.drawing.DrawingManagerOptions.prototype.map; /** * @type {google.maps.MarkerOptions|Object.<string>} */ google.maps.drawing.DrawingManagerOptions.prototype.markerOptions; /** * @type {google.maps.PolygonOptions|Object.<string>} */ google.maps.drawing.DrawingManagerOptions.prototype.polygonOptions; /** * @type {google.maps.PolylineOptions|Object.<string>} */ google.maps.drawing.DrawingManagerOptions.prototype.polylineOptions; /** * @type {google.maps.RectangleOptions|Object.<string>} */ google.maps.drawing.DrawingManagerOptions.prototype.rectangleOptions; /** * @constructor */ google.maps.drawing.OverlayCompleteEvent = function() {}; /** * @type {google.maps.Marker|google.maps.Polygon|google.maps.Polyline|google.maps.Rectangle|google.maps.Circle} */ google.maps.drawing.OverlayCompleteEvent.prototype.overlay; /** * @type {google.maps.drawing.OverlayType} */ google.maps.drawing.OverlayCompleteEvent.prototype.type; /** * @enum {number|string} */ google.maps.drawing.OverlayType = { CIRCLE: '', MARKER: '', POLYGON: '', POLYLINE: '', RECTANGLE: '' }; // Namespace google.maps.event = {}; /** * @param {Object} instance * @param {string} eventName * @param {!Function} handler * @param {boolean=} opt_capture * @return {google.maps.MapsEventListener} */ google.maps.event.addDomListener = function(instance, eventName, handler, opt_capture) {}; /** * @param {Object} instance * @param {string} eventName * @param {!Function} handler * @param {boolean=} opt_capture * @return {google.maps.MapsEventListener} */ google.maps.event.addDomListenerOnce = function(instance, eventName, handler, opt_capture) {}; /** * @param {Object} instance * @param {string} eventName * @param {!Function} handler * @return {google.maps.MapsEventListener} */ google.maps.event.addListener = function(instance, eventName, handler) {}; /** * @param {Object} instance * @param {string} eventName * @param {!Function} handler * @return {google.maps.MapsEventListener} */ google.maps.event.addListenerOnce = function(instance, eventName, handler) {}; /** * @param {Object} instance * @return {undefined} */ google.maps.event.clearInstanceListeners = function(instance) {}; /** * @param {Object} instance * @param {string} eventName * @return {undefined} */ google.maps.event.clearListeners = function(instance, eventName) {}; /** * @param {google.maps.MapsEventListener} listener * @return {undefined} */ google.maps.event.removeListener = function(listener) {}; /** * @param {Object} instance * @param {string} eventName * @param {...*} var_args * @return {undefined} */ google.maps.event.trigger = function(instance, eventName, var_args) {}; // Namespace google.maps.geometry = {}; // Namespace google.maps.geometry.encoding = {}; /** * @param {string} encodedPath * @return {Array.<google.maps.LatLng>} */ google.maps.geometry.encoding.decodePath = function(encodedPath) {}; /** * @param {Array.<google.maps.LatLng>|google.maps.MVCArray.<google.maps.LatLng>} path * @return {string} */ google.maps.geometry.encoding.encodePath = function(path) {}; // Namespace google.maps.geometry.poly = {}; /** * @param {google.maps.LatLng} point * @param {google.maps.Polygon} polygon * @return {boolean} */ google.maps.geometry.poly.containsLocation = function(point, polygon) {}; /** * @param {google.maps.LatLng} point * @param {google.maps.Polygon|google.maps.Polyline} poly * @param {number=} opt_tolerance * @return {boolean} */ google.maps.geometry.poly.isLocationOnEdge = function(point, poly, opt_tolerance) {}; // Namespace google.maps.geometry.spherical = {}; /** * @param {Array.<google.maps.LatLng>|google.maps.MVCArray.<google.maps.LatLng>} path * @param {number=} opt_radius * @return {number} */ google.maps.geometry.spherical.computeArea = function(path, opt_radius) {}; /** * @param {google.maps.LatLng} from * @param {google.maps.LatLng} to * @param {number=} opt_radius * @return {number} */ google.maps.geometry.spherical.computeDistanceBetween = function(from, to, opt_radius) {}; /** * @param {google.maps.LatLng} from * @param {google.maps.LatLng} to * @return {number} */ google.maps.geometry.spherical.computeHeading = function(from, to) {}; /** * @param {Array.<google.maps.LatLng>|google.maps.MVCArray.<google.maps.LatLng>} path * @param {number=} opt_radius * @return {number} */ google.maps.geometry.spherical.computeLength = function(path, opt_radius) {}; /** * @param {google.maps.LatLng} from * @param {number} distance * @param {number} heading * @param {number=} opt_radius * @return {google.maps.LatLng} */ google.maps.geometry.spherical.computeOffset = function(from, distance, heading, opt_radius) {}; /** * @param {Array.<google.maps.LatLng>|google.maps.MVCArray.<google.maps.LatLng>} loop * @param {number=} opt_radius * @return {number} */ google.maps.geometry.spherical.computeSignedArea = function(loop, opt_radius) {}; /** * @param {google.maps.LatLng} from * @param {google.maps.LatLng} to * @param {number} fraction * @return {google.maps.LatLng} */ google.maps.geometry.spherical.interpolate = function(from, to, fraction) {}; // Namespace google.maps.panoramio = {}; /** * @constructor */ google.maps.panoramio.PanoramioFeature = function() {}; /** * @type {string} */ google.maps.panoramio.PanoramioFeature.prototype.author; /** * @type {string} */ google.maps.panoramio.PanoramioFeature.prototype.photoId; /** * @type {string} */ google.maps.panoramio.PanoramioFeature.prototype.title; /** * @type {string} */ google.maps.panoramio.PanoramioFeature.prototype.url; /** * @type {string} */ google.maps.panoramio.PanoramioFeature.prototype.userId; /** * @param {(google.maps.panoramio.PanoramioLayerOptions|Object.<string>)=} opt_opts * @extends {google.maps.MVCObject} * @constructor */ google.maps.panoramio.PanoramioLayer = function(opt_opts) {}; /** * @nosideeffects * @return {google.maps.Map} */ google.maps.panoramio.PanoramioLayer.prototype.getMap = function() {}; /** * @nosideeffects * @return {string} */ google.maps.panoramio.PanoramioLayer.prototype.getTag = function() {}; /** * @nosideeffects * @return {string} */ google.maps.panoramio.PanoramioLayer.prototype.getUserId = function() {}; /** * @param {google.maps.Map} map * @return {undefined} */ google.maps.panoramio.PanoramioLayer.prototype.setMap = function(map) {}; /** * @param {google.maps.panoramio.PanoramioLayerOptions|Object.<string>} options * @return {undefined} */ google.maps.panoramio.PanoramioLayer.prototype.setOptions = function(options) {}; /** * @param {string} tag * @return {undefined} */ google.maps.panoramio.PanoramioLayer.prototype.setTag = function(tag) {}; /** * @param {string} userId * @return {undefined} */ google.maps.panoramio.PanoramioLayer.prototype.setUserId = function(userId) {}; /** * @constructor */ google.maps.panoramio.PanoramioLayerOptions = function() {}; /** * @type {boolean} */ google.maps.panoramio.PanoramioLayerOptions.prototype.clickable; /** * @type {google.maps.Map} */ google.maps.panoramio.PanoramioLayerOptions.prototype.map; /** * @type {boolean} */ google.maps.panoramio.PanoramioLayerOptions.prototype.suppressInfoWindows; /** * @type {string} */ google.maps.panoramio.PanoramioLayerOptions.prototype.tag; /** * @type {string} */ google.maps.panoramio.PanoramioLayerOptions.prototype.userId; /** * @constructor */ google.maps.panoramio.PanoramioMouseEvent = function() {}; /** * @type {google.maps.panoramio.PanoramioFeature} */ google.maps.panoramio.PanoramioMouseEvent.prototype.featureDetails; /** * @type {string} */ google.maps.panoramio.PanoramioMouseEvent.prototype.infoWindowHtml; /** * @type {google.maps.LatLng} */ google.maps.panoramio.PanoramioMouseEvent.prototype.latLng; /** * @type {google.maps.Size} */ google.maps.panoramio.PanoramioMouseEvent.prototype.pixelOffset; // Namespace google.maps.places = {}; /** * @param {HTMLInputElement} inputField * @param {(google.maps.places.AutocompleteOptions|Object.<string>)=} opt_opts * @extends {google.maps.MVCObject} * @constructor */ google.maps.places.Autocomplete = function(inputField, opt_opts) {}; /** * @nosideeffects * @return {google.maps.LatLngBounds} */ google.maps.places.Autocomplete.prototype.getBounds = function() {}; /** * @nosideeffects * @return {google.maps.places.PlaceResult} */ google.maps.places.Autocomplete.prototype.getPlace = function() {}; /** * @param {google.maps.LatLngBounds} bounds * @return {undefined} */ google.maps.places.Autocomplete.prototype.setBounds = function(bounds) {}; /** * @param {google.maps.places.ComponentRestrictions} restrictions * @return {undefined} */ google.maps.places.Autocomplete.prototype.setComponentRestrictions = function(restrictions) {}; /** * @param {Array.<string>} types * @return {undefined} */ google.maps.places.Autocomplete.prototype.setTypes = function(types) {}; /** * @constructor */ google.maps.places.AutocompleteOptions = function() {}; /** * @type {google.maps.LatLngBounds} */ google.maps.places.AutocompleteOptions.prototype.bounds; /** * @type {google.maps.places.ComponentRestrictions} */ google.maps.places.AutocompleteOptions.prototype.componentRestrictions; /** * @type {Array.<string>} */ google.maps.places.AutocompleteOptions.prototype.types; /** * @constructor */ google.maps.places.ComponentRestrictions = function() {}; /** * @type {string} */ google.maps.places.ComponentRestrictions.prototype.country; /** * @constructor */ google.maps.places.PlaceDetailsRequest = function() {}; /** * @type {string} */ google.maps.places.PlaceDetailsRequest.prototype.reference; /** * @constructor */ google.maps.places.PlaceGeometry = function() {}; /** * @type {google.maps.LatLng} */ google.maps.places.PlaceGeometry.prototype.location; /** * @type {google.maps.LatLngBounds} */ google.maps.places.PlaceGeometry.prototype.viewport; /** * @constructor */ google.maps.places.PlaceResult = function() {}; /** * @type {Array.<google.maps.GeocoderAddressComponent>} */ google.maps.places.PlaceResult.prototype.address_components; /** * @type {string} */ google.maps.places.PlaceResult.prototype.formatted_address; /** * @type {string} */ google.maps.places.PlaceResult.prototype.formatted_phone_number; /** * @type {google.maps.places.PlaceGeometry} */ google.maps.places.PlaceResult.prototype.geometry; /** * @type {Array.<string>} */ google.maps.places.PlaceResult.prototype.html_attributions; /** * @type {string} */ google.maps.places.PlaceResult.prototype.icon; /** * @type {string} */ google.maps.places.PlaceResult.prototype.id; /** * @type {string} */ google.maps.places.PlaceResult.prototype.international_phone_number; /** * @type {string} */ google.maps.places.PlaceResult.prototype.name; /** * @type {number} */ google.maps.places.PlaceResult.prototype.rating; /** * @type {string} */ google.maps.places.PlaceResult.prototype.reference; /** * @type {Array.<string>} */ google.maps.places.PlaceResult.prototype.types; /** * @type {string} */ google.maps.places.PlaceResult.prototype.url; /** * @type {string} */ google.maps.places.PlaceResult.prototype.vicinity; /** * @type {string} */ google.maps.places.PlaceResult.prototype.website; /** * @constructor */ google.maps.places.PlaceSearchPagination = function() {}; /** * @type {boolean} */ google.maps.places.PlaceSearchPagination.prototype.hasNextPage; /** * @return {undefined} */ google.maps.places.PlaceSearchPagination.prototype.nextPage = function() {}; /** * @constructor */ google.maps.places.PlaceSearchRequest = function() {}; /** * @type {google.maps.LatLngBounds} */ google.maps.places.PlaceSearchRequest.prototype.bounds; /** * @type {string} */ google.maps.places.PlaceSearchRequest.prototype.keyword; /** * @type {google.maps.LatLng} */ google.maps.places.PlaceSearchRequest.prototype.location; /** * @type {string} */ google.maps.places.PlaceSearchRequest.prototype.name; /** * @type {number} */ google.maps.places.PlaceSearchRequest.prototype.radius; /** * @type {google.maps.places.RankBy} */ google.maps.places.PlaceSearchRequest.prototype.rankBy; /** * @type {Array.<string>} */ google.maps.places.PlaceSearchRequest.prototype.types; /** * @param {HTMLDivElement|google.maps.Map} attrContainer * @constructor */ google.maps.places.PlacesService = function(attrContainer) {}; /** * @param {google.maps.places.PlaceDetailsRequest|Object.<string>} request * @param {function(google.maps.places.PlaceResult, google.maps.places.PlacesServiceStatus)} callback * @return {undefined} */ google.maps.places.PlacesService.prototype.getDetails = function(request, callback) {}; /** * @param {google.maps.places.PlaceSearchRequest|Object.<string>} request * @param {function(Array.<google.maps.places.PlaceResult>, google.maps.places.PlacesServiceStatus, google.maps.places.PlaceSearchPagination)} callback * @return {undefined} */ google.maps.places.PlacesService.prototype.nearbySearch = function(request, callback) {}; /** * @param {google.maps.places.TextSearchRequest|Object.<string>} request * @param {function(Array.<google.maps.places.PlaceResult>, google.maps.places.PlacesServiceStatus)} callback * @return {undefined} */ google.maps.places.PlacesService.prototype.textSearch = function(request, callback) {}; /** * @enum {number|string} */ google.maps.places.PlacesServiceStatus = { INVALID_REQUEST: '', OK: '', OVER_QUERY_LIMIT: '', REQUEST_DENIED: '', UNKNOWN_ERROR: '', ZERO_RESULTS: '' }; /** * @enum {number|string} */ google.maps.places.RankBy = { DISTANCE: '', PROMINENCE: '' }; /** * @constructor */ google.maps.places.TextSearchRequest = function() {}; /** * @type {google.maps.LatLngBounds} */ google.maps.places.TextSearchRequest.prototype.bounds; /** * @type {google.maps.LatLng} */ google.maps.places.TextSearchRequest.prototype.location; /** * @type {string} */ google.maps.places.TextSearchRequest.prototype.query; /** * @type {number} */ google.maps.places.TextSearchRequest.prototype.radius; // Namespace google.maps.visualization = {}; /** * @param {(google.maps.visualization.HeatmapLayerOptions|Object.<string>)=} opt_opts * @extends {google.maps.MVCObject} * @constructor */ google.maps.visualization.HeatmapLayer = function(opt_opts) {}; /** * @nosideeffects * @return {google.maps.MVCArray.<google.maps.LatLng|google.maps.visualization.WeightedLocation>} */ google.maps.visualization.HeatmapLayer.prototype.getData = function() {}; /** * @nosideeffects * @return {google.maps.Map} */ google.maps.visualization.HeatmapLayer.prototype.getMap = function() {}; /** * @param {google.maps.MVCArray.<google.maps.LatLng|google.maps.visualization.WeightedLocation>|Array.<google.maps.LatLng|google.maps.visualization.WeightedLocation>} data * @return {undefined} */ google.maps.visualization.HeatmapLayer.prototype.setData = function(data) {}; /** * @param {google.maps.Map} map * @return {undefined} */ google.maps.visualization.HeatmapLayer.prototype.setMap = function(map) {}; /** * @constructor */ google.maps.visualization.HeatmapLayerOptions = function() {}; /** * @type {google.maps.MVCArray.<google.maps.LatLng>} */ google.maps.visualization.HeatmapLayerOptions.prototype.data; /** * @type {boolean} */ google.maps.visualization.HeatmapLayerOptions.prototype.dissipating; /** * @type {Array.<string>} */ google.maps.visualization.HeatmapLayerOptions.prototype.gradient; /** * @type {google.maps.Map} */ google.maps.visualization.HeatmapLayerOptions.prototype.map; /** * @type {number} */ google.maps.visualization.HeatmapLayerOptions.prototype.maxIntensity; /** * @type {number} */ google.maps.visualization.HeatmapLayerOptions.prototype.opacity; /** * @type {number} */ google.maps.visualization.HeatmapLayerOptions.prototype.radius; /** * @constructor */ google.maps.visualization.WeightedLocation = function() {}; /** * @type {google.maps.LatLng} */ google.maps.visualization.WeightedLocation.prototype.location; /** * @type {number} */ google.maps.visualization.WeightedLocation.prototype.weight; // Namespace google.maps.weather = {}; /** * @extends {google.maps.MVCObject} * @constructor */ google.maps.weather.CloudLayer = function() {}; /** * @nosideeffects * @return {google.maps.Map} */ google.maps.weather.CloudLayer.prototype.getMap = function() {}; /** * @param {google.maps.Map} map * @return {undefined} */ google.maps.weather.CloudLayer.prototype.setMap = function(map) {}; /** * @enum {number|string} */ google.maps.weather.LabelColor = { BLACK: '', WHITE: '' }; /** * @enum {number|string} */ google.maps.weather.TemperatureUnit = { CELSIUS: '', FAHRENHEIT: '' }; /** * @constructor */ google.maps.weather.WeatherConditions = function() {}; /** * @type {string} */ google.maps.weather.WeatherConditions.prototype.day; /** * @type {string} */ google.maps.weather.WeatherConditions.prototype.description; /** * @type {number} */ google.maps.weather.WeatherConditions.prototype.high; /** * @type {number} */ google.maps.weather.WeatherConditions.prototype.humidity; /** * @type {number} */ google.maps.weather.WeatherConditions.prototype.low; /** * @type {string} */ google.maps.weather.WeatherConditions.prototype.shortDay; /** * @type {number} */ google.maps.weather.WeatherConditions.prototype.temperature; /** * @type {string} */ google.maps.weather.WeatherConditions.prototype.windDirection; /** * @type {number} */ google.maps.weather.WeatherConditions.prototype.windSpeed; /** * @constructor */ google.maps.weather.WeatherFeature = function() {}; /** * @type {google.maps.weather.WeatherConditions} */ google.maps.weather.WeatherFeature.prototype.current; /** * @type {Array.<google.maps.weather.WeatherForecast>} */ google.maps.weather.WeatherFeature.prototype.forecast; /** * @type {string} */ google.maps.weather.WeatherFeature.prototype.location; /** * @type {google.maps.weather.TemperatureUnit} */ google.maps.weather.WeatherFeature.prototype.temperatureUnit; /** * @type {google.maps.weather.WindSpeedUnit} */ google.maps.weather.WeatherFeature.prototype.windSpeedUnit; /** * @constructor */ google.maps.weather.WeatherForecast = function() {}; /** * @type {string} */ google.maps.weather.WeatherForecast.prototype.day; /** * @type {string} */ google.maps.weather.WeatherForecast.prototype.description; /** * @type {number} */ google.maps.weather.WeatherForecast.prototype.high; /** * @type {number} */ google.maps.weather.WeatherForecast.prototype.low; /** * @type {string} */ google.maps.weather.WeatherForecast.prototype.shortDay; /** * @param {(google.maps.weather.WeatherLayerOptions|Object.<string>)=} opt_opts * @extends {google.maps.MVCObject} * @constructor */ google.maps.weather.WeatherLayer = function(opt_opts) {}; /** * @nosideeffects * @return {google.maps.Map} */ google.maps.weather.WeatherLayer.prototype.getMap = function() {}; /** * @param {google.maps.Map} map * @return {undefined} */ google.maps.weather.WeatherLayer.prototype.setMap = function(map) {}; /** * @param {google.maps.weather.WeatherLayerOptions|Object.<string>} options * @return {undefined} */ google.maps.weather.WeatherLayer.prototype.setOptions = function(options) {}; /** * @constructor */ google.maps.weather.WeatherLayerOptions = function() {}; /** * @type {boolean} */ google.maps.weather.WeatherLayerOptions.prototype.clickable; /** * @type {google.maps.weather.LabelColor} */ google.maps.weather.WeatherLayerOptions.prototype.labelColor; /** * @type {google.maps.Map} */ google.maps.weather.WeatherLayerOptions.prototype.map; /** * @type {boolean} */ google.maps.weather.WeatherLayerOptions.prototype.suppressInfoWindows; /** * @type {google.maps.weather.TemperatureUnit} */ google.maps.weather.WeatherLayerOptions.prototype.temperatureUnits; /** * @type {google.maps.weather.WindSpeedUnit} */ google.maps.weather.WeatherLayerOptions.prototype.windSpeedUnits; /** * @constructor */ google.maps.weather.WeatherMouseEvent = function() {}; /** * @type {google.maps.weather.WeatherFeature} */ google.maps.weather.WeatherMouseEvent.prototype.featureDetails; /** * @type {string} */ google.maps.weather.WeatherMouseEvent.prototype.infoWindowHtml; /** * @type {google.maps.LatLng} */ google.maps.weather.WeatherMouseEvent.prototype.latLng; /** * @type {google.maps.Size} */ google.maps.weather.WeatherMouseEvent.prototype.pixelOffset; /** * @enum {number|string} */ google.maps.weather.WindSpeedUnit = { KILOMETERS_PER_HOUR: '', METERS_PER_SECOND: '', MILES_PER_HOUR: '' };
var assert = require('assert'); var Globals = require('../../lib/globals/expect.js'); var common = require('../../common.js'); var CommandQueue = common.require('core/queue.js'); module.exports = { 'test Queue' : { beforeEach: function (done) { CommandQueue.reset(); Globals.beforeEach.call(this, done); }, afterEach: function() { Globals.afterEach.call(this); }, 'Test commands queue' : function(done) { var client = this.client, urlCommand, endCommand; this.client.once('nightwatch:finished', function() { assert.equal(urlCommand.done, true); assert.equal(endCommand.children.length, 0); assert.equal(endCommand.done, true); assert.equal(CommandQueue.list().length, 0); done(); }); client.api.url('http://localhost').end(); assert.equal(CommandQueue.list().length, 2); urlCommand = CommandQueue.instance().rootNode.children[0]; endCommand = CommandQueue.instance().rootNode.children[1]; assert.equal(endCommand.done, false); assert.equal(urlCommand.done, false); assert.equal(endCommand.started, false); this.client.start(); assert.equal(urlCommand.started, true); } } };
$(function() { $widget = $('#calendar-widget') if ($widget.length) { $.get('/events/calendar.json', function(data){ $widget.fullCalendar({ editable: false, header: { left: 'title', firstDay: 1, center: '', aspectRatio: 1, right: 'today prev,next' }, events: data }); }); } });
import map from './map'; export default map;
/** * @author Richard Davey <rich@photonstorm.com> * @author Mat Groves (@Doormat23) * @copyright 2016 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * New version of PIXI.ComplexPrimitiveShader * * @class Phaser.Renderer.Canvas * @constructor * @param {Phaser.Game} game - Game reference to the currently running game. */ Phaser.Renderer.WebGL.Shaders.ComplexPrimitiveGraphics = function (renderer) { this.renderer = renderer; // WebGLContext this.gl = renderer.gl; /** * @property _UID * @type Number * @private */ this._UID = renderer.getShaderID(this); /** * The WebGL program. * @property program * @type Any */ this.program = null; /** * The vertex shader. * @property vertexSrc * @type Array */ this.fragmentSrc = []; this.vertexSrc = []; this.attributes = []; // @type {WebGLUniformLocation } this.projectionVector; // @type {WebGLUniformLocation } this.offsetVector; // @type {WebGLUniformLocation } this.tintColor; // @type {WebGLUniformLocation } this.color; // @type {WebGLUniformLocation } this.flipY; // @type {GLint} this.aVertexPosition; // @type {GLint} this.colorAttribute; // @type {WebGLUniformLocation } this.translationMatrix; // @type {WebGLUniformLocation } this.alpha; this.init(); }; Phaser.Renderer.WebGL.Shaders.ComplexPrimitiveGraphics.prototype.constructor = Phaser.Renderer.WebGL.Shaders.ComplexPrimitiveGraphics; Phaser.Renderer.WebGL.Shaders.ComplexPrimitiveGraphics.prototype = { init: function () { this.fragmentSrc = [ 'precision mediump float;', 'varying vec4 vColor;', 'void main(void) {', ' gl_FragColor = vColor;', '}' ]; this.vertexSrc = [ 'attribute vec2 aVertexPosition;', 'uniform mat3 translationMatrix;', 'uniform vec2 projectionVector;', 'uniform vec2 offsetVector;', 'uniform vec3 tint;', 'uniform float alpha;', 'uniform vec3 color;', 'uniform float flipY;', 'varying vec4 vColor;', 'void main(void) {', ' vec3 v = translationMatrix * vec3(aVertexPosition , 1.0);', ' v -= offsetVector.xyx;', ' gl_Position = vec4( v.x / projectionVector.x -1.0, (v.y / projectionVector.y * -flipY) + flipY , 0.0, 1.0);', ' vColor = vec4(color * alpha * tint, alpha);', '}' ]; var program = this.renderer.compileProgram(this.vertexSrc, this.fragmentSrc); var gl = this.gl; gl.useProgram(program); // get and store the uniforms for the shader this.projectionVector = gl.getUniformLocation(program, 'projectionVector'); this.offsetVector = gl.getUniformLocation(program, 'offsetVector'); this.tintColor = gl.getUniformLocation(program, 'tint'); this.flipY = gl.getUniformLocation(program, 'flipY'); this.color = gl.getUniformLocation(program, 'color'); // get and store the attributes this.aVertexPosition = gl.getAttribLocation(program, 'aVertexPosition'); this.colorAttribute = gl.getAttribLocation(program, 'aColor'); // this.attributes = [ this.aVertexPosition, this.colorAttribute ]; this.attributes = [ this.aVertexPosition ]; this.translationMatrix = gl.getUniformLocation(program, 'translationMatrix'); this.alpha = gl.getUniformLocation(program, 'alpha'); this.program = program; }, destroy: function () { this.gl.deleteProgram(this.program); this.gl = null; this.renderer = null; this.attributes = null; } };
/** * A promise-based Q-JSGI server and client API. * @module */ /*whatsupdoc*/ var HTTP = require("http"); // node var HTTPS = require("https"); // node var URL = require("url2"); // node var Q = require("q"); var Reader = require("./reader"); /** * @param {respond(request Request)} respond a JSGI responder function that * receives a Request object as its argument. The JSGI responder promises to * return an object of the form `{status, headers, body}`. The status and * headers must be fully resolved, but the body may be a promise for an object * with a `forEach(write(chunk String))` method, albeit an array of strings. * The `forEach` method may promise to resolve when all chunks have been * written. * @returns a Node Server object. */ exports.Server = function (respond) { var self = Object.create(exports.Server.prototype); var server = HTTP.createServer(function (_request, _response) { var request = exports.ServerRequest(_request); var response = exports.ServerResponse(_response); var closed = Q.defer(); _request.on("end", function (error, value) { if (error) { closed.reject(error); } else { closed.resolve(value); } }); Q.when(request, function (request) { return Q.when(respond(request, response), function (response) { if (!response) return; _response.writeHead(response.status, response.headers); if (response.onclose || response.onClose) Q.when(closed, response.onclose || response.onClose); return Q.when(response.body, function (body) { var length; if ( Array.isArray(body) && (length = body.length) && body.every(function (chunk) { return typeof chunk === "string" }) ) { body.forEach(function (chunk, i) { if (i < length - 1) { _response.write(chunk, response.charset); } else { _response.end(chunk, response.charset); } }); } else if (body) { var end; var done = body.forEach(function (chunk) { end = Q.when(end, function () { return Q.when(chunk, function (chunk) { _response.write(chunk, response.charset); }); }); }); return Q.when(done, function () { return Q.when(end, function () { _response.end(); }); }); } else { _response.end(); } }); }) }) .done(); // should be .fail(self.emitter("error")) }); var stopped = Q.defer(); server.on("close", function (err) { if (err) { stopped.reject(err); } else { stopped.resolve(); } }); /*** * Stops the server. * @returns {Promise * Undefined} a promise that will * resolve when the server is stopped. */ self.stop = function () { server.close(); listening = undefined; return stopped.promise; }; var listening = Q.defer(); server.on("listening", function (err) { if (err) { listening.reject(err); } else { listening.resolve(self); } }); /*** * Starts the server, listening on the given port * @param {Number} port * @returns {Promise * Undefined} a promise that will * resolve when the server is ready to receive * connections */ self.listen = function (/*...args*/) { if (typeof server.port !== "undefined") return Q.reject(new Error("A server cannot be restarted or " + "started on a new port")); server.listen.apply(server, arguments); return listening.promise; }; self.stopped = stopped.promise; self.node = server; self.nodeServer = server; // Deprecated self.address = server.address.bind(server); return self; }; Object.defineProperties(exports.Server, { port: { get: function () { return this.node.port; } }, host: { get: function () { return this.node.host; } } }); /** * A wrapper for a Node HTTP Request, as received by * the Q HTTP Server, suitable for use by the Q HTTP Client. */ exports.ServerRequest = function (_request, ssl) { var request = Object.create(_request); /*** {Array} HTTP version. (JSGI) */ request.version = _request.httpVersion.split(".").map(Math.floor); /*** {String} HTTP method, e.g., `"GET"` (JSGI) */ request.method = _request.method; /*** {String} path, starting with `"/"` */ request.path = _request.url; /*** {String} pathInfo, starting with `"/"`, the * portion of the path that has not yet * been routed (JSGI) */ request.pathInfo = URL.parse(_request.url).pathname; /*** {String} scriptName, the portion of the path that * has already been routed (JSGI) */ request.scriptName = ""; /*** {String} (JSGI) */ request.scheme = "http"; var address = _request.connection.address(); /*** {String} hostname */ if (_request.headers.host) { request.hostname = _request.headers.host.split(":")[0]; } else { request.hostname = address.address; } /*** {String} host */ request.host = request.hostname + ":" + address.port; request.port = address.port; var socket = _request.socket; /*** {String} */ request.remoteHost = socket.remoteAddress; /*** {Number} */ request.remotePort = socket.remotePort; /*** {String} url */ request.url = URL.format({ protocol: request.scheme, host: _request.headers.host, port: request.port === (ssl ? 443 : 80) ? null : request.port, path: request.path }); /*** A Q IO asynchronous text reader */ request.body = Reader(_request); /*** {Object} HTTP headers (JSGI)*/ request.headers = _request.headers; /*** The underlying Node request */ request.node = _request; request.nodeRequest = _request; // Deprecated /*** The underlying Node TCP connection */ request.nodeConnection = _request.connection; return Q.when(request.body, function (body) { request.body = body; return request; }); }; exports.ServerResponse = function (_response, ssl) { var response = Object.create(_response); response.ssl = ssl; response.node = _response; response.nodeResponse = _response; // Deprecated return response; }; exports.normalizeRequest = function (request) { if (typeof request === "string") { request = { url: request }; } if (request.url) { var url = URL.parse(request.url); request.host = url.hostname; request.port = url.port; request.ssl = url.protocol === "https:"; request.method = request.method || "GET"; request.path = (url.pathname || "") + (url.search || ""); request.headers = request.headers || {}; request.headers.host = url.hostname; // FIXME name consistency } return request; }; exports.normalizeResponse = function (response) { if (response === void 0) { return; } if (typeof response == "string") { response = [response]; } if (response.forEach) { response = { status: 200, headers: {}, body: response } } return response; }; /** * Issues an HTTP request. * * @param {Request {host, port, method, path, headers, * body}} request (may be a promise) * @returns {Promise * Response} promise for a response */ exports.request = function (request) { return Q.when(request, function (request) { request = exports.normalizeRequest(request); var deferred = Q.defer(); var ssl = request.ssl; var http = ssl ? HTTPS : HTTP; var headers = request.headers || {}; headers.host = headers.host || request.host; var _request = http.request({ "host": request.host, "port": request.port || (ssl ? 443 : 80), "path": request.path || "/", "method": request.method || "GET", "headers": headers, "agent": request.agent }, function (_response) { deferred.resolve(exports.ClientResponse(_response, request.charset)); _response.on("error", function (error) { // TODO find a better way to channel // this into the response console.warn(error && error.stack || error); deferred.reject(error); }); }); _request.on("error", function (error) { deferred.reject(error); }); Q.when(request.body, function (body) { var end, done; if (body) { done = body.forEach(function (chunk) { end = Q.when(end, function () { return Q.when(chunk, function (chunk) { _request.write(chunk, request.charset); }); }); }); } return Q.when(end, function () { return Q.when(done, function () { _request.end(); }); }); }).done(); return deferred.promise; }); }; /** * Issues a GET request to the given URL and returns * a promise for a `String` containing the entirety * of the response. * * @param {String} url * @returns {Promise * String} or a rejection if the * status code is not exactly 200. The reason for the * rejection is the full response object. */ exports.read = function (request, qualifier) { qualifier = qualifier || function (response) { return response.status === 200; }; return Q.when(exports.request(request), function (response) { if (!qualifier(response)){ var error = new Error("HTTP request failed with code " + response.status); error.response = response; throw error; } return Q.post(response.body, 'read', []); }); }; /** * A wrapper for the Node HTTP Response as provided * by the Q HTTP Client API, suitable for use by the * Q HTTP Server API. */ exports.ClientResponse = function (_response, charset) { var response = Object.create(exports.ClientResponse.prototype); /*** {Number} HTTP status code */ response.status = _response.statusCode; /*** HTTP version */ response.version = _response.httpVersion; /*** {Object} HTTP headers */ response.headers = _response.headers; /*** * A Q IO asynchronous text reader. */ response.node = _response; response.nodeResponse = _response; // Deprecated response.nodeConnection = _response.connection; // Deprecated return Q.when(Reader(_response, charset), function (body) { response.body = body; return response; }); };
/** * Determines whether any element of an observable sequence satisfies a condition if present, else if any items are in the sequence. * @param {Function} [predicate] A function to test each element for a condition. * @returns {Observable} An observable sequence containing a single element determining whether any elements in the source sequence pass the test in the specified predicate if given, else if any items are in the sequence. */ observableProto.some = function (predicate, thisArg) { var source = this; return predicate ? source.filter(predicate, thisArg).some() : new AnonymousObservable(function (observer) { return source.subscribe(function () { observer.onNext(true); observer.onCompleted(); }, observer.onError.bind(observer), function () { observer.onNext(false); observer.onCompleted(); }); }, source); }; /** @deprecated use #some instead */ observableProto.any = function () { //deprecate('any', 'some'); return this.some.apply(this, arguments); };
/** * The position and size of the Bitmap Text in global space, taking into account the Game Object's scale and world position. * * @typedef {object} Phaser.Types.GameObjects.BitmapText.GlobalBitmapTextSize * @since 3.0.0 * * @property {number} x - The x position of the BitmapText, taking into account the x position and scale of the Game Object. * @property {number} y - The y position of the BitmapText, taking into account the y position and scale of the Game Object. * @property {number} width - The width of the BitmapText, taking into account the x scale of the Game Object. * @property {number} height - The height of the BitmapText, taking into account the y scale of the Game Object. */
version https://git-lfs.github.com/spec/v1 oid sha256:0e7889c818b4129a08bc3843ba39b2e1118e6cfd3f186b1abf15037cd5599dd6 size 547
var traceur = require('traceur'); var traceurGet = require('../lib/utils').traceurGet; var ParseTreeTransformer = traceurGet('codegeneration/ParseTreeTransformer.js').ParseTreeTransformer; var ModuleSpecifier = traceurGet('syntax/trees/ParseTrees.js').ModuleSpecifier; var createStringLiteralToken = traceurGet('codegeneration/ParseTreeFactory.js').createStringLiteralToken; var InstantiateModuleTransformer = traceurGet('codegeneration/InstantiateModuleTransformer.js').InstantiateModuleTransformer; var extend = require('../lib/utils').extend; // patch pending https://github.com/google/traceur-compiler/pull/2053 var createUseStrictDirective = traceurGet('codegeneration/ParseTreeFactory.js').createUseStrictDirective; InstantiateModuleTransformer.prototype.__proto__.moduleProlog = function() { return [createUseStrictDirective()]; }; var CollectingErrorReporter = traceurGet('util/CollectingErrorReporter.js').CollectingErrorReporter; var UniqueIdentifierGenerator = traceurGet('codegeneration/UniqueIdentifierGenerator.js').UniqueIdentifierGenerator; function TraceurImportNormalizeTransformer(map) { this.map = map; return ParseTreeTransformer.apply(this, arguments); } TraceurImportNormalizeTransformer.prototype = Object.create(ParseTreeTransformer.prototype); TraceurImportNormalizeTransformer.prototype.transformModuleSpecifier = function(tree) { var depName = this.map(tree.token.processedValue) || tree.token.processedValue; return new ModuleSpecifier(tree.location, createStringLiteralToken(depName)); }; exports.TraceurImportNormalizeTransformer = TraceurImportNormalizeTransformer; function remap(source, map, fileName) { var compiler = new traceur.Compiler(); var tree = compiler.parse(source, fileName); tree = new TraceurImportNormalizeTransformer(map).transformAny(tree); return Promise.resolve({ source: compiler.write(tree) }); } exports.remap = remap; // override System instantiate to handle esm tracing exports.attach = function(loader) { var systemInstantiate = loader.instantiate; loader.instantiate = function(load) { // skip plugin loader attachment || non es modules || es modules handled by internal transpilation layer if (!loader.builder || load.metadata.format != 'esm' || load.metadata.originalSource) return systemInstantiate.call(this, load); var depsList = load.metadata.deps.concat([]); var babel = require('babel-core'); var output = babel.transform(load.source, { babelrc: false, compact: false, filename: load.path, //sourceFileName: load.path, inputSourceMap: load.metadata.sourceMap, ast: true, resolveModuleSource: function(dep) { if (depsList.indexOf(dep) == -1) depsList.push(dep); return dep; } }); // turn back on comments (for some reason!) output.ast.comments.forEach(function(comment) { comment.ignore = false; }); load.metadata.ast = output.ast; return Promise.resolve({ deps: depsList, execute: null }); }; }; var versionCheck = true; exports.compile = function(load, opts, loader) { if (!load.metadata.originalSource || load.metadata.loader && load.metadata.format == 'esm') { var babel = require('babel-core'); var babelOptions = { babelrc: false, compact: false, plugins: [[require('babel-plugin-transform-es2015-modules-systemjs'), { systemGlobal: opts.systemGlobal }]], filename: load.path, //sourceFileName: load.path, sourceMaps: opts.sourceMaps, inputSourceMap: load.metadata.sourceMap, moduleIds: !opts.anonymous, moduleId: !opts.anonymous && load.name, code: true, resolveModuleSource: function(dep) { if (opts.normalize) return load.depMap[dep]; else return dep; } }; var source = load.metadata.originalSource || load.source; var output; if (load.metadata.ast) output = babel.transformFromAst(load.metadata.ast, source, babelOptions); else output = babel.transform(source, babelOptions); // NB this can be removed with merging of () if (opts.systemGlobal != 'System') output.code = output.code.replace(/(\s|^)System\.register\(/, '$1' + opts.systemGlobal + '.register('); // for some reason Babel isn't respecting sourceFileName... if (output.map && !load.metadata.sourceMap) output.map.sources[0] = load.path; return Promise.resolve({ source: output.code, sourceMap: output.map }); } // ... legacy transpilation, to be deprecated with internal transpilation layer return Promise.resolve(global[loader.transpiler == 'typescript' ? 'ts' : loader.transpiler] || loader.pluginLoader.import(loader.transpiler)) .then(function(transpiler) { if (transpiler.__useDefault) transpiler = transpiler['default']; if (transpiler.Compiler) { var options = loader.traceurOptions || {}; options.modules = 'instantiate'; options.script = false; options.sourceRoot = true; options.moduleName = !opts.anonymous; if (opts.sourceMaps) options.sourceMaps = 'memory'; if (opts.lowResSourceMaps) options.lowResolutionSourceMap = true; if (load.metadata.sourceMap) options.inputSourceMap = load.metadata.sourceMap; var compiler = new transpiler.Compiler(options); var tree = compiler.parse(load.source, load.path); var transformer = new TraceurImportNormalizeTransformer(function(dep) { return opts.normalize ? load.depMap[dep] : dep; }); tree = transformer.transformAny(tree); tree = compiler.transform(tree, load.name); var outputSource = compiler.write(tree, load.path); if (outputSource.match(/\$traceurRuntime/)) load.metadata.usesTraceurRuntimeGlobal = true; return Promise.resolve({ source: outputSource, sourceMap: compiler.getSourceMap() }); } else if (transpiler.createLanguageService) { var options = loader.typescriptOptions || {}; if (options.target === undefined) options.target = transpiler.ScriptTarget.ES5; options.module = transpiler.ModuleKind.System; var transpileOptions = { compilerOptions: options, renamedDependencies: load.depMap, fileName: load.path, moduleName: !opts.anonymous && load.name }; var transpiled = transpiler.transpileModule(load.source, transpileOptions); return Promise.resolve({ source: transpiled.outputText, sourceMap: transpiled.sourceMapText }); } else { if (versionCheck) { var babelVersion = transpiler.version; if (babelVersion.split('.')[0] > 5) console.log('Warning - using Babel ' + babelVersion + '. This version of SystemJS builder is designed to run against Babel 5.'); versionCheck = false; } var options = extend({}, loader.babelOptions || {}); options.modules = 'system'; if (opts.sourceMaps) options.sourceMap = true; if (load.metadata.sourceMap) options.inputSourceMap = load.metadata.sourceMap; options.filename = load.path; options.filenameRelative = load.name; options.sourceFileName = load.path; options.keepModuleIdExtensions = true; options.code = true; options.ast = false; options.moduleIds = !opts.anonymous; options.externalHelpers = true; if (transpiler.version.match(/^4/)) options.returnUsedHelpers = true; else if (transpiler.version.match(/^5\.[01234]\./)) options.metadataUsedHelpers = true; if (opts.normalize) options.resolveModuleSource = function(dep) { return load.depMap[dep] || dep; }; var output = transpiler.transform(load.source, options); var usedHelpers = output.usedHelpers || output.metadata && output.metadata.usedHelpers; if ((!options.optional || options.optional.indexOf('runtime') == -1) && usedHelpers.length) load.metadata.usesBabelHelpersGlobal = true; // pending Babel v5, we need to manually map the helpers if (options.optional && options.optional.indexOf('runtime') != -1) load.deps.forEach(function(dep) { if (dep.match(/^babel-runtime/)) output.code = output.code.replace(dep, load.depMap[dep]); }); // clear options for reuse delete options.filenameRelative; delete options.sourceFileName; return Promise.resolve({ source: output.code, sourceMap: output.map }); } }) .then(function(output) { if (opts.systemGlobal != 'System') output.source = output.source.replace(/System\.register\(/, opts.systemGlobal + '.register('); return output; }); };
import { defineProperty, deprecateProperty } from '..'; import { moduleFor, AbstractTestCase } from 'internal-test-helpers'; moduleFor( 'defineProperty', class extends AbstractTestCase { ['@test toString'](assert) { let obj = {}; defineProperty(obj, 'toString', undefined, function () { return 'FOO'; }); assert.equal(obj.toString(), 'FOO', 'should replace toString'); } } ); moduleFor( 'Ember.deprecateProperty', class extends AbstractTestCase { ['@test enables access to deprecated property and returns the value of the new property']( assert ) { assert.expect(3); let obj = { foo: 'bar' }; deprecateProperty(obj, 'baz', 'foo', { id: 'baz-deprecation', until: 'some.version' }); expectDeprecation(); assert.equal(obj.baz, obj.foo, 'baz and foo are equal'); obj.foo = 'blammo'; assert.equal(obj.baz, obj.foo, 'baz and foo are equal'); } ['@test deprecatedKey is not enumerable'](assert) { assert.expect(2); let obj = { foo: 'bar', blammo: 'whammy' }; deprecateProperty(obj, 'baz', 'foo', { id: 'baz-deprecation', until: 'some.version' }); for (let prop in obj) { if (Object.prototype.hasOwnProperty.call(obj, prop)) { assert.notEqual(prop, 'baz'); } } } ['@test enables setter to deprecated property and updates the value of the new property']( assert ) { assert.expect(3); let obj = { foo: 'bar' }; deprecateProperty(obj, 'baz', 'foo', { id: 'baz-deprecation', until: 'some.version' }); expectDeprecation(); obj.baz = 'bloop'; assert.equal(obj.foo, 'bloop', 'updating baz updates foo'); assert.equal(obj.baz, obj.foo, 'baz and foo are equal'); } } );
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ 'use strict'; const models = require('./index'); /** * Describes a virtual machine scale set extension profile. * */ class VirtualMachineScaleSetExtensionProfile { /** * Create a VirtualMachineScaleSetExtensionProfile. * @member {array} [extensions] The virtual machine scale set child extension * resources. */ constructor() { } /** * Defines the metadata of VirtualMachineScaleSetExtensionProfile * * @returns {object} metadata of VirtualMachineScaleSetExtensionProfile * */ mapper() { return { required: false, serializedName: 'VirtualMachineScaleSetExtensionProfile', type: { name: 'Composite', className: 'VirtualMachineScaleSetExtensionProfile', modelProperties: { extensions: { required: false, serializedName: 'extensions', type: { name: 'Sequence', element: { required: false, serializedName: 'VirtualMachineScaleSetExtensionElementType', type: { name: 'Composite', className: 'VirtualMachineScaleSetExtension' } } } } } } }; } } module.exports = VirtualMachineScaleSetExtensionProfile;
// Copyright 2014 the V8 project authors. All rights reserved. // AUTO-GENERATED BY tools/generate-runtime-tests.py, DO NOT MODIFY // Flags: --allow-natives-syntax --harmony --harmony-proxies var _source = "foo"; var arg1 = false; %CompileString(_source, arg1);