diff --git a/docs/api/printer.rst b/docs/api/printer.rst index 5d7c8ebde..98f4ccbff 100644 --- a/docs/api/printer.rst +++ b/docs/api/printer.rst @@ -229,7 +229,7 @@ Issue a print head command feedrate Changes the feedrate factor to apply to the movements of the axes. - * ``factor``: The new factor, percentage as integer or float (percentage divided by 100) between 50 and 200%. + * ``factor``: The new factor, percentage between 50 and 200% as integer (``50`` to ``200``) or float (``0.5`` to ``2.0``). All of these commands except ``feedrate`` may only be sent if the printer is currently operational and not printing. Otherwise a :http:statuscode:`409` is returned. @@ -280,9 +280,9 @@ Issue a print head command HTTP/1.1 204 No Content - **Example feed rate request** + **Example feed rate request (1/2)** - Set the feed rate factor to 105%. + Set the feed rate factor to 105% using an integer argument. .. sourcecode:: http @@ -300,6 +300,26 @@ Issue a print head command HTTP/1.1 204 No Content + **Example feed rate request (2/2)** + + Set the feed rate factor to 105% using a float argument. + + .. sourcecode:: http + + POST /api/printer/printhead HTTP/1.1 + Host: example.com + Content-Type: application/json + X-Api-Key: abcdef... + + { + "command": "feedrate", + "factor": 1.05 + } + + .. sourcecode:: http + + HTTP/1.1 204 No Content + :json string command: The command to issue, either ``jog`` or ``home``. :json number x: ``jog`` command: The amount to travel on the X axis in mm. :json number y: ``jog`` command: The amount to travel on the Y axis in mm. @@ -346,7 +366,7 @@ Issue a tool command flowrate Changes the flow rate factor to apply to extrusion of the tool. - * ``factor``: The new factor, percentage as integer or float (percentage divided by 100) between 75 and 125%. + * ``factor``: The new factor, percentage between 75 and 125% as integer (``75`` to ``125``) or float (``0.75`` to ``1.25``). All of these commands may only be sent if the printer is currently operational and -- in case of ``select`` and ``extrude`` -- not printing. Otherwise a :http:statuscode:`409` is returned. @@ -461,9 +481,9 @@ Issue a tool command HTTP/1.1 204 No Content - **Example flow rate request** + **Example flow rate request (1/2)** - Set the flow rate factor to 95%. + Set the flow rate factor to 95% using an integer attribute. .. sourcecode:: http @@ -481,6 +501,26 @@ Issue a tool command HTTP/1.1 204 No Content + **Example flow rate request (2/2)** + + Set the flow rate factor to 95% using a float attribute. + + .. sourcecode:: http + + POST /api/printer/tool HTTP/1.1 + Host: example.com + Content-Type: application/json + X-Api-Key: abcdef... + + { + "command": "flowrate", + "factor": 0.95 + } + + .. sourcecode:: http + + HTTP/1.1 204 No Content + :json string command: The command to issue, either ``target``, ``offset``, ``select`` or ``extrude``. :json object targets: ``target`` command: The target temperatures to set. Valid properties have to match the format ``tool{n}``. :json object offsets: ``offset`` command: The offset temperature to set. Valid properties have to match the format ``tool{n}``. diff --git a/docs/bundledplugins/action_command_prompt.rst b/docs/bundledplugins/action_command_prompt.rst new file mode 100644 index 000000000..2d972cac4 --- /dev/null +++ b/docs/bundledplugins/action_command_prompt.rst @@ -0,0 +1,110 @@ +.. _sec-bundledplugins-action_command_prompt: + +Action Command Prompt support +============================= + +The OctoPrint Action Command Prompt Support Plugin comes bundled with OctoPrint (starting with 1.3.9). + +It allows firmware to trigger dialog prompts for logged in users using :ref:`action commands `, e.g. to wait +for user acknowledgement or allow the user to choose between options, and also to close the dialog again +in case its no longer needed, e.g. due to the user proceeding on the printer's own controller. + +The choice of the user can be communicated back to the firmware via a configurable GCODE command with a +placeholder for the selected option's index. + +.. _fig-bundledplugins-action_command_prompt-example: +.. figure:: ../images/bundledplugins-action_command_prompt-example.png + :align: center + :alt: Simple prompt example + + A simple dialog example triggered by the firmware + +.. _sec-bundledplugins-action_command_prompt-firststeps: + +First Steps +----------- + +In order for this plugin to work, you'll need to configure it with the command your firmware uses to accept +dialog selections. You can do that in the settings dialog. + +Currently there is no agreed upon command for this since no firmware has yet made use of this feature, so OctoPrint +ships with an empty value here. + +.. _sec-bundledplugins-action_command_prompt-configuration: + +Configuring the plugin +---------------------- + +The plugin supports the following configuration keys: + + * ``selection_command``: The command to send to the firmware on choice, including the ``{choice}`` placeholder, e.g. ``M876 S{choice}``. + +You can modify them either through the plugin's configuration dialog under Settings, or by directly editing ``config.yaml``. + +.. _sec-bundledplugins-action_command_prompt-action_commands: + +Supported action commands +------------------------- + +prompt_begin + Starts the definition of a prompt dialog. ```` is the message to display to the user. Will be ignored + if a dialog is already defined. + +prompt_choice + Defines a choice with the associated ````. Will be ignored if no dialog has been defined yet. + +prompt_button + Same as ``prompt_choice``. + +prompt_show + Tells OctoPrint that the dialog is now fully defined and to prompt the user. Will be ignored if no dialog is + defined yet. + +prompt_end + Tells OctoPrint that the dialog should now be closed (e.g. the user made the choice on the printer directly instead + of through OctoPrint). Will be ignored if no dialog is defined yet. + +.. _sec-bundledplugins-action_command_prompt-example: + +Example communication with the firmware +--------------------------------------- + +.. _sec-bundledplugins-action_command_prompt-sourcecode: + +To display the :ref:`above dialog ` the firmware sent these action commands: + +.. code-block:: none + + //action:prompt_begin Filament unloaded, swap then proceed + //action:prompt_choice Filament swapped + //action:prompt_show + +If the user clicks the button, assuming a ``selection_command`` of ``M876 S{choice}`` is configured, OctoPrint +will send back ``M876 S0`` (0-based index). + +A more complicated example with three options would be the following: + +.. code-block:: none + + //action:prompt_begin Filament runout detected. Please choose how to proceed: + //action:prompt_choice Swap filament + //action:prompt_choice Home X/Y and pause print + //action:prompt_choice Abort print + //action:prompt_show + +This would produce the following output: + +.. _fig-bundledplugins-action_command_prompt-example2: +.. figure:: ../images/bundledplugins-action_command_prompt-example2.png + :align: center + :alt: Another prompt example + + Another dialog example triggered by the firmware + +If the user selects "Abort print", OctoPrint will send ``2`` as selected choice. + +Source code +----------- + +The source of the Action Command Prompt Support plugin is bundled with OctoPrint and can be found in +its source repository under ``src/octoprint/plugins/action_command_prompt``. diff --git a/docs/bundledplugins/index.rst b/docs/bundledplugins/index.rst index bd862b005..26a520699 100644 --- a/docs/bundledplugins/index.rst +++ b/docs/bundledplugins/index.rst @@ -7,6 +7,7 @@ Bundled Plugins .. toctree:: :maxdepth: 2 + action_command_prompt.rst cura.rst discovery.rst logging.rst diff --git a/docs/features/action_commands.rst b/docs/features/action_commands.rst index 502f068b8..7fcf6063e 100644 --- a/docs/features/action_commands.rst +++ b/docs/features/action_commands.rst @@ -29,12 +29,27 @@ pause When this command is received from the printer, OctoPrint will pause a current print job just like if the "Pause" button had been clicked. +paused + When this command is received from the printer, OctoPrint will pause a current print job but *without* triggering + any GCODE scripts or sending SD print control commands to the printer. This might be interesting for firmware + that wants to signal to OctoPrint that a print should be paused but without any control interference from + OctoPrint, e.g. in case of a filament change fully managed by the firmware. + resume When this command is received from the printer, OctoPrint will resume a current print job just like if the "Resume" button had been clicked. +resumed + When this command is received from the printer, OctoPrint will resume a current print job but *without* triggering + any GCODE scripts or sending SD print control commands to the printer. This might be interesting for firmware + that wants to signal to OctoPrint that a print should be resumed but without any control interference from + OctoPrint, e.g. in case of a filament change fully managed by the firmware. + disconnect When this command is received from the printer, OctoPrint will immediately disconnect from it. +If the bundled :ref:`Action Command Prompt Support Plugin ` is enabled (which +should be the case by default), OctoPrint will also interactive dialog creation through its :ref:`supported commands `. + Support for additional commands may be added by plugins by implementing a handler for the :ref:`octoprint.comm.protocol.action ` hook. diff --git a/docs/images/bundledplugins-action_command_prompt-example.png b/docs/images/bundledplugins-action_command_prompt-example.png new file mode 100644 index 000000000..cd8d719f1 Binary files /dev/null and b/docs/images/bundledplugins-action_command_prompt-example.png differ diff --git a/docs/images/bundledplugins-action_command_prompt-example2.png b/docs/images/bundledplugins-action_command_prompt-example2.png new file mode 100644 index 000000000..bdc6d2e28 Binary files /dev/null and b/docs/images/bundledplugins-action_command_prompt-example2.png differ diff --git a/docs/plugins/hooks.rst b/docs/plugins/hooks.rst index a0524d6ea..5f86a2c7c 100644 --- a/docs/plugins/hooks.rst +++ b/docs/plugins/hooks.rst @@ -380,6 +380,52 @@ octoprint.cli.commands OctoPrint's CLI. :rtype: list +.. _sec-plugins-hook-comm-firmware-info: + +octoprint.comm.firmware.info +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. py:function:: firmware_info_hook(comm_instance, firmware_name, firmware_data, *args, **kwargs) + + Be notified of firmware information received from the printer following an ``M115``. + + Hook handlers may use this to react/adjust behaviour based on reported firmware data. OctoPrint parses the received + report line and provides the parsed ``firmware_name`` and additional ``firmware_data`` contained therein. A + response line ``FIRMWARE_NAME:Some Firmware Name FIRMWARE_VERSION:1.2.3 PROTOCOL_VERSION:1.0`` for example will + be turned into a ``dict`` looking like this: + + .. code-block:: python + + dict(FIRMWARE_NAME="Some Firmware Name", + FIRMWARE_VERSION="1.2.3", + PROTOCOL_VERSION="1.0") + + ``firmware_name`` will be ``Some Firmware Name`` in this case. + + :param object comm_instance: The :class:`~octoprint.util.comm.MachineCom` instance which triggered the hook. + :param str firmware_name: The name of the parsed capability + :param dict firmware_data: All data contained in the ``M115`` report + +.. _sec-plugins-hook-comm-firmware-capabilities: + +octoprint.comm.firmware.capabilities +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. py:function:: firmware_capability_hook(comm_instance, capability, enabled, already_defined, *args, **kwargs) + + Be notified of capability report entries received from the printer. + + Hook handlers may use this to react to custom firmware capabilities. OctoPrint parses the received capability + line and provides the parsed ``capability`` and whether it's ``enabled`` to the handler. Additionally all already + parsed capabilities will also be provided. + + Note that hook handlers will be called once per received capability line. + + :param object comm_instance: The :class:`~octoprint.util.comm.MachineCom` instance which triggered the hook. + :param str capability: The name of the parsed capability + :param bool enabled: Whether the capability is reported as enabled or disabled + :param dict already_defined: Already defined capabilities (capability name mapped to enabled flag) + .. _sec-plugins-hook-comm-protocol-action: octoprint.comm.protocol.action @@ -389,7 +435,7 @@ octoprint.comm.protocol.action React to a :ref:`action command ` received from the printer. - Hook handlers may use this to react to react to custom firmware messages. OctoPrint parses the received action + Hook handlers may use this to react to custom firmware messages. OctoPrint parses the received action command ``line`` and provides the parsed ``action`` (so anything after ``// action:``) to the hook handler. No returned value is expected. diff --git a/setup.py b/setup.py index a46e920ac..f783049cb 100644 --- a/setup.py +++ b/setup.py @@ -38,8 +38,7 @@ INSTALL_REQUIRES = [ "pkginfo>=1.4.2,<1.5", "requests>=2.18.4,<3", "semantic_version>=2.6.0,<2.7", - "psutil==5.4.3", # 5.4.4 introduced a breaking change concerning installing under non current - # setuptools versions. Pinning to 5.4.3 for now to work around this. + "psutil>=5.4.5,<5.5", "Click>=6.7,<6.8", "awesome-slugify>=1.6.5,<1.7", "feedparser>=5.2.1,<5.3", diff --git a/src/octoprint/job/__init__.py b/src/octoprint/job/__init__.py index 7b414fac5..d3507e99f 100644 --- a/src/octoprint/job/__init__.py +++ b/src/octoprint/job/__init__.py @@ -400,10 +400,10 @@ class SDFilePrintjob(StoragePrintjob, FileAwareProtocolListener): class PrintjobListener(object): - def on_job_started(self, job): + def on_job_started(self, job, suppress_script=False): pass - def on_job_done(self, job): + def on_job_done(self, job, suppress_script=False): pass def on_job_failed(self, job): @@ -412,13 +412,13 @@ class PrintjobListener(object): def on_job_cancelling(self, job, firmware_error=None): pass - def on_job_cancelled(self, job, cancel_position=None): + def on_job_cancelled(self, job, cancel_position=None, suppress_script=False): pass - def on_job_paused(self, job, pause_position=None): + def on_job_paused(self, job, pause_position=None, suppress_script=False): pass - def on_job_resumed(self, job): + def on_job_resumed(self, job, suppress_script=False): pass def on_job_progress(self, job): diff --git a/src/octoprint/plugin/core.py b/src/octoprint/plugin/core.py index f91b3835d..8987a8228 100644 --- a/src/octoprint/plugin/core.py +++ b/src/octoprint/plugin/core.py @@ -630,30 +630,46 @@ class PluginManager(object): def plugin_hooks(self): return {key: map(lambda v: (v[1], v[2]), value) for key, value in self._plugin_hooks.items()} - def find_plugins(self, existing=None, ignore_uninstalled=True): + def find_plugins(self, existing=None, ignore_uninstalled=True, incl_all_found=False): + added, found = self._find_plugins(existing=existing, ignore_uninstalled=ignore_uninstalled) + if incl_all_found: + return added, found + else: + return added + + def _find_plugins(self, existing=None, ignore_uninstalled=True): if existing is None: existing = dict(self.plugins) - result = OrderedDict() + result_added = OrderedDict() + result_found = [] + if self.plugin_folders: try: - result.update(self._find_plugins_from_folders(self.plugin_folders, - existing, - ignored_uninstalled=ignore_uninstalled)) + added, found = self._find_plugins_from_folders(self.plugin_folders, + existing, + ignored_uninstalled=ignore_uninstalled) + result_added.update(added) + result_found += found except: self.logger.exception("Error fetching plugins from folders") + if self.plugin_entry_points: - existing.update(result) + existing.update(result_added) try: - result.update(self._find_plugins_from_entry_points(self.plugin_entry_points, - existing, - ignore_uninstalled=ignore_uninstalled)) + added, found = self._find_plugins_from_entry_points(self.plugin_entry_points, + existing, + ignore_uninstalled=ignore_uninstalled) + result_added.update(added) + result_found += found except: self.logger.exception("Error fetching plugins from entry points") - return result + + return result_added, result_found def _find_plugins_from_folders(self, folders, existing, ignored_uninstalled=True): - result = OrderedDict() + added = OrderedDict() + found = [] for folder in folders: try: @@ -691,7 +707,8 @@ class PluginManager(object): # whatever this is, we ignore it continue - if key in existing or key in result or (ignored_uninstalled and key in self.marked_plugins["uninstalled"]): + found.append(key) + if key in existing or key in added or (ignored_uninstalled and key in self.marked_plugins["uninstalled"]): # plugin is already defined, ignore it continue @@ -702,16 +719,17 @@ class PluginManager(object): plugin.origin = FolderOrigin("folder", folder) plugin.managable = not flagged_readonly and not actual_readonly plugin.enabled = False - result[key] = plugin + added[key] = plugin except: self.logger.exception("Error processing folder entry {!r} from folder {}".format(entry, folder)) except: self.logger.exception("Error processing folder {}".format(folder)) - return result + return added, found def _find_plugins_from_entry_points(self, groups, existing, ignore_uninstalled=True): - result = OrderedDict() + added = OrderedDict() + found = [] # let's make sure we have a current working set ... working_set = pkg_resources.WorkingSet() @@ -745,7 +763,8 @@ class PluginManager(object): module_name = entry_point.module_name version = entry_point.dist.version - if key in existing or key in result or (ignore_uninstalled and key in self.marked_plugins["uninstalled"]): + found.append(key) + if key in existing or key in added or (ignore_uninstalled and key in self.marked_plugins["uninstalled"]): # plugin is already defined or marked as uninstalled, ignore it continue @@ -782,11 +801,11 @@ class PluginManager(object): module_name, plugin.location)) - result[key] = plugin + added[key] = plugin except: self.logger.exception("Error processing entry point {!r} for group {}".format(entry_point, group)) - return result + return added, found def _import_plugin_from_module(self, key, folder=None, module_name=None, name=None, version=None, summary=None, author=None, url=None, license=None, bundled=False): @@ -869,11 +888,26 @@ class PluginManager(object): if force_reload is None: force_reload = [] - plugins = self.find_plugins(existing=dict((k, v) for k, v in self.plugins.items() if not k in force_reload)) - self.disabled_plugins.update(plugins) + added, found = self.find_plugins(existing=dict((k, v) for k, v in self.plugins.items() if not k in force_reload), + incl_all_found=True) + + # let's clean everything we DIDN'T find first + removed = [key for key in self.enabled_plugins.keys() + self.disabled_plugins.keys() if key not in found] + for key in removed: + try: + del self.enabled_plugins[key] + except KeyError: + pass + + try: + del self.disabled_plugins[key] + except KeyError: + pass + + self.disabled_plugins.update(added) # 1st pass: loading the plugins - for name, plugin in plugins.items(): + for name, plugin in added.items(): try: if not plugin.blacklisted and not plugin.forced_disabled: self.load_plugin(name, plugin, startup=startup, initialize_implementation=initialize_implementations) @@ -887,7 +921,7 @@ class PluginManager(object): force_reload=force_reload) # 2nd pass: enabling those plugins that need enabling - for name, plugin in plugins.items(): + for name, plugin in added.items(): try: if plugin.loaded and not plugin.forced_disabled: if plugin.blacklisted: diff --git a/src/octoprint/plugins/action_command_prompt/__init__.py b/src/octoprint/plugins/action_command_prompt/__init__.py new file mode 100644 index 000000000..0dd9a4be2 --- /dev/null +++ b/src/octoprint/plugins/action_command_prompt/__init__.py @@ -0,0 +1,166 @@ +# coding=utf-8 +from __future__ import absolute_import, division, print_function, unicode_literals + +__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License" + +import octoprint.plugin + +from octoprint.server import user_permission + +import flask +from flask_babel import gettext + +class Prompt(object): + + def __init__(self, text): + self.text = text + self.choices = [] + + self._active = False + + @property + def active(self): + return self._active + + def add_choice(self, text): + self.choices.append(text) + + def activate(self): + self._active = True + + def validate_choice(self, choice): + return 0 <= choice < len(self.choices) + + +class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin, + octoprint.plugin.SettingsPlugin, + octoprint.plugin.SimpleApiPlugin, + octoprint.plugin.TemplatePlugin): + + # noinspection PyMissingConstructor + def __init__(self): + self._prompt = None + self._selection_command = None + + def initialize(self): + self._selection_command = self._settings.get([b"selection_command"]) + + #~ AssetPlugin + + def get_assets(self): + return dict(js=["js/action_command_prompt.js"]) + + #~ SettingsPlugin + + def get_settings_defaults(self): + return dict(selection_command=None) + + def on_settings_save(self, data): + octoprint.plugin.SettingsPlugin.on_settings_save(self, data) + self._selection_command = self._settings.get([b"selection_command"]) + + #~ SimpleApiPlugin + + def get_api_commands(self): + return dict(select=["choice"]) + + def on_api_command(self, command, data): + if command == "select": + if not user_permission.can(): + return flask.abort(403, "Insufficient permissions") + + if self._prompt is None: + return flask.abort(409, "No active prompt") + + choice = data["choice"] + if not isinstance(choice, int) or not self._prompt.validate_choice(choice): + return flask.abort(400, "{!r} is not a valid value for choice".format(choice)) + + self._answer_prompt(choice) + + def on_api_get(self, request): + if not user_permission.can(): + return flask.abort(403, "Insufficient permissions") + if self._prompt is None: + return flask.jsonify() + else: + return flask.jsonify(text=self._prompt.text, choices=self._prompt.choices) + + #~ TemplatePlugin + + def get_template_configs(self): + return [dict(type="settings", name=gettext("Action Command Prompt"), custom_bindings=False)] + + #~ action command handler + + def action_command_handler(self, comm, line, action, *args, **kwargs): + if not action.startswith(b"prompt_"): + return + + if self._selection_command is None: + self._logger.info("Got a prompt command from the printer but no selection command is defined") + return + + parts = action.split(None, 1) + if len(parts) == 1: + action = parts[0] + parameter = b"" + else: + action, parameter = parts + + if action == b"prompt_begin": + if self._prompt is not None and self._prompt.active: + self._logger.warn("Prompt is already defined") + return + self._prompt = Prompt(parameter.strip()) + + elif action == b"prompt_choice" or action == b"prompt_button": + if self._prompt is None: + return + if self._prompt.active: + self._logger.warn("Prompt is already active") + return + self._prompt.add_choice(parameter.strip()) + + elif action == b"prompt_show": + if self._prompt is None: + return + if self._prompt.active: + self._logger.warn("Prompt is already active") + return + self._show_prompt() + + elif action == b"prompt_end": + if self._prompt is None: + return + self._close_prompt() + self._prompt = None + + #~ prompt handling + + def _show_prompt(self): + self._prompt.activate() + self._plugin_manager.send_plugin_message(self._identifier, dict(action="show", + text=self._prompt.text, + choices=self._prompt.choices)) + + def _close_prompt(self): + self._prompt = None + self._plugin_manager.send_plugin_message(self._identifier, dict(action="close")) + + def _answer_prompt(self, choice): + self._close_prompt() + self._printer.commands([self._selection_command.format(choice=choice)]) + + +__plugin_name__ = "Action Command Prompt Support" +__plugin_description__ = "Allows your printer to trigger prompts via action commands on the connection" +__plugin_author__ = "Gina Häußge" +__plugin_disabling_discouraged__ = gettext("Without this plugin your printer will no longer be able to trigger" + "confirmation or selection prompts in OctoPrint") +__plugin_license__ = "AGPLv3" +__plugin_implementation__ = ActionCommandPromptPlugin() +__plugin_hooks__ = { + b"octoprint.comm.protocol.action": __plugin_implementation__.action_command_handler +} diff --git a/src/octoprint/plugins/action_command_prompt/static/js/action_command_prompt.js b/src/octoprint/plugins/action_command_prompt/static/js/action_command_prompt.js new file mode 100644 index 000000000..6298a5338 --- /dev/null +++ b/src/octoprint/plugins/action_command_prompt/static/js/action_command_prompt.js @@ -0,0 +1,104 @@ +(function (global, factory) { + if (typeof define === "function" && define.amd) { + define(["OctoPrintClient"], factory); + } else { + factory(global.OctoPrintClient); + } +})(this, function(OctoPrintClient) { + var OctoPrintActionCommandPromptClient = function(base) { + this.base = base; + }; + + OctoPrintActionCommandPromptClient.prototype.get = function(refresh, opts) { + return this.base.get(this.base.getSimpleApiUrl("action_command_prompt"), opts); + }; + + OctoPrintActionCommandPromptClient.prototype.select = function(choice, opts) { + var data = { + choice: choice + }; + return this.base.simpleApiCommand("action_command_prompt", "select", data, opts); + }; + + OctoPrintClient.registerPluginComponent("action_command_prompt", OctoPrintActionCommandPromptClient); + return OctoPrintActionCommandPromptClient; +}); + +$(function() { + function ActionCommandPromptViewModel(parameters) { + var self = this; + + self.loginState = parameters[0]; + + self._modal = undefined; + + self.requestData = function() { + if (!self.loginState.isUser()) return; + + OctoPrint.plugins.action_command_prompt.get() + .done(self.fromResponse); + }; + + self.fromResponse = function(data) { + if (data.hasOwnProperty("text") && data.hasOwnProperty("choices")) { + self._showPrompt(data.text, data.choices); + } + }; + + self._showPrompt = function(text, buttons) { + var opts = { + title: gettext("Message from your printer"), + message: text, + selections: buttons, + onselect: function(index) { + if (index > -1) { + self._select(index); + } + }, + onclose: function() { + self._modal = undefined; + } + }; + + self._modal = showSelectionDialog(opts) + }; + + self._select = function(index) { + OctoPrint.plugins.action_command_prompt.select(index); + }; + + self._closePrompt = function() { + if (self._modal) { + self._modal.modal("hide"); + } + }; + + self.onStartupComplete = function() { + self.requestData(); + }; + + self.onDataUpdaterPluginMessage = function(plugin, data) { + if (!self.loginState.isUser()) return; + if (plugin !== "action_command_prompt") { + return; + } + + switch (data.action) { + case "show": { + self._showPrompt(data.text, data.choices); + break; + } + case "close": { + self._closePrompt(); + break; + } + } + } + + } + + OCTOPRINT_VIEWMODELS.push({ + construct: ActionCommandPromptViewModel, + dependencies: ["loginStateViewModel"] + }); +}); diff --git a/src/octoprint/plugins/action_command_prompt/templates/action_command_prompt_settings.jinja2 b/src/octoprint/plugins/action_command_prompt/templates/action_command_prompt_settings.jinja2 new file mode 100644 index 000000000..a30e7f9b8 --- /dev/null +++ b/src/octoprint/plugins/action_command_prompt/templates/action_command_prompt_settings.jinja2 @@ -0,0 +1,11 @@ +

