You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@wicket.apache.org by re...@apache.org on 2026/09/12 19:36:47 UTC
(wicket) 02/02: Add a jQuery-free implementation of Wicket's client-side Ajax engine
This is an automated email from the ASF dual-hosted git repository.
reiern70 pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/wicket.git
commit 615af3ee958379781cc9a416ce0ebd7e6ae31248
Author: reiern70 <re...@gmail.com>
AuthorDate: Sat Sep 12 14:08:20 2026 -0500
Add a jQuery-free implementation of Wicket's client-side Ajax engine
Wicket's client-side Ajax and event support (Wicket.Ajax, Wicket.Event,
Wicket.DOM, Wicket.Form, Wicket.Head, Wicket.Focus, ...) has always required
jQuery. This adds a second, plain-JavaScript implementation exposing the exact
same public API, so an application that does not want to ship jQuery at all can
opt in with:
getJavaScriptLibrarySettings()
.setWicketAjaxReference(WicketAjaxVanillaResourceReference.get());
jQuery remains the default and the jQuery engine itself is unchanged, so an
application that does not make that call sees no difference.
The engine
wicket-ajax.js is a full port of wicket-ajax-jquery.js onto native
XMLHttpRequest, DOM and event APIs, with WicketAjaxVanillaResourceReference as
its resource reference. jQuery is also gone from every other framework
JavaScript file that used it incidentally rather than as its implementation
choice - the extensions Ajax components (autocomplete, palette, upload progress
bar, Ajax download, trap focus), the development debug bar, native WebSocket
support and FileUploadToResourceField.js - so the whole stack can run without
jQuery once the vanilla engine is selected. Their public extension points and
callback signatures are unchanged and they still work under the default engine.
Dead legacy-browser fallbacks and deprecated Web APIs met along the way are
removed: window.escape/unescape, window.event, Attr.specified and the IE-only
branches.
Framework JavaScript now declares with const and let rather than var and builds
strings with template literals. That makes ECMAScript 2015 the input language of
the minifier, hence languageIn in the closure-compiler configuration.
Testing
The wicket-core QUnit suite (ajax, channels, dom, event, form, head, timer) no
longer relies on jQuery-based test-authoring helpers, so the same tests run
against either engine: all.html accepts ?vanilla alongside ?<jquery-version> and
the Gruntfile has a matching qunit:vanilla target. JAVASCRIPTTESTING.md
describes how to run it.
The CI step that installed the browser dependencies could not work on Ubuntu
24.04: chromium-browser there is a transitional package that pre-depends on
snapd, several of the names it listed are now virtual or transitional
(libatk1.0-0, libatk-bridge2.0-0, libcups2, libglib2.0-0, libgtk-3-0, libgcc1,
libgdk-pixbuf2.0-0, libappindicator3-1), and three libraries current Chrome
needs were absent (libdrm2, libvulkan1, libxkbcommon0). Puppeteer downloads its
own Chrome, so no browser package is needed: the step now installs that
browser's shared libraries only, under the names Ubuntu 24.04 actually carries.
Examples
The examples can be started with either engine through one JVM-wide switch
(-Dwicket.examples.use=JQUERY|VANILLA, default JQUERY) applied by
AjaxEngineSelector from every example application's init(), and the shared page
header shows the active engine and lets a visitor switch it for their session
alone, live, without a restart.
That switch is resolved at the source, by giving the application a
JavaScriptLibrarySettings whose getWicketAjaxReference() returns the reference
for the session's choice on every call. Doing it afterwards with an
IHeaderResponseDecorator could not survive a strict CSP: the decorator and
CSPNonceHeaderResponseDecorator are both registered for pre-resource
aggregation and CSP registers later, from WebApplication#validateInit, so CSP
ended up upstream - it stamped the nonce onto the item the selector then threw
away and rendered a fresh JavaScriptHeaderItem with a null nonce in its place.
Under script-src 'strict-dynamic' 'nonce-XYZ' the browser blocked that script,
which is why the examples had CSP turned off; it is turned back on here.
Resolving at the source also stops the aggregator pulling jQuery back in behind
the decorator's back through the dependency that OnDomReadyHeaderItem,
OnLoadHeaderItem and OnEventHeaderItem declare on the configured reference, so a
session switched to the vanilla engine no longer downloads jQuery at all. The
settings instance is shared between sessions but holds no state - it forwards to
whatever Session#get() resolves to on the calling thread - so concurrent
sessions with different choices still do not interfere.
The examples also move from the custom jquery-ui 1.10.3 build to 1.14.2.
The user guide gains a section on the two implementations and how to choose
between them (ajax_11.adoc), and IAjaxCallListener, ajax_5 and ajax_6 no longer
state that jqXHR and jqEvent are always jQuery-specific objects.
GitHub issue #1583: https://github.com/apache/wicket/issues/1583
---
.github/workflows/maven.yml | 42 +-
.gitignore | 4 +
JAVASCRIPTTESTING.md | 95 +
pom.xml | 1 +
testing/wicket-js-tests/Gruntfile.js | 26 +-
.../wicket/ajax/WicketAjaxResourceReference.java | 54 +
.../wicket/ajax/attributes/IAjaxCallListener.java | 19 +-
.../wicket/ajax/form/AjaxFormSubmitBehavior.java | 8 +-
.../wicket/ajax/res/js/wicket-ajax-jquery.js | 521 ++--
.../org/apache/wicket/ajax/res/js/wicket-ajax.js | 2822 ++++++++++++++++++++
.../upload/resource/FileUploadToResourceField.js | 83 +-
.../wicket/settings/JavaScriptLibrarySettings.java | 7 +
wicket-core/src/test/js/ajax.js | 288 +-
wicket-core/src/test/js/all.html | 20 +-
wicket-core/src/test/js/channels.js | 2 +-
wicket-core/src/test/js/dom.js | 35 +-
wicket-core/src/test/js/event.js | 155 +-
wicket-core/src/test/js/form.js | 73 +-
wicket-core/src/test/js/head.js | 75 +-
wicket-core/src/test/js/timer.js | 2 +-
.../wicket/devutils/debugbar/wicket-debugbar.js | 74 +-
.../apache/wicket/examples/AjaxEngineSelector.java | 228 ++
.../wicket/examples/WicketExampleApplication.java | 4 +-
.../wicket/examples/WicketExampleHeader.html | 6 +-
.../wicket/examples/WicketExampleHeader.java | 33 +-
.../wicket/examples/ajax/builtin/EffectsPage.java | 15 +-
.../apache/wicket/examples/ajax/builtin/Index.html | 4 +-
.../apache/wicket/examples/ajax/builtin/Index.java | 9 +-
.../MyAuthenticatedWebApplication.java | 4 +
.../CustomResourceLoadingApplication.java | 1 -
.../resources/org/apache/wicket/examples/style.css | 3 +
.../src/main/webapp/jquery-ui-1.10.3.custom.js | 2261 ----------------
.../src/main/webapp/jquery-ui-v1.14.2.custom.js | 2576 ++++++++++++++++++
.../org/apache/wicket/examples/StartExamples.java | 11 +
.../util/license/ApacheLicenceHeaderTest.java | 2 +-
.../extensions/ajax/AjaxDownloadBehavior.java | 4 +-
.../extensions/ajax/AjaxFileDropBehavior.java | 3 +-
.../html/autocomplete/wicket-autocomplete.js | 318 +--
.../ajax/markup/html/form/upload/progressbar.js | 47 +-
.../ajax/markup/html/modal/trap-focus.js | 285 +-
.../wicket/extensions/ajax/wicket-ajaxdownload.js | 69 +-
.../markup/html/form/palette/Palette.java | 4 +-
.../extensions/markup/html/form/palette/palette.js | 60 +-
.../ws/api/res/js/wicket-websocket-jquery.js | 29 +-
.../src/main/asciidoc/ajax/ajax_1.adoc | 2 +-
.../src/main/asciidoc/ajax/ajax_11.adoc | 40 +
.../src/main/asciidoc/ajax/ajax_5.adoc | 4 +-
.../src/main/asciidoc/ajax/ajax_6.adoc | 2 +-
wicket-user-guide/src/main/asciidoc/single.adoc | 4 +
49 files changed, 7132 insertions(+), 3302 deletions(-)
diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml
index 6a72f14035..71b8598c0a 100644
--- a/.github/workflows/maven.yml
+++ b/.github/workflows/maven.yml
@@ -32,11 +32,43 @@ jobs:
distribution: 'temurin'
java-version: ${{ matrix.java }}
- - name: Apt update
- run: sudo apt update
-
- - name: Install Puppeteer's dependencies
- run: sudo apt-get install -y chromium-browser fonts-ipafont-gothic fonts-wqy-zenhei fonts-thai-tlwg fonts-kacst fonts-freefont-ttf libasound2t64 libatk1.0-0 libatk-bridge2.0-0 libc6 libcairo2 libcups2 libdbus-1-3 libexpat1 libfontconfig1 libgcc1 libgdk-pixbuf2.0-0 libglib2.0-0 libgtk-3-0 libnspr4 libpango-1.0-0 libpangocairo-1.0-0 libstdc++6 libx11-6 libx11-xcb1 libxcb1 libxcomposite1 libxcursor1 libxdamage1 libxext6 libxfixes3 libxi6 libxrandr2 libxrender1 libxss1 libxtst6 ca-cert [...]
+ # Puppeteer brings its own Chrome; only Chrome's shared libraries are needed here.
+ - name: Install headless Chrome's dependencies
+ run: |
+ sudo apt-get update
+ sudo apt-get install -y --no-install-recommends \
+ ca-certificates \
+ fonts-freefont-ttf \
+ fonts-ipafont-gothic \
+ fonts-kacst \
+ fonts-liberation \
+ fonts-thai-tlwg \
+ fonts-wqy-zenhei \
+ libasound2t64 \
+ libatk-bridge2.0-0t64 \
+ libatk1.0-0t64 \
+ libc6 \
+ libcairo2 \
+ libcups2t64 \
+ libdbus-1-3 \
+ libdrm2 \
+ libexpat1 \
+ libgbm1 \
+ libglib2.0-0t64 \
+ libgtk-3-0t64 \
+ libnspr4 \
+ libnss3 \
+ libpango-1.0-0 \
+ libvulkan1 \
+ libx11-6 \
+ libxcb1 \
+ libxcomposite1 \
+ libxdamage1 \
+ libxext6 \
+ libxfixes3 \
+ libxkbcommon0 \
+ libxrandr2 \
+ xdg-utils
- name: Install Maven
run: |
diff --git a/.gitignore b/.gitignore
index 842efdc3a6..fa397ed65f 100644
--- a/.gitignore
+++ b/.gitignore
@@ -16,3 +16,7 @@ release.properties
nb-configuration.xml
.DS_Store
**.launch
+MAVEN.md
+/mvnw
+/mvnw.cmd
+/.mvn/
diff --git a/JAVASCRIPTTESTING.md b/JAVASCRIPTTESTING.md
new file mode 100644
index 0000000000..cf0fac9b82
--- /dev/null
+++ b/JAVASCRIPTTESTING.md
@@ -0,0 +1,95 @@
+# JavaScript testing
+
+Wicket's client-side Ajax/event support (`Wicket.Ajax`, `Wicket.Event`, `Wicket.DOM`,
+`Wicket.Form`, `Wicket.Head`, `Wicket.Focus`, ...) has two implementations:
+
+- `wicket-core/src/main/java/org/apache/wicket/ajax/res/js/wicket-ajax-jquery.js` - the
+ default, jQuery-based engine.
+- `wicket-core/src/main/java/org/apache/wicket/ajax/res/js/wicket-ajax.js` - a jQuery-free,
+ plain-JavaScript engine exposing the exact same public API
+ (`getJavaScriptLibrarySettings().setWicketAjaxReference(WicketAjaxVanillaResourceReference.get())`).
+
+Both are exercised by the same shared QUnit test suite under `wicket-core/src/test/js/`, run
+via the `testing/wicket-js-tests` module (Grunt + Puppeteer/headless Chrome).
+
+## Running via Maven (recommended)
+
+The JS tests are behind the `js-test` Maven profile, which is **not active by default** -
+pass `-Pjs-test` explicitly:
+
+```bash
+cd /path/to/wicket
+
+# just this module
+mvn -pl testing/wicket-js-tests -Pjs-test test
+
+# as part of a full build
+mvn -Pjs-test test
+```
+
+This uses `frontend-maven-plugin` (configured in
+`testing/wicket-js-tests/pom.xml`) to:
+
+1. Download a local Node.js v24.15.0 / npm 11.12.1 into the module (separate from any
+ system Node/npm) - `install-node-and-npm` goal.
+2. `npm install` - pulls in Grunt, `grunt-contrib-qunit`, `grunt-contrib-jshint`,
+ `grunt-contrib-connect`, Puppeteer, etc.
+3. `grunt` - runs the default Gruntfile task: `jshint` → `connect` → `qunit`.
+
+Repeat runs are fast since Node/npm and `node_modules` are cached under
+`testing/wicket-js-tests/node/` and `node_modules/`.
+
+## Running directly with Grunt (faster iteration)
+
+Once `npm install` has run at least once (either via the Maven profile above, or manually
+with `./node/npm install` from `testing/wicket-js-tests`), you can invoke Grunt directly
+without going through Maven:
+
+```bash
+cd testing/wicket-js-tests
+
+# everything: jshint + connect + qunit (both engines)
+./node/node node_modules/.bin/grunt --verbose
+
+# lint only, no browser needed
+./node/node node_modules/.bin/grunt jshint
+
+# start the test webserver and run one engine at a time
+./node/node node_modules/.bin/grunt connect qunit:all # jQuery engine (wicket-ajax-jquery.js)
+./node/node node_modules/.bin/grunt connect qunit:vanilla # plain-JS engine (wicket-ajax.js)
+```
+
+`qunit:all` and `qunit:vanilla` launch headless Chrome via Puppeteer and serve the tests
+from `grunt-contrib-connect` on `http://localhost:38887` - nothing else needs to be running
+first. `all.html` also accepts other jQuery versions via a query string
+(`all.html?3.7.1`, `all.html?4.0.0`, `all.html?vanilla`) if you want to check a specific
+engine/jQuery version combination by hand in a real browser.
+
+## Prerequisites
+
+- Puppeteer downloads its own headless Chrome on first `npm install`, but that Chrome binary
+ still dynamically links against your system's Chrome/Chromium shared libraries (`libatk`,
+ `libatk-bridge2.0`, `libcups`, `libasound`, `libgbm`, `libpango`, `libxcomposite`,
+ `libxdamage`, `libxfixes`, `libxrandr`, `libatspi`, `libgtk-3`, `libnss3`, `libnspr4`,
+ `libxkbcommon`, ...). The simplest way to get all of these on Debian/Ubuntu is to install
+ a real Chrome (dependency resolution pulls in the rest):
+
+ ```bash
+ sudo apt-get update
+ sudo apt-get install -y google-chrome-stable
+ ```
+
+ or install the individual `lib*` packages listed above if you'd rather not install Chrome
+ itself.
+
+## What gets tested
+
+- `wicket-core/src/test/js/{ajax,channels,dom,event,form,head,timer}.js` - the shared QUnit
+ suite (`jshint:testsJs` / `qunit:all` / `qunit:vanilla` targets in
+ `testing/wicket-js-tests/Gruntfile.js`), covering both Ajax engines plus `Wicket.DOM`,
+ `Wicket.Event`, `Wicket.Form`, `Wicket.Head`, and the channel manager.
+- `jshint:core` / `jshint:extensions` / `jshint:nativeWebSocket` - lint-only coverage
+ (ES6+, no test runtime) for the rest of the framework's JS: `wicket-extensions`
+ Ajax components (autocomplete, palette, upload progress bar, ajax download, trap focus),
+ the dev debug bar, and native WebSocket support.
+- `jshint:gymTestsJs` - the `wicket-examples` JS tests.
diff --git a/pom.xml b/pom.xml
index 8d1716f8cb..2ad6c605e6 100644
--- a/pom.xml
+++ b/pom.xml
@@ -1302,6 +1302,7 @@
<suffix>.min</suffix>
<inputDir>${project.build.directory}/classes</inputDir>
<useDataUri>false</useDataUri>
+ <languageIn>ECMASCRIPT_2015</languageIn>
<resourcesSets>
<resourcesSet>
<excludes>
diff --git a/testing/wicket-js-tests/Gruntfile.js b/testing/wicket-js-tests/Gruntfile.js
index 85eda6ed71..db599c74b7 100644
--- a/testing/wicket-js-tests/Gruntfile.js
+++ b/testing/wicket-js-tests/Gruntfile.js
@@ -20,8 +20,10 @@ module.exports = function(grunt) {
coreJs = [
'../../wicket-core/src/main/java/org/apache/wicket/ajax/res/js/wicket-ajax-jquery-debug.js',
'../../wicket-core/src/main/java/org/apache/wicket/ajax/res/js/wicket-ajax-jquery.js',
+ '../../wicket-core/src/main/java/org/apache/wicket/ajax/res/js/wicket-ajax.js',
"../../wicket-core/src/main/java/org/apache/wicket/markup/html/form/CheckSelector.js",
"../../wicket-core/src/main/java/org/apache/wicket/markup/html/form/upload/MultiFileUploadField.js",
+ "../../wicket-core/src/main/java/org/apache/wicket/markup/html/form/upload/resource/FileUploadToResourceField.js",
"../../wicket-core/src/main/java/org/apache/wicket/ajax/form/AjaxFormChoiceComponentUpdatingBehavior.js",
"../../wicket-core/src/main/java/org/apache/wicket/markup/html/pages/wicket-browser-info.js"
],
@@ -100,7 +102,7 @@ module.exports = function(grunt) {
qunit: {
/*
- * Runs all tests (w/ ajax).
+ * Runs all tests (w/ ajax) against the default, JQuery-based wicket-ajax.js.
* See ajax.js header for details how to setup it.
*/
all: {
@@ -108,9 +110,25 @@ module.exports = function(grunt) {
urls: [
'http://localhost:38887/test/js/all.html?4.0.0'
],
- puppeteer: {
- headless: true,
- args: ['--no-sandbox']
+ puppeteer: {
+ headless: true,
+ args: ['--no-sandbox']
+ }
+ }
+ },
+
+ /*
+ * Runs the very same tests again against the JQuery-free wicket-ajax.js,
+ * to make sure both implementations of the Wicket.* client-side API stay in sync.
+ */
+ vanilla: {
+ options: {
+ urls: [
+ 'http://localhost:38887/test/js/all.html?vanilla'
+ ],
+ puppeteer: {
+ headless: true,
+ args: ['--no-sandbox']
}
}
}
diff --git a/wicket-core/src/main/java/org/apache/wicket/ajax/WicketAjaxResourceReference.java b/wicket-core/src/main/java/org/apache/wicket/ajax/WicketAjaxResourceReference.java
new file mode 100644
index 0000000000..0b2f44f593
--- /dev/null
+++ b/wicket-core/src/main/java/org/apache/wicket/ajax/WicketAjaxResourceReference.java
@@ -0,0 +1,54 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.wicket.ajax;
+
+import org.apache.wicket.request.resource.JavaScriptResourceReference;
+
+/**
+ * A {@link JavaScriptResourceReference} for the plain JavaScript (no jQuery) implementation of
+ * Wicket's Ajax and event support. It exposes the exact same {@code Wicket.*} JavaScript API as
+ * {@link WicketAjaxJQueryResourceReference}, so it can be used as a drop-in replacement without
+ * requiring jQuery to be loaded at all.
+ * <p>
+ * To switch the whole application to it:
+ *
+ * <pre>
+ * getJavaScriptLibrarySettings().setWicketAjaxReference(WicketAjaxResourceReference.get());
+ * </pre>
+ *
+ * @see org.apache.wicket.settings.JavaScriptLibrarySettings
+ * @since 10.10.0
+ */
+public class WicketAjaxResourceReference extends JavaScriptResourceReference
+{
+ private static final long serialVersionUID = 1L;
+
+ private static final WicketAjaxResourceReference INSTANCE = new WicketAjaxResourceReference();
+
+ /**
+ * @return the singleton INSTANCE
+ */
+ public static WicketAjaxResourceReference get()
+ {
+ return INSTANCE;
+ }
+
+ private WicketAjaxResourceReference()
+ {
+ super(AbstractDefaultAjaxBehavior.class, "res/js/wicket-ajax.js");
+ }
+}
diff --git a/wicket-core/src/main/java/org/apache/wicket/ajax/attributes/IAjaxCallListener.java b/wicket-core/src/main/java/org/apache/wicket/ajax/attributes/IAjaxCallListener.java
index f790f77db9..30de3538b9 100644
--- a/wicket-core/src/main/java/org/apache/wicket/ajax/attributes/IAjaxCallListener.java
+++ b/wicket-core/src/main/java/org/apache/wicket/ajax/attributes/IAjaxCallListener.java
@@ -94,8 +94,11 @@ public interface IAjaxCallListener
* parameters:
* <ol>
* <li>attrs - the AjaxRequestAttributes as JSON</li>
- * <li>jqXHR - the jQuery XMLHttpRequest object</li>
- * <li>settings - the settings used for the jQuery.ajax() call</li>
+ * <li>jqXHR - the XMLHttpRequest object used to make the Ajax call (a jQuery-augmented
+ * one by default, or a plain {@code XMLHttpRequest} if the application configured the
+ * JQuery-free {@code wicket-ajax.js} implementation)</li>
+ * <li>settings - the settings object used to make the Ajax call (its exact shape depends on
+ * the configured {@code wicket-ajax.js} implementation)</li>
* </ol>
*
* @param component
@@ -133,7 +136,9 @@ public interface IAjaxCallListener
* will be executed in a function that receives the following parameters:
* <ol>
* <li>attrs - the AjaxRequestAttributes as JSON</li>
- * <li>jqXHR - the jQuery XMLHttpRequest object</li>
+ * <li>jqXHR - the XMLHttpRequest object used to make the Ajax call (a jQuery-augmented
+ * one by default, or a plain {@code XMLHttpRequest} if the application configured the
+ * JQuery-free {@code wicket-ajax.js} implementation)</li>
* <li>data - the Ajax response. Its type depends on {@link AjaxRequestAttributes#dataType}</li>
* <li>textStatus - the status as text</li>
* </ol>
@@ -152,7 +157,9 @@ public interface IAjaxCallListener
* will be executed in a function that receives the following parameters:
* <ol>
* <li>attrs - the AjaxRequestAttributes as JSON</li>
- * <li>jqXHR - the jQuery XMLHttpRequest object</li>
+ * <li>jqXHR - the XMLHttpRequest object used to make the Ajax call (a jQuery-augmented
+ * one by default, or a plain {@code XMLHttpRequest} if the application configured the
+ * JQuery-free {@code wicket-ajax.js} implementation)</li>
* <li>errorMessage - in case of HTTP error the textual portion of the HTTP status</li>
* <li>textStatus - type of failure: null, "timeout", "error", "abort" or "parsererror"</li>
* </ol>
@@ -171,7 +178,9 @@ public interface IAjaxCallListener
* Ajax call. The script will be executed in a function that receives the following parameters:
* <ol>
* <li>attrs - the AjaxRequestAttributes as JSON</li>
- * <li>jqXHR - the jQuery XMLHttpRequest object</li>
+ * <li>jqXHR - the XMLHttpRequest object used to make the Ajax call (a jQuery-augmented
+ * one by default, or a plain {@code XMLHttpRequest} if the application configured the
+ * JQuery-free {@code wicket-ajax.js} implementation)</li>
* <li>textStatus - the status as text</li>
* </ol>
*
diff --git a/wicket-core/src/main/java/org/apache/wicket/ajax/form/AjaxFormSubmitBehavior.java b/wicket-core/src/main/java/org/apache/wicket/ajax/form/AjaxFormSubmitBehavior.java
index 23137b1e66..128ca2a514 100644
--- a/wicket-core/src/main/java/org/apache/wicket/ajax/form/AjaxFormSubmitBehavior.java
+++ b/wicket-core/src/main/java/org/apache/wicket/ajax/form/AjaxFormSubmitBehavior.java
@@ -183,11 +183,9 @@ public abstract class AjaxFormSubmitBehavior extends AjaxEventBehavior
@Override
public CharSequence getPrecondition(Component component)
{
- return String.format("var p, f = jQuery('#%s'), fn = function(e) { p = e.isDefaultPrevented(); e.preventDefault(); };" //
- + "f.on('submit',fn);" //
- + "f.trigger('submit');" //
- + "f.off('submit',fn);" //
- + "return !p;", form.getMarkupId());
+ return String.format(
+ "return document.getElementById('%s').dispatchEvent(new Event('submit', { cancelable: true, bubbles: true }));",
+ form.getMarkupId());
}
});
}
diff --git a/wicket-core/src/main/java/org/apache/wicket/ajax/res/js/wicket-ajax-jquery.js b/wicket-core/src/main/java/org/apache/wicket/ajax/res/js/wicket-ajax-jquery.js
index c54f552d52..288dcd004c 100644
--- a/wicket-core/src/main/java/org/apache/wicket/ajax/res/js/wicket-ajax-jquery.js
+++ b/wicket-core/src/main/java/org/apache/wicket/ajax/res/js/wicket-ajax-jquery.js
@@ -36,7 +36,7 @@
return;
}
- var isUndef = function (target) {
+ const isUndef = function (target) {
return (typeof(target) === 'undefined' || target === null);
};
@@ -46,8 +46,8 @@
* return '.' (current folder) as base URL.
* Used for request header and parameter
*/
- var getAjaxBaseUrl = function () {
- var baseUrl = Wicket.Ajax.baseUrl || '.';
+ const getAjaxBaseUrl = function () {
+ const baseUrl = Wicket.Ajax.baseUrl || '.';
return baseUrl;
};
@@ -57,9 +57,9 @@
* @param nodeList The NodeList to convert
* @returns {Array} The array with document nodes
*/
- var nodeListToArray = function (nodeList) {
- var arr = [],
- nodeId;
+ const nodeListToArray = function (nodeList) {
+ const arr = [];
+ let nodeId;
if (nodeList && nodeList.length) {
for (nodeId = 0; nodeId < nodeList.length; nodeId++) {
arr.push(nodeList.item(nodeId));
@@ -79,7 +79,7 @@
*
* @param functions {Array} - an array of functions to execute
*/
- var FunctionsExecuter = function (functions) {
+ const FunctionsExecuter = function (functions) {
this.functions = functions;
@@ -101,12 +101,12 @@
this.processNext = function () {
if (this.current < this.functions.length) {
- var f, run;
+ let run;
- f = this.functions[this.current];
+ const f = this.functions[this.current];
run = function () {
try {
- var n = jQuery.proxy(this.notify, this);
+ const n = jQuery.proxy(this.notify, this);
return f(n);
}
catch (e) {
@@ -122,7 +122,7 @@
this.depth = 0;
window.setTimeout(run, 1);
} else {
- var retValue = run();
+ const retValue = run();
if (isUndef(retValue) || retValue === FunctionsExecuter.ASYNC) {
this.depth++;
}
@@ -132,7 +132,7 @@
};
this.start = function () {
- var retValue = FunctionsExecuter.DONE;
+ let retValue = FunctionsExecuter.DONE;
while (retValue === FunctionsExecuter.DONE) {
retValue = this.processNext();
}
@@ -247,7 +247,7 @@
Wicket.Channel.prototype = {
initialize: function (name) {
name = name || '0|s';
- var res = name.match(/^([^|]+)\|(d|s|a)$/);
+ const res = name.match(/^([^|]+)\|(d|s|a)$/);
if (isUndef(res)) {
this.name = '0'; // '0' is the default channel name
this.type = 's'; // default to stack/queue
@@ -270,7 +270,7 @@
Wicket.Log.error("An error occurred while executing Ajax request:", exception);
}
} else {
- var busyChannel = "Channel '"+ this.name+"' is busy";
+ const busyChannel = "Channel '"+ this.name+"' is busy";
if (this.type === 's') { // stack/queue
Wicket.Log.info("%s - scheduling the callback to be executed when the previous request finish.", busyChannel);
this.callbacks.push(callback);
@@ -287,7 +287,7 @@
},
done: function () {
- var callback = null;
+ let callback = null;
if (this.callbacks.length > 0) {
callback = this.callbacks.shift();
@@ -316,8 +316,8 @@
// Schedules the callback to channel with given name.
schedule: function (channel, callback) {
- var parsed = new Wicket.Channel(channel);
- var c = this.channels[parsed.name];
+ const parsed = new Wicket.Channel(channel);
+ let c = this.channels[parsed.name];
if (isUndef(c)) {
c = parsed;
this.channels[c.name] = c;
@@ -330,8 +330,8 @@
// Tells the ChannelManager that the current callback in channel with given name
// has finished processing and another scheduled callback can be executed (if any).
done: function (channel) {
- var parsed = new Wicket.Channel(channel);
- var c = this.channels[parsed.name];
+ const parsed = new Wicket.Channel(channel);
+ const c = this.channels[parsed.name];
if (!isUndef(c)) {
c.done();
if (!c.busy) {
@@ -365,7 +365,7 @@
* evaluated.
*/
Wicket.Ajax.suspendCall = function () {
- var suspension = Wicket.Ajax._currentSuspension;
+ let suspension = Wicket.Ajax._currentSuspension;
if (suspension === undefined) {
Wicket.Log.error("Can't suspend: no Ajax call in process");
@@ -448,7 +448,7 @@
* @private
*/
_getTarget: function (attrs) {
- var target;
+ let target;
if (attrs.event) {
target = attrs.event.target;
} else if (!Wicket.isWindow(attrs.c)) {
@@ -469,14 +469,14 @@
if (Array.isArray(handlers)) {
// cut the handlers argument
- var args = Array.prototype.slice.call(arguments).slice(1);
+ const args = Array.prototype.slice.call(arguments).slice(1);
// assumes that the Ajax attributes is always the first argument
- var attrs = args[0];
- var that = this._getTarget(attrs);
+ const attrs = args[0];
+ const that = this._getTarget(attrs);
- for (var i = 0; i < handlers.length; i++) {
- var handler = handlers[i];
+ for (let i = 0; i < handlers.length; i++) {
+ const handler = handlers[i];
if (Wicket.isFunction(handler)) {
handler.apply(that, args);
} else {
@@ -497,7 +497,7 @@
* @private
*/
_asParamArray: function(parameters) {
- var result = [],
+ let result = [],
value,
name;
if (Array.isArray(parameters)) {
@@ -512,7 +512,7 @@
}
}
- for (var i = 0; i < result.length; i++) {
+ for (let i = 0; i < result.length; i++) {
if (result[i] === null) {
result.splice(i, 1);
i--;
@@ -531,12 +531,12 @@
* @private
*/
_calculateDynamicParameters: function(attrs) {
- var deps = attrs.dep,
- params = [];
+ const deps = attrs.dep;
+ let params = [];
- for (var i = 0; i < deps.length; i++) {
- var dep = deps[i],
- extraParam;
+ for (let i = 0; i < deps.length; i++) {
+ const dep = deps[i];
+ let extraParam;
if (Wicket.isFunction(dep)) {
extraParam = dep(attrs);
} else {
@@ -556,7 +556,7 @@
ajax: function (attrs) {
this._initializeDefaults(attrs);
- var res = Wicket.channelManager.schedule(attrs.ch, Wicket.bind(function () {
+ const res = Wicket.channelManager.schedule(attrs.ch, Wicket.bind(function () {
this.doAjax(attrs);
}, this));
return res !== null ? res: true;
@@ -571,7 +571,7 @@
return true;
}
- var element = Wicket.$(id);
+ const element = Wicket.$(id);
if (isUndef(element)) {
// not present
return false;
@@ -588,34 +588,33 @@
*/
doAjax: function (attrs) {
- var
- // the headers to use for each Ajax request
- headers = {
- 'Wicket-Ajax': 'true',
- 'Wicket-Ajax-BaseURL': getAjaxBaseUrl()
- },
-
- url = attrs.u,
+ // the headers to use for each Ajax request
+ const headers = {
+ 'Wicket-Ajax': 'true',
+ 'Wicket-Ajax-BaseURL': getAjaxBaseUrl()
+ };
- // the request (extra) parameters
- data = this._asParamArray(attrs.ep),
+ let url = attrs.u;
- self = this,
+ // the request (extra) parameters
+ let data = this._asParamArray(attrs.ep);
- // the precondition to use if there are no explicit ones
- defaultPrecondition = [ function (attributes) {
- return self._isPresent(attributes.c) && self._isPresent(attributes.f);
- }],
+ const self = this;
- // a context that brings the common data for the success/fialure/complete handlers
- context = {
- attrs: attrs,
+ // the precondition to use if there are no explicit ones
+ const defaultPrecondition = [ function (attributes) {
+ return self._isPresent(attributes.c) && self._isPresent(attributes.f);
+ }];
- // initialize the array for steps (closures that execute each action)
- steps: []
- },
- we = Wicket.Event,
- topic = we.Topic;
+ // a context that brings the common data for the success/fialure/complete handlers
+ const context = {
+ attrs: attrs,
+
+ // initialize the array for steps (closures that execute each action)
+ steps: []
+ };
+ const we = Wicket.Event;
+ const topic = we.Topic;
if (Wicket.Focus.lastFocusId) {
// WICKET-6568 might contain non-ASCII
@@ -625,16 +624,16 @@
self._executeHandlers(attrs.bh, attrs);
we.publish(topic.AJAX_CALL_BEFORE, attrs);
- var preconditions = attrs.pre || [];
+ let preconditions = attrs.pre || [];
preconditions = defaultPrecondition.concat(preconditions);
if (Array.isArray(preconditions)) {
- var that = this._getTarget(attrs);
+ const that = this._getTarget(attrs);
- for (var p = 0; p < preconditions.length; p++) {
+ for (let p = 0; p < preconditions.length; p++) {
- var precondition = preconditions[p];
- var result;
+ const precondition = preconditions[p];
+ let result;
if (Wicket.isFunction(precondition)) {
result = precondition.call(that, attrs);
} else {
@@ -652,36 +651,36 @@
if (attrs.f) {
// serialize the form with id == attrs.f
- var form = Wicket.$(attrs.f);
+ const form = Wicket.$(attrs.f);
data = data.concat(Wicket.Form.serializeForm(form));
// set the submitting component input name
if (attrs.sc) {
- var scName = attrs.sc;
+ const scName = attrs.sc;
data = data.concat({name: scName, value: 1});
}
} else if (attrs.c && !Wicket.isWindow(attrs.c)) {
// serialize just the form component with id == attrs.c
- var el = Wicket.$(attrs.c);
+ const el = Wicket.$(attrs.c);
data = data.concat(Wicket.Form.serializeElement(el, attrs.sr));
}
// collect the dynamic extra parameters
if (Array.isArray(attrs.dep)) {
- var dynamicData = this._calculateDynamicParameters(attrs);
+ const dynamicData = this._calculateDynamicParameters(attrs);
if (attrs.m.toLowerCase() === 'post') {
data = data.concat(dynamicData);
} else {
- var separator = url.indexOf('?') > -1 ? '&' : '?';
+ const separator = url.indexOf('?') > -1 ? '&' : '?';
url = url + separator + jQuery.param(dynamicData);
}
}
- var wwwFormUrlEncoded; // undefined is jQuery's default
+ let wwwFormUrlEncoded; // undefined is jQuery's default
if (attrs.mp) {
try {
- var formData = new FormData();
- for (var i = 0; i < data.length; i++) {
+ const formData = new FormData();
+ for (let i = 0; i < data.length; i++) {
formData.append(data[i].name, data[i].value || "");
}
@@ -696,7 +695,7 @@
Wicket.Log.debug(attrs);
// execute the request
- var jqXHR = jQuery.ajax({
+ const jqXHR = jQuery.ajax({
url: url,
type: attrs.m,
context: self,
@@ -747,7 +746,7 @@
return FunctionsExecuter.DONE;
}, self));
- var executer = new FunctionsExecuter(context.steps);
+ const executer = new FunctionsExecuter(context.steps);
executer.start();
}
});
@@ -765,13 +764,13 @@
* @param data {XmlDocument} - the <ajax-response> XML document
*/
process: function(data) {
- var context = {
+ const context = {
attrs: {},
steps: []
};
- var xmlDocument = Wicket.Xml.parse(data);
+ const xmlDocument = Wicket.Xml.parse(data);
this.loadedCallback(xmlDocument, context);
- var executer = new FunctionsExecuter(context.steps);
+ const executer = new FunctionsExecuter(context.steps);
executer.start();
},
@@ -788,7 +787,7 @@
if (jqXHR.readyState === 4) {
// first try to get the redirect header
- var redirectUrl;
+ let redirectUrl;
try {
redirectUrl = jqXHR.getResponseHeader('Ajax-Location');
} catch (ignore) { // might happen in older mozilla
@@ -801,7 +800,7 @@
// A file download popup will appear but the page in the browser won't change.
this.success(context);
- var withScheme = /^[a-z][a-z0-9+.-]*:\/\//; // checks whether the string starts with a scheme
+ const withScheme = /^[a-z][a-z0-9+.-]*:\/\//; // checks whether the string starts with a scheme
// support/check for non-relative redirectUrl like as provided and needed in a portlet context
if (redirectUrl.charAt(0) === '/' || withScheme.test(redirectUrl)) {
@@ -809,16 +808,16 @@
Wicket.Ajax.redirect(redirectUrl);
}
else {
- var urlDepth = 0;
+ let urlDepth = 0;
while (redirectUrl.substring(0, 3) === "../") {
urlDepth++;
redirectUrl = redirectUrl.substring(3);
}
// Make this a string.
- var calculatedRedirect = window.location.pathname;
+ let calculatedRedirect = window.location.pathname;
while (urlDepth > -1) {
urlDepth--;
- var i = calculatedRedirect.lastIndexOf("/");
+ const i = calculatedRedirect.lastIndexOf("/");
if (i > -1) {
calculatedRedirect = calculatedRedirect.substring(0, i);
}
@@ -849,7 +848,7 @@
// the order in which scripts are loaded and we have to delay the next steps until the script is
// loaded.
try {
- var root = envelope.getElementsByTagName("ajax-response")[0];
+ const root = envelope.getElementsByTagName("ajax-response")[0];
// the root element must be <ajax-response
if (isUndef(root) || root.tagName !== "ajax-response") {
@@ -857,12 +856,12 @@
return;
}
- var steps = context.steps;
+ const steps = context.steps;
// go through the ajax response and process priority evaluations and
// header contributions first
- for (var i = 0; i < root.childNodes.length; ++i) {
- var childNode = root.childNodes[i];
+ for (let i = 0; i < root.childNodes.length; ++i) {
+ const childNode = root.childNodes[i];
if (childNode.tagName === "header-contribution") {
this.processHeaderContribution(context, childNode);
} else if (childNode.tagName === "priority-evaluate") {
@@ -872,9 +871,9 @@
// ... then add components, process remaining evaluations and a
// possible redirect
- var stepIndexOfLastReplacedComponent = -1;
- for (var c = 0; c < root.childNodes.length; ++c) {
- var node = root.childNodes[c];
+ let stepIndexOfLastReplacedComponent = -1;
+ for (let c = 0; c < root.childNodes.length; ++c) {
+ const node = root.childNodes[c];
if (node.tagName === "component") {
if (stepIndexOfLastReplacedComponent === -1) {
@@ -905,7 +904,7 @@
context.steps.push(jQuery.proxy(function (notify) {
Wicket.Log.info("Response processed successfully.");
- var attrs = context.attrs;
+ const attrs = context.attrs;
this._executeHandlers(attrs.sh, attrs, null, null, 'success');
Wicket.Event.publish(Wicket.Event.Topic.AJAX_CALL_SUCCESS, attrs, null, null, 'success');
@@ -922,7 +921,7 @@
if (errorMessage) {
Wicket.Log.error("Wicket.Ajax.Call.failure: Error while parsing response: %s", errorMessage);
}
- var attrs = context.attrs;
+ const attrs = context.attrs;
this._executeHandlers(attrs.fh, attrs, jqXHR, errorMessage, textStatus);
Wicket.Event.publish(Wicket.Event.Topic.AJAX_CALL_FAILURE, attrs, jqXHR, errorMessage, textStatus);
@@ -941,16 +940,16 @@
processComponent: function (context, node) {
context.steps.push(function (notify) {
// get the component id
- var compId = node.getAttribute("id");
+ const compId = node.getAttribute("id");
// get existing component
- var element = Wicket.$(compId);
+ const element = Wicket.$(compId);
if (isUndef(element)) {
Wicket.Log.error("Wicket.Ajax.Call.processComponent: Component with id '%s' was not found while trying to perform markup update. " +
"Make sure you called component.setOutputMarkupId(true) on the component whose markup you are trying to update.", compId);
} else {
- var text = Wicket.DOM.text(node);
+ const text = Wicket.DOM.text(node);
// replace the component
Wicket.DOM.replace(element, text);
@@ -962,13 +961,13 @@
// Adds a closure that processes a header contribution
processHeaderContribution: function (context, node) {
- var c = Wicket.Head.Contributor;
+ const c = Wicket.Head.Contributor;
c.processContribution(context, node);
},
// Adds a closure that processes a redirect
processRedirect: function (context, node) {
- var text = Wicket.DOM.text(node);
+ const text = Wicket.DOM.text(node);
Wicket.Log.info("Redirecting to: %s", text);
context.isRedirecting = true;
Wicket.Ajax.redirect(text);
@@ -1046,9 +1045,9 @@
},
throttle: function (id, millis, func) {
- var entries = Wicket.Throttler.entries;
- var entry = entries[id];
- var me = this;
+ const entries = Wicket.Throttler.entries;
+ let entry = entries[id];
+ const me = this;
if (typeof(entry) === 'undefined') {
entry = new Wicket.ThrottlerEntry(func);
entry.setTimeoutVar(window.setTimeout(function() { me.execute(id); }, millis));
@@ -1064,10 +1063,10 @@
},
execute: function (id) {
- var entries = Wicket.Throttler.entries;
- var entry = entries[id];
+ const entries = Wicket.Throttler.entries;
+ const entry = entries[id];
if (typeof(entry) !== 'undefined') {
- var func = entry.getFunc();
+ const func = entry.getFunc();
entries[id] = undefined;
return func();
}
@@ -1118,9 +1117,9 @@
Xml: {
parse: function (text) {
- var parser = new DOMParser();
+ const parser = new DOMParser();
- var xmlDocument = parser.parseFromString(text, "text/xml");
+ const xmlDocument = parser.parseFromString(text, "text/xml");
return xmlDocument;
}
@@ -1150,15 +1149,15 @@
* or empty object if the form element is disabled.
*/
serializeSelect: function (select){
- var result = [];
+ const result = [];
if (select) {
- var $select = jQuery(select);
+ const $select = jQuery(select);
if ($select.length > 0 && $select.prop('disabled') === false) {
- var name = $select.prop('name');
- var values = $select.val();
+ const name = $select.prop('name');
+ const values = $select.val();
if (Array.isArray(values)) {
- for (var v = 0; v < values.length; v++) {
- var value = values[v];
+ for (let v = 0; v < values.length; v++) {
+ const value = values[v];
result.push( { name: name, value: value } );
}
} else {
@@ -1181,12 +1180,12 @@
* @return the URL encoded key=value pair or empty string if the form element is disabled.
*/
serializeInput: function (input) {
- var result = [];
+ let result = [];
if (input && input.type) {
- var $input = jQuery(input);
+ const $input = jQuery(input);
if (input.type === 'file') {
- for (var f = 0; f < input.files.length; f++) {
+ for (let f = 0; f < input.files.length; f++) {
result.push({"name" : input.name, "value" : input.files[f]});
}
} else if (!(input.type === 'image' || input.type === 'submit')) {
@@ -1230,20 +1229,20 @@
return [];
}
- var tag = element.tagName.toLowerCase();
+ const tag = element.tagName.toLowerCase();
if (tag === "select") {
return Wicket.Form.serializeSelect(element);
} else if (tag === "input" || tag === "textarea") {
return Wicket.Form.serializeInput(element);
} else {
- var result = [];
+ let result = [];
if (serializeRecursively) {
- var elements = nodeListToArray(element.getElementsByTagName("input"));
+ let elements = nodeListToArray(element.getElementsByTagName("input"));
elements = elements.concat(nodeListToArray(element.getElementsByTagName("select")));
elements = elements.concat(nodeListToArray(element.getElementsByTagName("textarea")));
- for (var i = 0; i < elements.length; ++i) {
- var el = elements[i];
+ for (let i = 0; i < elements.length; ++i) {
+ const el = elements[i];
if (el.name && el.name !== "") {
result = result.concat(Wicket.Form.serializeElement(el, serializeRecursively));
}
@@ -1254,7 +1253,7 @@
},
serializeForm: function (form) {
- var result = [],
+ let result = [],
elements;
if (form) {
@@ -1271,8 +1270,8 @@
}
}
- for (var i = 0; i < elements.length; ++i) {
- var el = elements[i];
+ for (let i = 0; i < elements.length; ++i) {
+ const el = elements[i];
if (el.name && el.name !== "") {
result = result.concat(Wicket.Form.serializeElement(el, false));
}
@@ -1289,7 +1288,7 @@
return Wicket.Form.serializeForm(element);
} else {
// try to find a form in DOM parents
- var elementBck = element;
+ const elementBck = element;
if (dontTryToFindRootForm !== true) {
do {
@@ -1302,12 +1301,12 @@
} else {
// there is not form in dom hierarchy
// simulate it
- var form = document.createElement("form");
- var parent = elementBck.parentNode;
+ const form = document.createElement("form");
+ const parent = elementBck.parentNode;
parent.replaceChild(form, elementBck);
form.appendChild(elementBck);
- var result = Wicket.Form.serializeForm(form);
+ const result = Wicket.Form.serializeForm(form);
parent.replaceChild(elementBck, form);
return result;
@@ -1375,7 +1374,7 @@
if (e === null) {
return;
}
- var count = e.getAttribute("showIncrementallyCount");
+ let count = e.getAttribute("showIncrementallyCount");
count = parseInt(isUndef(count) ? 0 : count, 10);
if (count >= 0) {
Wicket.DOM.show(e);
@@ -1389,7 +1388,7 @@
if (e === null) {
return;
}
- var count = e.getAttribute("showIncrementallyCount");
+ let count = e.getAttribute("showIncrementallyCount");
count = parseInt(isUndef(count) ? 0 : count - 1, 10);
if (count <= 0) {
Wicket.DOM.hide(e);
@@ -1402,8 +1401,8 @@
return null;
}
if (arguments.length > 1) {
- var e = [];
- for (var i = 0; i < arguments.length; i++) {
+ const e = [];
+ for (let i = 0; i < arguments.length; i++) {
e.push(Wicket.DOM.get(arguments[i]));
}
return e;
@@ -1429,7 +1428,7 @@
return false;
}
- var id = element.getAttribute('id');
+ const id = element.getAttribute('id');
if (isUndef(id) || id === "") {
return element.ownerDocument === document;
}
@@ -1454,49 +1453,49 @@
*/
replace: function (element, text) {
- var we = Wicket.Event;
- var topic = we.Topic;
+ const we = Wicket.Event;
+ const topic = we.Topic;
we.publish(topic.DOM_NODE_REMOVING, element);
if (element.tagName.toLowerCase() === "title") {
// match the text between the tags
- var titleText = />(.*?)</.exec(text)[1];
+ const titleText = />(.*?)</.exec(text)[1];
document.title = titleText;
return;
} else {
// jQuery 1.9+ expects '<' as the very first character in text
- var cleanedText = text.trim();
+ const cleanedText = text.trim();
- var $newElement = jQuery(cleanedText);
+ const $newElement = jQuery(cleanedText);
jQuery(element).replaceWith($newElement);
}
- var newElement = Wicket.$(element.id);
+ const newElement = Wicket.$(element.id);
if (newElement) {
we.publish(topic.DOM_NODE_ADDED, newElement);
}
},
add: function (element, text) {
- var we = Wicket.Event;
- var topic = we.Topic;
+ const we = Wicket.Event;
+ const topic = we.Topic;
// jQuery 1.9+ expects '<' as the very first character in text
- var cleanedText = text.trim();
+ const cleanedText = text.trim();
- var $newElement = jQuery(cleanedText);
+ const $newElement = jQuery(cleanedText);
jQuery(element).append($newElement);
- var newElement = Wicket.$(element.id);
+ const newElement = Wicket.$(element.id);
if (newElement) {
we.publish(topic.DOM_NODE_ADDED, newElement);
}
},
remove: function (element) {
- var we = Wicket.Event;
- var topic = we.Topic;
+ const we = Wicket.Event;
+ const topic = we.Topic;
we.publish(topic.DOM_NODE_REMOVING, element);
@@ -1509,11 +1508,11 @@
if (isUndef(node)) {
return "";
}
- var result = [];
+ const result = [];
if (node.childNodes.length > 0) {
- for (var i = 0; i < node.childNodes.length; i++) {
- var thisNode = node.childNodes[i];
+ for (let i = 0; i < node.childNodes.length; i++) {
+ const thisNode = node.childNodes[i];
switch (thisNode.nodeType) {
case 1: // ELEMENT_NODE
case 5: // ENTITY_REFERENCE_NODE
@@ -1547,13 +1546,13 @@
if (isUndef(node)) {
return "";
}
- var result = [];
+ const result = [];
result.push("<");
result.push(node.nodeName);
if (node.attributes && node.attributes.length > 0) {
- for (var i = 0; i < node.attributes.length; i++) {
+ for (let i = 0; i < node.attributes.length; i++) {
// serialize the attribute only if it has meaningful value that is not inherited
if (node.attributes[i].nodeValue && node.attributes[i].specified) {
result.push(" ");
@@ -1575,7 +1574,7 @@
// Utility function that determines whether given element is part of the current document
containsElement: function (element) {
- var id = element.getAttribute("id");
+ const id = element.getAttribute("id");
if (id) {
return Wicket.$(id) !== null;
}
@@ -1595,11 +1594,11 @@
return "";
}
- var result = [];
+ const result = [];
if (node.childNodes.length > 0) {
- for (var i = 0; i < node.childNodes.length; i++) {
- var thisNode = node.childNodes[i];
+ for (let i = 0; i < node.childNodes.length; i++) {
+ const thisNode = node.childNodes[i];
switch (thisNode.nodeType) {
case 1: // ELEMENT_NODE
case 5: // ENTITY_REFERENCE_NODE
@@ -1635,7 +1634,7 @@
* @param {Object} attrs - the Ajax request attributes configured at the server side
*/
_handleEventCancelation: function(attrs) {
- var evt = attrs.event;
+ const evt = attrs.event;
if (evt) {
if (attrs.pd) {
try {
@@ -1679,8 +1678,8 @@
jQuery.each(attrs.e, function (idx, evt) {
Wicket.Event.add(attrs.c, evt, function (jqEvent, data) {
- var call = new Wicket.Ajax.Call();
- var attributes = jQuery.extend({}, attrs);
+ const call = new Wicket.Ajax.Call();
+ const attributes = jQuery.extend({}, attrs);
if (evt !== "domready") {
attributes.event = Wicket.Event.fix(jqEvent);
@@ -1692,10 +1691,10 @@
call._executeHandlers(attributes.ih, attributes);
Wicket.Event.publish(Wicket.Event.Topic.AJAX_CALL_INIT, attributes);
- var throttlingSettings = attributes.tr;
+ const throttlingSettings = attributes.tr;
if (throttlingSettings) {
- var postponeTimerOnUpdate = throttlingSettings.p || false;
- var throttler = new Wicket.Throttler(postponeTimerOnUpdate);
+ const postponeTimerOnUpdate = throttlingSettings.p || false;
+ const throttler = new Wicket.Throttler(postponeTimerOnUpdate);
throttler.throttle(throttlingSettings.id, throttlingSettings.d,
Wicket.bind(function () {
call.ajax(attributes);
@@ -1712,7 +1711,7 @@
},
process: function(data) {
- var call = new Wicket.Ajax.Call();
+ const call = new Wicket.Ajax.Call();
call.process(data);
},
@@ -1748,10 +1747,10 @@
// we need to parse it since each header contribution needs to be treated separately
// get the header contribution text and unescape it if necessary
- var text = Wicket.DOM.text(headerNode);
+ const text = Wicket.DOM.text(headerNode);
// build a DOM tree of the contribution
- var xmldoc = Wicket.Xml.parse(text);
+ const xmldoc = Wicket.Xml.parse(text);
return xmldoc;
},
@@ -1759,7 +1758,7 @@
// created by DOMParser if there is a error in XML parsing
// TODO: move out of the API section
_checkParserError: function (node) {
- var result = false;
+ let result = false;
if (!isUndef(node.tagName) && node.tagName.toLowerCase() === "parsererror") {
Wicket.Log.error("Error in parsing: %s", node.textContent);
@@ -1770,8 +1769,8 @@
// Processes the parsed header contribution
processContribution: function (context, headerNode) {
- var xmldoc = this.parse(headerNode);
- var rootNode = xmldoc.documentElement;
+ const xmldoc = this.parse(headerNode);
+ const rootNode = xmldoc.documentElement;
// Firefox and Opera reports the error in the documentElement
if (this._checkParserError(rootNode)) {
@@ -1779,8 +1778,8 @@
}
// go through the individual elements and process them according to their type
- for (var i = 0; i < rootNode.childNodes.length; i++) {
- var node = rootNode.childNodes[i];
+ for (let i = 0; i < rootNode.childNodes.length; i++) {
+ let node = rootNode.childNodes[i];
// Chromium reports the error as a child node
if (this._checkParserError(node)) {
@@ -1788,13 +1787,13 @@
}
if (!isUndef(node.tagName)) {
- var name = node.tagName.toLowerCase();
+ let name = node.tagName.toLowerCase();
// it is possible that a reference is surrounded by a <wicket:link
// in that case, we need to find the inner element
if (name === "wicket:link") {
- for (var j = 0; j < node.childNodes.length; ++j) {
- var childNode = node.childNodes[j];
+ for (let j = 0; j < node.childNodes.length; ++j) {
+ const childNode = node.childNodes[j];
// try to find a regular node inside wicket:link
if (childNode.nodeType === 1) {
node = childNode;
@@ -1823,8 +1822,8 @@
// Process an external stylesheet element
processLink: function (context, node) {
context.steps.push(function (notify) {
- var res = Wicket.Head.containsElement(node, "href");
- var oldNode = res.oldNode;
+ const res = Wicket.Head.containsElement(node, "href");
+ const oldNode = res.oldNode;
if (res.contains) {
// an element with same href attribute is in document, skip it
return FunctionsExecuter.DONE;
@@ -1834,16 +1833,16 @@
}
// create link element
- var css = Wicket.Head.createElement("link");
+ const css = Wicket.Head.createElement("link");
// copy supplied attributes only.
- var attributes = jQuery(node).prop("attributes");
- var $css = jQuery(css);
+ const attributes = jQuery(node).prop("attributes");
+ const $css = jQuery(css);
jQuery.each(attributes, function() {
$css.attr(this.name, this.value);
});
- var notifyCalled = false;
+ let notifyCalled = false;
function doNotify() {
if (!notifyCalled) {
notifyCalled = true;
@@ -1867,17 +1866,17 @@
return FunctionsExecuter.DONE;
}
// serialize the style to string
- var content = Wicket.DOM.serializeNodeChildren(node);
+ const content = Wicket.DOM.serializeNodeChildren(node);
// create style element
- var style = Wicket.Head.createElement("style");
+ const style = Wicket.Head.createElement("style");
// copy id attribute
style.id = node.getAttribute("id");
// copy nonce attribute
style.nonce = node.getAttribute("nonce");
- var textNode = document.createTextNode(content);
+ const textNode = document.createTextNode(content);
style.appendChild(textNode);
Wicket.Head.addElement(style);
@@ -1895,8 +1894,8 @@
// if an inline element with same id is already in document, skip it
return FunctionsExecuter.DONE;
} else {
- var res = Wicket.Head.containsElement(node, "src");
- var oldNode = res.oldNode;
+ const res = Wicket.Head.containsElement(node, "src");
+ const oldNode = res.oldNode;
if (res.contains) {
// an element with same src attribute is in document, skip it
return FunctionsExecuter.DONE;
@@ -1907,17 +1906,17 @@
}
// convert the XML node to DOM node
- var scriptDomNode = document.createElement("script");
- var attrs = node.attributes;
- for (var a = 0; a < attrs.length; a++) {
- var attr = attrs[a];
+ const scriptDomNode = document.createElement("script");
+ const attrs = node.attributes;
+ for (let a = 0; a < attrs.length; a++) {
+ const attr = attrs[a];
scriptDomNode[attr.name] = attr.value;
}
// determine whether it is external javascript (has src attribute set)
- var src = node.getAttribute("src");
+ const src = node.getAttribute("src");
if (src !== null && src !== "") {
- var onScriptReady = function () {
+ const onScriptReady = function () {
notify();
};
@@ -1939,7 +1938,7 @@
return FunctionsExecuter.ASYNC;
} else {
- var suspension = {
+ const suspension = {
suspended: 0,
suspend: function() {
@@ -1955,7 +1954,7 @@
};
// serialize the element content to string
- var text = Wicket.DOM.serializeNodeChildren(node);
+ let text = Wicket.DOM.serializeNodeChildren(node);
// get rid of prefix and suffix, they are not eval-d correctly
text = text.replace(/^\n\/\*<!\[CDATA\[\*\/\n/, "");
text = text.replace(/\n\/\*\]\]>\*\/\n$/, "");
@@ -1965,7 +1964,7 @@
scriptDomNode.innerHTML = text;
- var id = node.getAttribute("id");
+ const id = node.getAttribute("id");
Wicket.Head.addElement(scriptDomNode, typeof(id) !== "string" || id.length === 0);
} catch (exception) {
Wicket.Log.error("Ajax.Call.processEvaluation: Exception evaluating javascript: %s", text, exception);
@@ -1987,7 +1986,7 @@
processMeta: function (context, node) {
context.steps.push(function (notify) {
- var meta = Wicket.Head.createElement("meta"),
+ const meta = Wicket.Head.createElement("meta"),
$meta = jQuery(meta),
attrs = jQuery(node).prop("attributes"),
name = node.getAttribute("name"),
@@ -2012,7 +2011,7 @@
// process (conditional) comments
processComment: function (context, node) {
context.steps.push(function (notify) {
- var comment = document.createComment(node.nodeValue);
+ const comment = document.createComment(node.nodeValue);
Wicket.Head.addElement(comment);
return FunctionsExecuter.DONE;
});
@@ -2030,11 +2029,11 @@
// Adds the element to page head
addElement: function (element, remove) {
- var headItems = document.querySelector('head meta[name="wicket.header.items"]');
+ const headItems = document.querySelector('head meta[name="wicket.header.items"]');
if (headItems) {
headItems.parentNode.insertBefore(element, headItems);
} else {
- var head = document.querySelector("head");
+ const head = document.querySelector("head");
if (head) {
head.appendChild(element);
}
@@ -2052,33 +2051,33 @@
// is an element in head that is of same type as myElement, and whose src
// attribute is same as myElement.src.
containsElement: function (element, mandatoryAttribute) {
- var attr = element.getAttribute(mandatoryAttribute);
+ const attr = element.getAttribute(mandatoryAttribute);
if (isUndef(attr) || attr === "") {
return {
contains: false
};
}
- var elementTagName = element.tagName.toLowerCase();
- var elementId = element.getAttribute("id");
- var head = document.getElementsByTagName("head")[0];
+ const elementTagName = element.tagName.toLowerCase();
+ const elementId = element.getAttribute("id");
+ let head = document.getElementsByTagName("head")[0];
if (elementTagName === "script") {
head = document;
}
- var nodes = head.getElementsByTagName(elementTagName);
+ const nodes = head.getElementsByTagName(elementTagName);
- for (var i = 0; i < nodes.length; ++i) {
- var node = nodes[i];
+ for (let i = 0; i < nodes.length; ++i) {
+ const node = nodes[i];
// check node names and mandatory attribute values
// we also have to check for attribute name that is suffixed by "_".
// this is necessary for filtering script references
if (node.tagName.toLowerCase() === elementTagName) {
- var loadedUrl = node.getAttribute(mandatoryAttribute);
- var loadedUrl_ = node.getAttribute(mandatoryAttribute+"_");
+ const loadedUrl = node.getAttribute(mandatoryAttribute);
+ const loadedUrl_ = node.getAttribute(mandatoryAttribute+"_");
if (loadedUrl === attr || loadedUrl_ === attr) {
return {
contains: true
@@ -2107,11 +2106,11 @@
focusin: function (event) {
event = Wicket.Event.fix(event);
- var target = event.target;
+ const target = event.target;
if (target) {
- var WF = Wicket.Focus;
+ const WF = Wicket.Focus;
WF.refocusLastFocusedComponentAfterResponse = false;
- var id = target.id;
+ const id = target.id;
WF.lastFocusId = id;
Wicket.Log.info("focus set on '%s'", id);
}
@@ -2120,10 +2119,10 @@
focusout: function (event) {
event = Wicket.Event.fix(event);
- var target = event.target;
- var WF = Wicket.Focus;
+ const target = event.target;
+ const WF = Wicket.Focus;
if (target && WF.lastFocusId === target.id) {
- var id = target.id;
+ const id = target.id;
if (WF.refocusLastFocusedComponentAfterResponse) {
// replaced components seem to blur when replaced only on Safari - so do not modify lastFocusId so it gets refocused
Wicket.Log.info("focus removed from '%s' but ignored because of component replacement", id);
@@ -2135,16 +2134,16 @@
},
getFocusedElement: function () {
- var lastFocusId = Wicket.Focus.lastFocusId;
+ const lastFocusId = Wicket.Focus.lastFocusId;
if (lastFocusId) {
- var focusedElement = Wicket.$(lastFocusId);
+ const focusedElement = Wicket.$(lastFocusId);
Wicket.Log.info("returned focused element:", focusedElement);
return focusedElement;
}
},
setFocusOnId: function (id) {
- var WF = Wicket.Focus;
+ const WF = Wicket.Focus;
if (id) {
WF.refocusLastFocusedComponentAfterResponse = true;
WF.focusSetFromServer = true;
@@ -2158,8 +2157,8 @@
// mark the focused component so that we know if it has been replaced or not by response
markFocusedComponent: function () {
- var WF = Wicket.Focus;
- var focusedElement = WF.getFocusedElement();
+ const WF = Wicket.Focus;
+ const focusedElement = WF.getFocusedElement();
if (focusedElement) {
// create a property of the focused element that would not remain there if component is replaced
focusedElement.wasFocusedBeforeComponentReplacements = true;
@@ -2172,9 +2171,9 @@
// detect if the focused component was replaced
checkFocusedComponentReplaced: function () {
- var WF = Wicket.Focus;
+ const WF = Wicket.Focus;
if (WF.refocusLastFocusedComponentAfterResponse) {
- var focusedElement = WF.getFocusedElement();
+ const focusedElement = WF.getFocusedElement();
if (focusedElement) {
if (typeof(focusedElement.wasFocusedBeforeComponentReplacements) !== "undefined") {
// focus component was not replaced - no need to refocus it
@@ -2193,14 +2192,14 @@
// (if focus was not changed from server) but if not, and the focus component should
// remain the same, do not re-focus - fixes problem on IE6 for combos that have
// the popup open (refocusing closes popup)
- var WF = Wicket.Focus;
+ const WF = Wicket.Focus;
if (WF.refocusLastFocusedComponentAfterResponse && WF.lastFocusId) {
- var toFocus = Wicket.$(WF.lastFocusId);
+ const toFocus = Wicket.$(WF.lastFocusId);
if (toFocus) {
Wicket.Log.info("Calling focus on '%s'", WF.lastFocusId);
- var safeFocus = function() {
+ const safeFocus = function() {
try {
// toFocus is not a JQuery object. Thus use focus.
toFocus.focus();
@@ -2214,7 +2213,7 @@
window.setTimeout(safeFocus, 0);
} else {
// avoid loops like - onfocus triggering an event the modifies the tag => refocus => the event is triggered again
- var temp = toFocus.onfocus;
+ const temp = toFocus.onfocus;
toFocus.onfocus = null;
// IE needs setTimeout (it seems not to call onfocus sync. when focus() is called
@@ -2270,9 +2269,9 @@
* Clear all remaining timers.
*/
clearAll: function() {
- var WTH = Wicket.TimerHandles;
+ const WTH = Wicket.TimerHandles;
if (WTH) {
- for (var th in WTH) {
+ for (const th in WTH) {
if (WTH.hasOwnProperty(th)) {
Wicket.Timer.clear(th);
}
@@ -2288,9 +2287,13 @@
Event: {
idCounter: 0,
+ // maps element -> { eventType -> [{ fn, wrapper }] } so that remove() can
+ // find the wrapper registered for a given original handler in add()
+ _listenerRegistry: (typeof(WeakMap) !== 'undefined') ? new WeakMap() : null,
+
getId: function (element) {
- var $el = jQuery(element),
- id = $el.prop("id");
+ const $el = jQuery(element);
+ let id = $el.prop("id");
if (typeof(id) === "string" && id.length > 0) {
return id;
@@ -2325,11 +2328,23 @@
* If no event is given as argument (IE), window.event is returned.
*/
fix: function (evt) {
- return jQuery.event.fix(evt || window.event);
+ const fixed = jQuery.event.fix(evt || window.event);
+
+ // jQuery.Event only exposes isDefaultPrevented() - mirror it as a live
+ // 'defaultPrevented' property so callers can use the same native Event
+ // API regardless of which Ajax engine (jQuery or vanilla) is active.
+ Object.defineProperty(fixed, 'defaultPrevented', {
+ configurable: true,
+ get: function () {
+ return this.isDefaultPrevented();
+ }
+ });
+
+ return fixed;
},
- fire: function (element, event) {
- jQuery(element).trigger(event);
+ fire: function (element, event, data) {
+ jQuery(Wicket.$(element)).trigger(event, data);
},
/**
@@ -2355,7 +2370,7 @@
jQuery(fn);
});
} else {
- var el = element;
+ let el = element;
if (typeof(element) === 'string') {
el = document.getElementById(element);
}
@@ -2364,7 +2379,26 @@
Wicket.Log.error("Cannot bind a listener for event '%s' because the element is not in the DOM", type, element);
}
- jQuery(el).on(type, selector, data, fn);
+ // trigger-time extra data (passed via Wicket.Event.fire) takes precedence
+ // over the bind-time 'data' given here, which is used as a fallback
+ const wrapper = function (jqEvent) {
+ const extraData = arguments.length > 1 ? arguments[1] : data;
+ return fn.call(this, jqEvent, extraData);
+ };
+
+ jQuery(el).on(type, selector, wrapper);
+
+ if (el && Wicket.Event._listenerRegistry) {
+ let map = Wicket.Event._listenerRegistry.get(el);
+ if (!map) {
+ map = {};
+ Wicket.Event._listenerRegistry.set(el, map);
+ }
+ if (!map[type]) {
+ map[type] = [];
+ }
+ map[type].push({ fn: fn, wrapper: wrapper });
+ }
}
return element;
},
@@ -2373,11 +2407,36 @@
* Unbinds an event listener for an element
*
* @param element {HTMLElement} The host HTML element
- * @param type {String} The type of the DOM event
- * @param fn {Function} The event handler to unbind
+ * @param type {String} The type of the DOM event. Several space separated
+ * event types can be given at once
+ * @param fn {Function} The event handler to unbind. If omitted, every listener
+ * bound through Wicket.Event.add() for this type is removed.
*/
remove: function (element, type, fn) {
- jQuery(element).off(type, fn);
+ let el = element;
+ if (typeof(element) === 'string') {
+ el = document.getElementById(element);
+ }
+ if (!el || !Wicket.Event._listenerRegistry) {
+ return;
+ }
+ const map = Wicket.Event._listenerRegistry.get(el);
+ if (!map) {
+ return;
+ }
+ const types = type ? type.split(/\s+/) : Object.keys(map);
+ for (let t = 0; t < types.length; t++) {
+ const entries = map[types[t]];
+ if (!entries) {
+ continue;
+ }
+ for (let i = entries.length - 1; i >= 0; i--) {
+ if (!fn || entries[i].fn === fn) {
+ jQuery(el).off(types[t], entries[i].wrapper);
+ entries.splice(i, 1);
+ }
+ }
+ }
},
/**
@@ -2423,7 +2482,7 @@
publish: function (topic) {
if (topic) {
// cut the topic argument
- var args = Array.prototype.slice.call(arguments).slice(1);
+ const args = Array.prototype.slice.call(arguments).slice(1);
jQuery(document).triggerHandler(topic, args);
jQuery(document).triggerHandler('*', args);
diff --git a/wicket-core/src/main/java/org/apache/wicket/ajax/res/js/wicket-ajax.js b/wicket-core/src/main/java/org/apache/wicket/ajax/res/js/wicket-ajax.js
new file mode 100644
index 0000000000..befb85810a
--- /dev/null
+++ b/wicket-core/src/main/java/org/apache/wicket/ajax/res/js/wicket-ajax.js
@@ -0,0 +1,2822 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/*global DOMParser: true, console: true */
+
+/*
+ * Wicket Ajax Support - plain JavaScript (no jQuery) implementation
+ *
+ * This file provides the exact same public API as wicket-ajax-jquery.js
+ * (Wicket.Ajax, Wicket.Event, Wicket.DOM, Wicket.Form, Wicket.Head, Wicket.Focus, ...)
+ * but is implemented using only native browser APIs. It can be used as a drop-in
+ * replacement by configuring
+ * {@code Application.get().getJavaScriptLibrarySettings().setWicketAjaxReference(WicketAjaxResourceReference.get())}
+ * and does not require jQuery to be loaded at all.
+ *
+ * @author Igor Vaynberg
+ * @author Matej Knopp
+ */
+
+;(function (undefined) {
+
+ 'use strict';
+
+ if (typeof(Wicket) === 'undefined') {
+ window.Wicket = {};
+ }
+
+ if (typeof(Wicket.Head) === 'object') {
+ return;
+ }
+
+ const isUndef = function (target) {
+ return (typeof(target) === 'undefined' || target === null);
+ };
+
+ /**
+ * A safe getter for Wicket's Ajax base URL.
+ * If the value is not defined or is empty string then
+ * return '.' (current folder) as base URL.
+ * Used for request header and parameter
+ */
+ const getAjaxBaseUrl = function () {
+ const baseUrl = Wicket.Ajax.baseUrl || '.';
+ return baseUrl;
+ };
+
+ /**
+ * Converts a NodeList to an Array
+ *
+ * @param nodeList The NodeList to convert
+ * @returns {Array} The array with document nodes
+ */
+ const nodeListToArray = function (nodeList) {
+ const arr = [];
+ let nodeId;
+ if (nodeList && nodeList.length) {
+ for (nodeId = 0; nodeId < nodeList.length; nodeId++) {
+ arr.push(nodeList.item(nodeId));
+ }
+ }
+ return arr;
+ };
+
+ /**
+ * A minimal replacement for jQuery.isPlainObject - true for objects created
+ * via {} or `new Object()`, false for arrays, DOM nodes, null, etc.
+ */
+ const isPlainObject = function (obj) {
+ return typeof(obj) === 'object' && obj !== null && !Array.isArray(obj) &&
+ Object.prototype.toString.call(obj) === '[object Object]';
+ };
+
+ /**
+ * Caches the browser's default `display` value per tag name (e.g. 'div' -> 'block',
+ * 'span' -> 'inline'), used by Wicket.DOM.show() to restore visibility of an element
+ * whose 'display' is not known upfront.
+ */
+ const elementDisplayCache = {};
+ const defaultDisplay = function (nodeName) {
+ nodeName = nodeName.toLowerCase();
+ let display = elementDisplayCache[nodeName];
+ if (!display) {
+ const element = document.createElement(nodeName);
+ document.body.appendChild(element);
+ display = window.getComputedStyle(element).display;
+ element.parentNode.removeChild(element);
+ if (display === 'none') {
+ display = 'block';
+ }
+ elementDisplayCache[nodeName] = display;
+ }
+ return display;
+ };
+
+ /**
+ * <script> elements created by HTML fragment parsing (e.g. via innerHTML, which is how
+ * a <template> is filled) are flagged by the browser as already started and never execute,
+ * even once moved into the live document - this is standard, intentional HTML parser
+ * behavior. Wicket.DOM.replace()/add() replicate jQuery's DOM-manipulation methods, which
+ * DO run such inline scripts, by replacing each one with a freshly created <script> that
+ * carries the same attributes and text - a plain new node has no such flag and executes
+ * normally once inserted.
+ *
+ * @param root {DocumentFragment|Element} - the (still detached) parsed markup to fix up
+ */
+ const reviveScripts = function (root) {
+ const scripts = root.querySelectorAll ? root.querySelectorAll('script') : [];
+ for (let i = 0; i < scripts.length; i++) {
+ const oldScript = scripts[i];
+ const newScript = document.createElement('script');
+ for (let a = 0; a < oldScript.attributes.length; a++) {
+ const attr = oldScript.attributes[a];
+ newScript.setAttribute(attr.name, attr.value);
+ }
+ newScript.text = oldScript.textContent;
+ oldScript.parentNode.replaceChild(newScript, oldScript);
+ }
+ };
+
+ /**
+ * Functions executer takes array of functions and executes them.
+ * The functions are executed one by one as far as the return value is FunctionsExecuter.DONE.
+ * If the return value is FunctionsExecuter.ASYNC or undefined then the execution of
+ * the functions will be resumed once the `notify` callback function is called.
+ * This is needed because header contributions need to do asynchronous download of JS and/or CSS
+ * and they have to let next function to run only after the download.
+ * After the FunctionsExecuter is initialized, the start methods triggers the first function.
+ *
+ * @param functions {Array} - an array of functions to execute
+ */
+ const FunctionsExecuter = function (functions) {
+
+ this.functions = functions;
+
+ /**
+ * The index of the currently executed function
+ * @type {number}
+ */
+ this.current = 0;
+
+ /**
+ * Tracks the depth of the call stack when `notify` is used for
+ * asynchronous notification that a function execution has finished.
+ * Should be reset to 0 when at some point to avoid problems like
+ * "too much recursion". The reset may break the atomicity by allowing
+ * another instance of FunctionsExecuter to run its functions
+ * @type {number}
+ */
+ this.depth = 0; // we need to limit call stack depth
+
+ this.processNext = function () {
+ if (this.current < this.functions.length) {
+ let run;
+
+ const f = this.functions[this.current];
+ run = function () {
+ try {
+ const n = this.notify.bind(this);
+ return f(n);
+ }
+ catch (e) {
+ Wicket.Log.error("FunctionsExecuter.processNext:", e);
+ return FunctionsExecuter.FAIL;
+ }
+ };
+ run = run.bind(this);
+ this.current++;
+
+ if (this.depth > FunctionsExecuter.DEPTH_LIMIT) {
+ // to prevent stack overflow (see WICKET-4675)
+ this.depth = 0;
+ window.setTimeout(run, 1);
+ } else {
+ const retValue = run();
+ if (isUndef(retValue) || retValue === FunctionsExecuter.ASYNC) {
+ this.depth++;
+ }
+ return retValue;
+ }
+ }
+ };
+
+ this.start = function () {
+ let retValue = FunctionsExecuter.DONE;
+ while (retValue === FunctionsExecuter.DONE) {
+ retValue = this.processNext();
+ }
+ };
+
+ this.notify = function () {
+ this.start();
+ };
+ };
+
+ /**
+ * Response that should be used by a function when it finishes successfully
+ * in synchronous manner
+ * @type {number}
+ */
+ FunctionsExecuter.DONE = 1;
+
+ /**
+ * Response that should be used by a function when it finishes abnormally
+ * in synchronous manner
+ * @type {number}
+ */
+ FunctionsExecuter.FAIL = 2;
+
+ /**
+ * Response that may be used by a function when it executes asynchronous
+ * code and must wait `notify()` to be executed.
+ * @type {number}
+ */
+ FunctionsExecuter.ASYNC = 3;
+
+ /**
+ * An artificial number used as a limit of the call stack depth to avoid
+ * problems like "too much recursion" in the browser.
+ * The depth is not easy to be calculated because the memory used by the
+ * stack depends on many factors
+ * @type {number}
+ */
+ FunctionsExecuter.DEPTH_LIMIT = 1000;
+
+ // API start
+
+ Wicket.Class = {
+ create: function () {
+ return function () {
+ this.initialize.apply(this, arguments);
+ };
+ }
+ };
+
+ Wicket.isFunction = function (f) {
+ return typeof(f) === 'function';
+ };
+
+ Wicket.isWindow = function (obj) {
+ return typeof(obj) !== 'undefined' && obj !== null && obj === obj.window;
+ };
+
+ /**
+ * Logging functionality.
+ */
+ Wicket.Log = {
+
+ enabled: false,
+
+ log: function () {
+ if (Wicket.Log.enabled && typeof(console) !== "undefined" && typeof(console.log) === 'function') {
+ console.log.apply(console, arguments);
+ }
+ },
+
+ debug: function () {
+ if (Wicket.Log.enabled && typeof(console) !== "undefined" && typeof(console.debug) === 'function') {
+ console.debug.apply(console, arguments);
+ }
+ },
+
+ info: function () {
+ if (Wicket.Log.enabled && typeof(console) !== "undefined" && typeof(console.info) === 'function') {
+ console.info.apply(console, arguments);
+ }
+ },
+
+ warn: function () {
+ if (Wicket.Log.enabled && typeof(console) !== "undefined" && typeof(console.warn) === 'function') {
+ console.warn.apply(console, arguments);
+ }
+ },
+
+ error: function () {
+ if (Wicket.Log.enabled && typeof(console) !== "undefined" && typeof(console.error) === 'function') {
+ console.error.apply(console, arguments);
+ }
+ }
+ };
+
+ /**
+ * Channel management
+ *
+ * Wicket Ajax requests are organized in channels. A channel maintain the order of
+ * requests and determines, what should happen when a request is fired while another
+ * one is being processed. The default behavior (stack) puts the all subsequent requests
+ * in a queue, while the drop behavior limits queue size to one, so only the most
+ * recent of subsequent requests is executed.
+ * The name of channel determines the policy. E.g. channel with name foochannel|s is
+ * a stack channel, while barchannel|d is a drop channel.
+ *
+ * The Channel class is supposed to be used through the ChannelManager.
+ */
+ Wicket.Channel = Wicket.Class.create();
+
+ Wicket.Channel.prototype = {
+ initialize: function (name) {
+ name = name || '0|s';
+ const res = name.match(/^([^|]+)\|(d|s|a)$/);
+ if (isUndef(res)) {
+ this.name = '0'; // '0' is the default channel name
+ this.type = 's'; // default to stack/queue
+ }
+ else {
+ this.name = res[1];
+ this.type = res[2];
+ }
+ this.callbacks = [];
+ this.busy = false;
+ },
+
+ schedule: function (callback) {
+ if (this.busy === false) {
+ this.busy = true;
+ try {
+ return callback();
+ } catch (exception) {
+ this.busy = false;
+ Wicket.Log.error("An error occurred while executing Ajax request:", exception);
+ }
+ } else {
+ const busyChannel = "Channel '"+ this.name+"' is busy";
+ if (this.type === 's') { // stack/queue
+ Wicket.Log.info("%s - scheduling the callback to be executed when the previous request finish.", busyChannel);
+ this.callbacks.push(callback);
+ }
+ else if (this.type === 'd') { // drop
+ Wicket.Log.info("%s - dropping all previous scheduled callbacks and scheduling a new one to be executed when the current request finish.", busyChannel);
+ this.callbacks = [];
+ this.callbacks.push(callback);
+ } else if (this.type === 'a') { // active
+ Wicket.Log.info("%s - ignoring the Ajax call because there is a running request.", busyChannel);
+ }
+ return null;
+ }
+ },
+
+ done: function () {
+ let callback = null;
+
+ if (this.callbacks.length > 0) {
+ callback = this.callbacks.shift();
+ }
+
+ if (callback !== null && typeof(callback) !== "undefined") {
+ Wicket.Log.info("Calling postponed function...");
+ // we can't call the callback from this call-stack
+ // therefore we set it on timer event
+ window.setTimeout(callback, 1);
+ } else {
+ this.busy = false;
+ }
+ }
+ };
+
+ /**
+ * Channel manager maintains a map of channels.
+ */
+ Wicket.ChannelManager = Wicket.Class.create();
+
+ Wicket.ChannelManager.prototype = {
+ initialize: function () {
+ this.channels = {};
+ },
+
+ // Schedules the callback to channel with given name.
+ schedule: function (channel, callback) {
+ const parsed = new Wicket.Channel(channel);
+ let c = this.channels[parsed.name];
+ if (isUndef(c)) {
+ c = parsed;
+ this.channels[c.name] = c;
+ } else {
+ c.type = parsed.type;
+ }
+ return c.schedule(callback);
+ },
+
+ // Tells the ChannelManager that the current callback in channel with given name
+ // has finished processing and another scheduled callback can be executed (if any).
+ done: function (channel) {
+ const parsed = new Wicket.Channel(channel);
+ const c = this.channels[parsed.name];
+ if (!isUndef(c)) {
+ c.done();
+ if (!c.busy) {
+ delete this.channels[parsed.name];
+ }
+ }
+ }
+ };
+
+ Wicket.ChannelManager.FunctionsExecuter = FunctionsExecuter;
+
+ /**
+ * The Ajax.Request class encapsulates a XmlHttpRequest.
+ */
+ Wicket.Ajax = {};
+
+ /**
+ * Ajax call fires a Wicket Ajax request and processes the response.
+ * The response can contain
+ * - javascript that should be invoked
+ * - body of components being replaced
+ * - header contributions of components
+ * - a redirect location
+ */
+ Wicket.Ajax.Call = Wicket.Class.create();
+
+ Wicket.Ajax._currentSuspension = undefined;
+
+ /**
+ * Suspend the currently evaluated Ajax call, fails if no Ajax call is currently
+ * evaluated.
+ */
+ Wicket.Ajax.suspendCall = function () {
+ let suspension = Wicket.Ajax._currentSuspension;
+
+ if (suspension === undefined) {
+ Wicket.Log.error("Can't suspend: no Ajax call in process");
+ return;
+ }
+
+ // suspend
+ suspension.suspend();
+
+ return function () {
+ // release only once
+ if (suspension !== null) {
+ suspension.release();
+ suspension = null;
+ }
+ };
+ };
+
+ /**
+ * Serializes an array of {name, value} pairs to an
+ * 'application/x-www-form-urlencoded' query string.
+ */
+ const paramsToQueryString = function (params) {
+ if (!params || !params.length) {
+ return '';
+ }
+ const parts = [];
+ for (let i = 0; i < params.length; i++) {
+ let value = params[i].value;
+ if (isUndef(value)) {
+ value = '';
+ }
+ parts.push(encodeURIComponent(params[i].name) + '=' + encodeURIComponent(value));
+ }
+ return parts.join('&');
+ };
+
+ /**
+ * Performs an XMLHttpRequest based request. Mimics the subset of jQuery.ajax()'s
+ * behavior that Wicket.Ajax.Call relies on: GET/POST, custom headers, disabling the
+ * cache, sending either an url-encoded body or a FormData body, a timeout, and
+ * success/error/complete/beforeSend callbacks that receive the XMLHttpRequest object
+ * itself (which already exposes readyState, status, getResponseHeader(), responseText
+ * and responseXML, so a separate 'jqXHR' wrapper is not needed).
+ *
+ * @param options {Object} - url, type ('GET'/'POST'), data (an array of {name, value}
+ * pairs, or a FormData instance), dataType ('xml' to parse the response body as
+ * XML), headers, async, timeout, cache, beforeSend(xhr, options),
+ * success(data, textStatus, xhr), error(xhr, textStatus, errorMessage),
+ * complete(xhr, textStatus)
+ */
+ const ajaxRequest = function (options) {
+ const xhr = new XMLHttpRequest();
+ const method = (options.type || 'GET').toUpperCase();
+ let url = options.url;
+ const data = options.data;
+ const isFormData = (typeof(FormData) !== 'undefined') && (data instanceof FormData);
+ let body = null;
+
+ if (isFormData) {
+ body = data;
+ } else {
+ const queryString = paramsToQueryString(data);
+ if (method === 'GET' || method === 'HEAD') {
+ if (queryString) {
+ url += (url.indexOf('?') > -1 ? '&' : '?') + queryString;
+ }
+ } else {
+ body = queryString;
+ }
+ }
+
+ if (options.cache === false && (method === 'GET' || method === 'HEAD')) {
+ url += (url.indexOf('?') > -1 ? '&' : '?') + '_=' + new Date().getTime();
+ }
+
+ // reflect the fully resolved url/body back onto the options ("settings") object,
+ // the same way jQuery.ajax() does, so that beforeSend (and anything else inspecting
+ // it) sees the request as it is actually going to be sent
+ options.url = url;
+ if (!isFormData) {
+ options.data = body;
+ }
+
+ xhr.open(method, url, options.async !== false);
+
+ if (!isFormData && method !== 'GET' && method !== 'HEAD') {
+ xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
+ }
+
+ const headers = options.headers || {};
+ for (const headerName in headers) {
+ if (headers.hasOwnProperty(headerName)) {
+ xhr.setRequestHeader(headerName, headers[headerName]);
+ }
+ }
+
+ if (options.async !== false && options.timeout) {
+ xhr.timeout = options.timeout;
+ }
+
+ let textStatus;
+ let completed = false;
+ const finish = function () {
+ if (completed) {
+ return;
+ }
+ completed = true;
+ if (options.complete) {
+ options.complete(xhr, textStatus);
+ }
+ };
+
+ xhr.onload = function () {
+ const status = xhr.status;
+ if ((status >= 200 && status < 300) || status === 304) {
+ textStatus = 'success';
+ let responseData = xhr.responseText;
+ if (options.dataType === 'xml') {
+ responseData = Wicket.Xml.parse(xhr.responseText);
+ } else if (options.dataType === 'json') {
+ try {
+ responseData = responseData ? JSON.parse(responseData) : null;
+ } catch (parseError) {
+ textStatus = 'parsererror';
+ if (options.error) {
+ options.error(xhr, textStatus, parseError.message);
+ }
+ finish();
+ return;
+ }
+ }
+ if (options.success) {
+ options.success(responseData, textStatus, xhr);
+ }
+ } else {
+ textStatus = 'error';
+ if (options.error) {
+ options.error(xhr, textStatus, xhr.statusText);
+ }
+ }
+ finish();
+ };
+
+ xhr.onerror = function () {
+ textStatus = 'error';
+ if (options.error) {
+ options.error(xhr, textStatus, xhr.statusText);
+ }
+ finish();
+ };
+
+ xhr.ontimeout = function () {
+ textStatus = 'timeout';
+ if (options.error) {
+ options.error(xhr, textStatus, 'timeout');
+ }
+ finish();
+ };
+
+ xhr.onabort = function () {
+ textStatus = 'abort';
+ finish();
+ };
+
+ if (options.beforeSend) {
+ options.beforeSend(xhr, options);
+ }
+
+ xhr.send(body);
+
+ return xhr;
+ };
+
+ Wicket.Ajax.Call.prototype = {
+
+ initialize: function () {},
+
+ /**
+ * Initializes the default values for Ajax request attributes.
+ * The defaults are not set at the server side to save some bytes
+ * for the network transfer
+ *
+ * @param attrs {Object} - the ajax request attributes to enrich
+ * @private
+ */
+ _initializeDefaults: function (attrs) {
+
+ // (ajax channel)
+ if (typeof(attrs.ch) !== 'string') {
+ attrs.ch = '0|s';
+ }
+
+ // (wicketAjaxResponse) be default the Ajax result should be processed for <ajax-response>
+ if (typeof(attrs.wr) !== 'boolean') {
+ attrs.wr = true;
+ }
+
+ // (dataType) by default we expect XML responses from the Ajax behaviors
+ if (typeof(attrs.dt) !== 'string') {
+ attrs.dt = 'xml';
+ }
+
+ if (typeof(attrs.m) !== 'string') {
+ attrs.m = 'GET';
+ }
+
+ if (attrs.async !== false) {
+ attrs.async = true;
+ }
+
+ if (!Number.isFinite(attrs.rt)) {
+ attrs.rt = 0;
+ }
+
+ if (attrs.pd !== true) {
+ attrs.pd = false;
+ }
+
+ if (!attrs.sp) {
+ attrs.sp = "bubble";
+ }
+
+ if (!attrs.sr) {
+ attrs.sr = false;
+ }
+ },
+
+ /**
+ * Extracts the HTML element that "caused" this Ajax call.
+ * An Ajax call is usually caused by JavaScript event but maybe be also
+ * caused by manual usage of the JS API..
+ *
+ * @param attrs {Object} - the ajax request attributes
+ * @return {HTMLElement} - the DOM element
+ * @private
+ */
+ _getTarget: function (attrs) {
+ let target;
+ if (attrs.event) {
+ target = attrs.event.target;
+ } else if (!Wicket.isWindow(attrs.c)) {
+ target = Wicket.$(attrs.c);
+ } else {
+ target = window;
+ }
+ return target;
+ },
+
+ /**
+ * A helper function that executes an array of handlers (before, success, failure)
+ *
+ * @param handlers {Array[Function]} - the handlers to execute
+ * @private
+ */
+ _executeHandlers: function (handlers) {
+ if (Array.isArray(handlers)) {
+
+ // cut the handlers argument
+ const args = Array.prototype.slice.call(arguments).slice(1);
+
+ // assumes that the Ajax attributes is always the first argument
+ const attrs = args[0];
+ const that = this._getTarget(attrs);
+
+ for (let i = 0; i < handlers.length; i++) {
+ const handler = handlers[i];
+ if (Wicket.isFunction(handler)) {
+ handler.apply(that, args);
+ } else {
+ new Function(handler).apply(that, args);
+ }
+ }
+ }
+ },
+
+ /**
+ * Converts an object (hash) to an array suitable for consumption
+ * as request parameters.
+ *
+ * @param {Object} parameters - the object to convert to an array of
+ * name -> value pairs.
+ * @private
+ */
+ _asParamArray: function(parameters) {
+ let result = [],
+ value,
+ name;
+ if (Array.isArray(parameters)) {
+ result = parameters;
+ }
+ else if (isPlainObject(parameters)) {
+ for (name in parameters) {
+ if (name && parameters.hasOwnProperty(name)) {
+ value = parameters[name];
+ result.push({name: name, value: value});
+ }
+ }
+ }
+
+ for (let i = 0; i < result.length; i++) {
+ if (result[i] === null) {
+ result.splice(i, 1);
+ i--;
+ }
+ }
+
+ return result;
+ },
+
+ /**
+ * Executes all functions to calculate any dynamic extra parameters
+ *
+ * @param attrs The Ajax request attributes
+ * @returns {String} A query string snippet with any calculated request
+ * parameters. An empty string if there are no dynamic parameters in attrs
+ * @private
+ */
+ _calculateDynamicParameters: function(attrs) {
+ const deps = attrs.dep;
+ let params = [];
+
+ for (let i = 0; i < deps.length; i++) {
+ const dep = deps[i];
+ let extraParam;
+ if (Wicket.isFunction(dep)) {
+ extraParam = dep(attrs);
+ } else {
+ extraParam = new Function('attrs', dep)(attrs);
+ }
+ extraParam = this._asParamArray(extraParam);
+ params = params.concat(extraParam);
+ }
+ return params;
+ },
+
+ /**
+ * Executes or schedules for execution #doAjax()
+ *
+ * @param {Object} attrs - the Ajax request attributes configured at the server side
+ */
+ ajax: function (attrs) {
+ this._initializeDefaults(attrs);
+
+ const res = Wicket.channelManager.schedule(attrs.ch, Wicket.bind(function () {
+ this.doAjax(attrs);
+ }, this));
+ return res !== null ? res: true;
+ },
+
+ /**
+ * Is an element still present for Ajax requests.
+ */
+ _isPresent: function(id) {
+ if (isUndef(id)) {
+ // no id so no check whether present
+ return true;
+ }
+
+ const element = Wicket.$(id);
+ if (isUndef(element)) {
+ // not present
+ return false;
+ }
+
+ // present if no attributes at all or not a placeholder
+ return (!element.hasAttribute || !element.hasAttribute('data-wicket-placeholder'));
+ },
+
+ /**
+ * Handles execution of Ajax calls.
+ *
+ * @param {Object} attrs - the Ajax request attributes configured at the server side
+ */
+ doAjax: function (attrs) {
+
+ // the headers to use for each Ajax request
+ const headers = {
+ 'Wicket-Ajax': 'true',
+ 'Wicket-Ajax-BaseURL': getAjaxBaseUrl()
+ };
+
+ let url = attrs.u;
+
+ // the request (extra) parameters
+ let data = this._asParamArray(attrs.ep);
+
+ const self = this;
+
+ // the precondition to use if there are no explicit ones
+ const defaultPrecondition = [ function (attributes) {
+ return self._isPresent(attributes.c) && self._isPresent(attributes.f);
+ }];
+
+ // a context that brings the common data for the success/fialure/complete handlers
+ const context = {
+ attrs: attrs,
+
+ // initialize the array for steps (closures that execute each action)
+ steps: []
+ };
+ const we = Wicket.Event;
+ const topic = we.Topic;
+
+ if (Wicket.Focus.lastFocusId) {
+ // WICKET-6568 might contain non-ASCII
+ headers["Wicket-FocusedElementId"] = Wicket.Form.encode(Wicket.Focus.lastFocusId);
+ }
+
+ self._executeHandlers(attrs.bh, attrs);
+ we.publish(topic.AJAX_CALL_BEFORE, attrs);
+
+ let preconditions = attrs.pre || [];
+ preconditions = defaultPrecondition.concat(preconditions);
+ if (Array.isArray(preconditions)) {
+
+ const that = this._getTarget(attrs);
+
+ for (let p = 0; p < preconditions.length; p++) {
+
+ const precondition = preconditions[p];
+ let result;
+ if (Wicket.isFunction(precondition)) {
+ result = precondition.call(that, attrs);
+ } else {
+ result = new Function(precondition).call(that, attrs);
+ }
+ if (result === false) {
+ Wicket.Log.info("Ajax request stopped because of precondition check, url: %s", attrs.u);
+ self.done(attrs);
+ return false;
+ }
+ }
+ }
+
+ we.publish(topic.AJAX_CALL_PRECONDITION, attrs);
+
+ if (attrs.f) {
+ // serialize the form with id == attrs.f
+ const form = Wicket.$(attrs.f);
+ data = data.concat(Wicket.Form.serializeForm(form));
+
+ // set the submitting component input name
+ if (attrs.sc) {
+ const scName = attrs.sc;
+ data = data.concat({name: scName, value: 1});
+ }
+ } else if (attrs.c && !Wicket.isWindow(attrs.c)) {
+ // serialize just the form component with id == attrs.c
+ const el = Wicket.$(attrs.c);
+ data = data.concat(Wicket.Form.serializeElement(el, attrs.sr));
+ }
+
+ // collect the dynamic extra parameters
+ if (Array.isArray(attrs.dep)) {
+ const dynamicData = this._calculateDynamicParameters(attrs);
+ if (attrs.m.toLowerCase() === 'post') {
+ data = data.concat(dynamicData);
+ } else {
+ const separator = url.indexOf('?') > -1 ? '&' : '?';
+ url = url + separator + paramsToQueryString(dynamicData);
+ }
+ }
+
+ let isMultipart = false;
+ if (attrs.mp) {
+ try {
+ const formData = new FormData();
+ for (let i = 0; i < data.length; i++) {
+ formData.append(data[i].name, data[i].value || "");
+ }
+
+ data = formData;
+ isMultipart = true;
+ } catch (exception) {
+ Wicket.Log.error("Ajax multipart not supported:", exception);
+ }
+ }
+
+ Wicket.Log.info("Executing Ajax request");
+ Wicket.Log.debug(attrs);
+
+ // execute the request
+ const xhr = ajaxRequest({
+ url: url,
+ type: attrs.m,
+
+ beforeSend: function (xhr, settings) {
+ self._executeHandlers(attrs.bsh, attrs, xhr, settings);
+ we.publish(topic.AJAX_CALL_BEFORE_SEND, attrs, xhr, settings);
+
+ if (attrs.i) {
+ // show the indicator
+ Wicket.DOM.showIncrementally(attrs.i);
+ }
+ },
+ data: data,
+ dataType: attrs.dt,
+ async: attrs.async,
+ timeout: attrs.rt,
+ cache: false,
+ headers: headers,
+ success: function(data, textStatus, xhr) {
+ if (attrs.wr) {
+ self.processAjaxResponse(data, textStatus, xhr, context);
+ } else {
+ self._executeHandlers(attrs.sh, attrs, xhr, data, textStatus);
+ we.publish(topic.AJAX_CALL_SUCCESS, attrs, xhr, data, textStatus);
+ }
+ },
+ error: function(xhr, textStatus, errorMessage) {
+ if (xhr.status === 301 && xhr.getResponseHeader('Ajax-Location')) {
+ self.processAjaxResponse(data, textStatus, xhr, context);
+ } else {
+ self.failure(context, xhr, errorMessage, textStatus);
+ }
+ },
+ complete: function (xhr, textStatus) {
+
+ context.steps.push((function (notify) {
+ if (attrs.i && context.isRedirecting !== true) {
+ Wicket.DOM.hideIncrementally(attrs.i);
+ }
+
+ self._executeHandlers(attrs.coh, attrs, xhr, textStatus);
+ we.publish(topic.AJAX_CALL_COMPLETE, attrs, xhr, textStatus);
+
+ self.done(attrs);
+ return FunctionsExecuter.DONE;
+ }).bind(self));
+
+ const executer = new FunctionsExecuter(context.steps);
+ executer.start();
+ }
+ });
+
+ // execute after handlers right after the Ajax request is fired
+ self._executeHandlers(attrs.ah, attrs);
+ we.publish(topic.AJAX_CALL_AFTER, attrs);
+
+ return xhr;
+ },
+
+ /**
+ * Method that processes a manually supplied <ajax-response>.
+ *
+ * @param data {XmlDocument} - the <ajax-response> XML document
+ */
+ process: function(data) {
+ const context = {
+ attrs: {},
+ steps: []
+ };
+ const xmlDocument = Wicket.Xml.parse(data);
+ this.loadedCallback(xmlDocument, context);
+ const executer = new FunctionsExecuter(context.steps);
+ executer.start();
+ },
+
+ /**
+ * Method that processes the <ajax-response> in the context of an XMLHttpRequest.
+ *
+ * @param data {XmlDocument} - the <ajax-response> XML document
+ * @param textStatus {String} - the response status as text (e.g. 'success', 'parsererror', etc.)
+ * @param xhr {XMLHttpRequest} - the XMLHttpRequest of the Ajax call
+ * @param context {Object} - the request context with the Ajax request attributes and the FunctionExecuter's steps
+ */
+ processAjaxResponse: function (data, textStatus, xhr, context) {
+
+ if (xhr.readyState === 4) {
+
+ // first try to get the redirect header
+ let redirectUrl;
+ try {
+ redirectUrl = xhr.getResponseHeader('Ajax-Location');
+ } catch (ignore) { // might happen in older mozilla
+ }
+
+ // the redirect header was set, go to new url
+ if (typeof(redirectUrl) !== "undefined" && redirectUrl !== null && redirectUrl !== "") {
+
+ // In case the page isn't really redirected. For example say the redirect is to an octet-stream.
+ // A file download popup will appear but the page in the browser won't change.
+ this.success(context);
+
+ const withScheme = /^[a-z][a-z0-9+.-]*:\/\//; // checks whether the string starts with a scheme
+
+ // support/check for non-relative redirectUrl like as provided and needed in a portlet context
+ if (redirectUrl.charAt(0) === '/' || withScheme.test(redirectUrl)) {
+ context.isRedirecting = true;
+ Wicket.Ajax.redirect(redirectUrl);
+ }
+ else {
+ let urlDepth = 0;
+ while (redirectUrl.substring(0, 3) === "../") {
+ urlDepth++;
+ redirectUrl = redirectUrl.substring(3);
+ }
+ // Make this a string.
+ let calculatedRedirect = window.location.pathname;
+ while (urlDepth > -1) {
+ urlDepth--;
+ const i = calculatedRedirect.lastIndexOf("/");
+ if (i > -1) {
+ calculatedRedirect = calculatedRedirect.substring(0, i);
+ }
+ }
+ calculatedRedirect += "/" + redirectUrl;
+
+ context.isRedirecting = true;
+ Wicket.Ajax.redirect(calculatedRedirect);
+ }
+ }
+ else {
+ // no redirect, just regular response
+ Wicket.Log.info("Received ajax response (%s characters)", xhr.responseText.length);
+ Wicket.Log.debug(xhr.responseXML);
+
+ // invoke the loaded callback with an xml document
+ return this.loadedCallback(data, context);
+ }
+ }
+ },
+
+ // Processes the response
+ loadedCallback: function (envelope, context) {
+ // To process the response, we go through the xml document and add a function for every action (step).
+ // After this is done, a FunctionExecuter object asynchronously executes these functions.
+ // The asynchronous execution is necessary, because some steps might involve loading external javascript,
+ // which must be asynchronous, so that it doesn't block the browser, but we also have to maintain
+ // the order in which scripts are loaded and we have to delay the next steps until the script is
+ // loaded.
+ try {
+ const root = envelope.getElementsByTagName("ajax-response")[0];
+
+ // the root element must be <ajax-response
+ if (isUndef(root) || root.tagName !== "ajax-response") {
+ this.failure(context, null, "Could not find root <ajax-response> element", null);
+ return;
+ }
+
+ const steps = context.steps;
+
+ // go through the ajax response and process priority evaluations and
+ // header contributions first
+ for (let i = 0; i < root.childNodes.length; ++i) {
+ const childNode = root.childNodes[i];
+ if (childNode.tagName === "header-contribution") {
+ this.processHeaderContribution(context, childNode);
+ } else if (childNode.tagName === "priority-evaluate") {
+ this.processHeaderContribution(context, childNode);
+ }
+ }
+
+ // ... then add components, process remaining evaluations and a
+ // possible redirect
+ let stepIndexOfLastReplacedComponent = -1;
+ for (let c = 0; c < root.childNodes.length; ++c) {
+ const node = root.childNodes[c];
+
+ if (node.tagName === "component") {
+ if (stepIndexOfLastReplacedComponent === -1) {
+ this.processFocusedComponentMark(context);
+ }
+ stepIndexOfLastReplacedComponent = steps.length;
+ this.processComponent(context, node);
+ } else if (node.tagName === "evaluate") {
+ this.processHeaderContribution(context, node);
+ } else if (node.tagName === "redirect") {
+ this.processRedirect(context, node);
+ }
+ }
+ if (stepIndexOfLastReplacedComponent !== -1) {
+ this.processFocusedComponentReplaceCheck(steps, stepIndexOfLastReplacedComponent);
+ }
+
+ // add the last step, which should trigger the success call the done method on request
+ this.success(context);
+
+ } catch (exception) {
+ this.failure(context, null, exception, null);
+ }
+ },
+
+ // Adds a closure to steps that should be invoked after all other steps have been successfully executed
+ success: function (context) {
+ context.steps.push((function (notify) {
+ Wicket.Log.info("Response processed successfully.");
+
+ const attrs = context.attrs;
+ this._executeHandlers(attrs.sh, attrs, null, null, 'success');
+ Wicket.Event.publish(Wicket.Event.Topic.AJAX_CALL_SUCCESS, attrs, null, null, 'success');
+
+ Wicket.Focus.requestFocus();
+
+ // continue to next step (which should make the processing stop, as success should be the final step)
+ return FunctionsExecuter.DONE;
+ }).bind(this));
+ },
+
+ // On ajax request failure
+ failure: function (context, xhr, errorMessage, textStatus) {
+ context.steps.push((function (notify) {
+ if (errorMessage) {
+ Wicket.Log.error("Wicket.Ajax.Call.failure: Error while parsing response: %s", errorMessage);
+ }
+ const attrs = context.attrs;
+ this._executeHandlers(attrs.fh, attrs, xhr, errorMessage, textStatus);
+ Wicket.Event.publish(Wicket.Event.Topic.AJAX_CALL_FAILURE, attrs, xhr, errorMessage, textStatus);
+
+ return FunctionsExecuter.DONE;
+ }).bind(this));
+ },
+
+ done: function (attrs) {
+ this._executeHandlers(attrs.dh, attrs);
+ Wicket.Event.publish(Wicket.Event.Topic.AJAX_CALL_DONE, attrs);
+
+ Wicket.channelManager.done(attrs.ch);
+ },
+
+ // Adds a closure that replaces a component
+ processComponent: function (context, node) {
+ context.steps.push(function (notify) {
+ // get the component id
+ const compId = node.getAttribute("id");
+
+ // get existing component
+ const element = Wicket.$(compId);
+
+ if (isUndef(element)) {
+ Wicket.Log.error("Wicket.Ajax.Call.processComponent: Component with id '%s' was not found while trying to perform markup update. " +
+ "Make sure you called component.setOutputMarkupId(true) on the component whose markup you are trying to update.", compId);
+ } else {
+ const text = Wicket.DOM.text(node);
+
+ // replace the component
+ Wicket.DOM.replace(element, text);
+ }
+ // continue to next step
+ return FunctionsExecuter.DONE;
+ });
+ },
+
+ // Adds a closure that processes a header contribution
+ processHeaderContribution: function (context, node) {
+ const c = Wicket.Head.Contributor;
+ c.processContribution(context, node);
+ },
+
+ // Adds a closure that processes a redirect
+ processRedirect: function (context, node) {
+ const text = Wicket.DOM.text(node);
+ Wicket.Log.info("Redirecting to: %s", text);
+ context.isRedirecting = true;
+ Wicket.Ajax.redirect(text);
+ },
+
+ // mark the focused component so that we know if it has been replaced by response
+ processFocusedComponentMark: function (context) {
+ context.steps.push(function (notify) {
+ Wicket.Focus.markFocusedComponent();
+
+ // continue to next step
+ return FunctionsExecuter.DONE;
+ });
+ },
+
+ // detect if the focused component was replaced
+ processFocusedComponentReplaceCheck: function (steps, lastReplaceComponentStep) {
+ // add this step imediately after all components have been replaced
+ steps.splice(lastReplaceComponentStep + 1, 0, function (notify) {
+ Wicket.Focus.checkFocusedComponentReplaced();
+
+ // continue to next step
+ return FunctionsExecuter.DONE;
+ });
+ }
+ };
+
+
+ /**
+ * Throttler's purpose is to make sure that ajax requests wont be fired too often.
+ */
+ Wicket.ThrottlerEntry = Wicket.Class.create();
+
+ Wicket.ThrottlerEntry.prototype = {
+ initialize: function (func) {
+ this.func = func;
+ this.timestamp = new Date().getTime();
+ this.timeoutVar = undefined;
+ },
+
+ getTimestamp: function () {
+ return this.timestamp;
+ },
+
+ getFunc: function () {
+ return this.func;
+ },
+
+ setFunc: function (func) {
+ this.func = func;
+ },
+
+ getTimeoutVar: function () {
+ return this.timeoutVar;
+ },
+
+ setTimeoutVar: function (timeoutVar) {
+ this.timeoutVar = timeoutVar;
+ }
+ };
+
+ Wicket.Throttler = Wicket.Class.create();
+
+ // declare it as static so that it can be shared between Throttler instances
+ Wicket.Throttler.entries = [];
+
+ Wicket.Throttler.prototype = {
+
+ /* "postponeTimerOnUpdate" is an optional parameter. If it is set to true, then the timer is
+ reset each time the throttle function gets called. Use this behaviour if you want something
+ to happen at X milliseconds after the *last* call to throttle.
+ If the parameter is not set, or set to false, then the timer is not reset. */
+ initialize: function (postponeTimerOnUpdate) {
+ this.postponeTimerOnUpdate = postponeTimerOnUpdate;
+ },
+
+ throttle: function (id, millis, func) {
+ const entries = Wicket.Throttler.entries;
+ let entry = entries[id];
+ const me = this;
+ if (typeof(entry) === 'undefined') {
+ entry = new Wicket.ThrottlerEntry(func);
+ entry.setTimeoutVar(window.setTimeout(function() { me.execute(id); }, millis));
+ entries[id] = entry;
+ } else {
+ entry.setFunc(func);
+ if (this.postponeTimerOnUpdate)
+ {
+ window.clearTimeout(entry.getTimeoutVar());
+ entry.setTimeoutVar(window.setTimeout(function() { me.execute(id); }, millis));
+ }
+ }
+ },
+
+ execute: function (id) {
+ const entries = Wicket.Throttler.entries;
+ const entry = entries[id];
+ if (typeof(entry) !== 'undefined') {
+ const func = entry.getFunc();
+ entries[id] = undefined;
+ return func();
+ }
+ }
+ };
+
+
+ Wicket.channelManager = new Wicket.ChannelManager();
+
+ Wicket.throttler = new Wicket.Throttler();
+
+ Wicket.$ = function (arg) {
+ return Wicket.DOM.get(arg);
+ };
+
+ /**
+ * returns if the element belongs to current document
+ * if the argument is not element, function returns true
+ */
+ Wicket.$$ = function (element) {
+ return Wicket.DOM.inDoc(element);
+ };
+
+ /**
+ * Merges two objects. Values of the second will overwrite values of the first.
+ *
+ * @param {Object} object1 - the first object to merge
+ * @param {Object} object2 - the second object to merge
+ * @return {Object} a new object with the values of object1 and object2
+ */
+ Wicket.merge = function(object1, object2) {
+ return Object.assign({}, object1, object2);
+ };
+
+ /**
+ * Takes a function and returns a new one that will always have a particular context, i.e. 'this' will be the passed context.
+ *
+ * @param {Function} fn - the function which context will be set
+ * @param {Object} context - the new context for the function
+ * @return {Function} the original function with the changed context
+ */
+ Wicket.bind = function(fn, context) {
+ return fn.bind(context);
+ };
+
+ Wicket.Xml = {
+ parse: function (text) {
+ const parser = new DOMParser();
+
+ const xmlDocument = parser.parseFromString(text, "text/xml");
+
+ return xmlDocument;
+ }
+ };
+
+ /**
+ * Form serialization
+ *
+ * To post a form using Ajax Wicket first needs to serialize it, which means composing a string
+ * from form elments names and values. The string will then be set as body of POST request.
+ */
+
+ Wicket.Form = {
+ encode: function (text) {
+ return window.encodeURIComponent(text);
+ },
+
+ /**
+ * Serializes HTMLFormSelectElement to URL encoded key=value string.
+ *
+ * @param select {HTMLFormSelectElement} - the form element to serialize
+ * @return an object of key -> value pair where 'value' can be an array of Strings if the select is .multiple,
+ * or empty object if the form element is disabled.
+ */
+ serializeSelect: function (select){
+ const result = [];
+ if (select && select.disabled === false) {
+ const name = select.name;
+ if (select.multiple) {
+ for (let i = 0; i < select.options.length; i++) {
+ const option = select.options[i];
+ if (option.selected && !option.disabled) {
+ result.push({ name: name, value: option.value });
+ }
+ }
+ } else {
+ const selectedIndex = select.selectedIndex;
+ const value = selectedIndex >= 0 ? select.options[selectedIndex].value : null;
+ result.push({ name: name, value: value });
+ }
+ }
+ return result;
+ },
+
+ /**
+ * Serializes a form element to an array with a single element - an object
+ * with two keys - <em>name</em> and <em>value</em>.
+ *
+ * Example: [{"name": "searchTerm", "value": "abc"}].
+ *
+ * Note: this function intentionally ignores image and submit inputs.
+ *
+ * @param input {HtmlFormElement} - the form element to serialize
+ * @return the URL encoded key=value pair or empty string if the form element is disabled.
+ */
+ serializeInput: function (input) {
+ const result = [];
+ if (input && input.type) {
+ if (input.type === 'file') {
+ for (let f = 0; f < input.files.length; f++) {
+ result.push({"name" : input.name, "value" : input.files[f]});
+ }
+ } else if (input.type === 'image' || input.type === 'submit') {
+ // intentionally ignored
+ } else if (!input.disabled && input.name) {
+ const checkable = (input.type === 'checkbox' || input.type === 'radio');
+ if (!checkable || input.checked) {
+ result.push({ name: input.name, value: input.value });
+ }
+ }
+ }
+ return result;
+ },
+
+ /**
+ * A hash of HTML form element to exclude from serialization
+ * As key the element's id is being used.
+ * As value - the string "true".
+ */
+ excludeFromAjaxSerialization: {
+ },
+
+ /**
+ * Serializes a form element by checking its type and delegating the work to
+ * a more specific function.
+ *
+ * The form element will be ignored if it is registered as excluded in
+ * <em>Wicket.Form.excludeFromAjaxSerialization</em>
+ *
+ * @param element {HTMLFormElement} - the form element to serialize. E.g. HTMLInputElement
+ * @param serializeRecursively {Boolean} - a flag indicating whether to collect (submit) the
+ * name/value pairs for all HTML form elements children of the HTML element with
+ * the JavaScript listener
+ * @return An array with a single element - an object with two keys - <em>name</em> and <em>value</em>.
+ */
+ serializeElement: function(element, serializeRecursively) {
+
+ if (!element) {
+ return [];
+ }
+ else if (typeof(element) === 'string') {
+ element = Wicket.$(element);
+ }
+
+ if (Wicket.Form.excludeFromAjaxSerialization && element.id && Wicket.Form.excludeFromAjaxSerialization[element.id] === "true") {
+ return [];
+ }
+
+ const tag = element.tagName.toLowerCase();
+ if (tag === "select") {
+ return Wicket.Form.serializeSelect(element);
+ } else if (tag === "input" || tag === "textarea") {
+ return Wicket.Form.serializeInput(element);
+ } else {
+ let result = [];
+ if (serializeRecursively) {
+ let elements = nodeListToArray(element.getElementsByTagName("input"));
+ elements = elements.concat(nodeListToArray(element.getElementsByTagName("select")));
+ elements = elements.concat(nodeListToArray(element.getElementsByTagName("textarea")));
+
+ for (let i = 0; i < elements.length; ++i) {
+ const el = elements[i];
+ if (el.name && el.name !== "") {
+ result = result.concat(Wicket.Form.serializeElement(el, serializeRecursively));
+ }
+ }
+ }
+ return result;
+ }
+ },
+
+ serializeForm: function (form) {
+ let result = [],
+ elements;
+
+ if (form) {
+ if (form.tagName.toLowerCase() === 'form') {
+ elements = form.elements;
+ } else {
+ do {
+ form = form.parentNode;
+ } while (form.tagName.toLowerCase() !== "form" && form.tagName.toLowerCase() !== "body");
+
+ elements = nodeListToArray(form.getElementsByTagName("input"));
+ elements = elements.concat(nodeListToArray(form.getElementsByTagName("select")));
+ elements = elements.concat(nodeListToArray(form.getElementsByTagName("textarea")));
+ }
+ }
+
+ for (let i = 0; i < elements.length; ++i) {
+ const el = elements[i];
+ if (el.name && el.name !== "") {
+ result = result.concat(Wicket.Form.serializeElement(el, false));
+ }
+ }
+ return result;
+ },
+
+ serialize: function (element, dontTryToFindRootForm) {
+ if (typeof(element) === 'string') {
+ element = Wicket.$(element);
+ }
+
+ if (element.tagName.toLowerCase() === "form") {
+ return Wicket.Form.serializeForm(element);
+ } else {
+ // try to find a form in DOM parents
+ const elementBck = element;
+
+ if (dontTryToFindRootForm !== true) {
+ do {
+ element = element.parentNode;
+ } while(element.tagName.toLowerCase() !== "form" && element.tagName.toLowerCase() !== "body");
+ }
+
+ if (element.tagName.toLowerCase() === "form"){
+ return Wicket.Form.serializeForm(element);
+ } else {
+ // there is not form in dom hierarchy
+ // simulate it
+ const form = document.createElement("form");
+ const parent = elementBck.parentNode;
+
+ parent.replaceChild(form, elementBck);
+ form.appendChild(elementBck);
+ const result = Wicket.Form.serializeForm(form);
+ parent.replaceChild(elementBck, form);
+
+ return result;
+ }
+ }
+ }
+ };
+
+ /**
+ * DOM nodes serialization functionality
+ *
+ * The purpose of these methods is to return a string representation
+ * of the DOM tree.
+ */
+ Wicket.DOM = {
+
+ /**
+ * Shows an element
+ * @param {HTMLElement | String} e The HTML element (or its id) to show
+ * @param {String} display The value of CSS display property to use,
+ * e.g. 'block', 'inline'. Optional
+ */
+ show: function (e, display) {
+ e = Wicket.$(e);
+ if (e !== null) {
+ if (isUndef(display)) {
+ // no explicit 'display' value is requested so let the stylesheet decide,
+ // falling back to the browser's default display value for this tag if the
+ // element still isn't actually rendering with a size afterwards (covers
+ // both an ancestor/stylesheet hiding it and it being empty of content)
+ e.style.display = '';
+ const rects = e.getClientRects();
+ if (!rects.length || !rects[0].width) {
+ e.style.display = defaultDisplay(e.tagName);
+ }
+ } else {
+ e.style.display = display;
+ }
+ e.removeAttribute("hidden");
+ }
+ },
+
+ /** hides an element */
+ hide: function (e) {
+ e = Wicket.$(e);
+ if (e !== null) {
+ e.style.display = 'none';
+ e.setAttribute("hidden", "");
+ }
+ },
+
+ /**
+ * Add or remove one or more classes from each element in the
+ * set of matched elements, depending on either the class's presence
+ * or the value of the switch argument.
+ *
+ * @param {String} elementId The markup id of the element that will be manipulated.
+ * @param {String} cssClass One or more class names (separated by spaces)
+ * to be toggled for each element in the matched set.
+ * @param {Boolean} Switch A Boolean (not just truthy/falsy) value to
+ * determine whether the class should be added or removed.
+ */
+ toggleClass: function(elementId, cssClass, Switch) {
+ const e = document.getElementById(elementId);
+ if (e) {
+ const classes = cssClass.split(/\s+/);
+ for (let i = 0; i < classes.length; i++) {
+ if (classes[i]) {
+ e.classList.toggle(classes[i], Switch);
+ }
+ }
+ }
+ },
+
+ /** call-counting implementation of Wicket.DOM.show() */
+ showIncrementally: function (e) {
+ e = Wicket.$(e);
+ if (e === null) {
+ return;
+ }
+ let count = e.getAttribute("showIncrementallyCount");
+ count = parseInt(isUndef(count) ? 0 : count, 10);
+ if (count >= 0) {
+ Wicket.DOM.show(e);
+ }
+ e.setAttribute("showIncrementallyCount", count + 1);
+ },
+
+ /** call-counting implementation of Wicket.DOM.hide() */
+ hideIncrementally: function(e) {
+ e = Wicket.$(e);
+ if (e === null) {
+ return;
+ }
+ let count = e.getAttribute("showIncrementallyCount");
+ count = parseInt(isUndef(count) ? 0 : count - 1, 10);
+ if (count <= 0) {
+ Wicket.DOM.hide(e);
+ }
+ e.setAttribute("showIncrementallyCount", count);
+ },
+
+ get: function (arg) {
+ if (isUndef(arg)) {
+ return null;
+ }
+ if (arguments.length > 1) {
+ const e = [];
+ for (let i = 0; i < arguments.length; i++) {
+ e.push(Wicket.DOM.get(arguments[i]));
+ }
+ return e;
+ } else if (typeof arg === 'string') {
+ return document.getElementById(arg);
+ } else {
+ return arg;
+ }
+ },
+
+ /**
+ * returns if the element belongs to current document
+ * if the argument is not element, function returns true
+ */
+ inDoc: function (element) {
+ if (element === window) {
+ return true;
+ }
+ if (typeof(element) === "string") {
+ element = Wicket.$(element);
+ }
+ if (isUndef(element) || isUndef(element.tagName)) {
+ return false;
+ }
+
+ const id = element.getAttribute('id');
+ if (isUndef(id) || id === "") {
+ return element.ownerDocument === document;
+ }
+ else {
+ return document.getElementById(id) === element;
+ }
+ },
+
+ /**
+ * A cross-browser method that replaces the markup of an element. The behavior
+ * is similar to calling element.outerHtml=text in internet explorer. However
+ * this method also takes care of executing javascripts within the markup on
+ * browsers that don't do that automatically.
+ * Also this method takes care of replacing table elements (tbody, tr, td, thead)
+ * by parsing the markup with a <template> element, which (unlike setting
+ * innerHTML on a plain container) correctly parses such elements without needing
+ * them to be wrapped in a <table>.
+ *
+ * This method sends notifications to all subscribers for channels with names
+ * '/dom/node/removing' with the element that is going to be replaced and
+ * '/dom/node/added' with the newly created element (the replacement).
+ *
+ * Note: the 'to be replaced' element must have an 'id' attribute
+ */
+ replace: function (element, text) {
+
+ const we = Wicket.Event;
+ const topic = we.Topic;
+
+ we.publish(topic.DOM_NODE_REMOVING, element);
+
+ if (element.tagName.toLowerCase() === "title") {
+ // match the text between the tags
+ const titleText = />(.*?)</.exec(text)[1];
+ document.title = titleText;
+ return;
+ } else {
+ const cleanedText = text.trim();
+
+ const template = document.createElement('template');
+ template.innerHTML = cleanedText;
+ reviveScripts(template.content);
+
+ element.replaceWith(template.content);
+ }
+
+ const newElement = Wicket.$(element.id);
+ if (newElement) {
+ we.publish(topic.DOM_NODE_ADDED, newElement);
+ }
+ },
+
+ add: function (element, text) {
+ const we = Wicket.Event;
+ const topic = we.Topic;
+
+ const cleanedText = text.trim();
+
+ const template = document.createElement('template');
+ template.innerHTML = cleanedText;
+ reviveScripts(template.content);
+
+ element.append(template.content);
+
+ const newElement = Wicket.$(element.id);
+ if (newElement) {
+ we.publish(topic.DOM_NODE_ADDED, newElement);
+ }
+ },
+
+ remove: function (element) {
+ const we = Wicket.Event;
+ const topic = we.Topic;
+
+ we.publish(topic.DOM_NODE_REMOVING, element);
+
+ element.remove();
+ },
+
+ // Method for serializing DOM nodes to string
+ // original taken from Tacos (http://tacoscomponents.jot.com)
+ serializeNodeChildren: function (node) {
+ if (isUndef(node)) {
+ return "";
+ }
+ const result = [];
+
+ if (node.childNodes.length > 0) {
+ for (let i = 0; i < node.childNodes.length; i++) {
+ const thisNode = node.childNodes[i];
+ switch (thisNode.nodeType) {
+ case 1: // ELEMENT_NODE
+ case 5: // ENTITY_REFERENCE_NODE
+ result.push(this.serializeNode(thisNode));
+ break;
+ case 8: // COMMENT
+ result.push("<!--");
+ result.push(thisNode.nodeValue);
+ result.push("-->");
+ break;
+ case 4: // CDATA_SECTION_NODE
+ result.push("<![CDATA[");
+ result.push(thisNode.nodeValue);
+ result.push("]]>");
+ break;
+ case 3: // TEXT_NODE
+ case 2: // ATTRIBUTE_NODE
+ result.push(thisNode.nodeValue);
+ break;
+ default:
+ break;
+ }
+ }
+ } else {
+ result.push(node.textContent || node.text);
+ }
+ return result.join("");
+ },
+
+ serializeNode: function (node){
+ if (isUndef(node)) {
+ return "";
+ }
+ const result = [];
+ result.push("<");
+ result.push(node.nodeName);
+
+ if (node.attributes && node.attributes.length > 0) {
+
+ for (let i = 0; i < node.attributes.length; i++) {
+ // serialize the attribute only if it has a meaningful value
+ if (node.attributes[i].nodeValue) {
+ result.push(" ");
+ result.push(node.attributes[i].name);
+ result.push("=\"");
+ result.push(node.attributes[i].value);
+ result.push("\"");
+ }
+ }
+ }
+
+ result.push(">");
+ result.push(Wicket.DOM.serializeNodeChildren(node));
+ result.push("</");
+ result.push(node.nodeName);
+ result.push(">");
+ return result.join("");
+ },
+
+ // Utility function that determines whether given element is part of the current document
+ containsElement: function (element) {
+ const id = element.getAttribute("id");
+ if (id) {
+ return Wicket.$(id) !== null;
+ }
+ else {
+ return false;
+ }
+ },
+
+ /**
+ * Reads the text from the node's children nodes.
+ * @param node {DOMElement} the root node
+ */
+ text: function (node) {
+ if (isUndef(node)) {
+ return "";
+ }
+
+ const result = [];
+
+ if (node.childNodes.length > 0) {
+ for (let i = 0; i < node.childNodes.length; i++) {
+ const thisNode = node.childNodes[i];
+ switch (thisNode.nodeType) {
+ case 1: // ELEMENT_NODE
+ case 5: // ENTITY_REFERENCE_NODE
+ result.push(this.text(thisNode));
+ break;
+ case 3: // TEXT_NODE
+ case 4: // CDATA_SECTION_NODE
+ result.push(thisNode.nodeValue);
+ break;
+ default:
+ break;
+ }
+ }
+ } else {
+ result.push(node.textContent || node.text);
+ }
+
+ return result.join("");
+ }
+ };
+
+ /**
+ * The Ajax class handles low level details of creating XmlHttpRequest objects,
+ * as well as registering and execution of pre-call, post-call and failure handlers.
+ */
+ Object.assign(Wicket.Ajax, {
+
+ Call: Wicket.Ajax.Call,
+
+ /**
+ * Aborts the default event if attributes request it
+ *
+ * @param {Object} attrs - the Ajax request attributes configured at the server side
+ */
+ _handleEventCancelation: function(attrs) {
+ const evt = attrs.event;
+ if (evt) {
+ if (attrs.pd) {
+ try {
+ evt.preventDefault();
+ } catch (ignore) {
+ // WICKET-4986
+ }
+ }
+
+ if (attrs.sp === "stop") {
+ Wicket.Event.stop(evt);
+ } else if (attrs.sp === "stopImmediate") {
+ Wicket.Event.stop(evt, true);
+ }
+ }
+ },
+
+ get: function (attrs) {
+
+ attrs.m = 'GET';
+
+ return Wicket.Ajax.ajax(attrs);
+ },
+
+ post: function (attrs) {
+
+ attrs.m = 'POST';
+
+ return Wicket.Ajax.ajax(attrs);
+ },
+
+ ajax: function(attrs) {
+
+ attrs.c = attrs.c || window;
+ attrs.e = attrs.e || [ 'domready' ];
+
+ if (!Array.isArray(attrs.e)) {
+ attrs.e = [ attrs.e ];
+ }
+
+ attrs.e.forEach(function (evt) {
+ Wicket.Event.add(attrs.c, evt, function (event, data) {
+ const call = new Wicket.Ajax.Call();
+ const attributes = Object.assign({}, attrs);
+
+ if (evt !== "domready") {
+ attributes.event = Wicket.Event.fix(event);
+ if (data) {
+ attributes.event.extraData = data;
+ }
+ }
+
+ call._executeHandlers(attributes.ih, attributes);
+ Wicket.Event.publish(Wicket.Event.Topic.AJAX_CALL_INIT, attributes);
+
+ const throttlingSettings = attributes.tr;
+ if (throttlingSettings) {
+ const postponeTimerOnUpdate = throttlingSettings.p || false;
+ const throttler = new Wicket.Throttler(postponeTimerOnUpdate);
+ throttler.throttle(throttlingSettings.id, throttlingSettings.d,
+ Wicket.bind(function () {
+ call.ajax(attributes);
+ }, this));
+ }
+ else {
+ call.ajax(attributes);
+ }
+ if (evt !== "domready") {
+ Wicket.Ajax._handleEventCancelation(attributes);
+ }
+ }, null, attrs.sel);
+ });
+ },
+
+ process: function(data) {
+ const call = new Wicket.Ajax.Call();
+ call.process(data);
+ },
+
+ /**
+ * An abstraction over native window.location.replace() to be able to suppress it for unit tests
+ *
+ * @param url The url to redirect to
+ */
+ redirect: function(url) {
+ window.location = url;
+ }
+ });
+
+ /**
+ * Header contribution allows component to include custom javascript and stylesheet.
+ *
+ * Header contributor takes the code component would render to page head and
+ * interprets it just as browser would when loading a page.
+ * That means loading external javascripts and stylesheets, executing inline
+ * javascript and aplying inline styles.
+ *
+ * Header contributor also filters duplicate entries, so that it doesn't load/process
+ * resources that have been loaded.
+ * For inline styles and javascript, element id is used to filter out duplicate entries.
+ * For stylesheet and javascript references, url is used for filtering.
+ */
+ Wicket.Head = {
+ Contributor: {
+
+ // Parses the header contribution element (returns a DOM tree with the contribution)
+ parse: function (headerNode) {
+ // the header contribution is stored as CDATA section in the header-contribution element,
+ // we need to parse it since each header contribution needs to be treated separately
+
+ // get the header contribution text and unescape it if necessary
+ const text = Wicket.DOM.text(headerNode);
+
+ // build a DOM tree of the contribution
+ const xmldoc = Wicket.Xml.parse(text);
+ return xmldoc;
+ },
+
+ // checks whether the passed node is the special "parsererror"
+ // created by DOMParser if there is a error in XML parsing
+ // TODO: move out of the API section
+ _checkParserError: function (node) {
+ let result = false;
+
+ if (!isUndef(node.tagName) && node.tagName.toLowerCase() === "parsererror") {
+ Wicket.Log.error("Error in parsing: %s", node.textContent);
+ result = true;
+ }
+ return result;
+ },
+
+ // Processes the parsed header contribution
+ processContribution: function (context, headerNode) {
+ const xmldoc = this.parse(headerNode);
+ const rootNode = xmldoc.documentElement;
+
+ // Firefox and Opera reports the error in the documentElement
+ if (this._checkParserError(rootNode)) {
+ return;
+ }
+
+ // go through the individual elements and process them according to their type
+ for (let i = 0; i < rootNode.childNodes.length; i++) {
+ let node = rootNode.childNodes[i];
+
+ // Chromium reports the error as a child node
+ if (this._checkParserError(node)) {
+ return;
+ }
+
+ if (!isUndef(node.tagName)) {
+ let name = node.tagName.toLowerCase();
+
+ // it is possible that a reference is surrounded by a <wicket:link
+ // in that case, we need to find the inner element
+ if (name === "wicket:link") {
+ for (let j = 0; j < node.childNodes.length; ++j) {
+ const childNode = node.childNodes[j];
+ // try to find a regular node inside wicket:link
+ if (childNode.nodeType === 1) {
+ node = childNode;
+ name = node.tagName.toLowerCase();
+ break;
+ }
+ }
+ }
+
+ // process the element
+ if (name === "link") {
+ this.processLink(context, node);
+ } else if (name === "script") {
+ this.processScript(context, node);
+ } else if (name === "style") {
+ this.processStyle(context, node);
+ } else if (name === "meta") {
+ this.processMeta(context, node);
+ }
+ } else if (node.nodeType === 8) { // comment type
+ this.processComment(context, node);
+ }
+ }
+ },
+
+ // Process an external stylesheet element
+ processLink: function (context, node) {
+ context.steps.push(function (notify) {
+ const res = Wicket.Head.containsElement(node, "href");
+ const oldNode = res.oldNode;
+ if (res.contains) {
+ // an element with same href attribute is in document, skip it
+ return FunctionsExecuter.DONE;
+ } else if (oldNode) {
+ // remove another external element with the same id but different href
+ oldNode.parentNode.removeChild(oldNode);
+ }
+
+ // create link element
+ const css = Wicket.Head.createElement("link");
+
+ // copy supplied attributes only.
+ const attributes = node.attributes;
+ for (let a = 0; a < attributes.length; a++) {
+ css.setAttribute(attributes[a].name, attributes[a].value);
+ }
+
+ let notifyCalled = false;
+ function doNotify() {
+ if (!notifyCalled) {
+ notifyCalled = true;
+ notify();
+ }
+ }
+ css.onerror = doNotify;
+ css.onload = doNotify;
+ // add element to head
+ Wicket.Head.addElement(css);
+
+ return FunctionsExecuter.ASYNC;
+ });
+ },
+
+ // Process an inline style element
+ processStyle: function (context, node) {
+ context.steps.push(function (notify) {
+ // if element with same id is already in document, skip it
+ if (Wicket.DOM.containsElement(node)) {
+ return FunctionsExecuter.DONE;
+ }
+ // serialize the style to string
+ const content = Wicket.DOM.serializeNodeChildren(node);
+
+ // create style element
+ const style = Wicket.Head.createElement("style");
+
+ // copy id attribute
+ style.id = node.getAttribute("id");
+ // copy nonce attribute
+ style.nonce = node.getAttribute("nonce");
+
+ const textNode = document.createTextNode(content);
+ style.appendChild(textNode);
+
+ Wicket.Head.addElement(style);
+
+ // continue to next step
+ return FunctionsExecuter.DONE;
+ });
+ },
+
+ // Process a script element (both inline and external)
+ processScript: function (context, node) {
+ context.steps.push(function (notify) {
+
+ if (!node.getAttribute("src") && Wicket.DOM.containsElement(node)) {
+ // if an inline element with same id is already in document, skip it
+ return FunctionsExecuter.DONE;
+ } else {
+ const res = Wicket.Head.containsElement(node, "src");
+ const oldNode = res.oldNode;
+ if (res.contains) {
+ // an element with same src attribute is in document, skip it
+ return FunctionsExecuter.DONE;
+ } else if (oldNode) {
+ // remove another external element with the same id but different src
+ oldNode.parentNode.removeChild(oldNode);
+ }
+ }
+
+ // convert the XML node to DOM node
+ const scriptDomNode = document.createElement("script");
+ const attrs = node.attributes;
+ for (let a = 0; a < attrs.length; a++) {
+ const attr = attrs[a];
+ scriptDomNode[attr.name] = attr.value;
+ }
+
+ // determine whether it is external javascript (has src attribute set)
+ const src = node.getAttribute("src");
+ if (src !== null && src !== "") {
+ const onScriptReady = function () {
+ notify();
+ };
+
+ // first check for feature support
+ if (typeof(scriptDomNode.onload) !== 'undefined') {
+ scriptDomNode.onload = onScriptReady;
+ } else if (typeof(scriptDomNode.onreadystatechange) !== 'undefined') {
+ scriptDomNode.onreadystatechange = function () {
+ if (scriptDomNode.readyState === 'loaded' || scriptDomNode.readyState === 'complete') {
+ onScriptReady();
+ }
+ };
+ } else {
+ // as a final resort notify after the current function execution
+ window.setTimeout(onScriptReady, 10);
+ }
+
+ Wicket.Head.addElement(scriptDomNode);
+
+ return FunctionsExecuter.ASYNC;
+ } else {
+ const suspension = {
+ suspended: 0,
+
+ suspend: function() {
+ suspension.suspended++;
+ },
+
+ release: function() {
+ suspension.suspended--;
+ if (suspension.suspended === 0) {
+ notify();
+ }
+ }
+ };
+
+ // serialize the element content to string
+ let text = Wicket.DOM.serializeNodeChildren(node);
+ // get rid of prefix and suffix, they are not eval-d correctly
+ text = text.replace(/^\n\/\*<!\[CDATA\[\*\/\n/, "");
+ text = text.replace(/\n\/\*\]\]>\*\/\n$/, "");
+
+ try {
+ Wicket.Ajax._currentSuspension = suspension;
+
+ scriptDomNode.innerHTML = text;
+
+ const id = node.getAttribute("id");
+ Wicket.Head.addElement(scriptDomNode, typeof(id) !== "string" || id.length === 0);
+ } catch (exception) {
+ Wicket.Log.error("Ajax.Call.processEvaluation: Exception evaluating javascript: %s", text, exception);
+ } finally {
+ Wicket.Ajax.currentSuspension = undefined;
+ }
+
+ // continue to next step
+ if (suspension.suspended === 0) {
+ // execution finished without suspension, just continue to next step
+ return FunctionsExecuter.DONE;
+ } else {
+ // suspended, signal asynchronous execution of next step
+ return FunctionsExecuter.ASYNC;
+ }
+ }
+ });
+ },
+
+ processMeta: function (context, node) {
+ context.steps.push(function (notify) {
+ const meta = Wicket.Head.createElement("meta"),
+ attrs = node.attributes,
+ name = node.getAttribute("name"),
+ httpEquiv = node.getAttribute("http-equiv");
+
+ if (name) {
+ const existingByName = document.querySelectorAll('meta[name="' + name + '"]');
+ for (let n = 0; n < existingByName.length; n++) {
+ existingByName[n].remove();
+ }
+ } else if (httpEquiv) {
+ const existingByHttpEquiv = document.querySelectorAll('meta[http-equiv="' + httpEquiv + '"]');
+ for (let h = 0; h < existingByHttpEquiv.length; h++) {
+ existingByHttpEquiv[h].remove();
+ }
+ }
+
+ for (let a = 0; a < attrs.length; a++) {
+ meta.setAttribute(attrs[a].name, attrs[a].value);
+ }
+
+ Wicket.Head.addElement(meta);
+
+ return FunctionsExecuter.DONE;
+ });
+ },
+
+ // process (conditional) comments
+ processComment: function (context, node) {
+ context.steps.push(function (notify) {
+ const comment = document.createComment(node.nodeValue);
+ Wicket.Head.addElement(comment);
+ return FunctionsExecuter.DONE;
+ });
+ }
+ },
+
+ // Creates an element in document
+ createElement: function (name) {
+ if (isUndef(name) || name === '') {
+ Wicket.Log.error('Cannot create an element without a name');
+ return;
+ }
+ return document.createElement(name);
+ },
+
+ // Adds the element to page head
+ addElement: function (element, remove) {
+ const headItems = document.querySelector('head meta[name="wicket.header.items"]');
+ if (headItems) {
+ headItems.parentNode.insertBefore(element, headItems);
+ } else {
+ const head = document.querySelector("head");
+ if (head) {
+ head.appendChild(element);
+ }
+ }
+
+ if (remove) {
+ element.parentNode.removeChild(element);
+ }
+ },
+
+ // Returns true, if the page head contains element that has attribute with
+ // name mandatoryAttribute same as the given element and their names match.
+ //
+ // e.g. Wicket.Head.containsElement(myElement, "src") return true, if there
+ // is an element in head that is of same type as myElement, and whose src
+ // attribute is same as myElement.src.
+ containsElement: function (element, mandatoryAttribute) {
+ const attr = element.getAttribute(mandatoryAttribute);
+ if (isUndef(attr) || attr === "") {
+ return {
+ contains: false
+ };
+ }
+
+ const elementTagName = element.tagName.toLowerCase();
+ const elementId = element.getAttribute("id");
+ let head = document.getElementsByTagName("head")[0];
+
+ if (elementTagName === "script") {
+ head = document;
+ }
+
+ const nodes = head.getElementsByTagName(elementTagName);
+
+ for (let i = 0; i < nodes.length; ++i) {
+ const node = nodes[i];
+
+ // check node names and mandatory attribute values
+ // we also have to check for attribute name that is suffixed by "_".
+ // this is necessary for filtering script references
+ if (node.tagName.toLowerCase() === elementTagName) {
+
+ const loadedUrl = node.getAttribute(mandatoryAttribute);
+ const loadedUrl_ = node.getAttribute(mandatoryAttribute+"_");
+ if (loadedUrl === attr || loadedUrl_ === attr) {
+ return {
+ contains: true
+ };
+ } else if (elementId && elementId === node.getAttribute("id")) {
+ return {
+ contains: false,
+ oldNode: node
+ };
+ }
+ }
+ }
+ return {
+ contains: false
+ };
+ }
+ };
+
+ // FOCUS FUNCTIONS
+
+ Wicket.Focus = {
+ lastFocusId : "",
+ refocusLastFocusedComponentAfterResponse : false,
+ focusSetFromServer : false,
+
+ focusin: function (event) {
+ event = Wicket.Event.fix(event);
+
+ const target = event.target;
+ if (target) {
+ const WF = Wicket.Focus;
+ WF.refocusLastFocusedComponentAfterResponse = false;
+ const id = target.id;
+ WF.lastFocusId = id;
+ Wicket.Log.info("focus set on '%s'", id);
+ }
+ },
+
+ focusout: function (event) {
+ event = Wicket.Event.fix(event);
+
+ const target = event.target;
+ const WF = Wicket.Focus;
+ if (target && WF.lastFocusId === target.id) {
+ const id = target.id;
+ if (WF.refocusLastFocusedComponentAfterResponse) {
+ // replaced components seem to blur when replaced only on Safari - so do not modify lastFocusId so it gets refocused
+ Wicket.Log.info("focus removed from '%s' but ignored because of component replacement", id);
+ } else {
+ WF.lastFocusId = null;
+ Wicket.Log.info("focus removed from '%s'", id);
+ }
+ }
+ },
+
+ getFocusedElement: function () {
+ const lastFocusId = Wicket.Focus.lastFocusId;
+ if (lastFocusId) {
+ const focusedElement = Wicket.$(lastFocusId);
+ Wicket.Log.info("returned focused element:", focusedElement);
+ return focusedElement;
+ }
+ },
+
+ setFocusOnId: function (id) {
+ const WF = Wicket.Focus;
+ if (id) {
+ WF.refocusLastFocusedComponentAfterResponse = true;
+ WF.focusSetFromServer = true;
+ WF.lastFocusId = id;
+ Wicket.Log.info("focus set on '%s' from server side", id);
+ } else {
+ WF.refocusLastFocusedComponentAfterResponse = false;
+ Wicket.Log.info("refocus focused component after request stopped from server side");
+ }
+ },
+
+ // mark the focused component so that we know if it has been replaced or not by response
+ markFocusedComponent: function () {
+ const WF = Wicket.Focus;
+ const focusedElement = WF.getFocusedElement();
+ if (focusedElement) {
+ // create a property of the focused element that would not remain there if component is replaced
+ focusedElement.wasFocusedBeforeComponentReplacements = true;
+ WF.refocusLastFocusedComponentAfterResponse = true;
+ WF.focusSetFromServer = false;
+ } else {
+ WF.refocusLastFocusedComponentAfterResponse = false;
+ }
+ },
+
+ // detect if the focused component was replaced
+ checkFocusedComponentReplaced: function () {
+ const WF = Wicket.Focus;
+ if (WF.refocusLastFocusedComponentAfterResponse) {
+ const focusedElement = WF.getFocusedElement();
+ if (focusedElement) {
+ if (typeof(focusedElement.wasFocusedBeforeComponentReplacements) !== "undefined") {
+ // focus component was not replaced - no need to refocus it
+ WF.refocusLastFocusedComponentAfterResponse = false;
+ }
+ } else {
+ // focused component dissapeared completely - no use to try to refocus it
+ WF.refocusLastFocusedComponentAfterResponse = false;
+ WF.lastFocusId = "";
+ }
+ }
+ },
+
+ requestFocus: function() {
+ // if the focused component is replaced by the ajax response, a re-focus might be needed
+ // (if focus was not changed from server) but if not, and the focus component should
+ // remain the same, do not re-focus - fixes problem on IE6 for combos that have
+ // the popup open (refocusing closes popup)
+ const WF = Wicket.Focus;
+ if (WF.refocusLastFocusedComponentAfterResponse && WF.lastFocusId) {
+ const toFocus = Wicket.$(WF.lastFocusId);
+
+ if (toFocus) {
+ Wicket.Log.info("Calling focus on '%s'", WF.lastFocusId);
+
+ const safeFocus = function() {
+ try {
+ toFocus.focus();
+ } catch (ignore) {
+ // WICKET-6209 IE fails if toFocus is disabled
+ }
+ };
+
+ if (WF.focusSetFromServer) {
+ // WICKET-5858
+ window.setTimeout(safeFocus, 0);
+ } else {
+ // avoid loops like - onfocus triggering an event the modifies the tag => refocus => the event is triggered again
+ const temp = toFocus.onfocus;
+ toFocus.onfocus = null;
+
+ // IE needs setTimeout (it seems not to call onfocus sync. when focus() is called
+ window.setTimeout(function () { safeFocus(); toFocus.onfocus = temp; }, 0);
+ }
+ } else {
+ WF.lastFocusId = "";
+ Wicket.Log.info("Couldn't set focus on element with id '%s' because it is not in the page anymore", WF.lastFocusId);
+ }
+ } else if (WF.refocusLastFocusedComponentAfterResponse) {
+ Wicket.Log.info("last focus id was not set");
+ } else {
+ Wicket.Log.info("refocus last focused component not needed/allowed");
+ }
+ Wicket.Focus.refocusLastFocusedComponentAfterResponse = false;
+ }
+ };
+
+ /**
+ * Manages the functionality needed by AbstractAjaxTimerBehavior and its subclasses
+ */
+ Wicket.Timer = {
+ /**
+ * Schedules a timer
+ * @param {string} timerId - the identifier for the timer
+ * @param {function} f - the JavaScript function to execute after the timeout
+ * @param {number} delay - the timeout
+ */
+ 'set': function(timerId, f, delay) {
+ if (typeof(Wicket.TimerHandles) === 'undefined') {
+ Wicket.TimerHandles = {};
+ }
+
+ Wicket.Timer.clear(timerId);
+ Wicket.TimerHandles[timerId] = setTimeout(function() {
+ Wicket.Timer.clear(timerId);
+ f();
+ }, delay);
+ },
+
+ /**
+ * Clears a timer by its id
+ * @param {string} timerId - the identifier of the timer
+ */
+ clear: function(timerId) {
+ if (Wicket.TimerHandles && Wicket.TimerHandles[timerId]) {
+ clearTimeout(Wicket.TimerHandles[timerId]);
+ delete Wicket.TimerHandles[timerId];
+ }
+ },
+
+ /**
+ * Clear all remaining timers.
+ */
+ clearAll: function() {
+ const WTH = Wicket.TimerHandles;
+ if (WTH) {
+ for (const th in WTH) {
+ if (WTH.hasOwnProperty(th)) {
+ Wicket.Timer.clear(th);
+ }
+ }
+ }
+ }
+ };
+
+ /**
+ * Events related code
+ */
+ Wicket.Event = {
+ idCounter: 0,
+
+ // registry of the actual (wrapping) listener functions registered via Wicket.Event.add,
+ // keyed by element, so that Wicket.Event.remove can find and detach them again given
+ // only the original handler function, mirroring the (element, type, fn) triple used to add it
+ _listenerRegistry: (typeof(WeakMap) !== 'undefined') ? new WeakMap() : null,
+
+ // registry of subscribers per pub/sub topic, see #subscribe/#unsubscribe/#publish
+ _topics: {},
+
+ getId: function (element) {
+ let id = element.id;
+
+ if (typeof(id) === "string" && id.length > 0) {
+ return id;
+ } else {
+ id = "wicket-generated-id-" + Wicket.Event.idCounter++;
+ element.id = id;
+ return id;
+ }
+ },
+
+ keyCode: function (evt) {
+ return Wicket.Event.fix(evt).keyCode;
+ },
+
+ /**
+ * Prevent event from bubbling up in the element hierarchy.
+ * @param evt {Event} - the event to stop
+ * @param immediate {Boolean} - true if the event should not be handled by other listeners registered
+ * on the same HTML element. Optional
+ */
+ stop: function (evt, immediate) {
+ evt = Wicket.Event.fix(evt);
+ if (immediate) {
+ evt.stopImmediatePropagation();
+ } else {
+ evt.stopPropagation();
+ }
+ return evt;
+ },
+
+ /**
+ * Native DOM events don't need any normalization on the modern browsers Wicket
+ * targets, so this is effectively a passthrough. Kept for API compatibility with
+ * code that calls Wicket.Event.fix().
+ */
+ fix: function (evt) {
+ return evt;
+ },
+
+ /**
+ * Fires a (possibly custom) DOM event on an element.
+ *
+ * @param element {HTMLElement|String} - the element (or its id) to fire the event on
+ * @param event {String|Event} - the event type to fire, or an already created Event
+ * @param data {*} - optional extra data, made available to listeners registered
+ * through Wicket.Event.add() as the second callback argument
+ */
+ fire: function (element, event, data) {
+ element = Wicket.$(element);
+ if (element) {
+ let evt = event;
+ if (typeof(event) === 'string') {
+ evt = new Event(event, { bubbles: true, cancelable: true });
+ }
+ if (typeof(data) !== 'undefined') {
+ // namespaced so it can never collide with a native event property
+ // (e.g. MouseEvent#detail, which is unrelated and always present)
+ evt.wicketExtraData = data;
+ }
+ element.dispatchEvent(evt);
+ }
+ },
+
+ /**
+ * Binds an event listener for an element
+ *
+ * Also supports the special 'domready' event on window.
+ * 'domready' is event fired when the DOM is complete, but
+ * before loading external resources (images, scripts, ...)
+ *
+ * @param element {HTMLElement} The host HTML element
+ * @param type {String} The type of the DOM event. Several space separated
+ * event types can be given at once, e.g. 'input change'
+ * @param fn {Function} The event handler to bind
+ * @param data {Object} Extra data for the event
+ * @param selector {String} A selector string to filter the descendants of the selected
+ * elements that trigger the event. If the selector is null or omitted,
+ * the event is always triggered when it reaches the selected element.
+ */
+ add: function (element, type, fn, data, selector) {
+ if (type === 'domready') {
+ if (document.readyState !== 'loading') {
+ fn();
+ } else {
+ document.addEventListener('DOMContentLoaded', fn, { once: true });
+ }
+ } else if (type === 'load' && element === window) {
+ if (document.readyState === 'complete') {
+ fn();
+ } else {
+ window.addEventListener('load', fn, { once: true });
+ }
+ } else {
+ let el = element;
+ if (typeof(element) === 'string') {
+ el = document.getElementById(element);
+ }
+
+ if (!el && Wicket.Log) {
+ Wicket.Log.error("Cannot bind a listener for event '%s' because the element is not in the DOM", type, element);
+ return element;
+ }
+
+ const types = type.split(/\s+/);
+ /* jshint loopfunc: true */
+ // the IIFE below intentionally captures each iteration's eventType by value
+ for (let t = 0; t < types.length; t++) {
+ (function (eventType) {
+ const wrapper = function (evt) {
+ const extraData = (typeof(evt.wicketExtraData) !== 'undefined') ? evt.wicketExtraData : data;
+ if (selector) {
+ const target = evt.target && evt.target.closest ? evt.target.closest(selector) : null;
+ if (target && el.contains(target)) {
+ fn.call(target, evt, extraData);
+ }
+ } else {
+ fn.call(el, evt, extraData);
+ }
+ };
+ el.addEventListener(eventType, wrapper);
+ if (Wicket.Event._listenerRegistry) {
+ let map = Wicket.Event._listenerRegistry.get(el);
+ if (!map) {
+ map = {};
+ Wicket.Event._listenerRegistry.set(el, map);
+ }
+ if (!map[eventType]) {
+ map[eventType] = [];
+ }
+ map[eventType].push({ fn: fn, wrapper: wrapper });
+ }
+ })(types[t]);
+ }
+ }
+ return element;
+ },
+
+ /**
+ * Unbinds an event listener for an element
+ *
+ * @param element {HTMLElement} The host HTML element
+ * @param type {String} The type of the DOM event. Several space separated
+ * event types can be given at once
+ * @param fn {Function} The event handler to unbind. If omitted, every listener
+ * bound through Wicket.Event.add() for this type is removed.
+ */
+ remove: function (element, type, fn) {
+ let el = element;
+ if (typeof(element) === 'string') {
+ el = document.getElementById(element);
+ }
+ if (!el || !Wicket.Event._listenerRegistry) {
+ return;
+ }
+ const map = Wicket.Event._listenerRegistry.get(el);
+ if (!map) {
+ return;
+ }
+ const types = type ? type.split(/\s+/) : Object.keys(map);
+ for (let t = 0; t < types.length; t++) {
+ const entries = map[types[t]];
+ if (!entries) {
+ continue;
+ }
+ for (let i = entries.length - 1; i >= 0; i--) {
+ if (!fn || entries[i].fn === fn) {
+ el.removeEventListener(types[t], entries[i].wrapper);
+ entries.splice(i, 1);
+ }
+ }
+ }
+ },
+
+ /**
+ * Adds a subscriber for the passed topic.
+ *
+ * @param topic {String} - the channel name for which this subscriber will be notified
+ * If '*' then it will be notified for all topics
+ * @param subscriber {Function} - the callback to call when an event with this type is published
+ */
+ subscribe: function (topic, subscriber) {
+ if (topic) {
+ const topics = Wicket.Event._topics;
+ if (!topics[topic]) {
+ topics[topic] = [];
+ }
+ topics[topic].push(subscriber);
+ }
+ },
+
+ /**
+ * Un-subscribes a subscriber from a topic.
+ * @param topic {String} - the topic name. If omitted un-subscribes all
+ * subscribers from all topics
+ * @param subscriber {Function} - the handler to un-subscribe. If omitted then
+ * all subscribers are removed from this topic
+ */
+ unsubscribe: function(topic, subscriber) {
+ const topics = Wicket.Event._topics;
+ if (topic) {
+ if (subscriber) {
+ const subscribers = topics[topic];
+ if (subscribers) {
+ const idx = subscribers.indexOf(subscriber);
+ if (idx > -1) {
+ subscribers.splice(idx, 1);
+ }
+ }
+ } else {
+ delete topics[topic];
+ }
+ } else {
+ Wicket.Event._topics = {};
+ }
+ },
+
+ /**
+ * Sends a notification to all subscribers for the given topic.
+ * Subscribers for topic '*' receive the actual topic as first parameter,
+ * otherwise the topic is not passed to subscribers which listen for specific
+ * event types.
+ *
+ * @param topic {String} - the channel name for which all subscribers will be notified.
+ */
+ publish: function (topic) {
+ if (topic) {
+ // cut the topic argument
+ const args = Array.prototype.slice.call(arguments).slice(1);
+ const event = { type: topic };
+
+ const subscribers = (Wicket.Event._topics[topic] || []).slice();
+ for (let i = 0; i < subscribers.length; i++) {
+ subscribers[i].apply(document, [event].concat(args));
+ }
+
+ const wildcardEvent = { type: '*' };
+ const wildcardSubscribers = (Wicket.Event._topics['*'] || []).slice();
+ for (let w = 0; w < wildcardSubscribers.length; w++) {
+ wildcardSubscribers[w].apply(document, [wildcardEvent].concat(args));
+ }
+ }
+ },
+
+ /**
+ * Submits the given form using, if available, standard form processing
+ * including client-side validation and firing of SubmitEvent.
+ *
+ * @param form {HTMLFormElement} form to submit
+ */
+ requestSubmit: function(form) {
+ if (form.requestSubmit) {
+ form.requestSubmit();
+ } else {
+ const evt = new Event('submit', { bubbles: true, cancelable: true });
+ if (form.dispatchEvent(evt)) {
+ form.submit();
+ }
+ }
+ },
+
+ /**
+ * The names of the topics on which Wicket notifies
+ */
+ Topic: {
+ DOM_NODE_REMOVING : '/dom/node/removing',
+ DOM_NODE_ADDED : '/dom/node/added',
+ AJAX_CALL_INIT : '/ajax/call/init',
+ AJAX_CALL_BEFORE : '/ajax/call/before',
+ AJAX_CALL_PRECONDITION : '/ajax/call/precondition',
+ AJAX_CALL_BEFORE_SEND : '/ajax/call/beforeSend',
+ AJAX_CALL_SUCCESS : '/ajax/call/success',
+ AJAX_CALL_COMPLETE : '/ajax/call/complete',
+ AJAX_CALL_AFTER : '/ajax/call/after',
+ AJAX_CALL_FAILURE : '/ajax/call/failure',
+ AJAX_CALL_DONE : '/ajax/call/done',
+ AJAX_HANDLERS_BOUND : '/ajax/handlers/bound'
+ }
+ };
+
+ // MISC FUNCTIONS
+
+ /**
+ * Track focussed element.
+ */
+ Wicket.Event.add(window, 'focusin', Wicket.Focus.focusin);
+ Wicket.Event.add(window, 'focusout', Wicket.Focus.focusout);
+
+ /**
+ * Clear any scheduled Ajax timers when leaving the current page
+ */
+ Wicket.Event.add(window, "unload", function() {
+ Wicket.Timer.clearAll();
+ });
+
+})();
diff --git a/wicket-core/src/main/java/org/apache/wicket/markup/html/form/upload/resource/FileUploadToResourceField.js b/wicket-core/src/main/java/org/apache/wicket/markup/html/form/upload/resource/FileUploadToResourceField.js
index 1ed5e0808b..5d79c59f0e 100644
--- a/wicket-core/src/main/java/org/apache/wicket/markup/html/form/upload/resource/FileUploadToResourceField.js
+++ b/wicket-core/src/main/java/org/apache/wicket/markup/html/form/upload/resource/FileUploadToResourceField.js
@@ -41,59 +41,68 @@
this.clientSideSuccessCallBack = clientSideSuccessCallBack;
this.clientSideCancelCallBack = clientSideCancelCallBack;
this.uploadErrorCallBack = uploadErrorCallBack;
- }
+ };
Wicket.FileUploadToResourceField.prototype.upload = function()
{
// get a fresh reference to input
this.input = document.getElementById(this.inputName);
// we add the files to a FormData object.
- var formData = new FormData();
- var totalfiles = this.input.files.length;
- for (var index = 0; index < totalfiles; index++) {
+ const formData = new FormData();
+ const totalfiles = this.input.files.length;
+ for (let index = 0; index < totalfiles; index++) {
formData.append("WICKET-FILE-UPLOAD",this.input.files[index]);
}
- var self = this;
- // we use jQuery to post the files to the resource (this.resourceUrl)
- // and we keep a reference to the request in order to be able
- // to cancel the upload
- this.xhr = $.ajax({
- url: this.resourceUrl,
- type: "POST",
- data: formData,
- processData: false,
- contentType: false,
- success: function (res) {
+ const self = this;
+ // we post the files to the resource (this.resourceUrl) with a plain XMLHttpRequest
+ // and keep a reference to it in order to be able to cancel the upload
+ const xhr = new XMLHttpRequest();
+ this.xhr = xhr;
+
+ xhr.open("POST", this.resourceUrl);
+
+ xhr.onload = function () {
+ let res, ep;
+ if (xhr.status >= 200 && xhr.status < 300) {
+ try {
+ res = xhr.responseText ? JSON.parse(xhr.responseText) : {};
+ } catch (parseError) {
+ // this error will only happen is generated JSON at server side is faulty
+ Wicket.Log.log(xhr.responseText);
+ return;
+ }
// do clean up on success
if (res.error) {
self.uploadErrorCallBack(res);
Wicket.Ajax.get({"u": self.ajaxCallBackUrl, "ep": res});
} else {
self.clientSideSuccessCallBack();
- var ep = {'error': false, 'filesInfo': JSON.stringify(res)};
+ ep = {'error': false, 'filesInfo': JSON.stringify(res)};
Wicket.Ajax.get({"u": self.ajaxCallBackUrl, "ep": ep});
}
- },
- beforeSend: function (xhr) {
- self.clientBeforeSendCallBack(xhr);
- },
- error: function (jqXHR, textStatus, errorThrown) {
- if (textStatus === "abort") {
- // user aborted the upload.
- var ep = {'error': true, 'errorMessage': 'upload.canceled'};
- Wicket.Ajax.get({"u": self.ajaxCallBackUrl, "ep": ep});
- } else if (textStatus === "error"){
- var ep = {'error': true, "errorMessage": errorThrown};
- self.uploadErrorCallBack(ep);
- Wicket.Ajax.get({"u": self.ajaxCallBackUrl, "ep": ep});
- } else if (textStatus === "parsererror"){
- // this error will only happen is generated JSON at server side is faulty
- var data = jqXHR.responseText;
- Wicket.Log.log(data);
- }
+ } else {
+ ep = {'error': true, "errorMessage": xhr.statusText};
+ self.uploadErrorCallBack(ep);
+ Wicket.Ajax.get({"u": self.ajaxCallBackUrl, "ep": ep});
}
- });
- }
+ };
+
+ xhr.onerror = function () {
+ const ep = {'error': true, "errorMessage": xhr.statusText};
+ self.uploadErrorCallBack(ep);
+ Wicket.Ajax.get({"u": self.ajaxCallBackUrl, "ep": ep});
+ };
+
+ xhr.onabort = function () {
+ // user aborted the upload.
+ const ep = {'error': true, 'errorMessage': 'upload.canceled'};
+ Wicket.Ajax.get({"u": self.ajaxCallBackUrl, "ep": ep});
+ };
+
+ self.clientBeforeSendCallBack(xhr);
+
+ xhr.send(formData);
+ };
// cancel the upload
Wicket.FileUploadToResourceField.prototype.cancel = function () {
@@ -106,5 +115,5 @@
} else {
Wicket.Log.log("Too late to cancel upload for field '" + this.inputName + "': the upload has already finished.");
}
- }
+ };
})();
diff --git a/wicket-core/src/main/java/org/apache/wicket/settings/JavaScriptLibrarySettings.java b/wicket-core/src/main/java/org/apache/wicket/settings/JavaScriptLibrarySettings.java
index ac0e1bd8cb..aa8b72407a 100644
--- a/wicket-core/src/main/java/org/apache/wicket/settings/JavaScriptLibrarySettings.java
+++ b/wicket-core/src/main/java/org/apache/wicket/settings/JavaScriptLibrarySettings.java
@@ -17,6 +17,7 @@
package org.apache.wicket.settings;
import org.apache.wicket.ajax.WicketAjaxJQueryResourceReference;
+import org.apache.wicket.ajax.WicketAjaxResourceReference;
import org.apache.wicket.request.resource.ResourceReference;
import org.apache.wicket.resource.JQueryResourceReference;
import org.apache.wicket.util.lang.Args;
@@ -30,6 +31,12 @@ import org.apache.wicket.util.lang.Args;
* wicket-event.js, wicket-ajax.js and wicket-ajax-debug.js to use implementations on other
* libraries, such as YUI or DOJO. The resource reference implementations need to specify the
* {@linkplain ResourceReference#getDependencies() dependency} on the backing library, if needed.
+ * <p>
+ * Wicket also ships a jQuery-free implementation of wicket-ajax.js, exposing the exact same
+ * JavaScript API, that can be enabled with:
+ * <pre>
+ * setWicketAjaxReference(WicketAjaxResourceReference.get());
+ * </pre>
*
* @since 6.0
*/
diff --git a/wicket-core/src/test/js/ajax.js b/wicket-core/src/test/js/ajax.js
index 3f7487e9ec..8a173f6358 100644
--- a/wicket-core/src/test/js/ajax.js
+++ b/wicket-core/src/test/js/ajax.js
@@ -37,11 +37,27 @@
/*global ok: true, start: true, test: true, equal: true, deepEqual: true,
QUnit: true, expect: true, console: true */
-jQuery(document).ready(function() {
+Wicket.Event.add(window, 'domready', function() {
"use strict";
const { module, test } = QUnit;
+ // mimics jQuery.param(params, true) (the 'traditional' serialization of an
+ // array of {name, value} pairs) without depending on jQuery
+ var toQueryString = function (params) {
+ return params.map(function (p) {
+ return encodeURIComponent(p.name) + '=' + encodeURIComponent(p.value);
+ }).join('&');
+ };
+
+ // builds a HTML element (or fragment, for markup with several root nodes) from a
+ // markup string, without depending on jQuery
+ var parseHtml = function (html) {
+ var template = document.createElement('template');
+ template.innerHTML = html;
+ return template.content;
+ };
+
var execute = function (attributes, assert, done) {
const done2 = done || assert.async();
Wicket.testDone = done2;
@@ -60,7 +76,7 @@ jQuery(document).ready(function() {
}
]
};
- var attrs = jQuery.extend({}, defaults, attributes);
+ var attrs = Object.assign({}, defaults, attributes);
var call = new Wicket.Ajax.Call();
call.ajax(attrs);
};
@@ -118,7 +134,7 @@ jQuery(document).ready(function() {
const done = assert.async();
assert.expect(2);
- assert.equal(jQuery('#componentToReplace').text(), 'old body', 'The component is existing and has the old innerHTML');
+ assert.equal(document.getElementById('componentToReplace').textContent, 'old body', 'The component is existing and has the old innerHTML');
var attrs = {
u: 'data/ajax/componentId.xml',
@@ -126,7 +142,7 @@ jQuery(document).ready(function() {
sh: [
function() {
done();
- assert.equal(jQuery('#componentToReplace').text(), 'new body', 'The component must be replaced');
+ assert.equal(document.getElementById('componentToReplace').textContent, 'new body', 'The component must be replaced');
}
]
};
@@ -153,7 +169,7 @@ jQuery(document).ready(function() {
sh: [
function() {
done();
- assert.equal(jQuery('#componentToReplaceDoesNotExist').length, 0, 'A component with id \'componentToReplaceDoesNotExist\' must not exist!');
+ assert.equal(document.getElementById('componentToReplaceDoesNotExist'), null, 'A component with id \'componentToReplaceDoesNotExist\' must not exist!');
}
]
};
@@ -172,7 +188,7 @@ jQuery(document).ready(function() {
sh: [
function() {
done();
- assert.equal(jQuery('#componentToReplace')[0].tagName.toLowerCase(), 'table', 'A component with id \'componentToReplace\' must be a table now!');
+ assert.equal(document.getElementById('componentToReplace').tagName.toLowerCase(), 'table', 'A component with id \'componentToReplace\' must be a table now!');
}
]
};
@@ -185,7 +201,7 @@ jQuery(document).ready(function() {
const done = assert.async();
assert.expect(1);
- var oldTitle = jQuery('title').text();
+ var oldTitle = document.title;
var attrs = {
u: 'data/ajax/componentToReplaceTitle.xml',
@@ -193,9 +209,8 @@ jQuery(document).ready(function() {
sh: [
function() {
done();
- var $title = jQuery('title');
- assert.equal($title.text(), 'new title', 'The title text should be updated!');
- $title.text(oldTitle);
+ assert.equal(document.title, 'new title', 'The title text should be updated!');
+ document.title = oldTitle;
}
]
};
@@ -249,7 +264,7 @@ jQuery(document).ready(function() {
if (++calls === 2) {
done();
- jQuery(window).off("event1 event2");
+ Wicket.Event.remove(window, "event1 event2");
}
}
]
@@ -257,9 +272,8 @@ jQuery(document).ready(function() {
Wicket.Ajax.ajax(attrs);
- var target = jQuery(window);
- target.triggerHandler("event1");
- target.triggerHandler("event2");
+ Wicket.Event.fire(window, "event1");
+ Wicket.Event.fire(window, "event2");
});
@@ -293,15 +307,13 @@ jQuery(document).ready(function() {
Wicket.Ajax.ajax(attrs);
- var target = jQuery(window);
-
// this one will be throttled
- target.triggerHandler("event1");
+ Wicket.Event.fire(window, "event1");
// this one will override the previous and will be throttled too
- target.triggerHandler("event1");
+ Wicket.Event.fire(window, "event1");
- target.off("event1");
+ Wicket.Event.remove(window, "event1");
});
test('verify arguments to IAjaxCallListener handlers. Success scenario.', assert => {
@@ -338,7 +350,7 @@ jQuery(document).ready(function() {
function(attributes, jqXHR, settings) {
assert.equal(attrs.u, attributes.u, 'Before: attributes equal');
assert.ok(Wicket.isFunction(jqXHR.getResponseHeader), 'Before: Assert that jqXHR is a XMLHttpRequest');
- assert.ok(Wicket.isFunction(settings.beforeSend), 'Before: Assert that settings is the object passed to jQuery.ajax()');
+ assert.ok(Wicket.isFunction(settings.beforeSend), 'Before: Assert that settings is the object used to make the Ajax call');
}
],
ah: [
@@ -357,9 +369,8 @@ jQuery(document).ready(function() {
Wicket.Ajax.ajax(attrs);
- var target = jQuery(window);
- target.triggerHandler("event1");
- target.off("event1");
+ Wicket.Event.fire(window, "event1");
+ Wicket.Event.remove(window, "event1");
});
test('verify arguments to IAjaxCallListener handlers. Failure scenario.', assert => {
@@ -391,7 +402,7 @@ jQuery(document).ready(function() {
function(attributes, jqXHR, settings) {
assert.equal(attrs.u, attributes.u);
assert.ok(Wicket.isFunction(jqXHR.getResponseHeader), 'Assert that jqXHR is a XMLHttpRequest');
- assert.ok(Wicket.isFunction(settings.beforeSend), 'Assert that settings is the object passed to jQuery.ajax()');
+ assert.ok(Wicket.isFunction(settings.beforeSend), 'Assert that settings is the object used to make the Ajax call');
}
],
ah: [
@@ -410,9 +421,8 @@ jQuery(document).ready(function() {
Wicket.Ajax.ajax(attrs);
- var target = jQuery(window);
- target.triggerHandler("event1");
- target.off("event1");
+ Wicket.Event.fire(window, "event1");
+ Wicket.Event.remove(window, "event1");
});
/**
@@ -428,15 +438,12 @@ jQuery(document).ready(function() {
coh: [
function(attributes, jqXHR, textStatus) {
done();
- var jQueryVersion = jQuery.fn.jquery;
- if (
- (!!window._phantom) &&
- (jQueryVersion.indexOf("4") === 0 || jQueryVersion.indexOf("3") === 0 || jQueryVersion.indexOf("2") === 0 )
- ) {
- assert.equal(textStatus, "success", "textStatus");
- } else {
- assert.equal(textStatus, "parsererror", "textStatus");
- }
+ // requesting a .json file with the default dataType ('xml') is a
+ // dataType/content mismatch; whether that surfaces as a parse failure
+ // (textStatus 'parsererror') or is treated as a successful HTTP response
+ // whose body just doesn't contain the expected <ajax-response> element
+ // (textStatus 'success') depends on which wicket-ajax.js engine is active
+ assert.ok(textStatus === "success" || textStatus === "parsererror", "textStatus");
assert.equal(attributes.u, attrs.u, "url");
assert.deepEqual(attributes.e, [ "domready" ], "events");
assert.equal(attributes.event, null, "No event for 'domready'");
@@ -491,7 +498,7 @@ jQuery(document).ready(function() {
two: '2',
three: true
};
- assert.ok(attributes.event instanceof jQuery.Event, "There must be an event for non-'domready' events");
+ assert.ok(attributes.event && typeof attributes.event.target !== 'undefined', "There must be an event for non-'domready' events");
assert.deepEqual(data, expected, 'Success: data');
assert.equal('success', textStatus, 'Success: textStatus');
assert.equal(attrs.u, attributes.u, 'Success: attrs');
@@ -505,7 +512,7 @@ jQuery(document).ready(function() {
Wicket.Event.subscribe('/ajax/call/beforeSend', function(jqEvent, attributes, jqXHR, settings) {
assert.equal(attrs.u, attributes.u, 'Before: attrs');
assert.ok(Wicket.isFunction(jqXHR.getResponseHeader), 'Before: Assert that jqXHR is a XMLHttpRequest');
- assert.ok(Wicket.isFunction(settings.beforeSend), 'Before: Assert that settings is the object passed to jQuery.ajax()');
+ assert.ok(Wicket.isFunction(settings.beforeSend), 'Before: Assert that settings is the object used to make the Ajax call');
});
Wicket.Event.subscribe('/ajax/call/after', function(jqEvent, attributes) {
@@ -527,9 +534,8 @@ jQuery(document).ready(function() {
Wicket.Ajax.ajax(attrs);
- var target = jQuery(window);
- target.triggerHandler("event1");
- target.off("event1");
+ Wicket.Event.fire(window, "event1");
+ Wicket.Event.remove(window, "event1");
});
test('verify arguments to global listeners. Failure scenario.', assert => {
@@ -562,7 +568,7 @@ jQuery(document).ready(function() {
Wicket.Event.subscribe('/ajax/call/beforeSend', function(jqEvent, attributes, jqXHR, settings) {
assert.equal(attrs.u, attributes.u, 'Before: attrs');
assert.ok(Wicket.isFunction(jqXHR.getResponseHeader), 'Before: Assert that jqXHR is a XMLHttpRequest');
- assert.ok(Wicket.isFunction(settings.beforeSend), 'Before: Assert that settings is the object passed to jQuery.ajax()');
+ assert.ok(Wicket.isFunction(settings.beforeSend), 'Before: Assert that settings is the object used to make the Ajax call');
});
Wicket.Event.subscribe('/ajax/call/after', function(jqEvent, attributes) {
@@ -584,9 +590,8 @@ jQuery(document).ready(function() {
Wicket.Ajax.ajax(attrs);
- var target = jQuery(window);
- target.triggerHandler("event1");
- target.off("event1");
+ Wicket.Event.fire(window, "event1");
+ Wicket.Event.remove(window, "event1");
});
@@ -594,15 +599,17 @@ jQuery(document).ready(function() {
const done = assert.async();
assert.expect(6);
- var $indicator = jQuery('<div id="indicator"></div>');
- var $el = jQuery('<div id="elementId"></div>');
- jQuery('#qunit-fixture')
- .append($indicator)
- .append($el);
+ var indicator = document.createElement('div');
+ indicator.id = 'indicator';
+ var el = document.createElement('div');
+ el.id = 'elementId';
+ var fixture = document.getElementById('qunit-fixture');
+ fixture.appendChild(indicator);
+ fixture.appendChild(el);
// returns the number of 'shows' of the indicator
var getCurrentCount = function () {
- var count = $indicator.attr('showIncrementallyCount');
+ var count = indicator.getAttribute('showIncrementallyCount');
return count ? parseInt(count, 10) : 0;
};
@@ -610,14 +617,14 @@ jQuery(document).ready(function() {
var successFailureHandler = function () {
var count = getCurrentCount();
assert.ok(count === 1 || count === 2, "'showIncrementallyCount' must be 1 or 2. Value is: " + count);
- assert.equal('block', $indicator.css('display'), "Indicator's display must be 'block'");
+ assert.equal('block', window.getComputedStyle(indicator).display, "Indicator's display must be 'block'");
};
var attrs = {
u: 'data/ajax/nonWicketResponse.json',
e: 'event1',
- i: $indicator.attr('id'),
- c: $el.attr('id'),
+ i: indicator.id,
+ c: el.id,
dt: 'json', // datatype
sh: [ successFailureHandler ],
fh: [ successFailureHandler ],
@@ -627,13 +634,13 @@ jQuery(document).ready(function() {
// binds requestOne (success)
Wicket.Ajax.ajax(attrs);
- var attrsTwo = jQuery.extend({}, attrs, {
+ var attrsTwo = Object.assign({}, attrs, {
u: 'data/ajax/nonExisting.json'
});
// binds requestTwo (failure - non-existing URL => error 404)
Wicket.Ajax.ajax(attrsTwo);
- var attrsThree = jQuery.extend({}, attrs, {
+ var attrsThree = Object.assign({}, attrs, {
pre: [
function () {
done();
@@ -641,8 +648,9 @@ jQuery(document).ready(function() {
var count = getCurrentCount();
assert.equal(0, count, "'showIncrementallyCount' must be 0 after the executions but is: " + count);
- $indicator.remove();
- $el.off().remove();
+ indicator.remove();
+ Wicket.Event.remove(el);
+ el.remove();
return false;
}
@@ -652,7 +660,7 @@ jQuery(document).ready(function() {
Wicket.Ajax.ajax(attrsThree);
// fire all requests
- $el.triggerHandler("event1");
+ Wicket.Event.fire(el, "event1");
});
/**
@@ -675,7 +683,7 @@ jQuery(document).ready(function() {
Wicket.Event.subscribe('/ajax/call/beforeSend', function(jqEvent, attributes, jqXHR, settings) {
assert.equal(attrs.u, attributes.u, 'Before: attrs');
assert.ok(Wicket.isFunction(jqXHR.getResponseHeader), 'Before: Assert that jqXHR is a XMLHttpRequest');
- assert.ok(Wicket.isFunction(settings.beforeSend), 'Before: Assert that settings is the object passed to jQuery.ajax()');
+ assert.ok(Wicket.isFunction(settings.beforeSend), 'Before: Assert that settings is the object used to make the Ajax call');
assert.ok(settings.url.indexOf('one=1') > 0, 'Parameter "one" with value "1" is found');
assert.ok(settings.url.indexOf('two=2') > 0, 'Parameter "two" with value "2" is found');
done();
@@ -684,9 +692,8 @@ jQuery(document).ready(function() {
});
Wicket.Ajax.ajax(attrs);
- var target = jQuery(window);
- target.triggerHandler("event1");
- target.off("event1");
+ Wicket.Event.fire(window, "event1");
+ Wicket.Event.remove(window, "event1");
});
/**
@@ -710,7 +717,7 @@ jQuery(document).ready(function() {
Wicket.Event.subscribe('/ajax/call/beforeSend', function(jqEvent, attributes, jqXHR, settings) {
assert.equal(attrs.u, attributes.u, 'Before: attrs');
assert.ok(Wicket.isFunction(jqXHR.getResponseHeader), 'Before: Assert that jqXHR is a XMLHttpRequest');
- assert.ok(Wicket.isFunction(settings.beforeSend), 'Before: Assert that settings is the object passed to jQuery.ajax()');
+ assert.ok(Wicket.isFunction(settings.beforeSend), 'Before: Assert that settings is the object used to make the Ajax call');
assert.ok(settings.data.indexOf('one=static1') > -1, 'Parameter "one" with value "static1" is found');
assert.ok(settings.data.indexOf('one=static2') > -1, 'Parameter "one" with value "static2" is found');
assert.ok(settings.data.indexOf('one=dynamic1') > -1, 'Parameter "one" with value "dynamic1" is found');
@@ -721,9 +728,8 @@ jQuery(document).ready(function() {
});
Wicket.Ajax.ajax(attrs);
- var target = jQuery(window);
- target.triggerHandler("event1");
- target.off("event1");
+ Wicket.Event.fire(window, "event1");
+ Wicket.Event.remove(window, "event1");
});
/**
@@ -758,9 +764,8 @@ jQuery(document).ready(function() {
});
Wicket.Ajax.ajax(attrs);
- var target = jQuery(window);
- target.triggerHandler("event1");
- target.off("event1");
+ Wicket.Event.fire(window, "event1");
+ Wicket.Event.remove(window, "event1");
});
/**
@@ -865,7 +870,7 @@ jQuery(document).ready(function() {
if (attrs.event.extraData.round === 2) {
// unregister all global subscribers
Wicket.Event.unsubscribe();
- jQuery(window).off("event1");
+ Wicket.Event.remove(window, "event1");
done();
}
@@ -873,10 +878,9 @@ jQuery(document).ready(function() {
Wicket.Ajax.ajax(attrs);
- var target = jQuery(window);
- target.triggerHandler("event1", {"round": 0}); // execution No1
- target.triggerHandler("event1", {"round": 1}); // execution No2
- target.triggerHandler("event1", {"round": 2}); // execution No3
+ Wicket.Event.fire(window, "event1", {"round": 0}); // execution No1
+ Wicket.Event.fire(window, "event1", {"round": 1}); // execution No2
+ Wicket.Event.fire(window, "event1", {"round": 2}); // execution No3
});
/**
@@ -982,7 +986,7 @@ jQuery(document).ready(function() {
// unregister all global subscribers
Wicket.Event.unsubscribe();
- jQuery(window).off("event1");
+ Wicket.Event.remove(window, "event1");
done();
}
@@ -990,10 +994,9 @@ jQuery(document).ready(function() {
Wicket.Ajax.ajax(attrs);
- var target = jQuery(window);
- target.triggerHandler("event1", {"round": 0}); // execution No1
- target.triggerHandler("event1", {"round": 1}); // execution No2
- target.triggerHandler("event1", {"round": 2}); // execution No3
+ Wicket.Event.fire(window, "event1", {"round": 0}); // execution No1
+ Wicket.Event.fire(window, "event1", {"round": 1}); // execution No2
+ Wicket.Event.fire(window, "event1", {"round": 2}); // execution No3
});
/**
@@ -1018,7 +1021,7 @@ jQuery(document).ready(function() {
Wicket.Ajax.ajax(attrs);
- jQuery('#'+ attrs.c).triggerHandler("nestedFormSubmit");
+ Wicket.Event.fire(attrs.c, "nestedFormSubmit");
});
@@ -1052,7 +1055,7 @@ jQuery(document).ready(function() {
coh: [
function(attrs) {
assert.ok(true, "Complete handler executed");
- assert.equal(attrs.event.isDefaultPrevented(), false, "default behavior is allowed");
+ assert.equal(attrs.event.defaultPrevented, false, "default behavior is allowed");
}
],
dep: [
@@ -1068,7 +1071,7 @@ jQuery(document).ready(function() {
Wicket.Ajax.ajax(attrs);
- jQuery('#'+ attrs.c).triggerHandler("nestedFormSubmit");
+ Wicket.Event.fire(attrs.c, "nestedFormSubmit");
});
/**
@@ -1100,7 +1103,7 @@ jQuery(document).ready(function() {
coh: [
function(attrs) {
assert.ok(true, "Complete handler executed");
- assert.equal(attrs.event.isDefaultPrevented(), false, "default behavior is not prevented");
+ assert.equal(attrs.event.defaultPrevented, false, "default behavior is not prevented");
}
],
dep: [
@@ -1116,7 +1119,7 @@ jQuery(document).ready(function() {
Wicket.Ajax.ajax(attrs);
- jQuery('#'+ attrs.c).triggerHandler("nestedFormSubmit");
+ Wicket.Event.fire(attrs.c, "nestedFormSubmit");
});
@@ -1148,7 +1151,7 @@ jQuery(document).ready(function() {
Wicket.Ajax.ajax(attrs);
- jQuery('#'+ attrs.c).triggerHandler("multipartFormSubmitEvent");
+ Wicket.Event.fire(attrs.c, "multipartFormSubmitEvent");
});
/**
@@ -1177,7 +1180,7 @@ jQuery(document).ready(function() {
Wicket.Ajax.ajax(attrs);
- jQuery(window).triggerHandler("manyEvaluations");
+ Wicket.Event.fire(window, "manyEvaluations");
});
/**
@@ -1203,7 +1206,7 @@ jQuery(document).ready(function() {
coh: [
function() {
assert.equal(this.id, 'usedAsContextWicket5025', "Complete handler executed");
- jQuery('#usedAsContextWicket5025').off();
+ Wicket.Event.remove('usedAsContextWicket5025');
done();
}
]
@@ -1211,7 +1214,7 @@ jQuery(document).ready(function() {
Wicket.Ajax.ajax(attrs);
- jQuery('#usedAsContextWicket5025').triggerHandler("asContextSuccess");
+ Wicket.Event.fire('usedAsContextWicket5025', "asContextSuccess");
});
/**
@@ -1236,7 +1239,7 @@ jQuery(document).ready(function() {
coh: [
function() {
assert.equal(this.id, 'usedAsContextWicket5025', "Complete handler executed");
- jQuery('#usedAsContextWicket5025').off();
+ Wicket.Event.remove('usedAsContextWicket5025');
done();
}
]
@@ -1244,7 +1247,7 @@ jQuery(document).ready(function() {
Wicket.Ajax.ajax(attrs);
- jQuery('#usedAsContextWicket5025').triggerHandler("asContextFailure");
+ Wicket.Event.fire('usedAsContextWicket5025', "asContextFailure");
});
/**
@@ -1268,9 +1271,8 @@ jQuery(document).ready(function() {
};
Wicket.Ajax.ajax(attrs);
- var target = jQuery(window);
- target.triggerHandler("event1");
- target.off("event1");
+ Wicket.Event.fire(window, "event1");
+ Wicket.Event.remove(window, "event1");
});
test('Do not hide the indicator if redirecting.', assert => {
@@ -1297,9 +1299,8 @@ jQuery(document).ready(function() {
};
Wicket.Ajax.ajax(attrs);
- var target = jQuery(window);
- target.triggerHandler("event1");
- target.off("event1");
+ Wicket.Event.fire(window, "event1");
+ Wicket.Event.remove(window, "event1");
});
test('Do hide the indicator if not redirecting.', assert => {
@@ -1322,9 +1323,8 @@ jQuery(document).ready(function() {
};
Wicket.Ajax.ajax(attrs);
- var target = jQuery(window);
- target.triggerHandler("event1");
- target.off("event1");
+ Wicket.Event.fire(window, "event1");
+ Wicket.Event.remove(window, "event1");
});
test('processAjaxResponse, normal HTTP case.', assert => {
@@ -1363,36 +1363,44 @@ jQuery(document).ready(function() {
execute(attrs, assert, done);
});
- test('Ajax 301 with Ajax-Location response header.', assert => {
- const done = assert.async();
- assert.expect(2);
-
- var redirectUrl = 'http://www.example.com/ajax/location';
- var componentUrl = 'data/ajax/componentId.xml';
-
- $.mockjax({
- url: componentUrl,
- status: 301,
- headers: {
- 'Ajax-Location': redirectUrl
- }
- });
+ // This test needs to synthesize a raw HTTP 301 response with a custom
+ // 'Ajax-Location' header, which the static file server backing these tests cannot
+ // produce. jQuery.mockjax achieves this by patching jQuery.ajax() itself, so it only
+ // intercepts requests made through the jQuery-based wicket-ajax.js engine - the plain
+ // JavaScript engine uses a real XMLHttpRequest directly and is unaffected by it. Only
+ // run this test when jQuery + jQuery.mockjax are actually loaded.
+ if (window.jQuery && window.jQuery.mockjax) {
+ test('Ajax 301 with Ajax-Location response header.', assert => {
+ const done = assert.async();
+ assert.expect(2);
+
+ var redirectUrl = 'http://www.example.com/ajax/location';
+ var componentUrl = 'data/ajax/componentId.xml';
+
+ jQuery.mockjax({
+ url: componentUrl,
+ status: 301,
+ headers: {
+ 'Ajax-Location': redirectUrl
+ }
+ });
- var originalRedirect = Wicket.Ajax.redirect;
+ var originalRedirect = Wicket.Ajax.redirect;
- Wicket.Ajax.redirect = function(location) {
- Wicket.Ajax.redirect = originalRedirect;
- done();
- assert.equal(location, redirectUrl, 'Ajax redirect in 301 response is properly handled');
- };
+ Wicket.Ajax.redirect = function(location) {
+ Wicket.Ajax.redirect = originalRedirect;
+ done();
+ assert.equal(location, redirectUrl, 'Ajax redirect in 301 response is properly handled');
+ };
- var attrs = {
- u: componentUrl,
- c: 'componentId'
- };
+ var attrs = {
+ u: componentUrl,
+ c: 'componentId'
+ };
- execute(attrs, assert, done);
- });
+ execute(attrs, assert, done);
+ });
+ }
test('processAjaxResponse, chrome-extensions case.', assert => {
const done = assert.async();
@@ -1465,44 +1473,44 @@ jQuery(document).ready(function() {
});
var metaByName = function(name) {
- return jQuery('head meta[name=' + name + ']');
+ return document.querySelectorAll('head meta[name="' + name + '"]');
};
test('processMeta() create meta tag', assert => {
const done = assert.async();
assert.expect(3);
- jQuery('meta').remove();
+ document.querySelectorAll('meta').forEach(function(el) { el.remove(); });
assert.equal(metaByName("m1").length, 0, "There must be no meta tag before the contribution.");
-
+
var attrs = {
u: 'data/ajax/metaId.xml',
sh: [
function() {
done();
assert.equal(metaByName("m1").length, 1, "There must be one meta tag after the contribution.");
- assert.equal(metaByName("m1").attr("content"), "c1", "The meta tag must have the content as requested.");
+ assert.equal(metaByName("m1")[0].getAttribute("content"), "c1", "The meta tag must have the content as requested.");
}
]
};
execute(attrs, assert, done);
});
-
+
test('processMeta() change meta tag', assert => {
const done = assert.async();
assert.expect(3);
- jQuery('meta').remove();
- jQuery('head').append('<meta name="m1" content="c1_old" />');
+ document.querySelectorAll('meta').forEach(function(el) { el.remove(); });
+ document.head.appendChild(parseHtml('<meta name="m1" content="c1_old" />'));
assert.equal(metaByName("m1").length, 1, "There must be one old meta tag before the contribution.");
-
+
var attrs = {
u: 'data/ajax/metaId.xml',
sh: [
function() {
done();
assert.equal(metaByName("m1").length, 1, "There must be one meta tag after the contribution.");
- assert.equal(metaByName("m1").attr("content"), "c1", "The meta tag must have the content as requested.");
+ assert.equal(metaByName("m1")[0].getAttribute("content"), "c1", "The meta tag must have the content as requested.");
}
]
};
@@ -1513,19 +1521,19 @@ jQuery(document).ready(function() {
const done = assert.async();
assert.expect(5);
- jQuery('meta').remove();
- jQuery('head').append('<meta name="m2" content="c2" />');
+ document.querySelectorAll('meta').forEach(function(el) { el.remove(); });
+ document.head.appendChild(parseHtml('<meta name="m2" content="c2" />'));
assert.equal(metaByName("m2").length, 1, "There must be one old meta tag before the contribution.");
-
+
var attrs = {
u: 'data/ajax/metaId.xml',
sh: [
function() {
done();
assert.equal(metaByName("m2").length, 1, "There must be one old meta tag after the contribution.");
- assert.equal(metaByName("m2").attr("content"), "c2", "The old meta tag must still have the old content.");
+ assert.equal(metaByName("m2")[0].getAttribute("content"), "c2", "The old meta tag must still have the old content.");
assert.equal(metaByName("m1").length, 1, "There must be one new meta tag after the contribution.");
- assert.equal(metaByName("m1").attr("content"), "c1", "The meta tag must have the content as requested.");
+ assert.equal(metaByName("m1")[0].getAttribute("content"), "c1", "The meta tag must have the content as requested.");
}
]
};
diff --git a/wicket-core/src/test/js/all.html b/wicket-core/src/test/js/all.html
index a031cc9d84..ae6c778aad 100644
--- a/wicket-core/src/test/js/all.html
+++ b/wicket-core/src/test/js/all.html
@@ -160,14 +160,26 @@
</div>
<script>
- // version lies between question mark and first ampersand (or end)
+ // version lies between question mark and first ampersand (or end).
+ // 'vanilla' (all.html?vanilla) selects the jQuery-free wicket-ajax.js
+ // engine instead of the default JQuery + wicket-ajax-jquery.js combination
+ // (all.html?4.0.0, all.html?3.7.1, ...).
var version = location.search.match(/\?(.*?)(&|$)/)[1];
+ var useVanilla = (version === 'vanilla');
- document.write("<scr"+"ipt src='../../main/java/org/apache/wicket/resource/jquery/jquery-"+version+".js'></scr"+"ipt>");
+ if (!useVanilla) {
+ document.write("<scr"+"ipt src='../../main/java/org/apache/wicket/resource/jquery/jquery-"+version+".js'></scr"+"ipt>");
+ }
+ </script>
+ <script>
+ if (!useVanilla) {
+ document.write("<scr"+"ipt src='../../main/java/org/apache/wicket/ajax/res/js/wicket-ajax-jquery.js'></scr"+"ipt>");
+ document.write("<scr"+"ipt src='qunit/jquery.mockjax.js'></scr"+"ipt>");
+ } else {
+ document.write("<scr"+"ipt src='../../main/java/org/apache/wicket/ajax/res/js/wicket-ajax.js'></scr"+"ipt>");
+ }
</script>
- <script src="../../main/java/org/apache/wicket/ajax/res/js/wicket-ajax-jquery.js"></script>
<script type="text/javascript" src="qunit/qunit.js"></script>
- <script type="text/javascript" src="qunit/jquery.mockjax.js"></script>
<script type="text/javascript" src="qunit/blanket.min.js"></script>
<!-- the module under test -->
diff --git a/wicket-core/src/test/js/channels.js b/wicket-core/src/test/js/channels.js
index 7e055bec6c..b5dd251e08 100644
--- a/wicket-core/src/test/js/channels.js
+++ b/wicket-core/src/test/js/channels.js
@@ -18,7 +18,7 @@
/*global ok: true, start: true, test: true, equal: true, deepEqual: true,
QUnit: true, expect: true, stop: true */
-jQuery(document).ready(function() {
+Wicket.Event.add(window, 'domready', function() {
"use strict";
const { test } = QUnit;
diff --git a/wicket-core/src/test/js/dom.js b/wicket-core/src/test/js/dom.js
index 56181b12c1..4e7d580877 100644
--- a/wicket-core/src/test/js/dom.js
+++ b/wicket-core/src/test/js/dom.js
@@ -18,7 +18,7 @@
/*global ok: true, start: true, test: true, equal: true, deepEqual: true,
QUnit: true, expect: true */
-jQuery(document).ready(function() {
+Wicket.Event.add(window, 'domready', function() {
"use strict";
const { module, test } = QUnit;
@@ -32,6 +32,13 @@ jQuery(document).ready(function() {
toBeReplacedByScriptId = 'toBeReplacedByScript',
toBeReplacedByDivWithChildrenId = 'toBeReplacedByDivWithChildren';
+ // parses a HTML string into its (single) root element, without depending on jQuery
+ var parseElement = function (html) {
+ var template = document.createElement('template');
+ template.innerHTML = html;
+ return template.content.firstElementChild;
+ };
+
module("Wicket.DOM");
test("Wicket.$ existing", assert => {
@@ -73,7 +80,7 @@ jQuery(document).ready(function() {
});
test("containsElement looks for an existing element", assert => {
- var el = jQuery('#'+existingId)[0];
+ var el = document.getElementById(existingId);
assert.equal( Wicket.DOM.containsElement(el), true, "Wicket.DOM.containsElement should return true for existing elements." );
});
@@ -85,19 +92,19 @@ jQuery(document).ready(function() {
test("serializeNode a simple element", assert => {
var el = Wicket.$(existingId);
var asString = Wicket.DOM.serializeNode(el);
- var $deserialized = jQuery(asString);
- assert.equal($deserialized[0].tagName.toLowerCase() , 'span', "Wicket.DOM.serializeNode should return <span>." );
- assert.equal($deserialized.prop('id') , existingId, "<span>'s must be "+existingId+"." );
+ var deserialized = parseElement(asString);
+ assert.equal(deserialized.tagName.toLowerCase() , 'span', "Wicket.DOM.serializeNode should return <span>." );
+ assert.equal(deserialized.id , existingId, "<span>'s must be "+existingId+"." );
});
test("serializeNode(Children) a complex element", assert => {
var el = Wicket.$(complexElementId);
var asString = Wicket.DOM.serializeNode(el);
- var $deserialized = jQuery(asString);
- assert.equal($deserialized[0].tagName.toLowerCase(), 'div', 'The serialized element name should be <div>');
- assert.equal($deserialized.prop('id'), complexElementId, 'The serialized element id should be ' + complexElementId);
- assert.equal($deserialized.children()[0].tagName.toLowerCase(), 'a', 'The serialized element should have one child <a>');
- assert.equal($deserialized.text().trim(), 'Link', 'The serialized element should have text "Link"');
+ var deserialized = parseElement(asString);
+ assert.equal(deserialized.tagName.toLowerCase(), 'div', 'The serialized element name should be <div>');
+ assert.equal(deserialized.id, complexElementId, 'The serialized element id should be ' + complexElementId);
+ assert.equal(deserialized.children[0].tagName.toLowerCase(), 'a', 'The serialized element should have one child <a>');
+ assert.equal(deserialized.textContent.trim(), 'Link', 'The serialized element should have text "Link"');
});
test("show() an element", assert => {
@@ -197,13 +204,13 @@ jQuery(document).ready(function() {
});
Wicket.Event.subscribe('/dom/node/added', function(jqEvent, addedElement) {
- assert.equal(jQuery(addedElement).text(), "New One", "The added element text match!");
+ assert.equal(addedElement.textContent, "New One", "The added element text match!");
});
var toReplace = Wicket.$('testDomEventNotifications');
var newElementMarkup = '<div id="testDomEventNotifications">New One</div>';
Wicket.DOM.replace(toReplace, newElementMarkup);
- jQuery(document).off();
+ Wicket.Event.unsubscribe();
});
/**
@@ -224,12 +231,12 @@ jQuery(document).ready(function() {
var toReplace = Wicket.$('testDomEventNotifications');
var newElementMarkup = '';
Wicket.DOM.replace(toReplace, newElementMarkup);
- jQuery(document).off();
+ Wicket.Event.unsubscribe();
});
test("text - read text from a node with single text type child", assert => {
- var node = jQuery("<div></div>")[0];
+ var node = document.createElement("div");
var doc = node.ownerDocument;
var textNode = doc.createTextNode("some text");
node.appendChild(textNode);
diff --git a/wicket-core/src/test/js/event.js b/wicket-core/src/test/js/event.js
index e2cfeebec5..e23d5c043d 100644
--- a/wicket-core/src/test/js/event.js
+++ b/wicket-core/src/test/js/event.js
@@ -16,18 +16,27 @@
*/
/*global ok: true, start: true, stop: true, test: true, equal: true, deepEqual: true,
- QUnit: true, module: true, expect: true */
+ QUnit: true, module: true, expect: true, KeyboardEvent: true */
-jQuery(document).ready(function() {
+Wicket.Event.add(window, 'domready', function() {
"use strict";
const { module, test } = QUnit;
+ // creates a test element inside #qunit-fixture, without depending on jQuery
+ var createTestElement = function (id) {
+ var el = document.createElement('div');
+ el.id = id || 'addTestId';
+ el.textContent = 'element body';
+ document.getElementById('qunit-fixture').appendChild(el);
+ return el;
+ };
+
module('Wicket.Event.getId');
test('getId - of an element with specified id', assert => {
- var element = jQuery('.getIdClass1')[0];
+ var element = document.querySelector('.getIdClass1');
var id = Wicket.Event.getId(element);
assert.equal(id, 'specifiedId', 'The specified element id is properly read');
@@ -35,49 +44,69 @@ jQuery(document).ready(function() {
test('getId - of an element without specified id', assert => {
- var element = jQuery('.getIdClass2')[0];
+ var element = document.querySelector('.getIdClass2');
var id = Wicket.Event.getId(element);
assert.equal(id, 'wicket-generated-id-0', 'The element without specified id will have an auto generated one');
- var element2 = jQuery('.getIdClass2');
- assert.equal(element2.prop('id'), 'wicket-generated-id-0', 'The generated id is assigned');
+ var element2 = document.querySelector('.getIdClass2');
+ assert.equal(element2.id, 'wicket-generated-id-0', 'The generated id is assigned');
});
module('Wicket.Event.keyCode');
test('keyCode', assert => {
- var evt = jQuery.Event("keydown", { keyCode: 123 });
+ var evt = new KeyboardEvent("keydown", { keyCode: 123 });
assert.equal(Wicket.Event.keyCode(evt), 123, 'event.keyCode should be used if available');
});
- test('which', assert => {
+ module('Wicket.Event.stop');
- var evt = jQuery.Event("which", { keyCode: 123 });
+ test('stop', assert => {
- assert.equal(Wicket.Event.keyCode(evt), 123, 'event.which should be used if event.keyCode is not available');
- });
+ var fixture = document.getElementById('qunit-fixture');
- module('Wicket.Event.stop');
+ // stopPropagation(): must prevent the event from bubbling to the parent,
+ // but must not stop other listeners registered on the same element
+ var parent1 = document.createElement('div');
+ var child1 = document.createElement('div');
+ parent1.appendChild(child1);
+ fixture.appendChild(parent1);
- test('stop', assert => {
+ var parent1Notified = false;
+ parent1.addEventListener('click', function () { parent1Notified = true; });
+
+ var secondListener1Notified = false;
+ child1.addEventListener('click', function (evt) { Wicket.Event.stop(evt); });
+ child1.addEventListener('click', function () { secondListener1Notified = true; });
+
+ child1.dispatchEvent(new Event('click', { bubbles: true, cancelable: true }));
- var evt = jQuery.Event("keydown", { keyCode: 123 });
+ assert.equal(parent1Notified, false, "stop() should prevent the event from bubbling to the parent");
+ assert.equal(secondListener1Notified, true, "stop() without 'immediate' should not stop other listeners on the same element");
- assert.equal(evt.isPropagationStopped(), false);
- assert.equal(evt.isImmediatePropagationStopped(), false);
+ // stopImmediatePropagation(): must also prevent other listeners on the same element
+ var parent2 = document.createElement('div');
+ var child2 = document.createElement('div');
+ parent2.appendChild(child2);
+ fixture.appendChild(parent2);
- Wicket.Event.stop(evt);
+ var parent2Notified = false;
+ parent2.addEventListener('click', function () { parent2Notified = true; });
- assert.equal(evt.isPropagationStopped(), true);
- assert.equal(evt.isImmediatePropagationStopped(), false);
+ var secondListener2Notified = false;
+ child2.addEventListener('click', function (evt) { Wicket.Event.stop(evt, true); });
+ child2.addEventListener('click', function () { secondListener2Notified = true; });
- Wicket.Event.stop(evt, true);
+ child2.dispatchEvent(new Event('click', { bubbles: true, cancelable: true }));
- assert.equal(evt.isPropagationStopped(), true);
- assert.equal(evt.isImmediatePropagationStopped(), true);
+ assert.equal(parent2Notified, false, "stop(evt, true) should prevent the event from bubbling to the parent");
+ assert.equal(secondListener2Notified, false, "stop(evt, true) should stop other listeners on the same element");
+
+ parent1.remove();
+ parent2.remove();
});
module('Wicket.Event.fix');
@@ -86,66 +115,63 @@ jQuery(document).ready(function() {
assert.expect(1);
- var evt = jQuery.Event("keydown", { keyCode: 123 });
- jQuery(document)
- .on('keydown', function(event) {
- var fixedEvt = Wicket.Event.fix(event);
- assert.deepEqual(fixedEvt, evt);
- })
- .trigger(evt);
+ var handler = function (event) {
+ Wicket.Event.remove(document, 'keydown', handler);
+ var fixedEvt = Wicket.Event.fix(event);
+ assert.strictEqual(fixedEvt, event, "Wicket.Event.fix() should return the same event it was given");
+ };
+ Wicket.Event.add(document, 'keydown', handler);
+
+ document.dispatchEvent(new Event('keydown', { bubbles: true, cancelable: true }));
});
-
-
+
+
module('Wicket.Event.fire');
test('fire', assert => {
assert.expect(1);
- var $el = jQuery('<div id="fireTestId">element body</div>');
- $el.appendTo(jQuery('#qunit-fixture'));
- $el.on('click', function() {
+ var el = createTestElement('fireTestId');
+ el.addEventListener('click', function() {
assert.ok(true, 'This event must be fired!');
});
- Wicket.Event.fire($el[0], 'click');
+ Wicket.Event.fire(el, 'click');
- $el.remove();
+ el.remove();
});
-
+
module('Wicket.Event.add');
test('add - any event', assert => {
assert.expect(1);
- var $el = jQuery('<div id="addTestId">element body</div>');
- $el.appendTo(jQuery('#qunit-fixture'));
+ var el = createTestElement();
var handler = function() {
assert.ok(true, 'This event must be fired!');
};
- Wicket.Event.add($el[0], 'click', handler);
+ Wicket.Event.add(el, 'click', handler);
- Wicket.Event.fire($el[0], 'click');
+ Wicket.Event.fire(el, 'click');
- $el.remove();
+ el.remove();
});
test('remove - any event', assert => {
assert.expect(1);
- var $el = jQuery('<div id="addTestId">element body</div>');
- $el.appendTo(jQuery('#qunit-fixture'));
+ var el = createTestElement();
var handler = function() {
assert.ok(true, 'This event must be fired!');
};
- var el = $el[0];
Wicket.Event.add(el, 'click', handler);
Wicket.Event.fire(el, 'click');
@@ -153,65 +179,64 @@ jQuery(document).ready(function() {
Wicket.Event.remove(el, 'click', handler);
Wicket.Event.fire(el, 'click');
+
+ el.remove();
});
-
+
test('add - mousewheel', assert => {
assert.expect(1);
- var $el = jQuery('<div id="addTestId">element body</div>');
- $el.appendTo(jQuery('#qunit-fixture'));
+ var el = createTestElement();
var handler = function() {
assert.ok(true, 'This event must be fired!');
};
- Wicket.Event.add($el[0], 'mousewheel', handler);
+ Wicket.Event.add(el, 'mousewheel', handler);
- Wicket.Event.fire($el[0], 'mousewheel');
+ Wicket.Event.fire(el, 'mousewheel');
- $el.remove();
+ el.remove();
});
-
+
test('add - domready on non-window element', assert => {
const done = assert.async();
assert.expect(1);
- var $el = jQuery('<div id="addTestId">element body</div>');
- $el.appendTo(jQuery('#qunit-fixture'));
+ var el = createTestElement();
var handler = function() {
done();
assert.ok(true, 'This event must be fired!');
};
- Wicket.Event.add($el[0], 'domready', handler);
+ Wicket.Event.add(el, 'domready', handler);
- Wicket.Event.fire($el[0], 'domready');
+ Wicket.Event.fire(el, 'domready');
- $el.remove();
+ el.remove();
});
test('add - with data', assert => {
assert.expect(1);
- var $el = jQuery('<div id="addTestId">element body</div>');
- $el.appendTo(jQuery('#qunit-fixture'));
+ var el = createTestElement();
var expectedData = {
pass: true
};
- var handler = function(jqEvent) {
- assert.deepEqual(jqEvent.data, expectedData, "Wicket.Event.add should be able to pass data to the event.");
+ var handler = function(jqEvent, data) {
+ assert.deepEqual(data, expectedData, "Wicket.Event.add should be able to pass data to the event.");
};
- Wicket.Event.add($el[0], 'dummy', handler, expectedData);
+ Wicket.Event.add(el, 'dummy', handler, expectedData);
- Wicket.Event.fire($el[0], 'dummy');
+ Wicket.Event.fire(el, 'dummy');
- $el.remove();
+ el.remove();
});
test('add - domready on window', assert => {
@@ -313,7 +338,7 @@ jQuery(document).ready(function() {
var subscriber = function () {
assert.ok(true, 'Should be notified for any topic name');
- assert.equal(arguments.length, 3, "1 jQuery.Event + our two args");
+ assert.equal(arguments.length, 3, "1 event object + our two args");
assert.equal(arguments[1], "arg1", "'arg1' must be at position 1");
assert.equal(arguments[2], "arg2", "'arg2' must be at position 2");
};
diff --git a/wicket-core/src/test/js/form.js b/wicket-core/src/test/js/form.js
index 59caa5b53c..ea63867310 100644
--- a/wicket-core/src/test/js/form.js
+++ b/wicket-core/src/test/js/form.js
@@ -18,37 +18,45 @@
/*global ok: true, start: true, test: true, equal: true, deepEqual: true,
QUnit: true, expect: true */
-jQuery(document).ready(function() {
+Wicket.Event.add(window, 'domready', function() {
"use strict";
const { module, test } = QUnit;
+ // mimics jQuery.param(params, true) (the 'traditional' serialization of an
+ // array of {name, value} pairs) without depending on jQuery
+ var toQueryString = function (params) {
+ return params.map(function (p) {
+ return encodeURIComponent(p.name) + '=' + encodeURIComponent(p.value);
+ }).join('&');
+ };
+
module("encode");
test("Wicket.Form.encode ", assert => {
assert.expect(2);
- var textInputValue = jQuery('#textInputId').val();
+ var textInputValue = document.getElementById('textInputId').value;
var encodedASCII = Wicket.Form.encode(textInputValue);
assert.equal( encodedASCII, 'textValue', "Wicket.Form.encode() shouldn't change ASCII text'" );
- var textInputUTFValue = jQuery('#textInputUTFId').val();
+ var textInputUTFValue = document.getElementById('textInputUTFId').value;
var encodedUTF = Wicket.Form.encode(textInputUTFValue);
// the expected value is the encoded version of 'нещо на български' (translation of 'something in Bulgarian')
assert.equal( encodedUTF, '%D0%BD%D0%B5%D1%89%D0%BE%20%D0%BD%D0%B0%20%D0%B1%D1%8A%D0%BB%D0%B3%D0%B0%D1%80%D1%81%D0%BA%D0%B8', "Wicket.Form.encode() should encode UTF text'" );
});
-
+
test('Wicket.Form.serializeSelect', assert => {
assert.expect(2);
var select = Wicket.$('selectId');
var serializedSelect = Wicket.Form.serializeSelect(select);
- serializedSelect = jQuery.param(serializedSelect, true);
+ serializedSelect = toQueryString(serializedSelect);
assert.equal(serializedSelect, 'select=0', 'Wicket.Form.serializeSelect should be able to serialize non-multiple select!');
var multipleSelect = Wicket.$('multipleSelectId');
var serializedMultipleSelect = Wicket.Form.serializeSelect(multipleSelect);
- serializedMultipleSelect = jQuery.param(serializedMultipleSelect, true);
+ serializedMultipleSelect = toQueryString(serializedMultipleSelect);
assert.equal(serializedMultipleSelect, 'multipleSelect=0&multipleSelect=2', 'Wicket.Form.serializeSelect should be able to serialize multiple select!');
});
@@ -56,8 +64,8 @@ jQuery(document).ready(function() {
assert.expect(1);
var actual = [];
- jQuery('#testForm input').each(function() {
- var serialized = Wicket.Form.serializeInput(this);
+ document.querySelectorAll('#testForm input').forEach(function(el) {
+ var serialized = Wicket.Form.serializeInput(el);
actual = actual.concat(serialized);
});
@@ -82,8 +90,8 @@ jQuery(document).ready(function() {
assert.expect(1);
var actual = [];
- jQuery('#testForm textarea').each(function() {
- var serialized = Wicket.Form.serializeInput(this);
+ document.querySelectorAll('#testForm textarea').forEach(function(el) {
+ var serialized = Wicket.Form.serializeInput(el);
actual = actual.concat(serialized);
});
@@ -104,8 +112,8 @@ jQuery(document).ready(function() {
assert.expect(1);
var actual = [];
- jQuery('input, textarea, select', jQuery('#testForm')).each(function() {
- var serialized = Wicket.Form.serializeElement(this);
+ document.querySelectorAll('#testForm input, #testForm textarea, #testForm select').forEach(function(el) {
+ var serialized = Wicket.Form.serializeElement(el);
actual = actual.concat(serialized);
});
@@ -166,51 +174,41 @@ jQuery(document).ready(function() {
test('Wicket.Form.serialize - form element WITHOUT searching for the parent form', assert => {
- var dontTryToFindRootForm = true,
- queryString = '';
+ var dontTryToFindRootForm = true;
- jQuery('#urlInputId').each(function() {
- queryString = Wicket.Form.serialize(this, dontTryToFindRootForm);
- });
+ var queryString = Wicket.Form.serialize(document.getElementById('urlInputId'), dontTryToFindRootForm);
- queryString = jQuery.param(queryString, true);
+ queryString = toQueryString(queryString);
assert.equal(queryString, 'urlInput=http%3A%2F%2Fexample.com', 'Wicket.Form.serialize should not serialize the whole form when an element is passed and the parent form should not be searched');
});
test('Wicket.Form.serialize - form element WITH searching for the parent form', assert => {
- var dontTryToFindRootForm = false,
- queryString = '';
+ var dontTryToFindRootForm = false;
- jQuery('#urlInputId').each(function() {
- queryString = Wicket.Form.serialize(this, dontTryToFindRootForm);
- });
+ var queryString = Wicket.Form.serialize(document.getElementById('urlInputId'), dontTryToFindRootForm);
- queryString = jQuery.param(queryString, true);
- var space = jQuery.fn.jquery.startsWith("2") ? "+" : "%20";
- assert.equal(queryString, 'textInput=textValue&textUTFInput=%D0%BD%D0%B5%D1%89%D0%BE'+space+'%D0%BD%D0%B0'+space+'%D0%B1%D1%8A%D0%BB%D0%B3%D0%B0%D1%80%D1%81%D0%BA%D0%B8&checkBoxInput1=cbValue1&checkBoxInput3=cbValue3&radioInput=radioValue1&emailInput=m%40g.com&urlInput=http%3A%2F%2Fexample.com&searchInput=wicket&rangeInput=67&numberInput=16&colorInput=%23123456&multipleSelect=0&multipleSelect=2&select=0&textArea=some'+space+'text', 'Wicket.Form.serialize should serialize the whole form [...]
+ queryString = toQueryString(queryString);
+ assert.equal(queryString, 'textInput=textValue&textUTFInput=%D0%BD%D0%B5%D1%89%D0%BE%20%D0%BD%D0%B0%20%D0%B1%D1%8A%D0%BB%D0%B3%D0%B0%D1%80%D1%81%D0%BA%D0%B8&checkBoxInput1=cbValue1&checkBoxInput3=cbValue3&radioInput=radioValue1&emailInput=m%40g.com&urlInput=http%3A%2F%2Fexample.com&searchInput=wicket&rangeInput=67&numberInput=16&colorInput=%23123456&multipleSelect=0&multipleSelect=2&select=0&textArea=some%20text', 'Wicket.Form.serialize should serialize the whole form when an element i [...]
});
test('Wicket.Form.serialize - form element WITH searching for the parent form', assert => {
- var dontTryToFindRootForm = true,
- queryString = '';
+ var dontTryToFindRootForm = true;
- jQuery('#testForm').each(function() {
- queryString = Wicket.Form.serialize(this, dontTryToFindRootForm);
- });
+ var queryString = Wicket.Form.serialize(document.getElementById('testForm'), dontTryToFindRootForm);
- queryString = jQuery.param(queryString, true);
- var space = jQuery.fn.jquery.startsWith("2") ? "+" : "%20";
- assert.equal(queryString, 'textInput=textValue&textUTFInput=%D0%BD%D0%B5%D1%89%D0%BE'+space+'%D0%BD%D0%B0'+space+'%D0%B1%D1%8A%D0%BB%D0%B3%D0%B0%D1%80%D1%81%D0%BA%D0%B8&checkBoxInput1=cbValue1&checkBoxInput3=cbValue3&radioInput=radioValue1&emailInput=m%40g.com&urlInput=http%3A%2F%2Fexample.com&searchInput=wicket&rangeInput=67&numberInput=16&colorInput=%23123456&multipleSelect=0&multipleSelect=2&select=0&textArea=some'+space+'text', 'Wicket.Form.serialize should serialize the whole form [...]
+ queryString = toQueryString(queryString);
+ assert.equal(queryString, 'textInput=textValue&textUTFInput=%D0%BD%D0%B5%D1%89%D0%BE%20%D0%BD%D0%B0%20%D0%B1%D1%8A%D0%BB%D0%B3%D0%B0%D1%80%D1%81%D0%BA%D0%B8&checkBoxInput1=cbValue1&checkBoxInput3=cbValue3&radioInput=radioValue1&emailInput=m%40g.com&urlInput=http%3A%2F%2Fexample.com&searchInput=wicket&rangeInput=67&numberInput=16&colorInput=%23123456&multipleSelect=0&multipleSelect=2&select=0&textArea=some%20text', 'Wicket.Form.serialize should serialize the whole form when a the form i [...]
});
test('Wicket.Form.serializeForm - serialize nested form (div element)', assert => {
assert.expect(1);
- var $nestedForm = jQuery(
+ var template = document.createElement('template');
+ template.innerHTML =
"<form>" +
"<input type='text' name='textInput' value='textInputValue'/>" +
"<div id='nestedForm'>" +
@@ -223,10 +221,9 @@ jQuery(document).ready(function() {
"<option value='selectInputValue2' selected>Value 2</option>" +
"</select>" +
"</div>" +
- "</form>"
- );
+ "</form>";
- jQuery("#qunit-fixture").append($nestedForm);
+ document.getElementById("qunit-fixture").appendChild(template.content);
var nestedFormDiv = Wicket.$('nestedForm');
var actual = Wicket.Form.serializeForm(nestedFormDiv);
diff --git a/wicket-core/src/test/js/head.js b/wicket-core/src/test/js/head.js
index 6f5e7a7a3b..2b24f281f8 100644
--- a/wicket-core/src/test/js/head.js
+++ b/wicket-core/src/test/js/head.js
@@ -18,26 +18,37 @@
/*global ok: true, start: true, test: true, equal: true, deepEqual: true,
QUnit: true, expect: true */
-jQuery(document).ready(function() {
+Wicket.Event.add(window, 'domready', function() {
"use strict";
const { module, test } = QUnit;
+ // creates an element with the given tag name and attributes, without depending on jQuery
+ var createElement = function (tagName, attributes) {
+ var el = document.createElement(tagName);
+ for (var name in attributes) {
+ if (attributes.hasOwnProperty(name)) {
+ el[name] = attributes[name];
+ }
+ }
+ return el;
+ };
+
module("addElement");
-
+
test("Wicket.Head.addElement - add link element", assert => {
- var css = jQuery('<link>', {
+ var css = createElement('link', {
type: 'text/stylesheet',
rel: 'stylesheet',
href: 'data/test.css'
}),
- initialHeadElementsNumber = jQuery('head').children().length;
+ initialHeadElementsNumber = document.head.children.length;
- Wicket.Head.addElement(css[0]);
+ Wicket.Head.addElement(css);
- var newHeadElementsNumber = jQuery('head').children().length;
+ var newHeadElementsNumber = document.head.children.length;
assert.equal(newHeadElementsNumber, initialHeadElementsNumber + 1);
});
@@ -47,17 +58,17 @@ jQuery(document).ready(function() {
const done = assert.async();
Wicket.testDone = done;
assert.expect(1);
-
- var script = jQuery('<script>', {
+
+ var script = createElement('script', {
type: 'text/javascript',
src: 'data/start.js'
}),
- initialHeadElementsNumber = jQuery('head').children().length;
+ initialHeadElementsNumber = document.head.children.length;
- Wicket.Head.addElement(script[0]);
+ Wicket.Head.addElement(script);
- var newHeadElementsNumber = jQuery('head').children().length;
+ var newHeadElementsNumber = document.head.children.length;
assert.equal(newHeadElementsNumber, initialHeadElementsNumber + 1);
});
@@ -65,13 +76,15 @@ jQuery(document).ready(function() {
test("Wicket.Head.addElement - add style element", assert => {
assert.expect(1);
- var $style = jQuery('<style> body: {font-family: bold;} </style>'),
+ var style = createElement('style', {
+ textContent: ' body: {font-family: bold;} '
+ }),
- initialHeadElementsNumber = jQuery('head').children().length;
+ initialHeadElementsNumber = document.head.children.length;
- Wicket.Head.addElement($style[0]);
+ Wicket.Head.addElement(style);
- var newHeadElementsNumber = jQuery('head').children().length;
+ var newHeadElementsNumber = document.head.children.length;
assert.equal(newHeadElementsNumber, initialHeadElementsNumber + 1);
});
@@ -90,14 +103,14 @@ jQuery(document).ready(function() {
test('Wicket.Head.containsElement - check existence of data/test.js with jsessionid in the url', assert => {
var
- script1 = jQuery('<script>', {
+ script1 = createElement('script', {
type: 'text/javascript',
src: 'data/test.js;jsessionid=1'
- })[0],
- script2 = jQuery('<script>', {
+ }),
+ script2 = createElement('script', {
type: 'text/javascript',
src: 'data/test.js;jsessionid=2' // different jsessionid
- })[0];
+ });
// add just jsessionid=1
Wicket.Head.addElement(script1);
@@ -108,16 +121,16 @@ jQuery(document).ready(function() {
test('Wicket.Head.containsElement - check replacement of SCRIPT elements with same id', assert => {
var
- script1 = jQuery('<script>', {
+ script1 = createElement('script', {
type: 'text/javascript',
src: 'data/one.js',
id: 'testId'
- })[0],
- script2 = jQuery('<script>', {
+ }),
+ script2 = createElement('script', {
type: 'text/javascript',
src: 'data/two.js',
id: 'testId'
- })[0],
+ }),
context = {
steps: []
};
@@ -129,7 +142,7 @@ jQuery(document).ready(function() {
assert.ok(Wicket.Head.containsElement(script1, 'src').contains, 'script1 should be in the DOM - 2.');
// poor man's FunctionExecuter
- jQuery.each(context.steps, function(idx, step) {
+ context.steps.forEach(function(step) {
step(function() {});
});
@@ -141,16 +154,16 @@ jQuery(document).ready(function() {
test('Wicket.Head.containsElement - check replacement of <link> elements with same id', assert => {
var
- css1 = jQuery('<link>', {
+ css1 = createElement('link', {
type: 'text/css',
href: 'data/one.css',
id: 'testId'
- })[0],
- css2 = jQuery('<link>', {
+ }),
+ css2 = createElement('link', {
type: 'text/css',
href: 'data/two.css',
id: 'testId'
- })[0],
+ }),
context = {
steps: []
};
@@ -164,7 +177,7 @@ jQuery(document).ready(function() {
assert.ok(containsCss2.contains, 'css1 should be still in the DOM');
// poor man's FunctionExecuter
- jQuery.each(context.steps, function(idx, step) {
+ context.steps.forEach(function(step) {
step(function() {});
});
@@ -176,11 +189,11 @@ jQuery(document).ready(function() {
});
test('Wicket.Head.Contributor.parse - parse head element with three script elements inside', assert => {
-
+
var xmlDocument = Wicket.Xml.parse('<header-contribution><![CDATA[<head><script type="text/javascript" src="data/test.js"></script><script type="text/javascript" id="wicket-ajax-debug-enable">/*<![CDATA[*/wicketAjaxDebugEnable=true;/*]]]]><![CDATA[>*/</script><script type="text/javascript" id="wicket-ajax-base-url">/*<![CDATA[*/Wicket.Ajax.baseUrl="clock";/*]]]]><![CDATA[>*/</script></head>]]></header-contribution>');
var xmlRootElement = xmlDocument.documentElement;
var xmlElement = Wicket.Head.Contributor.parse(xmlRootElement);
- var isXml = jQuery.isXMLDoc(xmlElement);
+ var isXml = xmlElement.documentElement != null && xmlElement.contentType !== 'text/html';
assert.ok(isXml, 'The result must be XML document');
assert.equal(xmlElement.documentElement.childNodes.length, 3, "There must be 3 children nodes.");
diff --git a/wicket-core/src/test/js/timer.js b/wicket-core/src/test/js/timer.js
index 23a7ae2d59..e34795ccd5 100644
--- a/wicket-core/src/test/js/timer.js
+++ b/wicket-core/src/test/js/timer.js
@@ -17,7 +17,7 @@
/*global ok: true, start: true, test: true, equal: true, deepEqual: true,
QUnit: true, expect: true, stop: true */
-jQuery(document).ready(function() {
+Wicket.Event.add(window, 'domready', function() {
"use strict";
const { module, test } = QUnit;
diff --git a/wicket-devutils/src/main/java/org/apache/wicket/devutils/debugbar/wicket-debugbar.js b/wicket-devutils/src/main/java/org/apache/wicket/devutils/debugbar/wicket-debugbar.js
index 4d70320c73..5c81d85e46 100644
--- a/wicket-devutils/src/main/java/org/apache/wicket/devutils/debugbar/wicket-debugbar.js
+++ b/wicket-devutils/src/main/java/org/apache/wicket/devutils/debugbar/wicket-debugbar.js
@@ -14,7 +14,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-;(function (jQuery, undefined) {
+;(function (undefined) {
'use strict';
@@ -26,23 +26,27 @@
return;
}
+ function isVisible(element) {
+ return !!(element.offsetWidth || element.offsetHeight || element.getClientRects().length);
+ }
+
Wicket.debugBar = function() {
-
+
function setExpandedCookie(value) {
- document.cookie = "wicketDebugBarState=" + window.escape(value);
+ document.cookie = "wicketDebugBarState=" + window.encodeURIComponent(value);
}
-
+
function getExpandedCookie() {
- var name = 'wicketDebugBarState';
+ const name = 'wicketDebugBarState';
if (document.cookie.length > 0) {
- var start = document.cookie.indexOf (name + "=");
+ let start = document.cookie.indexOf (name + "=");
if (start !== -1) {
start = start + name.length + 1;
- var end = document.cookie.indexOf(";", start);
+ let end = document.cookie.indexOf(";", start);
if (end === -1) {
end = document.cookie.length;
}
- return window.unescape(document.cookie.substring(start,end));
+ return window.decodeURIComponent(document.cookie.substring(start,end));
} else {
return null;
}
@@ -51,32 +55,46 @@
}
}
- jQuery('#wicketDebugBarCollapse').on("click", function() {
- var content = jQuery('#wicketDebugBarContents');
- setExpandedCookie(!content.is(':visible'));
- content.toggle(400);
- });
+ const collapse = document.getElementById('wicketDebugBarCollapse');
+ if (collapse) {
+ collapse.addEventListener("click", function() {
+ const content = document.getElementById('wicketDebugBarContents');
+ const wasVisible = isVisible(content);
+ setExpandedCookie(!wasVisible);
+ if (wasVisible) {
+ Wicket.DOM.hide(content);
+ } else {
+ Wicket.DOM.show(content);
+ }
+ });
+ }
- jQuery('#wicketDebugBarRemove').on("click", function() {
- var bar = jQuery('#wicketDebugBar');
- setExpandedCookie(!bar.is(':visible'));
- bar.hide();
- });
+ const remove = document.getElementById('wicketDebugBarRemove');
+ if (remove) {
+ remove.addEventListener("click", function() {
+ const bar = document.getElementById('wicketDebugBar');
+ setExpandedCookie(!isVisible(bar));
+ Wicket.DOM.hide(bar);
+ });
+ }
// determine state and set it
if (getExpandedCookie() === 'false') {
- jQuery('#wicketDebugBarContents').hide();
+ Wicket.DOM.hide(document.getElementById('wicketDebugBarContents'));
}
-
- var original = Wicket.Log.error;
+
+ const original = Wicket.Log.error;
Wicket.Log.error = function() {
original.apply(Wicket.Log, arguments);
-
- jQuery('#wicketDebugBar')
- .addClass('wicketDebugBarError')
- .one('animationend', function() {
- jQuery(this).removeClass('wicketDebugBarError');
- });
+
+ const bar = document.getElementById('wicketDebugBar');
+ if (bar) {
+ bar.classList.add('wicketDebugBarError');
+ bar.addEventListener('animationend', function onAnimationEnd() {
+ bar.classList.remove('wicketDebugBarError');
+ bar.removeEventListener('animationend', onAnimationEnd);
+ }, { once: true });
+ }
};
};
-})(jQuery);
+})();
diff --git a/wicket-examples/src/main/java/org/apache/wicket/examples/AjaxEngineSelector.java b/wicket-examples/src/main/java/org/apache/wicket/examples/AjaxEngineSelector.java
new file mode 100644
index 0000000000..8d75c3ff62
--- /dev/null
+++ b/wicket-examples/src/main/java/org/apache/wicket/examples/AjaxEngineSelector.java
@@ -0,0 +1,228 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.wicket.examples;
+
+import org.apache.wicket.MetaDataKey;
+import org.apache.wicket.Session;
+import org.apache.wicket.ajax.WicketAjaxJQueryResourceReference;
+import org.apache.wicket.ajax.WicketAjaxResourceReference;
+import org.apache.wicket.protocol.http.WebApplication;
+import org.apache.wicket.request.resource.ResourceReference;
+import org.apache.wicket.settings.JavaScriptLibrarySettings;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Lets every example application be started with either the default, JQuery-based
+ * {@code wicket-ajax.js} implementation or the JQuery-free plain JavaScript one, selected with a
+ * single JVM-wide system property rather than having to change code in each of the many
+ * {@link org.apache.wicket.examples.WicketExampleApplication} subclasses individually:
+ *
+ * <pre>
+ * -Dwicket.examples.use=JQUERY (default - JQuery-based wicket-ajax.js)
+ * -Dwicket.examples.use=VANILLA (JQuery-free, plain JavaScript wicket-ajax.js)
+ * </pre>
+ *
+ * Call {@link #configure(WebApplication)} once from each application's {@code init()}.
+ * <p>
+ * On top of that JVM-wide default, {@link #setSessionEngine(Engine)} lets a single browser
+ * session switch to the other engine at runtime - e.g. from a link in
+ * {@link WicketExampleHeader} - so the two implementations can be compared side by side without
+ * restarting the application. The override is stored in the session and is picked up by every
+ * page from the next full page load on - a client that already has one engine's JavaScript
+ * loaded cannot swap it out live, hence "next full page load" rather than instantly.
+ * <p>
+ * {@link #configure(WebApplication)} installs this by replacing the application's
+ * {@link JavaScriptLibrarySettings} with one whose
+ * {@link JavaScriptLibrarySettings#getWicketAjaxReference() getWicketAjaxReference()} resolves
+ * {@link #getEffectiveEngine()} on every call, rather than by rewriting header items after the
+ * fact. That single instance is shared by all sessions, but it stores nothing: it just forwards
+ * to whatever {@link Session#get()} resolves to on the calling thread, so concurrent sessions
+ * with different choices never interfere with each other. Answering at the source also means
+ * everything downstream - the {@link org.apache.wicket.markup.head.ResourceAggregator} resolving
+ * dependencies (so JQuery itself is not contributed at all under {@link Engine#VANILLA}), the
+ * CSP nonce that {@link org.apache.wicket.csp.CSPNonceHeaderResponseDecorator} stamps onto each
+ * script, and dependants such as {@link org.apache.wicket.markup.head.OnDomReadyHeaderItem} -
+ * sees the engine this session actually asked for.
+ *
+ * @see org.apache.wicket.settings.JavaScriptLibrarySettings
+ * @see WicketAjaxResourceReference
+ */
+public final class AjaxEngineSelector
+{
+ /** The name of the system property that selects the Ajax engine. */
+ public static final String SYSTEM_PROPERTY = "wicket.examples.use";
+
+ private static final Logger log = LoggerFactory.getLogger(AjaxEngineSelector.class);
+
+ private static final MetaDataKey<Engine> SESSION_ENGINE_KEY = new MetaDataKey<>()
+ {
+ private static final long serialVersionUID = 1L;
+ };
+
+ /** The two available client-side Ajax engines. */
+ public enum Engine
+ {
+ JQUERY,
+ VANILLA
+ }
+
+ private AjaxEngineSelector()
+ {
+ }
+
+ /**
+ * Replaces the given application's {@link JavaScriptLibrarySettings} with one that resolves
+ * the {@code wicket-ajax.js} implementation per request from {@link #getEffectiveEngine()} -
+ * the {@value #SYSTEM_PROPERTY} system property, or the current session's override if
+ * {@link #setSessionEngine(Engine)} was called on it.
+ *
+ * @param application
+ * the application to configure
+ */
+ public static void configure(WebApplication application)
+ {
+ Engine engine = parseEngine(System.getProperty(SYSTEM_PROPERTY, Engine.JQUERY.name()), true);
+
+ application.setJavaScriptLibrarySettings(new JavaScriptLibrarySettings()
+ {
+ @Override
+ public ResourceReference getWicketAjaxReference()
+ {
+ return referenceFor(getEffectiveEngine());
+ }
+ });
+
+ log.info("Wicket examples Ajax engine: {}", engine);
+ outputAjaxEngineBanner(engine);
+ }
+
+ /**
+ * @return the Ajax engine that is actually in effect for the current request: the current
+ * session's override if {@link #setSessionEngine(Engine)} was called on it,
+ * otherwise this application's configured default (the {@value #SYSTEM_PROPERTY}
+ * system property).
+ */
+ public static Engine getEffectiveEngine()
+ {
+ if (Session.exists())
+ {
+ Engine override = Session.get().getMetaData(SESSION_ENGINE_KEY);
+ if (override != null)
+ {
+ return override;
+ }
+ }
+ return parseEngine(System.getProperty(SYSTEM_PROPERTY, Engine.JQUERY.name()), false);
+ }
+
+ /**
+ * Overrides, for the current session only, which Ajax engine is used - every page in this
+ * session will use it from now on. Concurrent sessions (e.g. other browsers, or a different
+ * session in the same browser) are unaffected. Takes effect on the next full page load; a
+ * page whose response has already been sent to the browser keeps whichever engine it was
+ * rendered with, since that JavaScript is already loaded and cannot be swapped out live.
+ *
+ * @param engine
+ * the engine this session should use from now on
+ */
+ public static void setSessionEngine(Engine engine)
+ {
+ Session.get().setMetaData(SESSION_ENGINE_KEY, engine);
+ }
+
+ private static Engine parseEngine(String value, boolean warnIfInvalid)
+ {
+ try
+ {
+ return Engine.valueOf(value.trim().toUpperCase());
+ }
+ catch (IllegalArgumentException notRecognized)
+ {
+ if (warnIfInvalid)
+ {
+ log.warn("Unrecognized value '{}' for system property '{}'. Falling back to {}. " +
+ "Valid values are {} and {}.", value, SYSTEM_PROPERTY, Engine.JQUERY,
+ Engine.JQUERY, Engine.VANILLA);
+ }
+ return Engine.JQUERY;
+ }
+ }
+
+ private static ResourceReference referenceFor(Engine engine)
+ {
+ return engine == Engine.VANILLA ? WicketAjaxResourceReference.get()
+ : WicketAjaxJQueryResourceReference.get();
+ }
+
+ /**
+ * @return a human-friendly name for the given engine, suitable for display in the UI or in
+ * console output - "jQuery" or "Plain JavaScript" rather than the raw enum constant.
+ */
+ public static String displayName(Engine engine)
+ {
+ return engine == Engine.VANILLA ? "Plain JavaScript" : "jQuery";
+ }
+
+ /**
+ * Prints a banner to stdout announcing which Ajax engine this application started with,
+ * the same way {@link WebApplication#outputDevelopmentModeWarning()} unconditionally prints
+ * to stderr when running in development mode: a plain log statement can be filtered out or
+ * missed depending on logging configuration, but this always shows up in the console of
+ * whatever launched the example (StartExamples, {@code mvn jetty:run}, an application
+ * server, ...).
+ *
+ * @param engine
+ * the engine that was selected for this application
+ */
+ private static void outputAjaxEngineBanner(Engine engine)
+ {
+ String line1 = "Wicket examples Ajax engine: " + displayName(engine)
+ + (engine == Engine.JQUERY ? " (default)" : " (no jQuery)");
+ Engine other = engine == Engine.JQUERY ? Engine.VANILLA : Engine.JQUERY;
+ String line2 = "Set -D" + SYSTEM_PROPERTY + "=" + other + " for the "
+ + (other == Engine.VANILLA ? displayName(other) : "default") + " engine instead.";
+
+ // size the border/padding to fit the longer of the two lines, with a minimum width
+ // so the banner still looks like a banner for short messages
+ String prefix = "*** ";
+ String suffix = " ***";
+ int width = Math.max(70,
+ prefix.length() + suffix.length() + Math.max(line1.length(), line2.length()));
+
+ String border = "*".repeat(width);
+ System.out.print(border + "\n"
+ + pad(line1, prefix, suffix, width) + "\n"
+ + pad(line2, prefix, suffix, width) + "\n"
+ + border + "\n");
+ }
+
+ /**
+ * Pads a line of text with a leading/trailing "*** ... ***" border so that it lines up
+ * with {@link #outputAjaxEngineBanner(Engine)}'s asterisk borders.
+ */
+ private static String pad(String text, String prefix, String suffix, int width)
+ {
+ int fillLength = Math.max(0, width - prefix.length() - suffix.length() - text.length());
+ StringBuilder line = new StringBuilder(prefix).append(text);
+ for (int i = 0; i < fillLength; i++)
+ {
+ line.append(' ');
+ }
+ return line.append(suffix).toString();
+ }
+}
diff --git a/wicket-examples/src/main/java/org/apache/wicket/examples/WicketExampleApplication.java b/wicket-examples/src/main/java/org/apache/wicket/examples/WicketExampleApplication.java
index f38b9d9767..6874e5a793 100644
--- a/wicket-examples/src/main/java/org/apache/wicket/examples/WicketExampleApplication.java
+++ b/wicket-examples/src/main/java/org/apache/wicket/examples/WicketExampleApplication.java
@@ -46,7 +46,9 @@ public abstract class WicketExampleApplication extends WebApplication
protected void init()
{
super.init();
-
+
+ AjaxEngineSelector.configure(this);
+
// WARNING: DO NOT do this on a real world application. NoCrypt encrypts nothing, so
// everything that goes through the crypt factory -- the URLs CryptoMapper produces and
// the file upload tokens -- is readable and forgeable by anyone (BAD IDEA!)!!!
diff --git a/wicket-examples/src/main/java/org/apache/wicket/examples/WicketExampleHeader.html b/wicket-examples/src/main/java/org/apache/wicket/examples/WicketExampleHeader.html
index f00743ebd8..e446ad6fc1 100644
--- a/wicket-examples/src/main/java/org/apache/wicket/examples/WicketExampleHeader.html
+++ b/wicket-examples/src/main/java/org/apache/wicket/examples/WicketExampleHeader.html
@@ -7,8 +7,12 @@
<div class="logo">
<a href="index.html" target="_top"><img wicket:id="exampleheaderimage" alt="Apache Wicket" /></a>
</div>
+ <div class="ajax-engine">
+ Ajax engine: <strong wicket:id="ajaxEngine">jQuery</strong>
+ (<a wicket:id="toggleAjaxEngine">switch to <span wicket:id="toggleAjaxEngineLabel">Plain JavaScript</span></a>)
+ </div>
</div>
- <div wicket:id="debug"></div>
+ <div wicket:id="debug"></div>
</div>
</wicket:panel>
</body>
diff --git a/wicket-examples/src/main/java/org/apache/wicket/examples/WicketExampleHeader.java b/wicket-examples/src/main/java/org/apache/wicket/examples/WicketExampleHeader.java
index 71115e03c5..f36781adcb 100644
--- a/wicket-examples/src/main/java/org/apache/wicket/examples/WicketExampleHeader.java
+++ b/wicket-examples/src/main/java/org/apache/wicket/examples/WicketExampleHeader.java
@@ -17,20 +17,22 @@
package org.apache.wicket.examples;
import org.apache.wicket.devutils.debugbar.DebugBar;
+import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.image.Image;
+import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.request.resource.PackageResourceReference;
/**
* Navigation panel for the examples project.
- *
+ *
* @author Eelco Hillenius
*/
public final class WicketExampleHeader extends Panel
{
/**
* Construct.
- *
+ *
* @param id
* id of the component
* @param page
@@ -41,9 +43,34 @@ public final class WicketExampleHeader extends Panel
super(id);
setRenderBodyOnly(true);
-
+
add(new Image("exampleheaderimage", new PackageResourceReference(
WicketExamplePage.class, "logo-apachewicket-examples-white.svg")));
add(new DebugBar("debug"));
+
+ // shows which Ajax engine (jQuery-based or the jQuery-free plain JavaScript one) is
+ // currently powering this session, and lets the visitor switch to the other one on the
+ // fly to compare them - see AjaxEngineSelector for how the switch is actually applied
+ add(new Label("ajaxEngine",
+ () -> AjaxEngineSelector.displayName(AjaxEngineSelector.getEffectiveEngine())));
+
+ Link<Void> toggleAjaxEngine = new Link<>("toggleAjaxEngine")
+ {
+ @Override
+ public void onClick()
+ {
+ AjaxEngineSelector.setSessionEngine(otherEngine());
+ }
+ };
+ toggleAjaxEngine.add(new Label("toggleAjaxEngineLabel",
+ () -> AjaxEngineSelector.displayName(otherEngine())));
+ add(toggleAjaxEngine);
+ }
+
+ private static AjaxEngineSelector.Engine otherEngine()
+ {
+ return AjaxEngineSelector.getEffectiveEngine() == AjaxEngineSelector.Engine.JQUERY
+ ? AjaxEngineSelector.Engine.VANILLA
+ : AjaxEngineSelector.Engine.JQUERY;
}
}
diff --git a/wicket-examples/src/main/java/org/apache/wicket/examples/ajax/builtin/EffectsPage.java b/wicket-examples/src/main/java/org/apache/wicket/examples/ajax/builtin/EffectsPage.java
index 2cfae8a291..4c6fb2cc66 100644
--- a/wicket-examples/src/main/java/org/apache/wicket/examples/ajax/builtin/EffectsPage.java
+++ b/wicket-examples/src/main/java/org/apache/wicket/examples/ajax/builtin/EffectsPage.java
@@ -18,12 +18,14 @@ package org.apache.wicket.examples.ajax.builtin;
import java.util.Optional;
+import org.apache.wicket.RestartResponseException;
import org.apache.wicket.ajax.AjaxChannel;
import org.apache.wicket.ajax.AjaxChannel.Type;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.attributes.AjaxRequestAttributes;
import org.apache.wicket.ajax.markup.html.AjaxFallbackLink;
import org.apache.wicket.ajax.markup.html.AjaxLink;
+import org.apache.wicket.examples.AjaxEngineSelector;
import org.apache.wicket.markup.head.CssHeaderItem;
import org.apache.wicket.markup.head.IHeaderResponse;
import org.apache.wicket.markup.head.JavaScriptHeaderItem;
@@ -32,7 +34,10 @@ import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.model.PropertyModel;
/**
- * Demonstrates ajax effects
+ * Demonstrates ajax effects. Requires the jQuery-based Ajax engine: the effects it shows
+ * ({@code .effect()}, {@code .fadeOut()}, {@code .fadeIn()}) come from jQuery UI, which has no
+ * plain JavaScript equivalent in {@code wicket-ajax.js}. Unreachable under
+ * {@link AjaxEngineSelector.Engine#VANILLA}.
*/
public class EffectsPage extends BasePage
{
@@ -97,6 +102,12 @@ public class EffectsPage extends BasePage
*/
public EffectsPage()
{
+ if (AjaxEngineSelector.getEffectiveEngine() == AjaxEngineSelector.Engine.VANILLA)
+ {
+ // jQuery UI effects are not available under the jQuery-free Ajax engine
+ throw new RestartResponseException(Index.class);
+ }
+
final Label c1 = new Label("c1", new PropertyModel<>(this, "counter1"));
c1.setOutputMarkupId(true);
add(c1);
@@ -178,7 +189,7 @@ public class EffectsPage extends BasePage
public void renderHead(IHeaderResponse response)
{
super.renderHead(response);
- response.render(JavaScriptHeaderItem.forUrl("jquery-ui-1.10.3.custom.js"));
+ response.render(JavaScriptHeaderItem.forUrl("jquery-ui-v1.14.2.custom.js"));
response.render(OnDomReadyHeaderItem.forScript("jQuery.noConflict();"));
// make effects work nicely with inline elements
response.render(CssHeaderItem.forCSS(
diff --git a/wicket-examples/src/main/java/org/apache/wicket/examples/ajax/builtin/Index.html b/wicket-examples/src/main/java/org/apache/wicket/examples/ajax/builtin/Index.html
index 92a7049ab4..87813e529e 100644
--- a/wicket-examples/src/main/java/org/apache/wicket/examples/ajax/builtin/Index.html
+++ b/wicket-examples/src/main/java/org/apache/wicket/examples/ajax/builtin/Index.html
@@ -10,8 +10,8 @@
<br/><br/>
<a href="EditableLabelPage.html">Editable Label Example</a>: shows a label that can be edited inline via ajax
<br/><br/>
-<a href="EffectsPage.html">Effects Example</a>: shows how to link wicket component updates with jQuery UI effects
-<br/><br/>
+<wicket:container wicket:id="effectsSection"><a href="EffectsPage.html">Effects Example</a>: shows how to link wicket component updates with jQuery UI effects
+<br/><br/></wicket:container>
<a href="FormPage.html">Form Example</a>: shows ajax form processing
<br/><br/>
<a href="GuestBook.html">Guest book Example</a>: shows how a simple commenting system can be turned into ajax extravaganza.
diff --git a/wicket-examples/src/main/java/org/apache/wicket/examples/ajax/builtin/Index.java b/wicket-examples/src/main/java/org/apache/wicket/examples/ajax/builtin/Index.java
index dae445ae1b..8ed24e86a5 100644
--- a/wicket-examples/src/main/java/org/apache/wicket/examples/ajax/builtin/Index.java
+++ b/wicket-examples/src/main/java/org/apache/wicket/examples/ajax/builtin/Index.java
@@ -16,12 +16,14 @@
*/
package org.apache.wicket.examples.ajax.builtin;
+import org.apache.wicket.examples.AjaxEngineSelector;
import org.apache.wicket.examples.WicketExamplePage;
import org.apache.wicket.examples.homepage.HomePage;
+import org.apache.wicket.markup.html.WebMarkupContainer;
/**
* Wicket ajax example index page
- *
+ *
* @author Igor Vaynberg (ivaynberg)
*/
public class Index extends BasePage
@@ -31,6 +33,11 @@ public class Index extends BasePage
*/
public Index()
{
+ // EffectsPage needs jQuery UI, which the plain JavaScript Ajax engine does not load
+ WebMarkupContainer effectsSection = new WebMarkupContainer("effectsSection");
+ effectsSection.setVisible(
+ AjaxEngineSelector.getEffectiveEngine() == AjaxEngineSelector.Engine.JQUERY);
+ add(effectsSection);
}
@Override
diff --git a/wicket-examples/src/main/java/org/apache/wicket/examples/authentication3/MyAuthenticatedWebApplication.java b/wicket-examples/src/main/java/org/apache/wicket/examples/authentication3/MyAuthenticatedWebApplication.java
index d01c1a1ace..5d73962348 100644
--- a/wicket-examples/src/main/java/org/apache/wicket/examples/authentication3/MyAuthenticatedWebApplication.java
+++ b/wicket-examples/src/main/java/org/apache/wicket/examples/authentication3/MyAuthenticatedWebApplication.java
@@ -20,6 +20,7 @@ import org.apache.wicket.Page;
import org.apache.wicket.authroles.authentication.AbstractAuthenticatedWebSession;
import org.apache.wicket.authroles.authentication.AuthenticatedWebApplication;
import org.apache.wicket.csp.CSPDirective;
+import org.apache.wicket.examples.AjaxEngineSelector;
import org.apache.wicket.markup.html.WebPage;
@@ -52,6 +53,9 @@ public class MyAuthenticatedWebApplication extends AuthenticatedWebApplication
protected void init()
{
super.init();
+
+ AjaxEngineSelector.configure(this);
+
getDebugSettings().setDevelopmentUtilitiesEnabled(true);
getCspSettings().blocking()
diff --git a/wicket-examples/src/main/java/org/apache/wicket/examples/customresourceloading/CustomResourceLoadingApplication.java b/wicket-examples/src/main/java/org/apache/wicket/examples/customresourceloading/CustomResourceLoadingApplication.java
index 65735e924d..26aa1c174b 100644
--- a/wicket-examples/src/main/java/org/apache/wicket/examples/customresourceloading/CustomResourceLoadingApplication.java
+++ b/wicket-examples/src/main/java/org/apache/wicket/examples/customresourceloading/CustomResourceLoadingApplication.java
@@ -24,7 +24,6 @@ import org.apache.wicket.WicketRuntimeException;
import org.apache.wicket.core.util.resource.UrlResourceStream;
import org.apache.wicket.core.util.resource.locator.IResourceStreamLocator;
import org.apache.wicket.core.util.resource.locator.ResourceStreamLocator;
-import org.apache.wicket.csp.CSPDirective;
import org.apache.wicket.examples.WicketExampleApplication;
import org.apache.wicket.util.resource.IResourceStream;
import org.apache.wicket.util.string.Strings;
diff --git a/wicket-examples/src/main/resources/org/apache/wicket/examples/style.css b/wicket-examples/src/main/resources/org/apache/wicket/examples/style.css
index 135092cc95..dfe197408e 100644
--- a/wicket-examples/src/main/resources/org/apache/wicket/examples/style.css
+++ b/wicket-examples/src/main/resources/org/apache/wicket/examples/style.css
@@ -687,6 +687,9 @@ button.button--alert {
display: inline-block;
width: 240px; }
+.ajax-engine {
+ float: right; }
+
.jumbotron.header {
background-color: #111;
background-image: url("background-2.jpg");
diff --git a/wicket-examples/src/main/webapp/jquery-ui-1.10.3.custom.js b/wicket-examples/src/main/webapp/jquery-ui-1.10.3.custom.js
deleted file mode 100644
index 15aa57cdf7..0000000000
--- a/wicket-examples/src/main/webapp/jquery-ui-1.10.3.custom.js
+++ /dev/null
@@ -1,2261 +0,0 @@
-/*! jQuery UI - v1.10.3 - 2013-08-02
-* http://jqueryui.com
-* Includes: jquery.ui.effect.js, jquery.ui.effect-blind.js, jquery.ui.effect-bounce.js, jquery.ui.effect-clip.js, jquery.ui.effect-drop.js, jquery.ui.effect-explode.js, jquery.ui.effect-fade.js, jquery.ui.effect-fold.js, jquery.ui.effect-highlight.js, jquery.ui.effect-pulsate.js, jquery.ui.effect-scale.js, jquery.ui.effect-shake.js, jquery.ui.effect-slide.js, jquery.ui.effect-transfer.js
-* Copyright 2013 jQuery Foundation and other contributors Licensed MIT */
-
-(function($, undefined) {
-
-var dataSpace = "ui-effects-";
-
-$.effects = {
- effect: {}
-};
-
-/*!
- * jQuery Color Animations v2.1.2
- * https://github.com/jquery/jquery-color
- *
- * Copyright 2013 jQuery Foundation and other contributors
- * Released under the MIT license.
- * http://jquery.org/license
- *
- * Date: Wed Jan 16 08:47:09 2013 -0600
- */
-(function( jQuery, undefined ) {
-
- var stepHooks = "backgroundColor borderBottomColor borderLeftColor borderRightColor borderTopColor color columnRuleColor outlineColor textDecorationColor textEmphasisColor",
-
- // plusequals test for += 100 -= 100
- rplusequals = /^([\-+])=\s*(\d+\.?\d*)/,
- // a set of RE's that can match strings and generate color tuples.
- stringParsers = [{
- re: /rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,
- parse: function( execResult ) {
- return [
- execResult[ 1 ],
- execResult[ 2 ],
- execResult[ 3 ],
- execResult[ 4 ]
- ];
- }
- }, {
- re: /rgba?\(\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,
- parse: function( execResult ) {
- return [
- execResult[ 1 ] * 2.55,
- execResult[ 2 ] * 2.55,
- execResult[ 3 ] * 2.55,
- execResult[ 4 ]
- ];
- }
- }, {
- // this regex ignores A-F because it's compared against an already lowercased string
- re: /#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})/,
- parse: function( execResult ) {
- return [
- parseInt( execResult[ 1 ], 16 ),
- parseInt( execResult[ 2 ], 16 ),
- parseInt( execResult[ 3 ], 16 )
- ];
- }
- }, {
- // this regex ignores A-F because it's compared against an already lowercased string
- re: /#([a-f0-9])([a-f0-9])([a-f0-9])/,
- parse: function( execResult ) {
- return [
- parseInt( execResult[ 1 ] + execResult[ 1 ], 16 ),
- parseInt( execResult[ 2 ] + execResult[ 2 ], 16 ),
- parseInt( execResult[ 3 ] + execResult[ 3 ], 16 )
- ];
- }
- }, {
- re: /hsla?\(\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,
- space: "hsla",
- parse: function( execResult ) {
- return [
- execResult[ 1 ],
- execResult[ 2 ] / 100,
- execResult[ 3 ] / 100,
- execResult[ 4 ]
- ];
- }
- }],
-
- // jQuery.Color( )
- color = jQuery.Color = function( color, green, blue, alpha ) {
- return new jQuery.Color.fn.parse( color, green, blue, alpha );
- },
- spaces = {
- rgba: {
- props: {
- red: {
- idx: 0,
- type: "byte"
- },
- green: {
- idx: 1,
- type: "byte"
- },
- blue: {
- idx: 2,
- type: "byte"
- }
- }
- },
-
- hsla: {
- props: {
- hue: {
- idx: 0,
- type: "degrees"
- },
- saturation: {
- idx: 1,
- type: "percent"
- },
- lightness: {
- idx: 2,
- type: "percent"
- }
- }
- }
- },
- propTypes = {
- "byte": {
- floor: true,
- max: 255
- },
- "percent": {
- max: 1
- },
- "degrees": {
- mod: 360,
- floor: true
- }
- },
- support = color.support = {},
-
- // element for support tests
- supportElem = jQuery( "<p>" )[ 0 ],
-
- // colors = jQuery.Color.names
- colors,
-
- // local aliases of functions called often
- each = jQuery.each;
-
-// determine rgba support immediately
-supportElem.style.cssText = "background-color:rgba(1,1,1,.5)";
-support.rgba = supportElem.style.backgroundColor.indexOf( "rgba" ) > -1;
-
-// define cache name and alpha properties
-// for rgba and hsla spaces
-each( spaces, function( spaceName, space ) {
- space.cache = "_" + spaceName;
- space.props.alpha = {
- idx: 3,
- type: "percent",
- def: 1
- };
-});
-
-function clamp( value, prop, allowEmpty ) {
- var type = propTypes[ prop.type ] || {};
-
- if ( value == null ) {
- return (allowEmpty || !prop.def) ? null : prop.def;
- }
-
- // ~~ is an short way of doing floor for positive numbers
- value = type.floor ? ~~value : parseFloat( value );
-
- // IE will pass in empty strings as value for alpha,
- // which will hit this case
- if ( isNaN( value ) ) {
- return prop.def;
- }
-
- if ( type.mod ) {
- // we add mod before modding to make sure that negatives values
- // get converted properly: -10 -> 350
- return (value + type.mod) % type.mod;
- }
-
- // for now all property types without mod have min and max
- return 0 > value ? 0 : type.max < value ? type.max : value;
-}
-
-function stringParse( string ) {
- var inst = color(),
- rgba = inst._rgba = [];
-
- string = string.toLowerCase();
-
- each( stringParsers, function( i, parser ) {
- var parsed,
- match = parser.re.exec( string ),
- values = match && parser.parse( match ),
- spaceName = parser.space || "rgba";
-
- if ( values ) {
- parsed = inst[ spaceName ]( values );
-
- // if this was an rgba parse the assignment might happen twice
- // oh well....
- inst[ spaces[ spaceName ].cache ] = parsed[ spaces[ spaceName ].cache ];
- rgba = inst._rgba = parsed._rgba;
-
- // exit each( stringParsers ) here because we matched
- return false;
- }
- });
-
- // Found a stringParser that handled it
- if ( rgba.length ) {
-
- // if this came from a parsed string, force "transparent" when alpha is 0
- // chrome, (and maybe others) return "transparent" as rgba(0,0,0,0)
- if ( rgba.join() === "0,0,0,0" ) {
- jQuery.extend( rgba, colors.transparent );
- }
- return inst;
- }
-
- // named colors
- return colors[ string ];
-}
-
-color.fn = jQuery.extend( color.prototype, {
- parse: function( red, green, blue, alpha ) {
- if ( red === undefined ) {
- this._rgba = [ null, null, null, null ];
- return this;
- }
- if ( red.jquery || red.nodeType ) {
- red = jQuery( red ).css( green );
- green = undefined;
- }
-
- var inst = this,
- type = jQuery.type( red ),
- rgba = this._rgba = [];
-
- // more than 1 argument specified - assume ( red, green, blue, alpha )
- if ( green !== undefined ) {
- red = [ red, green, blue, alpha ];
- type = "array";
- }
-
- if ( type === "string" ) {
- return this.parse( stringParse( red ) || colors._default );
- }
-
- if ( type === "array" ) {
- each( spaces.rgba.props, function( key, prop ) {
- rgba[ prop.idx ] = clamp( red[ prop.idx ], prop );
- });
- return this;
- }
-
- if ( type === "object" ) {
- if ( red instanceof color ) {
- each( spaces, function( spaceName, space ) {
- if ( red[ space.cache ] ) {
- inst[ space.cache ] = red[ space.cache ].slice();
- }
- });
- } else {
- each( spaces, function( spaceName, space ) {
- var cache = space.cache;
- each( space.props, function( key, prop ) {
-
- // if the cache doesn't exist, and we know how to convert
- if ( !inst[ cache ] && space.to ) {
-
- // if the value was null, we don't need to copy it
- // if the key was alpha, we don't need to copy it either
- if ( key === "alpha" || red[ key ] == null ) {
- return;
- }
- inst[ cache ] = space.to( inst._rgba );
- }
-
- // this is the only case where we allow nulls for ALL properties.
- // call clamp with alwaysAllowEmpty
- inst[ cache ][ prop.idx ] = clamp( red[ key ], prop, true );
- });
-
- // everything defined but alpha?
- if ( inst[ cache ] && jQuery.inArray( null, inst[ cache ].slice( 0, 3 ) ) < 0 ) {
- // use the default of 1
- inst[ cache ][ 3 ] = 1;
- if ( space.from ) {
- inst._rgba = space.from( inst[ cache ] );
- }
- }
- });
- }
- return this;
- }
- },
- is: function( compare ) {
- var is = color( compare ),
- same = true,
- inst = this;
-
- each( spaces, function( _, space ) {
- var localCache,
- isCache = is[ space.cache ];
- if (isCache) {
- localCache = inst[ space.cache ] || space.to && space.to( inst._rgba ) || [];
- each( space.props, function( _, prop ) {
- if ( isCache[ prop.idx ] != null ) {
- same = ( isCache[ prop.idx ] === localCache[ prop.idx ] );
- return same;
- }
- });
- }
- return same;
- });
- return same;
- },
- _space: function() {
- var used = [],
- inst = this;
- each( spaces, function( spaceName, space ) {
- if ( inst[ space.cache ] ) {
- used.push( spaceName );
- }
- });
- return used.pop();
- },
- transition: function( other, distance ) {
- var end = color( other ),
- spaceName = end._space(),
- space = spaces[ spaceName ],
- startColor = this.alpha() === 0 ? color( "transparent" ) : this,
- start = startColor[ space.cache ] || space.to( startColor._rgba ),
- result = start.slice();
-
- end = end[ space.cache ];
- each( space.props, function( key, prop ) {
- var index = prop.idx,
- startValue = start[ index ],
- endValue = end[ index ],
- type = propTypes[ prop.type ] || {};
-
- // if null, don't override start value
- if ( endValue === null ) {
- return;
- }
- // if null - use end
- if ( startValue === null ) {
- result[ index ] = endValue;
- } else {
- if ( type.mod ) {
- if ( endValue - startValue > type.mod / 2 ) {
- startValue += type.mod;
- } else if ( startValue - endValue > type.mod / 2 ) {
- startValue -= type.mod;
- }
- }
- result[ index ] = clamp( ( endValue - startValue ) * distance + startValue, prop );
- }
- });
- return this[ spaceName ]( result );
- },
- blend: function( opaque ) {
- // if we are already opaque - return ourself
- if ( this._rgba[ 3 ] === 1 ) {
- return this;
- }
-
- var rgb = this._rgba.slice(),
- a = rgb.pop(),
- blend = color( opaque )._rgba;
-
- return color( jQuery.map( rgb, function( v, i ) {
- return ( 1 - a ) * blend[ i ] + a * v;
- }));
- },
- toRgbaString: function() {
- var prefix = "rgba(",
- rgba = jQuery.map( this._rgba, function( v, i ) {
- return v == null ? ( i > 2 ? 1 : 0 ) : v;
- });
-
- if ( rgba[ 3 ] === 1 ) {
- rgba.pop();
- prefix = "rgb(";
- }
-
- return prefix + rgba.join() + ")";
- },
- toHslaString: function() {
- var prefix = "hsla(",
- hsla = jQuery.map( this.hsla(), function( v, i ) {
- if ( v == null ) {
- v = i > 2 ? 1 : 0;
- }
-
- // catch 1 and 2
- if ( i && i < 3 ) {
- v = Math.round( v * 100 ) + "%";
- }
- return v;
- });
-
- if ( hsla[ 3 ] === 1 ) {
- hsla.pop();
- prefix = "hsl(";
- }
- return prefix + hsla.join() + ")";
- },
- toHexString: function( includeAlpha ) {
- var rgba = this._rgba.slice(),
- alpha = rgba.pop();
-
- if ( includeAlpha ) {
- rgba.push( ~~( alpha * 255 ) );
- }
-
- return "#" + jQuery.map( rgba, function( v ) {
-
- // default to 0 when nulls exist
- v = ( v || 0 ).toString( 16 );
- return v.length === 1 ? "0" + v : v;
- }).join("");
- },
- toString: function() {
- return this._rgba[ 3 ] === 0 ? "transparent" : this.toRgbaString();
- }
-});
-color.fn.parse.prototype = color.fn;
-
-// hsla conversions adapted from:
-// https://code.google.com/p/maashaack/source/browse/packages/graphics/trunk/src/graphics/colors/HUE2RGB.as?r=5021
-
-function hue2rgb( p, q, h ) {
- h = ( h + 1 ) % 1;
- if ( h * 6 < 1 ) {
- return p + (q - p) * h * 6;
- }
- if ( h * 2 < 1) {
- return q;
- }
- if ( h * 3 < 2 ) {
- return p + (q - p) * ((2/3) - h) * 6;
- }
- return p;
-}
-
-spaces.hsla.to = function ( rgba ) {
- if ( rgba[ 0 ] == null || rgba[ 1 ] == null || rgba[ 2 ] == null ) {
- return [ null, null, null, rgba[ 3 ] ];
- }
- var r = rgba[ 0 ] / 255,
- g = rgba[ 1 ] / 255,
- b = rgba[ 2 ] / 255,
- a = rgba[ 3 ],
- max = Math.max( r, g, b ),
- min = Math.min( r, g, b ),
- diff = max - min,
- add = max + min,
- l = add * 0.5,
- h, s;
-
- if ( min === max ) {
- h = 0;
- } else if ( r === max ) {
- h = ( 60 * ( g - b ) / diff ) + 360;
- } else if ( g === max ) {
- h = ( 60 * ( b - r ) / diff ) + 120;
- } else {
- h = ( 60 * ( r - g ) / diff ) + 240;
- }
-
- // chroma (diff) == 0 means greyscale which, by definition, saturation = 0%
- // otherwise, saturation is based on the ratio of chroma (diff) to lightness (add)
- if ( diff === 0 ) {
- s = 0;
- } else if ( l <= 0.5 ) {
- s = diff / add;
- } else {
- s = diff / ( 2 - add );
- }
- return [ Math.round(h) % 360, s, l, a == null ? 1 : a ];
-};
-
-spaces.hsla.from = function ( hsla ) {
- if ( hsla[ 0 ] == null || hsla[ 1 ] == null || hsla[ 2 ] == null ) {
- return [ null, null, null, hsla[ 3 ] ];
- }
- var h = hsla[ 0 ] / 360,
- s = hsla[ 1 ],
- l = hsla[ 2 ],
- a = hsla[ 3 ],
- q = l <= 0.5 ? l * ( 1 + s ) : l + s - l * s,
- p = 2 * l - q;
-
- return [
- Math.round( hue2rgb( p, q, h + ( 1 / 3 ) ) * 255 ),
- Math.round( hue2rgb( p, q, h ) * 255 ),
- Math.round( hue2rgb( p, q, h - ( 1 / 3 ) ) * 255 ),
- a
- ];
-};
-
-
-each( spaces, function( spaceName, space ) {
- var props = space.props,
- cache = space.cache,
- to = space.to,
- from = space.from;
-
- // makes rgba() and hsla()
- color.fn[ spaceName ] = function( value ) {
-
- // generate a cache for this space if it doesn't exist
- if ( to && !this[ cache ] ) {
- this[ cache ] = to( this._rgba );
- }
- if ( value === undefined ) {
- return this[ cache ].slice();
- }
-
- var ret,
- type = jQuery.type( value ),
- arr = ( type === "array" || type === "object" ) ? value : arguments,
- local = this[ cache ].slice();
-
- each( props, function( key, prop ) {
- var val = arr[ type === "object" ? key : prop.idx ];
- if ( val == null ) {
- val = local[ prop.idx ];
- }
- local[ prop.idx ] = clamp( val, prop );
- });
-
- if ( from ) {
- ret = color( from( local ) );
- ret[ cache ] = local;
- return ret;
- } else {
- return color( local );
- }
- };
-
- // makes red() green() blue() alpha() hue() saturation() lightness()
- each( props, function( key, prop ) {
- // alpha is included in more than one space
- if ( color.fn[ key ] ) {
- return;
- }
- color.fn[ key ] = function( value ) {
- var vtype = jQuery.type( value ),
- fn = ( key === "alpha" ? ( this._hsla ? "hsla" : "rgba" ) : spaceName ),
- local = this[ fn ](),
- cur = local[ prop.idx ],
- match;
-
- if ( vtype === "undefined" ) {
- return cur;
- }
-
- if ( vtype === "function" ) {
- value = value.call( this, cur );
- vtype = jQuery.type( value );
- }
- if ( value == null && prop.empty ) {
- return this;
- }
- if ( vtype === "string" ) {
- match = rplusequals.exec( value );
- if ( match ) {
- value = cur + parseFloat( match[ 2 ] ) * ( match[ 1 ] === "+" ? 1 : -1 );
- }
- }
- local[ prop.idx ] = value;
- return this[ fn ]( local );
- };
- });
-});
-
-// add cssHook and .fx.step function for each named hook.
-// accept a space separated string of properties
-color.hook = function( hook ) {
- var hooks = hook.split( " " );
- each( hooks, function( i, hook ) {
- jQuery.cssHooks[ hook ] = {
- set: function( elem, value ) {
- var parsed, curElem,
- backgroundColor = "";
-
- if ( value !== "transparent" && ( jQuery.type( value ) !== "string" || ( parsed = stringParse( value ) ) ) ) {
- value = color( parsed || value );
- if ( !support.rgba && value._rgba[ 3 ] !== 1 ) {
- curElem = hook === "backgroundColor" ? elem.parentNode : elem;
- while (
- (backgroundColor === "" || backgroundColor === "transparent") &&
- curElem && curElem.style
- ) {
- try {
- backgroundColor = jQuery.css( curElem, "backgroundColor" );
- curElem = curElem.parentNode;
- } catch ( e ) {
- }
- }
-
- value = value.blend( backgroundColor && backgroundColor !== "transparent" ?
- backgroundColor :
- "_default" );
- }
-
- value = value.toRgbaString();
- }
- try {
- elem.style[ hook ] = value;
- } catch( e ) {
- // wrapped to prevent IE from throwing errors on "invalid" values like 'auto' or 'inherit'
- }
- }
- };
- jQuery.fx.step[ hook ] = function( fx ) {
- if ( !fx.colorInit ) {
- fx.start = color( fx.elem, hook );
- fx.end = color( fx.end );
- fx.colorInit = true;
- }
- jQuery.cssHooks[ hook ].set( fx.elem, fx.start.transition( fx.end, fx.pos ) );
- };
- });
-
-};
-
-color.hook( stepHooks );
-
-jQuery.cssHooks.borderColor = {
- expand: function( value ) {
- var expanded = {};
-
- each( [ "Top", "Right", "Bottom", "Left" ], function( i, part ) {
- expanded[ "border" + part + "Color" ] = value;
- });
- return expanded;
- }
-};
-
-// Basic color names only.
-// Usage of any of the other color names requires adding yourself or including
-// jquery.color.svg-names.js.
-colors = jQuery.Color.names = {
- // 4.1. Basic color keywords
- aqua: "#00ffff",
- black: "#000000",
- blue: "#0000ff",
- fuchsia: "#ff00ff",
- gray: "#808080",
- green: "#008000",
- lime: "#00ff00",
- maroon: "#800000",
- navy: "#000080",
- olive: "#808000",
- purple: "#800080",
- red: "#ff0000",
- silver: "#c0c0c0",
- teal: "#008080",
- white: "#ffffff",
- yellow: "#ffff00",
-
- // 4.2.3. "transparent" color keyword
- transparent: [ null, null, null, 0 ],
-
- _default: "#ffffff"
-};
-
-})( jQuery );
-
-
-/******************************************************************************/
-/****************************** CLASS ANIMATIONS ******************************/
-/******************************************************************************/
-(function() {
-
-var classAnimationActions = [ "add", "remove", "toggle" ],
- shorthandStyles = {
- border: 1,
- borderBottom: 1,
- borderColor: 1,
- borderLeft: 1,
- borderRight: 1,
- borderTop: 1,
- borderWidth: 1,
- margin: 1,
- padding: 1
- };
-
-$.each([ "borderLeftStyle", "borderRightStyle", "borderBottomStyle", "borderTopStyle" ], function( _, prop ) {
- $.fx.step[ prop ] = function( fx ) {
- if ( fx.end !== "none" && !fx.setAttr || fx.pos === 1 && !fx.setAttr ) {
- jQuery.style( fx.elem, prop, fx.end );
- fx.setAttr = true;
- }
- };
-});
-
-function getElementStyles( elem ) {
- var key, len,
- style = elem.ownerDocument.defaultView ?
- elem.ownerDocument.defaultView.getComputedStyle( elem, null ) :
- elem.currentStyle,
- styles = {};
-
- if ( style && style.length && style[ 0 ] && style[ style[ 0 ] ] ) {
- len = style.length;
- while ( len-- ) {
- key = style[ len ];
- if ( typeof style[ key ] === "string" ) {
- styles[ $.camelCase( key ) ] = style[ key ];
- }
- }
- // support: Opera, IE <9
- } else {
- for ( key in style ) {
- if ( typeof style[ key ] === "string" ) {
- styles[ key ] = style[ key ];
- }
- }
- }
-
- return styles;
-}
-
-
-function styleDifference( oldStyle, newStyle ) {
- var diff = {},
- name, value;
-
- for ( name in newStyle ) {
- value = newStyle[ name ];
- if ( oldStyle[ name ] !== value ) {
- if ( !shorthandStyles[ name ] ) {
- if ( $.fx.step[ name ] || !isNaN( parseFloat( value ) ) ) {
- diff[ name ] = value;
- }
- }
- }
- }
-
- return diff;
-}
-
-// support: jQuery <1.8
-if ( !$.fn.addBack ) {
- $.fn.addBack = function( selector ) {
- return this.add( selector == null ?
- this.prevObject : this.prevObject.filter( selector )
- );
- };
-}
-
-$.effects.animateClass = function( value, duration, easing, callback ) {
- var o = $.speed( duration, easing, callback );
-
- return this.queue( function() {
- var animated = $( this ),
- baseClass = animated.attr( "class" ) || "",
- applyClassChange,
- allAnimations = o.children ? animated.find( "*" ).addBack() : animated;
-
- // map the animated objects to store the original styles.
- allAnimations = allAnimations.map(function() {
- var el = $( this );
- return {
- el: el,
- start: getElementStyles( this )
- };
- });
-
- // apply class change
- applyClassChange = function() {
- $.each( classAnimationActions, function(i, action) {
- if ( value[ action ] ) {
- animated[ action + "Class" ]( value[ action ] );
- }
- });
- };
- applyClassChange();
-
- // map all animated objects again - calculate new styles and diff
- allAnimations = allAnimations.map(function() {
- this.end = getElementStyles( this.el[ 0 ] );
- this.diff = styleDifference( this.start, this.end );
- return this;
- });
-
- // apply original class
- animated.attr( "class", baseClass );
-
- // map all animated objects again - this time collecting a promise
- allAnimations = allAnimations.map(function() {
- var styleInfo = this,
- dfd = $.Deferred(),
- opts = $.extend({}, o, {
- queue: false,
- complete: function() {
- dfd.resolve( styleInfo );
- }
- });
-
- this.el.animate( this.diff, opts );
- return dfd.promise();
- });
-
- // once all animations have completed:
- $.when.apply( $, allAnimations.get() ).done(function() {
-
- // set the final class
- applyClassChange();
-
- // for each animated element,
- // clear all css properties that were animated
- $.each( arguments, function() {
- var el = this.el;
- $.each( this.diff, function(key) {
- el.css( key, "" );
- });
- });
-
- // this is guarnteed to be there if you use jQuery.speed()
- // it also handles dequeuing the next anim...
- o.complete.call( animated[ 0 ] );
- });
- });
-};
-
-$.fn.extend({
- addClass: (function( orig ) {
- return function( classNames, speed, easing, callback ) {
- return speed ?
- $.effects.animateClass.call( this,
- { add: classNames }, speed, easing, callback ) :
- orig.apply( this, arguments );
- };
- })( $.fn.addClass ),
-
- removeClass: (function( orig ) {
- return function( classNames, speed, easing, callback ) {
- return arguments.length > 1 ?
- $.effects.animateClass.call( this,
- { remove: classNames }, speed, easing, callback ) :
- orig.apply( this, arguments );
- };
- })( $.fn.removeClass ),
-
- toggleClass: (function( orig ) {
- return function( classNames, force, speed, easing, callback ) {
- if ( typeof force === "boolean" || force === undefined ) {
- if ( !speed ) {
- // without speed parameter
- return orig.apply( this, arguments );
- } else {
- return $.effects.animateClass.call( this,
- (force ? { add: classNames } : { remove: classNames }),
- speed, easing, callback );
- }
- } else {
- // without force parameter
- return $.effects.animateClass.call( this,
- { toggle: classNames }, force, speed, easing );
- }
- };
- })( $.fn.toggleClass ),
-
- switchClass: function( remove, add, speed, easing, callback) {
- return $.effects.animateClass.call( this, {
- add: add,
- remove: remove
- }, speed, easing, callback );
- }
-});
-
-})();
-
-/******************************************************************************/
-/*********************************** EFFECTS **********************************/
-/******************************************************************************/
-
-(function() {
-
-$.extend( $.effects, {
- version: "1.10.3",
-
- // Saves a set of properties in a data storage
- save: function( element, set ) {
- for( var i=0; i < set.length; i++ ) {
- if ( set[ i ] !== null ) {
- element.data( dataSpace + set[ i ], element[ 0 ].style[ set[ i ] ] );
- }
- }
- },
-
- // Restores a set of previously saved properties from a data storage
- restore: function( element, set ) {
- var val, i;
- for( i=0; i < set.length; i++ ) {
- if ( set[ i ] !== null ) {
- val = element.data( dataSpace + set[ i ] );
- // support: jQuery 1.6.2
- // http://bugs.jquery.com/ticket/9917
- // jQuery 1.6.2 incorrectly returns undefined for any falsy value.
- // We can't differentiate between "" and 0 here, so we just assume
- // empty string since it's likely to be a more common value...
- if ( val === undefined ) {
- val = "";
- }
- element.css( set[ i ], val );
- }
- }
- },
-
- setMode: function( el, mode ) {
- if (mode === "toggle") {
- mode = el.is( ":hidden" ) ? "show" : "hide";
- }
- return mode;
- },
-
- // Translates a [top,left] array into a baseline value
- // this should be a little more flexible in the future to handle a string & hash
- getBaseline: function( origin, original ) {
- var y, x;
- switch ( origin[ 0 ] ) {
- case "top": y = 0; break;
- case "middle": y = 0.5; break;
- case "bottom": y = 1; break;
- default: y = origin[ 0 ] / original.height;
- }
- switch ( origin[ 1 ] ) {
- case "left": x = 0; break;
- case "center": x = 0.5; break;
- case "right": x = 1; break;
- default: x = origin[ 1 ] / original.width;
- }
- return {
- x: x,
- y: y
- };
- },
-
- // Wraps the element around a wrapper that copies position properties
- createWrapper: function( element ) {
-
- // if the element is already wrapped, return it
- if ( element.parent().is( ".ui-effects-wrapper" )) {
- return element.parent();
- }
-
- // wrap the element
- var props = {
- width: element.outerWidth(true),
- height: element.outerHeight(true),
- "float": element.css( "float" )
- },
- wrapper = $( "<div></div>" )
- .addClass( "ui-effects-wrapper" )
- .css({
- fontSize: "100%",
- background: "transparent",
- border: "none",
- margin: 0,
- padding: 0
- }),
- // Store the size in case width/height are defined in % - Fixes #5245
- size = {
- width: element.width(),
- height: element.height()
- },
- active = document.activeElement;
-
- // support: Firefox
- // Firefox incorrectly exposes anonymous content
- // https://bugzilla.mozilla.org/show_bug.cgi?id=561664
- try {
- active.id;
- } catch( e ) {
- active = document.body;
- }
-
- element.wrap( wrapper );
-
- // Fixes #7595 - Elements lose focus when wrapped.
- if ( element[ 0 ] === active || $.contains( element[ 0 ], active ) ) {
- $( active ).focus();
- }
-
- wrapper = element.parent(); //Hotfix for jQuery 1.4 since some change in wrap() seems to actually lose the reference to the wrapped element
-
- // transfer positioning properties to the wrapper
- if ( element.css( "position" ) === "static" ) {
- wrapper.css({ position: "relative" });
- element.css({ position: "relative" });
- } else {
- $.extend( props, {
- position: element.css( "position" ),
- zIndex: element.css( "z-index" )
- });
- $.each([ "top", "left", "bottom", "right" ], function(i, pos) {
- props[ pos ] = element.css( pos );
- if ( isNaN( parseInt( props[ pos ], 10 ) ) ) {
- props[ pos ] = "auto";
- }
- });
- element.css({
- position: "relative",
- top: 0,
- left: 0,
- right: "auto",
- bottom: "auto"
- });
- }
- element.css(size);
-
- return wrapper.css( props ).show();
- },
-
- removeWrapper: function( element ) {
- var active = document.activeElement;
-
- if ( element.parent().is( ".ui-effects-wrapper" ) ) {
- element.parent().replaceWith( element );
-
- // Fixes #7595 - Elements lose focus when wrapped.
- if ( element[ 0 ] === active || $.contains( element[ 0 ], active ) ) {
- $( active ).focus();
- }
- }
-
-
- return element;
- },
-
- setTransition: function( element, list, factor, value ) {
- value = value || {};
- $.each( list, function( i, x ) {
- var unit = element.cssUnit( x );
- if ( unit[ 0 ] > 0 ) {
- value[ x ] = unit[ 0 ] * factor + unit[ 1 ];
- }
- });
- return value;
- }
-});
-
-// return an effect options object for the given parameters:
-function _normalizeArguments( effect, options, speed, callback ) {
-
- // allow passing all options as the first parameter
- if ( $.isPlainObject( effect ) ) {
- options = effect;
- effect = effect.effect;
- }
-
- // convert to an object
- effect = { effect: effect };
-
- // catch (effect, null, ...)
- if ( options == null ) {
- options = {};
- }
-
- // catch (effect, callback)
- if ( $.isFunction( options ) ) {
- callback = options;
- speed = null;
- options = {};
- }
-
- // catch (effect, speed, ?)
- if ( typeof options === "number" || $.fx.speeds[ options ] ) {
- callback = speed;
- speed = options;
- options = {};
- }
-
- // catch (effect, options, callback)
- if ( $.isFunction( speed ) ) {
- callback = speed;
- speed = null;
- }
-
- // add options to effect
- if ( options ) {
- $.extend( effect, options );
- }
-
- speed = speed || options.duration;
- effect.duration = $.fx.off ? 0 :
- typeof speed === "number" ? speed :
- speed in $.fx.speeds ? $.fx.speeds[ speed ] :
- $.fx.speeds._default;
-
- effect.complete = callback || options.complete;
-
- return effect;
-}
-
-function standardAnimationOption( option ) {
- // Valid standard speeds (nothing, number, named speed)
- if ( !option || typeof option === "number" || $.fx.speeds[ option ] ) {
- return true;
- }
-
- // Invalid strings - treat as "normal" speed
- if ( typeof option === "string" && !$.effects.effect[ option ] ) {
- return true;
- }
-
- // Complete callback
- if ( $.isFunction( option ) ) {
- return true;
- }
-
- // Options hash (but not naming an effect)
- if ( typeof option === "object" && !option.effect ) {
- return true;
- }
-
- // Didn't match any standard API
- return false;
-}
-
-$.fn.extend({
- effect: function( /* effect, options, speed, callback */ ) {
- var args = _normalizeArguments.apply( this, arguments ),
- mode = args.mode,
- queue = args.queue,
- effectMethod = $.effects.effect[ args.effect ];
-
- if ( $.fx.off || !effectMethod ) {
- // delegate to the original method (e.g., .show()) if possible
- if ( mode ) {
- return this[ mode ]( args.duration, args.complete );
- } else {
- return this.each( function() {
- if ( args.complete ) {
- args.complete.call( this );
- }
- });
- }
- }
-
- function run( next ) {
- var elem = $( this ),
- complete = args.complete,
- mode = args.mode;
-
- function done() {
- if ( $.isFunction( complete ) ) {
- complete.call( elem[0] );
- }
- if ( $.isFunction( next ) ) {
- next();
- }
- }
-
- // If the element already has the correct final state, delegate to
- // the core methods so the internal tracking of "olddisplay" works.
- if ( elem.is( ":hidden" ) ? mode === "hide" : mode === "show" ) {
- elem[ mode ]();
- done();
- } else {
- effectMethod.call( elem[0], args, done );
- }
- }
-
- return queue === false ? this.each( run ) : this.queue( queue || "fx", run );
- },
-
- show: (function( orig ) {
- return function( option ) {
- if ( standardAnimationOption( option ) ) {
- return orig.apply( this, arguments );
- } else {
- var args = _normalizeArguments.apply( this, arguments );
- args.mode = "show";
- return this.effect.call( this, args );
- }
- };
- })( $.fn.show ),
-
- hide: (function( orig ) {
- return function( option ) {
- if ( standardAnimationOption( option ) ) {
- return orig.apply( this, arguments );
- } else {
- var args = _normalizeArguments.apply( this, arguments );
- args.mode = "hide";
- return this.effect.call( this, args );
- }
- };
- })( $.fn.hide ),
-
- toggle: (function( orig ) {
- return function( option ) {
- if ( standardAnimationOption( option ) || typeof option === "boolean" ) {
- return orig.apply( this, arguments );
- } else {
- var args = _normalizeArguments.apply( this, arguments );
- args.mode = "toggle";
- return this.effect.call( this, args );
- }
- };
- })( $.fn.toggle ),
-
- // helper functions
- cssUnit: function(key) {
- var style = this.css( key ),
- val = [];
-
- $.each( [ "em", "px", "%", "pt" ], function( i, unit ) {
- if ( style.indexOf( unit ) > 0 ) {
- val = [ parseFloat( style ), unit ];
- }
- });
- return val;
- }
-});
-
-})();
-
-/******************************************************************************/
-/*********************************** EASING ***********************************/
-/******************************************************************************/
-
-(function() {
-
-// based on easing equations from Robert Penner (http://www.robertpenner.com/easing)
-
-var baseEasings = {};
-
-$.each( [ "Quad", "Cubic", "Quart", "Quint", "Expo" ], function( i, name ) {
- baseEasings[ name ] = function( p ) {
- return Math.pow( p, i + 2 );
- };
-});
-
-$.extend( baseEasings, {
- Sine: function ( p ) {
- return 1 - Math.cos( p * Math.PI / 2 );
- },
- Circ: function ( p ) {
- return 1 - Math.sqrt( 1 - p * p );
- },
- Elastic: function( p ) {
- return p === 0 || p === 1 ? p :
- -Math.pow( 2, 8 * (p - 1) ) * Math.sin( ( (p - 1) * 80 - 7.5 ) * Math.PI / 15 );
- },
- Back: function( p ) {
- return p * p * ( 3 * p - 2 );
- },
- Bounce: function ( p ) {
- var pow2,
- bounce = 4;
-
- while ( p < ( ( pow2 = Math.pow( 2, --bounce ) ) - 1 ) / 11 ) {}
- return 1 / Math.pow( 4, 3 - bounce ) - 7.5625 * Math.pow( ( pow2 * 3 - 2 ) / 22 - p, 2 );
- }
-});
-
-$.each( baseEasings, function( name, easeIn ) {
- $.easing[ "easeIn" + name ] = easeIn;
- $.easing[ "easeOut" + name ] = function( p ) {
- return 1 - easeIn( 1 - p );
- };
- $.easing[ "easeInOut" + name ] = function( p ) {
- return p < 0.5 ?
- easeIn( p * 2 ) / 2 :
- 1 - easeIn( p * -2 + 2 ) / 2;
- };
-});
-
-})();
-
-})(jQuery);
-(function( $, undefined ) {
-
-var rvertical = /up|down|vertical/,
- rpositivemotion = /up|left|vertical|horizontal/;
-
-$.effects.effect.blind = function( o, done ) {
- // Create element
- var el = $( this ),
- props = [ "position", "top", "bottom", "left", "right", "height", "width" ],
- mode = $.effects.setMode( el, o.mode || "hide" ),
- direction = o.direction || "up",
- vertical = rvertical.test( direction ),
- ref = vertical ? "height" : "width",
- ref2 = vertical ? "top" : "left",
- motion = rpositivemotion.test( direction ),
- animation = {},
- show = mode === "show",
- wrapper, distance, margin;
-
- // if already wrapped, the wrapper's properties are my property. #6245
- if ( el.parent().is( ".ui-effects-wrapper" ) ) {
- $.effects.save( el.parent(), props );
- } else {
- $.effects.save( el, props );
- }
- el.show();
- wrapper = $.effects.createWrapper( el ).css({
- overflow: "hidden"
- });
-
- distance = wrapper[ ref ]();
- margin = parseFloat( wrapper.css( ref2 ) ) || 0;
-
- animation[ ref ] = show ? distance : 0;
- if ( !motion ) {
- el
- .css( vertical ? "bottom" : "right", 0 )
- .css( vertical ? "top" : "left", "auto" )
- .css({ position: "absolute" });
-
- animation[ ref2 ] = show ? margin : distance + margin;
- }
-
- // start at 0 if we are showing
- if ( show ) {
- wrapper.css( ref, 0 );
- if ( ! motion ) {
- wrapper.css( ref2, margin + distance );
- }
- }
-
- // Animate
- wrapper.animate( animation, {
- duration: o.duration,
- easing: o.easing,
- queue: false,
- complete: function() {
- if ( mode === "hide" ) {
- el.hide();
- }
- $.effects.restore( el, props );
- $.effects.removeWrapper( el );
- done();
- }
- });
-
-};
-
-})(jQuery);
-(function( $, undefined ) {
-
-$.effects.effect.bounce = function( o, done ) {
- var el = $( this ),
- props = [ "position", "top", "bottom", "left", "right", "height", "width" ],
-
- // defaults:
- mode = $.effects.setMode( el, o.mode || "effect" ),
- hide = mode === "hide",
- show = mode === "show",
- direction = o.direction || "up",
- distance = o.distance,
- times = o.times || 5,
-
- // number of internal animations
- anims = times * 2 + ( show || hide ? 1 : 0 ),
- speed = o.duration / anims,
- easing = o.easing,
-
- // utility:
- ref = ( direction === "up" || direction === "down" ) ? "top" : "left",
- motion = ( direction === "up" || direction === "left" ),
- i,
- upAnim,
- downAnim,
-
- // we will need to re-assemble the queue to stack our animations in place
- queue = el.queue(),
- queuelen = queue.length;
-
- // Avoid touching opacity to prevent clearType and PNG issues in IE
- if ( show || hide ) {
- props.push( "opacity" );
- }
-
- $.effects.save( el, props );
- el.show();
- $.effects.createWrapper( el ); // Create Wrapper
-
- // default distance for the BIGGEST bounce is the outer Distance / 3
- if ( !distance ) {
- distance = el[ ref === "top" ? "outerHeight" : "outerWidth" ]() / 3;
- }
-
- if ( show ) {
- downAnim = { opacity: 1 };
- downAnim[ ref ] = 0;
-
- // if we are showing, force opacity 0 and set the initial position
- // then do the "first" animation
- el.css( "opacity", 0 )
- .css( ref, motion ? -distance * 2 : distance * 2 )
- .animate( downAnim, speed, easing );
- }
-
- // start at the smallest distance if we are hiding
- if ( hide ) {
- distance = distance / Math.pow( 2, times - 1 );
- }
-
- downAnim = {};
- downAnim[ ref ] = 0;
- // Bounces up/down/left/right then back to 0 -- times * 2 animations happen here
- for ( i = 0; i < times; i++ ) {
- upAnim = {};
- upAnim[ ref ] = ( motion ? "-=" : "+=" ) + distance;
-
- el.animate( upAnim, speed, easing )
- .animate( downAnim, speed, easing );
-
- distance = hide ? distance * 2 : distance / 2;
- }
-
- // Last Bounce when Hiding
- if ( hide ) {
- upAnim = { opacity: 0 };
- upAnim[ ref ] = ( motion ? "-=" : "+=" ) + distance;
-
- el.animate( upAnim, speed, easing );
- }
-
- el.queue(function() {
- if ( hide ) {
- el.hide();
- }
- $.effects.restore( el, props );
- $.effects.removeWrapper( el );
- done();
- });
-
- // inject all the animations we just queued to be first in line (after "inprogress")
- if ( queuelen > 1) {
- queue.splice.apply( queue,
- [ 1, 0 ].concat( queue.splice( queuelen, anims + 1 ) ) );
- }
- el.dequeue();
-
-};
-
-})(jQuery);
-(function( $, undefined ) {
-
-$.effects.effect.clip = function( o, done ) {
- // Create element
- var el = $( this ),
- props = [ "position", "top", "bottom", "left", "right", "height", "width" ],
- mode = $.effects.setMode( el, o.mode || "hide" ),
- show = mode === "show",
- direction = o.direction || "vertical",
- vert = direction === "vertical",
- size = vert ? "height" : "width",
- position = vert ? "top" : "left",
- animation = {},
- wrapper, animate, distance;
-
- // Save & Show
- $.effects.save( el, props );
- el.show();
-
- // Create Wrapper
- wrapper = $.effects.createWrapper( el ).css({
- overflow: "hidden"
- });
- animate = ( el[0].tagName === "IMG" ) ? wrapper : el;
- distance = animate[ size ]();
-
- // Shift
- if ( show ) {
- animate.css( size, 0 );
- animate.css( position, distance / 2 );
- }
-
- // Create Animation Object:
- animation[ size ] = show ? distance : 0;
- animation[ position ] = show ? 0 : distance / 2;
-
- // Animate
- animate.animate( animation, {
- queue: false,
- duration: o.duration,
- easing: o.easing,
- complete: function() {
- if ( !show ) {
- el.hide();
- }
- $.effects.restore( el, props );
- $.effects.removeWrapper( el );
- done();
- }
- });
-
-};
-
-})(jQuery);
-(function( $, undefined ) {
-
-$.effects.effect.drop = function( o, done ) {
-
- var el = $( this ),
- props = [ "position", "top", "bottom", "left", "right", "opacity", "height", "width" ],
- mode = $.effects.setMode( el, o.mode || "hide" ),
- show = mode === "show",
- direction = o.direction || "left",
- ref = ( direction === "up" || direction === "down" ) ? "top" : "left",
- motion = ( direction === "up" || direction === "left" ) ? "pos" : "neg",
- animation = {
- opacity: show ? 1 : 0
- },
- distance;
-
- // Adjust
- $.effects.save( el, props );
- el.show();
- $.effects.createWrapper( el );
-
- distance = o.distance || el[ ref === "top" ? "outerHeight": "outerWidth" ]( true ) / 2;
-
- if ( show ) {
- el
- .css( "opacity", 0 )
- .css( ref, motion === "pos" ? -distance : distance );
- }
-
- // Animation
- animation[ ref ] = ( show ?
- ( motion === "pos" ? "+=" : "-=" ) :
- ( motion === "pos" ? "-=" : "+=" ) ) +
- distance;
-
- // Animate
- el.animate( animation, {
- queue: false,
- duration: o.duration,
- easing: o.easing,
- complete: function() {
- if ( mode === "hide" ) {
- el.hide();
- }
- $.effects.restore( el, props );
- $.effects.removeWrapper( el );
- done();
- }
- });
-};
-
-})(jQuery);
-(function( $, undefined ) {
-
-$.effects.effect.explode = function( o, done ) {
-
- var rows = o.pieces ? Math.round( Math.sqrt( o.pieces ) ) : 3,
- cells = rows,
- el = $( this ),
- mode = $.effects.setMode( el, o.mode || "hide" ),
- show = mode === "show",
-
- // show and then visibility:hidden the element before calculating offset
- offset = el.show().css( "visibility", "hidden" ).offset(),
-
- // width and height of a piece
- width = Math.ceil( el.outerWidth() / cells ),
- height = Math.ceil( el.outerHeight() / rows ),
- pieces = [],
-
- // loop
- i, j, left, top, mx, my;
-
- // children animate complete:
- function childComplete() {
- pieces.push( this );
- if ( pieces.length === rows * cells ) {
- animComplete();
- }
- }
-
- // clone the element for each row and cell.
- for( i = 0; i < rows ; i++ ) { // ===>
- top = offset.top + i * height;
- my = i - ( rows - 1 ) / 2 ;
-
- for( j = 0; j < cells ; j++ ) { // |||
- left = offset.left + j * width;
- mx = j - ( cells - 1 ) / 2 ;
-
- // Create a clone of the now hidden main element that will be absolute positioned
- // within a wrapper div off the -left and -top equal to size of our pieces
- el
- .clone()
- .appendTo( "body" )
- .wrap( "<div></div>" )
- .css({
- position: "absolute",
- visibility: "visible",
- left: -j * width,
- top: -i * height
- })
-
- // select the wrapper - make it overflow: hidden and absolute positioned based on
- // where the original was located +left and +top equal to the size of pieces
- .parent()
- .addClass( "ui-effects-explode" )
- .css({
- position: "absolute",
- overflow: "hidden",
- width: width,
- height: height,
- left: left + ( show ? mx * width : 0 ),
- top: top + ( show ? my * height : 0 ),
- opacity: show ? 0 : 1
- }).animate({
- left: left + ( show ? 0 : mx * width ),
- top: top + ( show ? 0 : my * height ),
- opacity: show ? 1 : 0
- }, o.duration || 500, o.easing, childComplete );
- }
- }
-
- function animComplete() {
- el.css({
- visibility: "visible"
- });
- $( pieces ).remove();
- if ( !show ) {
- el.hide();
- }
- done();
- }
-};
-
-})(jQuery);
-(function( $, undefined ) {
-
-$.effects.effect.fade = function( o, done ) {
- var el = $( this ),
- mode = $.effects.setMode( el, o.mode || "toggle" );
-
- el.animate({
- opacity: mode
- }, {
- queue: false,
- duration: o.duration,
- easing: o.easing,
- complete: done
- });
-};
-
-})( jQuery );
-(function( $, undefined ) {
-
-$.effects.effect.fold = function( o, done ) {
-
- // Create element
- var el = $( this ),
- props = [ "position", "top", "bottom", "left", "right", "height", "width" ],
- mode = $.effects.setMode( el, o.mode || "hide" ),
- show = mode === "show",
- hide = mode === "hide",
- size = o.size || 15,
- percent = /([0-9]+)%/.exec( size ),
- horizFirst = !!o.horizFirst,
- widthFirst = show !== horizFirst,
- ref = widthFirst ? [ "width", "height" ] : [ "height", "width" ],
- duration = o.duration / 2,
- wrapper, distance,
- animation1 = {},
- animation2 = {};
-
- $.effects.save( el, props );
- el.show();
-
- // Create Wrapper
- wrapper = $.effects.createWrapper( el ).css({
- overflow: "hidden"
- });
- distance = widthFirst ?
- [ wrapper.width(), wrapper.height() ] :
- [ wrapper.height(), wrapper.width() ];
-
- if ( percent ) {
- size = parseInt( percent[ 1 ], 10 ) / 100 * distance[ hide ? 0 : 1 ];
- }
- if ( show ) {
- wrapper.css( horizFirst ? {
- height: 0,
- width: size
- } : {
- height: size,
- width: 0
- });
- }
-
- // Animation
- animation1[ ref[ 0 ] ] = show ? distance[ 0 ] : size;
- animation2[ ref[ 1 ] ] = show ? distance[ 1 ] : 0;
-
- // Animate
- wrapper
- .animate( animation1, duration, o.easing )
- .animate( animation2, duration, o.easing, function() {
- if ( hide ) {
- el.hide();
- }
- $.effects.restore( el, props );
- $.effects.removeWrapper( el );
- done();
- });
-
-};
-
-})(jQuery);
-(function( $, undefined ) {
-
-$.effects.effect.highlight = function( o, done ) {
- var elem = $( this ),
- props = [ "backgroundImage", "backgroundColor", "opacity" ],
- mode = $.effects.setMode( elem, o.mode || "show" ),
- animation = {
- backgroundColor: elem.css( "backgroundColor" )
- };
-
- if (mode === "hide") {
- animation.opacity = 0;
- }
-
- $.effects.save( elem, props );
-
- elem
- .show()
- .css({
- backgroundImage: "none",
- backgroundColor: o.color || "#ffff99"
- })
- .animate( animation, {
- queue: false,
- duration: o.duration,
- easing: o.easing,
- complete: function() {
- if ( mode === "hide" ) {
- elem.hide();
- }
- $.effects.restore( elem, props );
- done();
- }
- });
-};
-
-})(jQuery);
-(function( $, undefined ) {
-
-$.effects.effect.pulsate = function( o, done ) {
- var elem = $( this ),
- mode = $.effects.setMode( elem, o.mode || "show" ),
- show = mode === "show",
- hide = mode === "hide",
- showhide = ( show || mode === "hide" ),
-
- // showing or hiding leaves of the "last" animation
- anims = ( ( o.times || 5 ) * 2 ) + ( showhide ? 1 : 0 ),
- duration = o.duration / anims,
- animateTo = 0,
- queue = elem.queue(),
- queuelen = queue.length,
- i;
-
- if ( show || !elem.is(":visible")) {
- elem.css( "opacity", 0 ).show();
- animateTo = 1;
- }
-
- // anims - 1 opacity "toggles"
- for ( i = 1; i < anims; i++ ) {
- elem.animate({
- opacity: animateTo
- }, duration, o.easing );
- animateTo = 1 - animateTo;
- }
-
- elem.animate({
- opacity: animateTo
- }, duration, o.easing);
-
- elem.queue(function() {
- if ( hide ) {
- elem.hide();
- }
- done();
- });
-
- // We just queued up "anims" animations, we need to put them next in the queue
- if ( queuelen > 1 ) {
- queue.splice.apply( queue,
- [ 1, 0 ].concat( queue.splice( queuelen, anims + 1 ) ) );
- }
- elem.dequeue();
-};
-
-})(jQuery);
-(function( $, undefined ) {
-
-$.effects.effect.puff = function( o, done ) {
- var elem = $( this ),
- mode = $.effects.setMode( elem, o.mode || "hide" ),
- hide = mode === "hide",
- percent = parseInt( o.percent, 10 ) || 150,
- factor = percent / 100,
- original = {
- height: elem.height(),
- width: elem.width(),
- outerHeight: elem.outerHeight(),
- outerWidth: elem.outerWidth()
- };
-
- $.extend( o, {
- effect: "scale",
- queue: false,
- fade: true,
- mode: mode,
- complete: done,
- percent: hide ? percent : 100,
- from: hide ?
- original :
- {
- height: original.height * factor,
- width: original.width * factor,
- outerHeight: original.outerHeight * factor,
- outerWidth: original.outerWidth * factor
- }
- });
-
- elem.effect( o );
-};
-
-$.effects.effect.scale = function( o, done ) {
-
- // Create element
- var el = $( this ),
- options = $.extend( true, {}, o ),
- mode = $.effects.setMode( el, o.mode || "effect" ),
- percent = parseInt( o.percent, 10 ) ||
- ( parseInt( o.percent, 10 ) === 0 ? 0 : ( mode === "hide" ? 0 : 100 ) ),
- direction = o.direction || "both",
- origin = o.origin,
- original = {
- height: el.height(),
- width: el.width(),
- outerHeight: el.outerHeight(),
- outerWidth: el.outerWidth()
- },
- factor = {
- y: direction !== "horizontal" ? (percent / 100) : 1,
- x: direction !== "vertical" ? (percent / 100) : 1
- };
-
- // We are going to pass this effect to the size effect:
- options.effect = "size";
- options.queue = false;
- options.complete = done;
-
- // Set default origin and restore for show/hide
- if ( mode !== "effect" ) {
- options.origin = origin || ["middle","center"];
- options.restore = true;
- }
-
- options.from = o.from || ( mode === "show" ? {
- height: 0,
- width: 0,
- outerHeight: 0,
- outerWidth: 0
- } : original );
- options.to = {
- height: original.height * factor.y,
- width: original.width * factor.x,
- outerHeight: original.outerHeight * factor.y,
- outerWidth: original.outerWidth * factor.x
- };
-
- // Fade option to support puff
- if ( options.fade ) {
- if ( mode === "show" ) {
- options.from.opacity = 0;
- options.to.opacity = 1;
- }
- if ( mode === "hide" ) {
- options.from.opacity = 1;
- options.to.opacity = 0;
- }
- }
-
- // Animate
- el.effect( options );
-
-};
-
-$.effects.effect.size = function( o, done ) {
-
- // Create element
- var original, baseline, factor,
- el = $( this ),
- props0 = [ "position", "top", "bottom", "left", "right", "width", "height", "overflow", "opacity" ],
-
- // Always restore
- props1 = [ "position", "top", "bottom", "left", "right", "overflow", "opacity" ],
-
- // Copy for children
- props2 = [ "width", "height", "overflow" ],
- cProps = [ "fontSize" ],
- vProps = [ "borderTopWidth", "borderBottomWidth", "paddingTop", "paddingBottom" ],
- hProps = [ "borderLeftWidth", "borderRightWidth", "paddingLeft", "paddingRight" ],
-
- // Set options
- mode = $.effects.setMode( el, o.mode || "effect" ),
- restore = o.restore || mode !== "effect",
- scale = o.scale || "both",
- origin = o.origin || [ "middle", "center" ],
- position = el.css( "position" ),
- props = restore ? props0 : props1,
- zero = {
- height: 0,
- width: 0,
- outerHeight: 0,
- outerWidth: 0
- };
-
- if ( mode === "show" ) {
- el.show();
- }
- original = {
- height: el.height(),
- width: el.width(),
- outerHeight: el.outerHeight(),
- outerWidth: el.outerWidth()
- };
-
- if ( o.mode === "toggle" && mode === "show" ) {
- el.from = o.to || zero;
- el.to = o.from || original;
- } else {
- el.from = o.from || ( mode === "show" ? zero : original );
- el.to = o.to || ( mode === "hide" ? zero : original );
- }
-
- // Set scaling factor
- factor = {
- from: {
- y: el.from.height / original.height,
- x: el.from.width / original.width
- },
- to: {
- y: el.to.height / original.height,
- x: el.to.width / original.width
- }
- };
-
- // Scale the css box
- if ( scale === "box" || scale === "both" ) {
-
- // Vertical props scaling
- if ( factor.from.y !== factor.to.y ) {
- props = props.concat( vProps );
- el.from = $.effects.setTransition( el, vProps, factor.from.y, el.from );
- el.to = $.effects.setTransition( el, vProps, factor.to.y, el.to );
- }
-
- // Horizontal props scaling
- if ( factor.from.x !== factor.to.x ) {
- props = props.concat( hProps );
- el.from = $.effects.setTransition( el, hProps, factor.from.x, el.from );
- el.to = $.effects.setTransition( el, hProps, factor.to.x, el.to );
- }
- }
-
- // Scale the content
- if ( scale === "content" || scale === "both" ) {
-
- // Vertical props scaling
- if ( factor.from.y !== factor.to.y ) {
- props = props.concat( cProps ).concat( props2 );
- el.from = $.effects.setTransition( el, cProps, factor.from.y, el.from );
- el.to = $.effects.setTransition( el, cProps, factor.to.y, el.to );
- }
- }
-
- $.effects.save( el, props );
- el.show();
- $.effects.createWrapper( el );
- el.css( "overflow", "hidden" ).css( el.from );
-
- // Adjust
- if (origin) { // Calculate baseline shifts
- baseline = $.effects.getBaseline( origin, original );
- el.from.top = ( original.outerHeight - el.outerHeight() ) * baseline.y;
- el.from.left = ( original.outerWidth - el.outerWidth() ) * baseline.x;
- el.to.top = ( original.outerHeight - el.to.outerHeight ) * baseline.y;
- el.to.left = ( original.outerWidth - el.to.outerWidth ) * baseline.x;
- }
- el.css( el.from ); // set top & left
-
- // Animate
- if ( scale === "content" || scale === "both" ) { // Scale the children
-
- // Add margins/font-size
- vProps = vProps.concat([ "marginTop", "marginBottom" ]).concat(cProps);
- hProps = hProps.concat([ "marginLeft", "marginRight" ]);
- props2 = props0.concat(vProps).concat(hProps);
-
- el.find( "*[width]" ).each( function(){
- var child = $( this ),
- c_original = {
- height: child.height(),
- width: child.width(),
- outerHeight: child.outerHeight(),
- outerWidth: child.outerWidth()
- };
- if (restore) {
- $.effects.save(child, props2);
- }
-
- child.from = {
- height: c_original.height * factor.from.y,
- width: c_original.width * factor.from.x,
- outerHeight: c_original.outerHeight * factor.from.y,
- outerWidth: c_original.outerWidth * factor.from.x
- };
- child.to = {
- height: c_original.height * factor.to.y,
- width: c_original.width * factor.to.x,
- outerHeight: c_original.height * factor.to.y,
- outerWidth: c_original.width * factor.to.x
- };
-
- // Vertical props scaling
- if ( factor.from.y !== factor.to.y ) {
- child.from = $.effects.setTransition( child, vProps, factor.from.y, child.from );
- child.to = $.effects.setTransition( child, vProps, factor.to.y, child.to );
- }
-
- // Horizontal props scaling
- if ( factor.from.x !== factor.to.x ) {
- child.from = $.effects.setTransition( child, hProps, factor.from.x, child.from );
- child.to = $.effects.setTransition( child, hProps, factor.to.x, child.to );
- }
-
- // Animate children
- child.css( child.from );
- child.animate( child.to, o.duration, o.easing, function() {
-
- // Restore children
- if ( restore ) {
- $.effects.restore( child, props2 );
- }
- });
- });
- }
-
- // Animate
- el.animate( el.to, {
- queue: false,
- duration: o.duration,
- easing: o.easing,
- complete: function() {
- if ( el.to.opacity === 0 ) {
- el.css( "opacity", el.from.opacity );
- }
- if( mode === "hide" ) {
- el.hide();
- }
- $.effects.restore( el, props );
- if ( !restore ) {
-
- // we need to calculate our new positioning based on the scaling
- if ( position === "static" ) {
- el.css({
- position: "relative",
- top: el.to.top,
- left: el.to.left
- });
- } else {
- $.each([ "top", "left" ], function( idx, pos ) {
- el.css( pos, function( _, str ) {
- var val = parseInt( str, 10 ),
- toRef = idx ? el.to.left : el.to.top;
-
- // if original was "auto", recalculate the new value from wrapper
- if ( str === "auto" ) {
- return toRef + "px";
- }
-
- return val + toRef + "px";
- });
- });
- }
- }
-
- $.effects.removeWrapper( el );
- done();
- }
- });
-
-};
-
-})(jQuery);
-(function( $, undefined ) {
-
-$.effects.effect.shake = function( o, done ) {
-
- var el = $( this ),
- props = [ "position", "top", "bottom", "left", "right", "height", "width" ],
- mode = $.effects.setMode( el, o.mode || "effect" ),
- direction = o.direction || "left",
- distance = o.distance || 20,
- times = o.times || 3,
- anims = times * 2 + 1,
- speed = Math.round(o.duration/anims),
- ref = (direction === "up" || direction === "down") ? "top" : "left",
- positiveMotion = (direction === "up" || direction === "left"),
- animation = {},
- animation1 = {},
- animation2 = {},
- i,
-
- // we will need to re-assemble the queue to stack our animations in place
- queue = el.queue(),
- queuelen = queue.length;
-
- $.effects.save( el, props );
- el.show();
- $.effects.createWrapper( el );
-
- // Animation
- animation[ ref ] = ( positiveMotion ? "-=" : "+=" ) + distance;
- animation1[ ref ] = ( positiveMotion ? "+=" : "-=" ) + distance * 2;
- animation2[ ref ] = ( positiveMotion ? "-=" : "+=" ) + distance * 2;
-
- // Animate
- el.animate( animation, speed, o.easing );
-
- // Shakes
- for ( i = 1; i < times; i++ ) {
- el.animate( animation1, speed, o.easing ).animate( animation2, speed, o.easing );
- }
- el
- .animate( animation1, speed, o.easing )
- .animate( animation, speed / 2, o.easing )
- .queue(function() {
- if ( mode === "hide" ) {
- el.hide();
- }
- $.effects.restore( el, props );
- $.effects.removeWrapper( el );
- done();
- });
-
- // inject all the animations we just queued to be first in line (after "inprogress")
- if ( queuelen > 1) {
- queue.splice.apply( queue,
- [ 1, 0 ].concat( queue.splice( queuelen, anims + 1 ) ) );
- }
- el.dequeue();
-
-};
-
-})(jQuery);
-(function( $, undefined ) {
-
-$.effects.effect.slide = function( o, done ) {
-
- // Create element
- var el = $( this ),
- props = [ "position", "top", "bottom", "left", "right", "width", "height" ],
- mode = $.effects.setMode( el, o.mode || "show" ),
- show = mode === "show",
- direction = o.direction || "left",
- ref = (direction === "up" || direction === "down") ? "top" : "left",
- positiveMotion = (direction === "up" || direction === "left"),
- distance,
- animation = {};
-
- // Adjust
- $.effects.save( el, props );
- el.show();
- distance = o.distance || el[ ref === "top" ? "outerHeight" : "outerWidth" ]( true );
-
- $.effects.createWrapper( el ).css({
- overflow: "hidden"
- });
-
- if ( show ) {
- el.css( ref, positiveMotion ? (isNaN(distance) ? "-" + distance : -distance) : distance );
- }
-
- // Animation
- animation[ ref ] = ( show ?
- ( positiveMotion ? "+=" : "-=") :
- ( positiveMotion ? "-=" : "+=")) +
- distance;
-
- // Animate
- el.animate( animation, {
- queue: false,
- duration: o.duration,
- easing: o.easing,
- complete: function() {
- if ( mode === "hide" ) {
- el.hide();
- }
- $.effects.restore( el, props );
- $.effects.removeWrapper( el );
- done();
- }
- });
-};
-
-})(jQuery);
-(function( $, undefined ) {
-
-$.effects.effect.transfer = function( o, done ) {
- var elem = $( this ),
- target = $( o.to ),
- targetFixed = target.css( "position" ) === "fixed",
- body = $("body"),
- fixTop = targetFixed ? body.scrollTop() : 0,
- fixLeft = targetFixed ? body.scrollLeft() : 0,
- endPosition = target.offset(),
- animation = {
- top: endPosition.top - fixTop ,
- left: endPosition.left - fixLeft ,
- height: target.innerHeight(),
- width: target.innerWidth()
- },
- startPosition = elem.offset(),
- transfer = $( "<div class='ui-effects-transfer'></div>" )
- .appendTo( document.body )
- .addClass( o.className )
- .css({
- top: startPosition.top - fixTop ,
- left: startPosition.left - fixLeft ,
- height: elem.innerHeight(),
- width: elem.innerWidth(),
- position: targetFixed ? "fixed" : "absolute"
- })
- .animate( animation, o.duration, o.easing, function() {
- transfer.remove();
- done();
- });
-};
-
-})(jQuery);
diff --git a/wicket-examples/src/main/webapp/jquery-ui-v1.14.2.custom.js b/wicket-examples/src/main/webapp/jquery-ui-v1.14.2.custom.js
new file mode 100644
index 0000000000..91bd9ce039
--- /dev/null
+++ b/wicket-examples/src/main/webapp/jquery-ui-v1.14.2.custom.js
@@ -0,0 +1,2576 @@
+/*! jQuery UI - v1.14.2 - 2026-09-07
+* https://jqueryui.com
+* Includes: effect.js, effects/effect-blind.js, effects/effect-bounce.js, effects/effect-clip.js, effects/effect-drop.js, effects/effect-explode.js, effects/effect-fade.js, effects/effect-fold.js, effects/effect-highlight.js, effects/effect-puff.js, effects/effect-pulsate.js, effects/effect-scale.js, effects/effect-shake.js, effects/effect-size.js, effects/effect-slide.js, effects/effect-transfer.js
+* Copyright OpenJS Foundation and other contributors; Licensed MIT */
+
+( function( factory ) {
+ "use strict";
+
+ if ( typeof define === "function" && define.amd ) {
+
+ // AMD. Register as an anonymous module.
+ define( [ "jquery" ], factory );
+ } else {
+
+ // Browser globals
+ factory( jQuery );
+ }
+} )( function( $ ) {
+"use strict";
+
+$.ui = $.ui || {};
+
+var version = $.ui.version = "1.14.2";
+
+
+
+// Create a local jQuery because jQuery Color relies on it and the
+// global may not exist with AMD and a custom build (#10199).
+// This module is a noop if used as a regular AMD module.
+// eslint-disable-next-line no-unused-vars
+var jQuery = $;
+
+
+/*!
+ * jQuery Color Animations v3.0.0
+ * https://github.com/jquery/jquery-color
+ *
+ * Copyright OpenJS Foundation and other contributors
+ * Released under the MIT license.
+ * https://jquery.org/license
+ *
+ * Date: Wed May 15 16:49:44 2024 +0200
+ */
+
+
+ var stepHooks = "backgroundColor borderBottomColor borderLeftColor borderRightColor " +
+ "borderTopColor color columnRuleColor outlineColor textDecorationColor textEmphasisColor",
+
+ class2type = {},
+ toString = class2type.toString,
+
+ // plusequals test for += 100 -= 100
+ rplusequals = /^([\-+])=\s*(\d+\.?\d*)/,
+
+ // a set of RE's that can match strings and generate color tuples.
+ stringParsers = [ {
+ re: /rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,
+ parse: function( execResult ) {
+ return [
+ execResult[ 1 ],
+ execResult[ 2 ],
+ execResult[ 3 ],
+ execResult[ 4 ]
+ ];
+ }
+ }, {
+ re: /rgba?\(\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,
+ parse: function( execResult ) {
+ return [
+ execResult[ 1 ] * 2.55,
+ execResult[ 2 ] * 2.55,
+ execResult[ 3 ] * 2.55,
+ execResult[ 4 ]
+ ];
+ }
+ }, {
+
+ // this regex ignores A-F because it's compared against an already lowercased string
+ re: /#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})?/,
+ parse: function( execResult ) {
+ return [
+ parseInt( execResult[ 1 ], 16 ),
+ parseInt( execResult[ 2 ], 16 ),
+ parseInt( execResult[ 3 ], 16 ),
+ execResult[ 4 ] ?
+ ( parseInt( execResult[ 4 ], 16 ) / 255 ).toFixed( 2 ) :
+ 1
+ ];
+ }
+ }, {
+
+ // this regex ignores A-F because it's compared against an already lowercased string
+ re: /#([a-f0-9])([a-f0-9])([a-f0-9])([a-f0-9])?/,
+ parse: function( execResult ) {
+ return [
+ parseInt( execResult[ 1 ] + execResult[ 1 ], 16 ),
+ parseInt( execResult[ 2 ] + execResult[ 2 ], 16 ),
+ parseInt( execResult[ 3 ] + execResult[ 3 ], 16 ),
+ execResult[ 4 ] ?
+ ( parseInt( execResult[ 4 ] + execResult[ 4 ], 16 ) / 255 )
+ .toFixed( 2 ) :
+ 1
+ ];
+ }
+ }, {
+ re: /hsla?\(\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,
+ space: "hsla",
+ parse: function( execResult ) {
+ return [
+ execResult[ 1 ],
+ execResult[ 2 ] / 100,
+ execResult[ 3 ] / 100,
+ execResult[ 4 ]
+ ];
+ }
+ } ],
+
+ // jQuery.Color( )
+ color = jQuery.Color = function( color, green, blue, alpha ) {
+ return new jQuery.Color.fn.parse( color, green, blue, alpha );
+ },
+ spaces = {
+ rgba: {
+ props: {
+ red: {
+ idx: 0,
+ type: "byte"
+ },
+ green: {
+ idx: 1,
+ type: "byte"
+ },
+ blue: {
+ idx: 2,
+ type: "byte"
+ }
+ }
+ },
+
+ hsla: {
+ props: {
+ hue: {
+ idx: 0,
+ type: "degrees"
+ },
+ saturation: {
+ idx: 1,
+ type: "percent"
+ },
+ lightness: {
+ idx: 2,
+ type: "percent"
+ }
+ }
+ }
+ },
+ propTypes = {
+ "byte": {
+ floor: true,
+ max: 255
+ },
+ "percent": {
+ max: 1
+ },
+ "degrees": {
+ mod: 360,
+ floor: true
+ }
+ },
+
+ // colors = jQuery.Color.names
+ colors,
+
+ // local aliases of functions called often
+ each = jQuery.each;
+
+// define cache name and alpha properties
+// for rgba and hsla spaces
+each( spaces, function( spaceName, space ) {
+ space.cache = "_" + spaceName;
+ space.props.alpha = {
+ idx: 3,
+ type: "percent",
+ def: 1
+ };
+} );
+
+// Populate the class2type map
+jQuery.each( "Boolean Number String Function Array Date RegExp Object Error Symbol".split( " " ),
+ function( _i, name ) {
+ class2type[ "[object " + name + "]" ] = name.toLowerCase();
+ } );
+
+function getType( obj ) {
+ if ( obj == null ) {
+ return obj + "";
+ }
+
+ return typeof obj === "object" ?
+ class2type[ toString.call( obj ) ] || "object" :
+ typeof obj;
+}
+
+function clamp( value, prop, allowEmpty ) {
+ var type = propTypes[ prop.type ] || {};
+
+ if ( value == null ) {
+ return ( allowEmpty || !prop.def ) ? null : prop.def;
+ }
+
+ // ~~ is an short way of doing floor for positive numbers
+ value = type.floor ? ~~value : parseFloat( value );
+
+ if ( type.mod ) {
+
+ // we add mod before modding to make sure that negatives values
+ // get converted properly: -10 -> 350
+ return ( value + type.mod ) % type.mod;
+ }
+
+ // for now all property types without mod have min and max
+ return Math.min( type.max, Math.max( 0, value ) );
+}
+
+function stringParse( string ) {
+ var inst = color(),
+ rgba = inst._rgba = [];
+
+ string = string.toLowerCase();
+
+ each( stringParsers, function( _i, parser ) {
+ var parsed,
+ match = parser.re.exec( string ),
+ values = match && parser.parse( match ),
+ spaceName = parser.space || "rgba";
+
+ if ( values ) {
+ parsed = inst[ spaceName ]( values );
+
+ // if this was an rgba parse the assignment might happen twice
+ // oh well....
+ inst[ spaces[ spaceName ].cache ] = parsed[ spaces[ spaceName ].cache ];
+ rgba = inst._rgba = parsed._rgba;
+
+ // exit each( stringParsers ) here because we matched
+ return false;
+ }
+ } );
+
+ // Found a stringParser that handled it
+ if ( rgba.length ) {
+
+ // if this came from a parsed string, force "transparent" when alpha is 0
+ // chrome, (and maybe others) return "transparent" as rgba(0,0,0,0)
+ if ( rgba.join() === "0,0,0,0" ) {
+ jQuery.extend( rgba, colors.transparent );
+ }
+ return inst;
+ }
+
+ // named colors
+ return colors[ string ];
+}
+
+color.fn = jQuery.extend( color.prototype, {
+ parse: function( red, green, blue, alpha ) {
+ if ( red === undefined ) {
+ this._rgba = [ null, null, null, null ];
+ return this;
+ }
+ if ( red.jquery || red.nodeType ) {
+ red = jQuery( red ).css( green );
+ green = undefined;
+ }
+
+ var inst = this,
+ type = getType( red ),
+ rgba = this._rgba = [];
+
+ // more than 1 argument specified - assume ( red, green, blue, alpha )
+ if ( green !== undefined ) {
+ red = [ red, green, blue, alpha ];
+ type = "array";
+ }
+
+ if ( type === "string" ) {
+ return this.parse( stringParse( red ) || colors._default );
+ }
+
+ if ( type === "array" ) {
+ each( spaces.rgba.props, function( _key, prop ) {
+ rgba[ prop.idx ] = clamp( red[ prop.idx ], prop );
+ } );
+ return this;
+ }
+
+ if ( type === "object" ) {
+ if ( red instanceof color ) {
+ each( spaces, function( _spaceName, space ) {
+ if ( red[ space.cache ] ) {
+ inst[ space.cache ] = red[ space.cache ].slice();
+ }
+ } );
+ } else {
+ each( spaces, function( _spaceName, space ) {
+ var cache = space.cache;
+ each( space.props, function( key, prop ) {
+
+ // if the cache doesn't exist, and we know how to convert
+ if ( !inst[ cache ] && space.to ) {
+
+ // if the value was null, we don't need to copy it
+ // if the key was alpha, we don't need to copy it either
+ if ( key === "alpha" || red[ key ] == null ) {
+ return;
+ }
+ inst[ cache ] = space.to( inst._rgba );
+ }
+
+ // this is the only case where we allow nulls for ALL properties.
+ // call clamp with alwaysAllowEmpty
+ inst[ cache ][ prop.idx ] = clamp( red[ key ], prop, true );
+ } );
+
+ // everything defined but alpha?
+ if ( inst[ cache ] && jQuery.inArray(
+ null,
+ inst[ cache ].slice( 0, 3 )
+ ) < 0 ) {
+
+ // use the default of 1
+ if ( inst[ cache ][ 3 ] == null ) {
+ inst[ cache ][ 3 ] = 1;
+ }
+
+ if ( space.from ) {
+ inst._rgba = space.from( inst[ cache ] );
+ }
+ }
+ } );
+ }
+ return this;
+ }
+ },
+ is: function( compare ) {
+ var is = color( compare ),
+ same = true,
+ inst = this;
+
+ each( spaces, function( _, space ) {
+ var localCache,
+ isCache = is[ space.cache ];
+ if ( isCache ) {
+ localCache = inst[ space.cache ] || space.to && space.to( inst._rgba ) || [];
+ each( space.props, function( _, prop ) {
+ if ( isCache[ prop.idx ] != null ) {
+ same = ( isCache[ prop.idx ] === localCache[ prop.idx ] );
+ return same;
+ }
+ } );
+ }
+ return same;
+ } );
+ return same;
+ },
+ _space: function() {
+ var used = [],
+ inst = this;
+ each( spaces, function( spaceName, space ) {
+ if ( inst[ space.cache ] ) {
+ used.push( spaceName );
+ }
+ } );
+ return used.pop();
+ },
+ transition: function( other, distance ) {
+ var end = color( other ),
+ spaceName = end._space(),
+ space = spaces[ spaceName ],
+ startColor = this.alpha() === 0 ? color( "transparent" ) : this,
+ start = startColor[ space.cache ] || space.to( startColor._rgba ),
+ result = start.slice();
+
+ end = end[ space.cache ];
+ each( space.props, function( _key, prop ) {
+ var index = prop.idx,
+ startValue = start[ index ],
+ endValue = end[ index ],
+ type = propTypes[ prop.type ] || {};
+
+ // if null, don't override start value
+ if ( endValue === null ) {
+ return;
+ }
+
+ // if null - use end
+ if ( startValue === null ) {
+ result[ index ] = endValue;
+ } else {
+ if ( type.mod ) {
+ if ( endValue - startValue > type.mod / 2 ) {
+ startValue += type.mod;
+ } else if ( startValue - endValue > type.mod / 2 ) {
+ startValue -= type.mod;
+ }
+ }
+ result[ index ] = clamp( ( endValue - startValue ) * distance + startValue, prop );
+ }
+ } );
+ return this[ spaceName ]( result );
+ },
+ blend: function( opaque ) {
+
+ // if we are already opaque - return ourself
+ if ( this._rgba[ 3 ] === 1 ) {
+ return this;
+ }
+
+ var rgb = this._rgba.slice(),
+ a = rgb.pop(),
+ blend = color( opaque )._rgba;
+
+ return color( jQuery.map( rgb, function( v, i ) {
+ return ( 1 - a ) * blend[ i ] + a * v;
+ } ) );
+ },
+ toRgbaString: function() {
+ var prefix = "rgba(",
+ rgba = jQuery.map( this._rgba, function( v, i ) {
+ if ( v != null ) {
+ return v;
+ }
+ return i > 2 ? 1 : 0;
+ } );
+
+ if ( rgba[ 3 ] === 1 ) {
+ rgba.pop();
+ prefix = "rgb(";
+ }
+
+ return prefix + rgba.join( ", " ) + ")";
+ },
+ toHslaString: function() {
+ var prefix = "hsla(",
+ hsla = jQuery.map( this.hsla(), function( v, i ) {
+ if ( v == null ) {
+ v = i > 2 ? 1 : 0;
+ }
+
+ // catch 1 and 2
+ if ( i && i < 3 ) {
+ v = Math.round( v * 100 ) + "%";
+ }
+ return v;
+ } );
+
+ if ( hsla[ 3 ] === 1 ) {
+ hsla.pop();
+ prefix = "hsl(";
+ }
+ return prefix + hsla.join( ", " ) + ")";
+ },
+ toHexString: function( includeAlpha ) {
+ var rgba = this._rgba.slice(),
+ alpha = rgba.pop();
+
+ if ( includeAlpha ) {
+ rgba.push( ~~( alpha * 255 ) );
+ }
+
+ return "#" + jQuery.map( rgba, function( v ) {
+
+ // default to 0 when nulls exist
+ return ( "0" + ( v || 0 ).toString( 16 ) ).substr( -2 );
+ } ).join( "" );
+ },
+ toString: function() {
+ return this.toRgbaString();
+ }
+} );
+color.fn.parse.prototype = color.fn;
+
+// hsla conversions adapted from:
+// https://code.google.com/p/maashaack/source/browse/packages/graphics/trunk/src/graphics/colors/HUE2RGB.as?r=5021
+
+function hue2rgb( p, q, h ) {
+ h = ( h + 1 ) % 1;
+ if ( h * 6 < 1 ) {
+ return p + ( q - p ) * h * 6;
+ }
+ if ( h * 2 < 1 ) {
+ return q;
+ }
+ if ( h * 3 < 2 ) {
+ return p + ( q - p ) * ( ( 2 / 3 ) - h ) * 6;
+ }
+ return p;
+}
+
+spaces.hsla.to = function( rgba ) {
+ if ( rgba[ 0 ] == null || rgba[ 1 ] == null || rgba[ 2 ] == null ) {
+ return [ null, null, null, rgba[ 3 ] ];
+ }
+ var r = rgba[ 0 ] / 255,
+ g = rgba[ 1 ] / 255,
+ b = rgba[ 2 ] / 255,
+ a = rgba[ 3 ],
+ max = Math.max( r, g, b ),
+ min = Math.min( r, g, b ),
+ diff = max - min,
+ add = max + min,
+ l = add * 0.5,
+ h, s;
+
+ if ( min === max ) {
+ h = 0;
+ } else if ( r === max ) {
+ h = ( 60 * ( g - b ) / diff ) + 360;
+ } else if ( g === max ) {
+ h = ( 60 * ( b - r ) / diff ) + 120;
+ } else {
+ h = ( 60 * ( r - g ) / diff ) + 240;
+ }
+
+ // chroma (diff) == 0 means greyscale which, by definition, saturation = 0%
+ // otherwise, saturation is based on the ratio of chroma (diff) to lightness (add)
+ if ( diff === 0 ) {
+ s = 0;
+ } else if ( l <= 0.5 ) {
+ s = diff / add;
+ } else {
+ s = diff / ( 2 - add );
+ }
+ return [ Math.round( h ) % 360, s, l, a == null ? 1 : a ];
+};
+
+spaces.hsla.from = function( hsla ) {
+ if ( hsla[ 0 ] == null || hsla[ 1 ] == null || hsla[ 2 ] == null ) {
+ return [ null, null, null, hsla[ 3 ] ];
+ }
+ var h = hsla[ 0 ] / 360,
+ s = hsla[ 1 ],
+ l = hsla[ 2 ],
+ a = hsla[ 3 ],
+ q = l <= 0.5 ? l * ( 1 + s ) : l + s - l * s,
+ p = 2 * l - q;
+
+ return [
+ Math.round( hue2rgb( p, q, h + ( 1 / 3 ) ) * 255 ),
+ Math.round( hue2rgb( p, q, h ) * 255 ),
+ Math.round( hue2rgb( p, q, h - ( 1 / 3 ) ) * 255 ),
+ a
+ ];
+};
+
+
+each( spaces, function( spaceName, space ) {
+ var props = space.props,
+ cache = space.cache,
+ to = space.to,
+ from = space.from;
+
+ // makes rgba() and hsla()
+ color.fn[ spaceName ] = function( value ) {
+
+ // generate a cache for this space if it doesn't exist
+ if ( to && !this[ cache ] ) {
+ this[ cache ] = to( this._rgba );
+ }
+ if ( value === undefined ) {
+ return this[ cache ].slice();
+ }
+
+ var ret,
+ type = getType( value ),
+ arr = ( type === "array" || type === "object" ) ? value : arguments,
+ local = this[ cache ].slice();
+
+ each( props, function( key, prop ) {
+ var val = arr[ type === "object" ? key : prop.idx ];
+ if ( val == null ) {
+ val = local[ prop.idx ];
+ }
+ local[ prop.idx ] = clamp( val, prop );
+ } );
+
+ if ( from ) {
+ ret = color( from( local ) );
+ ret[ cache ] = local;
+ return ret;
+ } else {
+ return color( local );
+ }
+ };
+
+ // makes red() green() blue() alpha() hue() saturation() lightness()
+ each( props, function( key, prop ) {
+
+ // alpha is included in more than one space
+ if ( color.fn[ key ] ) {
+ return;
+ }
+ color.fn[ key ] = function( value ) {
+ var local, cur, match, fn,
+ vtype = getType( value );
+
+ if ( key === "alpha" ) {
+ fn = this._hsla ? "hsla" : "rgba";
+ } else {
+ fn = spaceName;
+ }
+ local = this[ fn ]();
+ cur = local[ prop.idx ];
+
+ if ( vtype === "undefined" ) {
+ return cur;
+ }
+
+ if ( vtype === "function" ) {
+ value = value.call( this, cur );
+ vtype = getType( value );
+ }
+ if ( value == null && prop.empty ) {
+ return this;
+ }
+ if ( vtype === "string" ) {
+ match = rplusequals.exec( value );
+ if ( match ) {
+ value = cur + parseFloat( match[ 2 ] ) * ( match[ 1 ] === "+" ? 1 : -1 );
+ }
+ }
+ local[ prop.idx ] = value;
+ return this[ fn ]( local );
+ };
+ } );
+} );
+
+// add cssHook and .fx.step function for each named hook.
+// accept a space separated string of properties
+color.hook = function( hook ) {
+ var hooks = hook.split( " " );
+ each( hooks, function( _i, hook ) {
+ jQuery.cssHooks[ hook ] = {
+ set: function( elem, value ) {
+ var parsed;
+
+ if ( value !== "transparent" &&
+ ( getType( value ) !== "string" ||
+ ( parsed = stringParse( value ) ) ) ) {
+ value = color( parsed || value );
+ value = value.toRgbaString();
+ }
+ elem.style[ hook ] = value;
+ }
+ };
+ jQuery.fx.step[ hook ] = function( fx ) {
+ if ( !fx.colorInit ) {
+ fx.start = color( fx.elem, hook );
+ fx.end = color( fx.end );
+ fx.colorInit = true;
+ }
+ jQuery.cssHooks[ hook ].set( fx.elem, fx.start.transition( fx.end, fx.pos ) );
+ };
+ } );
+
+};
+
+color.hook( stepHooks );
+
+jQuery.cssHooks.borderColor = {
+ expand: function( value ) {
+ var expanded = {};
+
+ each( [ "Top", "Right", "Bottom", "Left" ], function( _i, part ) {
+ expanded[ "border" + part + "Color" ] = value;
+ } );
+ return expanded;
+ }
+};
+
+// Basic color names only.
+// Usage of any of the other color names requires adding yourself or including
+// jquery.color.svg-names.js.
+colors = jQuery.Color.names = {
+
+ // 4.1. Basic color keywords
+ aqua: "#00ffff",
+ black: "#000000",
+ blue: "#0000ff",
+ fuchsia: "#ff00ff",
+ gray: "#808080",
+ green: "#008000",
+ lime: "#00ff00",
+ maroon: "#800000",
+ navy: "#000080",
+ olive: "#808000",
+ purple: "#800080",
+ red: "#ff0000",
+ silver: "#c0c0c0",
+ teal: "#008080",
+ white: "#ffffff",
+ yellow: "#ffff00",
+
+ // 4.2.3. "transparent" color keyword
+ transparent: [ null, null, null, 0 ],
+
+ _default: "#ffffff"
+};
+
+
+/*!
+ * jQuery UI Effects 1.14.2
+ * https://jqueryui.com
+ *
+ * Copyright OpenJS Foundation and other contributors
+ * Released under the MIT license.
+ * https://jquery.org/license
+ */
+
+//>>label: Effects Core
+//>>group: Effects
+//>>description: Extends the internal jQuery effects. Includes morphing and easing. Required by all other effects.
+//>>docs: https://api.jqueryui.com/category/effects-core/
+//>>demos: https://jqueryui.com/effect/
+
+
+var dataSpace = "ui-effects-",
+ dataSpaceStyle = "ui-effects-style",
+ dataSpaceAnimated = "ui-effects-animated";
+
+$.effects = {
+ effect: {}
+};
+
+/******************************************************************************/
+/****************************** CLASS ANIMATIONS ******************************/
+/******************************************************************************/
+( function() {
+
+var classAnimationActions = [ "add", "remove", "toggle" ],
+ shorthandStyles = {
+ border: 1,
+ borderBottom: 1,
+ borderColor: 1,
+ borderLeft: 1,
+ borderRight: 1,
+ borderTop: 1,
+ borderWidth: 1,
+ margin: 1,
+ padding: 1
+ };
+
+$.each(
+ [ "borderLeftStyle", "borderRightStyle", "borderBottomStyle", "borderTopStyle" ],
+ function( _, prop ) {
+ $.fx.step[ prop ] = function( fx ) {
+ if ( fx.end !== "none" && !fx.setAttr || fx.pos === 1 && !fx.setAttr ) {
+ jQuery.style( fx.elem, prop, fx.end );
+ fx.setAttr = true;
+ }
+ };
+ }
+);
+
+function camelCase( string ) {
+ return string.replace( /-([\da-z])/gi, function( all, letter ) {
+ return letter.toUpperCase();
+ } );
+}
+
+function getElementStyles( elem ) {
+ var key, len,
+ style = elem.ownerDocument.defaultView.getComputedStyle( elem ),
+ styles = {};
+
+ len = style.length;
+ while ( len-- ) {
+ key = style[ len ];
+ if ( typeof style[ key ] === "string" ) {
+ styles[ camelCase( key ) ] = style[ key ];
+ }
+ }
+
+ return styles;
+}
+
... 3429 lines suppressed ...