You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@tapestry.apache.org by th...@apache.org on 2025/04/19 21:10:11 UTC
(tapestry-5) 02/26: decaffeinate: Convert ajax.coffee and 27 other files to JS
This is an automated email from the ASF dual-hosted git repository.
thiagohp pushed a commit to branch feature/coffeescript-to-typescript
in repository https://gitbox.apache.org/repos/asf/tapestry-5.git
commit 63124239d044be87630fc1555ab7ae5cd1c053cc
Author: decaffeinate <th...@arsmachina.com.br>
AuthorDate: Fri Apr 4 10:11:41 2025 -0300
decaffeinate: Convert ajax.coffee and 27 other files to JS
---
.../coffeescript/META-INF/modules/t5/core/ajax.js | 202 ++++----
.../META-INF/modules/t5/core/ajaxformloop.js | 139 ++---
.../coffeescript/META-INF/modules/t5/core/alert.js | 304 ++++++-----
.../META-INF/modules/t5/core/autocomplete.js | 96 ++--
.../META-INF/modules/t5/core/bootstrap.js | 49 +-
.../META-INF/modules/t5/core/confirm-click.js | 205 ++++----
.../META-INF/modules/t5/core/console.js | 374 +++++++-------
.../META-INF/modules/t5/core/datefield.js | 366 +++++++------
.../META-INF/modules/t5/core/events.js | 367 ++++++-------
.../META-INF/modules/t5/core/exception-display.js | 59 ++-
.../META-INF/modules/t5/core/exception-frame.js | 115 +++--
.../META-INF/modules/t5/core/fields.js | 333 ++++++------
.../META-INF/modules/t5/core/form-fragment.js | 219 ++++----
.../coffeescript/META-INF/modules/t5/core/forms.js | 341 +++++++------
.../META-INF/modules/t5/core/graphviz.js | 63 ++-
.../coffeescript/META-INF/modules/t5/core/init.js | 61 ++-
.../META-INF/modules/t5/core/localdate.js | 80 +--
.../META-INF/modules/t5/core/messages.js | 113 ++--
.../META-INF/modules/t5/core/moment.js | 45 +-
.../META-INF/modules/t5/core/pageinit.js | 512 ++++++++++---------
.../META-INF/modules/t5/core/palette.js | 568 ++++++++++++---------
.../META-INF/modules/t5/core/select.js | 56 +-
.../META-INF/modules/t5/core/time-interval.js | 117 +++--
.../coffeescript/META-INF/modules/t5/core/tree.js | 237 +++++----
.../coffeescript/META-INF/modules/t5/core/utils.js | 127 +++--
.../META-INF/modules/t5/core/validation.js | 380 ++++++++------
.../META-INF/modules/t5/core/zone-refresh.js | 146 +++---
.../coffeescript/META-INF/modules/t5/core/zone.js | 259 +++++-----
28 files changed, 3234 insertions(+), 2699 deletions(-)
diff --git a/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/ajax.js b/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/ajax.js
index 8e5794324..4d27daba1 100644
--- a/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/ajax.js
+++ b/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/ajax.js
@@ -1,95 +1,107 @@
-# Copyright 2012-2014 The Apache Software Foundation
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http:#www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-# ## t5/core/ajax
-#
-# Exports a single function, that invokes `t5/core/dom:ajaxRequest()` with the provided `url` and a modified version of the
-# `options`.
-#
-# * options.method - "post", "get", etc., default: "post".
-# * options.element - if provided, the URL will be treated as a server-side event name
-# and the actual URL to be used will be obtained from dom.getEventUrl(url, element)
-# * options.contentType - request content, defaults to "application/x-www-form-urlencoded"
-# * options.data - optional, additional key/value pairs (for the default content type)
-# * options.success - handler to invoke on success. Passed the ResponseWrapper object.
-# Default does nothing.
-# * options.failure - handler to invoke on failure (server responds with a non-2xx code).
-# Passed the response. Default will throw the exception
-# * options.exception - handler to invoke when an exception occurs (often means the server is unavailable).
-# Passed the exception. Default will generate an exception message and throw an `Error`.
-# Note: not really supported under jQuery, a hold-over from Prototype.
-# * options.complete - handler to invoke after success, falure, or exception. The handler is passed no
-# parameters.
-#
-# It wraps (or provides) `success`, `exception`, and `failure` handlers, extended to handle a partial page render
-# response (for success), or properly log a server-side failure or client-side exception, including using the
-# `t5/core/exception-frame` module to display a server-side processing exception.
-define ["t5/core/pageinit", "t5/core/dom", "t5/core/exception-frame", "t5/core/console", "underscore"],
- (pageinit, dom, exceptionframe, console, _) ->
- (url, options) ->
-
- complete = ->
- if options.complete
- options.complete()
-
- return
-
- if options.hasOwnProperty 'element'
- url = dom.getEventUrl(url, options.element)
-
- newOptions = _.extend {}, options,
-
- # Logs the exception to the console before passing it to the
- # provided exception handler or throwing the exception.
- exception: (exception) ->
- console.error "Request to #{url} failed with #{exception}"
-
- if options.exception
- options.exception exception
- else
- throw exception
-
- complete()
-
- return
-
- failure: (response, failureMessage) ->
- raw = response.header "X-Tapestry-ErrorMessage"
- unless _.isEmpty raw
- message = window.unescape raw
- console.error "Request to #{url} failed with '#{message}'."
-
- contentType = response.header "content-type"
-
- isHTML = contentType and (contentType.split(';')[0] is "text/html")
-
- if isHTML
- exceptionframe response.text
- else
- console.error failureMessage
-
- options.failure and options.failure(response)
-
- complete()
-
- return
-
- success: (response) ->
- pageinit.handlePartialPageRenderResponse response, options.success
-
- complete()
-
- return
-
- dom.ajaxRequest url, newOptions
\ No newline at end of file
+/*
+ * decaffeinate suggestions:
+ * DS102: Remove unnecessary code created because of implicit returns
+ * Full docs: https://github.com/decaffeinate/decaffeinate/blob/main/docs/suggestions.md
+ */
+// Copyright 2012-2014 The Apache Software Foundation
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http:#www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// ## t5/core/ajax
+//
+// Exports a single function, that invokes `t5/core/dom:ajaxRequest()` with the provided `url` and a modified version of the
+// `options`.
+//
+// * options.method - "post", "get", etc., default: "post".
+// * options.element - if provided, the URL will be treated as a server-side event name
+// and the actual URL to be used will be obtained from dom.getEventUrl(url, element)
+// * options.contentType - request content, defaults to "application/x-www-form-urlencoded"
+// * options.data - optional, additional key/value pairs (for the default content type)
+// * options.success - handler to invoke on success. Passed the ResponseWrapper object.
+// Default does nothing.
+// * options.failure - handler to invoke on failure (server responds with a non-2xx code).
+// Passed the response. Default will throw the exception
+// * options.exception - handler to invoke when an exception occurs (often means the server is unavailable).
+// Passed the exception. Default will generate an exception message and throw an `Error`.
+// Note: not really supported under jQuery, a hold-over from Prototype.
+// * options.complete - handler to invoke after success, falure, or exception. The handler is passed no
+// parameters.
+//
+// It wraps (or provides) `success`, `exception`, and `failure` handlers, extended to handle a partial page render
+// response (for success), or properly log a server-side failure or client-side exception, including using the
+// `t5/core/exception-frame` module to display a server-side processing exception.
+define(["t5/core/pageinit", "t5/core/dom", "t5/core/exception-frame", "t5/core/console", "underscore"],
+ (pageinit, dom, exceptionframe, console, _) => (function(url, options) {
+
+ const complete = function() {
+ if (options.complete) {
+ options.complete();
+ }
+
+ };
+
+ if (options.hasOwnProperty('element')) {
+ url = dom.getEventUrl(url, options.element);
+ }
+
+ const newOptions = _.extend({}, options, {
+
+ // Logs the exception to the console before passing it to the
+ // provided exception handler or throwing the exception.
+ exception(exception) {
+ console.error(`Request to ${url} failed with ${exception}`);
+
+ if (options.exception) {
+ options.exception(exception);
+ } else {
+ throw exception;
+ }
+
+ complete();
+
+ },
+
+ failure(response, failureMessage) {
+ const raw = response.header("X-Tapestry-ErrorMessage");
+ if (!_.isEmpty(raw)) {
+ const message = window.unescape(raw);
+ console.error(`Request to ${url} failed with '${message}'.`);
+
+ const contentType = response.header("content-type");
+
+ const isHTML = contentType && (contentType.split(';')[0] === "text/html");
+
+ if (isHTML) {
+ exceptionframe(response.text);
+ }
+ } else {
+ console.error(failureMessage);
+ }
+
+ options.failure && options.failure(response);
+
+ complete();
+
+ },
+
+ success(response) {
+ pageinit.handlePartialPageRenderResponse(response, options.success);
+
+ complete();
+
+ }
+ }
+ );
+
+ return dom.ajaxRequest(url, newOptions);
+ }));
\ No newline at end of file
diff --git a/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/ajaxformloop.js b/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/ajaxformloop.js
index 0dca35d2b..465a47f56 100644
--- a/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/ajaxformloop.js
+++ b/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/ajaxformloop.js
@@ -1,87 +1,102 @@
-# Copyright 2012, 2013 The Apache Software Foundation
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http:#www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+/*
+ * decaffeinate suggestions:
+ * DS102: Remove unnecessary code created because of implicit returns
+ * DS207: Consider shorter variations of null checks
+ * Full docs: https://github.com/decaffeinate/decaffeinate/blob/main/docs/suggestions.md
+ */
+// Copyright 2012, 2013 The Apache Software Foundation
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http:#www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
-# ## t5/core/ajaxformloop
-#
-# Provides handlers related to the core/AjaxFormLoop component (as well as core/AddRowLink and
-# core/RemoveRowLink).
-define ["t5/core/dom", "t5/core/events", "t5/core/console", "t5/core/ajax"],
- (dom, events, console, ajax) ->
+// ## t5/core/ajaxformloop
+//
+// Provides handlers related to the core/AjaxFormLoop component (as well as core/AddRowLink and
+// core/RemoveRowLink).
+define(["t5/core/dom", "t5/core/events", "t5/core/console", "t5/core/ajax"],
+ function(dom, events, console, ajax) {
- # "afl" is short for "AjaxFormLoop".
- AFL_SELECTOR = "[data-container-type='core/AjaxFormLoop']"
- FRAGMENT_TYPE = "core/ajaxformloop-fragment"
+ // "afl" is short for "AjaxFormLoop".
+ const AFL_SELECTOR = "[data-container-type='core/AjaxFormLoop']";
+ const FRAGMENT_TYPE = "core/ajaxformloop-fragment";
- dom.onDocument "click", "#{AFL_SELECTOR} [data-afl-behavior=remove]", ->
+ dom.onDocument("click", `${AFL_SELECTOR} [data-afl-behavior=remove]`, function() {
- afl = @findParent AFL_SELECTOR
+ const afl = this.findParent(AFL_SELECTOR);
- unless afl
- console.error "Enclosing element for AjaxFormLoop remove row link not found."
- return false
+ if (!afl) {
+ console.error("Enclosing element for AjaxFormLoop remove row link not found.");
+ return false;
+ }
- url = afl.attr "data-remove-row-url"
+ const url = afl.attr("data-remove-row-url");
- ajax url,
- data:
- "t:rowvalue": (@closest "[data-afl-row-value]").attr "data-afl-row-value"
- success: =>
- # The server has removed the row from persistent storage, lets
- # do the same on the UI.
+ ajax(url, {
+ data: {
+ "t:rowvalue": (this.closest("[data-afl-row-value]")).attr("data-afl-row-value")
+ },
+ success: () => {
+ // The server has removed the row from persistent storage, lets
+ // do the same on the UI.
- fragment = @findParent "[data-container-type='#{FRAGMENT_TYPE}']"
+ const fragment = this.findParent(`[data-container-type='${FRAGMENT_TYPE}']`);
- # TODO: Fire some before & after events, to allow for animation.
+ // TODO: Fire some before & after events, to allow for animation.
- # The fragment takes with it the hidden fields that control form submission
- # for its portion of the form.
- fragment.remove()
+ // The fragment takes with it the hidden fields that control form submission
+ // for its portion of the form.
+ return fragment.remove();
+ }
+ }
+ );
- return false
+ return false;
+ });
- dom.onDocument "click", "#{AFL_SELECTOR} [data-afl-behavior=insert-before] [data-afl-trigger=add]", ->
+ dom.onDocument("click", `${AFL_SELECTOR} [data-afl-behavior=insert-before] [data-afl-trigger=add]`, function() {
- afl = @findParent AFL_SELECTOR
+ const afl = this.findParent(AFL_SELECTOR);
- insertionPoint = @findParent "[data-afl-behavior=insert-before]"
+ const insertionPoint = this.findParent("[data-afl-behavior=insert-before]");
- url = afl.attr "data-inject-row-url"
+ const url = afl.attr("data-inject-row-url");
- ajax url,
- success: (response) ->
- content = response.json?.content or ""
+ ajax(url, {
+ success(response) {
+ const content = (response.json != null ? response.json.content : undefined) || "";
- # Create a new element with the same type (usually "div") and class as this element.
- # It will contain the new content.
+ // Create a new element with the same type (usually "div") and class as this element.
+ // It will contain the new content.
- newElement = dom.create insertionPoint.element.tagName,
- 'class': insertionPoint.element.className, 'data-container-type': FRAGMENT_TYPE,
- content
+ const newElement = dom.create(insertionPoint.element.tagName,
+ {'class': insertionPoint.element.className, 'data-container-type': FRAGMENT_TYPE},
+ content);
- insertionPoint.insertBefore newElement
+ insertionPoint.insertBefore(newElement);
- # Initialize components inside the new row
- newElement.trigger events.initializeComponents
+ // Initialize components inside the new row
+ newElement.trigger(events.initializeComponents);
- # Trigger this event, to inform the world that the zone-like new element has been updated
- # with content.
- insertionPoint.trigger events.zone.didUpdate
+ // Trigger this event, to inform the world that the zone-like new element has been updated
+ // with content.
+ insertionPoint.trigger(events.zone.didUpdate);
- return
+ }
+ }
+ );
- return false
+ return false;
+ });
- # This module is all event handlers, and no exported functions.
- return
\ No newline at end of file
+ // This module is all event handlers, and no exported functions.
+});
\ No newline at end of file
diff --git a/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/alert.js b/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/alert.js
index 778515020..0dddb6189 100644
--- a/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/alert.js
+++ b/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/alert.js
@@ -1,142 +1,172 @@
-# Copyright 2012-2013 The Apache Software Foundation
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http:#www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-# ## t5/core/alert
-#
-# Support for the core/Alerts components.
-#
-define ["t5/core/dom", "t5/core/console", "t5/core/messages", "t5/core/ajax", "underscore", "t5/core/bootstrap"],
- (dom, console, messages, ajax, _, {glyph}) ->
-
- severityToClass =
- info: "alert-info"
- success: "alert-success"
- warn: "alert-warning"
+/*
+ * decaffeinate suggestions:
+ * DS102: Remove unnecessary code created because of implicit returns
+ * DS207: Consider shorter variations of null checks
+ * Full docs: https://github.com/decaffeinate/decaffeinate/blob/main/docs/suggestions.md
+ */
+// Copyright 2012-2013 The Apache Software Foundation
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http:#www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// ## t5/core/alert
+//
+// Support for the core/Alerts components.
+//
+define(["t5/core/dom", "t5/core/console", "t5/core/messages", "t5/core/ajax", "underscore", "t5/core/bootstrap"],
+ function(dom, console, messages, ajax, _, {glyph}) {
+
+ let exports;
+ const severityToClass = {
+ info: "alert-info",
+ success: "alert-success",
+ warn: "alert-warning",
error: "alert-danger"
+ };
- getURL = (container) -> container.attr "data-dismiss-url"
+ const getURL = container => container.attr("data-dismiss-url");
- removeAlert = (container, alert) ->
- alert.remove()
+ const removeAlert = function(container, alert) {
+ alert.remove();
- if container.find(".alert").length is 0
- container.update null
-
- dismissAll = (container) ->
-
- alerts = container.find "[data-alert-id]"
-
- if alerts.length is 0
- container.update null
- return
-
- ajax (getURL container),
- success: -> container.update null
-
- dismissOne = (container, button) ->
-
- alert = button.parent()
-
- id = alert.attr "data-alert-id"
-
- unless id
- removeAlert container, alert
- return
-
- ajax (getURL container),
- data: { id }
- success: -> removeAlert container, alert
-
- setupUI = (outer) ->
-
- outer.update """
- <div data-container-type="inner"></div>
- """
-
- if (outer.attr "data-show-dismiss-all") is "true"
- outer.append """
- <div class="pull-right">
- <button class="btn btn-xs btn-default" data-action="dismiss-all">
- #{glyph "remove"}
- #{messages "core-dismiss-label"}
- </button>
- </div>
- """
-
- outer.on "click", "[data-action=dismiss-all]", ->
- dismissAll outer
- return false
-
- outer.on "click", "button.close", ->
- dismissOne outer, this
- return false
-
- findInnerContainer = ->
- outer = dom.body.findFirst "[data-container-type=alerts]"
-
- unless outer
- console.error "Unable to locate alert container element to present an alert."
- return null
-
- # Set up the inner content when needed
- unless outer.element.firstChild
- setupUI outer
-
- return outer?.findFirst "[data-container-type=inner]"
-
- # The `data` for the alert has a number of keys to control its behavior:
- #
- # * severity - used to determine the CSS class, may be "warn", "error", or "info" (the default)
- # * message - message to display to as te alert's body
- # * markup - if true, then the message contains markup that should not be HTML escaped
- alert = (data) ->
-
- container = findInnerContainer()
-
- return unless container
-
- # Map from severity name to a CSS class; using alert-info if no severity, or unknown severity
- className = severityToClass[data.severity] or "alert-info"
-
- content = if data.markup then data.message else _.escape data.message
-
- # Note that `data-dismiss=alert` is purposely excluded
- # - we want to handle closes w/ notifications to the server if not transient
- # - we don't want to rely on bootstrap.js, as that will drag jQuery into the application
- # Also, the <span> tag makes it easier to pull out just the content when doing tests,
- # but we only add this add if the alert doesn't have a message that contains markup (TAP5-1863)
- element = dom.create "div",
- "data-alert-id": data.id
+ if (container.find(".alert").length === 0) {
+ return container.update(null);
+ }
+ };
+
+ const dismissAll = function(container) {
+
+ const alerts = container.find("[data-alert-id]");
+
+ if (alerts.length === 0) {
+ container.update(null);
+ return;
+ }
+
+ return ajax((getURL(container)),
+ {success() { return container.update(null); }});
+ };
+
+ const dismissOne = function(container, button) {
+
+ const alert = button.parent();
+
+ const id = alert.attr("data-alert-id");
+
+ if (!id) {
+ removeAlert(container, alert);
+ return;
+ }
+
+ return ajax((getURL(container)), {
+ data: { id },
+ success() { return removeAlert(container, alert); }
+ }
+ );
+ };
+
+ const setupUI = function(outer) {
+
+ outer.update(`\
+<div data-container-type="inner"></div>\
+`
+ );
+
+ if ((outer.attr("data-show-dismiss-all")) === "true") {
+ outer.append(`\
+<div class="pull-right">
+ <button class="btn btn-xs btn-default" data-action="dismiss-all">
+ ${glyph("remove")}
+ ${messages("core-dismiss-label")}
+ </button>
+ </div>\
+`
+ );
+ }
+
+ outer.on("click", "[data-action=dismiss-all]", function() {
+ dismissAll(outer);
+ return false;
+ });
+
+ return outer.on("click", "button.close", function() {
+ dismissOne(outer, this);
+ return false;
+ });
+ };
+
+ const findInnerContainer = function() {
+ const outer = dom.body.findFirst("[data-container-type=alerts]");
+
+ if (!outer) {
+ console.error("Unable to locate alert container element to present an alert.");
+ return null;
+ }
+
+ // Set up the inner content when needed
+ if (!outer.element.firstChild) {
+ setupUI(outer);
+ }
+
+ return (outer != null ? outer.findFirst("[data-container-type=inner]") : undefined);
+ };
+
+ // The `data` for the alert has a number of keys to control its behavior:
+ //
+ // * severity - used to determine the CSS class, may be "warn", "error", or "info" (the default)
+ // * message - message to display to as te alert's body
+ // * markup - if true, then the message contains markup that should not be HTML escaped
+ const alert = function(data) {
+
+ const container = findInnerContainer();
+
+ if (!container) { return; }
+
+ // Map from severity name to a CSS class; using alert-info if no severity, or unknown severity
+ const className = severityToClass[data.severity] || "alert-info";
+
+ const content = data.markup ? data.message : _.escape(data.message);
+
+ // Note that `data-dismiss=alert` is purposely excluded
+ // - we want to handle closes w/ notifications to the server if not transient
+ // - we don't want to rely on bootstrap.js, as that will drag jQuery into the application
+ // Also, the <span> tag makes it easier to pull out just the content when doing tests,
+ // but we only add this add if the alert doesn't have a message that contains markup (TAP5-1863)
+ const element = dom.create("div", {
+ "data-alert-id": data.id,
class: "alert alert-dismissable " + className
- if data.markup
- """
- <button type="button" class="close">×</button>
- #{content}
- """
- else
- """
- <button type="button" class="close">×</button>
- <span>#{content}</span>
- """
-
- container.append element
-
- if data['transient']
- outerContainer = container.findParent '[data-container-type=alerts]'
- _.delay removeAlert, exports.TRANSIENT_DURATION, outerContainer, element
-
- alert.TRANSIENT_DURATION = 5000
-
- # Export the alert function
- exports = alert
+ },
+ data.markup ?
+ `\
+<button type="button" class="close">×</button>
+${content}\
+`
+ :
+ `\
+<button type="button" class="close">×</button>
+<span>${content}</span>\
+`
+ );
+
+ container.append(element);
+
+ if (data['transient']) {
+ const outerContainer = container.findParent('[data-container-type=alerts]');
+ return _.delay(removeAlert, exports.TRANSIENT_DURATION, outerContainer, element);
+ }
+ };
+
+ alert.TRANSIENT_DURATION = 5000;
+
+ // Export the alert function
+ return exports = alert;
+});
diff --git a/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/autocomplete.js b/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/autocomplete.js
index fe09a564a..a1146f2f7 100644
--- a/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/autocomplete.js
+++ b/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/autocomplete.js
@@ -1,48 +1,58 @@
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http:#www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-# ## t5/core/autocomplete
-#
-# Support for the core/Autocomplete Tapestry mixin, a wrapper around
-# the Twitter autocomplete.js library.
-define ["t5/core/dom", "t5/core/ajax", "underscore", "jquery", "t5/core/utils", "t5/core/typeahead"],
- (dom, ajax, _, $, {extendURL}) ->
-
- init = (spec) ->
- $field = $ document.getElementById spec.id
-
- engine = new Bloodhound
- datumTokenizer: Bloodhound.tokenizers.whitespace
- queryTokenizer: Bloodhound.tokenizers.whitespace
- limit: spec.limit
- remote:
- url: spec.url
- replace: (uri, query) -> extendURL uri, "t:input": query
- filter: (response) -> response.matches
-
- engine.initialize()
-
- dataset =
- name: spec.id
- displayKey: _.identity
+/*
+ * decaffeinate suggestions:
+ * DS102: Remove unnecessary code created because of implicit returns
+ * Full docs: https://github.com/decaffeinate/decaffeinate/blob/main/docs/suggestions.md
+ */
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http:#www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// ## t5/core/autocomplete
+//
+// Support for the core/Autocomplete Tapestry mixin, a wrapper around
+// the Twitter autocomplete.js library.
+define(["t5/core/dom", "t5/core/ajax", "underscore", "jquery", "t5/core/utils", "t5/core/typeahead"],
+ function(dom, ajax, _, $, {extendURL}) {
+
+ let exports;
+ const init = function(spec) {
+ const $field = $(document.getElementById(spec.id));
+
+ const engine = new Bloodhound({
+ datumTokenizer: Bloodhound.tokenizers.whitespace,
+ queryTokenizer: Bloodhound.tokenizers.whitespace,
+ limit: spec.limit,
+ remote: {
+ url: spec.url,
+ replace(uri, query) { return extendURL(uri, {"t:input": query}); },
+ filter(response) { return response.matches; }
+ }
+ });
+
+ engine.initialize();
+
+ const dataset = {
+ name: spec.id,
+ displayKey: _.identity,
source: engine.ttAdapter()
+ };
- $field.typeahead
- minLength: spec.minChars
- dataset
+ $field.typeahead(
+ {minLength: spec.minChars},
+ dataset);
- # don't validate the "tt-hint" input field created by Typeahead (fix for TAP5-2440)
- $field.prev(".tt-hint").removeAttr("data-validation data-optionality data-required-message")
+ // don't validate the "tt-hint" input field created by Typeahead (fix for TAP5-2440)
+ $field.prev(".tt-hint").removeAttr("data-validation data-optionality data-required-message");
- return
+ };
- exports = init
+ return exports = init;
+});
diff --git a/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/bootstrap.js b/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/bootstrap.js
index fd9fcbe1a..58fbd9c2e 100644
--- a/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/bootstrap.js
+++ b/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/bootstrap.js
@@ -1,29 +1,30 @@
-# Copyright 2013 The Apache Software Foundation
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http:#www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+// Copyright 2013 The Apache Software Foundation
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http:#www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
-# ## t5/core/bootstrap
-#
-# Utilities for leveraging Bootstrap
-define ["t5/core/bootstrap"],
- ->
+// ## t5/core/bootstrap
+//
+// Utilities for leveraging Bootstrap
+define(["t5/core/bootstrap"],
+ function() {
- exports =
- # Generates the CSS class name for an icon.
- #
- # * name - of icon, e.g., "arrow-left"
- glyph: (name) -> """<span class="glyphicon glyphicon-#{name}"></span>"""
+ const exports =
+ // Generates the CSS class name for an icon.
+ //
+ // * name - of icon, e.g., "arrow-left"
+ {glyph(name) { return `<span class="glyphicon glyphicon-${name}"></span>`; }};
- return exports
+ return exports;
+});
diff --git a/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/confirm-click.js b/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/confirm-click.js
index 1d79e849c..0d7bb7c2c 100644
--- a/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/confirm-click.js
+++ b/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/confirm-click.js
@@ -1,96 +1,109 @@
-# ## t5/core/confirm-click
-#
-# Support for the Tapestry Confirm mixin, and for running confirmation dialogs programmatically.
-
-define ["jquery", "t5/core/events", "bootstrap/modal"],
-
- ($, events) ->
-
- # Runs a modal dialog, invoking a callback if the user selects the OK option. On any form of cancel,
- # there is no callback.
- #
- # options.title - default "Confirm"
- # options.message - required
- # options.okClass - default "btn-warning"
- # options.okLabel - default "OK"
- # options.cancelLabel - default "Cancel"
- # options.ok - callback function, required
- runDialog = (options) ->
-
- confirmed = false
-
- content = """
- <div class="modal fade" role="dialog" tabindex='-1'>
- <div class="modal-dialog">
- <div class="modal-content">
- <div class="modal-header">
- <a class="close" data-dismiss="modal">×</a>
- <h3>#{options.title or "Confirm"}</h3>
- </div>
- <div class="modal-body">#{options.message}</div>
- <div class="modal-footer">
- <button class="btn #{options.okClass or "btn-warning"}" data-dismiss="modal">#{options.okLabel or "OK"}</button>
- <button class="btn btn-default" data-dismiss="modal">#{options.cancelLabel or "Cancel"}</button>
- </div>
- </div>
- </div>
- </div>
- """
-
- $dialog = $ content
-
- $dialog.on "click", ".modal-footer button:first", ->
- confirmed = true
- return
-
- # Let the animation run before (perhaps) invoking the callback.
- $dialog.modal().on "hidden.bs.modal", ->
- $dialog.remove()
- if confirmed
- options.ok()
-
- $dialog.appendTo $ "body"
-
- # Focus on the first button (the "OK") button.
- $dialog.on "shown.bs.modal", ->
- $dialog.find(".modal-footer .btn").first().focus()
-
- # Support for the Confirm mixin
- $("body").on "click", "[data-confirm-message]:not(.disabled)", (event)->
-
- $this = $(this)
-
- # We use a data- attribute as a flag, to indicate that the user confirmed the behavior.
-
- if ($this.attr "data-confirm-state") is "confirmed"
- $this.attr "data-confirm-state", null
- return # allow default behavior to continue
-
- runDialog
- title: $this.attr "data-confirm-title"
- message: $this.attr "data-confirm-message"
- okClass: $this.attr "data-confirm-class-ok"
- okLabel: $this.attr "data-confirm-label-ok"
- cancelLabel: $this.attr "data-confirm-label-cancel"
- ok: ->
- $this.attr "data-confirm-state", "confirmed"
- # In the case of an Ajax update, or a button, this is enough. In the case of a simple link,
- # the default behavior when triggering click() is to do nothing, and our document event handler
- # (just below) picks up the slack.
- $this.click()
-
- # Cancel the original click event
- return false
-
- ($ document).on "click", "a[data-confirm-message]:not(.disabled, [data-update-zone], [data-async-trigger])", (event) ->
-
- target = $ event.target
-
- # See note above; this replicates the default behavior of a link element that is lost because
- # of the
- window.location.href = target.attr "href"
- return false
-
- # Exports:
-
- { runDialog }
+/*
+ * decaffeinate suggestions:
+ * DS102: Remove unnecessary code created because of implicit returns
+ * Full docs: https://github.com/decaffeinate/decaffeinate/blob/main/docs/suggestions.md
+ */
+// ## t5/core/confirm-click
+//
+// Support for the Tapestry Confirm mixin, and for running confirmation dialogs programmatically.
+
+define(["jquery", "t5/core/events", "bootstrap/modal"],
+
+ function($, events) {
+
+ // Runs a modal dialog, invoking a callback if the user selects the OK option. On any form of cancel,
+ // there is no callback.
+ //
+ // options.title - default "Confirm"
+ // options.message - required
+ // options.okClass - default "btn-warning"
+ // options.okLabel - default "OK"
+ // options.cancelLabel - default "Cancel"
+ // options.ok - callback function, required
+ const runDialog = function(options) {
+
+ let confirmed = false;
+
+ const content = `\
+<div class="modal fade" role="dialog" tabindex='-1'>
+ <div class="modal-dialog">
+ <div class="modal-content">
+ <div class="modal-header">
+ <a class="close" data-dismiss="modal">×</a>
+ <h3>${options.title || "Confirm"}</h3>
+ </div>
+ <div class="modal-body">${options.message}</div>
+ <div class="modal-footer">
+ <button class="btn ${options.okClass || "btn-warning"}" data-dismiss="modal">${options.okLabel || "OK"}</button>
+ <button class="btn btn-default" data-dismiss="modal">${options.cancelLabel || "Cancel"}</button>
+ </div>
+ </div>
+ </div>
+</div>\
+`;
+
+ const $dialog = $(content);
+
+ $dialog.on("click", ".modal-footer button:first", function() {
+ confirmed = true;
+ });
+
+ // Let the animation run before (perhaps) invoking the callback.
+ $dialog.modal().on("hidden.bs.modal", function() {
+ $dialog.remove();
+ if (confirmed) {
+ return options.ok();
+ }
+ });
+
+ $dialog.appendTo($("body"));
+
+ // Focus on the first button (the "OK") button.
+ return $dialog.on("shown.bs.modal", () => $dialog.find(".modal-footer .btn").first().focus());
+ };
+
+ // Support for the Confirm mixin
+ $("body").on("click", "[data-confirm-message]:not(.disabled)", function(event){
+
+ const $this = $(this);
+
+ // We use a data- attribute as a flag, to indicate that the user confirmed the behavior.
+
+ if (($this.attr("data-confirm-state")) === "confirmed") {
+ $this.attr("data-confirm-state", null);
+ return; // allow default behavior to continue
+ }
+
+ runDialog({
+ title: $this.attr("data-confirm-title"),
+ message: $this.attr("data-confirm-message"),
+ okClass: $this.attr("data-confirm-class-ok"),
+ okLabel: $this.attr("data-confirm-label-ok"),
+ cancelLabel: $this.attr("data-confirm-label-cancel"),
+ ok() {
+ $this.attr("data-confirm-state", "confirmed");
+ // In the case of an Ajax update, or a button, this is enough. In the case of a simple link,
+ // the default behavior when triggering click() is to do nothing, and our document event handler
+ // (just below) picks up the slack.
+ return $this.click();
+ }
+ });
+
+ // Cancel the original click event
+ return false;
+ });
+
+ ($(document)).on("click", "a[data-confirm-message]:not(.disabled, [data-update-zone], [data-async-trigger])", function(event) {
+
+ const target = $(event.target);
+
+ // See note above; this replicates the default behavior of a link element that is lost because
+ // of the
+ window.location.href = target.attr("href");
+ return false;
+ });
+
+ // Exports:
+
+ return { runDialog };
+});
diff --git a/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/console.js b/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/console.js
index 1f0945697..a65bb3c2c 100644
--- a/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/console.js
+++ b/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/console.js
@@ -1,218 +1,250 @@
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http:#www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+/*
+ * decaffeinate suggestions:
+ * DS101: Remove unnecessary use of Array.from
+ * DS102: Remove unnecessary code created because of implicit returns
+ * DS207: Consider shorter variations of null checks
+ * Full docs: https://github.com/decaffeinate/decaffeinate/blob/main/docs/suggestions.md
+ */
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http:#www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// ## t5/core/console
+//
+// A wrapper around the native console, when it exists.
+define(["t5/core/dom", "underscore", "t5/core/bootstrap"],
+ function(dom, _, { glyph }) {
+
+ let e;
+ let nativeConsole = null;
+
+ try {
+ // FireFox will throw an exception if you even access the console object and it does
+ // not exist. Wow!
+ nativeConsole = window.console || {};
+ } catch (error) { e = error; }
+
+ let floatingConsole = null;
+ let messages = null;
+
+ const noFilter = () => true;
+
+ let filter = noFilter;
+
+ const updateFilter = function(text) {
+ if (text === "") {
+ filter = noFilter;
+ return;
+ }
+
+ const words = text.toLowerCase().split(/\s+/);
+
+ filter = function(e) {
+ const content = e.text().toLowerCase();
+
+ for (var word of Array.from(words)) {
+ if (content.indexOf(word) < 0) { return false; }
+ }
+
+ return true;
+ };
-# ## t5/core/console
-#
-# A wrapper around the native console, when it exists.
-define ["t5/core/dom", "underscore", "t5/core/bootstrap"],
- (dom, _, { glyph }) ->
+ };
- nativeConsole = null
+ const consoleAttribute = dom.body.attr("data-floating-console");
- try
- # FireFox will throw an exception if you even access the console object and it does
- # not exist. Wow!
- nativeConsole = window.console or {}
- catch e
+ const forceFloating = (consoleAttribute === "enabled") || (consoleAttribute === "invisible");
- floatingConsole = null
- messages = null
+ const button = function(action, icon, label, disabled) { if (disabled == null) { disabled = false; } return `\
+<button data-action="${action}" class="btn btn-default btn-mini">
+ ${glyph(icon)} ${label}
+</button>\
+`; };
- noFilter = -> true
+ // _internal_: displays the message inside the floating console, creating the floating
+ // console as needed.
+ const display = function(className, message) {
- filter = noFilter
+ if (!floatingConsole) {
+ floatingConsole = dom.create(
+ {class: "tapestry-console"},
+ `\
+<div class="message-container"></div>
+<div class="row">
+ <div class="btn-group btn-group-sm col-md-4">
+ ${button("clear", "remove", "Clear Console")}
+ ${button("enable", "play", "Enable Console")}
+ ${button("disable", "pause", "Disable Console")}
+ </div>
+ <div class="col-md-8">
+ <input class="form-control" size="40" placeholder="Filter console content">
+ </div>
+</div>\
+`
+ );
+
+ dom.body.prepend(floatingConsole);
+
+ // Basically, any non-blank value will enable the floating console. In addition, the special
+ // value "invisible" will enable it but then hide it ... this is useful in tests, since
+ // the console output is captured in the markup, but the visible console can have unwanted interactions
+ // (such as obscuring elements that make them unclickable).
+ if (consoleAttribute === "invisible") {
+ floatingConsole.hide();
+ }
+ }
+
+ messages = floatingConsole.findFirst(".message-container");
- updateFilter = (text) ->
- if text is ""
- filter = noFilter
- return
+ floatingConsole.findFirst("[data-action=enable]").attr("disabled", true);
- words = text.toLowerCase().split /\s+/
+ floatingConsole.on("click", "[data-action=clear]", function() {
+ floatingConsole.hide();
+ return messages.update("");
+ });
- filter = (e) ->
- content = e.text().toLowerCase()
+ floatingConsole.on("click", "[data-action=disable]", function() {
- for word in words
- return false if content.indexOf(word) < 0
+ this.attr("disabled", true);
+ floatingConsole.findFirst("[data-action=enable]").attr("disabled", false);
- return true
+ messages.hide();
- return
+ return false;
+ });
- consoleAttribute = dom.body.attr "data-floating-console"
+ floatingConsole.on("click", "[data-action=enable]", function() {
- forceFloating = (consoleAttribute is "enabled") or (consoleAttribute is "invisible")
+ this.attr("disabled", true);
+ floatingConsole.findFirst("[data-action=disable]").attr("disabled", false);
- button = (action, icon, label, disabled = false) -> """
- <button data-action="#{action}" class="btn btn-default btn-mini">
- #{glyph icon} #{label}
- </button>
- """
+ messages.show();
- # _internal_: displays the message inside the floating console, creating the floating
- # console as needed.
- display = (className, message) ->
+ return false;
+ });
- unless floatingConsole
- floatingConsole = dom.create
- class: "tapestry-console",
- """
- <div class="message-container"></div>
- <div class="row">
- <div class="btn-group btn-group-sm col-md-4">
- #{button "clear", "remove", "Clear Console"}
- #{button "enable", "play", "Enable Console"}
- #{button "disable", "pause", "Disable Console"}
- </div>
- <div class="col-md-8">
- <input class="form-control" size="40" placeholder="Filter console content">
- </div>
- </div>
- """
+ floatingConsole.on("change keyup", "input", function() {
+ updateFilter(this.value());
- dom.body.prepend floatingConsole
+ for (e of Array.from(messages.children())) {
+ var visible = filter(e);
- # Basically, any non-blank value will enable the floating console. In addition, the special
- # value "invisible" will enable it but then hide it ... this is useful in tests, since
- # the console output is captured in the markup, but the visible console can have unwanted interactions
- # (such as obscuring elements that make them unclickable).
- if consoleAttribute is "invisible"
- floatingConsole.hide()
+ e[visible ? "show" : "hide"]();
+ }
- messages = floatingConsole.findFirst ".message-container"
+ return false;
+ });
- floatingConsole.findFirst("[data-action=enable]").attr "disabled", true
+ const div = dom.create(
+ {class: className},
+ _.escape(message));
- floatingConsole.on "click", "[data-action=clear]", ->
- floatingConsole.hide()
- messages.update ""
+ // Should really filter on original message, not escaped.
- floatingConsole.on "click", "[data-action=disable]", ->
+ if (!filter(div)) {
+ div.hide();
+ }
- @attr "disabled", true
- floatingConsole.findFirst("[data-action=enable]").attr "disabled", false
+ messages.append(div);
- messages.hide()
+ // A slightly clumsy way to ensure that the container is scrolled to the bottom.
+ return _.delay(() => messages.element.scrollTop = messages.element.scrollHeight);
+ };
- return false
+ const level = (className, consolefn) => (function(message) {
+ // consolefn may be null if there's no console; under IE it may be non-null, but not a function.
+ // For some testing, it is nice to force the floating console to always display.
- floatingConsole.on "click", "[data-action=enable]", ->
+ if (forceFloating || (!consolefn)) {
+ // Display it floating. If there's a real problem, such as a failed Ajax request, then the
+ // client-side code should be alerting the user in some other way, and not rely on them
+ // being able to see the logged console output.
+ display(className, message);
- @attr "disabled", true
- floatingConsole.findFirst("[data-action=disable]").attr "disabled", false
+ if (!forceFloating) { return; }
+ }
- messages.show()
+ if (window.console && (_.isFunction(consolefn))) {
+ // Use the available native console, calling it like an instance method
+ consolefn.call(window.console, message);
+ return;
+ }
- return false
+ // And IE just has to be different. The properties of console are callable, like functions,
+ // but aren't proper functions that work with `call()` either.
+ // On IE8, the console object is undefined unless debugging tools are enabled.
+ // In that case, nativeConsole will be an empty object.
+ if (consolefn) {
+ consolefn(message);
+ }
- floatingConsole.on "change keyup", "input", ->
- updateFilter @value()
+ });
- for e in messages.children()
- visible = filter e
+ const exports = {
+ info: level("info", nativeConsole.info),
+ warn: level("warn", nativeConsole.warn),
+ error: level("error", nativeConsole.error),
- e[if visible then "show" else "hide"]()
+ // Determine whether debug is enabled by checking for the necessary attribute (which is missing
+ // in production mode).
+ debugEnabled: ((document.documentElement.getAttribute("data-debug-enabled")) != null)
+ };
- return false
+ const noop = function() {};
- div = dom.create
- class: className,
- _.escape message
-
- # Should really filter on original message, not escaped.
-
- unless filter div
- div.hide()
-
- messages.append div
-
- # A slightly clumsy way to ensure that the container is scrolled to the bottom.
- _.delay -> messages.element.scrollTop = messages.element.scrollHeight
-
- level = (className, consolefn) ->
- (message) ->
- # consolefn may be null if there's no console; under IE it may be non-null, but not a function.
- # For some testing, it is nice to force the floating console to always display.
-
- if forceFloating or (not consolefn)
- # Display it floating. If there's a real problem, such as a failed Ajax request, then the
- # client-side code should be alerting the user in some other way, and not rely on them
- # being able to see the logged console output.
- display className, message
-
- return unless forceFloating
-
- if window.console and (_.isFunction consolefn)
- # Use the available native console, calling it like an instance method
- consolefn.call window.console, message
- return
-
- # And IE just has to be different. The properties of console are callable, like functions,
- # but aren't proper functions that work with `call()` either.
- # On IE8, the console object is undefined unless debugging tools are enabled.
- # In that case, nativeConsole will be an empty object.
- if consolefn
- consolefn message
-
- return
-
- exports =
- info: level "info", nativeConsole.info
- warn: level "warn", nativeConsole.warn
- error: level "error", nativeConsole.error
-
- # Determine whether debug is enabled by checking for the necessary attribute (which is missing
- # in production mode).
- debugEnabled: (document.documentElement.getAttribute "data-debug-enabled")?
-
- noop = ->
-
- # When debugging is not enabled, then the debug function becomes a no-op.
+ // When debugging is not enabled, then the debug function becomes a no-op.
exports.debug =
- if exports.debugEnabled
- # If native console available, go for it. IE doesn't have debug, so we use log instead.
- # Add a special noop case for IE8, since IE8 is just crazy.
- level "debug", (nativeConsole.debug or nativeConsole.log or noop)
- else
- noop
+ exports.debugEnabled ?
+ // If native console available, go for it. IE doesn't have debug, so we use log instead.
+ // Add a special noop case for IE8, since IE8 is just crazy.
+ level("debug", (nativeConsole.debug || nativeConsole.log || noop))
+ :
+ noop;
- # This is also an aid to debugging; it allows arbitrary scripts to present on the console; when using Geb
- # and/or Selenium, it is very useful to present debugging data right on the page.
- window.t5console = exports
+ // This is also an aid to debugging; it allows arbitrary scripts to present on the console; when using Geb
+ // and/or Selenium, it is very useful to present debugging data right on the page.
+ window.t5console = exports;
- requirejs.onError = (err) ->
+ requirejs.onError = function(err) {
- message = "RequireJS error: #{err?.requireType or 'unknown'}"
+ let message = `RequireJS error: ${(err != null ? err.requireType : undefined) || 'unknown'}`;
- if err.message
- message += """: #{err.message}"""
+ if (err.message) {
+ message += `: ${err.message}`;
+ }
- if err.requireType
- modules = err?.requireModules
- if modules and modules.length > 0
- message += """, modules #{modules.join(", ")}"""
+ if (err.requireType) {
+ const modules = err != null ? err.requireModules : undefined;
+ if (modules && (modules.length > 0)) {
+ message += `, modules ${modules.join(", ")}`;
+ }
+ }
- if err.fileName
- message += """, #{err.fileName}"""
+ if (err.fileName) {
+ message += `, ${err.fileName}`;
+ }
- if err.lineNumber
- message += """, line #{err.lineNumber}"""
+ if (err.lineNumber) {
+ message += `, line ${err.lineNumber}`;
+ }
- if err.columnNumber
- message += """, line #{err.columnNumber}"""
+ if (err.columnNumber) {
+ message += `, line ${err.columnNumber}`;
+ }
- exports.error message
+ return exports.error(message);
+ };
- # Return the exports; we keep a reference to it, so we can see exports.DURATION, even
- # if some other module imports this one and modifies that property.
- return exports
\ No newline at end of file
+ // Return the exports; we keep a reference to it, so we can see exports.DURATION, even
+ // if some other module imports this one and modifies that property.
+ return exports;
+});
\ No newline at end of file
diff --git a/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/datefield.js b/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/datefield.js
index e4ea18f08..e0c01a6e3 100644
--- a/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/datefield.js
+++ b/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/datefield.js
@@ -1,180 +1,224 @@
-# Copyright 2012, 2013 The Apache Software Foundation
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http:#www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-# ## t5/core/datefield
-#
-# Provides support for the `core/DateField` component.
-define ["t5/core/dom", "t5/core/events", "t5/core/messages", "t5/core/ajax", "underscore", "t5/core/datepicker", "t5/core/fields"],
- (dom, events, messages, ajax, _, DatePicker) ->
-
-
- # Translate from the provided order (SUNDAY = 0, MONDAY = 1), to
- # the order needed by the DatePicker component (MONDAY = 0 ... SUNDAY = 6)
- serverFirstDay = parseInt messages "date-symbols.first-day"
- datePickerFirstDay = if serverFirstDay is 0 then 6 else serverFirstDay - 1
-
- # Localize a few other things.
- days = (messages "date-symbols.days").split ","
-
- # Shuffle sunday to the end, so that monday is first.
-
- days.push days.shift()
-
- monthsLabels = (messages "date-symbols.months").split ","
- abbreviateWeekDay = (name) -> name.substr(0, 1).toLowerCase()
- locale = (document.documentElement.getAttribute("data-locale")) || "en"
- if (locale.indexOf 'zh') is 0
- # TAP5-1886, Chinese weekdays cannot be abbreviated using the first character
- abbreviateWeekDay = (name) -> name.substr(name.length-1)
- daysLabels = (abbreviateWeekDay name for name in days)
- todayLabel = messages "core-datefield-today"
- noneLabel = messages "core-datefield-none"
-
-
- # Track the active popup; only one allowed at a time. May look to rework this
- # later so that there's just one popup and it is moved around the viewport, or
- # around the DOM.
- activePopup = null
-
-
- isPartOfPopup = (element) ->
- element.findParent(".labelPopup")? or element.findParent(".datefield-popup")?
-
- dom.body.on "click", ->
- if activePopup and not isPartOfPopup @
- activePopup.hide()
- activePopup = null
- return
-
-
- class Controller
- constructor: (@container) ->
- @field = @container.findFirst 'input:not([name="t:formdata"])'
- @trigger = @container.findFirst "button"
-
- @trigger.on "click", =>
- @doTogglePopup()
- false
-
- showPopup: ->
- if activePopup and activePopup isnt @popup
- activePopup.hide()
-
- @popup.show()
- activePopup = @popup
-
- hidePopup: ->
- @popup.hide()
- activePopup = null
-
- doTogglePopup: ->
- return if @field.element.disabled
-
- unless @popup
- @createPopup()
- activePopup?.hide()
- else if @popup.visible()
- @hidePopup()
- return
-
- value = @field.value()
-
- if value is ""
- @datePicker.setDate null
- @showPopup()
- return
-
- @field.addClass "ajax-wait"
-
- ajax (@container.attr "data-parse-url"),
- data:
+/*
+ * decaffeinate suggestions:
+ * DS101: Remove unnecessary use of Array.from
+ * DS102: Remove unnecessary code created because of implicit returns
+ * DS205: Consider reworking code to avoid use of IIFEs
+ * DS207: Consider shorter variations of null checks
+ * Full docs: https://github.com/decaffeinate/decaffeinate/blob/main/docs/suggestions.md
+ */
+// Copyright 2012, 2013 The Apache Software Foundation
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http:#www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// ## t5/core/datefield
+//
+// Provides support for the `core/DateField` component.
+define(["t5/core/dom", "t5/core/events", "t5/core/messages", "t5/core/ajax", "underscore", "t5/core/datepicker", "t5/core/fields"],
+ function(dom, events, messages, ajax, _, DatePicker) {
+
+
+ // Translate from the provided order (SUNDAY = 0, MONDAY = 1), to
+ // the order needed by the DatePicker component (MONDAY = 0 ... SUNDAY = 6)
+ let name;
+ const serverFirstDay = parseInt(messages("date-symbols.first-day"));
+ const datePickerFirstDay = serverFirstDay === 0 ? 6 : serverFirstDay - 1;
+
+ // Localize a few other things.
+ const days = (messages("date-symbols.days")).split(",");
+
+ // Shuffle sunday to the end, so that monday is first.
+
+ days.push(days.shift());
+
+ const monthsLabels = (messages("date-symbols.months")).split(",");
+ let abbreviateWeekDay = name => name.substr(0, 1).toLowerCase();
+ const locale = (document.documentElement.getAttribute("data-locale")) || "en";
+ if ((locale.indexOf('zh')) === 0) {
+ // TAP5-1886, Chinese weekdays cannot be abbreviated using the first character
+ abbreviateWeekDay = name => name.substr(name.length-1);
+ }
+ const daysLabels = ((() => {
+ const result = [];
+ for (name of Array.from(days)) { result.push(abbreviateWeekDay(name));
+ }
+ return result;
+ })());
+ const todayLabel = messages("core-datefield-today");
+ const noneLabel = messages("core-datefield-none");
+
+
+ // Track the active popup; only one allowed at a time. May look to rework this
+ // later so that there's just one popup and it is moved around the viewport, or
+ // around the DOM.
+ let activePopup = null;
+
+
+ const isPartOfPopup = element => (element.findParent(".labelPopup") != null) || (element.findParent(".datefield-popup") != null);
+
+ dom.body.on("click", function() {
+ if (activePopup && !isPartOfPopup(this)) {
+ activePopup.hide();
+ activePopup = null;
+ }
+ });
+
+
+ class Controller {
+ constructor(container) {
+ this.container = container;
+ this.field = this.container.findFirst('input:not([name="t:formdata"])');
+ this.trigger = this.container.findFirst("button");
+
+ this.trigger.on("click", () => {
+ this.doTogglePopup();
+ return false;
+ });
+ }
+
+ showPopup() {
+ if (activePopup && (activePopup !== this.popup)) {
+ activePopup.hide();
+ }
+
+ this.popup.show();
+ return activePopup = this.popup;
+ }
+
+ hidePopup() {
+ this.popup.hide();
+ return activePopup = null;
+ }
+
+ doTogglePopup() {
+ if (this.field.element.disabled) { return; }
+
+ if (!this.popup) {
+ this.createPopup();
+ if (activePopup != null) {
+ activePopup.hide();
+ }
+ } else if (this.popup.visible()) {
+ this.hidePopup();
+ return;
+ }
+
+ const value = this.field.value();
+
+ if (value === "") {
+ this.datePicker.setDate(null);
+ this.showPopup();
+ return;
+ }
+
+ this.field.addClass("ajax-wait");
+
+ return ajax((this.container.attr("data-parse-url")), {
+ data: {
input: value
- onerror: (message) =>
- @field.removeClass "ajax-wait"
- @fieldError message
+ },
+ onerror: message => {
+ this.field.removeClass("ajax-wait");
+ this.fieldError(message);
- @showPopup()
- return
+ this.showPopup();
+ },
- success: (response) =>
- @field.removeClass "ajax-wait"
- reply = response.json
+ success: response => {
+ this.field.removeClass("ajax-wait");
+ const reply = response.json;
- if reply.result
- @clearFieldError()
- [year, month, day] = reply.result.split '-'
+ if (reply.result) {
+ this.clearFieldError();
+ const [year, month, day] = Array.from(reply.result.split('-'));
- date = new Date year, month-1, day
- @datePicker.setDate date
+ const date = new Date(year, month-1, day);
+ this.datePicker.setDate(date);
+ }
- if reply.error
- @fieldError (_.escape reply.error)
+ if (reply.error) {
+ this.fieldError((_.escape(reply.error)));
- @datePicker.setDate null
+ this.datePicker.setDate(null);
+ }
- @showPopup()
- return
+ this.showPopup();
+ }
+ }
+ );
+ }
- fieldError: (message) ->
- @field.focus().trigger events.field.showValidationError, { message }
+ fieldError(message) {
+ return this.field.focus().trigger(events.field.showValidationError, { message });
+ }
- clearFieldError: ->
- @field.trigger events.field.clearValidationError
+ clearFieldError() {
+ return this.field.trigger(events.field.clearValidationError);
+ }
- createPopup: ->
- @datePicker = new DatePicker()
- @datePicker.setFirstWeekDay datePickerFirstDay
+ createPopup() {
+ this.datePicker = new DatePicker();
+ this.datePicker.setFirstWeekDay(datePickerFirstDay);
- @datePicker.setLocalizations monthsLabels, daysLabels, todayLabel, noneLabel
+ this.datePicker.setLocalizations(monthsLabels, daysLabels, todayLabel, noneLabel);
- @popup = dom.create("div", { class: "datefield-popup well"}).append @datePicker.create()
- @container.insertAfter @popup
+ this.popup = dom.create("div", { class: "datefield-popup well"}).append(this.datePicker.create());
+ this.container.insertAfter(this.popup);
- @datePicker.onselect = _.bind @onSelect, this
+ return this.datePicker.onselect = _.bind(this.onSelect, this);
+ }
- onSelect: ->
- date = @datePicker.getDate()
+ onSelect() {
+ const date = this.datePicker.getDate();
- if date is null
- @hidePopup()
- @clearFieldError()
- @field.value ""
- return
+ if (date === null) {
+ this.hidePopup();
+ this.clearFieldError();
+ this.field.value("");
+ return;
+ }
- @field.addClass "ajax-wait"
+ this.field.addClass("ajax-wait");
- normalizedFormat = "#{date.getFullYear()}-#{date.getMonth()+1}-#{date.getDate()}"
- ajax (@container.attr "data-format-url"),
- data:
+ const normalizedFormat = `${date.getFullYear()}-${date.getMonth()+1}-${date.getDate()}`;
+ return ajax((this.container.attr("data-format-url")), {
+ data: {
input: normalizedFormat
- failure: (response, message) =>
- @field.removeClass "ajax-wait"
- @fieldError message
- success: (response) =>
- @field.removeClass "ajax-wait"
- @clearFieldError()
- @field.value response.json.result
- @hidePopup()
-
-
- # Initialization:
-
- dom.scanner "[data-component-type='core/DateField']", (container) ->
- # Hide it from later scans
- container.attr "data-component-type", null
-
- new Controller(container)
-
- # Exports nothing.
- return null
+ },
+ failure: (response, message) => {
+ this.field.removeClass("ajax-wait");
+ return this.fieldError(message);
+ },
+ success: response => {
+ this.field.removeClass("ajax-wait");
+ this.clearFieldError();
+ this.field.value(response.json.result);
+ return this.hidePopup();
+ }
+ }
+ );
+ }
+ }
+
+
+ // Initialization:
+
+ dom.scanner("[data-component-type='core/DateField']", function(container) {
+ // Hide it from later scans
+ container.attr("data-component-type", null);
+
+ return new Controller(container);
+ });
+
+ // Exports nothing.
+ return null;
+});
diff --git a/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/events.js b/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/events.js
index ec7da0bf8..9a2588a46 100644
--- a/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/events.js
+++ b/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/events.js
@@ -1,187 +1,194 @@
-# Copyright 2012-2014 The Apache Software Foundation
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http:#www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-# ## t5/core/events
-#
-# This module defines logical names for all events that Tapestry-controlled elements
-# trigger or listener for. Prototype requires that all custom events have a namespace prefix; jQuery appears to
-# allow it without issue.
-define
-
- # Defines events related to the validation and submission of forms. See module `t5/core/forms` for further details.
- # All events are triggered on a specific HTML `<form>` element, and top-level handlers take it from there.
- form:
- # Triggered after fields have been validated, when there are no field validation exceptions, to allow for
- # cross-form validation. Passed a memo object: the handler should set the `error` property of the memo
- # to true to indicate a validation exception occured, and the form submission should be prevented.
- validate: "t5:form:validate"
-
- # Triggered after fields and form have been validated, when there are field or form validation exceptions.
- validateInError: "t5:form:validateInError"
-
- # Triggered after `validate` (when there are no prior validation exceptions), to allow certain elements
- # to configure themselves immediately before the form is submitted. This exists primarily for components such
- # as FormFragment, which will enable or disable a hidden field to match the visibility of the fragment.
- # There is no event memo.
+// Copyright 2012-2014 The Apache Software Foundation
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http:#www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// ## t5/core/events
+//
+// This module defines logical names for all events that Tapestry-controlled elements
+// trigger or listener for. Prototype requires that all custom events have a namespace prefix; jQuery appears to
+// allow it without issue.
+define({
+
+ // Defines events related to the validation and submission of forms. See module `t5/core/forms` for further details.
+ // All events are triggered on a specific HTML `<form>` element, and top-level handlers take it from there.
+ form: {
+ // Triggered after fields have been validated, when there are no field validation exceptions, to allow for
+ // cross-form validation. Passed a memo object: the handler should set the `error` property of the memo
+ // to true to indicate a validation exception occured, and the form submission should be prevented.
+ validate: "t5:form:validate",
+
+ // Triggered after fields and form have been validated, when there are field or form validation exceptions.
+ validateInError: "t5:form:validateInError",
+
+ // Triggered after `validate` (when there are no prior validation exceptions), to allow certain elements
+ // to configure themselves immediately before the form is submitted. This exists primarily for components such
+ // as FormFragment, which will enable or disable a hidden field to match the visibility of the fragment.
+ // There is no event memo.
prepareForSubmit: "t5:form:prepare-for-submit"
-
- # Events releated to form input fields. Primarily, these events are related to form input validation.
- # Validating a field involves three major steps:
- #
- # * optional - check for a required field that has no value
- # * translate - translate a string to another representation, such as `Date`, or a number
- # * validate - validate the field against any number of other constraints (such as ranges)
- #
- # A field that is blank but not required is considered valid: the translate and validate steps are skipped.
- #
- # When a validation error occurs, the event handler should present the validation error (see below), but also
- # return `false`. This will prevent the event from propogating to other event handlers (Tapestry only supports
- # a single validation exception per field).
- #
- # Presenting validation error: The event handler has two options for indicating a validation failure
- # at any of the three steps:
- #
- # * set the `error` property of the memo to true, and trigger the `showValidationError` event (or otherwise
- # make the validation error visible)
- # * set the `error` property of the memo to the message to display; this will indicate a failure, and the
- # `showValidationError` event will be triggered automatically.
- # * In addition, return `false` to prevent the event bubbling (see note above).
- field:
-
- # Perform the optionality check. The event memo includes a `value` property. If the field is required
- # but the value is blank, then a validation error should be presented (as described above). The `value`
- # property of the memo is as described for the `translate` event.
- optional: "t5:field:optional"
-
- # Trigged by the field if there is a field value (a non-empty string, or a non-empty array in the case
- # of a select element). The event memo includes the field's value as the `value` property.
- # For text fields, the value is the text inside the field. For select elements, it is an array of the values
- # of selected options. If the element has the attribute `data-value-mode` set to 'options', then the
- # value will be the array of all options (selected or not; this is provided for the core/Palette Tapestry
- # component).
- #
- # An event handler may update the event, setting the `translated` property to an alternate formatting, or
- # alternate representation (e.g., `Date`, or a number) for the input value. If the input can not be translated,
- # then a validation error should be presented (as described above).
- translate: "t5:field:translate"
-
- # Triggered by the field if there is a field value, and the `translate` event succeeded. The event memo
- # includes a `value' property, and a `translated` property. If any constraints on the field are invalid,
- # then the event handler should be presented (as described above).
- validate: "t5:field:validate"
-
- # Triggered by the form on all enclosed elements with the `data-validation` attribute (indicating they are
- # interested in participating with user input validation). The default implementation fires a series of
- # events: `optional`, `translate`, `validate`. The latter two are always skipped if the input is blank, or if
- # a preceding event set the memo's `error` property to true. If all events complete without setting an error,
- # then the `clearValidationError` event is triggered, to remove any validation errors from previous
- # validation cycles.
- #
- # This event is passed a memo object; it should set the memo's `error` property to true if validation failed
- # for the field.
- inputValidation: "t5:field:input-validation"
-
- # Clears and hides the element used to display validation error messages. There is no memo for
- # this event. The p.help-block for the field is located (if it exists) and emptied and hidden.
- # The containing .form-group element (if it exists) has its "has-error" class name removed.
- clearValidationError: "t5:field:clear-validation-error"
-
- # Presents a validation error for a field. The event memo should have a `message` key; the message to present
- # (as a string, or even as a detached DOM element). The help block for the field will be located or created,
- # made visible, and have its content updated to `memo.message`. If a containing element has the class ".form-group",
- # then the class "has-error" will be added; otherwise, the immediately containing element will have class "has-error"
- # added. The latter handles the case where, for layout reasons, the error container can not be inside the same
- # .form-group as the form control (this often happens when constructing horizontal forms).
- #
- # The rules for locating the help block:
- #
- # * Search for element with attribute `data-error-block-for` set to the field's `id` attribute
- # * If not found, find the enclosing .form-group element
- # * Search the form group for an element with attribute `data-presentation="error"`
- # * Otherwise, it is not found (but may be created dynamically)
- # * If found, set the `data-error-block-for` attribute to the field's `id` (assigning a unique id to the field
- # if not already present)
- #
- # The rules for creating the help block:
- #
- # * The element is created as `p.help-block` with `data-error-block-for` attribute set to the
- # field's id. The field will be assigned an id if necesary.
- # * Normally, the block is inserted immediately after the field
- # * If the field's immediate container has class "input-group", then the block is inserted after the container
+ },
+
+ // Events releated to form input fields. Primarily, these events are related to form input validation.
+ // Validating a field involves three major steps:
+ //
+ // * optional - check for a required field that has no value
+ // * translate - translate a string to another representation, such as `Date`, or a number
+ // * validate - validate the field against any number of other constraints (such as ranges)
+ //
+ // A field that is blank but not required is considered valid: the translate and validate steps are skipped.
+ //
+ // When a validation error occurs, the event handler should present the validation error (see below), but also
+ // return `false`. This will prevent the event from propogating to other event handlers (Tapestry only supports
+ // a single validation exception per field).
+ //
+ // Presenting validation error: The event handler has two options for indicating a validation failure
+ // at any of the three steps:
+ //
+ // * set the `error` property of the memo to true, and trigger the `showValidationError` event (or otherwise
+ // make the validation error visible)
+ // * set the `error` property of the memo to the message to display; this will indicate a failure, and the
+ // `showValidationError` event will be triggered automatically.
+ // * In addition, return `false` to prevent the event bubbling (see note above).
+ field: {
+
+ // Perform the optionality check. The event memo includes a `value` property. If the field is required
+ // but the value is blank, then a validation error should be presented (as described above). The `value`
+ // property of the memo is as described for the `translate` event.
+ optional: "t5:field:optional",
+
+ // Trigged by the field if there is a field value (a non-empty string, or a non-empty array in the case
+ // of a select element). The event memo includes the field's value as the `value` property.
+ // For text fields, the value is the text inside the field. For select elements, it is an array of the values
+ // of selected options. If the element has the attribute `data-value-mode` set to 'options', then the
+ // value will be the array of all options (selected or not; this is provided for the core/Palette Tapestry
+ // component).
+ //
+ // An event handler may update the event, setting the `translated` property to an alternate formatting, or
+ // alternate representation (e.g., `Date`, or a number) for the input value. If the input can not be translated,
+ // then a validation error should be presented (as described above).
+ translate: "t5:field:translate",
+
+ // Triggered by the field if there is a field value, and the `translate` event succeeded. The event memo
+ // includes a `value' property, and a `translated` property. If any constraints on the field are invalid,
+ // then the event handler should be presented (as described above).
+ validate: "t5:field:validate",
+
+ // Triggered by the form on all enclosed elements with the `data-validation` attribute (indicating they are
+ // interested in participating with user input validation). The default implementation fires a series of
+ // events: `optional`, `translate`, `validate`. The latter two are always skipped if the input is blank, or if
+ // a preceding event set the memo's `error` property to true. If all events complete without setting an error,
+ // then the `clearValidationError` event is triggered, to remove any validation errors from previous
+ // validation cycles.
+ //
+ // This event is passed a memo object; it should set the memo's `error` property to true if validation failed
+ // for the field.
+ inputValidation: "t5:field:input-validation",
+
+ // Clears and hides the element used to display validation error messages. There is no memo for
+ // this event. The p.help-block for the field is located (if it exists) and emptied and hidden.
+ // The containing .form-group element (if it exists) has its "has-error" class name removed.
+ clearValidationError: "t5:field:clear-validation-error",
+
+ // Presents a validation error for a field. The event memo should have a `message` key; the message to present
+ // (as a string, or even as a detached DOM element). The help block for the field will be located or created,
+ // made visible, and have its content updated to `memo.message`. If a containing element has the class ".form-group",
+ // then the class "has-error" will be added; otherwise, the immediately containing element will have class "has-error"
+ // added. The latter handles the case where, for layout reasons, the error container can not be inside the same
+ // .form-group as the form control (this often happens when constructing horizontal forms).
+ //
+ // The rules for locating the help block:
+ //
+ // * Search for element with attribute `data-error-block-for` set to the field's `id` attribute
+ // * If not found, find the enclosing .form-group element
+ // * Search the form group for an element with attribute `data-presentation="error"`
+ // * Otherwise, it is not found (but may be created dynamically)
+ // * If found, set the `data-error-block-for` attribute to the field's `id` (assigning a unique id to the field
+ // if not already present)
+ //
+ // The rules for creating the help block:
+ //
+ // * The element is created as `p.help-block` with `data-error-block-for` attribute set to the
+ // field's id. The field will be assigned an id if necesary.
+ // * Normally, the block is inserted immediately after the field
+ // * If the field's immediate container has class "input-group", then the block is inserted after the container
showValidationError: "t5:field:show-validation-error"
-
- # Events triggered by the Palette component.
- palette:
- # Event triggered when the selection is about to change.
- #
- # * memo.selectedOptions - array of selected options (e.g., HTMLOptionElement) representing which options
- # will be selected in the Palette, should the change be allowed.
- # * memo.reorder - if true, then the event represents changing the order of the selections only
- # * memo.cancel - function to invoke to prevent the change to the Palette from occurring
- # * memo.defer - like cancel, but returns a no-arguments function that will perform the update at a later date (e.g.,
- # after a confirmation panel)
- willChange: "t5:palette:willChange"
- # Event triggered after the Palette selection has changed.
- #
- # * memo.selectedOptions - array of selected options (e.g., HTMLOptionElement)
- # * memo.reorder - if true, the event represents a change in the order of selections only
+ },
+
+ // Events triggered by the Palette component.
+ palette: {
+ // Event triggered when the selection is about to change.
+ //
+ // * memo.selectedOptions - array of selected options (e.g., HTMLOptionElement) representing which options
+ // will be selected in the Palette, should the change be allowed.
+ // * memo.reorder - if true, then the event represents changing the order of the selections only
+ // * memo.cancel - function to invoke to prevent the change to the Palette from occurring
+ // * memo.defer - like cancel, but returns a no-arguments function that will perform the update at a later date (e.g.,
+ // after a confirmation panel)
+ willChange: "t5:palette:willChange",
+ // Event triggered after the Palette selection has changed.
+ //
+ // * memo.selectedOptions - array of selected options (e.g., HTMLOptionElement)
+ // * memo.reorder - if true, the event represents a change in the order of selections only
didChange: "t5:palette:didChange"
-
- # Defines a number of event names specific to Tapestry Zones. Zones are Tapestry components that are structured
- # to correctly support dynamic updates from the server via an Ajax request, and a standard response
- # (the partial page render reponse). More details are available in the `t5/core/zone` module.
- zone:
- # Invoked on a zone element to force an update to its content. The event memo should contain a `content` key (an
- # Element, or a `t5/core/dom:ElementWrapper`, or more typically, a string containing HTML markup). A standard top-level
- # handler is defined by module `t5/core/zone`, and is responsible for the actual update; it triggers the
- # `events.zone.willUpdate` and `events.zone.didUpdate` events just before and just after changing the element's
- # content.
- update: "t5:zone:update"
-
- # Triggered (by the standard `events.zone.update` event handler) just before the content in a Zone will be updated.
- willUpdate: "t5:zone:will-update"
-
- # Triggered (by the standard `events.zone.update` event handle) just after the content in a Zone has updated.
- # If the zone was not visible, it is made visible after its content is changed, and before this event is triggered.
- # Some number of other components that also perform Ajax updates of the page also trigger this event.
- #
- # Certain components bind this event to scan new additions to the page to see if certain structures exist and
- # create client-side support in the form of controllers and event handlers. DateField is one such example
- # (see `t5/core/datefield` module).
- didUpdate: "t5:zone:did-update"
-
- # Triggered on (or within) a zone element, the default handler will peform an Ajax request and, when the response is available,
- # update the zone (via `events.zone.update`). The request should provide a partial page render response. If the
- # response includes a `content` key, its value will be the markup to replace the zone element's body.
- #
- # * memo.url - URL to use for the Ajax request
- # * memo.parameters - (optional) additional query parameters for the request
+ },
+
+ // Defines a number of event names specific to Tapestry Zones. Zones are Tapestry components that are structured
+ // to correctly support dynamic updates from the server via an Ajax request, and a standard response
+ // (the partial page render reponse). More details are available in the `t5/core/zone` module.
+ zone: {
+ // Invoked on a zone element to force an update to its content. The event memo should contain a `content` key (an
+ // Element, or a `t5/core/dom:ElementWrapper`, or more typically, a string containing HTML markup). A standard top-level
+ // handler is defined by module `t5/core/zone`, and is responsible for the actual update; it triggers the
+ // `events.zone.willUpdate` and `events.zone.didUpdate` events just before and just after changing the element's
+ // content.
+ update: "t5:zone:update",
+
+ // Triggered (by the standard `events.zone.update` event handler) just before the content in a Zone will be updated.
+ willUpdate: "t5:zone:will-update",
+
+ // Triggered (by the standard `events.zone.update` event handle) just after the content in a Zone has updated.
+ // If the zone was not visible, it is made visible after its content is changed, and before this event is triggered.
+ // Some number of other components that also perform Ajax updates of the page also trigger this event.
+ //
+ // Certain components bind this event to scan new additions to the page to see if certain structures exist and
+ // create client-side support in the form of controllers and event handlers. DateField is one such example
+ // (see `t5/core/datefield` module).
+ didUpdate: "t5:zone:did-update",
+
+ // Triggered on (or within) a zone element, the default handler will peform an Ajax request and, when the response is available,
+ // update the zone (via `events.zone.update`). The request should provide a partial page render response. If the
+ // response includes a `content` key, its value will be the markup to replace the zone element's body.
+ //
+ // * memo.url - URL to use for the Ajax request
+ // * memo.parameters - (optional) additional query parameters for the request
refresh: "t5:zone:refresh"
-
- # Event names for arbitrary elements. These notifications exist primarily to allow for customizations in how
- # certain behaviors are presented, for example, to add animation when certain elements are hidden or revealed.
- element:
- # Triggered when a hidden element has just been displayed.
- didShow: "t5:element:did-show"
- # Trigered when a visible element has just been hidden.
+ },
+
+ // Event names for arbitrary elements. These notifications exist primarily to allow for customizations in how
+ // certain behaviors are presented, for example, to add animation when certain elements are hidden or revealed.
+ element: {
+ // Triggered when a hidden element has just been displayed.
+ didShow: "t5:element:did-show",
+ // Trigered when a visible element has just been hidden.
didHide: "t5:element:did-hide"
- # Event names specific to client-side element associated with the FormFragment component. These events exist to allow
- # client code to cleanly adjust the visibility of the fragment, or remove it.
- formfragment:
- # Requests that the fragment change its visibility. The event memo is an object with a single key, visible, a
- # boolean. The fragment will show or hide itself if necessary (triggering the `element.didShow` or
- # `element.didHide` event).
+ },
+ // Event names specific to client-side element associated with the FormFragment component. These events exist to allow
+ // client code to cleanly adjust the visibility of the fragment, or remove it.
+ formfragment: {
+ // Requests that the fragment change its visibility. The event memo is an object with a single key, visible, a
+ // boolean. The fragment will show or hide itself if necessary (triggering the `element.didShow` or
+ // `element.didHide` event).
changeVisibility: "t5:fragment:change-visibility"
- # Event to scan inserted DOM content for components to initialize (see t5/core/dom:scanner)
+ },
+ // Event to scan inserted DOM content for components to initialize (see t5/core/dom:scanner)
initializeComponents : "t5:initializeComponents"
+});
diff --git a/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/exception-display.js b/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/exception-display.js
index 5559c07d9..1cb89f044 100644
--- a/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/exception-display.js
+++ b/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/exception-display.js
@@ -1,30 +1,39 @@
-# Copyright 2012-2013 The Apache Software Foundation
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http:#www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+/*
+ * decaffeinate suggestions:
+ * DS101: Remove unnecessary use of Array.from
+ * Full docs: https://github.com/decaffeinate/decaffeinate/blob/main/docs/suggestions.md
+ */
+// Copyright 2012-2013 The Apache Software Foundation
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http:#www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
-# ## t5/core/exception-display
-#
-# Provides dynamic behavior for the t5/core/ExceptionDisplay component; specifically,
-# filtering the stack trace.
-define ["t5/core/dom"],
- (dom) ->
+// ## t5/core/exception-display
+//
+// Provides dynamic behavior for the t5/core/ExceptionDisplay component; specifically,
+// filtering the stack trace.
+define(["t5/core/dom"],
+ function(dom) {
- dom.onDocument "click", "[data-behavior=stack-trace-filter-toggle]", ->
- checked = @element.checked
+ dom.onDocument("click", "[data-behavior=stack-trace-filter-toggle]", function() {
+ const {
+ checked
+ } = this.element;
- for traceList in dom.body.find ".stack-trace"
- traceList[if checked then "addClass" else "removeClass"] "filtered"
+ for (var traceList of Array.from(dom.body.find(".stack-trace"))) {
+ traceList[checked ? "addClass" : "removeClass"]("filtered");
+ }
- return
+ });
- return null
+ return null;
+});
diff --git a/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/exception-frame.js b/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/exception-frame.js
index f587ecc4e..25c73a459 100644
--- a/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/exception-frame.js
+++ b/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/exception-frame.js
@@ -1,64 +1,75 @@
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http:#www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+/*
+ * decaffeinate suggestions:
+ * DS102: Remove unnecessary code created because of implicit returns
+ * Full docs: https://github.com/decaffeinate/decaffeinate/blob/main/docs/suggestions.md
+ */
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http:#www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
-# ## t5/core/exception-frame
-#
-# Manages a special element used to present an HTML exception report from an Ajax request (where a non-markup response
-# was expected, including a partial page render response).
-define ["t5/core/dom"], (dom) ->
+// ## t5/core/exception-frame
+//
+// Manages a special element used to present an HTML exception report from an Ajax request (where a non-markup response
+// was expected, including a partial page render response).
+define(["t5/core/dom"], function(dom) {
- write = (container, content) ->
- iframe = (container.findFirst "iframe").element
+ const write = function(container, content) {
+ const iframe = (container.findFirst("iframe")).element;
- # See http://xkr.us/articles/dom/iframe-document/
+ // See http://xkr.us/articles/dom/iframe-document/
- iframeDocument = iframe.contentWindow or iframe.contentDocument
- if iframeDocument.document
- iframeDocument = iframeDocument.document
+ let iframeDocument = iframe.contentWindow || iframe.contentDocument;
+ if (iframeDocument.document) {
+ iframeDocument = iframeDocument.document;
+ }
- # Clear current content:
- iframeDocument.open()
- # Write new content:
- iframeDocument.write content
- iframeDocument.close()
+ // Clear current content:
+ iframeDocument.open();
+ // Write new content:
+ iframeDocument.write(content);
+ return iframeDocument.close();
+ };
- clear = ->
- container = @closest '.exception-container'
- container.remove()
- return false
+ const clear = function() {
+ const container = this.closest('.exception-container');
+ container.remove();
+ return false;
+ };
- create = ->
+ const create = function() {
- container = dom.create
- class: "exception-container"
- """
- <iframe> </iframe>
- <div>
- <button class="pull-right btn btn-primary">
- <i class="icon-remove icon-white"></i>
- Close
- </button>
- </div>
- """
+ const container = dom.create(
+ {class: "exception-container"},
+ `\
+<iframe> </iframe>
+<div>
+ <button class="pull-right btn btn-primary">
+ <i class="icon-remove icon-white"></i>
+ Close
+ </button>
+</div>\
+`
+ );
- dom.body.append container.hide()
+ dom.body.append(container.hide());
- container.on "click", "button", clear
- container
+ container.on("click", "button", clear);
+ return container;
+ };
- # Export single function:
+ // Export single function:
- (exceptionContent) ->
- container = create()
- write container, exceptionContent
- container.show()
- return
\ No newline at end of file
+ return function(exceptionContent) {
+ const container = create();
+ write(container, exceptionContent);
+ container.show();
+ };
+});
\ No newline at end of file
diff --git a/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/fields.js b/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/fields.js
index a43dc61f7..2c9d085a6 100644
--- a/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/fields.js
+++ b/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/fields.js
@@ -1,195 +1,220 @@
-# Copyright 2012-2013 The Apache Software Foundation
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http:#www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-# ## t5/core/fields
-#
-# Module for logic relating to form input fields (input, select, textarea); specifically
-# presenting validation errors and perfoming input validation when necessary.
-define ["underscore", "t5/core/events", "t5/core/dom", "t5/core/utils", "t5/core/forms"],
- (_, events, dom, utils) ->
-
- ensureFieldId = (field) ->
- fieldId = field.attr "id"
-
- unless fieldId
- fieldId = _.uniqueId "field"
- field.attr "id", fieldId
-
- return fieldId
-
- # Finds any `.help-block` used for presenting errors for the provided field.
- # Returns the found block(s) as an array of ElementWrapper. Returns null
- # if no blocks can be found.
- #
- # Normally, you would expect just a single help block for a field, but in some cases,
- # such as to support responsive layout, there will be multiple help blocks for a single field.
- #
- # * field - element wrapper for the field
- findHelpBlocks = (field) ->
- fieldId = field.attr "id"
-
- # When the field has an id (the normal case!), search the body for
- # the matching help blocks.
- if fieldId
- blocks = dom.body.find "[data-error-block-for='#{fieldId}']"
-
- return blocks if blocks.length > 0
- else
- # Assign a unique (hopefully!) client id for the field, which will be
- # used to link the field and the new help-block together.
- fieldId = ensureFieldId field
-
- # Not found by id, but see if an empty placeholder was provided within
- # the same .form-group.
-
- group = field.findParent ".form-group"
-
- return null unless group
-
- # This happens less often, now that the Errors component ensures (at render time)
- # a fieldId and a data-error-block-for element. Even so, sometimes a template
- # will just contain a div.help-block[data-presentation=error]
- block = group.findFirst "[data-presentation=error]"
-
- if block
- block.attr "data-error-block-for", fieldId
- return [block]
-
- # Not found, so perhaps it will be created dynamically.
- return null
-
- createHelpBlock = (field) ->
- fieldId = ensureFieldId field
-
- # No containing group ... this is a problem, probably an old 5.3 application upgraded to 5.4
- # or beyond. Place the block just after the field.
-
- container = field.parent()
-
- block = dom.create "p",
- class: "help-block form-text text-danger"
- "data-error-block-for": fieldId
+/*
+ * decaffeinate suggestions:
+ * DS101: Remove unnecessary use of Array.from
+ * DS102: Remove unnecessary code created because of implicit returns
+ * Full docs: https://github.com/decaffeinate/decaffeinate/blob/main/docs/suggestions.md
+ */
+// Copyright 2012-2013 The Apache Software Foundation
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http:#www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// ## t5/core/fields
+//
+// Module for logic relating to form input fields (input, select, textarea); specifically
+// presenting validation errors and perfoming input validation when necessary.
+define(["underscore", "t5/core/events", "t5/core/dom", "t5/core/utils", "t5/core/forms"],
+ function(_, events, dom, utils) {
+
+ let exports;
+ const ensureFieldId = function(field) {
+ let fieldId = field.attr("id");
+
+ if (!fieldId) {
+ fieldId = _.uniqueId("field");
+ field.attr("id", fieldId);
+ }
+
+ return fieldId;
+ };
+
+ // Finds any `.help-block` used for presenting errors for the provided field.
+ // Returns the found block(s) as an array of ElementWrapper. Returns null
+ // if no blocks can be found.
+ //
+ // Normally, you would expect just a single help block for a field, but in some cases,
+ // such as to support responsive layout, there will be multiple help blocks for a single field.
+ //
+ // * field - element wrapper for the field
+ const findHelpBlocks = function(field) {
+ let fieldId = field.attr("id");
+
+ // When the field has an id (the normal case!), search the body for
+ // the matching help blocks.
+ if (fieldId) {
+ const blocks = dom.body.find(`[data-error-block-for='${fieldId}']`);
+
+ if (blocks.length > 0) { return blocks; }
+ } else {
+ // Assign a unique (hopefully!) client id for the field, which will be
+ // used to link the field and the new help-block together.
+ fieldId = ensureFieldId(field);
+ }
+
+ // Not found by id, but see if an empty placeholder was provided within
+ // the same .form-group.
+
+ const group = field.findParent(".form-group");
+
+ if (!group) { return null; }
+
+ // This happens less often, now that the Errors component ensures (at render time)
+ // a fieldId and a data-error-block-for element. Even so, sometimes a template
+ // will just contain a div.help-block[data-presentation=error]
+ const block = group.findFirst("[data-presentation=error]");
+
+ if (block) {
+ block.attr("data-error-block-for", fieldId);
+ return [block];
+ }
+
+ // Not found, so perhaps it will be created dynamically.
+ return null;
+ };
+
+ const createHelpBlock = function(field) {
+ const fieldId = ensureFieldId(field);
+
+ // No containing group ... this is a problem, probably an old 5.3 application upgraded to 5.4
+ // or beyond. Place the block just after the field.
+
+ const container = field.parent();
+
+ const block = dom.create("p", {
+ class: "help-block form-text text-danger",
+ "data-error-block-for": fieldId,
"id": fieldId + "-help-block"
+ }
+ );
- # The .input-group selectors are used to attach buttons or markers to the field.
- # In which case, the help block can go after the group instead.
- if container.hasClass("input-group")
- container.insertAfter block
- else
- field.insertAfter block
+ // The .input-group selectors are used to attach buttons or markers to the field.
+ // In which case, the help block can go after the group instead.
+ if (container.hasClass("input-group")) {
+ container.insertAfter(block);
+ } else {
+ field.insertAfter(block);
+ }
- return block
+ return block;
+ };
- showValidationError = (id, message) ->
- dom.wrap(id).trigger events.field.showValidationError, { message }
+ const showValidationError = (id, message) => dom.wrap(id).trigger(events.field.showValidationError, { message });
- collectOptionValues = (wrapper) ->
- _.pluck wrapper.element.options, "value"
+ const collectOptionValues = wrapper => _.pluck(wrapper.element.options, "value");
- # Default registrations:
+ // Default registrations:
- dom.onDocument events.field.inputValidation, (event, formMemo) ->
+ dom.onDocument(events.field.inputValidation, function(event, formMemo) {
- # Fields that are disabled, or not visible to the user are not subject to
- # validation. Typically, a field will only be invisible due to the
- # core/FormFragment component.
- return if @element.disabled or (not @deepVisible())
+ // Fields that are disabled, or not visible to the user are not subject to
+ // validation. Typically, a field will only be invisible due to the
+ // core/FormFragment component.
+ if (this.element.disabled || (!this.deepVisible())) { return; }
- failure = false
+ let failure = false;
- fieldValue =
- if (@attr "data-value-mode") is "options"
- collectOptionValues this
- else if @element.type is "checkbox"
- @checked()
- else
- @value()
+ const fieldValue =
+ (this.attr("data-value-mode")) === "options" ?
+ collectOptionValues(this)
+ : this.element.type === "checkbox" ?
+ this.checked()
+ :
+ this.value();
- memo = value: fieldValue
+ const memo = {value: fieldValue};
- postEventTrigger = =>
- if memo.error
- # Assume the event handler displayed the message.
- failure = true
+ const postEventTrigger = () => {
+ if (memo.error) {
+ // Assume the event handler displayed the message.
+ failure = true;
- if _.isString memo.error
+ if (_.isString(memo.error)) {
- @trigger events.field.showValidationError, { message: memo.error }
+ return this.trigger(events.field.showValidationError, { message: memo.error });
+ }
+ }
+ };
- @trigger events.field.optional, memo
+ this.trigger(events.field.optional, memo);
- postEventTrigger()
+ postEventTrigger();
- unless failure or (utils.isBlank memo.value)
+ if (!failure && (!utils.isBlank(memo.value))) {
- @trigger events.field.translate, memo
+ this.trigger(events.field.translate, memo);
- postEventTrigger()
+ postEventTrigger();
- unless failure
- if _.isUndefined memo.translated
- memo.translated = memo.value
+ if (!failure) {
+ if (_.isUndefined(memo.translated)) {
+ memo.translated = memo.value;
+ }
- @trigger events.field.validate, memo
+ this.trigger(events.field.validate, memo);
- postEventTrigger()
+ postEventTrigger();
+ }
+ }
- if failure
- formMemo.error = true
+ if (failure) {
+ formMemo.error = true;
this.attr('aria-invalid', 'true');
this.attr('aria-describedby', this.attr('id') + "-help-block");
- else
+ } else {
this.attr('aria-invalid', 'false');
this.attr('aria-describedby ', null);
- @trigger events.field.clearValidationError
+ this.trigger(events.field.clearValidationError);
+ }
- return
+ });
- dom.onDocument events.field.clearValidationError, ->
- blocks = exports.findHelpBlocks this
+ dom.onDocument(events.field.clearValidationError, function() {
+ const blocks = exports.findHelpBlocks(this);
- for block in blocks or []
- block.hide().update("")
- block.parent().removeClass "has-error"
- block.attr("role", null)
+ for (var block of Array.from(blocks || [])) {
+ block.hide().update("");
+ block.parent().removeClass("has-error");
+ block.attr("role", null);
+ }
- group = @findParent ".form-group"
+ const group = this.findParent(".form-group");
- group and group.removeClass "has-error"
+ group && group.removeClass("has-error");
- return
+ });
- dom.onDocument events.field.showValidationError, (event, memo) ->
- blocks = exports.findHelpBlocks this
+ dom.onDocument(events.field.showValidationError, function(event, memo) {
+ let blocks = exports.findHelpBlocks(this);
- unless blocks
- blocks = [exports.createHelpBlock this]
+ if (!blocks) {
+ blocks = [exports.createHelpBlock(this)];
+ }
- for block in blocks
- block.removeClass("invisible").show().update(memo.message)
- # Add "has-error" to the help-block's immediate container; this assist with some layout issues
- # where the help block can't be under the same .form-group element as the field (more common
- # with a horizontal form layout).
- block.parent().addClass("has-error")
- block.attr("role", "alert")
+ for (var block of Array.from(blocks)) {
+ block.removeClass("invisible").show().update(memo.message);
+ // Add "has-error" to the help-block's immediate container; this assist with some layout issues
+ // where the help block can't be under the same .form-group element as the field (more common
+ // with a horizontal form layout).
+ block.parent().addClass("has-error");
+ block.attr("role", "alert");
+ }
- group = @findParent ".form-group"
+ const group = this.findParent(".form-group");
- container = group or @parent().closest(":not(.input-group)")
+ const container = group || this.parent().closest(":not(.input-group)");
- container.addClass "has-error"
+ container.addClass("has-error");
- return
+ });
- exports = {findHelpBlocks, createHelpBlock, showValidationError}
\ No newline at end of file
+ return exports = {findHelpBlocks, createHelpBlock, showValidationError};
+});
\ No newline at end of file
diff --git a/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/form-fragment.js b/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/form-fragment.js
index ce4e1138c..ce03724ae 100644
--- a/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/form-fragment.js
+++ b/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/form-fragment.js
@@ -1,98 +1,121 @@
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http:#www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-
-# ## t5/core/form-fragment
-#
-define ["underscore", "t5/core/dom", "t5/core/events", "t5/core/forms"],
- (_, dom, events) ->
-
- SELECTOR = "[data-component-type='core/FormFragment']"
-
- REENABLE = "data-re-enable-when-fragment-visible"
-
- disableInputFields = (fragment) ->
-
- # This is an example of where the t5/core/dom abstraction label is problematic,
- # as this is very inefficient vs. the native jQuery approach.
- for field in fragment.find "input:not(:disabled)"
- field.attr "disabled", true
- field.attr REENABLE, true
-
- renableInputFields = (fragment) ->
-
- for field in fragment.find "input[#{REENABLE}]"
- field.attr "disabled", null
- field.attr REENABLE, null
-
- updateFields = (fragment, makeVisible) ->
-
- # This is a server side option that says the content of the fragment should always be submitted,
- # even if the fragment is not currently visible.
- return if fragment.attr "data-always-submit"
-
- f = if makeVisible then renableInputFields else disableInputFields
-
- f fragment
-
- # Again, a DOM event to make the FormFragment visible or invisible; this is useful
- # because of the didShow/didHide events ... but we're really just seeing the evolution
- # from the old style (the FormFragment class as controller) to the new style (DOM events and
- # top-level event handlers).
- dom.onDocument events.formfragment.changeVisibility, SELECTOR, (event) ->
- makeVisible = event.memo.visible
-
- this[if makeVisible then "show" else "hide"]()
-
- updateFields this, makeVisible
-
- @trigger events.element[if makeVisible then "didShow" else "didHide"]
-
- return false
-
- # When a FormFragment is initially rendered as hidden, then we need to do some
- # book-keeping on the client side.
- hide = (id) ->
- field = dom(id)
-
- updateFields field, false
-
- # Initializes a trigger for a FormFragment
- #
- # * spec.triggerId - id of checkbox or radio button
- # * spec.fragmentId - id of FormFragment element
- # * spec.invert - (optional) if true, then checked trigger hides (not shows) the fragment
- linkTrigger = (spec) ->
- unless spec.triggerId? then throw new Error "Incomplete parameters, triggerId is null"
- unless spec.fragmentId? then throw new Error "Incomplete parameters, fragmentId is null"
- trigger = dom spec.triggerId
- fragment = dom spec.fragmentId
- if fragment is null
- throw new Error "Invalid configuration, fragment with id #{spec.fragmentId} not found"
-
- invert = spec.invert or false
-
- update = ->
- checked = trigger.element.checked
- makeVisible = checked isnt invert
-
- fragment.trigger events.formfragment.changeVisibility, visible: makeVisible
-
- return
-
- if trigger.element.type is "radio"
- dom.on trigger.element.form, "click", update
- else
- trigger.on "click", update
-
- # Module exports:
- { linkTrigger, hide }
+/*
+ * decaffeinate suggestions:
+ * DS101: Remove unnecessary use of Array.from
+ * DS102: Remove unnecessary code created because of implicit returns
+ * DS205: Consider reworking code to avoid use of IIFEs
+ * DS207: Consider shorter variations of null checks
+ * Full docs: https://github.com/decaffeinate/decaffeinate/blob/main/docs/suggestions.md
+ */
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http:#www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+
+// ## t5/core/form-fragment
+//
+define(["underscore", "t5/core/dom", "t5/core/events", "t5/core/forms"],
+ function(_, dom, events) {
+
+ const SELECTOR = "[data-component-type='core/FormFragment']";
+
+ const REENABLE = "data-re-enable-when-fragment-visible";
+
+ const disableInputFields = fragment => // This is an example of where the t5/core/dom abstraction label is problematic,
+ // as this is very inefficient vs. the native jQuery approach.
+ (() => {
+ const result = [];
+ for (var field of Array.from(fragment.find("input:not(:disabled)"))) {
+ field.attr("disabled", true);
+ result.push(field.attr(REENABLE, true));
+ }
+ return result;
+ })();
+
+ const renableInputFields = fragment => (() => {
+ const result = [];
+ for (var field of Array.from(fragment.find(`input[${REENABLE}]`))) {
+ field.attr("disabled", null);
+ result.push(field.attr(REENABLE, null));
+ }
+ return result;
+ })();
+
+ const updateFields = function(fragment, makeVisible) {
+
+ // This is a server side option that says the content of the fragment should always be submitted,
+ // even if the fragment is not currently visible.
+ if (fragment.attr("data-always-submit")) { return; }
+
+ const f = makeVisible ? renableInputFields : disableInputFields;
+
+ return f(fragment);
+ };
+
+ // Again, a DOM event to make the FormFragment visible or invisible; this is useful
+ // because of the didShow/didHide events ... but we're really just seeing the evolution
+ // from the old style (the FormFragment class as controller) to the new style (DOM events and
+ // top-level event handlers).
+ dom.onDocument(events.formfragment.changeVisibility, SELECTOR, function(event) {
+ const makeVisible = event.memo.visible;
+
+ this[makeVisible ? "show" : "hide"]();
+
+ updateFields(this, makeVisible);
+
+ this.trigger(events.element[makeVisible ? "didShow" : "didHide"]);
+
+ return false;
+ });
+
+ // When a FormFragment is initially rendered as hidden, then we need to do some
+ // book-keeping on the client side.
+ const hide = function(id) {
+ const field = dom(id);
+
+ return updateFields(field, false);
+ };
+
+ // Initializes a trigger for a FormFragment
+ //
+ // * spec.triggerId - id of checkbox or radio button
+ // * spec.fragmentId - id of FormFragment element
+ // * spec.invert - (optional) if true, then checked trigger hides (not shows) the fragment
+ const linkTrigger = function(spec) {
+ if (spec.triggerId == null) { throw new Error("Incomplete parameters, triggerId is null"); }
+ if (spec.fragmentId == null) { throw new Error("Incomplete parameters, fragmentId is null"); }
+ const trigger = dom(spec.triggerId);
+ const fragment = dom(spec.fragmentId);
+ if (fragment === null) {
+ throw new Error(`Invalid configuration, fragment with id ${spec.fragmentId} not found`);
+ }
+
+ const invert = spec.invert || false;
+
+ const update = function() {
+ const {
+ checked
+ } = trigger.element;
+ const makeVisible = checked !== invert;
+
+ fragment.trigger(events.formfragment.changeVisibility, {visible: makeVisible});
+
+ };
+
+ if (trigger.element.type === "radio") {
+ return dom.on(trigger.element.form, "click", update);
+ } else {
+ return trigger.on("click", update);
+ }
+ };
+
+ // Module exports:
+ return { linkTrigger, hide };
+});
diff --git a/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/forms.js b/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/forms.js
index 00a8e6a34..985333c44 100644
--- a/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/forms.js
+++ b/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/forms.js
@@ -1,211 +1,240 @@
-# Copyright 2012, 2013 The Apache Software Foundation
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http:#www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-# ## t5/core/forms
-#
-# Defines handlers for HTML forms and HTML field elements, specifically to control input validation.
-
-define ["t5/core/events", "t5/core/dom", "underscore"],
- (events, dom, _) ->
-
- # Meta-data name that indicates the next submission should skip validation (typically, because
- # the form was submitted by a "cancel" button).
- SKIP_VALIDATION = "t5:skip-validation"
+/*
+ * decaffeinate suggestions:
+ * DS101: Remove unnecessary use of Array.from
+ * DS102: Remove unnecessary code created because of implicit returns
+ * Full docs: https://github.com/decaffeinate/decaffeinate/blob/main/docs/suggestions.md
+ */
+// Copyright 2012, 2013 The Apache Software Foundation
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http:#www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// ## t5/core/forms
+//
+// Defines handlers for HTML forms and HTML field elements, specifically to control input validation.
+
+define(["t5/core/events", "t5/core/dom", "underscore"],
+ function(events, dom, _) {
+
+ // Meta-data name that indicates the next submission should skip validation (typically, because
+ // the form was submitted by a "cancel" button).
+ let exports;
+ const SKIP_VALIDATION = "t5:skip-validation";
- # Data attribute and value added to HTML forms generated by the
- # Tapestry's Form component from the core library.
- DATA_ATTRIBUTE = "data-generator"
- DATA_ATTRIBUTE_VALUE = "tapestry/core/form"
- TAPESTRY_CORE_FORM_SELECTOR = "form[" + DATA_ATTRIBUTE + "='" + DATA_ATTRIBUTE_VALUE + "']"
+ // Data attribute and value added to HTML forms generated by the
+ // Tapestry's Form component from the core library.
+ const DATA_ATTRIBUTE = "data-generator";
+ const DATA_ATTRIBUTE_VALUE = "tapestry/core/form";
+ const TAPESTRY_CORE_FORM_SELECTOR = "form[" + DATA_ATTRIBUTE + "='" + DATA_ATTRIBUTE_VALUE + "']";
- clearSubmittingHidden = (form) ->
- hidden = form.findFirst "[name='t:submit']"
+ const clearSubmittingHidden = function(form) {
+ const hidden = form.findFirst("[name='t:submit']");
- # Clear if found
- hidden and hidden.value null
+ // Clear if found
+ hidden && hidden.value(null);
- form.meta SKIP_VALIDATION, null
+ form.meta(SKIP_VALIDATION, null);
- return
+ };
- setSubmittingHidden = (form, submitter) ->
+ const setSubmittingHidden = function(form, submitter) {
- mode = submitter.attr "data-submit-mode"
- isCancel = mode is "cancel"
- if mode and mode isnt "normal"
- form.meta SKIP_VALIDATION, true
+ const mode = submitter.attr("data-submit-mode");
+ const isCancel = mode === "cancel";
+ if (mode && (mode !== "normal")) {
+ form.meta(SKIP_VALIDATION, true);
+ }
- hidden = form.findFirst "[name='t:submit']"
+ let hidden = form.findFirst("[name='t:submit']");
- unless hidden
- firstHidden = form.findFirst "input[type=hidden]"
- hidden = dom.create "input", type: "hidden", name: "t:submit"
- firstHidden.insertBefore hidden
+ if (!hidden) {
+ const firstHidden = form.findFirst("input[type=hidden]");
+ hidden = dom.create("input", {type: "hidden", name: "t:submit"});
+ firstHidden.insertBefore(hidden);
+ }
- # TODO: Research why we need id and name and get rid of one if possible.
- name = if isCancel then "cancel" else submitter.element.name
- # Not going to drag in all of json2 just for this one purpose, but even
- # so, I'd like to get rid of this. Prototype includes Object.toJSON(), but jQuery
- # is curiously absent an equivalent.
- hidden.value "[\"#{submitter.element.id}\",\"#{name}\"]"
+ // TODO: Research why we need id and name and get rid of one if possible.
+ const name = isCancel ? "cancel" : submitter.element.name;
+ // Not going to drag in all of json2 just for this one purpose, but even
+ // so, I'd like to get rid of this. Prototype includes Object.toJSON(), but jQuery
+ // is curiously absent an equivalent.
+ hidden.value(`[\"${submitter.element.id}\",\"${name}\"]`);
- return
+ };
- # Passed the element wrapper for a form element, returns a map of all the values
- # for all non-disabled fields (including hidden fields, select, textarea). This is primarily
- # used when assembling an Ajax request for a form submission.
- gatherParameters = (form) ->
- result = {}
+ // Passed the element wrapper for a form element, returns a map of all the values
+ // for all non-disabled fields (including hidden fields, select, textarea). This is primarily
+ // used when assembling an Ajax request for a form submission.
+ const gatherParameters = function(form) {
+ const result = {};
- fields = form.find "input, select, textarea"
+ const fields = form.find("input, select, textarea");
- _.each fields, (field) ->
- return if field.attr "disabled"
+ _.each(fields, function(field) {
+ if (field.attr("disabled")) { return; }
- type = field.element.type
+ const {
+ type
+ } = field.element;
- # Ignore types file and submit; file doesn't make sense for Ajax, and submit
- # is handled by keeping a hidden field active with the data Tapestry needs
- # on the server.
- return if type is "file" or type is "submit"
+ // Ignore types file and submit; file doesn't make sense for Ajax, and submit
+ // is handled by keeping a hidden field active with the data Tapestry needs
+ // on the server.
+ if ((type === "file") || (type === "submit")) { return; }
- return if (type is "checkbox" or type is "radio") and field.checked() is false
+ if (((type === "checkbox") || (type === "radio")) && (field.checked() === false)) { return; }
- value = field.value()
+ const value = field.value();
- return if value is null
+ if (value === null) { return; }
- name = field.element.name
+ const {
+ name
+ } = field.element;
- # Many modern UIs create name-less elements on the fly (e.g., Backbone); these may be mixed
- # in with normal elements managed by Tapestry but should be ignored (not sent to the server in a POST
- # or Ajax update).
- return if name is ""
+ // Many modern UIs create name-less elements on the fly (e.g., Backbone); these may be mixed
+ // in with normal elements managed by Tapestry but should be ignored (not sent to the server in a POST
+ // or Ajax update).
+ if (name === "") { return; }
- existing = result[name]
+ const existing = result[name];
- if _.isArray existing
- existing.push value
- return
+ if (_.isArray(existing)) {
+ existing.push(value);
+ return;
+ }
- if existing
- result[name] = [existing, value]
- return
+ if (existing) {
+ result[name] = [existing, value];
+ return;
+ }
- result[name] = value
+ return result[name] = value;
+ });
- return result
+ return result;
+ };
- defaultValidateAndSubmit = ->
+ const defaultValidateAndSubmit = function() {
- where = -> "processing form submission"
+ let where = () => "processing form submission";
- try
+ try {
- if ((@attr "data-validate") is "submit") and
- (not @meta SKIP_VALIDATION)
+ if (((this.attr("data-validate")) === "submit") &&
+ (!this.meta(SKIP_VALIDATION))) {
- @meta SKIP_VALIDATION, null
+ let memo;
+ this.meta(SKIP_VALIDATION, null);
- hasError = false
- focusField = null
+ let hasError = false;
+ let focusField = null;
- for field in @find "[data-validation]"
- memo = {}
- where = -> "triggering #{events.field.inputValidation} event on #{field.toString()}"
- field.trigger events.field.inputValidation, memo
+ for (var field of Array.from(this.find("[data-validation]"))) {
+ memo = {};
+ where = () => `triggering ${events.field.inputValidation} event on ${field.toString()}`;
+ field.trigger(events.field.inputValidation, memo);
- if memo.error
- hasError = true
- focusField = field unless focusField
+ if (memo.error) {
+ hasError = true;
+ if (!focusField) { focusField = field; }
+ }
+ }
- # Only do form validation if all individual field validation
- # was successful.
- unless hasError
- memo = {}
- where = -> "trigging cross-form validation event"
- @trigger events.form.validate, memo
+ // Only do form validation if all individual field validation
+ // was successful.
+ if (!hasError) {
+ memo = {};
+ where = () => "trigging cross-form validation event";
+ this.trigger(events.form.validate, memo);
- hasError = memo.error
+ hasError = memo.error;
+ }
- if hasError
- clearSubmittingHidden this
+ if (hasError) {
+ clearSubmittingHidden(this);
- # If a specific field has been identified as the source of the validation error, then
- # focus on it.
- focusField.focus() if focusField
+ // If a specific field has been identified as the source of the validation error, then
+ // focus on it.
+ if (focusField) { focusField.focus(); }
- # Trigger an event to inform that form validation results in error
- where = -> "triggering validation in error event"
- @trigger events.form.validateInError
+ // Trigger an event to inform that form validation results in error
+ where = () => "triggering validation in error event";
+ this.trigger(events.form.validateInError);
- # Cancel the original submit event when there's an error
- return false
+ // Cancel the original submit event when there's an error
+ return false;
+ }
+ }
- # Allow certain types of elements to do last-moment set up. Basically, this is for
- # FormFragment, or similar, to make their hidden field enabled or disabled to match
- # their UI's visible/hidden status. This is assumed to work or throw an exception; there
- # is no memo.
- where = -> "triggering #{events.form.prepareForSubmit} event (after validation)"
+ // Allow certain types of elements to do last-moment set up. Basically, this is for
+ // FormFragment, or similar, to make their hidden field enabled or disabled to match
+ // their UI's visible/hidden status. This is assumed to work or throw an exception; there
+ // is no memo.
+ where = () => `triggering ${events.form.prepareForSubmit} event (after validation)`;
- @trigger events.form.prepareForSubmit
+ this.trigger(events.form.prepareForSubmit);
- catch error
- console.error "Form validiation/submit error `#{error.toString()}', in form #{this.toString()}, #{where()}"
- console.error error
- return false
+ } catch (error) {
+ console.error(`Form validiation/submit error \`${error.toString()}', in form ${this.toString()}, ${where()}`);
+ console.error(error);
+ return false;
+ }
- # Otherwise, the event is good, there are no validation problems, let the normal processing commence.
- # Possibly, the document event handler provided by the t5/core/zone module will intercept form submission if this
- # is an Ajax submission.
- return
+ // Otherwise, the event is good, there are no validation problems, let the normal processing commence.
+ // Possibly, the document event handler provided by the t5/core/zone module will intercept form submission if this
+ // is an Ajax submission.
+ };
- dom.onDocument "submit", TAPESTRY_CORE_FORM_SELECTOR, defaultValidateAndSubmit
+ dom.onDocument("submit", TAPESTRY_CORE_FORM_SELECTOR, defaultValidateAndSubmit);
- # On any click on a submit or image, update the containing form to indicate that the element
- # was responsible for the eventual submit; this is very important to Ajax updates, otherwise the
- # information about which control triggered the submit gets lost.
- dom.onDocument "click", TAPESTRY_CORE_FORM_SELECTOR + " input[type=submit], " + TAPESTRY_CORE_FORM_SELECTOR + " input[type=image]", ->
- setSubmittingHidden (dom @element.form), this
- return
+ // On any click on a submit or image, update the containing form to indicate that the element
+ // was responsible for the eventual submit; this is very important to Ajax updates, otherwise the
+ // information about which control triggered the submit gets lost.
+ dom.onDocument("click", TAPESTRY_CORE_FORM_SELECTOR + " input[type=submit], " + TAPESTRY_CORE_FORM_SELECTOR + " input[type=image]", function() {
+ setSubmittingHidden((dom(this.element.form)), this);
+ });
- # Support for link submits. `data-submit-mode` will be non-null, possibly "cancel".
- # Update the hidden field, but also cancel the default behavior for the click.
- dom.onDocument "click", "a[data-submit-mode]", ->
- form = @findParent "form"
+ // Support for link submits. `data-submit-mode` will be non-null, possibly "cancel".
+ // Update the hidden field, but also cancel the default behavior for the click.
+ dom.onDocument("click", "a[data-submit-mode]", function() {
+ const form = this.findParent("form");
- unless form
- console.error "Submitting link element not contained inside a form element."
- return false
+ if (!form) {
+ console.error("Submitting link element not contained inside a form element.");
+ return false;
+ }
- setSubmittingHidden form, @closest "a[data-submit-mode]"
+ setSubmittingHidden(form, this.closest("a[data-submit-mode]"));
- # Now the ugly part; if we just invoke submit() on the form, it does not trigger
- # the form's "submit" event, which we need.
+ // Now the ugly part; if we just invoke submit() on the form, it does not trigger
+ // the form's "submit" event, which we need.
- form.trigger "submit"
+ form.trigger("submit");
- # And cancel the default behavior for the original click event
- return false
+ // And cancel the default behavior for the original click event
+ return false;
+ });
- exports =
- gatherParameters: gatherParameters
+ return exports = {
+ gatherParameters,
- setSubmittingElement: setSubmittingHidden
-
- # Sets a flag on the form to indicate that client-side validation should be bypassed.
- # This is typically associated with submit buttons that "cancel" the form.
- skipValidation: (form) ->
- form.meta SKIP_VALIDATION, true
+ setSubmittingElement: setSubmittingHidden,
+
+ // Sets a flag on the form to indicate that client-side validation should be bypassed.
+ // This is typically associated with submit buttons that "cancel" the form.
+ skipValidation(form) {
+ return form.meta(SKIP_VALIDATION, true);
+ }
+ };
+});
diff --git a/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/graphviz.js b/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/graphviz.js
index e1fbe3ee2..80391a241 100644
--- a/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/graphviz.js
+++ b/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/graphviz.js
@@ -1,29 +1,36 @@
-# Copyright 2023 The Apache Software Foundation
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http:#www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+/*
+ * decaffeinate suggestions:
+ * DS102: Remove unnecessary code created because of implicit returns
+ * Full docs: https://github.com/decaffeinate/decaffeinate/blob/main/docs/suggestions.md
+ */
+// Copyright 2023 The Apache Software Foundation
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http:#www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
-# ## t5/core/graphviz
-#
-# Support to the core/Graphviz Tapestry component.
-define ["https://cdn.jsdelivr.net/npm/@hpcc-js/wasm/dist/graphviz.umd.js"],
- (hpccWasm) ->
- render = (value, id, showDownloadLink) ->
- hpccWasm.Graphviz.load().then (graphviz) ->
- svg = graphviz.dot value
- div = document.getElementById id
- layout = graphviz.layout(value, "svg", "dot")
- div.innerHTML = layout
- if showDownloadLink
- link = document.getElementById (id + "-download")
- link.setAttribute "href", "data:image/svg+xml;charset=utf-8," + encodeURIComponent(layout)
- return render
+// ## t5/core/graphviz
+//
+// Support to the core/Graphviz Tapestry component.
+define(["https://cdn.jsdelivr.net/npm/@hpcc-js/wasm/dist/graphviz.umd.js"],
+ function(hpccWasm) {
+ const render = (value, id, showDownloadLink) => hpccWasm.Graphviz.load().then(function(graphviz) {
+ const svg = graphviz.dot(value);
+ const div = document.getElementById(id);
+ const layout = graphviz.layout(value, "svg", "dot");
+ div.innerHTML = layout;
+ if (showDownloadLink) {
+ const link = document.getElementById((id + "-download"));
+ return link.setAttribute("href", "data:image/svg+xml;charset=utf-8," + encodeURIComponent(layout));
+ }
+ });
+ return render;
+});
diff --git a/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/init.js b/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/init.js
index 67aa07bc3..372e5a12d 100644
--- a/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/init.js
+++ b/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/init.js
@@ -1,30 +1,35 @@
-# Copyright 2012 The Apache Software Foundation
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http:#www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+/*
+ * decaffeinate suggestions:
+ * DS102: Remove unnecessary code created because of implicit returns
+ * Full docs: https://github.com/decaffeinate/decaffeinate/blob/main/docs/suggestions.md
+ */
+// Copyright 2012 The Apache Software Foundation
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http:#www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
-# ## t5/core/init
-#
-# Compatibility module, invokes functions on the T5.initializers namespace.
-#
-# Introduced in 5.4, to be removed at some point in the future, when T5.initializers is itself no more.
-define ["t5/core/console"],
+// ## t5/core/init
+//
+// Compatibility module, invokes functions on the T5.initializers namespace.
+//
+// Introduced in 5.4, to be removed at some point in the future, when T5.initializers is itself no more.
+define(["t5/core/console"],
- (console) ->
-
- # Exports a single function that finds an initializer in `T5.initializers` and invokes it.
- (initName, args...) ->
- fn = T5.initializers[initName]
- if not fn
- console.error "Initialization function '#{initName}' not found in T5.initializers namespace."
- else
- fn.apply null, args
+ console => // Exports a single function that finds an initializer in `T5.initializers` and invokes it.
+ (function(initName, ...args) {
+ const fn = T5.initializers[initName];
+ if (!fn) {
+ return console.error(`Initialization function '${initName}' not found in T5.initializers namespace.`);
+ } else {
+ return fn.apply(null, args);
+ }
+ }));
diff --git a/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/localdate.js b/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/localdate.js
index 3ec7ca28a..9eaa73236 100644
--- a/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/localdate.js
+++ b/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/localdate.js
@@ -1,37 +1,43 @@
-# Copyright 2013 The Apache Software Foundation
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http:#www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-# ## t5/core/localdate
-#
-# Used with the LocalDate component to present a Date in a particular format, in the
-# browser's time zone.
-
-define ["t5/core/dom", "t5/core/moment"],
-(dom, moment) ->
-
- ATTR = "data-localdate-format"
-
- dom.scanner "[#{ATTR}]", (el) ->
- format = el.attr ATTR
-
- isoString = el.text()
-
- m = moment isoString
-
- el.update m.format format
-
- # A good scanner callback always removes itself from future scans.
- el.attr ATTR, null
-
- return
+/*
+ * decaffeinate suggestions:
+ * DS102: Remove unnecessary code created because of implicit returns
+ * Full docs: https://github.com/decaffeinate/decaffeinate/blob/main/docs/suggestions.md
+ */
+// Copyright 2013 The Apache Software Foundation
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http:#www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// ## t5/core/localdate
+//
+// Used with the LocalDate component to present a Date in a particular format, in the
+// browser's time zone.
+
+define(["t5/core/dom", "t5/core/moment"],
+function(dom, moment) {
+
+ const ATTR = "data-localdate-format";
+
+ return dom.scanner(`[${ATTR}]`, function(el) {
+ const format = el.attr(ATTR);
+
+ const isoString = el.text();
+
+ const m = moment(isoString);
+
+ el.update(m.format(format));
+
+ // A good scanner callback always removes itself from future scans.
+ el.attr(ATTR, null);
+
+ });
+});
diff --git a/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/messages.js b/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/messages.js
index 957cccea4..5e045c4b3 100644
--- a/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/messages.js
+++ b/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/messages.js
@@ -1,55 +1,58 @@
-# Copyright 2012-2013 The Apache Software Foundation
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http:#www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-# ## t5/core/messages
-#
-# For all of these modules, we've turned off CoffeeScript's normal outer function
-# wrapper, as each module is just a call to `define()` with a function that fulfills
-# the same purpose. This one is different, as it is necessary to compute one of the dependencies.
-# On the server `t5/core/messages/<locale>` is actually generated dynamically, as is a simple
-# mapping of message keys to message values, from the global application message catalog.
-#
-# This module provides access to localized messages from the Tapestry applications' server-side
-# application message catalog (which is, itself, built from multiple resources, some provided by
-# the framework, others provided by the application, or third-party libraries).
-#
-# Messages in the catalog that contain Java-style format specifiers are not included, as there
-# is no facility for formatting those on the client. This is actually done as a simple test for the
-# presence of the `%` character. In addition, any message key that begins with "private-" is
-# assumed to contain sensitive data (such as database URLs or passwords) and will not be
-# exposed to the client.
-
-# In the unexpected case that the data-locale attribute is missing, assume English
-locale = (document.documentElement.getAttribute "data-locale") or "en"
-
-define ["t5/core/messages/#{locale}", "underscore", "t5/core/console"],
- (messages, _, console) ->
-
- # Returns the application message catalog message for the given key. Returns
- # a placeholder if the key is not found.
- get = (key) ->
- value = messages[key]
-
- if value
- return value
- else
- console.error "No value for message catalog key '#{key}' exists."
- return "[[Missing Key: '#{key}']]"
-
- # Returns all keys that are defined by the underlying catalog, in no specific order.
- get.keys = -> _.keys messages
-
-
- # Export get as the main function.
- return get
+// Copyright 2012-2013 The Apache Software Foundation
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http:#www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// ## t5/core/messages
+//
+// For all of these modules, we've turned off CoffeeScript's normal outer function
+// wrapper, as each module is just a call to `define()` with a function that fulfills
+// the same purpose. This one is different, as it is necessary to compute one of the dependencies.
+// On the server `t5/core/messages/<locale>` is actually generated dynamically, as is a simple
+// mapping of message keys to message values, from the global application message catalog.
+//
+// This module provides access to localized messages from the Tapestry applications' server-side
+// application message catalog (which is, itself, built from multiple resources, some provided by
+// the framework, others provided by the application, or third-party libraries).
+//
+// Messages in the catalog that contain Java-style format specifiers are not included, as there
+// is no facility for formatting those on the client. This is actually done as a simple test for the
+// presence of the `%` character. In addition, any message key that begins with "private-" is
+// assumed to contain sensitive data (such as database URLs or passwords) and will not be
+// exposed to the client.
+
+// In the unexpected case that the data-locale attribute is missing, assume English
+const locale = (document.documentElement.getAttribute("data-locale")) || "en";
+
+define([`t5/core/messages/${locale}`, "underscore", "t5/core/console"],
+ function(messages, _, console) {
+
+ // Returns the application message catalog message for the given key. Returns
+ // a placeholder if the key is not found.
+ const get = function(key) {
+ const value = messages[key];
+
+ if (value) {
+ return value;
+ } else {
+ console.error(`No value for message catalog key '${key}' exists.`);
+ return `[[Missing Key: '${key}']]`;
+ }
+ };
+
+ // Returns all keys that are defined by the underlying catalog, in no specific order.
+ get.keys = () => _.keys(messages);
+
+
+ // Export get as the main function.
+ return get;
+});
diff --git a/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/moment.js b/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/moment.js
index 4b1125410..8bb24633b 100644
--- a/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/moment.js
+++ b/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/moment.js
@@ -1,25 +1,26 @@
-# Copyright 2013 The Apache Software Foundation
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http:#www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+// Copyright 2013 The Apache Software Foundation
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http:#www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
-# ## t5/core/moment
-#
-# A wrapper around Moment.js; this simply initializes Moment to
-# use the correct locale (as per the data-locale attribute of the document element).
-define ["moment"],
-(moment) ->
- locale = (document.documentElement.getAttribute "data-locale") or "en"
+// ## t5/core/moment
+//
+// A wrapper around Moment.js; this simply initializes Moment to
+// use the correct locale (as per the data-locale attribute of the document element).
+define(["moment"],
+function(moment) {
+ const locale = (document.documentElement.getAttribute("data-locale")) || "en";
- moment.locale(locale)
+ moment.locale(locale);
- return moment
\ No newline at end of file
+ return moment;
+});
\ No newline at end of file
diff --git a/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/pageinit.js b/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/pageinit.js
index 34f336449..de47602b8 100644
--- a/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/pageinit.js
+++ b/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/pageinit.js
@@ -1,241 +1,287 @@
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http:#www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-# ## t5/core/pageinit
-#
-# Module that defines functions used for page initialization.
-# The initialize function is passed an array of initializers; each initializer is itself
-# an array. The first value in the initializer defines the name of the module to invoke.
-# The module name may also indicate the function exported by the module, as a suffix following a colon:
-# e.g., "my/module:myfunc".
-# Any additional values in the initializer are passed to the function. The context of the function (this) is null.
-define ["underscore", "t5/core/console", "t5/core/dom", "t5/core/events"],
- (_, console, dom, events) ->
- pathPrefix = null
-
- # Borrowed from Prototype:
- isOpera = Object.prototype.toString.call(window.opera) == '[object Opera]'
- isIE = !!window.attachEvent && !isOpera
-
- rebuildURL = (path) ->
- return path if path.match /^https?:/
-
- # See Tapestry.rebuildURL() for an error about the path not starting with a leading '/'
- # We'll assume that doesn't happen.
-
- if !pathPrefix
- l = window.location
- pathPrefix = "#{l.protocol}//#{l.host}"
-
- return pathPrefix + path
-
- rebuildURLOnIE =
- if isIE then rebuildURL else _.identity
-
- addStylesheets = (newStylesheets) ->
- return unless newStylesheets
-
- # Figure out which stylesheets are loaded; adjust for IE, and especially, IE 9
- # which can report a stylesheet's URL as null (not empty string).
- loaded = _.chain(document.styleSheets)
+/*
+ * decaffeinate suggestions:
+ * DS101: Remove unnecessary use of Array.from
+ * DS102: Remove unnecessary code created because of implicit returns
+ * DS201: Simplify complex destructure assignments
+ * DS207: Consider shorter variations of null checks
+ * Full docs: https://github.com/decaffeinate/decaffeinate/blob/main/docs/suggestions.md
+ */
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http:#www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// ## t5/core/pageinit
+//
+// Module that defines functions used for page initialization.
+// The initialize function is passed an array of initializers; each initializer is itself
+// an array. The first value in the initializer defines the name of the module to invoke.
+// The module name may also indicate the function exported by the module, as a suffix following a colon:
+// e.g., "my/module:myfunc".
+// Any additional values in the initializer are passed to the function. The context of the function (this) is null.
+define(["underscore", "t5/core/console", "t5/core/dom", "t5/core/events"],
+ function(_, console, dom, events) {
+ let exports;
+ let pathPrefix = null;
+
+ // Borrowed from Prototype:
+ const isOpera = Object.prototype.toString.call(window.opera) === '[object Opera]';
+ const isIE = !!window.attachEvent && !isOpera;
+
+ const rebuildURL = function(path) {
+ if (path.match(/^https?:/)) { return path; }
+
+ // See Tapestry.rebuildURL() for an error about the path not starting with a leading '/'
+ // We'll assume that doesn't happen.
+
+ if (!pathPrefix) {
+ const l = window.location;
+ pathPrefix = `${l.protocol}//${l.host}`;
+ }
+
+ return pathPrefix + path;
+ };
+
+ const rebuildURLOnIE =
+ isIE ? rebuildURL : _.identity;
+
+ const addStylesheets = function(newStylesheets) {
+ if (!newStylesheets) { return; }
+
+ // Figure out which stylesheets are loaded; adjust for IE, and especially, IE 9
+ // which can report a stylesheet's URL as null (not empty string).
+ const loaded = _.chain(document.styleSheets)
.pluck("href")
.without("")
.without(null)
- .map(rebuildURLOnIE)
+ .map(rebuildURLOnIE);
- insertionPoint = _.find(document.styleSheets, (ss) ->
- parent = ss.ownerNode || ss.owningElement
- parent.rel is "stylesheet ajax-insertion-point")
+ const insertionPoint = _.find(document.styleSheets, function(ss) {
+ const parent = ss.ownerNode || ss.owningElement;
+ return parent.rel === "stylesheet ajax-insertion-point";
+ });
- # Most browsers support document.head, but older IE doesn't:
- head = document.head or document.getElementsByTagName("head")[0]
+ // Most browsers support document.head, but older IE doesn't:
+ const head = document.head || document.getElementsByTagName("head")[0];
_.chain(newStylesheets)
- .map((ss) -> { href: rebuildURL(ss.href), media: ss.media })
- .reject((ss) -> loaded.contains(ss.href).value())
- .each((ss) ->
- element = document.createElement "link"
- element.setAttribute "type", "text/css"
- element.setAttribute "rel", "stylesheet"
- element.setAttribute "href", ss.href
- if ss.media
- element.setAttribute "media", ss.media
-
- if insertionPoint
- head.insertBefore element, insertionPoint.ownerNode
- else
- head.appendChild element
-
- console.debug "Added stylesheet #{ss.href}"
- )
-
- return
-
- invokeInitializer = (tracker, qualifiedName, initArguments) ->
- [moduleName, functionName] = qualifiedName.split ':'
-
- require [moduleName], (moduleLib) ->
+ .map(ss => ({
+ href: rebuildURL(ss.href),
+ media: ss.media
+ }))
+ .reject(ss => loaded.contains(ss.href).value())
+ .each(function(ss) {
+ const element = document.createElement("link");
+ element.setAttribute("type", "text/css");
+ element.setAttribute("rel", "stylesheet");
+ element.setAttribute("href", ss.href);
+ if (ss.media) {
+ element.setAttribute("media", ss.media);
+ }
+
+ if (insertionPoint) {
+ head.insertBefore(element, insertionPoint.ownerNode);
+ } else {
+ head.appendChild(element);
+ }
+
+ return console.debug(`Added stylesheet ${ss.href}`);
+ });
+
+ };
+
+ const invokeInitializer = function(tracker, qualifiedName, initArguments) {
+ const [moduleName, functionName] = Array.from(qualifiedName.split(':'));
+
+ return require([moduleName], function(moduleLib) {
- try
- # Some modules export nothing but do some full-page initialization, such as adding
- # event handlers to the body.
- if not functionName and
- initArguments.length is 0 and
- not _.isFunction moduleLib
- console.debug "Loaded module #{moduleName}"
- return
-
- unless moduleLib
- throw new Error "require('#{moduleName}') returned #{moduleLib} when not expected"
-
- fn = if functionName? then moduleLib[functionName] else moduleLib
-
- unless fn?
- if functionName
- console.error "Could not locate function `#{qualifiedName}' in #{JSON.stringify(moduleLib)}"
- console.error moduleLib
- throw new Error "Could not locate function `#{qualifiedName}'."
-
- if console.debugEnabled
- argsString = (JSON.stringify arg for arg in initArguments).join(", ")
- console.debug "Invoking #{qualifiedName}(#{argsString})"
-
- fn.apply null, initArguments
- finally
- tracker()
-
- # Loads all specified libraries in order (this includes the core stack, other stacks, and
- # any free-standing libraries). It then executes the initializations. Once all initializations have
- # completed (which is usually an asynchronous operation, as initializations may require the loading
- # of further modules), then the `data-page-initialized` attribute of the `<body>` element is set to
- # 'true'.
- #
- # This is the main export of the module; other functions are attached as properties.
- loadLibrariesAndInitialize = (libraries, inits) ->
- console.debug "Loading #{libraries?.length or 0} libraries"
- exports.loadLibraries libraries,
- -> exports.initialize inits,
- ->
- # At this point, all libraries have been loaded, and all inits should have executed. Unless some of
- # the inits triggered Ajax updates (such as a core/ProgressiveDisplay component), then the page should
- # be ready to go. We set a flag, mostly used by test suites, to ensure that all is ready.
- # Later Ajax requests will cause the data-ajax-active attribute to be incremented (from 0)
- # and decremented (when the requests complete).
-
- dom.body.attr "data-page-initialized", "true"
-
- for mask in dom.body.find ".pageloading-mask"
- mask.remove()
-
- exports = _.extend loadLibrariesAndInitialize,
- # Passed a list of initializers, executes each initializer in order. Due to asynchronous loading
- # of modules, the exact order in which initializer functions are invoked is not predictable.
- initialize: (inits = [], callback) ->
- console.debug "Executing #{inits.length} inits"
- callbackCountdown = inits.length + 1
-
- # tracker gets invoked once after each require/callback, plus once extra
- # (to handle the case where there are no inits). When the count hits zero,
- # it invokes the callback (if there is one).
- tracker = ->
- callbackCountdown--
-
- if callbackCountdown is 0
- console.debug "All inits executed"
- callback() if callback
-
- # First value in each init is the qualified module name; anything after
- # that are arguments to be passed to the identified function. A string
- # is the name of a module to load, or function to invoke, that
- # takes no parameters.
- for init in inits
- if _.isString init
- invokeInitializer tracker, init, []
- else
- [qualifiedName, initArguments...] = init
- invokeInitializer tracker, qualifiedName, initArguments
-
- tracker()
-
- # Pre-loads a number of libraries in order. When the last library is loaded,
- # invokes the callback (with no parameters).
- loadLibraries: (libraries, callback) ->
- reducer = (callback, library) -> ->
- console.debug "Loading library #{library}"
- require [library], callback
-
- finalCallback = _.reduceRight libraries, reducer, callback
-
- finalCallback.call null
-
- evalJavaScript: (js) ->
- console.debug "Evaluating: #{js}"
- eval js
-
- # Triggers the focus event on the field, if the field exist. Focus occurs delayed 1/8th of a
- # second, which helps ensure that other initializions on the page are in place.
- #
- # * fieldId - element id of field to focus on
- focus: (fieldId) ->
- field = dom fieldId
-
- if field
- _.delay (-> field.focus()), 125
-
- # Passed the response from an Ajax request, when the request is successful.
- # This is used for any request that attaches partial-page-render data to the main JSON object
- # response. If no such data is attached, the callback is simply invoked immediately.
- # Otherwise, Tapestry processes the partial-page-render data. This may involve loading some number
- # of JavaScript libraries and CSS style sheets, and a number of direct updates to the DOM. After DOM updates,
- # the callback is invoked, passed the response (with any Tapestry-specific data removed).
- # After the callback is invoked, page initializations occur. This method returns null.
-
- # * response - the Ajax response object
- # * callback - invoked after scripts are loaded, but before page initializations occur (may be null)
- handlePartialPageRenderResponse: (response, callback) ->
-
- # Capture the partial page response portion of the overall response, and
- # then remove it so it doesn't interfere elsewhere.
- responseJSON = response.json or {}
- partial = responseJSON._tapestry
- delete responseJSON._tapestry
-
- # Extreme case: the data has a redirectURL which forces an immediate redirect to the URL.
- # No other initialization or callback invocation occurs.
- if partial?.redirectURL
- if window.location.href is partial.redirectURL
- window.location.reload true
- else
- window.location.href = partial.redirectURL
- return
-
- addStylesheets partial?.stylesheets
-
- # Make sure all libraries are loaded
- exports.loadLibraries partial?.libraries, ->
-
- # After libraries are loaded, update each zone:
- _(partial?.content).each ([id, content]) ->
- console.debug "Updating content for zone #{id}"
-
- zone = dom.wrap id
-
- if zone
- zone.trigger events.zone.update, { content }
-
- # Invoke the callback, if present. The callback may do its own content updates.
- callback and callback(response)
-
- # Lastly, perform initializations from the partial page render response.
- exports.initialize partial?.inits
-
- return
+ try {
+ // Some modules export nothing but do some full-page initialization, such as adding
+ // event handlers to the body.
+ if (!functionName &&
+ (initArguments.length === 0) &&
+ !_.isFunction(moduleLib)) {
+ console.debug(`Loaded module ${moduleName}`);
+ return;
+ }
+
+ if (!moduleLib) {
+ throw new Error(`require('${moduleName}') returned ${moduleLib} when not expected`);
+ }
+
+ const fn = (functionName != null) ? moduleLib[functionName] : moduleLib;
+
+ if (fn == null) {
+ if (functionName) {
+ console.error(`Could not locate function \`${qualifiedName}' in ${JSON.stringify(moduleLib)}`);
+ console.error(moduleLib);
+ }
+ throw new Error(`Could not locate function \`${qualifiedName}'.`);
+ }
+
+ if (console.debugEnabled) {
+ const argsString = (Array.from(initArguments).map((arg) => JSON.stringify(arg))).join(", ");
+ console.debug(`Invoking ${qualifiedName}(${argsString})`);
+ }
+
+ return fn.apply(null, initArguments);
+ } finally {
+ tracker();
+ }
+ });
+ };
+
+ // Loads all specified libraries in order (this includes the core stack, other stacks, and
+ // any free-standing libraries). It then executes the initializations. Once all initializations have
+ // completed (which is usually an asynchronous operation, as initializations may require the loading
+ // of further modules), then the `data-page-initialized` attribute of the `<body>` element is set to
+ // 'true'.
+ //
+ // This is the main export of the module; other functions are attached as properties.
+ const loadLibrariesAndInitialize = function(libraries, inits) {
+ console.debug(`Loading ${(libraries != null ? libraries.length : undefined) || 0} libraries`);
+ return exports.loadLibraries(libraries,
+ () => exports.initialize(inits,
+ function() {
+ // At this point, all libraries have been loaded, and all inits should have executed. Unless some of
+ // the inits triggered Ajax updates (such as a core/ProgressiveDisplay component), then the page should
+ // be ready to go. We set a flag, mostly used by test suites, to ensure that all is ready.
+ // Later Ajax requests will cause the data-ajax-active attribute to be incremented (from 0)
+ // and decremented (when the requests complete).
+
+ dom.body.attr("data-page-initialized", "true");
+
+ return Array.from(dom.body.find(".pageloading-mask")).map((mask) =>
+ mask.remove());
+ }));
+ };
+
+ return exports = _.extend(loadLibrariesAndInitialize, {
+ // Passed a list of initializers, executes each initializer in order. Due to asynchronous loading
+ // of modules, the exact order in which initializer functions are invoked is not predictable.
+ initialize(inits, callback) {
+ if (inits == null) { inits = []; }
+ console.debug(`Executing ${inits.length} inits`);
+ let callbackCountdown = inits.length + 1;
+
+ // tracker gets invoked once after each require/callback, plus once extra
+ // (to handle the case where there are no inits). When the count hits zero,
+ // it invokes the callback (if there is one).
+ const tracker = function() {
+ callbackCountdown--;
+
+ if (callbackCountdown === 0) {
+ console.debug("All inits executed");
+ if (callback) { return callback(); }
+ }
+ };
+
+ // First value in each init is the qualified module name; anything after
+ // that are arguments to be passed to the identified function. A string
+ // is the name of a module to load, or function to invoke, that
+ // takes no parameters.
+ for (var init of Array.from(inits)) {
+ if (_.isString(init)) {
+ invokeInitializer(tracker, init, []);
+ } else {
+ var [qualifiedName, ...initArguments] = Array.from(init);
+ invokeInitializer(tracker, qualifiedName, initArguments);
+ }
+ }
+
+ return tracker();
+ },
+
+ // Pre-loads a number of libraries in order. When the last library is loaded,
+ // invokes the callback (with no parameters).
+ loadLibraries(libraries, callback) {
+ const reducer = (callback, library) => (function() {
+ console.debug(`Loading library ${library}`);
+ return require([library], callback);
+ });
+
+ const finalCallback = _.reduceRight(libraries, reducer, callback);
+
+ return finalCallback.call(null);
+ },
+
+ evalJavaScript(js) {
+ console.debug(`Evaluating: ${js}`);
+ return eval(js);
+ },
+
+ // Triggers the focus event on the field, if the field exist. Focus occurs delayed 1/8th of a
+ // second, which helps ensure that other initializions on the page are in place.
+ //
+ // * fieldId - element id of field to focus on
+ focus(fieldId) {
+ const field = dom(fieldId);
+
+ if (field) {
+ return _.delay((() => field.focus()), 125);
+ }
+ },
+
+ // Passed the response from an Ajax request, when the request is successful.
+ // This is used for any request that attaches partial-page-render data to the main JSON object
+ // response. If no such data is attached, the callback is simply invoked immediately.
+ // Otherwise, Tapestry processes the partial-page-render data. This may involve loading some number
+ // of JavaScript libraries and CSS style sheets, and a number of direct updates to the DOM. After DOM updates,
+ // the callback is invoked, passed the response (with any Tapestry-specific data removed).
+ // After the callback is invoked, page initializations occur. This method returns null.
+
+ // * response - the Ajax response object
+ // * callback - invoked after scripts are loaded, but before page initializations occur (may be null)
+ handlePartialPageRenderResponse(response, callback) {
+
+ // Capture the partial page response portion of the overall response, and
+ // then remove it so it doesn't interfere elsewhere.
+ const responseJSON = response.json || {};
+ const partial = responseJSON._tapestry;
+ delete responseJSON._tapestry;
+
+ // Extreme case: the data has a redirectURL which forces an immediate redirect to the URL.
+ // No other initialization or callback invocation occurs.
+ if (partial != null ? partial.redirectURL : undefined) {
+ if (window.location.href === partial.redirectURL) {
+ window.location.reload(true);
+ } else {
+ window.location.href = partial.redirectURL;
+ }
+ return;
+ }
+
+ addStylesheets(partial != null ? partial.stylesheets : undefined);
+
+ // Make sure all libraries are loaded
+ exports.loadLibraries(partial != null ? partial.libraries : undefined, function() {
+
+ // After libraries are loaded, update each zone:
+ _(partial != null ? partial.content : undefined).each(function(...args) {
+ const [id, content] = Array.from(args[0]);
+ console.debug(`Updating content for zone ${id}`);
+
+ const zone = dom.wrap(id);
+
+ if (zone) {
+ return zone.trigger(events.zone.update, { content });
+ }});
+
+ // Invoke the callback, if present. The callback may do its own content updates.
+ callback && callback(response);
+
+ // Lastly, perform initializations from the partial page render response.
+ return exports.initialize(partial != null ? partial.inits : undefined);
+ });
+
+ }
+ }
+ );
+});
diff --git a/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/palette.js b/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/palette.js
index 52fa98404..68d1b4da8 100644
--- a/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/palette.js
+++ b/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/palette.js
@@ -1,300 +1,380 @@
-# Copyright 2012-2024 The Apache Software Foundation
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http:#www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-# ## t5/core/palette
-#
-# Support for the `core/Palette` component.
-define ["t5/core/dom", "underscore", "t5/core/events"],
- (dom, _, events) ->
-
- isSelected = (option) -> option.selected
-
- class PaletteController
-
- constructor: (id) ->
- @selected = (dom id)
- @container = @selected.findParent ".palette"
- @available = @container.findFirst ".palette-available select"
- @hidden = @container.findFirst "input[type=hidden]"
+/*
+ * decaffeinate suggestions:
+ * DS101: Remove unnecessary use of Array.from
+ * DS102: Remove unnecessary code created because of implicit returns
+ * DS205: Consider reworking code to avoid use of IIFEs
+ * Full docs: https://github.com/decaffeinate/decaffeinate/blob/main/docs/suggestions.md
+ */
+// Copyright 2012-2024 The Apache Software Foundation
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http:#www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// ## t5/core/palette
+//
+// Support for the `core/Palette` component.
+define(["t5/core/dom", "underscore", "t5/core/events"],
+ function(dom, _, events) {
+
+ const isSelected = option => option.selected;
+
+ class PaletteController {
+
+ constructor(id) {
+ this.selected = (dom(id));
+ this.container = this.selected.findParent(".palette");
+ this.available = this.container.findFirst(".palette-available select");
+ this.hidden = this.container.findFirst("input[type=hidden]");
+
+ this.select = this.container.findFirst("[data-action=select]");
+ this.deselect = this.container.findFirst("[data-action=deselect]");
+
+ this.moveUp = this.container.findFirst("[data-action=move-up]");
+ this.moveDown = this.container.findFirst("[data-action=move-down]");
+
+ // Track where reorder is allowed based on whether the buttons actually exist
+ this.reorder = this.moveUp !== null;
+
+ this.valueToOrderIndex = {};
+
+ for (let i = 0; i < this.available.element.options.length; i++) {
+ var option = this.available.element.options[i];
+ this.valueToOrderIndex[option.value] = i;
+ }
+
+ // This occurs even when the palette is disabled, to present the
+ // values correctly. Otherwise it looks like nothing is selected.
+ this.initialTransfer();
+
+ if (!this.selected.element.disabled) {
+ this.updateButtons();
+ this.bindEvents();
+ }
+ }
+
+ initialTransfer() {
+ // Get the values for options that should move over
+ let i, option;
+ const values = JSON.parse(this.hidden.value());
+ const valueToPosition = {};
+
+ for (i = 0; i < values.length; i++) {
+ var v = values[i];
+ valueToPosition[v] = i;
+ }
+
+ const e = this.available.element;
+
+ const movers = [];
+
+ for (i = e.options.length - 1; i >= 0; i--) {
+ option = e.options[i];
+ var {
+ value
+ } = option;
+ var pos = valueToPosition[value];
+ if (pos !== undefined) {
+ movers[pos] = option;
+ e.remove(i);
+ }
+ }
+
+ return (() => {
+ const result = [];
+ for (option of Array.from(movers)) {
+ result.push(this.selected.element.add(option));
+ }
+ return result;
+ })();
+ }
+
+ // Invoked after any change to the selections list to update the hidden field as well as the
+ // buttons' state.
+ updateAfterChange() {
+ this.updateHidden();
+ return this.updateButtons();
+ }
+
+ updateHidden() {
+ const values = (Array.from(this.selected.element.options).map((option) => option.value));
+ return this.hidden.value(JSON.stringify(values));
+ }
+
+ bindEvents() {
+ this.container.on("change", "select", () => {
+ this.updateButtons();
+ return false;
+ });
- @select = @container.findFirst "[data-action=select]"
- @deselect = @container.findFirst "[data-action=deselect]"
+ this.select.on("click", () => {
+ this.doSelect();
+ return false;
+ });
- @moveUp = @container.findFirst "[data-action=move-up]"
- @moveDown = @container.findFirst "[data-action=move-down]"
+ this.available.on("dblclick", () => {
+ this.doSelect();
+ return false;
+ });
- # Track where reorder is allowed based on whether the buttons actually exist
- @reorder = @moveUp isnt null
+ this.deselect.on("click", () => {
+ this.doDeselect();
+ return false;
+ });
- @valueToOrderIndex = {}
+ this.selected.on("dblclick", () => {
+ this.doDeselect();
+ return false;
+ });
- for option,i in @available.element.options
- @valueToOrderIndex[option.value] = i
+ if (this.reorder) {
+ this.moveUp.on("click", () => {
+ this.doMoveUp();
+ return false;
+ });
- # This occurs even when the palette is disabled, to present the
- # values correctly. Otherwise it looks like nothing is selected.
- @initialTransfer()
+ return this.moveDown.on("click", () => {
+ this.doMoveDown();
+ return false;
+ });
+ }
+ }
- unless @selected.element.disabled
- @updateButtons()
- @bindEvents()
+ // Invoked whenever the selections in either list changes or after an updates; figures out which buttons
+ // should be enabled and which disabled.
+ updateButtons() {
+ this.select.element.disabled = this.available.element.selectedIndex < 0;
- initialTransfer: ->
- # Get the values for options that should move over
- values = JSON.parse @hidden.value()
- valueToPosition = {}
+ const nothingSelected = this.selected.element.selectedIndex < 0;
- for v, i in values
- valueToPosition[v] = i
+ this.deselect.element.disabled = nothingSelected;
- e = @available.element
+ if (this.reorder) {
+ this.moveUp.element.disabled = nothingSelected || this.allSelectionsAtTop();
+ return this.moveDown.element.disabled = nothingSelected || this.allSelectionsAtBottom();
+ }
+ }
- movers = []
+ doSelect() { return this.transferOptions(this.available, this.selected, this.reorder); }
- for i in [(e.options.length - 1)..0] by -1
- option = e.options[i]
- value = option.value
- pos = valueToPosition[value]
- unless pos is undefined
- movers[pos] = option
- e.remove i
+ doDeselect() { return this.transferOptions(this.selected, this.available, false); }
- for option in movers
- @selected.element.add option
+ doMoveUp() {
+ let options = _.toArray(this.selected.element.options);
- # Invoked after any change to the selections list to update the hidden field as well as the
- # buttons' state.
- updateAfterChange: ->
- @updateHidden()
- @updateButtons()
+ const groups = _.partition(options, isSelected);
- updateHidden: ->
- values = (option.value for option in @selected.element.options)
- @hidden.value JSON.stringify values
+ const movers = groups[0];
- bindEvents: ->
- @container.on "change", "select", =>
- @updateButtons()
- return false
+ // The element before the first selected element is the pivot; all the selected elements will
+ // move before the pivot. If there is no pivot, the elements are shifted to the front of the list.
+ const firstMoverIndex = _.first(movers).index;
+ const pivot = options[firstMoverIndex - 1];
- @select.on "click", =>
- @doSelect()
- return false
+ options = groups[1];
- @available.on "dblclick", =>
- @doSelect()
- return false
+ const splicePos = pivot ? _.indexOf(options, pivot) : 0;
- @deselect.on "click", =>
- @doDeselect()
- return false
+ movers.reverse();
- @selected.on "dblclick", =>
- @doDeselect()
- return false
+ for (var o of Array.from(movers)) {
+ options.splice(splicePos, 0, o);
+ }
- if @reorder
- @moveUp.on "click", =>
- @doMoveUp()
- return false
+ return this.reorderSelected(options);
+ }
- @moveDown.on "click", =>
- @doMoveDown()
- return false
- # Invoked whenever the selections in either list changes or after an updates; figures out which buttons
- # should be enabled and which disabled.
- updateButtons: ->
- @select.element.disabled = @available.element.selectedIndex < 0
+ doMoveDown() {
+ let options = _.toArray(this.selected.element.options);
- nothingSelected = @selected.element.selectedIndex < 0
+ const groups = _.partition(options, isSelected);
- @deselect.element.disabled = nothingSelected
+ const movers = groups[0];
- if @reorder
- @moveUp.element.disabled = nothingSelected or @allSelectionsAtTop()
- @moveDown.element.disabled = nothingSelected or @allSelectionsAtBottom()
+ // The element after the last selected element is the pivot; all the selected elements will
+ // move after the pivot. If there is no pivot, the elements are shifted to the end of the list.
+ const lastMoverIndex = movers.slice(-1)[0].index;
+ const pivot = options[lastMoverIndex + 1];
- doSelect: -> @transferOptions @available, @selected, @reorder
+ options = groups[1];
- doDeselect: -> @transferOptions @selected, @available, false
+ const splicePos = pivot ? _.indexOf(options, pivot) + 1 : options.length;
- doMoveUp: ->
- options = _.toArray @selected.element.options
+ movers.reverse();
- groups = _.partition options, isSelected
+ for (var o of Array.from(movers)) {
+ options.splice(splicePos, 0, o);
+ }
- movers = groups[0]
+ return this.reorderSelected(options);
+ }
- # The element before the first selected element is the pivot; all the selected elements will
- # move before the pivot. If there is no pivot, the elements are shifted to the front of the list.
- firstMoverIndex = _.first(movers).index
- pivot = options[firstMoverIndex - 1]
+ // Reorders the selected options to the provided list of options; handles triggering the willUpdate and
+ // didUpdate events.
+ reorderSelected(options) {
- options = groups[1]
+ return this.performUpdate(true, options, () => {
- splicePos = if pivot then _.indexOf options, pivot else 0
+ this.deleteOptions(this.selected);
- movers.reverse()
+ return Array.from(options).map((o) =>
+ this.selected.element.add(o, null));
+ });
+ }
- for o in movers
- options.splice splicePos, 0, o
+ // Performs the update, which includes the willChange and didChange events.
+ performUpdate(reorder, selectedOptions, updateCallback) {
- @reorderSelected options
+ let canceled = false;
+ const doUpdate = () => {
+ updateCallback();
- doMoveDown: ->
- options = _.toArray @selected.element.options
+ this.selected.trigger(events.palette.didChange, { selectedOptions, reorder });
- groups = _.partition options, isSelected
+ return this.updateAfterChange();
+ };
- movers = groups[0]
+ const memo = {
+ selectedOptions,
+ reorder,
+ cancel() { return canceled = true; },
+ defer() {
+ canceled = true;
+ return doUpdate;
+ }
+ };
- # The element after the last selected element is the pivot; all the selected elements will
- # move after the pivot. If there is no pivot, the elements are shifted to the end of the list.
- lastMoverIndex = movers[-1..-1][0].index
- pivot = options[lastMoverIndex + 1]
+ this.selected.trigger(events.palette.willChange, memo);
- options = groups[1]
+ if (!canceled) { return doUpdate(); }
+ }
- splicePos = if pivot then _.indexOf(options, pivot) + 1 else options.length
+ // Deletes all options from a select (an ElementWrapper), prior to new options being populated in.
+ deleteOptions(select) {
- movers.reverse()
+ const e = select.element;
- for o in movers
- options.splice splicePos, 0, o
+ return (() => {
+ const result = [];
+ for (let i = e.length - 1; i >= 0; i--) {
+ result.push(e.remove(i));
+ }
+ return result;
+ })();
+ }
- @reorderSelected options
+ // Moves options between the available and selected lists, including event notifiations before and after.
+ transferOptions(from, to, atEnd) {
- # Reorders the selected options to the provided list of options; handles triggering the willUpdate and
- # didUpdate events.
- reorderSelected: (options) ->
+ let o;
+ if (from.element.selectedIndex === -1) {
+ return;
+ }
- @performUpdate true, options, =>
+ // This could be done in a single pass, but:
+ const movers = _.filter(from.element.options, isSelected);
+ const fromOptions = _.reject(from.element.options, isSelected);
- @deleteOptions @selected
+ const toOptions = _.toArray(to.element.options);
- for o in options
- @selected.element.add o, null
+ for (o of Array.from(movers)) {
+ this.insertOption(toOptions, o, atEnd);
+ }
- # Performs the update, which includes the willChange and didChange events.
- performUpdate: (reorder, selectedOptions, updateCallback) ->
+ const isSelectedSelect = to === this.selected;
+ const selectedOptions = isSelectedSelect ? toOptions : fromOptions;
- canceled = false
+ return this.performUpdate(false, selectedOptions, () => {
+ let i;
+ for (i = from.element.length - 1; i >= 0; i--) {
+ if (from.element.options[i].selected) {
+ from.element.remove(i);
+ }
+ }
- doUpdate = =>
- updateCallback()
+ // A bit ugly: update the to select by removing all, then adding back in.
- @selected.trigger events.palette.didChange, { selectedOptions, reorder }
+ for (i = to.element.length - 1; i >= 0; i--) {
+ to.element.options[i].selected = false;
+ to.element.remove(i);
+ }
- @updateAfterChange()
-
- memo =
- selectedOptions: selectedOptions
- reorder: reorder
- cancel: -> canceled = true
- defer: ->
- canceled = true
- return doUpdate
-
- @selected.trigger events.palette.willChange, memo
-
- doUpdate() unless canceled
-
- # Deletes all options from a select (an ElementWrapper), prior to new options being populated in.
- deleteOptions: (select) ->
-
- e = select.element
-
- for i in [(e.length - 1)..0] by -1
- e.remove i
-
- # Moves options between the available and selected lists, including event notifiations before and after.
- transferOptions: (from, to, atEnd) ->
-
- if from.element.selectedIndex is -1
- return
-
- # This could be done in a single pass, but:
- movers = _.filter from.element.options, isSelected
- fromOptions = _.reject from.element.options, isSelected
-
- toOptions = _.toArray to.element.options
-
- for o in movers
- @insertOption toOptions, o, atEnd
-
- isSelectedSelect = to is @selected
- selectedOptions = if isSelectedSelect then toOptions else fromOptions
-
- @performUpdate false, selectedOptions, =>
- for i in [(from.element.length - 1)..0] by -1
- if from.element.options[i].selected
- from.element.remove i
-
- # A bit ugly: update the to select by removing all, then adding back in.
-
- for i in [(to.element.length - 1)..0] by -1
- to.element.options[i].selected = false
- to.element.remove i
-
- for o in toOptions
- groupIdx = o.getAttribute('data-optgroup-idx')
- if isSelectedSelect or !groupIdx or groupIdx == ''
- to.element.add o, null
- else
- group = to.element.children[parseInt(groupIdx)]
- group.appendChild o
-
-
- insertOption: (options, option, atEnd) ->
-
- unless atEnd
- optionOrder = @valueToOrderIndex[option.value]
- before = _.find options, (o) => @valueToOrderIndex[o.value] > optionOrder
-
- if before
- i = _.indexOf options, before
- options.splice i, 0, option
- else
- options.push option
-
-
- indexOfLastSelection: (select) ->
- e = select.element
- if e.selectedIndex < 0
- return -1
-
- for i in [(e.options.length - 1)..(e.selectedIndex)] by -1
- if e.options[i].selected
- return i
-
- return -1
-
- allSelectionsAtTop: ->
- last = @indexOfLastSelection @selected
- options = _.toArray @selected.element.options
-
- _(options[0..last]).all (o) -> o.selected
-
- allSelectionsAtBottom: ->
- e = @selected.element
- last = e.selectedIndex
- options = _.toArray e.options
-
- _(options[last..]).all (o) -> o.selected
-
-
- # Export just the initializer function
- (id) -> new PaletteController(id)
\ No newline at end of file
+ return (() => {
+ const result = [];
+ for (o of Array.from(toOptions)) {
+ var groupIdx = o.getAttribute('data-optgroup-idx');
+ if (isSelectedSelect || !groupIdx || (groupIdx === '')) {
+ result.push(to.element.add(o, null));
+ } else {
+ var group = to.element.children[parseInt(groupIdx)];
+ result.push(group.appendChild(o));
+ }
+ }
+ return result;
+ })();
+ });
+ }
+
+
+ insertOption(options, option, atEnd) {
+
+ let before;
+ if (!atEnd) {
+ const optionOrder = this.valueToOrderIndex[option.value];
+ before = _.find(options, o => this.valueToOrderIndex[o.value] > optionOrder);
+ }
+
+ if (before) {
+ const i = _.indexOf(options, before);
+ return options.splice(i, 0, option);
+ } else {
+ return options.push(option);
+ }
+ }
+
+
+ indexOfLastSelection(select) {
+ const e = select.element;
+ if (e.selectedIndex < 0) {
+ return -1;
+ }
+
+ for (let i = e.options.length - 1, end = e.selectedIndex; i >= end; i--) {
+ if (e.options[i].selected) {
+ return i;
+ }
+ }
+
+ return -1;
+ }
+
+ allSelectionsAtTop() {
+ const last = this.indexOfLastSelection(this.selected);
+ const options = _.toArray(this.selected.element.options);
+
+ return _(options.slice(0, +last + 1 || undefined)).all(o => o.selected);
+ }
+
+ allSelectionsAtBottom() {
+ const e = this.selected.element;
+ const last = e.selectedIndex;
+ const options = _.toArray(e.options);
+
+ return _(options.slice(last)).all(o => o.selected);
+ }
+ }
+
+
+ // Export just the initializer function
+ return id => new PaletteController(id);
+});
\ No newline at end of file
diff --git a/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/select.js b/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/select.js
index f006c7073..3d74fd969 100644
--- a/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/select.js
+++ b/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/select.js
@@ -1,32 +1,36 @@
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http:#www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http:#www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
-# ## t5/core/select
-#
-# Provides a document event handler that triggers an update a zone when the value
-# of a select element within the zone changes.
-define ["t5/core/events", "t5/core/dom", "t5/core/zone"],
+// ## t5/core/select
+//
+// Provides a document event handler that triggers an update a zone when the value
+// of a select element within the zone changes.
+define(["t5/core/events", "t5/core/dom", "t5/core/zone"],
- (events, dom, zone) ->
+ function(events, dom, zone) {
- dom.onDocument "change", "select[data-update-zone]", ->
+ dom.onDocument("change", "select[data-update-zone]", function() {
- containingZone = zone.findZone this
+ const containingZone = zone.findZone(this);
- if containingZone
- containingZone.trigger events.zone.refresh,
- url: @attr "data-update-url"
- parameters:
- "t:selectvalue": @value()
+ if (containingZone) {
+ containingZone.trigger(events.zone.refresh, {
+ url: this.attr("data-update-url"),
+ parameters: {
+ "t:selectvalue": this.value()
+ }
+ }
+ );
+ }
- return
- return
+ });
+});
diff --git a/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/time-interval.js b/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/time-interval.js
index 7221e76ef..2bd17f5be 100644
--- a/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/time-interval.js
+++ b/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/time-interval.js
@@ -1,55 +1,62 @@
-# Copyright 2013 The Apache Software Foundation
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http:#www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-# ## t5/core/time-interval
-#
-# Used with the Interval component to express the interval between two timestamps,
-# or the dynamic difference between now and an end point in the past or future.
-define ["t5/core/dom", "t5/core/moment"],
-(dom, moment) ->
-
- ATTR = "data-timeinterval"
-
- DEFAULT_FORMAT = 'YYYY-MM-DDTHH:mm:ss.SSSZ'
-
- toMoment = (s) -> if s then (moment s, DEFAULT_FORMAT) else moment()
-
- updateElement = (el) ->
- start = toMoment el.attr "data-timeinterval-start"
- end = toMoment el.attr "data-timeinterval-end"
- plain = el.attr "data-timeinterval-plain"
-
- el.update end.from start, plain
- return
-
- updateDynamics = ->
- for el in dom.body.find "[#{ATTR}=dynamic]"
- updateElement el
- return
-
- # Update any dynamic intervals (the ones without a specific start date) about once a second
- setInterval updateDynamics, 1000
-
- dom.scanner "[#{ATTR}=true]", (el) ->
-
- updateElement el
-
- if (el.attr "data-timeinterval-start") and (el.attr "data-timeinterval-end")
- el.attr ATTR, null
- else
- el.attr ATTR, "dynamic"
-
- return
-
- return # no exports
+/*
+ * decaffeinate suggestions:
+ * DS101: Remove unnecessary use of Array.from
+ * Full docs: https://github.com/decaffeinate/decaffeinate/blob/main/docs/suggestions.md
+ */
+// Copyright 2013 The Apache Software Foundation
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http:#www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// ## t5/core/time-interval
+//
+// Used with the Interval component to express the interval between two timestamps,
+// or the dynamic difference between now and an end point in the past or future.
+define(["t5/core/dom", "t5/core/moment"],
+function(dom, moment) {
+
+ const ATTR = "data-timeinterval";
+
+ const DEFAULT_FORMAT = 'YYYY-MM-DDTHH:mm:ss.SSSZ';
+
+ const toMoment = function(s) { if (s) { return (moment(s, DEFAULT_FORMAT)); } else { return moment(); } };
+
+ const updateElement = function(el) {
+ const start = toMoment(el.attr("data-timeinterval-start"));
+ const end = toMoment(el.attr("data-timeinterval-end"));
+ const plain = el.attr("data-timeinterval-plain");
+
+ el.update(end.from(start, plain));
+ };
+
+ const updateDynamics = function() {
+ for (var el of Array.from(dom.body.find(`[${ATTR}=dynamic]`))) {
+ updateElement(el);
+ }
+ };
+
+ // Update any dynamic intervals (the ones without a specific start date) about once a second
+ setInterval(updateDynamics, 1000);
+
+ dom.scanner(`[${ATTR}=true]`, function(el) {
+
+ updateElement(el);
+
+ if ((el.attr("data-timeinterval-start")) && (el.attr("data-timeinterval-end"))) {
+ el.attr(ATTR, null);
+ } else {
+ el.attr(ATTR, "dynamic");
+ }
+
+ });
+
+}); // no exports
diff --git a/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/tree.js b/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/tree.js
index 556dcf1be..78f71dae2 100644
--- a/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/tree.js
+++ b/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/tree.js
@@ -1,114 +1,133 @@
-# Copyright 2012, 2013 The Apache Software Foundation
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http:#www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+/*
+ * decaffeinate suggestions:
+ * DS102: Remove unnecessary code created because of implicit returns
+ * Full docs: https://github.com/decaffeinate/decaffeinate/blob/main/docs/suggestions.md
+ */
+// Copyright 2012, 2013 The Apache Software Foundation
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http:#www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// ## t5/core/tree
+//
+// Handlers to support to the core/Tree Tapestry component.
+define(["t5/core/dom", "t5/core/ajax", "t5/core/zone"],
+ function(dom, ajax) {
+ const TREE = "[data-component-type='core/Tree']";
+ const NODE_ID = "data-node-id";
+ const SELECTOR = `${TREE} [${NODE_ID}]`;
+
+ const LOADING = "tree-children-loading";
+ const LOADED = "tree-children-loaded";
+ const EXPANDED = "tree-expanded";
+ const SELECTED = "selected-leaf-node";
+
+ const send = function(node, action, success) {
+ const container = node.findParent(TREE);
+ const url = container.attr("data-tree-action-url");
+
+ return ajax(url, {
+ data: {
+ "t:action": action,
+ "t:nodeid": node.attr(NODE_ID)
+ },
+ success
+ }
+ );
+ };
+
+ const loadChildren = function(node) {
+
+ // Ignore duplicate requests to load the children.
+ if (node.meta(LOADING)) { return; }
+
+ node.meta(LOADING, true);
+
+ node.addClass("empty-node");
+ node.update("<span class='tree-ajax-wait'/>");
+
+ return send(node, "expand", function(response) {
+ // Remove the Ajax spinner and mark the node as expanded (it will have a "-"
+ // icon instead of a "+" icon)
+ node.update("").addClass(EXPANDED).removeClass("empty-node");
+
+ const label = node.findParent("li").findFirst(".tree-label");
+
+ label.insertAfter(response.json.content);
+
+ node.meta(LOADING, false);
+ return node.meta(LOADED, true);
+ });
+ };
+
+ // toggles a folder in the tree between expanded and collapsed (once data for the folder
+ // has been loaded).
+ const toggle = function(node) {
+ const sublist = node.findParent("li").findFirst("ul");
+
+ if (node.hasClass(EXPANDED)) {
+ node.removeClass(EXPANDED);
+ sublist.hide();
+ send(node, "markCollapsed");
+ return;
+ }
+
+ node.addClass(EXPANDED);
+ sublist.show();
+ return send(node, "markExpanded");
+ };
+
+ // The handler is triggered on the `<span data-node-id=''>` directly inside the `<li>`.
+ const clickHandler = function() {
+
+ // Ignore clicks on leaf nodes, and on folders that are known to be empty.
+ if ((this.parent().hasClass("leaf-node")) || (this.hasClass("empty-node"))) {
+ return false;
+ }
+
+ // If not already loaded then fire off the Ajax request to load the content.
+ if ((this.meta(LOADED)) || (this.hasClass(EXPANDED))) {
+ toggle(this);
+ } else {
+ loadChildren(this);
+ }
+
+ return false;
+ };
+
+ const toggleSelection = function() {
+
+ const selected = this.hasClass(SELECTED);
+
+ const node = this.findParent("li").findFirst(`[${NODE_ID}]`);
+
+ if (selected) {
+ this.removeClass(SELECTED);
+ send(node, "deselect");
+ } else {
+ this.addClass(SELECTED);
+ send(node, "select");
+ }
+
+ return false;
+ };
-# ## t5/core/tree
-#
-# Handlers to support to the core/Tree Tapestry component.
-define ["t5/core/dom", "t5/core/ajax", "t5/core/zone"],
- (dom, ajax) ->
- TREE = "[data-component-type='core/Tree']"
- NODE_ID = "data-node-id"
- SELECTOR = "#{TREE} [#{NODE_ID}]"
+ dom.onDocument("click", SELECTOR, clickHandler);
- LOADING = "tree-children-loading"
- LOADED = "tree-children-loaded"
- EXPANDED = "tree-expanded"
- SELECTED = "selected-leaf-node"
+ dom.onDocument("click",
+ `${TREE}[data-tree-node-selection-enabled] LI.leaf-node > .tree-label`,
+ toggleSelection);
- send = (node, action, success) ->
- container = node.findParent TREE
- url = container.attr "data-tree-action-url"
- ajax url,
- data:
- "t:action": action
- "t:nodeid": node.attr NODE_ID
- success: success
-
- loadChildren = (node) ->
-
- # Ignore duplicate requests to load the children.
- return if node.meta LOADING
-
- node.meta LOADING, true
-
- node.addClass "empty-node"
- node.update "<span class='tree-ajax-wait'/>"
-
- send node, "expand", (response) ->
- # Remove the Ajax spinner and mark the node as expanded (it will have a "-"
- # icon instead of a "+" icon)
- node.update("").addClass(EXPANDED).removeClass("empty-node")
-
- label = node.findParent("li").findFirst(".tree-label")
-
- label.insertAfter response.json.content
-
- node.meta LOADING, false
- node.meta LOADED, true
-
- # toggles a folder in the tree between expanded and collapsed (once data for the folder
- # has been loaded).
- toggle = (node) ->
- sublist = node.findParent("li").findFirst("ul")
-
- if node.hasClass EXPANDED
- node.removeClass EXPANDED
- sublist.hide()
- send node, "markCollapsed"
- return
-
- node.addClass EXPANDED
- sublist.show()
- send node, "markExpanded"
-
- # The handler is triggered on the `<span data-node-id=''>` directly inside the `<li>`.
- clickHandler = ->
-
- # Ignore clicks on leaf nodes, and on folders that are known to be empty.
- if (@parent().hasClass "leaf-node") or (@hasClass "empty-node")
- return false
-
- # If not already loaded then fire off the Ajax request to load the content.
- if (@meta LOADED) or (@hasClass EXPANDED)
- toggle this
- else
- loadChildren this
-
- return false
-
- toggleSelection = ->
-
- selected = @hasClass SELECTED
-
- node = @findParent("li").findFirst("[#{NODE_ID}]")
-
- if selected
- @removeClass SELECTED
- send node, "deselect"
- else
- @addClass SELECTED
- send node, "select"
-
- return false
-
- dom.onDocument "click", SELECTOR, clickHandler
-
- dom.onDocument "click",
- "#{TREE}[data-tree-node-selection-enabled] LI.leaf-node > .tree-label",
- toggleSelection
-
-
- return null
+ return null;
+});
diff --git a/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/utils.js b/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/utils.js
index c89b2941a..b556d58e7 100644
--- a/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/utils.js
+++ b/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/utils.js
@@ -1,59 +1,74 @@
-# Copyright 2012, 2013 The Apache Software Foundation
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http:#www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-## t5/core/utils
-#
-# A few handy functions.
-define ["underscore"],
-
- (_) ->
-
- trim = (input) ->
- if String.prototype.trim
- input.trim()
- else
- input.replace(/^\s+/, '').replace(/\s+$/, '')
-
- # Extends a URL, adding parameters and values from the params object. The values must already
- # be URI encoded.
- extendURL = (url, params) ->
-
- sep = if url.indexOf("?") >= 0 then "&" else "?"
-
- for name, value of params
- url = url + sep + name + "=" + value
- sep = "&"
-
- return url
-
- exports =
- trim: trim
- extendURL: extendURL
-
- startsWith: (string, pattern) -> (string.indexOf pattern) is 0
- # Trims leading and trailing whitespace from a string. Delegates to String.prototype.trim if present.
- # Determines if the input is a blank string, or null, or an empty array.
- isBlank: (input) ->
-
- return true if input is null
-
- if _.isArray input
- return input.length is 0
+/*
+ * decaffeinate suggestions:
+ * DS102: Remove unnecessary code created because of implicit returns
+ * Full docs: https://github.com/decaffeinate/decaffeinate/blob/main/docs/suggestions.md
+ */
+// Copyright 2012, 2013 The Apache Software Foundation
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http:#www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+//# t5/core/utils
+//
+// A few handy functions.
+define(["underscore"],
+
+ function(_) {
+
+ let exports;
+ const trim = function(input) {
+ if (String.prototype.trim) {
+ return input.trim();
+ } else {
+ return input.replace(/^\s+/, '').replace(/\s+$/, '');
+ }
+ };
+
+ // Extends a URL, adding parameters and values from the params object. The values must already
+ // be URI encoded.
+ const extendURL = function(url, params) {
+
+ let sep = url.indexOf("?") >= 0 ? "&" : "?";
+
+ for (var name in params) {
+ var value = params[name];
+ url = url + sep + name + "=" + value;
+ sep = "&";
+ }
+
+ return url;
+ };
+
+ return exports = {
+ trim,
+ extendURL,
+
+ startsWith(string, pattern) { return (string.indexOf(pattern)) === 0; },
+ // Trims leading and trailing whitespace from a string. Delegates to String.prototype.trim if present.
+ // Determines if the input is a blank string, or null, or an empty array.
+ isBlank(input) {
+
+ if (input === null) { return true; }
+
+ if (_.isArray(input)) {
+ return input.length === 0;
+ }
- return false if typeof input is "boolean"
+ if (typeof input === "boolean") { return false; }
- return (exports.trim input).length is 0
+ return (exports.trim(input)).length === 0;
+ },
- # Splits the input string into words separated by whitespace
- split: (str) -> _(str.split " ").reject((s) -> s is "")
+ // Splits the input string into words separated by whitespace
+ split(str) { return _(str.split(" ")).reject(s => s === ""); }
+ };
+});
diff --git a/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/validation.js b/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/validation.js
index b140f0b03..d54bcd024 100644
--- a/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/validation.js
+++ b/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/validation.js
@@ -1,178 +1,220 @@
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http:#www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-# ## t5/core/validation
-#
-# Support for Tapestry's built-in set of translators and validators.
-#
-define ["underscore", "t5/core/dom", "t5/core/events", "t5/core/utils", "t5/core/messages", "t5/core/fields"],
- (_, dom, events, utils, messages) ->
+/*
+ * decaffeinate suggestions:
+ * DS101: Remove unnecessary use of Array.from
+ * DS102: Remove unnecessary code created because of implicit returns
+ * Full docs: https://github.com/decaffeinate/decaffeinate/blob/main/docs/suggestions.md
+ */
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http:#www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// ## t5/core/validation
+//
+// Support for Tapestry's built-in set of translators and validators.
+//
+define(["underscore", "t5/core/dom", "t5/core/events", "t5/core/utils", "t5/core/messages", "t5/core/fields"],
+ function(_, dom, events, utils, messages) {
+
+ const REGEXP_META = "t5:regular-expression";
+
+ const minus = messages("decimal-symbols.minus");
+ const grouping = messages("decimal-symbols.group");
+ const decimal = messages("decimal-symbols.decimal");
+
+ // Formats a string for a localized number into a simple number. This uses localization
+ // information provided by `t5/core/messages` to remove grouping seperators and convert the
+ // minus sign and decimal seperator into english norms ("-" and ".") that are compatible
+ // with the `Number` constructor. May throw `Error` if the input can not be parsed.
+ //
+ // A little state machine does the parsing; the input may have a leading minus sign.
+ // It then consists primarily of numeric digits. At least one digit must occur
+ // between each grouping character. Grouping characters are not allowed
+ // after the decimal point.
+ //
+ // * input - input string to be converted
+ // * isInteger - restrict to integer values (decimal point not allowed)
+ const parseNumber = function(input, isInteger) {
+
+ let canonical = "";
+
+ const accept = ch => canonical += ch;
+
+ const acceptDigitOnly = function(ch) {
+ if ((ch < "0") || (ch > "9")) {
+ throw new Error(messages("core-input-not-numeric"));
+ }
+
+ accept(ch);
+ };
+
+ const mustBeDigit = function(ch) {
+ acceptDigitOnly(ch);
+ return any;
+ };
+
+ var decimalPortion = function(ch) {
+ acceptDigitOnly(ch);
+ return decimalPortion;
+ };
+
+ var any = function(ch) {
+ switch (ch) {
+ case grouping: return mustBeDigit;
+ case decimal:
+ if (isInteger) {
+ throw new Error(messages("core-input-not-integer"));
+ }
+
+ accept(".");
+ return decimalPortion;
+ default:
+ return mustBeDigit(ch);
+ }
+ };
+
+ const leadingMinus = function(ch) {
+ if (ch === minus) {
+ accept("-");
+ return mustBeDigit;
+ } else {
+ return any(ch);
+ }
+ };
+
+ let state = leadingMinus;
+
+ for (var ch of Array.from(utils.trim(input))) {
+ state = (state(ch));
+ }
+
+ return Number(canonical);
+ };
+
+ const matches = function(input, re) {
+ const groups = input.match(re);
+
+ // Unlike Java, there isn't an easy way to match the entire string. This
+ // gets the job done.
+
+ if (groups === null) { return false; }
+
+ return groups[0] === input;
+ };
+
+ const emailRE = new RegExp("[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?\\.)+[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?");
+
+ const translate = function(field, memo, isInteger) {
+ try {
+ const result = parseNumber(memo.value, isInteger);
+
+ if (_.isNaN(result)) {
+ throw messages("core-input-not-numeric");
+ }
+
+ return memo.translated = result;
+ } catch (e) {
+ memo.error = (field.attr("data-translation-message")) || e.message || "ERROR";
+ return false;
+ }
+ };
+
+ dom.onDocument(events.field.optional, "[data-optionality=required]", function(event, memo) {
+
+ if (utils.isBlank(memo.value)) {
+ return memo.error = (this.attr("data-required-message")) || "REQUIRED";
+ }
+ });
+
+ dom.onDocument(events.field.translate, "[data-translation=numeric]", function(event, memo) {
+ return translate(this, memo, false);
+ });
+
+ dom.onDocument(events.field.translate, "[data-translation=integer]", function(event, memo) {
+ return translate(this, memo, true);
+ });
+
+ dom.onDocument(events.field.validate, "[data-validate-min-length]", function(event, memo) {
+ const min = parseInt(this.attr("data-validate-min-length"));
+
+ if (memo.translated.length < min) {
+ memo.error = (this.attr("data-min-length-message")) || "TOO SHORT";
+ return false;
+ }
+ });
+
+ dom.onDocument(events.field.validate, "[data-validate-max-length]", function(event, memo) {
+ const max = parseInt(this.attr("data-validate-max-length"));
+
+ if (memo.translated.length > max) {
+ memo.error = (this.attr("data-max-length-message")) || "TOO LONG";
+ return false;
+ }
+ });
+
+ dom.onDocument(events.field.validate, "[data-validate-max]", function(event, memo) {
+ const max = parseInt(this.attr("data-validate-max"));
+
+ if (memo.translated > max) {
+ memo.error = (this.attr("data-max-message")) || "TOO LARGE";
+ return false;
+ }
+ });
+
+ dom.onDocument(events.field.validate, "[data-validate-min]", function(event, memo) {
+ const min = parseInt(this.attr("data-validate-min"));
+
+ if (memo.translated < min) {
+ memo.error = (this.attr("data-min-message")) || "TOO SMALL";
+ return false;
+ }
+ });
- REGEXP_META = "t5:regular-expression"
-
- minus = messages "decimal-symbols.minus"
- grouping = messages "decimal-symbols.group"
- decimal = messages "decimal-symbols.decimal"
-
- # Formats a string for a localized number into a simple number. This uses localization
- # information provided by `t5/core/messages` to remove grouping seperators and convert the
- # minus sign and decimal seperator into english norms ("-" and ".") that are compatible
- # with the `Number` constructor. May throw `Error` if the input can not be parsed.
- #
- # A little state machine does the parsing; the input may have a leading minus sign.
- # It then consists primarily of numeric digits. At least one digit must occur
- # between each grouping character. Grouping characters are not allowed
- # after the decimal point.
- #
- # * input - input string to be converted
- # * isInteger - restrict to integer values (decimal point not allowed)
- parseNumber = (input, isInteger) ->
+ dom.onDocument(events.field.validate, "[data-validate-email]", function(event, memo) {
- canonical = ""
+ if (!matches(memo.translated, emailRE)) {
+ memo.error = (this.attr("data-email-message")) || "INVALID EMAIL";
+ return false;
+ }
+ });
- accept = (ch) -> canonical += ch
+ dom.onDocument(events.field.validate, "[data-validate-regexp]", function(event, memo) {
- acceptDigitOnly = (ch) ->
- if ch < "0" or ch > "9"
- throw new Error messages "core-input-not-numeric"
+ // Cache the compiled regular expression.
+ let re = this.meta(REGEXP_META);
- accept ch
- return
+ if (!re) {
+ re = new RegExp(this.attr("data-validate-regexp"));
+ this.meta(REGEXP_META, re);
+ }
- mustBeDigit = (ch) ->
- acceptDigitOnly ch
- return any
+ if (!matches(memo.translated, re)) {
+ memo.error = (this.attr("data-regexp-message")) || "INVALID";
+ return false;
+ }
+ });
- decimalPortion = (ch) ->
- acceptDigitOnly ch
- return decimalPortion
+ dom.onDocument(events.field.validate, "[data-expected-status=checked]", function(event, memo) {
- any = (ch) ->
- switch ch
- when grouping then return mustBeDigit
- when decimal
- if isInteger
- throw new Error messages "core-input-not-integer"
+ if (!memo.value) {
+ return memo.error = (this.attr("data-checked-message")) || "MUST BE CHECKED";
+ }
+ });
- accept "."
- return decimalPortion
- else
- mustBeDigit ch
-
- leadingMinus = (ch) ->
- if ch is minus
- accept "-"
- return mustBeDigit
- else
- any ch
-
- state = leadingMinus
-
- for ch in utils.trim input
- state = (state ch)
-
- return Number canonical
-
- matches = (input, re) ->
- groups = input.match re
-
- # Unlike Java, there isn't an easy way to match the entire string. This
- # gets the job done.
-
- return false if groups is null
-
- groups[0] is input
-
- emailRE = new RegExp("[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?\\.)+[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?")
-
- translate = (field, memo, isInteger) ->
- try
- result = parseNumber memo.value, isInteger
-
- if _.isNaN result
- throw messages "core-input-not-numeric"
-
- memo.translated = result
- catch e
- memo.error = (field.attr "data-translation-message") or e.message or "ERROR"
- return false
-
- dom.onDocument events.field.optional, "[data-optionality=required]", (event, memo) ->
-
- if utils.isBlank memo.value
- memo.error = (@attr "data-required-message") or "REQUIRED"
-
- dom.onDocument events.field.translate, "[data-translation=numeric]", (event, memo) ->
- translate this, memo, false
-
- dom.onDocument events.field.translate, "[data-translation=integer]", (event, memo) ->
- translate this, memo, true
-
- dom.onDocument events.field.validate, "[data-validate-min-length]", (event, memo) ->
- min = parseInt @attr "data-validate-min-length"
-
- if memo.translated.length < min
- memo.error = (@attr "data-min-length-message") or "TOO SHORT"
- return false
-
- dom.onDocument events.field.validate, "[data-validate-max-length]", (event, memo) ->
- max = parseInt @attr "data-validate-max-length"
-
- if memo.translated.length > max
- memo.error = (@attr "data-max-length-message") or "TOO LONG"
- return false
-
- dom.onDocument events.field.validate, "[data-validate-max]", (event, memo) ->
- max = parseInt @attr "data-validate-max"
-
- if memo.translated > max
- memo.error = (@attr "data-max-message") or "TOO LARGE"
- return false
-
- dom.onDocument events.field.validate, "[data-validate-min]", (event, memo) ->
- min = parseInt @attr "data-validate-min"
-
- if memo.translated < min
- memo.error = (@attr "data-min-message") or "TOO SMALL"
- return false
-
- dom.onDocument events.field.validate, "[data-validate-email]", (event, memo) ->
-
- unless (matches memo.translated, emailRE)
- memo.error = (@attr "data-email-message") or "INVALID EMAIL"
- return false
-
- dom.onDocument events.field.validate, "[data-validate-regexp]", (event, memo) ->
-
- # Cache the compiled regular expression.
- re = @meta REGEXP_META
-
- unless re
- re = new RegExp(@attr "data-validate-regexp")
- @meta REGEXP_META, re
-
- unless (matches memo.translated, re)
- memo.error = (@attr "data-regexp-message") or "INVALID"
- return false
-
- dom.onDocument events.field.validate, "[data-expected-status=checked]", (event, memo) ->
-
- unless memo.value
- memo.error = (@attr "data-checked-message") or "MUST BE CHECKED"
-
- dom.onDocument events.field.validate, "[data-expected-status=unchecked]", (event, memo) ->
-
- if memo.value
- memo.error = (@attr "data-checked-message") or "MUST NOT BE CHECKED"
-
- # Export the number parser, just to be nice (and to support some testing).
- return { parseNumber }
\ No newline at end of file
+ dom.onDocument(events.field.validate, "[data-expected-status=unchecked]", function(event, memo) {
+
+ if (memo.value) {
+ return memo.error = (this.attr("data-checked-message")) || "MUST NOT BE CHECKED";
+ }
+ });
+
+ // Export the number parser, just to be nice (and to support some testing).
+ return { parseNumber };
+});
\ No newline at end of file
diff --git a/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/zone-refresh.js b/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/zone-refresh.js
index a6b743b9c..8082bdd48 100644
--- a/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/zone-refresh.js
+++ b/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/zone-refresh.js
@@ -1,68 +1,78 @@
-# Copyright 2012 The Apache Software Foundation
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http:#www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-# ## t5/core/zone-refresh
-define ["t5/core/events", "t5/core/dom", "t5/core/console"],
- (events, dom, console) ->
-
- # Initialize a timer for the zone at the specified period (in seconds). The zone will be
- # refreshed with the provided URL.
- initialize = (zoneId, period, url) ->
- zone = dom zoneId
-
- unless zone
- console.err "Zone #{zoneId} not found for periodic refresh."
- return
-
- # Only one periodic refresh per zone.
- return if zone.meta "periodic-refresh"
-
- zone.meta "periodic-refresh", true
-
- executing = false
-
- # Whenever the zone updates, we can clear the executing flag.
-
- zone.on events.zone.didUpdate, ->
- executing = false
- return
-
- cleanUp = ->
- window.clearInterval intervalId
- zone = null
- return
-
- handler = ->
- # Don't clog things up if the response rate is too slow
- return if executing
-
- # If the zone element is no longer part of the DOM, stop the
- # timer
-
- unless (zone.closest 'body')
- cleanUp()
- return
-
- # Set the flag now, it will clear when the zone updates.
- executing = true
-
- zone.trigger events.zone.refresh, { url }
-
- intervalId = window.setInterval handler, period * 1000
-
- # Not sure if this is needed except for IE:
- (dom window).on "beforeunload", cleanUp
-
- # export the single function:
- return initialize
+/*
+ * decaffeinate suggestions:
+ * DS102: Remove unnecessary code created because of implicit returns
+ * Full docs: https://github.com/decaffeinate/decaffeinate/blob/main/docs/suggestions.md
+ */
+// Copyright 2012 The Apache Software Foundation
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http:#www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// ## t5/core/zone-refresh
+define(["t5/core/events", "t5/core/dom", "t5/core/console"],
+ function(events, dom, console) {
+
+ // Initialize a timer for the zone at the specified period (in seconds). The zone will be
+ // refreshed with the provided URL.
+ const initialize = function(zoneId, period, url) {
+ let zone = dom(zoneId);
+
+ if (!zone) {
+ console.err(`Zone ${zoneId} not found for periodic refresh.`);
+ return;
+ }
+
+ // Only one periodic refresh per zone.
+ if (zone.meta("periodic-refresh")) { return; }
+
+ zone.meta("periodic-refresh", true);
+
+ let executing = false;
+
+ // Whenever the zone updates, we can clear the executing flag.
+
+ zone.on(events.zone.didUpdate, function() {
+ executing = false;
+ });
+
+ const cleanUp = function() {
+ window.clearInterval(intervalId);
+ zone = null;
+ };
+
+ const handler = function() {
+ // Don't clog things up if the response rate is too slow
+ if (executing) { return; }
+
+ // If the zone element is no longer part of the DOM, stop the
+ // timer
+
+ if (!zone.closest('body')) {
+ cleanUp();
+ return;
+ }
+
+ // Set the flag now, it will clear when the zone updates.
+ executing = true;
+
+ return zone.trigger(events.zone.refresh, { url });
+ };
+
+ var intervalId = window.setInterval(handler, period * 1000);
+
+ // Not sure if this is needed except for IE:
+ return (dom(window)).on("beforeunload", cleanUp);
+ };
+
+ // export the single function:
+ return initialize;
+});
diff --git a/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/zone.js b/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/zone.js
index dbcbd5518..639053fb5 100644
--- a/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/zone.js
+++ b/tapestry-core/src/main/coffeescript/META-INF/modules/t5/core/zone.js
@@ -1,160 +1,189 @@
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http:#www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-# ## t5/core/zone
-#
-# Provides a default handler for events related to zones. A zone is any kind of
-# client-side element that can be updated; a zone will normally have a unique id.
-# Typically, a client-side zone element is rendered by, and corresponds to, a server-side
-# core/Zone component; however, certain other components (such as core/ProgressiveDisplay) may
-# also be treated as zones.
-#
-# Most often, a zone is any element with attribute `data-container-type=zone` and corresponds
-# to a core/Zone server-side component.
-define ["t5/core/dom", "t5/core/events", "t5/core/ajax", "t5/core/console", "t5/core/forms", "underscore"],
-
- (dom, events, ajax, console, forms, _) ->
+/*
+ * decaffeinate suggestions:
+ * DS102: Remove unnecessary code created because of implicit returns
+ * DS207: Consider shorter variations of null checks
+ * Full docs: https://github.com/decaffeinate/decaffeinate/blob/main/docs/suggestions.md
+ */
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http:#www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// ## t5/core/zone
+//
+// Provides a default handler for events related to zones. A zone is any kind of
+// client-side element that can be updated; a zone will normally have a unique id.
+// Typically, a client-side zone element is rendered by, and corresponds to, a server-side
+// core/Zone component; however, certain other components (such as core/ProgressiveDisplay) may
+// also be treated as zones.
+//
+// Most often, a zone is any element with attribute `data-container-type=zone` and corresponds
+// to a core/Zone server-side component.
+define(["t5/core/dom", "t5/core/events", "t5/core/ajax", "t5/core/console", "t5/core/forms", "underscore"],
+
+ function(dom, events, ajax, console, forms, _) {
- unless (typeof ajax) == "function"
- console.error "ajax variable is not a function, but instead it is " + JSON.stringify(ajax)
- console.error ajax
- throw new Error "ajax variable is not a function"
+ if ((typeof ajax) !== "function") {
+ console.error("ajax variable is not a function, but instead it is " + JSON.stringify(ajax));
+ console.error(ajax);
+ throw new Error("ajax variable is not a function");
+ }
- # For a given element that may have the `data-update-zone` attribute, locates the
- # zone element. May return null if the zone can not be found (after logging an error
- # to the console).
- #
- # * element - starting point for determining zone
- findZone = (element) ->
- zoneId = element.attr "data-update-zone"
+ // For a given element that may have the `data-update-zone` attribute, locates the
+ // zone element. May return null if the zone can not be found (after logging an error
+ // to the console).
+ //
+ // * element - starting point for determining zone
+ const findZone = function(element) {
+ let zone;
+ const zoneId = element.attr("data-update-zone");
- if zoneId is "^"
- zone = element.findParent "[data-container-type=zone]"
+ if (zoneId === "^") {
+ zone = element.findParent("[data-container-type=zone]");
- if zone is null
- throw new Error "Unable to locate containing zone for #{element}."
+ if (zone === null) {
+ throw new Error(`Unable to locate containing zone for ${element}.`);
+ }
- return zone
+ return zone;
+ }
- zone = dom zoneId
+ zone = dom(zoneId);
- if zone is null
- throw new Error "Unable to locate zone '#{zoneId}'."
+ if (zone === null) {
+ throw new Error(`Unable to locate zone '${zoneId}'.`);
+ }
- return zone
+ return zone;
+ };
- dom.onDocument "click", "a[data-update-zone]", (event) ->
+ dom.onDocument("click", "a[data-update-zone]", function(event) {
- element = @closest "[data-update-zone]"
+ const element = this.closest("[data-update-zone]");
- unless element
- throw new Error "Could not locate containing element with data-update-zone attribute."
+ if (!element) {
+ throw new Error("Could not locate containing element with data-update-zone attribute.");
+ }
- zone = findZone element
+ const zone = findZone(element);
- if zone
- zone.trigger events.zone.refresh, url: element.attr "href"
+ if (zone) {
+ zone.trigger(events.zone.refresh, {url: element.attr("href")});
+ }
- event.nativeEvent.preventDefault()
- return
+ event.nativeEvent.preventDefault();
+ });
- dom.onDocument "submit", "form[data-update-zone]", ->
+ dom.onDocument("submit", "form[data-update-zone]", function() {
- zone = findZone this
+ const zone = findZone(this);
- if zone
- formParameters = forms.gatherParameters this
+ if (zone) {
+ const formParameters = forms.gatherParameters(this);
- zone.trigger events.zone.refresh,
- url: (@attr "action")
+ zone.trigger(events.zone.refresh, {
+ url: (this.attr("action")),
parameters: formParameters
+ }
+ );
+ }
- return false
+ return false;
+ });
- dom.onDocument "submit", "form[data-async-trigger]", ->
+ dom.onDocument("submit", "form[data-async-trigger]", function() {
- formParameters = forms.gatherParameters this
+ const formParameters = forms.gatherParameters(this);
- @addClass "ajax-update"
+ this.addClass("ajax-update");
- ajax (@attr "action"),
- data: formParameters
- complete: => @removeClass "ajax-update"
+ ajax((this.attr("action")), {
+ data: formParameters,
+ complete: () => this.removeClass("ajax-update")
+ }
+ );
- return false
+ return false;
+ });
- dom.onDocument events.zone.update, (event) ->
+ dom.onDocument(events.zone.update, function(event) {
- @trigger events.zone.willUpdate
+ this.trigger(events.zone.willUpdate);
- content = event.memo.content
+ const {
+ content
+ } = event.memo;
- # The server may have passed down the empty string for the content; that removes the existing content.
- # On the other hand, the server may have not provided a content key; in that case, content is undefined
- # which means to leave the existing content alone.
- #
- # Note that currently, the willUpdate and didUpdate events are triggered even when the zone is not actually
- # updated. That may be a bug.
- unless content is undefined
- @update content
+ // The server may have passed down the empty string for the content; that removes the existing content.
+ // On the other hand, the server may have not provided a content key; in that case, content is undefined
+ // which means to leave the existing content alone.
+ //
+ // Note that currently, the willUpdate and didUpdate events are triggered even when the zone is not actually
+ // updated. That may be a bug.
+ if (content !== undefined) {
+ this.update(content);
+ }
- @trigger events.initializeComponents
- @trigger events.zone.didUpdate
+ this.trigger(events.initializeComponents);
+ return this.trigger(events.zone.didUpdate);
+ });
- dom.onDocument events.zone.refresh, (event) ->
+ dom.onDocument(events.zone.refresh, function(event) {
- # This event may be triggered on an element inside the zone, rather than on the zone itself. Scan upwards
- # to find the actual zone.
- zone = @closest "[data-container-type=zone]"
+ // This event may be triggered on an element inside the zone, rather than on the zone itself. Scan upwards
+ // to find the actual zone.
+ const zone = this.closest("[data-container-type=zone]");
- # A Zone inside a form will render some additional parameters to coordinate updates with the Form on the server.
- attr = zone.attr "data-zone-parameters"
+ // A Zone inside a form will render some additional parameters to coordinate updates with the Form on the server.
+ const attr = zone.attr("data-zone-parameters");
- parameters = attr and JSON.parse attr
+ const parameters = attr && JSON.parse(attr);
- simpleIdParams = if zone.attr "data-simple-ids" then {"t:suppress-namespaced-ids": true}
+ const simpleIdParams = zone.attr("data-simple-ids") ? {"t:suppress-namespaced-ids": true} : undefined;
- ajax event.memo.url,
- data: _.extend { "t:zoneid": zone.element.id }, simpleIdParams, parameters, event.memo.parameters
- success: (response) ->
- zone.trigger events.zone.update, content: response.json?.content
+ return ajax(event.memo.url, {
+ data: _.extend({ "t:zoneid": zone.element.id }, simpleIdParams, parameters, event.memo.parameters),
+ success(response) {
+ return zone.trigger(events.zone.update, {content: (response.json != null ? response.json.content : undefined)});
+ }
+ }
+ );
+ });
- dom.onDocument "click", "a[data-async-trigger]", (event)->
- link = @closest 'a[data-async-trigger]'
+ dom.onDocument("click", "a[data-async-trigger]", function(event){
+ const link = this.closest('a[data-async-trigger]');
- link.addClass "ajax-update"
+ link.addClass("ajax-update");
- ajax (link.attr "href"),
- complete: -> link.removeClass "ajax-update"
+ ajax((link.attr("href")),
+ {complete() { return link.removeClass("ajax-update"); }});
- event.nativeEvent.preventDefault()
+ event.nativeEvent.preventDefault();
- return
+ });
- # Locates a zone element by its unique id attribute, and (deferred, to a later event loop cycle),
- # performs a standard refresh of the zone. This is primarily used by the core/ProgressiveDisplay component.
- #
- # * id - client id of the element
- # * url - URL to use to refresh the element.
- deferredZoneUpdate = (id, url) ->
+ // Locates a zone element by its unique id attribute, and (deferred, to a later event loop cycle),
+ // performs a standard refresh of the zone. This is primarily used by the core/ProgressiveDisplay component.
+ //
+ // * id - client id of the element
+ // * url - URL to use to refresh the element.
+ const deferredZoneUpdate = (id, url) => _.defer(function() {
+ const zone = dom(id);
- _.defer ->
- zone = dom id
+ if (zone === null) {
+ console.error(`Could not locate element '${id}' to update.`);
+ return;
+ }
- if zone is null
- console.error "Could not locate element '#{id}' to update."
- return
+ return zone.trigger(events.zone.refresh, { url });});
- zone.trigger events.zone.refresh, { url }
-
- # Most of this module is document-level event handlers, but there's also some exports:
- return { deferredZoneUpdate, findZone }
+ // Most of this module is document-level event handlers, but there's also some exports:
+ return { deferredZoneUpdate, findZone };
+});