{{ _('Action Command Prompt Settings') }}

+ +
+
+ +
+ +
{{ _('Use this to define the command to tell the printer about the selection. OctoPrint will replace {choice} with the index of the selected choice. E.g. M876 S{choice} will become M123 S1') }}
+
+
+
diff --git a/src/octoprint/plugins/printer_safety_check/__init__.py b/src/octoprint/plugins/printer_safety_check/__init__.py index e8a2618d5..d324b4eaa 100644 --- a/src/octoprint/plugins/printer_safety_check/__init__.py +++ b/src/octoprint/plugins/printer_safety_check/__init__.py @@ -9,6 +9,7 @@ import octoprint.plugin from octoprint.events import Events from octoprint.access import USER_GROUP from octoprint.access.permissions import Permissions +from octoprint.util.version import get_comparable_version import flask from flask_babel import gettext @@ -39,13 +40,32 @@ CR10S_RECEIVED_TEST = lambda line: line and CR10S_AUTHOR in line.lower() # Malyan M200 aka Monoprice Select Mini MALYANM200_M115_TEST = lambda name, data: name and name.lower().startswith("malyan") and data.get("MODEL") == "M200" +# Any Repetier versions < 0.92 +REPETIER_BEFORE_092_M115_TEST = lambda name, data: name and name.lower().startswith("repetier") and extract_repetier_version(name) is not None and extract_repetier_version(name) < get_comparable_version("0.92") + +# THERMAL_PROTECTION capability reported as disabled +THERMAL_PROTECTION_CAP_TEST = lambda cap, enabled: cap == "THERMAL_PROTECTION" and not enabled + SAFETY_CHECKS = { - "firmware-unsafe": dict(m115=(ANETA8_M115_TEST, MALYANM200_M115_TEST), + "firmware-unsafe": dict(m115=(ANETA8_M115_TEST, MALYANM200_M115_TEST, REPETIER_BEFORE_092_M115_TEST), received=(ANYCUBIC_RECEIVED_TEST, CR10S_RECEIVED_TEST), + cap=(THERMAL_PROTECTION_CAP_TEST,), message=u"Your printer's firmware is known to lack mandatory safety features (e.g. " \ u"thermal runaway protection). This is a fire risk.") } +def extract_repetier_version(name): + """ + Extracts the Repetier version number from the firmware name. + + Example: "Repetier_0.91" => 0.91 + """ + version = None + if "_" in name: + _, version = name.split("_", 1) + version = get_comparable_version(version, base=True) + return version + class PrinterSafetyCheckPlugin(octoprint.plugin.AssetPlugin, octoprint.plugin.EventHandlerPlugin, octoprint.plugin.SimpleApiPlugin, @@ -77,10 +97,7 @@ class PrinterSafetyCheckPlugin(octoprint.plugin.AssetPlugin, ##~~ EventHandlerPlugin API def on_event(self, event, payload): - if event == Events.FIRMWARE_DATA: - self._run_checks("m115", payload.get("name"), payload.get("data")) - self._scan_received = False - elif event == Events.DISCONNECTED: + if event == Events.DISCONNECTED: self._reset_warnings() ##~~ SimpleApiPlugin API @@ -97,7 +114,18 @@ class PrinterSafetyCheckPlugin(octoprint.plugin.AssetPlugin, self._run_checks("received", line) return line - # Additional permissions hook + ##~~ Firmware info hook handler + + def on_firmware_info_received(self, comm_instance, firmware_name, firmware_data): + self._run_checks("m115", firmware_name, firmware_data) + self._scan_received = False + + ##~~ Firmware capability hook handler + + def on_firmware_cap_received(self, comm_instance, cap, enabled, all_caps): + self._run_checks("cap", cap, enabled) + + ##~~ Additional permissions hook handler def get_additional_permissions(self): return [ @@ -154,6 +182,8 @@ __plugin_license__ = "AGPLv3" __plugin_implementation__ = PrinterSafetyCheckPlugin() __plugin_hooks__ = { "octoprint.comm.protocol.gcode.received": __plugin_implementation__.on_gcode_received, + "octoprint.comm.protocol.firmware.info": __plugin_implementation__.on_firmware_info_received, + "octoprint.comm.protocol.firmware.capabilities": __plugin_implementation__.on_firmware_cap_received, "octoprint.access.permissions": __plugin_implementation__.get_additional_permissions } diff --git a/src/octoprint/printer/__init__.py b/src/octoprint/printer/__init__.py index bcff47267..8cb3571cc 100644 --- a/src/octoprint/printer/__init__.py +++ b/src/octoprint/printer/__init__.py @@ -24,7 +24,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms import re from octoprint.settings import settings -from octoprint.util import deprecated +from octoprint.util import deprecated, natural_key from octoprint.filemanager import FileDestinations @@ -68,8 +68,8 @@ class PrinterInterface(object): """ import octoprint.util.comm as comm return { - "ports": comm.serialList(), - "baudrates": comm.baudrateList(), + "ports": sorted(comm.serialList(), key=natural_key), + "baudrates": sorted(comm.baudrateList(), reverse=True), "portPreference": settings().get(["serial", "port"]), "baudratePreference": settings().getInt(["serial", "baudrate"]), "autoconnect": settings().getBoolean(["serial", "autoconnect"]) diff --git a/src/octoprint/printer/estimation.py b/src/octoprint/printer/estimation.py index f9128785d..e327428c1 100644 --- a/src/octoprint/printer/estimation.py +++ b/src/octoprint/printer/estimation.py @@ -39,7 +39,10 @@ class PrintTimeEstimator(object): if self._job_type == "sdcard": # we are interesting in a rolling window of roughly the last 15s, so the number of entries has to be derived # by that divided by the sd status polling interval - rolling_window = 15 / settings().get(["serial", "timeout", "sdStatus"]) + interval = settings().getFloat(["serial", "timeout", "sdStatus"]) + if interval <= 0: + interval = 1.0 + rolling_window = 15 / interval # we are happy when one rolling window has been stable countdown = rolling_window diff --git a/src/octoprint/printer/standard.py b/src/octoprint/printer/standard.py index d5d567d67..5735287de 100644 --- a/src/octoprint/printer/standard.py +++ b/src/octoprint/printer/standard.py @@ -695,6 +695,12 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback, ProtocolListener, def is_paused(self, *args, **kwargs): return self._protocol is not None and self._protocol.state == ProtocolState.PAUSED + def is_resuming(self, *args, **kwargs): + return self._comm is not None and self._comm.isResuming() + + def is_finishing(self, *args, **kwargs): + return self._comm is not None and self._comm.isFinishing() + def is_error(self, *args, **kwargs): return self._protocol is not None and self._protocol.state == ProtocolState.DISCONNECTED_WITH_ERROR @@ -991,15 +997,17 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback, ProtocolListener, self._logger.exception("Error while trying to send initial state update") def _get_state_flags(self): - return dict(operational=self.is_operational(), - printing=self.is_printing(), - cancelling=self.is_cancelling(), - pausing=self.is_pausing(), - closedOrError=self.is_closed_or_error(), - error=self.is_error(), - paused=self.is_paused(), - ready=self.is_ready(), - sdReady=self.is_sd_ready()) + return self._dict(operational=self.is_operational(), + printing=self.is_printing(), + cancelling=self.is_cancelling(), + pausing=self.is_pausing(), + resuming=self.is_resuming(), + finishing=self.is_finishing(), + closedOrError=self.is_closed_or_error(), + error=self.is_error(), + paused=self.is_paused(), + ready=self.is_ready(), + sdReady=self.is_sd_ready()) def _get_origin_for_job(self, job=None): if job is None: @@ -1096,18 +1104,19 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback, ProtocolListener, self._state_monitor.trigger_progress_update() - def on_job_started(self, job): + def on_job_started(self, job, suppress_script=False): if self._job is None or job != self._job.job: return payload = job.event_payload() if payload: eventManager().fire(Events.PRINT_STARTED, payload) - self.script("beforePrintStarted", - context=dict(event=payload), - must_be_set=False) + if not suppress_script: + self.script("beforePrintStarted", + context=dict(event=payload), + must_be_set=False) - def on_job_done(self, job): + def on_job_done(self, job, suppress_script=False): if self._job is None or job != self._job.job: return @@ -1137,9 +1146,10 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback, ProtocolListener, flags=self._get_state_flags())) eventManager().fire(Events.PRINT_DONE, payload) - self.script("afterPrintDone", - context=dict(event=payload), - must_be_set=False) + if not suppress_script: + self.script("afterPrintDone", + context=dict(event=payload), + must_be_set=False) def log_print(): self._file_manager.log_print(payload["origin"], @@ -1172,7 +1182,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback, ProtocolListener, payload["firmwareError"] = firmware_error eventManager().fire(Events.PRINT_CANCELLING, payload) - def on_job_cancelled(self, job, cancel_position=None): + def on_job_cancelled(self, job, cancel_position=None, suppress_script=False): if self._job is None or job != self._job.job: return @@ -1185,9 +1195,10 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback, ProtocolListener, payload["position"] = cancel_position eventManager().fire(Events.PRINT_CANCELLED, payload) - self.script("afterPrintCancelled", - context=dict(event=payload), - must_be_set=False) + if not suppress_script: + self.script("afterPrintCancelled", + context=dict(event=payload), + must_be_set=False) def finalize(): self._file_manager.log_print(job.storage, @@ -1202,7 +1213,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback, ProtocolListener, thread.daemon = True thread.start() - def on_job_paused(self, job, pause_position=None): + def on_job_paused(self, job, pause_position=None, suppress_script=False): if self._job is None or job != self._job.job: return @@ -1211,20 +1222,22 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback, ProtocolListener, if pause_position: payload["position"] = pause_position eventManager().fire(Events.PRINT_PAUSED, payload) - self.script("afterPrintPaused", - context=dict(event=payload), - must_be_set=False) + if not suppress_script: + self.script("afterPrintPaused", + context=dict(event=payload), + must_be_set=False) - def on_job_resumed(self, job): + def on_job_resumed(self, job, suppress_script=False): if self._job is None or job != self._job.job: return payload = job.event_payload() if payload: eventManager().fire(Events.PRINT_RESUMED, payload) - self.script("beforePrintResumed", - context=dict(event=payload), - must_be_set=False) + if not suppress_script: + self.script("beforePrintResumed", + context=dict(event=payload), + must_be_set=False) #~~ comm.MachineComPrintCallback implementation diff --git a/src/octoprint/server/api/connection.py b/src/octoprint/server/api/connection.py index d6a22ee89..737279d08 100644 --- a/src/octoprint/server/api/connection.py +++ b/src/octoprint/server/api/connection.py @@ -80,8 +80,8 @@ def _get_options(): default_profile = printerProfileManager.get_default() options = dict( - ports=sorted(connection_options["ports"]), - baudrates=sorted(connection_options["baudrates"], reverse=True), + ports=connection_options["ports"], + baudrates=connection_options["baudrates"], printerProfiles=[dict(id=printer_profile["id"], name=printer_profile["name"] if "name" in printer_profile else printer_profile["id"]) for printer_profile in profile_options.values() if "id" in printer_profile], portPreference=connection_options["portPreference"], baudratePreference=connection_options["baudratePreference"], diff --git a/src/octoprint/server/api/settings.py b/src/octoprint/server/api/settings.py index 905631f6f..f9a3f4dad 100644 --- a/src/octoprint/server/api/settings.py +++ b/src/octoprint/server/api/settings.py @@ -385,17 +385,17 @@ def _saveSettings(data): if "autoconnect" in data["serial"]: s.setBoolean(["serial", "autoconnect"], data["serial"]["autoconnect"]) if "port" in data["serial"]: s.set(["serial", "port"], data["serial"]["port"]) if "baudrate" in data["serial"]: s.setInt(["serial", "baudrate"], data["serial"]["baudrate"]) - if "timeoutConnection" in data["serial"]: s.setFloat(["serial", "timeout", "connection"], data["serial"]["timeoutConnection"]) - if "timeoutDetection" in data["serial"]: s.setFloat(["serial", "timeout", "detection"], data["serial"]["timeoutDetection"]) - if "timeoutCommunication" in data["serial"]: s.setFloat(["serial", "timeout", "communication"], data["serial"]["timeoutCommunication"]) - if "timeoutCommunicationBusy" in data["serial"]: s.setFloat(["serial", "timeout", "communicationBusy"], data["serial"]["timeoutCommunicationBusy"]) - if "timeoutTemperature" in data["serial"]: s.setFloat(["serial", "timeout", "temperature"], data["serial"]["timeoutTemperature"]) - if "timeoutTemperatureTargetSet" in data["serial"]: s.setFloat(["serial", "timeout", "temperatureTargetSet"], data["serial"]["timeoutTemperatureTargetSet"]) - if "timeoutTemperatureAutoreport" in data["serial"]: s.setFloat(["serial", "timeout", "temperatureAutoreport"], data["serial"]["timeoutTemperatureAutoreport"]) - if "timeoutSdStatus" in data["serial"]: s.setFloat(["serial", "timeout", "sdStatus"], data["serial"]["timeoutSdStatus"]) - if "timeoutSdStatusAutoreport" in data["serial"]: s.setFloat(["serial", "timeout", "sdStatusAutoreport"], data["serial"]["timeoutSdStatusAutoreport"]) - if "timeoutBaudrateDetectionPause" in data["serial"]: s.setFloat(["serial", "timeout", "baudrateDetectionPause"], data["serial"]["timeoutBaudrateDetectionPause"]) - if "timeoutPositionLogWait" in data["serial"]: s.setFloat(["serial", "timeout", "positionLogWait"], data["serial"]["timeoutPositionLogWait"]) + if "timeoutConnection" in data["serial"]: s.setFloat(["serial", "timeout", "connection"], data["serial"]["timeoutConnection"], minimum=1.0) + if "timeoutDetection" in data["serial"]: s.setFloat(["serial", "timeout", "detection"], data["serial"]["timeoutDetection"], minimum=1.0) + if "timeoutCommunication" in data["serial"]: s.setFloat(["serial", "timeout", "communication"], data["serial"]["timeoutCommunication"], minimum=1.0) + if "timeoutCommunicationBusy" in data["serial"]: s.setFloat(["serial", "timeout", "communicationBusy"], data["serial"]["timeoutCommunicationBusy"], minimum=1.0) + if "timeoutTemperature" in data["serial"]: s.setFloat(["serial", "timeout", "temperature"], data["serial"]["timeoutTemperature"], minimum=1.0) + if "timeoutTemperatureTargetSet" in data["serial"]: s.setFloat(["serial", "timeout", "temperatureTargetSet"], data["serial"]["timeoutTemperatureTargetSet"], minimum=1.0) + if "timeoutTemperatureAutoreport" in data["serial"]: s.setFloat(["serial", "timeout", "temperatureAutoreport"], data["serial"]["timeoutTemperatureAutoreport"], minimum=0.0) + if "timeoutSdStatus" in data["serial"]: s.setFloat(["serial", "timeout", "sdStatus"], data["serial"]["timeoutSdStatus"], minimum=1.0) + if "timeoutSdStatusAutoreport" in data["serial"]: s.setFloat(["serial", "timeout", "sdStatusAutoreport"], data["serial"]["timeoutSdStatusAutoreport"], minimum=0.0) + if "timeoutBaudrateDetectionPause" in data["serial"]: s.setFloat(["serial", "timeout", "baudrateDetectionPause"], data["serial"]["timeoutBaudrateDetectionPause"], minimum=0.0) + if "timeoutPositionLogWait" in data["serial"]: s.setFloat(["serial", "timeout", "positionLogWait"], data["serial"]["timeoutPositionLogWait"], minimum=1.0) if "additionalPorts" in data["serial"] and isinstance(data["serial"]["additionalPorts"], (list, tuple)): s.set(["serial", "additionalPorts"], data["serial"]["additionalPorts"]) if "additionalBaudrates" in data["serial"] and isinstance(data["serial"]["additionalBaudrates"], (list, tuple)): s.set(["serial", "additionalBaudrates"], data["serial"]["additionalBaudrates"]) if "longRunningCommands" in data["serial"] and isinstance(data["serial"]["longRunningCommands"], (list, tuple)): s.set(["serial", "longRunningCommands"], data["serial"]["longRunningCommands"]) diff --git a/src/octoprint/static/js/app/helpers.js b/src/octoprint/static/js/app/helpers.js index 2fe9fc1b0..49af106bc 100644 --- a/src/octoprint/static/js/app/helpers.js +++ b/src/octoprint/static/js/app/helpers.js @@ -650,6 +650,7 @@ function showMessageDialog(msg, options) { var onclose = options.onclose || undefined; var onshow = options.onshow || undefined; var onshown = options.onshown || undefined; + var nofade = options.nofade || false; if (_.isString(message)) { message = $("

" + message + "

"); @@ -660,7 +661,11 @@ function showMessageDialog(msg, options) { var modalFooter = $(''); var modal = $('
') - .addClass('modal hide fade') + .addClass("modal hide"); + if (!nofade) { + modal.addClass("fade"); + } + modal .append($('
').addClass('modal-header').append(modalHeader)) .append($('
').addClass('modal-body').append(modalBody)) .append($('
').addClass('modal-footer').append(modalFooter)); @@ -669,6 +674,7 @@ function showMessageDialog(msg, options) { if (onclose && _.isFunction(onclose)) { onclose(); } + modal.remove(); }); if (onshow) { @@ -705,6 +711,7 @@ function showConfirmationDialog(msg, onacknowledge, options) { var onproceed = options.onproceed || undefined; var onclose = options.onclose || undefined; var dialogClass = options.dialogClass || ""; + var nofade = options.nofade || false; var modalHeader = $('

' + title + '

'); var modalBody; @@ -721,8 +728,11 @@ function showConfirmationDialog(msg, onacknowledge, options) { .addClass("btn-" + proceedClass); var modal = $('
') - .addClass('modal hide fade') - .addClass(dialogClass) + .addClass('modal hide'); + if (!nofade) { + modal.addClass('fade'); + } + modal.addClass(dialogClass) .append($('
').addClass('modal-header').append(modalHeader)) .append($('
').addClass('modal-body').append(modalBody)) .append($('
').addClass('modal-footer').append(cancelButton).append(proceedButton)); @@ -739,6 +749,108 @@ function showConfirmationDialog(msg, onacknowledge, options) { onproceed(e); } modal.modal("hide"); + modal.remove(); + }); + + return modal; +} + +function showSelectionDialog(options) { + var title = options.title; + var message = options.message || undefined; + var selections = options.selections || []; + + var maycancel = options.maycancel || false; + var cancel = options.cancel || undefined; + var onselect = options.onselect || undefined; + var onclose = options.onclose || undefined; + var dialogClass = options.dialogClass || ""; + var nofade = options.nofade || false; + + // header + var modalHeader; + if (maycancel) { + modalHeader = $('

' + title + '

'); + } else { + modalHeader = $('

' + title + '

'); + } + + // body + var buttons = []; + var selectionBody = $("
"); + var container; + var additionalClass; + + if (selections.length === 1) { + container = selectionBody; + additionalClass = "btn-block"; + } else if (selections.length === 2) { + container = $("
"); + selectionBody.append(container); + additionalClass = "span6" + } else { + container = $("
"); + selectionBody.append(container); + additionalClass = "span6 offset3"; + } + + _.each(selections, function(s, i) { + var button = $(''); + if (additionalClass) { + button.addClass(additionalClass); + } + container.append(button); + buttons.push(button); + + if (selections.length > 2 && i < selections.length - 1) { + container = $("
"); + selectionBody.append(container); + } + }); + + // divs + var headerDiv = $('
').addClass('modal-header').append(modalHeader); + + var bodyDiv = $('
').addClass('modal-body'); + if (message) { + bodyDiv.append($('

' + message + '

')); + } + bodyDiv.append(selectionBody); + + // create modal and do final wiring up + var modal = $('
') + .addClass('modal hide'); + if (!nofade) { + modal.addClass('fade'); + } + if (!cancel) { + modal.data("backdrop", "static").data("keyboard", "false"); + } + + modal.addClass(dialogClass) + .append(headerDiv) + .append(bodyDiv); + modal.on('hidden', function(event) { + if (onclose && _.isFunction(onclose)) { + onclose(event); + } + modal.remove(); + }); + modal.modal("show"); + + _.each(buttons, function(button) { + button.click(function(e) { + e.preventDefault(); + var index = button.data("index"); + if (index < 0) { + return; + } + + if (onselect && _.isFunction(onselect)) { + onselect(index, e); + } + modal.modal("hide"); + }) }); return modal; diff --git a/src/octoprint/static/js/app/viewmodels/connection.js b/src/octoprint/static/js/app/viewmodels/connection.js index 42a5ab46c..e2224e59d 100644 --- a/src/octoprint/static/js/app/viewmodels/connection.js +++ b/src/octoprint/static/js/app/viewmodels/connection.js @@ -160,6 +160,10 @@ $(function() { } }; + self.onEventSettingsUpdated = function() { + self.requestData(); + } + self.onStartup = function() { var connectionTab = $("#connection"); connectionTab.on("show", function() { diff --git a/src/octoprint/static/js/app/viewmodels/printerstate.js b/src/octoprint/static/js/app/viewmodels/printerstate.js index 0ac1ad1a7..5a8fc56f5 100644 --- a/src/octoprint/static/js/app/viewmodels/printerstate.js +++ b/src/octoprint/static/js/app/viewmodels/printerstate.js @@ -339,7 +339,8 @@ $(function() { proceed: gettext("Yes"), onproceed: function() { OctoPrint.job.cancel(); - } + }, + nofade: true }); } }; diff --git a/src/octoprint/static/js/lib/jquery/jquery.js b/src/octoprint/static/js/lib/jquery/jquery.js index 5c3c456ac..9b5206bcc 100644 --- a/src/octoprint/static/js/lib/jquery/jquery.js +++ b/src/octoprint/static/js/lib/jquery/jquery.js @@ -1,20 +1,22 @@ /*! - * jQuery JavaScript Library v2.2.4 - * http://jquery.com/ + * jQuery JavaScript Library v3.3.1 + * https://jquery.com/ * * Includes Sizzle.js - * http://sizzlejs.com/ + * https://sizzlejs.com/ * - * Copyright jQuery Foundation and other contributors + * Copyright JS Foundation and other contributors * Released under the MIT license - * http://jquery.org/license + * https://jquery.org/license * - * Date: 2016-05-20T17:23Z + * Date: 2018-01-20T17:24Z */ +( function( global, factory ) { -(function( global, factory ) { + "use strict"; if ( typeof module === "object" && typeof module.exports === "object" ) { + // For CommonJS and CommonJS-like environments where a proper `window` // is present, execute the factory and get jQuery. // For environments that do not have a `window` with a `document` @@ -35,17 +37,20 @@ } // Pass this if window is not defined yet -}(typeof window !== "undefined" ? window : this, function( window, noGlobal ) { +} )( typeof window !== "undefined" ? window : this, function( window, noGlobal ) { + +// Edge <= 12 - 13+, Firefox <=18 - 45+, IE 10 - 11, Safari 5.1 - 9+, iOS 6 - 9.1 +// throw exceptions when non-strict code (e.g., ASP.NET 4.5) accesses strict mode +// arguments.callee.caller (trac-13335). But as of jQuery 3.0 (2016), strict mode should be common +// enough that all such attempts are guarded in a try block. +"use strict"; -// Support: Firefox 18+ -// Can't be in strict mode, several libs including ASP.NET trace -// the stack via arguments.caller.callee and Firefox dies if -// you try to trace through "use strict" call chains. (#13335) -//"use strict"; var arr = []; var document = window.document; +var getProto = Object.getPrototypeOf; + var slice = arr.slice; var concat = arr.concat; @@ -60,12 +65,71 @@ var toString = class2type.toString; var hasOwn = class2type.hasOwnProperty; +var fnToString = hasOwn.toString; + +var ObjectFunctionString = fnToString.call( Object ); + var support = {}; +var isFunction = function isFunction( obj ) { + + // Support: Chrome <=57, Firefox <=52 + // In some browsers, typeof returns "function" for HTML elements + // (i.e., `typeof document.createElement( "object" ) === "function"`). + // We don't want to classify *any* DOM node as a function. + return typeof obj === "function" && typeof obj.nodeType !== "number"; + }; + + +var isWindow = function isWindow( obj ) { + return obj != null && obj === obj.window; + }; + + + + + var preservedScriptAttributes = { + type: true, + src: true, + noModule: true + }; + + function DOMEval( code, doc, node ) { + doc = doc || document; + + var i, + script = doc.createElement( "script" ); + + script.text = code; + if ( node ) { + for ( i in preservedScriptAttributes ) { + if ( node[ i ] ) { + script[ i ] = node[ i ]; + } + } + } + doc.head.appendChild( script ).parentNode.removeChild( script ); + } + + +function toType( obj ) { + if ( obj == null ) { + return obj + ""; + } + + // Support: Android <=2.3 only (functionish RegExp) + return typeof obj === "object" || typeof obj === "function" ? + class2type[ toString.call( obj ) ] || "object" : + typeof obj; +} +/* global Symbol */ +// Defining this global in .eslintrc.json would create a danger of using the global +// unguarded in another place, it seems safer to define global only for this module + var - version = "2.2.4", + version = "3.3.1", // Define a local copy of jQuery jQuery = function( selector, context ) { @@ -75,18 +139,9 @@ var return new jQuery.fn.init( selector, context ); }, - // Support: Android<4.1 + // Support: Android <=4.0 only // Make sure we trim BOM and NBSP - rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, - - // 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(); - }; + rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g; jQuery.fn = jQuery.prototype = { @@ -95,9 +150,6 @@ jQuery.fn = jQuery.prototype = { constructor: jQuery, - // Start with an empty selector - selector: "", - // The default length of a jQuery object is 0 length: 0, @@ -108,13 +160,14 @@ jQuery.fn = jQuery.prototype = { // 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 just the one element from the set - ( num < 0 ? this[ num + this.length ] : this[ num ] ) : + // Return all the elements in a clean array + if ( num == null ) { + return slice.call( this ); + } - // Return all the elements in a clean array - slice.call( this ); + // Return just the one element from the set + return num < 0 ? this[ num + this.length ] : this[ num ]; }, // Take an array of elements and push it onto the stack @@ -126,7 +179,6 @@ jQuery.fn = jQuery.prototype = { // 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; @@ -189,7 +241,7 @@ jQuery.extend = jQuery.fn.extend = function() { } // Handle case when target is a string or something (possible in deep copy) - if ( typeof target !== "object" && !jQuery.isFunction( target ) ) { + if ( typeof target !== "object" && !isFunction( target ) ) { target = {}; } @@ -216,11 +268,11 @@ jQuery.extend = jQuery.fn.extend = function() { // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject( copy ) || - ( copyIsArray = jQuery.isArray( copy ) ) ) ) { + ( copyIsArray = Array.isArray( copy ) ) ) ) { if ( copyIsArray ) { copyIsArray = false; - clone = src && jQuery.isArray( src ) ? src : []; + clone = src && Array.isArray( src ) ? src : []; } else { clone = src && jQuery.isPlainObject( src ) ? src : {}; @@ -255,105 +307,42 @@ jQuery.extend( { noop: function() {}, - isFunction: function( obj ) { - return jQuery.type( obj ) === "function"; - }, - - isArray: Array.isArray, - - isWindow: function( obj ) { - return obj != null && obj === obj.window; - }, - - isNumeric: function( obj ) { - - // parseFloat NaNs numeric-cast false positives (null|true|false|"") - // ...but misinterprets leading-number strings, particularly hex literals ("0x...") - // subtraction forces infinities to NaN - // adding 1 corrects loss of precision from parseFloat (#15100) - var realStringObj = obj && obj.toString(); - return !jQuery.isArray( obj ) && ( realStringObj - parseFloat( realStringObj ) + 1 ) >= 0; - }, - isPlainObject: function( obj ) { - var key; + var proto, Ctor; - // 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 ) ) { + // Detect obvious negatives + // Use toString instead of jQuery.type to catch host objects + if ( !obj || toString.call( obj ) !== "[object Object]" ) { return false; } - // Not own constructor property must be Object - if ( obj.constructor && - !hasOwn.call( obj, "constructor" ) && - !hasOwn.call( obj.constructor.prototype || {}, "isPrototypeOf" ) ) { - return false; + proto = getProto( obj ); + + // Objects with no prototype (e.g., `Object.create( null )`) are plain + if ( !proto ) { + return true; } - // Own properties are enumerated firstly, so to speed up, - // if last one is own, then all properties are own - for ( key in obj ) {} - - return key === undefined || hasOwn.call( obj, key ); + // Objects with prototype are plain iff they were constructed by a global Object function + Ctor = hasOwn.call( proto, "constructor" ) && proto.constructor; + return typeof Ctor === "function" && fnToString.call( Ctor ) === ObjectFunctionString; }, isEmptyObject: function( obj ) { + + /* eslint-disable no-unused-vars */ + // See https://github.com/eslint/eslint/issues/6125 var name; + for ( name in obj ) { return false; } return true; }, - type: function( obj ) { - if ( obj == null ) { - return obj + ""; - } - - // Support: Android<4.0, iOS<6 (functionish RegExp) - return typeof obj === "object" || typeof obj === "function" ? - class2type[ toString.call( obj ) ] || "object" : - typeof obj; - }, - // 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 - // Support: IE9-11+ - // 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(); + DOMEval( code ); }, each: function( obj, callback ) { @@ -377,7 +366,7 @@ jQuery.extend( { return obj; }, - // Support: Android<4.1 + // Support: Android <=4.0 only trim: function( text ) { return text == null ? "" : @@ -406,6 +395,8 @@ jQuery.extend( { return arr == null ? -1 : indexOf.call( arr, elem, i ); }, + // Support: Android <=4.0 only, PhantomJS 1 only + // push.apply(_, arraylike) throws on ancient WebKit merge: function( first, second ) { var len = +second.length, j = 0, @@ -474,51 +465,14 @@ jQuery.extend( { // 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 = slice.call( arguments, 2 ); - proxy = function() { - return fn.apply( context || this, args.concat( 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; - }, - - now: Date.now, - // jQuery.support is not used in Core but other projects attach their // properties to it so it needs to exist. support: support } ); -// JSHint would error on this code due to the Symbol not being defined in ES5. -// Defining this global in .jshintrc would create a danger of using the global -// unguarded in another place, it seems safer to just disable JSHint for these -// three lines. -/* jshint ignore: start */ if ( typeof Symbol === "function" ) { jQuery.fn[ Symbol.iterator ] = arr[ Symbol.iterator ]; } -/* jshint ignore: end */ // Populate the class2type map jQuery.each( "Boolean Number String Function Array Date RegExp Object Error Symbol".split( " " ), @@ -528,14 +482,14 @@ function( i, name ) { function isArrayLike( obj ) { - // Support: iOS 8.2 (not reproducible in simulator) + // Support: real iOS 8.2 only (not reproducible in simulator) // `in` check used to prevent JIT error (gh-2145) // hasOwn isn't used here due to false negatives // regarding Nodelist length in IE var length = !!obj && "length" in obj && obj.length, - type = jQuery.type( obj ); + type = toType( obj ); - if ( type === "function" || jQuery.isWindow( obj ) ) { + if ( isFunction( obj ) || isWindow( obj ) ) { return false; } @@ -544,14 +498,14 @@ function isArrayLike( obj ) { } var Sizzle = /*! - * Sizzle CSS Selector Engine v2.2.1 - * http://sizzlejs.com/ + * Sizzle CSS Selector Engine v2.3.3 + * https://sizzlejs.com/ * * Copyright jQuery Foundation and other contributors * Released under the MIT license * http://jquery.org/license * - * Date: 2015-10-17 + * Date: 2016-08-08 */ (function( window ) { @@ -592,9 +546,6 @@ var i, return 0; }, - // General-purpose constants - MAX_NEGATIVE = 1 << 31, - // Instance methods hasOwn = ({}).hasOwnProperty, arr = [], @@ -603,7 +554,7 @@ var i, push = arr.push, slice = arr.slice, // Use a stripped-down indexOf as it's faster than native - // http://jsperf.com/thor-indexof-vs-for/5 + // https://jsperf.com/thor-indexof-vs-for/5 indexOf = function( list, elem ) { var i = 0, len = list.length; @@ -623,7 +574,7 @@ var i, whitespace = "[\\x20\\t\\r\\n\\f]", // http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier - identifier = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", + identifier = "(?:\\\\.|[\\w-]|[^\0-\\xa0])+", // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace + @@ -680,9 +631,9 @@ var i, rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rsibling = /[+~]/, - rescape = /'|\\/g, - // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters + // CSS escapes + // http://www.w3.org/TR/CSS21/syndata.html#escaped-characters runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ), funescape = function( _, escaped, escapedWhitespace ) { var high = "0x" + escaped - 0x10000; @@ -698,13 +649,39 @@ var i, String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); }, + // CSS string/identifier serialization + // https://drafts.csswg.org/cssom/#common-serializing-idioms + rcssescape = /([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g, + fcssescape = function( ch, asCodePoint ) { + if ( asCodePoint ) { + + // U+0000 NULL becomes U+FFFD REPLACEMENT CHARACTER + if ( ch === "\0" ) { + return "\uFFFD"; + } + + // Control characters and (dependent upon position) numbers get escaped as code points + return ch.slice( 0, -1 ) + "\\" + ch.charCodeAt( ch.length - 1 ).toString( 16 ) + " "; + } + + // Other potentially-special ASCII characters get backslash-escaped + return "\\" + ch; + }, + // Used for iframes // See setDocument() // Removing the function wrapper causes a "Permission Denied" // error in IE unloadHandler = function() { setDocument(); - }; + }, + + disabledAncestor = addCombinator( + function( elem ) { + return elem.disabled === true && ("form" in elem || "label" in elem); + }, + { dir: "parentNode", next: "legend" } + ); // Optimize for push.apply( _, NodeList ) try { @@ -736,7 +713,7 @@ try { } function Sizzle( selector, context, results, seed ) { - var m, i, elem, nid, nidselect, match, groups, newSelector, + var m, i, elem, nid, match, groups, newSelector, newContext = context && context.ownerDocument, // nodeType defaults to 9, since context defaults to document @@ -829,7 +806,7 @@ function Sizzle( selector, context, results, seed ) { // Capture the context ID, setting it first if necessary if ( (nid = context.getAttribute( "id" )) ) { - nid = nid.replace( rescape, "\\$&" ); + nid = nid.replace( rcssescape, fcssescape ); } else { context.setAttribute( "id", (nid = expando) ); } @@ -837,9 +814,8 @@ function Sizzle( selector, context, results, seed ) { // Prefix every selector in the list groups = tokenize( selector ); i = groups.length; - nidselect = ridentifier.test( nid ) ? "#" + nid : "[id='" + nid + "']"; while ( i-- ) { - groups[i] = nidselect + " " + toSelector( groups[i] ); + groups[i] = "#" + nid + " " + toSelector( groups[i] ); } newSelector = groups.join( "," ); @@ -900,22 +876,22 @@ function markFunction( fn ) { /** * Support testing using an element - * @param {Function} fn Passed the created div and expects a boolean result + * @param {Function} fn Passed the created element and returns a boolean result */ function assert( fn ) { - var div = document.createElement("div"); + var el = document.createElement("fieldset"); try { - return !!fn( div ); + return !!fn( el ); } catch (e) { return false; } finally { // Remove from its parent by default - if ( div.parentNode ) { - div.parentNode.removeChild( div ); + if ( el.parentNode ) { + el.parentNode.removeChild( el ); } // release memory in IE - div = null; + el = null; } } @@ -942,8 +918,7 @@ function addHandle( attrs, handler ) { function siblingCheck( a, b ) { var cur = b && a, diff = cur && a.nodeType === 1 && b.nodeType === 1 && - ( ~b.sourceIndex || MAX_NEGATIVE ) - - ( ~a.sourceIndex || MAX_NEGATIVE ); + a.sourceIndex - b.sourceIndex; // Use IE sourceIndex if available on both nodes if ( diff ) { @@ -984,6 +959,62 @@ function createButtonPseudo( type ) { }; } +/** + * Returns a function to use in pseudos for :enabled/:disabled + * @param {Boolean} disabled true for :disabled; false for :enabled + */ +function createDisabledPseudo( disabled ) { + + // Known :disabled false positives: fieldset[disabled] > legend:nth-of-type(n+2) :can-disable + return function( elem ) { + + // Only certain elements can match :enabled or :disabled + // https://html.spec.whatwg.org/multipage/scripting.html#selector-enabled + // https://html.spec.whatwg.org/multipage/scripting.html#selector-disabled + if ( "form" in elem ) { + + // Check for inherited disabledness on relevant non-disabled elements: + // * listed form-associated elements in a disabled fieldset + // https://html.spec.whatwg.org/multipage/forms.html#category-listed + // https://html.spec.whatwg.org/multipage/forms.html#concept-fe-disabled + // * option elements in a disabled optgroup + // https://html.spec.whatwg.org/multipage/forms.html#concept-option-disabled + // All such elements have a "form" property. + if ( elem.parentNode && elem.disabled === false ) { + + // Option elements defer to a parent optgroup if present + if ( "label" in elem ) { + if ( "label" in elem.parentNode ) { + return elem.parentNode.disabled === disabled; + } else { + return elem.disabled === disabled; + } + } + + // Support: IE 6 - 11 + // Use the isDisabled shortcut property to check for disabled fieldset ancestors + return elem.isDisabled === disabled || + + // Where there is no isDisabled, check manually + /* jshint -W018 */ + elem.isDisabled !== !disabled && + disabledAncestor( elem ) === disabled; + } + + return elem.disabled === disabled; + + // Try to winnow out elements that can't be disabled before trusting the disabled property. + // Some victims get caught in our net (label, legend, menu, track), but it shouldn't + // even exist on them, let alone have a boolean value. + } else if ( "label" in elem ) { + return elem.disabled === disabled; + } + + // Remaining elements are neither :enabled nor :disabled + return false; + }; +} + /** * Returns a function to use in pseudos for positionals * @param {Function} fn @@ -1036,7 +1067,7 @@ isXML = Sizzle.isXML = function( elem ) { * @returns {Object} Returns the current document */ setDocument = Sizzle.setDocument = function( node ) { - var hasCompare, parent, + var hasCompare, subWindow, doc = node ? node.ownerDocument || node : preferredDoc; // Return early if doc is invalid or already selected @@ -1051,14 +1082,16 @@ setDocument = Sizzle.setDocument = function( node ) { // Support: IE 9-11, Edge // Accessing iframe documents after unload throws "permission denied" errors (jQuery #13936) - if ( (parent = document.defaultView) && parent.top !== parent ) { - // Support: IE 11 - if ( parent.addEventListener ) { - parent.addEventListener( "unload", unloadHandler, false ); + if ( preferredDoc !== document && + (subWindow = document.defaultView) && subWindow.top !== subWindow ) { + + // Support: IE 11, Edge + if ( subWindow.addEventListener ) { + subWindow.addEventListener( "unload", unloadHandler, false ); // Support: IE 9 - 10 only - } else if ( parent.attachEvent ) { - parent.attachEvent( "onunload", unloadHandler ); + } else if ( subWindow.attachEvent ) { + subWindow.attachEvent( "onunload", unloadHandler ); } } @@ -1068,18 +1101,18 @@ setDocument = Sizzle.setDocument = function( node ) { // Support: IE<8 // Verify that getAttribute really returns attributes and not properties // (excepting IE8 booleans) - support.attributes = assert(function( div ) { - div.className = "i"; - return !div.getAttribute("className"); + support.attributes = assert(function( el ) { + el.className = "i"; + return !el.getAttribute("className"); }); /* getElement(s)By* ---------------------------------------------------------------------- */ // Check if getElementsByTagName("*") returns only elements - support.getElementsByTagName = assert(function( div ) { - div.appendChild( document.createComment("") ); - return !div.getElementsByTagName("*").length; + support.getElementsByTagName = assert(function( el ) { + el.appendChild( document.createComment("") ); + return !el.getElementsByTagName("*").length; }); // Support: IE<9 @@ -1087,32 +1120,28 @@ setDocument = Sizzle.setDocument = function( node ) { // Support: IE<10 // Check if getElementById returns elements by name - // The broken getElementById methods don't pick up programatically-set names, + // The broken getElementById methods don't pick up programmatically-set names, // so use a roundabout getElementsByName test - support.getById = assert(function( div ) { - docElem.appendChild( div ).id = expando; + support.getById = assert(function( el ) { + docElem.appendChild( el ).id = expando; return !document.getElementsByName || !document.getElementsByName( expando ).length; }); - // ID find and filter + // ID filter and find if ( support.getById ) { - Expr.find["ID"] = function( id, context ) { - if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { - var m = context.getElementById( id ); - return m ? [ m ] : []; - } - }; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { return elem.getAttribute("id") === attrId; }; }; + Expr.find["ID"] = function( id, context ) { + if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { + var elem = context.getElementById( id ); + return elem ? [ elem ] : []; + } + }; } else { - // Support: IE6/7 - // getElementById is not reliable as a find shortcut - delete Expr.find["ID"]; - Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { @@ -1121,6 +1150,36 @@ setDocument = Sizzle.setDocument = function( node ) { return node && node.value === attrId; }; }; + + // Support: IE 6 - 7 only + // getElementById is not reliable as a find shortcut + Expr.find["ID"] = function( id, context ) { + if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { + var node, i, elems, + elem = context.getElementById( id ); + + if ( elem ) { + + // Verify the id attribute + node = elem.getAttributeNode("id"); + if ( node && node.value === id ) { + return [ elem ]; + } + + // Fall back on getElementsByName + elems = context.getElementsByName( id ); + i = 0; + while ( (elem = elems[i++]) ) { + node = elem.getAttributeNode("id"); + if ( node && node.value === id ) { + return [ elem ]; + } + } + } + + return []; + } + }; } // Tag @@ -1174,77 +1233,87 @@ setDocument = Sizzle.setDocument = function( node ) { // We allow this because of a bug in IE8/9 that throws an error // whenever `document.activeElement` is accessed on an iframe // So, we allow :focus to pass through QSA all the time to avoid the IE error - // See http://bugs.jquery.com/ticket/13378 + // See https://bugs.jquery.com/ticket/13378 rbuggyQSA = []; if ( (support.qsa = rnative.test( document.querySelectorAll )) ) { // Build QSA regex // Regex strategy adopted from Diego Perini - assert(function( div ) { + assert(function( el ) { // Select is set to empty string on purpose // This is to test IE's treatment of not explicitly // setting a boolean content attribute, // since its presence should be enough - // http://bugs.jquery.com/ticket/12359 - docElem.appendChild( div ).innerHTML = "" + + // https://bugs.jquery.com/ticket/12359 + docElem.appendChild( el ).innerHTML = "" + ""; // Support: IE8, Opera 11-12.16 // Nothing should be selected when empty strings follow ^= or $= or *= // The test attribute must be unknown in Opera but "safe" for WinRT - // http://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section - if ( div.querySelectorAll("[msallowcapture^='']").length ) { + // https://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section + if ( el.querySelectorAll("[msallowcapture^='']").length ) { rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); } // Support: IE8 // Boolean attributes and "value" are not treated correctly - if ( !div.querySelectorAll("[selected]").length ) { + if ( !el.querySelectorAll("[selected]").length ) { rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); } // Support: Chrome<29, Android<4.4, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.8+ - if ( !div.querySelectorAll( "[id~=" + expando + "-]" ).length ) { + if ( !el.querySelectorAll( "[id~=" + expando + "-]" ).length ) { rbuggyQSA.push("~="); } // Webkit/Opera - :checked should return selected option elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked // IE8 throws error here and will not see later tests - if ( !div.querySelectorAll(":checked").length ) { + if ( !el.querySelectorAll(":checked").length ) { rbuggyQSA.push(":checked"); } // Support: Safari 8+, iOS 8+ // https://bugs.webkit.org/show_bug.cgi?id=136851 - // In-page `selector#id sibing-combinator selector` fails - if ( !div.querySelectorAll( "a#" + expando + "+*" ).length ) { + // In-page `selector#id sibling-combinator selector` fails + if ( !el.querySelectorAll( "a#" + expando + "+*" ).length ) { rbuggyQSA.push(".#.+[+~]"); } }); - assert(function( div ) { + assert(function( el ) { + el.innerHTML = "" + + ""; + // Support: Windows 8 Native Apps // The type and name attributes are restricted during .innerHTML assignment var input = document.createElement("input"); input.setAttribute( "type", "hidden" ); - div.appendChild( input ).setAttribute( "name", "D" ); + el.appendChild( input ).setAttribute( "name", "D" ); // Support: IE8 // Enforce case-sensitivity of name attribute - if ( div.querySelectorAll("[name=d]").length ) { + if ( el.querySelectorAll("[name=d]").length ) { rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" ); } // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here and will not see later tests - if ( !div.querySelectorAll(":enabled").length ) { + if ( el.querySelectorAll(":enabled").length !== 2 ) { + rbuggyQSA.push( ":enabled", ":disabled" ); + } + + // Support: IE9-11+ + // IE's :disabled selector does not pick up the children of disabled fieldsets + docElem.appendChild( el ).disabled = true; + if ( el.querySelectorAll(":disabled").length !== 2 ) { rbuggyQSA.push( ":enabled", ":disabled" ); } // Opera 10-11 does not throw on post-comma invalid pseudos - div.querySelectorAll("*,:x"); + el.querySelectorAll("*,:x"); rbuggyQSA.push(",.*:"); }); } @@ -1255,14 +1324,14 @@ setDocument = Sizzle.setDocument = function( node ) { docElem.oMatchesSelector || docElem.msMatchesSelector) )) ) { - assert(function( div ) { + assert(function( el ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) - support.disconnectedMatch = matches.call( div, "div" ); + support.disconnectedMatch = matches.call( el, "*" ); // This should fail with an exception // Gecko does not error, returns false instead - matches.call( div, "[s!='']:x" ); + matches.call( el, "[s!='']:x" ); rbuggyMatches.push( "!=", pseudos ); }); } @@ -1464,6 +1533,10 @@ Sizzle.attr = function( elem, name ) { null; }; +Sizzle.escape = function( sel ) { + return (sel + "").replace( rcssescape, fcssescape ); +}; + Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; @@ -1931,13 +2004,8 @@ Expr = Sizzle.selectors = { }, // Boolean properties - "enabled": function( elem ) { - return elem.disabled === false; - }, - - "disabled": function( elem ) { - return elem.disabled === true; - }, + "enabled": createDisabledPseudo( false ), + "disabled": createDisabledPseudo( true ), "checked": function( elem ) { // In CSS3, :checked should return both checked and selected elements @@ -2139,7 +2207,9 @@ function toSelector( tokens ) { function addCombinator( matcher, combinator, base ) { var dir = combinator.dir, - checkNonElements = base && dir === "parentNode", + skip = combinator.next, + key = skip || dir, + checkNonElements = base && key === "parentNode", doneName = done++; return combinator.first ? @@ -2150,6 +2220,7 @@ function addCombinator( matcher, combinator, base ) { return matcher( elem, context, xml ); } } + return false; } : // Check against all ancestor/preceding elements @@ -2175,14 +2246,16 @@ function addCombinator( matcher, combinator, base ) { // Defend against cloned attroperties (jQuery gh-1709) uniqueCache = outerCache[ elem.uniqueID ] || (outerCache[ elem.uniqueID ] = {}); - if ( (oldCache = uniqueCache[ dir ]) && + if ( skip && skip === elem.nodeName.toLowerCase() ) { + elem = elem[ dir ] || elem; + } else if ( (oldCache = uniqueCache[ key ]) && oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) { // Assign to newCache so results back-propagate to previous elements return (newCache[ 2 ] = oldCache[ 2 ]); } else { // Reuse newcache so results back-propagate to previous elements - uniqueCache[ dir ] = newCache; + uniqueCache[ key ] = newCache; // A match means we're done; a fail means we have to keep checking if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) { @@ -2192,6 +2265,7 @@ function addCombinator( matcher, combinator, base ) { } } } + return false; }; } @@ -2554,8 +2628,7 @@ select = Sizzle.select = function( selector, context, results, seed ) { // Reduce context if the leading compound selector is an ID tokens = match[0] = match[0].slice( 0 ); if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && - support.getById && context.nodeType === 9 && documentIsHTML && - Expr.relative[ tokens[1].type ] ) { + context.nodeType === 9 && documentIsHTML && Expr.relative[ tokens[1].type ] ) { context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0]; if ( !context ) { @@ -2625,17 +2698,17 @@ setDocument(); // Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) // Detached nodes confoundingly follow *each other* -support.sortDetached = assert(function( div1 ) { +support.sortDetached = assert(function( el ) { // Should return 1, but returns 4 (following) - return div1.compareDocumentPosition( document.createElement("div") ) & 1; + return el.compareDocumentPosition( document.createElement("fieldset") ) & 1; }); // Support: IE<8 // Prevent attribute/property "interpolation" -// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx -if ( !assert(function( div ) { - div.innerHTML = ""; - return div.firstChild.getAttribute("href") === "#" ; +// https://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx +if ( !assert(function( el ) { + el.innerHTML = ""; + return el.firstChild.getAttribute("href") === "#" ; }) ) { addHandle( "type|href|height|width", function( elem, name, isXML ) { if ( !isXML ) { @@ -2646,10 +2719,10 @@ if ( !assert(function( div ) { // Support: IE<9 // Use defaultValue in place of getAttribute("value") -if ( !support.attributes || !assert(function( div ) { - div.innerHTML = ""; - div.firstChild.setAttribute( "value", "" ); - return div.firstChild.getAttribute( "value" ) === ""; +if ( !support.attributes || !assert(function( el ) { + el.innerHTML = ""; + el.firstChild.setAttribute( "value", "" ); + return el.firstChild.getAttribute( "value" ) === ""; }) ) { addHandle( "value", function( elem, name, isXML ) { if ( !isXML && elem.nodeName.toLowerCase() === "input" ) { @@ -2660,8 +2733,8 @@ if ( !support.attributes || !assert(function( div ) { // Support: IE<9 // Use getAttributeNode to fetch booleans when getAttribute lies -if ( !assert(function( div ) { - return div.getAttribute("disabled") == null; +if ( !assert(function( el ) { + return el.getAttribute("disabled") == null; }) ) { addHandle( booleans, function( elem, name, isXML ) { var val; @@ -2682,11 +2755,15 @@ return Sizzle; jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; + +// Deprecated jQuery.expr[ ":" ] = jQuery.expr.pseudos; jQuery.uniqueSort = jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; +jQuery.escapeSelector = Sizzle.escape; + @@ -2721,40 +2798,41 @@ var siblings = function( n, elem ) { var rneedsContext = jQuery.expr.match.needsContext; -var rsingleTag = ( /^<([\w-]+)\s*\/?>(?:<\/\1>|)$/ ); +function nodeName( elem, name ) { + + return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); + +}; +var rsingleTag = ( /^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i ); + -var risSimple = /^.[^:#\[\.,]*$/; // Implement the identical functionality for filter and not function winnow( elements, qualifier, not ) { - if ( jQuery.isFunction( qualifier ) ) { + if ( isFunction( qualifier ) ) { return jQuery.grep( elements, function( elem, i ) { - /* jshint -W018 */ return !!qualifier.call( elem, i, elem ) !== not; } ); - } + // Single element if ( qualifier.nodeType ) { return jQuery.grep( elements, function( elem ) { return ( elem === qualifier ) !== not; } ); - } - if ( typeof qualifier === "string" ) { - if ( risSimple.test( qualifier ) ) { - return jQuery.filter( qualifier, elements, not ); - } - - qualifier = jQuery.filter( qualifier, elements ); + // Arraylike of elements (jQuery, arguments, Array) + if ( typeof qualifier !== "string" ) { + return jQuery.grep( elements, function( elem ) { + return ( indexOf.call( qualifier, elem ) > -1 ) !== not; + } ); } - return jQuery.grep( elements, function( elem ) { - return ( indexOf.call( qualifier, elem ) > -1 ) !== not; - } ); + // Filtered directly for both simple and complex selectors + return jQuery.filter( qualifier, elements, not ); } jQuery.filter = function( expr, elems, not ) { @@ -2764,18 +2842,19 @@ jQuery.filter = function( expr, elems, 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; - } ) ); + if ( elems.length === 1 && elem.nodeType === 1 ) { + return jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : []; + } + + return jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { + return elem.nodeType === 1; + } ) ); }; jQuery.fn.extend( { find: function( selector ) { - var i, + var i, ret, len = this.length, - ret = [], self = this; if ( typeof selector !== "string" ) { @@ -2788,14 +2867,13 @@ jQuery.fn.extend( { } ) ); } + ret = this.pushStack( [] ); + 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; + return len > 1 ? jQuery.uniqueSort( ret ) : ret; }, filter: function( selector ) { return this.pushStack( winnow( this, selector || [], false ) ); @@ -2827,7 +2905,8 @@ var rootjQuery, // A simple way to check for HTML strings // Prioritize #id over to avoid XSS via location.hash (#9521) // Strict HTML recognition (#11290: must start with <) - rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/, + // Shortcut simple #id case for speed + rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/, init = jQuery.fn.init = function( selector, context, root ) { var match, elem; @@ -2874,7 +2953,7 @@ var rootjQuery, for ( match in context ) { // Properties of context are called as methods if possible - if ( jQuery.isFunction( this[ match ] ) ) { + if ( isFunction( this[ match ] ) ) { this[ match ]( context[ match ] ); // ...and otherwise set as attributes @@ -2890,17 +2969,12 @@ var rootjQuery, } else { elem = document.getElementById( match[ 2 ] ); - // Support: Blackberry 4.6 - // gEBID returns nodes no longer in the document (#6963) - if ( elem && elem.parentNode ) { + if ( elem ) { // Inject the element directly into the jQuery object - this.length = 1; this[ 0 ] = elem; + this.length = 1; } - - this.context = document; - this.selector = selector; return this; } @@ -2916,13 +2990,13 @@ var rootjQuery, // HANDLE: $(DOMElement) } else if ( selector.nodeType ) { - this.context = this[ 0 ] = selector; + this[ 0 ] = selector; this.length = 1; return this; // HANDLE: $(function) // Shortcut for document ready - } else if ( jQuery.isFunction( selector ) ) { + } else if ( isFunction( selector ) ) { return root.ready !== undefined ? root.ready( selector ) : @@ -2930,11 +3004,6 @@ var rootjQuery, selector( jQuery ); } - if ( selector.selector !== undefined ) { - this.selector = selector.selector; - this.context = selector.context; - } - return jQuery.makeArray( selector, this ); }; @@ -2975,23 +3044,24 @@ jQuery.fn.extend( { i = 0, l = this.length, matched = [], - pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? - jQuery( selectors, context || this.context ) : - 0; + targets = typeof selectors !== "string" && jQuery( selectors ); - for ( ; i < l; i++ ) { - for ( cur = this[ i ]; cur && cur !== context; cur = cur.parentNode ) { + // Positional selectors never match, since there's no _selection_ context + if ( !rneedsContext.test( selectors ) ) { + 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 : + // Always skip document fragments + if ( cur.nodeType < 11 && ( targets ? + targets.index( cur ) > -1 : - // Don't pass non-elements to Sizzle - cur.nodeType === 1 && - jQuery.find.matchesSelector( cur, selectors ) ) ) { + // Don't pass non-elements to Sizzle + cur.nodeType === 1 && + jQuery.find.matchesSelector( cur, selectors ) ) ) { - matched.push( cur ); - break; + matched.push( cur ); + break; + } } } } @@ -3076,7 +3146,18 @@ jQuery.each( { return siblings( elem.firstChild ); }, contents: function( elem ) { - return elem.contentDocument || jQuery.merge( [], elem.childNodes ); + if ( nodeName( elem, "iframe" ) ) { + return elem.contentDocument; + } + + // Support: IE 9 - 11 only, iOS 7 only, Android Browser <=4.3 only + // Treat the template element as a regular one in browsers that + // don't support it. + if ( nodeName( elem, "template" ) ) { + elem = elem.content || elem; + } + + return jQuery.merge( [], elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { @@ -3106,14 +3187,14 @@ jQuery.each( { return this.pushStack( matched ); }; } ); -var rnotwhite = ( /\S+/g ); +var rnothtmlwhite = ( /[^\x20\t\r\n\f]+/g ); // Convert String-formatted options into Object-formatted ones function createOptions( options ) { var object = {}; - jQuery.each( options.match( rnotwhite ) || [], function( _, flag ) { + jQuery.each( options.match( rnothtmlwhite ) || [], function( _, flag ) { object[ flag ] = true; } ); return object; @@ -3174,7 +3255,7 @@ jQuery.Callbacks = function( options ) { fire = function() { // Enforce single-firing - locked = options.once; + locked = locked || options.once; // Execute callbacks for all pending executions, // respecting firingIndex overrides and runtime changes @@ -3230,11 +3311,11 @@ jQuery.Callbacks = function( options ) { ( function add( args ) { jQuery.each( args, function( _, arg ) { - if ( jQuery.isFunction( arg ) ) { + if ( isFunction( arg ) ) { if ( !options.unique || !self.has( arg ) ) { list.push( arg ); } - } else if ( arg && arg.length && jQuery.type( arg ) !== "string" ) { + } else if ( arg && arg.length && toType( arg ) !== "string" ) { // Inspect recursively add( arg ); @@ -3298,7 +3379,7 @@ jQuery.Callbacks = function( options ) { // Abort any pending executions lock: function() { locked = queue = []; - if ( !memory ) { + if ( !memory && !firing ) { list = memory = ""; } return this; @@ -3336,15 +3417,59 @@ jQuery.Callbacks = function( options ) { }; +function Identity( v ) { + return v; +} +function Thrower( ex ) { + throw ex; +} + +function adoptValue( value, resolve, reject, noValue ) { + var method; + + try { + + // Check for promise aspect first to privilege synchronous behavior + if ( value && isFunction( ( method = value.promise ) ) ) { + method.call( value ).done( resolve ).fail( reject ); + + // Other thenables + } else if ( value && isFunction( ( method = value.then ) ) ) { + method.call( value, resolve, reject ); + + // Other non-thenables + } else { + + // Control `resolve` arguments by letting Array#slice cast boolean `noValue` to integer: + // * false: [ value ].slice( 0 ) => resolve( value ) + // * true: [ value ].slice( 1 ) => resolve() + resolve.apply( undefined, [ value ].slice( noValue ) ); + } + + // For Promises/A+, convert exceptions into rejections + // Since jQuery.when doesn't unwrap thenables, we can skip the extra checks appearing in + // Deferred#then to conditionally suppress rejection. + } catch ( value ) { + + // Support: Android 4.0 only + // Strict mode functions invoked without .call/.apply get global-object context + reject.apply( undefined, [ value ] ); + } +} + 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" ) ] + // action, add listener, callbacks, + // ... .then handlers, argument index, [final state] + [ "notify", "progress", jQuery.Callbacks( "memory" ), + jQuery.Callbacks( "memory" ), 2 ], + [ "resolve", "done", jQuery.Callbacks( "once memory" ), + jQuery.Callbacks( "once memory" ), 0, "resolved" ], + [ "reject", "fail", jQuery.Callbacks( "once memory" ), + jQuery.Callbacks( "once memory" ), 1, "rejected" ] ], state = "pending", promise = { @@ -3355,23 +3480,33 @@ jQuery.extend( { deferred.done( arguments ).fail( arguments ); return this; }, - then: function( /* fnDone, fnFail, fnProgress */ ) { + "catch": function( fn ) { + return promise.then( null, fn ); + }, + + // Keep pipe for back-compat + pipe: function( /* fnDone, fnFail, fnProgress */ ) { var fns = arguments; + return jQuery.Deferred( function( newDefer ) { jQuery.each( tuples, function( i, tuple ) { - var fn = jQuery.isFunction( fns[ i ] ) && fns[ i ]; - // deferred[ done | fail | progress ] for forwarding actions to newDefer + // Map tuples (progress, done, fail) to arguments (done, fail, progress) + var fn = isFunction( fns[ tuple[ 4 ] ] ) && fns[ tuple[ 4 ] ]; + + // deferred.progress(function() { bind to newDefer or newDefer.notify }) + // deferred.done(function() { bind to newDefer or newDefer.resolve }) + // deferred.fail(function() { bind to newDefer or newDefer.reject }) deferred[ tuple[ 1 ] ]( function() { var returned = fn && fn.apply( this, arguments ); - if ( returned && jQuery.isFunction( returned.promise ) ) { + if ( returned && isFunction( returned.promise ) ) { returned.promise() .progress( newDefer.notify ) .done( newDefer.resolve ) .fail( newDefer.reject ); } else { newDefer[ tuple[ 0 ] + "With" ]( - this === promise ? newDefer.promise() : this, + this, fn ? [ returned ] : arguments ); } @@ -3380,6 +3515,170 @@ jQuery.extend( { fns = null; } ).promise(); }, + then: function( onFulfilled, onRejected, onProgress ) { + var maxDepth = 0; + function resolve( depth, deferred, handler, special ) { + return function() { + var that = this, + args = arguments, + mightThrow = function() { + var returned, then; + + // Support: Promises/A+ section 2.3.3.3.3 + // https://promisesaplus.com/#point-59 + // Ignore double-resolution attempts + if ( depth < maxDepth ) { + return; + } + + returned = handler.apply( that, args ); + + // Support: Promises/A+ section 2.3.1 + // https://promisesaplus.com/#point-48 + if ( returned === deferred.promise() ) { + throw new TypeError( "Thenable self-resolution" ); + } + + // Support: Promises/A+ sections 2.3.3.1, 3.5 + // https://promisesaplus.com/#point-54 + // https://promisesaplus.com/#point-75 + // Retrieve `then` only once + then = returned && + + // Support: Promises/A+ section 2.3.4 + // https://promisesaplus.com/#point-64 + // Only check objects and functions for thenability + ( typeof returned === "object" || + typeof returned === "function" ) && + returned.then; + + // Handle a returned thenable + if ( isFunction( then ) ) { + + // Special processors (notify) just wait for resolution + if ( special ) { + then.call( + returned, + resolve( maxDepth, deferred, Identity, special ), + resolve( maxDepth, deferred, Thrower, special ) + ); + + // Normal processors (resolve) also hook into progress + } else { + + // ...and disregard older resolution values + maxDepth++; + + then.call( + returned, + resolve( maxDepth, deferred, Identity, special ), + resolve( maxDepth, deferred, Thrower, special ), + resolve( maxDepth, deferred, Identity, + deferred.notifyWith ) + ); + } + + // Handle all other returned values + } else { + + // Only substitute handlers pass on context + // and multiple values (non-spec behavior) + if ( handler !== Identity ) { + that = undefined; + args = [ returned ]; + } + + // Process the value(s) + // Default process is resolve + ( special || deferred.resolveWith )( that, args ); + } + }, + + // Only normal processors (resolve) catch and reject exceptions + process = special ? + mightThrow : + function() { + try { + mightThrow(); + } catch ( e ) { + + if ( jQuery.Deferred.exceptionHook ) { + jQuery.Deferred.exceptionHook( e, + process.stackTrace ); + } + + // Support: Promises/A+ section 2.3.3.3.4.1 + // https://promisesaplus.com/#point-61 + // Ignore post-resolution exceptions + if ( depth + 1 >= maxDepth ) { + + // Only substitute handlers pass on context + // and multiple values (non-spec behavior) + if ( handler !== Thrower ) { + that = undefined; + args = [ e ]; + } + + deferred.rejectWith( that, args ); + } + } + }; + + // Support: Promises/A+ section 2.3.3.3.1 + // https://promisesaplus.com/#point-57 + // Re-resolve promises immediately to dodge false rejection from + // subsequent errors + if ( depth ) { + process(); + } else { + + // Call an optional hook to record the stack, in case of exception + // since it's otherwise lost when execution goes async + if ( jQuery.Deferred.getStackHook ) { + process.stackTrace = jQuery.Deferred.getStackHook(); + } + window.setTimeout( process ); + } + }; + } + + return jQuery.Deferred( function( newDefer ) { + + // progress_handlers.add( ... ) + tuples[ 0 ][ 3 ].add( + resolve( + 0, + newDefer, + isFunction( onProgress ) ? + onProgress : + Identity, + newDefer.notifyWith + ) + ); + + // fulfilled_handlers.add( ... ) + tuples[ 1 ][ 3 ].add( + resolve( + 0, + newDefer, + isFunction( onFulfilled ) ? + onFulfilled : + Identity + ) + ); + + // rejected_handlers.add( ... ) + tuples[ 2 ][ 3 ].add( + resolve( + 0, + newDefer, + isFunction( onRejected ) ? + onRejected : + Thrower + ) + ); + } ).promise(); + }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object @@ -3389,33 +3688,58 @@ jQuery.extend( { }, 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 ]; + stateString = tuple[ 5 ]; - // promise[ done | fail | progress ] = list.add + // promise.progress = list.add + // promise.done = list.add + // promise.fail = list.add promise[ tuple[ 1 ] ] = list.add; // Handle state if ( stateString ) { - list.add( function() { + list.add( + function() { - // state = [ resolved | rejected ] - state = stateString; + // state = "resolved" (i.e., fulfilled) + // state = "rejected" + state = stateString; + }, - // [ reject_list | resolve_list ].disable; progress_list.lock - }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); + // rejected_callbacks.disable + // fulfilled_callbacks.disable + tuples[ 3 - i ][ 2 ].disable, + + // rejected_handlers.disable + // fulfilled_handlers.disable + tuples[ 3 - i ][ 3 ].disable, + + // progress_callbacks.lock + tuples[ 0 ][ 2 ].lock, + + // progress_handlers.lock + tuples[ 0 ][ 3 ].lock + ); } - // deferred[ resolve | reject | notify ] + // progress_handlers.fire + // fulfilled_handlers.fire + // rejected_handlers.fire + list.add( tuple[ 3 ].fire ); + + // deferred.notify = function() { deferred.notifyWith(...) } + // deferred.resolve = function() { deferred.resolveWith(...) } + // deferred.reject = function() { deferred.rejectWith(...) } deferred[ tuple[ 0 ] ] = function() { - deferred[ tuple[ 0 ] + "With" ]( this === deferred ? promise : this, arguments ); + deferred[ tuple[ 0 ] + "With" ]( this === deferred ? undefined : this, arguments ); return this; }; + + // deferred.notifyWith = list.fireWith + // deferred.resolveWith = list.fireWith + // deferred.rejectWith = list.fireWith deferred[ tuple[ 0 ] + "With" ] = list.fireWith; } ); @@ -3432,68 +3756,95 @@ jQuery.extend( { }, // Deferred helper - when: function( subordinate /* , ..., subordinateN */ ) { - var i = 0, + when: function( singleValue ) { + var + + // count of uncompleted subordinates + remaining = arguments.length, + + // count of unprocessed arguments + i = remaining, + + // subordinate fulfillment data + resolveContexts = Array( i ), resolveValues = slice.call( arguments ), - length = resolveValues.length, - // the count of uncompleted subordinates - remaining = length !== 1 || - ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, + // the master Deferred + master = jQuery.Deferred(), - // 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 ) { + // subordinate callback factory + updateFunc = function( i ) { return function( value ) { - contexts[ i ] = this; - values[ i ] = arguments.length > 1 ? slice.call( arguments ) : value; - if ( values === progressValues ) { - deferred.notifyWith( contexts, values ); - } else if ( !( --remaining ) ) { - deferred.resolveWith( contexts, values ); + resolveContexts[ i ] = this; + resolveValues[ i ] = arguments.length > 1 ? slice.call( arguments ) : value; + if ( !( --remaining ) ) { + master.resolveWith( resolveContexts, resolveValues ); } }; - }, + }; - progressValues, progressContexts, resolveContexts; + // Single- and empty arguments are adopted like Promise.resolve + if ( remaining <= 1 ) { + adoptValue( singleValue, master.done( updateFunc( i ) ).resolve, master.reject, + !remaining ); - // 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() - .progress( updateFunc( i, progressContexts, progressValues ) ) - .done( updateFunc( i, resolveContexts, resolveValues ) ) - .fail( deferred.reject ); - } else { - --remaining; - } + // Use .then() to unwrap secondary thenables (cf. gh-3000) + if ( master.state() === "pending" || + isFunction( resolveValues[ i ] && resolveValues[ i ].then ) ) { + + return master.then(); } } - // If we're not waiting on anything, resolve the master - if ( !remaining ) { - deferred.resolveWith( resolveContexts, resolveValues ); + // Multiple arguments are aggregated like Promise.all array elements + while ( i-- ) { + adoptValue( resolveValues[ i ], updateFunc( i ), master.reject ); } - return deferred.promise(); + return master.promise(); } } ); +// These usually indicate a programmer mistake during development, +// warn about them ASAP rather than swallowing them by default. +var rerrorNames = /^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/; + +jQuery.Deferred.exceptionHook = function( error, stack ) { + + // Support: IE 8 - 9 only + // Console exists when dev tools are open, which can happen at any time + if ( window.console && window.console.warn && error && rerrorNames.test( error.name ) ) { + window.console.warn( "jQuery.Deferred exception: " + error.message, error.stack, stack ); + } +}; + + + + +jQuery.readyException = function( error ) { + window.setTimeout( function() { + throw error; + } ); +}; + + + + // The deferred used on DOM ready -var readyList; +var readyList = jQuery.Deferred(); jQuery.fn.ready = function( fn ) { - // Add the callback - jQuery.ready.promise().done( fn ); + readyList + .then( fn ) + + // Wrap jQuery.readyException in a function so that the lookup + // happens at the time of error handling instead of callback + // registration. + .catch( function( error ) { + jQuery.readyException( error ); + } ); return this; }; @@ -3507,15 +3858,6 @@ jQuery.extend( { // 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 ) { @@ -3534,53 +3876,36 @@ jQuery.extend( { // If there are functions bound, to execute readyList.resolveWith( document, [ jQuery ] ); - - // Trigger any bound ready events - if ( jQuery.fn.triggerHandler ) { - jQuery( document ).triggerHandler( "ready" ); - jQuery( document ).off( "ready" ); - } } } ); -/** - * The ready event handler and self cleanup method - */ +jQuery.ready.then = readyList.then; + +// The ready event handler and self cleanup method function completed() { document.removeEventListener( "DOMContentLoaded", completed ); window.removeEventListener( "load", completed ); jQuery.ready(); } -jQuery.ready.promise = function( obj ) { - if ( !readyList ) { +// Catch cases where $(document).ready() is called +// after the browser event has already occurred. +// Support: IE <=9 - 10 only +// Older IE sometimes signals "interactive" too soon +if ( document.readyState === "complete" || + ( document.readyState !== "loading" && !document.documentElement.doScroll ) ) { - readyList = jQuery.Deferred(); + // Handle it asynchronously to allow scripts the opportunity to delay ready + window.setTimeout( jQuery.ready ); - // Catch cases where $(document).ready() is called - // after the browser event has already occurred. - // Support: IE9-10 only - // Older IE sometimes signals "interactive" too soon - if ( document.readyState === "complete" || - ( document.readyState !== "loading" && !document.documentElement.doScroll ) ) { +} else { - // Handle it asynchronously to allow scripts the opportunity to delay ready - window.setTimeout( jQuery.ready ); + // Use the handy event callback + document.addEventListener( "DOMContentLoaded", completed ); - } else { - - // Use the handy event callback - document.addEventListener( "DOMContentLoaded", completed ); - - // A fallback to window.onload, that will always work - window.addEventListener( "load", completed ); - } - } - return readyList.promise( obj ); -}; - -// Kick off the DOM ready check even if the user does not -jQuery.ready.promise(); + // A fallback to window.onload, that will always work + window.addEventListener( "load", completed ); +} @@ -3593,7 +3918,7 @@ var access = function( elems, fn, key, value, chainable, emptyGet, raw ) { bulk = key == null; // Sets many values - if ( jQuery.type( key ) === "object" ) { + if ( toType( key ) === "object" ) { chainable = true; for ( i in key ) { access( elems, fn, i, key[ i ], true, emptyGet, raw ); @@ -3603,7 +3928,7 @@ var access = function( elems, fn, key, value, chainable, emptyGet, raw ) { } else if ( value !== undefined ) { chainable = true; - if ( !jQuery.isFunction( value ) ) { + if ( !isFunction( value ) ) { raw = true; } @@ -3634,14 +3959,34 @@ var access = function( elems, fn, key, value, chainable, emptyGet, raw ) { } } - return chainable ? - elems : + if ( chainable ) { + return elems; + } - // Gets - bulk ? - fn.call( elems ) : - len ? fn( elems[ 0 ], key ) : emptyGet; + // Gets + if ( bulk ) { + return fn.call( elems ); + } + + return len ? fn( elems[ 0 ], key ) : emptyGet; }; + + +// Matches dashed string for camelizing +var rmsPrefix = /^-ms-/, + rdashAlpha = /-([a-z])/g; + +// Used by camelCase as callback to replace() +function fcamelCase( all, letter ) { + return letter.toUpperCase(); +} + +// Convert dashed to camelCase; used by the css and data modules +// Support: IE <=9 - 11, Edge 12 - 15 +// Microsoft forgot to hump their vendor prefix (#9572) +function camelCase( string ) { + return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); +} var acceptData = function( owner ) { // Accepts only: @@ -3650,7 +3995,6 @@ var acceptData = function( owner ) { // - Node.DOCUMENT_NODE // - Object // - Any - /* jshint -W018 */ return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType ); }; @@ -3665,35 +4009,8 @@ Data.uid = 1; Data.prototype = { - register: function( owner, initial ) { - var value = initial || {}; - - // If it is a node unlikely to be stringify-ed or looped over - // use plain assignment - if ( owner.nodeType ) { - owner[ this.expando ] = value; - - // Otherwise secure it in a non-enumerable, non-writable property - // configurability must be true to allow the property to be - // deleted with the delete operator - } else { - Object.defineProperty( owner, this.expando, { - value: value, - writable: true, - configurable: true - } ); - } - return owner[ this.expando ]; - }, cache: function( owner ) { - // We can accept data for non-element nodes in modern browsers, - // but we should not, see #8335. - // Always return an empty object. - if ( !acceptData( owner ) ) { - return {}; - } - // Check if the owner object already has a cache var value = owner[ this.expando ]; @@ -3730,15 +4047,16 @@ Data.prototype = { cache = this.cache( owner ); // Handle: [ owner, key, value ] args + // Always use camelCase key (gh-2257) if ( typeof data === "string" ) { - cache[ data ] = value; + cache[ camelCase( data ) ] = value; // Handle: [ owner, { properties } ] args } else { // Copy the properties one-by-one to the cache object for ( prop in data ) { - cache[ prop ] = data[ prop ]; + cache[ camelCase( prop ) ] = data[ prop ]; } } return cache; @@ -3746,10 +4064,11 @@ Data.prototype = { get: function( owner, key ) { return key === undefined ? this.cache( owner ) : - owner[ this.expando ] && owner[ this.expando ][ key ]; + + // Always use camelCase key (gh-2257) + owner[ this.expando ] && owner[ this.expando ][ camelCase( key ) ]; }, access: function( owner, key, value ) { - var stored; // In cases where either: // @@ -3765,10 +4084,7 @@ Data.prototype = { if ( key === undefined || ( ( key && typeof key === "string" ) && value === undefined ) ) { - stored = this.get( owner, key ); - - return stored !== undefined ? - stored : this.get( owner, jQuery.camelCase( key ) ); + return this.get( owner, key ); } // When the key is not a string, or both a key and value @@ -3784,58 +4100,45 @@ Data.prototype = { return value !== undefined ? value : key; }, remove: function( owner, key ) { - var i, name, camel, + var i, cache = owner[ this.expando ]; if ( cache === undefined ) { return; } - if ( key === undefined ) { - this.register( owner ); - - } else { + if ( key !== undefined ) { // Support array or space separated string of keys - if ( jQuery.isArray( key ) ) { + if ( Array.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 ) ); + // If key is an array of keys... + // We always set camelCase keys, so remove that. + key = key.map( camelCase ); } else { - camel = jQuery.camelCase( key ); + key = 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( rnotwhite ) || [] ); - } + // If a key with the spaces exists, use it. + // Otherwise, create an array by matching non-whitespace + key = key in cache ? + [ key ] : + ( key.match( rnothtmlwhite ) || [] ); } - i = name.length; + i = key.length; while ( i-- ) { - delete cache[ name[ i ] ]; + delete cache[ key[ i ] ]; } } // Remove the expando if there's no more data if ( key === undefined || jQuery.isEmptyObject( cache ) ) { - // Support: Chrome <= 35-45+ + // Support: Chrome <=35 - 45 // Webkit & Blink performance suffers when deleting properties // from DOM nodes, so set to undefined instead - // https://code.google.com/p/chromium/issues/detail?id=378607 + // https://bugs.chromium.org/p/chromium/issues/detail?id=378607 (bug restricted) if ( owner.nodeType ) { owner[ this.expando ] = undefined; } else { @@ -3867,6 +4170,31 @@ var dataUser = new Data(); var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/, rmultiDash = /[A-Z]/g; +function getData( data ) { + if ( data === "true" ) { + return true; + } + + if ( data === "false" ) { + return false; + } + + if ( data === "null" ) { + return null; + } + + // Only convert to a number if it doesn't change the string + if ( data === +data + "" ) { + return +data; + } + + if ( rbrace.test( data ) ) { + return JSON.parse( data ); + } + + return data; +} + function dataAttr( elem, key, data ) { var name; @@ -3878,14 +4206,7 @@ function dataAttr( elem, key, data ) { 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 ) ? jQuery.parseJSON( data ) : - data; + data = getData( data ); } catch ( e ) {} // Make sure we set the data so it isn't changed later @@ -3936,12 +4257,12 @@ jQuery.fn.extend( { i = attrs.length; while ( i-- ) { - // Support: IE11+ + // Support: IE 11 only // The attrs elements can be null (#14894) if ( attrs[ i ] ) { name = attrs[ i ].name; if ( name.indexOf( "data-" ) === 0 ) { - name = jQuery.camelCase( name.slice( 5 ) ); + name = camelCase( name.slice( 5 ) ); dataAttr( elem, name, data[ name ] ); } } @@ -3961,7 +4282,7 @@ jQuery.fn.extend( { } return access( this, function( value ) { - var data, camelKey; + var data; // The calling jQuery object (element matches) is not empty // (and therefore has an element appears at this[ 0 ]) and the @@ -3971,29 +4292,15 @@ jQuery.fn.extend( { if ( elem && value === undefined ) { // Attempt to get data from the cache - // with the key as-is - data = dataUser.get( elem, key ) || - - // Try to find dashed key if it exists (gh-2779) - // This is for 2.2.x only - dataUser.get( elem, key.replace( rmultiDash, "-$&" ).toLowerCase() ); - - if ( data !== undefined ) { - return data; - } - - camelKey = jQuery.camelCase( key ); - - // Attempt to get data from the cache - // with the key camelized - data = dataUser.get( elem, camelKey ); + // The key will always be camelCased in Data + data = dataUser.get( elem, key ); if ( data !== undefined ) { return data; } // Attempt to "discover" the data in // HTML5 custom data-* attrs - data = dataAttr( elem, camelKey, undefined ); + data = dataAttr( elem, key ); if ( data !== undefined ) { return data; } @@ -4003,24 +4310,10 @@ jQuery.fn.extend( { } // Set the data... - camelKey = jQuery.camelCase( key ); 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 = dataUser.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...* - dataUser.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 ) { - dataUser.set( this, key, value ); - } + // We always store the camelCased key + dataUser.set( this, key, value ); } ); }, null, value, arguments.length > 1, null, true ); }, @@ -4043,7 +4336,7 @@ jQuery.extend( { // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { - if ( !queue || jQuery.isArray( data ) ) { + if ( !queue || Array.isArray( data ) ) { queue = dataPriv.access( elem, type, jQuery.makeArray( data ) ); } else { queue.push( data ); @@ -4173,24 +4466,58 @@ var rcssNum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" ); var cssExpand = [ "Top", "Right", "Bottom", "Left" ]; -var isHidden = function( elem, el ) { +var isHiddenWithinTree = function( elem, el ) { - // isHidden might be called from jQuery#filter function; + // isHiddenWithinTree might be called from jQuery#filter function; // in that case, element will be second argument elem = el || elem; - return jQuery.css( elem, "display" ) === "none" || - !jQuery.contains( elem.ownerDocument, elem ); + + // Inline style trumps all + return elem.style.display === "none" || + elem.style.display === "" && + + // Otherwise, check computed style + // Support: Firefox <=43 - 45 + // Disconnected elements can have computed display: none, so first confirm that elem is + // in the document. + jQuery.contains( elem.ownerDocument, elem ) && + + jQuery.css( elem, "display" ) === "none"; }; +var 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; +}; + + function adjustCSS( elem, prop, valueParts, tween ) { - var adjusted, - scale = 1, + var adjusted, scale, maxIterations = 20, currentValue = tween ? - function() { return tween.cur(); } : - function() { return jQuery.css( elem, prop, "" ); }, + function() { + return tween.cur(); + } : + function() { + return jQuery.css( elem, prop, "" ); + }, initial = currentValue(), unit = valueParts && valueParts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ), @@ -4200,30 +4527,33 @@ function adjustCSS( elem, prop, valueParts, tween ) { if ( initialInUnit && initialInUnit[ 3 ] !== unit ) { + // Support: Firefox <=54 + // Halve the iteration target value to prevent interference from CSS upper bounds (gh-2144) + initial = initial / 2; + // Trust units reported by jQuery.css unit = unit || initialInUnit[ 3 ]; - // Make sure we update the tween properties later on - valueParts = valueParts || []; - // Iteratively approximate from a nonzero starting point initialInUnit = +initial || 1; - do { + while ( maxIterations-- ) { - // If previous iteration zeroed out, double until we get *something*. - // Use string for doubling so we don't accidentally see scale as unchanged below - scale = scale || ".5"; - - // Adjust and apply - initialInUnit = initialInUnit / scale; + // Evaluate and update our best guess (doubling guesses that zero out). + // Finish if the scale equals or crosses 1 (making the old*new product non-positive). jQuery.style( elem, prop, initialInUnit + unit ); + if ( ( 1 - scale ) * ( 1 - ( scale = currentValue() / initial || 0.5 ) ) <= 0 ) { + maxIterations = 0; + } + initialInUnit = initialInUnit / scale; - // Update scale, tolerating zero or NaN from tween.cur() - // Break the loop if scale is unchanged or perfect, or if we've just had enough. - } while ( - scale !== ( scale = currentValue() / initial ) && scale !== 1 && --maxIterations - ); + } + + initialInUnit = initialInUnit * 2; + jQuery.style( elem, prop, initialInUnit + unit ); + + // Make sure we update the tween properties later on + valueParts = valueParts || []; } if ( valueParts ) { @@ -4241,18 +4571,114 @@ function adjustCSS( elem, prop, valueParts, tween ) { } return adjusted; } + + +var defaultDisplayMap = {}; + +function getDefaultDisplay( elem ) { + var temp, + doc = elem.ownerDocument, + nodeName = elem.nodeName, + display = defaultDisplayMap[ nodeName ]; + + if ( display ) { + return display; + } + + temp = doc.body.appendChild( doc.createElement( nodeName ) ); + display = jQuery.css( temp, "display" ); + + temp.parentNode.removeChild( temp ); + + if ( display === "none" ) { + display = "block"; + } + defaultDisplayMap[ nodeName ] = display; + + return display; +} + +function showHide( elements, show ) { + var display, elem, + values = [], + index = 0, + length = elements.length; + + // Determine new display value for elements that need to change + for ( ; index < length; index++ ) { + elem = elements[ index ]; + if ( !elem.style ) { + continue; + } + + display = elem.style.display; + if ( show ) { + + // Since we force visibility upon cascade-hidden elements, an immediate (and slow) + // check is required in this first loop unless we have a nonempty display value (either + // inline or about-to-be-restored) + if ( display === "none" ) { + values[ index ] = dataPriv.get( elem, "display" ) || null; + if ( !values[ index ] ) { + elem.style.display = ""; + } + } + if ( elem.style.display === "" && isHiddenWithinTree( elem ) ) { + values[ index ] = getDefaultDisplay( elem ); + } + } else { + if ( display !== "none" ) { + values[ index ] = "none"; + + // Remember what we're overwriting + dataPriv.set( elem, "display", display ); + } + } + } + + // Set the display of the elements in a second loop to avoid constant reflow + for ( index = 0; index < length; index++ ) { + if ( values[ index ] != null ) { + elements[ index ].style.display = values[ index ]; + } + } + + return elements; +} + +jQuery.fn.extend( { + show: function() { + return showHide( this, true ); + }, + hide: function() { + return showHide( this ); + }, + toggle: function( state ) { + if ( typeof state === "boolean" ) { + return state ? this.show() : this.hide(); + } + + return this.each( function() { + if ( isHiddenWithinTree( this ) ) { + jQuery( this ).show(); + } else { + jQuery( this ).hide(); + } + } ); + } +} ); var rcheckableType = ( /^(?:checkbox|radio)$/i ); -var rtagName = ( /<([\w:-]+)/ ); +var rtagName = ( /<([a-z][^\/\0>\x20\t\r\n\f]+)/i ); -var rscriptType = ( /^$|\/(?:java|ecma)script/i ); +var rscriptType = ( /^$|^module$|\/(?:java|ecma)script/i ); // We have to close these tags to support XHTML (#13200) var wrapMap = { - // Support: IE9 + // Support: IE <=9 only option: [ 1, "" ], // XHTML parsers do not magically insert elements in the @@ -4266,7 +4692,7 @@ var wrapMap = { _default: [ 0, "", "" ] }; -// Support: IE9 +// Support: IE <=9 only wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; @@ -4275,17 +4701,25 @@ wrapMap.th = wrapMap.td; function getAll( context, tag ) { - // Support: IE9-11+ + // Support: IE <=9 - 11 only // Use typeof to avoid zero-argument method invocation on host objects (#15151) - var ret = typeof context.getElementsByTagName !== "undefined" ? - context.getElementsByTagName( tag || "*" ) : - typeof context.querySelectorAll !== "undefined" ? - context.querySelectorAll( tag || "*" ) : - []; + var ret; - return tag === undefined || tag && jQuery.nodeName( context, tag ) ? - jQuery.merge( [ context ], ret ) : - ret; + if ( typeof context.getElementsByTagName !== "undefined" ) { + ret = context.getElementsByTagName( tag || "*" ); + + } else if ( typeof context.querySelectorAll !== "undefined" ) { + ret = context.querySelectorAll( tag || "*" ); + + } else { + ret = []; + } + + if ( tag === undefined || tag && nodeName( context, tag ) ) { + return jQuery.merge( [ context ], ret ); + } + + return ret; } @@ -4319,9 +4753,9 @@ function buildFragment( elems, context, scripts, selection, ignored ) { if ( elem || elem === 0 ) { // Add nodes directly - if ( jQuery.type( elem ) === "object" ) { + if ( toType( elem ) === "object" ) { - // Support: Android<4.1, PhantomJS<2 + // Support: Android <=4.0 only, PhantomJS 1 only // push.apply(_, arraylike) throws on ancient WebKit jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); @@ -4344,7 +4778,7 @@ function buildFragment( elems, context, scripts, selection, ignored ) { tmp = tmp.lastChild; } - // Support: Android<4.1, PhantomJS<2 + // Support: Android <=4.0 only, PhantomJS 1 only // push.apply(_, arraylike) throws on ancient WebKit jQuery.merge( nodes, tmp.childNodes ); @@ -4401,7 +4835,7 @@ function buildFragment( elems, context, scripts, selection, ignored ) { div = fragment.appendChild( document.createElement( "div" ) ), input = document.createElement( "input" ); - // Support: Android 4.0-4.3, Safari<=5.1 + // Support: Android 4.0 - 4.3 only // Check state lost if the name is set (#11217) // Support: Windows Web Apps (WWA) // `name` and `type` must use .setAttribute for WWA (#14901) @@ -4411,15 +4845,17 @@ function buildFragment( elems, context, scripts, selection, ignored ) { div.appendChild( input ); - // Support: Safari<=5.1, Android<4.2 + // Support: Android <=4.1 only // Older WebKit doesn't clone checked state correctly in fragments support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked; - // Support: IE<=11+ + // Support: IE <=11 only // Make sure textarea (and checkbox) defaultValue is properly cloned div.innerHTML = ""; support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue; } )(); +var documentElement = document.documentElement; + var @@ -4435,7 +4871,7 @@ function returnFalse() { return false; } -// Support: IE9 +// Support: IE <=9 only // See #13393 for more info function safeActiveElement() { try { @@ -4531,6 +4967,12 @@ jQuery.event = { selector = handleObjIn.selector; } + // Ensure that invalid selectors throw exceptions at attach time + // Evaluate against documentElement in case elem is a non-element node (e.g., document) + if ( selector ) { + jQuery.find.matchesSelector( documentElement, selector ); + } + // Make sure that the handler has a unique ID, used to find/remove it later if ( !handler.guid ) { handler.guid = jQuery.guid++; @@ -4551,7 +4993,7 @@ jQuery.event = { } // Handle multiple events separated by a space - types = ( types || "" ).match( rnotwhite ) || [ "" ]; + types = ( types || "" ).match( rnothtmlwhite ) || [ "" ]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[ t ] ) || []; @@ -4633,7 +5075,7 @@ jQuery.event = { } // Once for each type.namespace in types; type may be omitted - types = ( types || "" ).match( rnotwhite ) || [ "" ]; + types = ( types || "" ).match( rnothtmlwhite ) || [ "" ]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[ t ] ) || []; @@ -4694,19 +5136,23 @@ jQuery.event = { } }, - dispatch: function( event ) { + dispatch: function( nativeEvent ) { // Make a writable jQuery.Event from the native event object - event = jQuery.event.fix( event ); + var event = jQuery.event.fix( nativeEvent ); - var i, j, ret, matched, handleObj, - handlerQueue = [], - args = slice.call( arguments ), + var i, j, ret, matched, handleObj, handlerQueue, + args = new Array( arguments.length ), handlers = ( dataPriv.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; + + for ( i = 1; i < arguments.length; i++ ) { + args[ i ] = arguments[ i ]; + } + event.delegateTarget = this; // Call the preDispatch hook for the mapped type, and let it bail if desired @@ -4755,146 +5201,95 @@ jQuery.event = { }, handlers: function( event, handlers ) { - var i, matches, sel, handleObj, + var i, handleObj, sel, matchedHandlers, matchedSelectors, handlerQueue = [], delegateCount = handlers.delegateCount, cur = event.target; - // Support (at least): Chrome, IE9 // Find delegate handlers - // Black-hole SVG instance trees (#13180) - // - // Support: Firefox<=42+ - // Avoid non-left-click in FF but don't block IE radio events (#3861, gh-2343) - if ( delegateCount && cur.nodeType && - ( event.type !== "click" || isNaN( event.button ) || event.button < 1 ) ) { + if ( delegateCount && + + // Support: IE <=9 + // Black-hole SVG instance trees (trac-13180) + cur.nodeType && + + // Support: Firefox <=42 + // Suppress spec-violating clicks indicating a non-primary pointer button (trac-3861) + // https://www.w3.org/TR/DOM-Level-3-Events/#event-type-click + // Support: IE 11 only + // ...but not arrow key "clicks" of radio inputs, which can have `button` -1 (gh-2343) + !( event.type === "click" && event.button >= 1 ) ) { for ( ; cur !== this; cur = cur.parentNode || this ) { // Don't check non-elements (#13208) // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) - if ( cur.nodeType === 1 && ( cur.disabled !== true || event.type !== "click" ) ) { - matches = []; + if ( cur.nodeType === 1 && !( event.type === "click" && cur.disabled === true ) ) { + matchedHandlers = []; + matchedSelectors = {}; 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 ? + if ( matchedSelectors[ sel ] === undefined ) { + matchedSelectors[ sel ] = handleObj.needsContext ? jQuery( sel, this ).index( cur ) > -1 : jQuery.find( sel, this, null, [ cur ] ).length; } - if ( matches[ sel ] ) { - matches.push( handleObj ); + if ( matchedSelectors[ sel ] ) { + matchedHandlers.push( handleObj ); } } - if ( matches.length ) { - handlerQueue.push( { elem: cur, handlers: matches } ); + if ( matchedHandlers.length ) { + handlerQueue.push( { elem: cur, handlers: matchedHandlers } ); } } } } // Add the remaining (directly-bound) handlers + cur = this; if ( delegateCount < handlers.length ) { - handlerQueue.push( { elem: this, handlers: handlers.slice( delegateCount ) } ); + handlerQueue.push( { elem: cur, handlers: handlers.slice( delegateCount ) } ); } return handlerQueue; }, - // Includes some event props shared by KeyEvent and MouseEvent - props: ( "altKey bubbles cancelable ctrlKey currentTarget detail eventPhase " + - "metaKey relatedTarget shiftKey target timeStamp view which" ).split( " " ), + addProp: function( name, hook ) { + Object.defineProperty( jQuery.Event.prototype, name, { + enumerable: true, + configurable: true, - fixHooks: {}, + get: isFunction( hook ) ? + function() { + if ( this.originalEvent ) { + return hook( this.originalEvent ); + } + } : + function() { + if ( this.originalEvent ) { + return this.originalEvent[ name ]; + } + }, - 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; + set: function( value ) { + Object.defineProperty( this, name, { + enumerable: true, + configurable: true, + writable: true, + value: value + } ); } - - 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; + fix: function( originalEvent ) { + return originalEvent[ jQuery.expando ] ? + originalEvent : + new jQuery.Event( originalEvent ); }, special: { @@ -4927,7 +5322,7 @@ jQuery.event = { // For checkbox, fire native event so checked state will be right trigger: function() { - if ( this.type === "checkbox" && this.click && jQuery.nodeName( this, "input" ) ) { + if ( this.type === "checkbox" && this.click && nodeName( this, "input" ) ) { this.click(); return false; } @@ -4935,7 +5330,7 @@ jQuery.event = { // For cross-browser consistency, don't fire native .click() on links _default: function( event ) { - return jQuery.nodeName( event.target, "a" ); + return nodeName( event.target, "a" ); } }, @@ -4977,11 +5372,21 @@ jQuery.Event = function( src, props ) { this.isDefaultPrevented = src.defaultPrevented || src.defaultPrevented === undefined && - // Support: Android<4.0 + // Support: Android <=2.3 only src.returnValue === false ? returnTrue : returnFalse; + // Create target properties + // Support: Safari <=6 - 7 only + // Target should not be a text node (#504, #13143) + this.target = ( src.target && src.target.nodeType === 3 ) ? + src.target.parentNode : + src.target; + + this.currentTarget = src.currentTarget; + this.relatedTarget = src.relatedTarget; + // Event type } else { this.type = src; @@ -4993,14 +5398,14 @@ jQuery.Event = function( src, props ) { } // Create a timestamp if incoming event doesn't have one - this.timeStamp = src && src.timeStamp || jQuery.now(); + this.timeStamp = src && src.timeStamp || Date.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 +// https://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { constructor: jQuery.Event, isDefaultPrevented: returnFalse, @@ -5039,13 +5444,74 @@ jQuery.Event.prototype = { } }; +// Includes all common event props including KeyEvent and MouseEvent specific props +jQuery.each( { + altKey: true, + bubbles: true, + cancelable: true, + changedTouches: true, + ctrlKey: true, + detail: true, + eventPhase: true, + metaKey: true, + pageX: true, + pageY: true, + shiftKey: true, + view: true, + "char": true, + charCode: true, + key: true, + keyCode: true, + button: true, + buttons: true, + clientX: true, + clientY: true, + offsetX: true, + offsetY: true, + pointerId: true, + pointerType: true, + screenX: true, + screenY: true, + targetTouches: true, + toElement: true, + touches: true, + + which: function( event ) { + var button = event.button; + + // Add which for key events + if ( event.which == null && rkeyEvent.test( event.type ) ) { + return event.charCode != null ? event.charCode : event.keyCode; + } + + // Add which for click: 1 === left; 2 === middle; 3 === right + if ( !event.which && button !== undefined && rmouseEvent.test( event.type ) ) { + if ( button & 1 ) { + return 1; + } + + if ( button & 2 ) { + return 3; + } + + if ( button & 4 ) { + return 2; + } + + return 0; + } + + return event.which; + } +}, jQuery.event.addProp ); + // Create mouseenter/leave events using mouseover/out and event-time checks // so that event delegation works in jQuery. // Do the same for pointerenter/pointerleave and pointerover/pointerout // // Support: Safari 7 only // Safari sends mouseenter too often; see: -// https://code.google.com/p/chromium/issues/detail?id=470258 +// https://bugs.chromium.org/p/chromium/issues/detail?id=470258 // for the description of the bug (it existed in older Chrome versions as well). jQuery.each( { mouseenter: "mouseover", @@ -5076,6 +5542,7 @@ jQuery.each( { } ); jQuery.fn.extend( { + on: function( types, selector, data, fn ) { return on( this, types, selector, data, fn ); }, @@ -5122,26 +5589,32 @@ jQuery.fn.extend( { var - rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:-]+)[^>]*)\/>/gi, - // Support: IE 10-11, Edge 10240+ + /* eslint-disable max-len */ + + // See https://github.com/eslint/eslint/issues/3229 + rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([a-z][^\/\0>\x20\t\r\n\f]*)[^>]*)\/>/gi, + + /* eslint-enable */ + + // Support: IE <=10 - 11, Edge 12 - 13 only // In IE/Edge using regex groups here causes severe slowdowns. // See https://connect.microsoft.com/IE/feedback/details/1736512/ rnoInnerhtml = /\s*$/g; -// Manipulating tables requires a tbody +// Prefer a tbody over its parent table for containing new rows function manipulationTarget( elem, content ) { - return jQuery.nodeName( elem, "table" ) && - jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ? + if ( nodeName( elem, "table" ) && + nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ) { - elem.getElementsByTagName( "tbody" )[ 0 ] || - elem.appendChild( elem.ownerDocument.createElement( "tbody" ) ) : - elem; + return jQuery( elem ).children( "tbody" )[ 0 ] || elem; + } + + return elem; } // Replace/restore the type attribute of script elements for safe DOM manipulation @@ -5150,10 +5623,8 @@ function disableScript( elem ) { return elem; } function restoreScript( elem ) { - var match = rscriptTypeMasked.exec( elem.type ); - - if ( match ) { - elem.type = match[ 1 ]; + if ( ( elem.type || "" ).slice( 0, 5 ) === "true/" ) { + elem.type = elem.type.slice( 5 ); } else { elem.removeAttribute( "type" ); } @@ -5219,15 +5690,15 @@ function domManip( collection, args, callback, ignored ) { l = collection.length, iNoClone = l - 1, value = args[ 0 ], - isFunction = jQuery.isFunction( value ); + valueIsFunction = isFunction( value ); // We can't cloneNode fragments that contain checked, in WebKit - if ( isFunction || + if ( valueIsFunction || ( l > 1 && typeof value === "string" && !support.checkClone && rchecked.test( value ) ) ) { return collection.each( function( index ) { var self = collection.eq( index ); - if ( isFunction ) { + if ( valueIsFunction ) { args[ 0 ] = value.call( this, index, self.html() ); } domManip( self, args, callback, ignored ); @@ -5259,7 +5730,7 @@ function domManip( collection, args, callback, ignored ) { // Keep references to cloned scripts for later restoration if ( hasScripts ) { - // Support: Android<4.1, PhantomJS<2 + // Support: Android <=4.0 only, PhantomJS 1 only // push.apply(_, arraylike) throws on ancient WebKit jQuery.merge( scripts, getAll( node, "script" ) ); } @@ -5281,14 +5752,14 @@ function domManip( collection, args, callback, ignored ) { !dataPriv.access( node, "globalEval" ) && jQuery.contains( doc, node ) ) { - if ( node.src ) { + if ( node.src && ( node.type || "" ).toLowerCase() !== "module" ) { // Optional AJAX dependency, but won't run scripts if not present if ( jQuery._evalUrl ) { jQuery._evalUrl( node.src ); } } else { - jQuery.globalEval( node.textContent.replace( rcleanScript, "" ) ); + DOMEval( node.textContent.replace( rcleanScript, "" ), doc, node ); } } } @@ -5334,7 +5805,7 @@ jQuery.extend( { if ( !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 + // We eschew Sizzle here for performance reasons: https://jsperf.com/getall-vs-sizzle/2 destElements = getAll( clone ); srcElements = getAll( elem ); @@ -5387,13 +5858,13 @@ jQuery.extend( { } } - // Support: Chrome <= 35-45+ + // Support: Chrome <=35 - 45+ // Assign undefined instead of using delete, see Data#remove elem[ dataPriv.expando ] = undefined; } if ( elem[ dataUser.expando ] ) { - // Support: Chrome <= 35-45+ + // Support: Chrome <=35 - 45+ // Assign undefined instead of using delete, see Data#remove elem[ dataUser.expando ] = undefined; } @@ -5403,10 +5874,6 @@ jQuery.extend( { } ); jQuery.fn.extend( { - - // Keep domManip exposed until 3.0 (gh-2225) - domManip: domManip, - detach: function( selector ) { return remove( this, selector, true ); }, @@ -5564,86 +6031,19 @@ jQuery.each( { elems = i === last ? this : this.clone( true ); jQuery( insert[ i ] )[ original ]( elems ); - // Support: QtWebKit - // .get() because push.apply(_, arraylike) throws + // Support: Android <=4.0 only, PhantomJS 1 only + // .get() because push.apply(_, arraylike) throws on ancient WebKit push.apply( ret, elems.get() ); } return this.pushStack( ret ); }; } ); - - -var iframe, - elemdisplay = { - - // Support: Firefox - // We have to pre-define these values for FF (#10227) - HTML: "block", - BODY: "block" - }; - -/** - * Retrieve the actual display of a element - * @param {String} name nodeName of the element - * @param {Object} doc Document object - */ - -// Called only from within defaultDisplay -function actualDisplay( name, doc ) { - var elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ), - - display = jQuery.css( elem[ 0 ], "display" ); - - // We don't have any data stored on the element, - // so use "detach" method as fast way to get rid of the element - elem.detach(); - - return display; -} - -/** - * Try to determine the default display value of an element - * @param {String} nodeName - */ -function defaultDisplay( nodeName ) { - var doc = document, - display = elemdisplay[ nodeName ]; - - if ( !display ) { - display = actualDisplay( nodeName, doc ); - - // If the simple way fails, read from inside an iframe - if ( display === "none" || !display ) { - - // Use the already-created iframe if possible - iframe = ( iframe || jQuery( "