You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@juneau.apache.org by ja...@apache.org on 2026/08/26 14:05:34 UTC
(juneau) 02/06: Land the shared chrome scale contract and three disjoint views slices.
This is an automated email from the ASF dual-hosted git repository.
jamesbognar pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/juneau.git
commit c8bf5b330cd8a68cabe5bdf6d4a1561ca6f733ad
Author: James Bognar <ja...@apache.org>
AuthorDate: Wed Aug 26 08:48:51 2026 -0400
Land the shared chrome scale contract and three disjoint views slices.
Four slices developed independently in separate clones, each green on its own gate,
then run together here for the first time: widgets 355, views 1321 (142
browser-tagged skips, pre-existing), console-ui 179, zero failures throughout.
The scale contract is why the other three were held to disjoint lanes.
juneau-views.css now defines one named step set -- --jc-chrome-control-height and
-control-height-compact, -control-padding-x and -control-padding-x-wide,
-font-size-*, -glyph-size and -glyph-size-small, -line-height -- and the hardcoded
32px / 10px / 16px values that had drifted apart across the ribbon, the console
chrome and the theme now reference it. chrome.css, ConsoleChromeMixin and Theme
consume the same tokens. ChromeScaleScanner and ChromeScale_ContractScan_Test pin
the contract so a step cannot be silently re-valued: each assertion checks both
that a declaration references the token and that the token still carries its
declared value, which is what makes the pin resistant to a later edit that keeps
the reference but moves the number.
CardContent adds a deliberate raw-markup card body -- div(rawText(...)), never
escaped -- mirroring the existing Tab/Subtab "trusted, first-party template"
contract instead of inventing a second one. Its javadoc names stored XSS as the
risk explicitly and points at CardFieldList as the live-data alternative, and
CardBody dispatch stays closed and fail-closed on an unknown body, with the
message naming all three known bodies. RawContentSinkScanner was widened to cross
into the widgets module so the new sink is actually covered; the widening was
verified by executing the scanner (32 sinks, 0 violations, 2 of them in widgets)
rather than by reading it, because a wrong relative path would have scanned
nothing and still passed.
The ribbon change normalizes a refresh action into its own trailing group when the
author left it ungrouped. It keys on the pre-existing type === "refresh"
discriminator so no new marker field was invented, and gates on group == null,
which is what makes an explicit .group() opt-out fall out for free rather than
being special-cased. The dangling-divider cleanup runs only when a refresh
actually moves, so a divider already trailing in the author's own declaration is
left alone. The helper is DOM-free and sits above the binding layer, with a Node
harness covering it directly.
SymbolSprite_StemIds_Test pins the sprite's 20 stem ids by set equality ahead of
the glyph redraw, preserving the existing hyphen/underscore inconsistency verbatim
so the guard describes the sprite as it is rather than as it ought to be.
ViewsMixin_Serving_Test.java carries two of these slices at once. The scale
assertions and the ribbon-grouping comment were written in different clones and
merged here by applying the first onto the second rather than overwriting it, so
neither was ever momentarily discarded -- and this commit is the first time that
file has executed with both present.
---
.../rest/server/console/ConsoleChromeMixin.java | 34 +-
.../apache/juneau/rest/server/console/Theme.java | 4 +-
.../resources/org/apache/juneau/console/chrome.css | 10 +-
.../server/console/ConsoleChromeMixin_Test.java | 43 +++
.../juneau/rest/server/views/CardGridTable.java | 36 ++-
.../org/apache/juneau/views/juneau-ribbon.js | 43 ++-
.../org/apache/juneau/views/juneau-views.css | 142 ++++++--
.../rest/server/views/CardGridTable_Emit_Test.java | 38 ++-
.../views/CardGridTable_ViewCardBody_Test.java | 25 +-
.../rest/server/views/ChromeScaleScanner.java | 358 +++++++++++++++++++++
.../views/ChromeScale_ContractScan_Test.java | 144 +++++++++
.../rest/server/views/RawContentSinkScanner.java | 52 ++-
.../server/views/SymbolSprite_StemIds_Test.java | 86 +++++
.../server/views/ViewsJs_RibbonNormalize_Test.java | 232 +++++++++++++
.../rest/server/views/ViewsMixin_Serving_Test.java | 12 +-
.../src/test/js/ribbon-normalize.cjs | 207 ++++++++++++
.../juneau/rest/server/widgets/CardBody.java | 10 +-
.../juneau/rest/server/widgets/CardContent.java | 88 +++++
.../rest/server/widgets/CardContent_Test.java | 61 ++++
19 files changed, 1529 insertions(+), 96 deletions(-)
diff --git a/juneau-rest/juneau-rest-server-console-ui/src/main/java/org/apache/juneau/rest/server/console/ConsoleChromeMixin.java b/juneau-rest/juneau-rest-server-console-ui/src/main/java/org/apache/juneau/rest/server/console/ConsoleChromeMixin.java
index e378989ba8..5acd178b21 100644
--- a/juneau-rest/juneau-rest-server-console-ui/src/main/java/org/apache/juneau/rest/server/console/ConsoleChromeMixin.java
+++ b/juneau-rest/juneau-rest-server-console-ui/src/main/java/org/apache/juneau/rest/server/console/ConsoleChromeMixin.java
@@ -39,8 +39,8 @@ import org.apache.juneau.rest.server.util.*;
* {@code DataTablesMixin} in the {@code juneau-rest-server-datatables} module for the identical asset-serving
* pattern this mirrors — not linked here since that module is not a dependency of this one). The served
* response is the static
- * structural {@code chrome.css} (shipped in this module's classpath) with the active theme's tokens appended as a
- * {@code :root{}} block.
+ * structural {@code chrome.css} (shipped in this module's classpath) with the active theme's tokens appended as an
+ * {@code html:root{}} block.
*
* <h5 class='section'>Mount styles:</h5>
* <p>
@@ -355,10 +355,21 @@ public class ConsoleChromeMixin {
return req.getContext().getBeanStore().getBean(ThemeSettings.class).orElse(ThemeSettings.DEFAULT).getTheme();
}
- /** Renders one theme's tokens as an appended {@code :root{ ... }} block, escaping every value at the declaration boundary. */
+ /**
+ * Renders one theme's tokens as an appended {@code html:root{ ... }} block, escaping every value at the
+ * declaration boundary.
+ *
+ * <p>
+ * The selector is {@code html:root} rather than a bare {@code :root} so the block scores {@code (0,0,1,1)}
+ * instead of {@code (0,0,1,0)}. A separately-linked stylesheet that declares the same token names in its own
+ * {@code :root} would tie a bare {@code :root} on specificity, and the cascade would then fall through to
+ * source order — which across two stylesheets is the order the consumer's {@code <link>} elements
+ * happen to appear in, something this framework neither sets nor can observe. The extra type selector makes
+ * the theme's tokens out-rank such a declaration in either link order.
+ */
private static String rootBlock(Theme theme) {
var sb = new StringBuilder();
- sb.append(":root{");
+ sb.append("html:root{");
for (var e : theme.getTokens().entrySet())
sb.append(e.getKey()).append(':').append(CssValueEscaper.escape(e.getValue())).append(';');
sb.append('}');
@@ -366,16 +377,17 @@ public class ConsoleChromeMixin {
}
/**
- * Renders {@link Theme#OPEN}'s {@code :root{}} block with the framework-authored role-token alias derivations
- * ({@link #OPEN_ROLE_ALIASES}) appended inside the same block, immediately after the leaf tokens. The aliases
- * are appended as trusted framework literal text (not routed through {@code CssValueEscaper}, which is for
- * consumer-supplied values); folding them into {@code Theme.OPEN}'s block keeps the served response at exactly
- * one {@code :root{}} block for the default theme while still placing every derived default before any
- * active-theme override block.
+ * Renders {@link Theme#OPEN}'s {@code html:root{}} block with the framework-authored role-token alias
+ * derivations ({@link #OPEN_ROLE_ALIASES}) appended inside the same block, immediately after the leaf tokens.
+ * The aliases are appended as trusted framework literal text (not routed through {@code CssValueEscaper},
+ * which is for consumer-supplied values); folding them into {@code Theme.OPEN}'s block keeps the served
+ * response at exactly one {@code html:root{}} block for the default theme while still placing every derived
+ * default before any active-theme override block. See {@link #rootBlock(Theme)} for why the selector carries
+ * the {@code html} type prefix.
*/
private static String openRootBlock() {
var sb = new StringBuilder();
- sb.append(":root{");
+ sb.append("html:root{");
for (var e : Theme.OPEN.getTokens().entrySet())
sb.append(e.getKey()).append(':').append(CssValueEscaper.escape(e.getValue())).append(';');
sb.append(OPEN_ROLE_ALIASES);
diff --git a/juneau-rest/juneau-rest-server-console-ui/src/main/java/org/apache/juneau/rest/server/console/Theme.java b/juneau-rest/juneau-rest-server-console-ui/src/main/java/org/apache/juneau/rest/server/console/Theme.java
index 04812b5af8..ce7212d783 100644
--- a/juneau-rest/juneau-rest-server-console-ui/src/main/java/org/apache/juneau/rest/server/console/Theme.java
+++ b/juneau-rest/juneau-rest-server-console-ui/src/main/java/org/apache/juneau/rest/server/console/Theme.java
@@ -27,8 +27,8 @@ import java.util.regex.*;
* <p>
* A {@link Theme} is pure data — it carries no classpath assets (fonts/logos/background images; that is a
* fast-follow, see the design's P3) — just a name and a map of {@code --jc-*} token names to CSS values.
- * {@code ConsoleChromeMixin} appends the active theme's tokens to the served {@code chrome.css} response as a
- * {@code :root{}} block, on top of {@link #OPEN}'s own block.
+ * {@code ConsoleChromeMixin} appends the active theme's tokens to the served {@code chrome.css} response as an
+ * {@code html:root{}} block, on top of {@link #OPEN}'s own block.
*
* <h5 class='section'>Security:</h5>
* <p>
diff --git a/juneau-rest/juneau-rest-server-console-ui/src/main/resources/org/apache/juneau/console/chrome.css b/juneau-rest/juneau-rest-server-console-ui/src/main/resources/org/apache/juneau/console/chrome.css
index 4dc5f5c9a7..fac062af5d 100644
--- a/juneau-rest/juneau-rest-server-console-ui/src/main/resources/org/apache/juneau/console/chrome.css
+++ b/juneau-rest/juneau-rest-server-console-ui/src/main/resources/org/apache/juneau/console/chrome.css
@@ -22,8 +22,14 @@
its own. Every --jc-* token is defined by the DYNAMIC part of the served
response: ConsoleChromeMixin always appends Theme.OPEN's token block, then
(if a non-default theme is active) a second block of that theme's
- overrides. Appended blocks win by CSS cascade order, so a consumer never
- needs to out-rank a token defined in this static file.
+ overrides. Those blocks are emitted at html:root, specificity (0,0,1,1), so
+ they out-rank a same-named token declared at :root (0,0,1,0) by a
+ separately linked stylesheet — juneau-views.css, which declares its own
+ token set, included — whichever order the consumer links the two in. Do
+ not read this as "later text always wins": two :root blocks in separately
+ linked files tie on specificity and are resolved by <link> order, which
+ this framework neither sets nor can observe. The type prefix is what makes
+ the theme's value win rather than the append position.
SECURITY - SINK-PROPERTY DISCIPLINE (do not casually add a new var(--jc-*)
reference without re-reading this):
diff --git a/juneau-rest/juneau-rest-server-console-ui/src/test/java/org/apache/juneau/rest/server/console/ConsoleChromeMixin_Test.java b/juneau-rest/juneau-rest-server-console-ui/src/test/java/org/apache/juneau/rest/server/console/ConsoleChromeMixin_Test.java
index 19373fb185..3526a8ab15 100644
--- a/juneau-rest/juneau-rest-server-console-ui/src/test/java/org/apache/juneau/rest/server/console/ConsoleChromeMixin_Test.java
+++ b/juneau-rest/juneau-rest-server-console-ui/src/test/java/org/apache/juneau/rest/server/console/ConsoleChromeMixin_Test.java
@@ -881,6 +881,49 @@ class ConsoleChromeMixin_Test extends TestBase {
assertFalse(body.contains("--jc-tag-red-text:var("), () -> "unresolved var() reference leaked into the served declaration:\n" + body);
}
+ //-----------------------------------------------------------------------------------------------------------------
+ // q) Emitted token blocks carry the html:root type prefix, so a theme token out-ranks a same-named token
+ // declared at :root by a separately linked stylesheet regardless of <link> order
+ //-----------------------------------------------------------------------------------------------------------------
+
+ /**
+ * Both emission sites must carry the {@code html} type prefix, not just one.
+ *
+ * <p>
+ * Two blocks at plain {@code :root} in separately linked stylesheets tie at specificity {@code (0,0,1,0)} and
+ * are resolved by the order the consumer's {@code <link>} elements appear in — which this framework
+ * neither sets nor can observe, so a theme override is silently defeated whenever a consumer links the other
+ * way round. {@code html:root} scores {@code (0,0,1,1)} and wins in either order.
+ *
+ * <p>
+ * Deliberately asserted as an <i>anchored</i> prefix rather than a {@code contains("html:root{")}: the
+ * pre-existing helpers in this class match {@code :root\{} as a substring, and {@code html:root{} contains
+ * that, so every one of them stays green whether or not the prefix is emitted. A substring assertion here
+ * would inherit exactly that blind spot and pass against the unfixed emitter.
+ */
+ @Test void q01_bothEmittedTokenBlocks_carryTheHtmlTypePrefix() throws Exception {
+ var body = bodyOf(MockRestClient.buildLax(ThemeSettingsHost.class));
+ assertEquals(2, countRootBlocks(body), () -> "expected Theme.OPEN block + THEME_A's override block, body:\n" + body);
+ var m = Pattern.compile("(.{0,5}):root\\{").matcher(body);
+ var n = 0;
+ while (m.find()) {
+ n++;
+ assertEquals("html", m.group(1), () -> "token block emitted without the html type prefix, body:\n" + body);
+ }
+ assertEquals(2, n, () -> "expected both emission sites to be checked, body:\n" + body);
+ }
+
+ /**
+ * The static {@code chrome.css} must keep shipping no token block of its own, which is what makes appending
+ * one work at all. Guards the other half of (q01): a {@code :root} appearing in the static file would be
+ * counted by (q01)'s matcher and would not carry the prefix.
+ */
+ @Test void q02_staticChromeCss_shipsNoTokenBlockOfItsOwn() throws IOException {
+ var css = readChromeCss();
+ var m = Pattern.compile("^\\s*+(html)?+:root\\s*+\\{", Pattern.MULTILINE).matcher(css);
+ assertFalse(m.find(), () -> "static chrome.css must ship no :root block of its own");
+ }
+
//-----------------------------------------------------------------------------------------------------------------
// Test helpers
//-----------------------------------------------------------------------------------------------------------------
diff --git a/juneau-rest/juneau-rest-server-views/src/main/java/org/apache/juneau/rest/server/views/CardGridTable.java b/juneau-rest/juneau-rest-server-views/src/main/java/org/apache/juneau/rest/server/views/CardGridTable.java
index 2cad1a8955..3204a532d4 100644
--- a/juneau-rest/juneau-rest-server-views/src/main/java/org/apache/juneau/rest/server/views/CardGridTable.java
+++ b/juneau-rest/juneau-rest-server-views/src/main/java/org/apache/juneau/rest/server/views/CardGridTable.java
@@ -49,12 +49,15 @@ import org.apache.juneau.rest.server.widgets.*;
*
* <h5 class='section'>Closed body dispatch (fail-closed):</h5>
* <p>
- * The body dispatch is a <b>closed</b>, enumerated set: {@link CardFieldList} and {@link ViewCardBody}. Any other
- * {@link CardBody} implementation throws at emit rather than being silently dropped, so a body type nobody taught
- * this emitter about can never reach the page. In particular there is no raw-markup body: the toolkit has no
- * markup sanitizer, so a body that would pour author markup into a card is refused here rather than emitted
- * un-neutralized. Each known body brings its <b>own</b> data path — {@link ViewCardBody} inherits the hosted
- * table's ajax/refresh and does not reuse the {@code CardFieldList} refresh envelope.
+ * The body dispatch is a <b>closed</b>, enumerated set: {@link CardFieldList}, {@link ViewCardBody}, and
+ * {@link CardContent}. Any other {@link CardBody} implementation throws at emit rather than being silently
+ * dropped, so a body type nobody taught this emitter about can never reach the page. {@link CardContent} is the
+ * one raw-markup body: it carries the "template engine, trusted / first-party content only" ownership contract
+ * documented on its own javadoc — the caller pre-sanitizes, this emitter writes {@link CardContent#content}
+ * verbatim via {@code rawText(...)}, and a build-gating scanner in this module's test tree checks that only
+ * compile-time literals reach its setter. Each known body brings its <b>own</b> data path — {@link
+ * ViewCardBody} inherits the hosted table's ajax/refresh and does not reuse the {@code CardFieldList} refresh
+ * envelope; {@link CardContent} carries no data path at all.
*
* <h5 class='section'>Request-aware emit:</h5>
* <p>
@@ -316,13 +319,15 @@ public class CardGridTable {
}
/**
- * Closed body dispatch: {@link CardFieldList} and {@link ViewCardBody}; any other {@link CardBody} fails closed
- * at emit. A {@link ViewCardBody} on the request-free path also fails closed rather than emitting a hosted
- * table stripped of the token and server values it was declared with.
+ * Closed body dispatch: {@link CardFieldList}, {@link ViewCardBody}, and {@link CardContent}; any other
+ * {@link CardBody} fails closed at emit. A {@link ViewCardBody} on the request-free path also fails closed
+ * rather than emitting a hosted table stripped of the token and server values it was declared with.
*/
private static HtmlElement<?> emitBody(CardBody body, HttpServletRequest req, String idScope) {
if (body instanceof CardFieldList fl)
return emitFieldList(fl);
+ if (body instanceof CardContent cc)
+ return emitContent(cc);
if (body instanceof ViewCardBody vcb) {
if (req == null)
throw iaex("CardGridTable cannot emit a ViewCardBody without a request: the hosted table needs one "
@@ -331,7 +336,7 @@ public class CardGridTable {
return ViewTable.of(req, vcb.view, idScope);
}
throw iaex("CardGridTable does not know how to emit CardBody type '%s'; the known card bodies are "
- + "CardFieldList and ViewCardBody.", body == null ? "null" : body.getClass().getName());
+ + "CardFieldList, ViewCardBody, and CardContent.", body == null ? "null" : body.getClass().getName());
}
/**
@@ -351,6 +356,17 @@ public class CardGridTable {
.attr("style", "grid-template-columns:repeat(" + fl.columns + ",minmax(0,1fr))");
}
+ /**
+ * Emits a {@link CardContent} as a single {@code <div class="card-content">} whose child is the body's
+ * {@link CardContent#content} written <b>verbatim</b>, via {@code rawText(...)} — the raw-markup
+ * ownership contract documented on {@link CardContent}. Unlike every other human string this emitter paints
+ * (title, field label, field value), this one is never entity-escaped; the caller is responsible for having
+ * pre-sanitized it.
+ */
+ private static Div emitContent(CardContent cc) {
+ return div(rawText(cc.content)).class_("card-content");
+ }
+
/**
* Emits one {@link Card#actions} entry, in the same DOM vocabulary an {@link AppHeaderTable} action uses: the
* marker + behavior attributes the client enhancement selects on, the tooltip as both {@code aria-label} and
diff --git a/juneau-rest/juneau-rest-server-views/src/main/resources/org/apache/juneau/views/juneau-ribbon.js b/juneau-rest/juneau-rest-server-views/src/main/resources/org/apache/juneau/views/juneau-ribbon.js
index 174fb4008d..307e1d163c 100644
--- a/juneau-rest/juneau-rest-server-views/src/main/resources/org/apache/juneau/views/juneau-ribbon.js
+++ b/juneau-rest/juneau-rest-server-views/src/main/resources/org/apache/juneau/views/juneau-ribbon.js
@@ -169,6 +169,37 @@
return "tune";
}
+ /**
+ * Moves every ungrouped {@code refresh} action to the end of the list, in one trailing cluster keyed by the
+ * reserved synthetic group {@code __refresh} (mirroring this file's {@code __ungrouped} convention), so a
+ * refresh control reads as a self-contained control at the far right of the toolbar regardless of where a
+ * view declared it. Pure and DOM-free; {@link #buildRibbon} is the only caller.
+ *
+ * <ul>
+ * <li>No {@code refresh} action - returns {@code actions} unchanged (identity no-op).
+ * <li>One or more ungrouped {@code refresh} actions - all of them are removed from their declared position(s)
+ * and re-appended at the end, in their original relative order, sharing the {@code __refresh} group id
+ * (so {@link #buildRibbon}'s adjacent-group clustering renders them as ONE cluster, not several).
+ * <li>A {@code refresh} action that already carries an explicit {@code group} opts OUT completely - it is
+ * left exactly where its neighbours put it, ungrouped by this function. This is a consumer's escape
+ * hatch: a deliberate {@code .group(...)} on refresh means "I clustered this on purpose".
+ * <li>A {@code divider} left dangling in trailing position by the move (nothing left to divide once refresh
+ * is gone) is dropped rather than rendered as an empty seam.
+ * </ul>
+ *
+ * <p>As with {@code __ungrouped}, a consumer literally naming a group {@code "__refresh"} collides with this
+ * reserved key; that risk is tolerated here for the same reason it already is for {@code __ungrouped}.
+ */
+ function normalizeRibbon(actions) {
+ actions = actions || [];
+ const moving = actions.filter(function (a) { return a.type === "refresh" && a.group == null; });
+ if (!moving.length) return actions;
+ const kept = actions.filter(function (a) { return !(a.type === "refresh" && a.group == null); });
+ while (kept.length && kept[kept.length - 1].type === "divider") kept.pop();
+ const moved = moving.map(function (a) { return Object.assign({}, a, { group: "__refresh" }); });
+ return kept.concat(moved);
+ }
+
// ==================================================================================================================
// DOM / JQUERY BINDING LAYER (thin shim; not exercised by the pure unit tests)
// ==================================================================================================================
@@ -226,17 +257,22 @@
* <p>Adjacent actions sharing a non-null {@code group} id (visual-parity design doc §4.A, item 2/5) are
* clustered into ONE segmented {@code .juneau-view-ribbon-group} wrapper (shared borders, rounded only on the
* outer ends - see juneau-views.css) via the local {@code place(el, groupId)} helper below. Actions with no
- * explicit {@code group} (including an {@code export} action's resolved buttons) share the synthetic
- * {@code __ungrouped} id so consecutive icon buttons — refresh + copy/csv/excel/pdf — render as one connected
+ * explicit {@code group} (excluding {@code refresh}, see below) share the synthetic {@code __ungrouped} id so
+ * consecutive icon buttons — e.g. {@code columnSearchToggle} + copy/csv/excel/pdf — render as one connected
* ribbon rather than orphan glyphs. A {@code divider} always closes any open cluster; an explicit
* {@code group} id still splits clusters the way the caller declared.
+ *
+ * <p>Before any of that, {@link #normalizeRibbon} moves every ungrouped {@code refresh} action into its own
+ * trailing {@code __refresh} cluster at the far right, regardless of where the view declared it - a refresh
+ * control reads as self-contained rather than welded to whatever ungrouped buttons happen to sit beside it.
+ * A {@code refresh} with an explicit {@code group} opts out of that move entirely.
*/
// NOSONAR javascript:S3776 -- one dispatch branch per RibbonAction.type (design doc §4.A); each branch is a
// few lines and several are pinned verbatim by the wiring canary tests below `functionBody(body, "function
// buildRibbon(")`, so splitting them into further helpers would reduce test/code locality without reducing
// real complexity.
function buildRibbon(viewDef, ctx) {
- const actions = viewDef.ribbon || [];
+ const actions = normalizeRibbon(viewDef.ribbon || []);
if (!actions.length) return null;
const $ = window.jQuery;
@@ -390,6 +426,7 @@
resolveExportButtons: resolveExportButtons,
ribbonStorageKey: ribbonStorageKey,
resolveButtonIcon: resolveButtonIcon,
+ normalizeRibbon: normalizeRibbon,
// binding
loadPersistedState: loadPersistedState,
build: buildRibbon
diff --git a/juneau-rest/juneau-rest-server-views/src/main/resources/org/apache/juneau/views/juneau-views.css b/juneau-rest/juneau-rest-server-views/src/main/resources/org/apache/juneau/views/juneau-views.css
index b0c14ece09..ac0f23c06d 100644
--- a/juneau-rest/juneau-rest-server-views/src/main/resources/org/apache/juneau/views/juneau-views.css
+++ b/juneau-rest/juneau-rest-server-views/src/main/resources/org/apache/juneau/views/juneau-views.css
@@ -86,6 +86,70 @@
--jc-card-gap: 1rem;
--jc-card-min: 280px;
--jc-card-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
+ /*
+ * Shared chrome scale (merged here for the same reason the card tokens are - one :root selector). This is
+ * the single set of named steps every chrome surface spends, so a toolbar, a detail panel and a dialog
+ * cannot each derive their own. Coverage is DIMENSIONAL AND TYPE STEPS ONLY: control heights, control
+ * horizontal padding, spacing, type sizes, line-height and glyph sizes. The currentColor / no-palette rule
+ * this file's header states is a SEPARATE contract and is deliberately not a member - it has no step
+ * structure, so it could not be extended the way a step can. The 1px border weight and the 0.25em corner
+ * radius are likewise out: a shape value is not a density value.
+ *
+ * A later surface MAY add a step. Declare it in this group, name it <family>-<role> (spelled out, never
+ * abbreviated), and give it a one-line comment naming the surface that needed it. What a surface may
+ * never do:
+ * 1. Write a literal inline that duplicates an existing step. If a value equals a step, spend the step.
+ * 2. Re-value or rename an existing step to suit itself. A surface needing a different number adds a
+ * NEW step; it does not move one out from under the other surfaces.
+ * 3. Introduce a surface-prefixed name for a chrome-wide value that another surface could legitimately
+ * spend.
+ * 4. Declare a step anywhere but here. A step declared only in a consumer's stylesheet is invisible to
+ * the themeless render this file's header exists to guarantee.
+ *
+ * Spacing ladder - the same six names and the same values as the console chrome's own spacing seam,
+ * re-declared here rather than referenced so this file stays dependency-free and all three layers share one
+ * spacing vocabulary instead of forking a second ladder. -5 and -6 have no consumer in this file yet and
+ * are declared anyway: the ladder is declared whole, as its upstream counterpart is.
+ */
+ --jc-space-1: 4px;
+ --jc-space-2: 8px;
+ --jc-space-3: 12px;
+ --jc-space-4: 16px;
+ --jc-space-5: 24px;
+ --jc-space-6: 32px;
+ /*
+ * Control heights. BOTH are first-class steps, not a default plus a deviation - a surface spending the
+ * compact step is not deviating from the full-height one. Neither name mentions a surface: `compact` is a
+ * density word, so a compact toolbar control and a full-height detail control are each expressible without
+ * a new token.
+ */
+ --jc-chrome-control-height: 32px;
+ --jc-chrome-control-height-compact: 28px;
+ /*
+ * Control horizontal padding. Deliberately OFF the 4px ladder: rounding 10px to 8px or 12px would be a
+ * visual change no surface asked for. Vertical padding is deliberately NOT a step - both control heights
+ * are stated directly and `box-sizing: border-box` is already in force, so padding-y is a derived value
+ * rather than an independent one.
+ */
+ --jc-chrome-control-padding-x: 10px;
+ --jc-chrome-control-padding-x-wide: 14px; /* PROVISIONAL - fixed when the detail action button first renders. */
+ /*
+ * Type steps. A label-smaller-than-value pairing is expressed as the STEP PAIR (-font-size-1 for the
+ * label, -font-size-3 for the value, 0.857x) rather than as a ratio token: no CSS property could consume a
+ * ratio, and nothing would stop a surface setting two sizes that ignore it, whereas two named steps are the
+ * only two values on offer. The ratio is therefore provisional for as long as -font-size-3 is.
+ */
+ --jc-chrome-font-size-1: 0.75rem;
+ --jc-chrome-font-size-2: 0.8125rem; /* PROVISIONAL - fixed when the detail action button first renders. */
+ --jc-chrome-font-size-3: 0.875rem; /* PROVISIONAL - fixed when the detail field value first renders. */
+ --jc-chrome-line-height: 1.2; /* PROVISIONAL - fixed with --jc-chrome-font-size-2. */
+ /*
+ * Glyph sizes, one per role, stated once rather than repeated per selector. These are chrome-wide glyph
+ * ROLES; a widget's own internal proportions (a pill dot, a toggle knob) are sized to their own text and
+ * are deliberately not enrolled here.
+ */
+ --jc-chrome-glyph-size: 16px;
+ --jc-chrome-glyph-size-small: 12px;
}
.jc-progress {
@@ -167,7 +231,7 @@
flex-wrap: wrap;
align-items: center;
gap: 1.25em;
- margin: 0 0 0.5em;
+ margin: 0 0 var(--jc-space-2);
}
.jc-stat {
@@ -275,10 +339,19 @@ table.dataTable {
border-top-width: 2px; /* accented top rule */
}
+/*
+ * The cell font-size is PINNED here, not merely inherited from the table rule above, because everything the
+ * DataTables child row renders (the whole detail-panel family) sizes its `em` spacing against it. Left to
+ * inheritance, a host theme that set a cell font-size on a views table would silently re-resolve every one of
+ * those declarations. `rem`, never `em`: at cell level an `em` would COMPOUND, so a nested views table would
+ * render its cells at 9px and its own nested cells at 6.75px. A theme that legitimately should win can still
+ * win by matching this selector's specificity and coming later.
+ */
table[data-juneau-view] > thead > tr > th,
table[data-juneau-view] > thead > tr > td,
table.dataTable > thead > tr > th,
table.dataTable > thead > tr > td {
+ font-size: 0.75rem;
padding: 4px 5px;
font-weight: normal;
text-align: left;
@@ -291,6 +364,7 @@ table[data-juneau-view] > tbody > tr > th,
table[data-juneau-view] > tbody > tr > td,
table.dataTable > tbody > tr > th,
table.dataTable > tbody > tr > td {
+ font-size: 0.75rem;
padding: 4px 5px;
vertical-align: middle;
border: 1px solid;
@@ -342,8 +416,8 @@ table.dataTable thead .sorting_desc_disabled:after {
justify-content: center;
box-sizing: border-box;
min-width: 32px;
- height: 32px;
- padding: 0 10px; /* ribbon-button horizontal padding between glyphs */
+ height: var(--jc-chrome-control-height);
+ padding: 0 var(--jc-chrome-control-padding-x); /* ribbon-button horizontal padding between glyphs */
border: 1px solid; /* currentColor - no palette color set here */
border-radius: 0.25em;
background: transparent;
@@ -351,7 +425,7 @@ table.dataTable thead .sorting_desc_disabled:after {
cursor: pointer;
}
-.juneau-view-ribbon-btn svg { width: 16px; height: 16px; fill: currentColor; }
+.juneau-view-ribbon-btn svg { width: var(--jc-chrome-glyph-size); height: var(--jc-chrome-glyph-size); fill: currentColor; }
.juneau-view-ribbon-btn:disabled { opacity: 0.4; cursor: not-allowed; }
@@ -478,7 +552,7 @@ table.dataTable thead .sorting_desc_disabled:after {
* NEUTRAL - shape only; chrome.css themes the track wash and selected accent pill.
*/
.juneau-view-ribbon-group.juneau-view-detail-tabs[data-juneau-strip-mode="tab"] {
- gap: 0.25em;
+ gap: var(--jc-space-1);
width: 100%;
margin: 0 0 0.75em;
padding: 0.25em;
@@ -582,7 +656,7 @@ table.dataTable thead .sorting_desc_disabled:after {
display: inline-flex;
align-items: stretch;
box-sizing: border-box;
- height: 32px;
+ height: var(--jc-chrome-control-height);
border: 1px solid; /* currentColor - no palette color set here */
border-radius: 0.25em;
font-family: inherit; /* <button> UA font otherwise; apps theme via body font */
@@ -608,7 +682,7 @@ table.dataTable thead .sorting_desc_disabled:after {
}
.juneau-view-pagingpill-btn:last-child { border-right: none; }
.juneau-view-pagingpill-btn:disabled { opacity: 0.4; cursor: not-allowed; }
-.juneau-view-pagingpill-btn svg { width: 12px; height: 12px; fill: currentColor; }
+.juneau-view-pagingpill-btn svg { width: var(--jc-chrome-glyph-size-small); height: var(--jc-chrome-glyph-size-small); fill: currentColor; }
/*
* The pill's central segment (visual-parity follow-up): BOTH the compact "n-n of n" range summary AND the
@@ -637,7 +711,7 @@ table.dataTable thead .sorting_desc_disabled:after {
.juneau-view-pagingpill-info { white-space: nowrap; font-family: inherit; }
-.juneau-view-pagingpill-caret svg { width: 12px; height: 12px; fill: currentColor; }
+.juneau-view-pagingpill-caret svg { width: var(--jc-chrome-glyph-size-small); height: var(--jc-chrome-glyph-size-small); fill: currentColor; }
/* The popup itself - absolutely positioned below the menu button; `[hidden]` (set/cleared by juneau-views.js)
is enough to show/hide it, so no explicit `display` toggle rule is needed here. */
@@ -688,9 +762,9 @@ table.dataTable thead .sorting_desc_disabled:after {
flex-wrap: nowrap;
justify-content: space-between;
align-items: center;
- gap: 0.5em;
- margin: 0 0 0.5em 0;
- font-size: 0.75rem; /* same type size as the table / paging+search */
+ gap: var(--jc-space-2);
+ margin: 0 0 var(--jc-space-2) 0;
+ font-size: var(--jc-chrome-font-size-1); /* same type size as the table / paging+search */
}
.juneau-view-toolbar-left,
@@ -698,7 +772,7 @@ table.dataTable thead .sorting_desc_disabled:after {
display: flex;
flex-wrap: nowrap;
align-items: center;
- gap: 0.5em;
+ gap: var(--jc-space-2);
}
/* Native DT search box, once relocated into the right cluster: inline with the icon ribbon, not a
@@ -715,7 +789,7 @@ table.dataTable thead .sorting_desc_disabled:after {
.juneau-view-toolbar-right .dataTables_filter input,
.juneau-view-toolbar-right .dt-search input {
box-sizing: border-box;
- height: 32px;
+ height: var(--jc-chrome-control-height);
margin: 0;
padding: 0 0.5em;
border: 1px solid; /* currentColor - no palette color set here */
@@ -785,14 +859,14 @@ table.dataTable thead .sorting_desc_disabled:after {
overflow-x: auto;
white-space: nowrap;
gap: 0.5em;
- margin: 0 0 0.5em 0;
+ margin: 0 0 var(--jc-space-2) 0;
}
.jc-tab,
.jc-subtab {
flex: 0 0 auto;
display: inline-block;
- padding: 0.35em 0.75em;
+ padding: 0.35em var(--jc-space-3);
text-decoration: none;
border: 1px solid; /* currentColor - no palette color set here */
border-radius: 0.25em;
@@ -819,8 +893,8 @@ table.dataTable thead .sorting_desc_disabled:after {
/* Fail-loud PAGE_META contract-version-mismatch banner - neutral, no palette color (mirrors .juneau-view-error). */
.jc-page-error {
display: block;
- padding: 0.5em 0.75em;
- margin: 0.25em 0;
+ padding: var(--jc-space-2) var(--jc-space-3);
+ margin: var(--jc-space-1) 0;
border: 1px solid; /* currentColor - no palette color set here */
border-radius: 0.25em;
font-weight: bold;
@@ -867,8 +941,8 @@ table.dataTable thead .sorting_desc_disabled:after {
display: flex;
align-items: center;
flex-wrap: wrap;
- gap: 0.5em;
- margin: 0 0 0.5em 0;
+ gap: var(--jc-space-2);
+ margin: 0 0 var(--jc-space-2) 0;
}
.jc-bar-text,
@@ -937,11 +1011,11 @@ table.dataTable thead .sorting_desc_disabled:after {
/* The expanded detail body itself - DataTables' native child row (juneau-views.js `row.child(...).show()`). */
.juneau-view-detail-panel {
margin: 0;
- padding: 0.5em 1em;
+ padding: var(--jc-space-2) var(--jc-space-3);
}
.juneau-view-detail-section {
- margin: 0 0 1em;
+ margin: 0 0 var(--jc-space-3);
}
.juneau-view-detail-section-title {
@@ -958,7 +1032,7 @@ table.dataTable thead .sorting_desc_disabled:after {
.juneau-view-detail-fields {
display: grid;
- gap: 0.5em 1em;
+ gap: var(--jc-space-2) var(--jc-space-3);
}
.juneau-view-detail-field-title {
@@ -1016,7 +1090,7 @@ table.dataTable thead .sorting_desc_disabled:after {
max-width: 90vw;
max-height: 90vh;
overflow: auto;
- padding: 1em 1.25em;
+ padding: var(--jc-space-4) 1.25em;
border: 1px solid;
border-radius: 6px;
background: #fff;
@@ -1044,7 +1118,7 @@ table.dataTable thead .sorting_desc_disabled:after {
}
.juneau-view-dialog-fields {
- margin: 0 0 1em;
+ margin: 0 0 var(--jc-space-4);
}
.juneau-view-dialog-fields dt {
@@ -1059,10 +1133,10 @@ table.dataTable thead .sorting_desc_disabled:after {
}
.juneau-view-dialog-form {
- margin: 0 0 1em;
+ margin: 0 0 var(--jc-space-4);
display: flex;
flex-direction: column;
- gap: 0.75em;
+ gap: var(--jc-space-3);
}
/*
@@ -1072,10 +1146,10 @@ table.dataTable thead .sorting_desc_disabled:after {
* NEUTRAL - shape only; chrome.css themes the track wash and selected accent pill.
*/
.juneau-view-ribbon-group.juneau-view-dialog-sections[data-juneau-strip-mode="tab"] {
- gap: 0.25em;
+ gap: var(--jc-space-1);
width: 100%;
margin: 0;
- padding: 0.25em;
+ padding: var(--jc-space-1);
border-bottom: none;
}
@@ -1089,7 +1163,7 @@ table.dataTable thead .sorting_desc_disabled:after {
.juneau-view-dialog-form-section {
display: flex;
flex-direction: column;
- gap: 0.75em;
+ gap: var(--jc-space-3);
}
/*
@@ -1103,7 +1177,7 @@ table.dataTable thead .sorting_desc_disabled:after {
.juneau-view-dialog-form-row label {
display: block;
font-weight: 600;
- margin-bottom: 0.25em;
+ margin-bottom: var(--jc-space-1);
}
.juneau-view-dialog-form-row input,
@@ -1178,7 +1252,7 @@ table.dataTable thead .sorting_desc_disabled:after {
.juneau-view-dialog-actions {
display: flex;
- gap: 0.5em;
+ gap: var(--jc-space-2);
justify-content: flex-end;
}
@@ -1190,7 +1264,7 @@ table.dataTable thead .sorting_desc_disabled:after {
.juneau-view-action-menu {
position: fixed;
margin: 0;
- padding: 0.25em 0;
+ padding: var(--jc-space-1) 0;
list-style: none;
min-width: 10em;
border: 1px solid var(--jc-popover-border);
@@ -1417,7 +1491,7 @@ table.dataTable thead .sorting_desc_disabled:after {
.juneau-view-card-header {
display: flex;
align-items: center;
- gap: 0.5em;
+ gap: var(--jc-space-2);
padding: 0.5rem 0.75rem;
border-bottom: 1px solid var(--jc-card-border, #dddddd);
}
@@ -1447,7 +1521,7 @@ table.dataTable thead .sorting_desc_disabled:after {
.juneau-view-card-actions {
margin-left: auto;
display: flex;
- gap: 0.25em;
+ gap: var(--jc-space-1);
}
.juneau-view-card-refresh {
diff --git a/juneau-rest/juneau-rest-server-views/src/test/java/org/apache/juneau/rest/server/views/CardGridTable_Emit_Test.java b/juneau-rest/juneau-rest-server-views/src/test/java/org/apache/juneau/rest/server/views/CardGridTable_Emit_Test.java
index 33a4a745f6..be9f411c03 100644
--- a/juneau-rest/juneau-rest-server-views/src/test/java/org/apache/juneau/rest/server/views/CardGridTable_Emit_Test.java
+++ b/juneau-rest/juneau-rest-server-views/src/test/java/org/apache/juneau/rest/server/views/CardGridTable_Emit_Test.java
@@ -214,11 +214,43 @@ class CardGridTable_Emit_Test extends TestBase {
}
//------------------------------------------------------------------------------------------------------------------
- // No CardContent this child (i2)
+ // CardContent: the raw-markup body, verbatim/unescaped (opposite of every field value)
//------------------------------------------------------------------------------------------------------------------
- @Test void a19_noCardContentEmit() {
- assertFalse(html(grid()).contains("card-content"), "no CardContent markup this child (i2)");
+ @Test void a19_fieldListOnlyGrid_emitsNoCardContentWrapper() {
+ // The card-content wrapper is conditioned on an actual CardContent body being present, not stamped
+ // unconditionally onto every card.
+ assertFalse(html(grid()).contains("card-content"), "no card-content wrapper without a CardContent body");
+ }
+
+ @Test void a20_cardContentBodyEmitsRawMarkupVerbatim() {
+ var g = CardGrid.create("g1").cards(
+ Card.create("c1", "T").body(CardContent.create().content("<p>Raw <b>markup</b>.</p>")));
+ var h = html(g);
+ assertTrue(h.contains("class=\"card-content\""), h);
+ assertTrue(h.contains("<p>Raw <b>markup</b>.</p>"),
+ () -> "raw content must appear byte-for-byte verbatim (no escaping):\n" + h);
+ }
+
+ @Test void a21_cardContentIsNeverHtmlEntityEscaped_unlikeFieldValues() {
+ var g = CardGrid.create("g1").cards(
+ Card.create("c1", "T").body(CardContent.create().content("<script>alert(1)</script>")));
+ var h = html(g);
+ // The card TITLE is escaped (existing contract, a14) ... but CardContent's body is emitted verbatim - this
+ // is the template-engine ownership contract, not a bug.
+ assertTrue(h.contains("<script>alert(1)</script>"),
+ () -> "content must be emitted verbatim per its documented ownership contract:\n" + h);
+ }
+
+ @Test void a22_cardContentBodyCarriesNoRefreshWire() {
+ // CardContent brings no data path of its own (unlike CardFieldList); none of the refresh attributes may
+ // appear on a card whose only body is raw content.
+ var g = CardGrid.create("g1").cards(
+ Card.create("c1", "T").body(CardContent.create().content("<p>x</p>")));
+ var h = html(g);
+ assertFalse(h.contains(CardGridTable.CARD_REFRESH_ATTR), h);
+ assertFalse(h.contains(CardGridTable.CARD_CONTRACT_ATTR), h);
+ assertFalse(h.contains(CardGridTable.CARD_REFRESH_TRIGGER_ATTR), h);
}
private static int countOf(String haystack, String needle) {
diff --git a/juneau-rest/juneau-rest-server-views/src/test/java/org/apache/juneau/rest/server/views/CardGridTable_ViewCardBody_Test.java b/juneau-rest/juneau-rest-server-views/src/test/java/org/apache/juneau/rest/server/views/CardGridTable_ViewCardBody_Test.java
index 5ea2c1a3e1..01479bdc24 100644
--- a/juneau-rest/juneau-rest-server-views/src/test/java/org/apache/juneau/rest/server/views/CardGridTable_ViewCardBody_Test.java
+++ b/juneau-rest/juneau-rest-server-views/src/test/java/org/apache/juneau/rest/server/views/CardGridTable_ViewCardBody_Test.java
@@ -291,13 +291,13 @@ class CardGridTable_ViewCardBody_Test extends TestBase {
}
//------------------------------------------------------------------------------------------------------------------
- // e) Unknown bodies still fail closed (including a raw-content body, which this child does not ship)
+ // e) Unknown bodies still fail closed; a ViewCardBody card does not spuriously emit another body's markers
//------------------------------------------------------------------------------------------------------------------
- /** A raw-markup body shape. There is no sanitizer in the toolkit, so the emitter must refuse it. */
- static class CardContent implements CardBody {
+ /** A {@link CardBody} implementation this emitter has never been taught about; pins the fail-closed default. */
+ static class UnknownCardBody implements CardBody {
@SuppressWarnings({
- "unused" // The field exists to make this stand-in look exactly like the body type it stands in for.
+ "unused" // The field exists to make this stand-in look like a real body type carrying data.
})
String html = "<b>hi</b>";
@@ -305,21 +305,26 @@ class CardGridTable_ViewCardBody_Test extends TestBase {
@Override public void validate() {}
}
- @Test void e01_rawContentBodyFailsClosedOnTheRequestAwarePath() {
- var c = Card.create("c1", "T").body(new CardContent());
+ @Test void e01_unknownCardBodyFailsClosedOnTheRequestAwarePath() {
+ var c = Card.create("c1", "T").body(new UnknownCardBody());
var req = tokenRequest();
var e = assertThrows(IllegalArgumentException.class, () -> CardGridTable.of(req, c));
assertTrue(e.getMessage().contains("CardFieldList"), e::getMessage);
- assertTrue(e.getMessage().contains(CardContent.class.getName()), e::getMessage);
+ assertTrue(e.getMessage().contains(UnknownCardBody.class.getName()), e::getMessage);
}
- @Test void e02_rawContentBodyFailsClosedOnTheGridPathToo() {
- var g = CardGrid.create("g1").cards(Card.create("c1", "T").body(new CardContent()));
+ @Test void e02_unknownCardBodyFailsClosedOnTheGridPathToo() {
+ var g = CardGrid.create("g1").cards(Card.create("c1", "T").body(new UnknownCardBody()));
var e = assertThrows(IllegalArgumentException.class, () -> CardGridTable.of(g));
assertTrue(e.getMessage().contains("CardFieldList"), e::getMessage);
}
- @Test void e03_noRawContentMarkupIsEverEmitted() {
+ /**
+ * Scenario-scoped, not a framework-wide guarantee: {@link CardContent} is a real body type with its own
+ * positive coverage (see {@code CardGridTable_Emit_Test}). This only pins that a card hosting a
+ * {@link ViewCardBody} does not spuriously pick up the {@code card-content} marker that body type owns.
+ */
+ @Test void e03_viewCardBodyDoesNotEmitTheCardContentMarker() {
var h = Html.of(CardGridTable.of(tokenRequest(), viewCard("c1", view())));
assertFalse(h.contains("card-content"), h);
}
diff --git a/juneau-rest/juneau-rest-server-views/src/test/java/org/apache/juneau/rest/server/views/ChromeScaleScanner.java b/juneau-rest/juneau-rest-server-views/src/test/java/org/apache/juneau/rest/server/views/ChromeScaleScanner.java
new file mode 100644
index 0000000000..6881194c71
--- /dev/null
+++ b/juneau-rest/juneau-rest-server-views/src/test/java/org/apache/juneau/rest/server/views/ChromeScaleScanner.java
@@ -0,0 +1,358 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.juneau.rest.server.views;
+
+import java.util.*;
+import java.util.regex.*;
+
+/**
+ * Test-only, <b>private</b> stylesheet scanner enforcing the shared chrome scale contract on
+ * {@code juneau-views.css}: the named dimensional and type steps every chrome surface spends.
+ *
+ * <p>
+ * Not shipped and deliberately not public API, mirroring the discipline of the {@link RawContentSinkScanner}
+ * test-only guard this class is modeled on and sits beside.
+ *
+ * <h5 class='section'>What it enforces</h5>
+ * <ol>
+ * <li><b>Declaration.</b> Every step in {@link #scale()} is declared exactly once in the file. A step declared
+ * twice has two values in flight; a step declared zero times cannot be spent.
+ * <li><b>No literal that duplicates a step.</b> On the properties a chrome surface actually sizes with, a
+ * literal whose value equals a declared step is a violation — if a value equals a step, spend the
+ * step. This is the half that turns the contract's own "never write a literal that duplicates a step" rule
+ * from advice into a build failure.
+ * </ol>
+ *
+ * <h5 class='section'>Why the second half is narrower than it first looks, and deliberately so</h5>
+ * <p>
+ * The prohibition binds <b>computed</b> values, not written ones, and an {@code em} value can only be computed
+ * once you know its declaration's font-size context. That context is <i>not</i> uniform in this file — it
+ * runs from a UA/system control font through 10.2px, 12px, 16px and up — so a checker that assumed one
+ * context would reproduce, in test form, exactly the defect this contract exists to close. Two consequences,
+ * both intentional:
+ * <ul>
+ * <li><b>{@code em} values are never evaluated here.</b> Only absolute {@code px}/{@code rem} literals are
+ * compared. In particular a form control that sets no {@code font-size} of its own resolves its {@code em}
+ * against a UA/system font that varies by browser and platform, so a computation against one engine's
+ * value would report a violation on that engine and pass on every other. This scanner must never do that.
+ * <li><b>{@code rem} is normalised to px at 16px per rem.</b> That is safe in a way {@code em} is not: nothing
+ * in this file, and nothing in the console chrome that themes it, sets a {@code font-size} on
+ * {@code html}/{@code body}, so the root context is the browser default in both a themeless and a themed
+ * render.
+ * </ul>
+ *
+ * <h5 class='section'>Provisional steps are excluded from the second half</h5>
+ * <p>
+ * A step whose value is still provisional has not been rendered on a views surface yet. Binding the file's
+ * existing declarations to it would tie unrelated surfaces to a number the surface that owns it is going to
+ * re-decide — which is the "re-value a step out from under the other surfaces" failure, arrived at from
+ * the other direction. Provisional steps are still checked for {@link #scale() declaration}.
+ *
+ * <h5 class='section'>Why there is a recorded-exception table rather than a clean sheet</h5>
+ * <p>
+ * {@link #recordedLiterals()} lists every literal that stays a literal, each with a reason. It exists so the
+ * check is a <b>ratchet</b>: the recorded set is what the file looks like today, and anything new is a failure.
+ * An entry is not an excuse — a reader can see precisely which declarations have not been routed onto the
+ * ladder and why. The table is asserted to be non-vacuous by the accompanying test: an entry matching nothing is
+ * itself a failure, so the list cannot rot into a silent allow-everything.
+ */
+final class ChromeScaleScanner {
+
+ private ChromeScaleScanner() {}
+
+ /** The family a step belongs to, which decides the properties it can legitimately be spent on. */
+ enum Family { SPACE, CONTROL_HEIGHT, CONTROL_PADDING_X, FONT_SIZE, LINE_HEIGHT, GLYPH }
+
+ /**
+ * One named step.
+ *
+ * @param token The custom-property name.
+ * @param value The declared value, exactly as written in the stylesheet.
+ * @param confirmed Whether the value is settled (as opposed to provisional pending a surface that renders it).
+ * @param family The step's family.
+ */
+ record Step(String token, String value, boolean confirmed, Family family) {}
+
+ /**
+ * One literal that deliberately stays a literal.
+ *
+ * @param selector A substring of the owning rule's selector text.
+ * @param property The property name.
+ * @param value The literal value, exactly as written.
+ * @param reason Why it is not spending a step.
+ */
+ record RecordedLiteral(String selector, String property, String value, String reason) {}
+
+ /** One declaration parsed out of the stylesheet. */
+ record Decl(String selector, String property, String value) {}
+
+ /** The scan outcome. */
+ record Result(List<String> violations, List<Decl> checked, Set<RecordedLiteral> matchedRecords) {}
+
+ private static final List<Step> SCALE = List.of(
+ new Step("--jc-space-1", "4px", true, Family.SPACE),
+ new Step("--jc-space-2", "8px", true, Family.SPACE),
+ new Step("--jc-space-3", "12px", true, Family.SPACE),
+ new Step("--jc-space-4", "16px", true, Family.SPACE),
+ new Step("--jc-space-5", "24px", true, Family.SPACE),
+ new Step("--jc-space-6", "32px", true, Family.SPACE),
+ new Step("--jc-chrome-control-height", "32px", true, Family.CONTROL_HEIGHT),
+ new Step("--jc-chrome-control-height-compact", "28px", true, Family.CONTROL_HEIGHT),
+ new Step("--jc-chrome-control-padding-x", "10px", true, Family.CONTROL_PADDING_X),
+ new Step("--jc-chrome-control-padding-x-wide", "14px", false, Family.CONTROL_PADDING_X),
+ new Step("--jc-chrome-font-size-1", "0.75rem", true, Family.FONT_SIZE),
+ new Step("--jc-chrome-font-size-2", "0.8125rem", false, Family.FONT_SIZE),
+ new Step("--jc-chrome-font-size-3", "0.875rem", false, Family.FONT_SIZE),
+ new Step("--jc-chrome-line-height", "1.2", false, Family.LINE_HEIGHT),
+ new Step("--jc-chrome-glyph-size", "16px", true, Family.GLYPH),
+ new Step("--jc-chrome-glyph-size-small", "12px", true, Family.GLYPH)
+ );
+
+ /**
+ * Every literal that deliberately stays a literal, with the reason it is not spending a step.
+ *
+ * <p>
+ * Grouped by reason rather than by file order, so a reader can see how many distinct reasons there actually
+ * are. Three, at present.
+ */
+ private static final List<RecordedLiteral> RECORDED_LITERALS = List.of(
+ // (1) The table cell type context. This value is what every `em` in the DataTables child row resolves
+ // against, so it is deliberately NOT a token: a theme that overrode the token would silently re-resolve
+ // the whole detail-panel family, which is the exact dependency pinning it was meant to remove.
+ new RecordedLiteral("table[data-juneau-view], table.dataTable", "font-size", "0.75rem",
+ "anchors the table type context; a token here would be overridable and the pin would stop pinning"),
+ new RecordedLiteral("> thead > tr > th", "font-size", "0.75rem",
+ "pins the cell type context; a token here would be overridable and the pin would stop pinning"),
+ new RecordedLiteral("> tbody > tr > th", "font-size", "0.75rem",
+ "pins the cell type context; a token here would be overridable and the pin would stop pinning"),
+
+ // (2) The card grid sizes itself in `rem`. The membership sweep behind the spacing ladder evaluated
+ // `em`-valued declarations only, so these were never assessed against a step and routing them now would
+ // be a card-grid density decision this contract does not own.
+ new RecordedLiteral(".juneau-view-card-status", "font-size", "0.75rem",
+ "card-grid rem sizing, never assessed by the em-valued membership sweep"),
+ new RecordedLiteral(".juneau-view-card-field dt", "font-size", "0.75rem",
+ "card-grid rem sizing, never assessed by the em-valued membership sweep"),
+ new RecordedLiteral(".juneau-view-card-fields", "gap", "0.4rem 0.75rem",
+ "card-grid rem sizing, never assessed by the em-valued membership sweep"),
+
+ // (3) A third glyph site at the small glyph size, in a widget the glyph-role naming enumerated only two
+ // consumers for. Routing it is pixel-neutral but adds a consumer to a named role, which is a decision
+ // for whoever owns the row-detail control rather than one to take in passing.
+ new RecordedLiteral(".juneau-view-detail-control svg", "width", "12px",
+ "a third small-glyph consumer; enrolling it widens a named glyph role and is not this contract's call"),
+ new RecordedLiteral(".juneau-view-detail-control svg", "height", "12px",
+ "a third small-glyph consumer; enrolling it widens a named glyph role and is not this contract's call")
+ );
+
+ /** Properties a chrome surface sizes with, and the step families each may legitimately spend. */
+ private static final Map<String,Set<Family>> CHECKED_PROPERTIES = Map.of(
+ "height", Set.of(Family.CONTROL_HEIGHT, Family.SPACE, Family.GLYPH),
+ "min-height", Set.of(Family.CONTROL_HEIGHT, Family.SPACE),
+ "font-size", Set.of(Family.FONT_SIZE),
+ "gap", Set.of(Family.SPACE),
+ "line-height", Set.of(Family.LINE_HEIGHT),
+ "width", Set.of(Family.GLYPH)
+ );
+
+ /** {@code width} is only a scale property on an SVG glyph; elsewhere it is a content measure. */
+ private static final String SVG_SELECTOR_SUFFIX = "svg";
+
+ /** Matches one {@code selector { ... }} rule block. */
+ private static final Pattern RULE = Pattern.compile("([^{}]+)\\{([^{}]*)\\}");
+
+ /** Matches a {@code var(...)} reference, including any fallback, so a fallback is not read as a bare literal. */
+ private static final Pattern VAR_REF = Pattern.compile("var\\([^()]*(?:\\([^()]*\\)[^()]*)*\\)");
+
+ /** Matches an absolute length/size token. */
+ private static final Pattern ABSOLUTE = Pattern.compile("(?<![\\w.-])(\\d*\\.?\\d+)(px|rem)(?![\\w-])");
+
+ /** The steps this contract declares. */
+ static List<Step> scale() {
+ return SCALE;
+ }
+
+ /** Every literal deliberately left as a literal, with its reason. */
+ static List<RecordedLiteral> recordedLiterals() {
+ return RECORDED_LITERALS;
+ }
+
+ /**
+ * Reports any step not declared exactly once in the stylesheet.
+ *
+ * @param css The stylesheet text.
+ * @return One message per step that is missing or declared more than once; empty when every step is sound.
+ */
+ static List<String> checkDeclaredExactlyOnce(String css) {
+ var code = stripComments(css);
+ var out = new ArrayList<String>();
+ for (var s : SCALE) {
+ var m = Pattern.compile(Pattern.quote(s.token()) + "\\s*:\\s*([^;}]+)").matcher(code);
+ var found = new ArrayList<String>();
+ while (m.find())
+ found.add(m.group(1).trim());
+ if (found.size() != 1) {
+ out.add(s.token() + ": expected exactly one declaration, found " + found.size() + " " + found);
+ } else if (!found.get(0).equals(s.value())) {
+ out.add(s.token() + ": declared as '" + found.get(0) + "', contract says '" + s.value() + "'");
+ }
+ }
+ return out;
+ }
+
+ /**
+ * Scans for literals that duplicate a declared step on a property the scale covers.
+ *
+ * @param css The stylesheet text.
+ * @return The violations, the declarations actually examined, and which recorded exceptions were matched.
+ */
+ static Result scan(String css) {
+ var violations = new ArrayList<String>();
+ var checked = new ArrayList<Decl>();
+ var matched = new LinkedHashSet<RecordedLiteral>();
+ var code = stripComments(css);
+
+ var rules = RULE.matcher(code);
+ while (rules.find()) {
+ var selector = normalise(rules.group(1));
+ if (selector.startsWith("@") || selector.isEmpty())
+ continue;
+ for (var d : declarations(selector, rules.group(2))) {
+ var families = CHECKED_PROPERTIES.get(d.property());
+ if (families == null)
+ continue;
+ if ("width".equals(d.property()) && !isSvgSelector(selector))
+ continue;
+ checked.add(d);
+ var hit = findDuplicatedStep(d, families);
+ if (hit == null)
+ continue;
+ var record = findRecord(d);
+ if (record != null) {
+ matched.add(record);
+ continue;
+ }
+ violations.add(d.selector() + " { " + d.property() + ": " + d.value() + " } duplicates the step "
+ + hit.token() + " (" + hit.value() + "). If a value equals a step, spend the step - or add a "
+ + "recorded exception with the reason it cannot.");
+ }
+ }
+ return new Result(violations, checked, matched);
+ }
+
+ /**
+ * The confirmed step of an eligible family whose value the declaration writes out as a literal.
+ *
+ * <p>
+ * Role-named families are searched before the spacing ladder, so a 32px {@code height} is reported against
+ * {@code --jc-chrome-control-height} rather than against the numerically-identical {@code --jc-space-6}. Both
+ * are violations either way; naming the apter one is what makes the message actionable.
+ */
+ private static Step findDuplicatedStep(Decl d, Set<Family> families) {
+ var literals = absoluteValues(d.value());
+ if (literals.isEmpty())
+ return null;
+ for (var roleNamed : List.of(true, false)) {
+ for (var s : SCALE) {
+ if (!s.confirmed() || !families.contains(s.family()) || (s.family() == Family.SPACE) == roleNamed)
+ continue;
+ var stepPx = toPx(s.value());
+ if (stepPx != null && literals.contains(stepPx))
+ return s;
+ }
+ }
+ return null;
+ }
+
+ private static RecordedLiteral findRecord(Decl d) {
+ for (var r : RECORDED_LITERALS)
+ if (d.selector().contains(r.selector()) && r.property().equals(d.property()) && r.value().equals(d.value()))
+ return r;
+ return null;
+ }
+
+ /** True if any comma-separated selector in the group targets an {@code svg} element. */
+ private static boolean isSvgSelector(String selector) {
+ for (var s : selector.split(","))
+ if (s.trim().endsWith(SVG_SELECTOR_SUFFIX))
+ return true;
+ return false;
+ }
+
+ /**
+ * Every absolute value in a declaration, normalised to px. {@code var(...)} expressions are removed first, so
+ * a token's own fallback (e.g. {@code var(--jc-card-gap, 1rem)}) is not mistaken for a bare literal - the
+ * declaration is already spending a token, which is the thing the rule asks for.
+ */
+ private static Set<Double> absoluteValues(String value) {
+ var out = new LinkedHashSet<Double>();
+ var m = ABSOLUTE.matcher(VAR_REF.matcher(value).replaceAll(" "));
+ while (m.find())
+ out.add(px(Double.parseDouble(m.group(1)), m.group(2)));
+ return out;
+ }
+
+ private static Double toPx(String value) {
+ var m = ABSOLUTE.matcher(value);
+ return m.find() ? px(Double.parseDouble(m.group(1)), m.group(2)) : null;
+ }
+
+ /** Normalises to px. {@code rem} resolves at the browser default because nothing here sets a root font-size. */
+ private static double px(double n, String unit) {
+ return "rem".equals(unit) ? n * 16.0 : n;
+ }
+
+ private static List<Decl> declarations(String selector, String body) {
+ var out = new ArrayList<Decl>();
+ for (var raw : body.split(";")) {
+ var colon = raw.indexOf(':');
+ if (colon < 0)
+ continue;
+ var property = raw.substring(0, colon).trim().toLowerCase(Locale.ROOT);
+ var value = normalise(raw.substring(colon + 1));
+ if (property.isEmpty() || property.startsWith("--") || value.isEmpty())
+ continue;
+ out.add(new Decl(selector, property, value));
+ }
+ return out;
+ }
+
+ private static String normalise(String s) {
+ return s.replaceAll("\\s+", " ").trim();
+ }
+
+ /** Blanks out comment content so a value mentioned in a comment is not read as a declaration. */
+ private static String stripComments(String s) {
+ var out = new StringBuilder(s.length());
+ var i = 0;
+ while (i < s.length()) {
+ if (s.charAt(i) == '/' && i + 1 < s.length() && s.charAt(i + 1) == '*') {
+ i += 2;
+ while (i + 1 < s.length() && !(s.charAt(i) == '*' && s.charAt(i + 1) == '/')) {
+ if (s.charAt(i) == '\n')
+ out.append('\n');
+ i++;
+ }
+ i = Math.min(s.length(), i + 2);
+ continue;
+ }
+ out.append(s.charAt(i));
+ i++;
+ }
+ return out.toString();
+ }
+}
diff --git a/juneau-rest/juneau-rest-server-views/src/test/java/org/apache/juneau/rest/server/views/ChromeScale_ContractScan_Test.java b/juneau-rest/juneau-rest-server-views/src/test/java/org/apache/juneau/rest/server/views/ChromeScale_ContractScan_Test.java
new file mode 100644
index 0000000000..9fe6181832
--- /dev/null
+++ b/juneau-rest/juneau-rest-server-views/src/test/java/org/apache/juneau/rest/server/views/ChromeScale_ContractScan_Test.java
@@ -0,0 +1,144 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.juneau.rest.server.views;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+import java.io.*;
+import java.nio.charset.*;
+
+import org.apache.juneau.*;
+import org.junit.jupiter.api.*;
+
+/**
+ * Guards the shared chrome scale contract on the served {@code juneau-views.css}: the steps are declared once
+ * each, and no surface writes a literal that duplicates one.
+ *
+ * <p>
+ * Driven by {@link ChromeScaleScanner}, which carries the contract's own step table and the reasoning behind
+ * what it does and does not evaluate.
+ */
+class ChromeScale_ContractScan_Test extends TestBase {
+
+ private static String viewsCss() throws IOException {
+ try (var in = ChromeScale_ContractScan_Test.class.getResourceAsStream("/org/apache/juneau/views/juneau-views.css")) {
+ assertNotNull(in, "juneau-views.css not found on the test classpath");
+ return new String(in.readAllBytes(), StandardCharsets.UTF_8);
+ }
+ }
+
+ //-----------------------------------------------------------------------------------------------------------------
+ // a) Every step is declared exactly once, at the value the contract states
+ //-----------------------------------------------------------------------------------------------------------------
+
+ @Test void a01_everyStepIsDeclaredExactlyOnce() throws IOException {
+ var problems = ChromeScaleScanner.checkDeclaredExactlyOnce(viewsCss());
+ assertTrue(problems.isEmpty(), () -> "chrome scale declaration problems:\n " + String.join("\n ", problems));
+ }
+
+ /**
+ * The ladders are declared whole, so a step with no consumer today is still declared. Asserting the count
+ * pins that: a future edit that prunes an "unused" step has to come through this test.
+ */
+ @Test void a02_ladderIsDeclaredWhole_includingStepsWithNoConsumerYet() throws IOException {
+ var css = viewsCss();
+ assertTrue(css.contains("--jc-space-5: 24px;"), "the spacing ladder is declared whole, unused steps included");
+ assertTrue(css.contains("--jc-space-6: 32px;"), "the spacing ladder is declared whole, unused steps included");
+ assertEquals(16, ChromeScaleScanner.scale().size());
+ }
+
+ //-----------------------------------------------------------------------------------------------------------------
+ // b) No literal duplicates a declared step
+ //-----------------------------------------------------------------------------------------------------------------
+
+ @Test void b01_noLiteralDuplicatesADeclaredStep() throws IOException {
+ var r = ChromeScaleScanner.scan(viewsCss());
+ assertTrue(r.violations().isEmpty(), () -> "literals duplicating a declared step:\n "
+ + String.join("\n ", r.violations()));
+ }
+
+ /**
+ * A scanner that silently stops matching reads as a passing test, which is worse than no scanner. The scan
+ * must actually reach a meaningful number of declarations on the properties the scale covers.
+ */
+ @Test void b02_scanIsNotVacuous() throws IOException {
+ var r = ChromeScaleScanner.scan(viewsCss());
+ assertTrue(r.checked().size() > 20, () -> "scan examined only " + r.checked().size()
+ + " declarations - it has probably stopped matching rather than found a clean file");
+ }
+
+ /**
+ * The recorded-exception table is a ratchet, not an allowlist that may rot: an entry matching nothing means
+ * the declaration it excused has moved or been fixed, and the entry must go rather than sit there quietly
+ * widening what the scan will tolerate.
+ */
+ @Test void b03_everyRecordedExceptionStillMatchesSomething() throws IOException {
+ var r = ChromeScaleScanner.scan(viewsCss());
+ var stale = ChromeScaleScanner.recordedLiterals().stream()
+ .filter(x -> !r.matchedRecords().contains(x))
+ .map(x -> x.selector() + " { " + x.property() + ": " + x.value() + " }")
+ .toList();
+ assertTrue(stale.isEmpty(), () -> "recorded exceptions that no longer match any declaration - remove them:\n "
+ + String.join("\n ", stale));
+ }
+
+ /** Every recorded exception states why it is not spending a step; a bare entry is not auditable. */
+ @Test void b04_everyRecordedExceptionCarriesAReason() {
+ ChromeScaleScanner.recordedLiterals()
+ .forEach(x -> assertFalse(x.reason() == null || x.reason().isBlank(),
+ () -> "recorded exception with no reason: " + x.selector() + " { " + x.property() + " }"));
+ }
+
+ /**
+ * Proves the scan can actually fail. Without this, (b01) passing tells you nothing about whether the check
+ * works or merely never fires.
+ */
+ @Test void b05_syntheticDuplicateLiteralIsCaught() {
+ var r = ChromeScaleScanner.scan(".synthetic-surface { height: 32px; }");
+ assertEquals(1, r.violations().size(), () -> "expected the synthetic duplicate to be caught: " + r.violations());
+ assertTrue(r.violations().get(0).contains("--jc-chrome-control-height"), r.violations().get(0));
+ }
+
+ /**
+ * An {@code em} value must never be treated as a step match. Its computed value depends on a font-size
+ * context this file does not have one of, and on form controls that context is a UA/system font that differs
+ * by browser - so an engine-specific computation would fail on one platform and pass on another.
+ */
+ @Test void b06_emValuesAreNeverTreatedAsAStepMatch() {
+ // 0.9em computes to exactly 12px against Chrome's form-control font and to nothing near a step elsewhere.
+ var r = ChromeScaleScanner.scan(".synthetic-toggle::after { width: 0.9em; height: 0.9em; }");
+ assertTrue(r.violations().isEmpty(), () -> "an em value was evaluated as a step match: " + r.violations());
+ }
+
+ /** A provisional step has no rendered consumer yet, so an existing literal must not be bound to its value. */
+ @Test void b07_provisionalStepValuesDoNotTriggerAViolation() {
+ var r = ChromeScaleScanner.scan(".synthetic-label { font-size: 0.8125rem; }");
+ assertTrue(r.violations().isEmpty(), () -> "a provisional step value was enforced: " + r.violations());
+ }
+
+ /** A declaration already spending a token is compliant, fallback and all. */
+ @Test void b08_tokenFallbackIsNotReadAsABareLiteral() {
+ var r = ChromeScaleScanner.scan(".synthetic-grid { gap: var(--jc-card-gap, 1rem); }");
+ assertTrue(r.violations().isEmpty(), () -> "a var() fallback was read as a bare literal: " + r.violations());
+ }
+
+ /** {@code width} is a scale property on an SVG glyph and a content measure everywhere else. */
+ @Test void b09_widthIsOnlyCheckedOnGlyphs() {
+ assertTrue(ChromeScaleScanner.scan(".synthetic-cell { width: 16px; }").violations().isEmpty());
+ assertEquals(1, ChromeScaleScanner.scan(".synthetic-btn svg { width: 16px; }").violations().size());
+ }
+}
diff --git a/juneau-rest/juneau-rest-server-views/src/test/java/org/apache/juneau/rest/server/views/RawContentSinkScanner.java b/juneau-rest/juneau-rest-server-views/src/test/java/org/apache/juneau/rest/server/views/RawContentSinkScanner.java
index e08555b76e..5bcba01157 100644
--- a/juneau-rest/juneau-rest-server-views/src/test/java/org/apache/juneau/rest/server/views/RawContentSinkScanner.java
+++ b/juneau-rest/juneau-rest-server-views/src/test/java/org/apache/juneau/rest/server/views/RawContentSinkScanner.java
@@ -31,7 +31,11 @@ import java.util.regex.*;
* modeled on. It scans this module's own Java sources (both {@code src/main/java} and {@code src/test/java}, since
* unlike the {@code <script>}-JSON sink this is a brand-new, forward-looking guardrail with no pre-existing
* "known-good" callers to anchor a main-source-only scan to — see the accompanying test's anti-vacuous
- * checks) and fails the build if any call to the {@link Tab#content(String)}/{@link Subtab#content(String)}
+ * checks) — <b>and also</b> the sibling widgets module's Java sources, the same way {@link #scanShippedJs}
+ * already follows the card/calendar/chrome JS assets across the module boundary (see {@link #WIDGETS_MODULE_DIR}):
+ * a raw-markup sink is a raw-markup sink regardless of which of the two card-widget modules declares it. It fails
+ * the build if any call to the {@link Tab#content(String)}/{@link Subtab#content(String)}/
+ * {@link org.apache.juneau.rest.server.widgets.CardContent#content(String) CardContent#content(String)}
* fluent-setter passes an argument that is not a compile-time string literal (or a {@code +}-concatenation of
* literals).
*
@@ -51,12 +55,13 @@ import java.util.regex.*;
* <h5 class='section'>What counts as a sink</h5>
* <p>
* A sink is any source-level call whose method name is exactly {@code content} (i.e. {@code .content(...)}) —
- * scoped to this module's own tree, where (verified before this scanner was written) the only such calls are the
- * {@link Tab}/{@link Subtab} fluent setters this item adds; nothing else in this module declares or calls a
+ * scoped to this module's own tree plus the sibling widgets module's tree (see {@link #scanTree}), where (verified
+ * when each of the two callers was added) the only such calls are the {@link Tab}/{@link Subtab} fluent setters and
+ * the widgets module's {@code CardContent} fluent setter; nothing else in either tree declares or calls a
* {@code content(...)} method. This scanner does not attempt receiver-type resolution and does not scan outside
- * this module (other Juneau modules declare unrelated {@code content(...)} methods, e.g.
- * {@code RestRequest.content(Object)}, which are out of scope by construction because they are never on this
- * module's classpath of scanned files).
+ * these two modules (other Juneau modules declare unrelated {@code content(...)} methods, e.g.
+ * {@code RestRequest.content(Object)}, which are out of scope by construction because they are never on the
+ * scanned trees).
*
* <h5 class='section'>Why it must also assert it is not vacuous</h5>
* <p>
@@ -106,6 +111,14 @@ final class RawContentSinkScanner {
private static final String WIDGETS_JS_DIR =
"../juneau-rest-server-widgets/src/main/resources/org/apache/juneau/widgets";
+ /**
+ * The widgets module's root, relative to this module's root — the Java-source counterpart of
+ * {@link #WIDGETS_JS_DIR}. The card body beans (including the raw-markup {@code CardContent}) live there, so
+ * {@link #scanTree} follows this path to keep scanning the file that declares the sink rather than stopping at
+ * the module boundary the test happens to run in.
+ */
+ private static final String WIDGETS_MODULE_DIR = "../juneau-rest-server-widgets";
+
/** First-party icon-registry SVG assignments; never request/app/renderer text. */
private static final List<AllowedJsSink> SHIPPED_JS_ALLOWLIST = List.of(
new AllowedJsSink(VIEWS_JS_DIR + "/juneau-views.js", "b.innerHTML = markup;"),
@@ -287,17 +300,31 @@ final class RawContentSinkScanner {
}
/**
- * Walks the specified module root and scans every {@code src/main/java} and {@code src/test/java} Java
- * source under it (both trees, per this class's javadoc: this guardrail has no pre-existing main-source-only
- * "known-good" anchor to lean on the way {@code ScriptJsonSinkScanner} does).
+ * Walks the specified module root <b>and</b> the sibling widgets module root ({@link #WIDGETS_MODULE_DIR}),
+ * scanning every {@code src/main/java} and {@code src/test/java} Java source under each (both trees per
+ * module, per this class's javadoc: this guardrail has no pre-existing main-source-only "known-good" anchor to
+ * lean on the way {@code ScriptJsonSinkScanner} does). The widgets module is included because it declares its
+ * own {@code content(...)} sink ({@code CardContent}) and this guardrail follows the sink, not the module the
+ * test happens to run in.
*
- * @param moduleRoot The module root (e.g. {@code juneau-rest/juneau-rest-server-views}).
- * @return The aggregated sinks and violations across the tree.
- * @throws IOException If the tree cannot be walked.
+ * @param moduleRoot The views module root (e.g. {@code juneau-rest/juneau-rest-server-views}).
+ * @return The aggregated sinks and violations across both trees.
+ * @throws IOException If either tree cannot be walked.
*/
static Result scanTree(Path moduleRoot) throws IOException {
var sinks = new ArrayList<Sink>();
var violations = new ArrayList<String>();
+ scanJavaSources(moduleRoot, sinks, violations);
+ scanJavaSources(moduleRoot.resolve(WIDGETS_MODULE_DIR), sinks, violations);
+ return new Result(sinks, violations);
+ }
+
+ /**
+ * Scans one module root's {@code src/main/java} and {@code src/test/java} trees, appending every sink and
+ * violation found to {@code sinks}/{@code violations}. Extracted from {@link #scanTree} so that method can
+ * walk both this module and the sibling widgets module with identical logic.
+ */
+ private static void scanJavaSources(Path moduleRoot, List<Sink> sinks, List<String> violations) throws IOException {
var target = File.separator + "target" + File.separator;
for (var sourceDir : List.of("main", "test")) {
var srcRoot = moduleRoot.resolve("src").resolve(sourceDir).resolve("java");
@@ -317,7 +344,6 @@ final class RawContentSinkScanner {
}
}
}
- return new Result(sinks, violations);
}
/**
diff --git a/juneau-rest/juneau-rest-server-views/src/test/java/org/apache/juneau/rest/server/views/SymbolSprite_StemIds_Test.java b/juneau-rest/juneau-rest-server-views/src/test/java/org/apache/juneau/rest/server/views/SymbolSprite_StemIds_Test.java
new file mode 100644
index 0000000000..d673b6e344
--- /dev/null
+++ b/juneau-rest/juneau-rest-server-views/src/test/java/org/apache/juneau/rest/server/views/SymbolSprite_StemIds_Test.java
@@ -0,0 +1,86 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.juneau.rest.server.views;
+
+import static java.nio.charset.StandardCharsets.*;
+import static org.junit.jupiter.api.Assertions.*;
+
+import java.io.*;
+import java.util.*;
+import java.util.regex.*;
+
+import org.apache.juneau.*;
+import org.junit.jupiter.api.*;
+
+/**
+ * Pins the exact set of {@code <symbol>} stem ids shipped in {@code juneau-symbols.svg}.
+ *
+ * <p>
+ * A third-party host page can override one of these glyphs by looking the stem id up by name and swapping in a
+ * replacement drawing for it. That lookup is name-based only, so if a stem id here is renamed - or quietly added
+ * or removed - without a matching change on the consuming side, the override stops finding its target. The
+ * result is not an error: the glyph simply renders as nothing, with no signal anywhere in this module. Guarding
+ * against that silent failure is the entire point of this test, so the check below is set equality rather than a
+ * one-directional containment check - a containment check would happily let a new id slip in unnoticed.
+ */
+class SymbolSprite_StemIds_Test extends TestBase {
+
+ /**
+ * The complete set of stem ids as of the time this guard was written. This set is intentionally frozen:
+ * any difference from what is actually shipped must be a deliberate, reviewed decision, not an accident of
+ * an artwork or naming change.
+ */
+ private static final Set<String> EXPECTED_IDS = Set.of(
+ "juneau-sym-cancel", "juneau-sym-check", "juneau-sym-chevrondown", "juneau-sym-chevronright",
+ "juneau-sym-close", "juneau-sym-collapse_all", "juneau-sym-columns", "juneau-sym-copy", "juneau-sym-csv",
+ "juneau-sym-download", "juneau-sym-edit", "juneau-sym-filter", "juneau-sym-new", "juneau-sym-pdf",
+ "juneau-sym-refresh", "juneau-sym-search", "juneau-sym-settings", "juneau-sym-spreadsheet",
+ "juneau-sym-toggle-deleted", "juneau-sym-toggle_column_search"
+ );
+
+ private static final Pattern SYMBOL_ID_PATTERN = Pattern.compile("<symbol\\s+id=\"([^\"]+)\"");
+
+ private static Set<String> actualIds() throws IOException {
+ String svg;
+ try (var in = ViewsMixin.class.getResourceAsStream(ViewsMixin.SYMBOLS_SVG_RESOURCE)) {
+ assertNotNull(in, () -> "missing classpath resource: " + ViewsMixin.SYMBOLS_SVG_RESOURCE);
+ svg = new String(in.readAllBytes(), UTF_8);
+ }
+ var ids = new LinkedHashSet<String>();
+ var m = SYMBOL_ID_PATTERN.matcher(svg);
+ while (m.find())
+ ids.add(m.group(1));
+ return ids;
+ }
+
+ @Test void a01_stemIdSetIsPinned() throws Exception {
+ var actual = actualIds();
+ if (actual.equals(EXPECTED_IDS))
+ return;
+
+ var removed = new TreeSet<>(EXPECTED_IDS);
+ removed.removeAll(actual);
+ var added = new TreeSet<>(actual);
+ added.removeAll(EXPECTED_IDS);
+
+ fail("juneau-symbols.svg <symbol> stem ids no longer match the pinned set - removed: " + removed
+ + ", added: " + added + ". A stem id is a lookup key a host page can override a glyph by; changing,"
+ + " adding, or removing one here (even one renamed to something equivalent-looking) breaks that"
+ + " lookup silently, with no error on either side. If this change is intentional, update"
+ + " EXPECTED_IDS to match.");
+ }
+}
diff --git a/juneau-rest/juneau-rest-server-views/src/test/java/org/apache/juneau/rest/server/views/ViewsJs_RibbonNormalize_Test.java b/juneau-rest/juneau-rest-server-views/src/test/java/org/apache/juneau/rest/server/views/ViewsJs_RibbonNormalize_Test.java
new file mode 100644
index 0000000000..c3a05a5da7
--- /dev/null
+++ b/juneau-rest/juneau-rest-server-views/src/test/java/org/apache/juneau/rest/server/views/ViewsJs_RibbonNormalize_Test.java
@@ -0,0 +1,232 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.juneau.rest.server.views;
+
+import static java.nio.charset.StandardCharsets.*;
+import static org.junit.jupiter.api.Assertions.*;
+import static org.junit.jupiter.api.Assumptions.*;
+
+import java.io.*;
+import java.nio.file.*;
+import java.util.*;
+import java.util.concurrent.*;
+
+import org.apache.juneau.*;
+import org.apache.juneau.marshall.marshaller.*;
+import org.junit.jupiter.api.*;
+
+/**
+ * The module's first behavioral DOM harness for {@code buildRibbon(...)} in {@code juneau-ribbon.js}, covering the
+ * refresh-to-trailing-cluster normalization.
+ *
+ * <p>
+ * The existing wiring canaries in {@code ViewsMixin_Serving_Test} (e.g. {@code f04_...}) assert only source
+ * substrings - {@code function place(}, {@code juneau-view-ribbon-group}, {@code __ungrouped} - every one of which
+ * survives this normalizer landing, so they stay green regardless of whether refresh actually moves. This class
+ * asserts the rendered DOM shape instead: which buttons land in which {@code .juneau-view-ribbon-group} cluster,
+ * and in what order, for each of the normalizer's specified cases.
+ */
+class ViewsJs_RibbonNormalize_Test extends TestBase {
+
+ private static String ribbonJs() throws IOException {
+ try (var in = ViewsMixin.class.getResourceAsStream(ViewsMixin.RIBBON_JS_RESOURCE)) {
+ assertNotNull(in);
+ return new String(in.readAllBytes(), UTF_8);
+ }
+ }
+
+ //------------------------------------------------------------------------------------------------------------------
+ // Behavioral harness
+ //------------------------------------------------------------------------------------------------------------------
+
+ private static Map<?,?> report;
+
+ @BeforeAll
+ static void probeIfNodeAvailable() throws Exception {
+ if (!nodeAvailable())
+ return;
+ var harness = locateHarness();
+ if (harness == null)
+ return;
+ var ribbonFile = Files.createTempFile("juneau-ribbon-", ".js");
+ try {
+ Files.writeString(ribbonFile, ribbonJs(), UTF_8);
+ report = Json.to(runNode(harness, ribbonFile), Map.class);
+ } finally {
+ Files.deleteIfExists(ribbonFile);
+ }
+ }
+
+ private static boolean nodeAvailable() {
+ try {
+ var p = new ProcessBuilder("node", "--version").redirectErrorStream(true).start();
+ if (!p.waitFor(5, TimeUnit.SECONDS)) {
+ p.destroyForcibly();
+ return false;
+ }
+ return p.exitValue() == 0;
+ } catch (Exception e) {
+ return false;
+ }
+ }
+
+ private static Path locateHarness() {
+ var basedir = System.getProperty("basedir");
+ if (basedir != null) {
+ var p = Path.of(basedir, "src/test/js/ribbon-normalize.cjs");
+ if (Files.isRegularFile(p)) return p.toAbsolutePath().normalize();
+ }
+ for (var rel : List.of(
+ "src/test/js/ribbon-normalize.cjs",
+ "juneau-rest/juneau-rest-server-views/src/test/js/ribbon-normalize.cjs"
+ )) {
+ var p = Path.of(rel);
+ if (Files.isRegularFile(p)) return p.toAbsolutePath().normalize();
+ }
+ return null;
+ }
+
+ private static String runNode(Path harness, Path ribbonJs) throws Exception {
+ var stdout = Files.createTempFile("ribbon-normalize-stdout-", ".json");
+ var stderr = Files.createTempFile("ribbon-normalize-stderr-", ".txt");
+ try {
+ var pb = new ProcessBuilder(List.of("node", harness.toString(), ribbonJs.toString()))
+ .redirectOutput(stdout.toFile())
+ .redirectError(stderr.toFile());
+ var p = pb.start();
+ if (!p.waitFor(30, TimeUnit.SECONDS)) {
+ p.destroyForcibly();
+ fail("ribbon-normalize.cjs did not finish within 30s; stderr:\n" + quietRead(stderr));
+ }
+ if (p.exitValue() != 0)
+ fail("ribbon-normalize.cjs exited " + p.exitValue() + "; stderr:\n" + quietRead(stderr)
+ + "\nstdout:\n" + quietRead(stdout));
+ return Files.readString(stdout, UTF_8);
+ } finally {
+ Files.deleteIfExists(stdout);
+ Files.deleteIfExists(stderr);
+ }
+ }
+
+ private static String quietRead(Path p) {
+ try { return Files.readString(p, UTF_8); }
+ catch (IOException e) { return "(unreadable: " + e.getMessage() + ")"; }
+ }
+
+ private static Map<?,?> report() {
+ assumeTrue(report != null, "node not available or ribbon-normalize.cjs not found — behavioral layer skipped");
+ return report;
+ }
+
+ @Test void a01_harnessLoadedTheRibbonRuntime() {
+ assertEquals(true, report().get("hasBuild"), report()::toString);
+ assertEquals(true, report().get("hasNormalizeRibbon"), () -> "normalizeRibbon must be exported on NS.ribbon: " + report());
+ }
+
+ //------------------------------------------------------------------------------------------------------------------
+ // Pure function: normalizeRibbon(actions) - DOM-free
+ //------------------------------------------------------------------------------------------------------------------
+
+ @Test void b01_noRefreshAction_isAnIdentityNoOp() {
+ var r = report();
+ assertEquals(true, r.get("pure_noRefresh_isSameReference"),
+ () -> "with no refresh action, normalizeRibbon must return the SAME array reference, unperturbed: " + r);
+ }
+
+ @Test void b02_oneRefreshAction_movesLastIntoItsOwnGroup() {
+ var r = report();
+ assertEquals("export,refresh", r.get("pure_oneRefresh_order"), r::toString);
+ assertEquals("__refresh", r.get("pure_oneRefresh_lastGroup"), r::toString);
+ assertEquals(true, r.get("pure_oneRefresh_exportGroupUnset"),
+ () -> "the export action itself must be untouched by the move: " + r);
+ }
+
+ @Test void b03_twoOrMoreRefreshActions_allMoveTogetherPreservingRelativeOrder() {
+ var r = report();
+ assertEquals("export,refresh:first,refresh:second", r.get("pure_twoRefresh_order"), r::toString);
+ assertEquals(true, r.get("pure_twoRefresh_bothInRefreshGroup"),
+ () -> "both refresh actions must land in the SAME trailing __refresh cluster: " + r);
+ assertEquals(true, r.get("pure_twoRefresh_relativeOrderPreserved"), r::toString);
+ }
+
+ @Test void b04_explicitGroupOnRefresh_optsOutCompletely() {
+ var r = report();
+ assertEquals("refresh,export", r.get("pure_explicitGroup_order"),
+ () -> "an explicitly-grouped refresh must NOT be relocated to the end: " + r);
+ assertEquals(true, r.get("pure_explicitGroup_groupUnchanged"),
+ () -> "an explicitly-grouped refresh must not be re-grouped into __refresh: " + r);
+ }
+
+ @Test void b05_danglingTrailingDividerIsDropped() {
+ var r = report();
+ assertEquals("export,refresh", r.get("pure_trailingDivider_order"),
+ () -> "a divider stranded in trailing position by the move must be dropped: " + r);
+ assertEquals(true, r.get("pure_trailingDivider_dropped"), r::toString);
+ // A NON-trailing divider (still separating two other actions once refresh is gone) must survive.
+ assertEquals("divider,export,refresh", r.get("pure_nonTrailingDivider_order"), r::toString);
+ }
+
+ //------------------------------------------------------------------------------------------------------------------
+ // DOM behavior: buildRibbon(viewDef, ctx), through the full render path
+ //------------------------------------------------------------------------------------------------------------------
+
+ @Test void c01_noRefreshAction_domIsUnaffected() {
+ var r = report();
+ assertEquals(1L, ((Number)r.get("dom_noRefresh_groupCount")).longValue(), r::toString);
+ assertEquals(2L, ((Number)r.get("dom_noRefresh_onlyGroupButtonCount")).longValue(), r::toString);
+ }
+
+ @Test void c02_oneRefreshDeclaredFirst_rendersAsTwoClustersWithRefreshAloneAndLast() {
+ var r = report();
+ assertEquals(2L, ((Number)r.get("dom_oneRefresh_groupCount")).longValue(),
+ () -> "must render TWO clusters (exports, refresh) - not one merged cluster: " + r);
+ assertEquals(2L, ((Number)r.get("dom_oneRefresh_firstGroupButtonCount")).longValue(),
+ () -> "the first cluster must be the two export buttons: " + r);
+ assertEquals(1L, ((Number)r.get("dom_oneRefresh_lastGroupButtonCount")).longValue(),
+ () -> "the last cluster must hold refresh ALONE: " + r);
+ assertEquals(true, r.get("dom_oneRefresh_lastGroupIsRefreshGlyph"), r::toString);
+ assertEquals(true, r.get("dom_oneRefresh_lastGroupIsLastChildOfBar"),
+ () -> "the refresh cluster must be the rightmost element of the bar: " + r);
+ }
+
+ @Test void c03_twoRefreshActions_bothLandInOneTrailingClusterInRelativeOrder() {
+ var r = report();
+ assertEquals(2L, ((Number)r.get("dom_twoRefresh_groupCount")).longValue(), r::toString);
+ assertEquals(2L, ((Number)r.get("dom_twoRefresh_lastGroupButtonCount")).longValue(),
+ () -> "both refresh buttons must share ONE trailing cluster: " + r);
+ assertEquals("A,B", r.get("dom_twoRefresh_lastGroupTitles"),
+ () -> "relative order of the moved refresh actions must be preserved: " + r);
+ }
+
+ @Test void c04_explicitGroupOnRefresh_staysWithItsDeclaredNeighbourNotRelocated() {
+ var r = report();
+ assertEquals(2L, ((Number)r.get("dom_explicitGroup_groupCount")).longValue(), r::toString);
+ assertEquals(2L, ((Number)r.get("dom_explicitGroup_firstGroupButtonCount")).longValue(), r::toString);
+ assertEquals("Refresh,Column search", r.get("dom_explicitGroup_firstGroupTitles"),
+ () -> "refresh must stay clustered with its declared group-mate, in declared order: " + r);
+ assertEquals(true, r.get("dom_explicitGroup_isNotLastChildOfBar"),
+ () -> "an opted-out refresh must NOT be relocated to the far right: " + r);
+ }
+
+ @Test void c05_danglingTrailingDivider_isDroppedFromTheRenderedBar() {
+ var r = report();
+ assertEquals(2L, ((Number)r.get("dom_trailingDivider_groupCount")).longValue(), r::toString);
+ assertEquals(0L, ((Number)r.get("dom_trailingDivider_dividerCount")).longValue(),
+ () -> "a divider stranded before the moved refresh must not render as an empty seam: " + r);
+ assertEquals(1L, ((Number)r.get("dom_trailingDivider_lastGroupButtonCount")).longValue(), r::toString);
+ }
+}
diff --git a/juneau-rest/juneau-rest-server-views/src/test/java/org/apache/juneau/rest/server/views/ViewsMixin_Serving_Test.java b/juneau-rest/juneau-rest-server-views/src/test/java/org/apache/juneau/rest/server/views/ViewsMixin_Serving_Test.java
index 599bea4219..5125435175 100644
--- a/juneau-rest/juneau-rest-server-views/src/test/java/org/apache/juneau/rest/server/views/ViewsMixin_Serving_Test.java
+++ b/juneau-rest/juneau-rest-server-views/src/test/java/org/apache/juneau/rest/server/views/ViewsMixin_Serving_Test.java
@@ -426,7 +426,11 @@ class ViewsMixin_Serving_Test extends TestBase {
var body = cWithMixin.get(ViewsMixin.VIEWS_CSS_PATH).run().assertStatus(200).getContent().asString();
assertTrue(body.contains(".juneau-view-ribbon-btn {"), body);
assertTrue(body.contains("min-width: 32px"), body);
- assertTrue(body.contains("height: 32px"), body);
+ // The button's height now spends the shared control-height step rather than repeating its literal, so the
+ // shape is pinned by asserting BOTH halves - the reference here and the step's declared value - rather
+ // than dropping to the reference alone, which would pass even if the step were re-valued.
+ assertTrue(body.contains("height: var(--jc-chrome-control-height)"), body);
+ assertTrue(body.contains("--jc-chrome-control-height: 32px"), body);
assertTrue(body.contains("display: flex"), body);
assertTrue(body.contains("border: 1px solid"), body);
assertTrue(body.contains(".juneau-view-ribbon-btn svg {"), body);
@@ -498,8 +502,10 @@ class ViewsMixin_Serving_Test extends TestBase {
var fnBody = functionBody(body, "function buildRibbon(");
assertTrue(fnBody.contains("function place("), fnBody);
assertTrue(fnBody.contains("juneau-view-ribbon-group"), fnBody);
- // Ungrouped icon buttons (refresh + export, etc.) share one synthetic cluster so they render as a
- // connected ribbon rather than orphan glyphs. An explicit .group() still splits clusters.
+ // Ungrouped icon buttons (export, columnSearchToggle, etc.) share one synthetic cluster so they render as
+ // a connected ribbon rather than orphan glyphs. refresh is excluded from that cluster by default - it is
+ // normalized into its own trailing group instead (see normalizeRibbon) - unless it declares an explicit
+ // .group() of its own, in which case it joins that group like any other action.
assertTrue(fnBody.contains("__ungrouped"), fnBody);
assertTrue(fnBody.contains("place("), fnBody);
// A divider always closes any open cluster (a divider is a deliberate visual break, not a grouping seam).
diff --git a/juneau-rest/juneau-rest-server-views/src/test/js/ribbon-normalize.cjs b/juneau-rest/juneau-rest-server-views/src/test/js/ribbon-normalize.cjs
new file mode 100644
index 0000000000..e93cf1ebf0
--- /dev/null
+++ b/juneau-rest/juneau-rest-server-views/src/test/js/ribbon-normalize.cjs
@@ -0,0 +1,207 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/*
+ * ribbon-normalize.cjs - the module's first always-on DOM harness for buildRibbon(...) in juneau-ribbon.js, built
+ * to prove the refresh-to-trailing-cluster normalization against real rendered DOM structure rather than source
+ * text (the existing wiring canaries in ViewsMixin_Serving_Test only assert substrings that survive this change
+ * unchanged).
+ *
+ * Covers, each as its own case:
+ *
+ * 1. No refresh action - normalizeRibbon is an identity no-op, and buildRibbon's output is unaffected.
+ * 2. Exactly one (ungrouped) refresh - it is removed from its declared position and rendered alone, last, in
+ * its own one-button ".juneau-view-ribbon-group" cluster; the export cluster ahead of it is untouched.
+ * 3. Two or more ungrouped refresh actions - ALL of them move, preserving their relative order, into the SAME
+ * trailing cluster (not split across two clusters, not left behind).
+ * 4. A refresh action carrying an explicit `group` opts out entirely: it is not moved and does not join the
+ * synthetic `__refresh` cluster - it stays exactly where its neighbours put it.
+ * 5. A `divider` left dangling in trailing position by the move (nothing follows it once refresh is gone) is
+ * dropped, not rendered as an empty seam; a NON-trailing divider (still separating two other actions)
+ * survives untouched.
+ *
+ * Usage: node ribbon-normalize.cjs <juneau-ribbon.js>
+ *
+ * Prints ONE JSON object to stdout; every assertion lives in the Java test.
+ */
+'use strict';
+
+const fs = require('node:fs');
+const path = require('node:path');
+const vm = require('node:vm');
+const { makeEnv } = require(path.join(__dirname, 'views-dom-shim.cjs'));
+
+const ribbonJsPath = process.argv[2];
+if (!ribbonJsPath) {
+ console.error('usage: node ribbon-normalize.cjs <juneau-ribbon.js>');
+ process.exit(2);
+}
+const ribbonJsSource = fs.readFileSync(path.resolve(ribbonJsPath), 'utf8');
+
+/**
+ * Loads a fresh copy of juneau-ribbon.js into its own env/sandbox. `withExportFeature` installs a minimal
+ * jQuery-with-DataTables-Buttons stand-in so the `export` branch of buildRibbon actually resolves and renders
+ * its buttons (feature-detection would otherwise degrade export to nothing, per the file's own design).
+ */
+function loadRibbon(withExportFeature) {
+ const env = makeEnv();
+ if (withExportFeature)
+ env.window.jQuery = { fn: { dataTable: { Buttons: function () {} } } };
+ const sandbox = {
+ window: env.window, document: env.document, console: console,
+ setTimeout: function () { return 0; }, clearTimeout: function () {},
+ setInterval: function () { return 0; }, clearInterval: function () {}
+ };
+ vm.runInNewContext(ribbonJsSource, sandbox, { filename: 'juneau-ribbon.js' });
+ return { env: env, NS: env.window.JuneauViews };
+}
+
+const out = {};
+const first = loadRibbon(false);
+out.hasBuild = !!(first.NS && first.NS.ribbon && typeof first.NS.ribbon.build === 'function');
+out.hasNormalizeRibbon = !!(first.NS && first.NS.ribbon && typeof first.NS.ribbon.normalizeRibbon === 'function');
+if (!out.hasBuild) { process.stdout.write(JSON.stringify(out)); process.exit(0); }
+
+/** A minimal RibbonAction-shaped action literal, mirroring the RibbonAction wire shape. */
+function action(type, extra) { return Object.assign({ type: type }, extra || {}); }
+
+// ------------------------------------------------------------------------------------------------------------------
+// Pure function: normalizeRibbon(actions) - DOM-free, run only when the export exists (pre-fix it does not).
+// ------------------------------------------------------------------------------------------------------------------
+
+if (out.hasNormalizeRibbon) {
+ const normalizeRibbon = first.NS.ribbon.normalizeRibbon;
+
+ // 1) No refresh action - identity no-op (same array reference back).
+ const noRefresh = [action('export', { buttons: ['copy', 'csv'] }), action('columnSearchToggle')];
+ out.pure_noRefresh_isSameReference = normalizeRibbon(noRefresh) === noRefresh;
+
+ // 2) Exactly one refresh - moved last, into '__refresh'; the export action itself is untouched.
+ const oneRefresh = [action('refresh'), action('export', { buttons: ['copy', 'csv'] })];
+ const oneRefreshResult = normalizeRibbon(oneRefresh);
+ out.pure_oneRefresh_order = oneRefreshResult.map(function (x) { return x.type; }).join(',');
+ out.pure_oneRefresh_lastGroup = oneRefreshResult[oneRefreshResult.length - 1].group;
+ out.pure_oneRefresh_exportGroupUnset = oneRefreshResult[0].type === 'export' && oneRefreshResult[0].group == null;
+
+ // 3) Two refresh actions - BOTH move, preserving relative order, into the SAME trailing group.
+ const twoRefresh = [
+ action('refresh', { title: 'first' }), action('export', { buttons: ['copy'] }), action('refresh', { title: 'second' })
+ ];
+ const twoRefreshResult = normalizeRibbon(twoRefresh);
+ out.pure_twoRefresh_order = twoRefreshResult.map(function (x) { return x.type + (x.title ? ':' + x.title : ''); }).join(',');
+ out.pure_twoRefresh_bothInRefreshGroup = twoRefreshResult[1].group === '__refresh' && twoRefreshResult[2].group === '__refresh';
+ out.pure_twoRefresh_relativeOrderPreserved = twoRefreshResult[1].title === 'first' && twoRefreshResult[2].title === 'second';
+
+ // 4) Explicit group on refresh - opts out entirely: stays in place, group left exactly as declared.
+ const explicitGroup = [action('refresh', { group: 'filters' }), action('export', { buttons: ['copy'] })];
+ const explicitGroupResult = normalizeRibbon(explicitGroup);
+ out.pure_explicitGroup_order = explicitGroupResult.map(function (x) { return x.type; }).join(',');
+ out.pure_explicitGroup_groupUnchanged = explicitGroupResult[0].group === 'filters';
+
+ // 5a) Trailing divider dropped: '..., divider(), refresh()' leaves no dangling divider once refresh moves.
+ const trailingDivider = [action('export', { buttons: ['copy'] }), action('divider'), action('refresh')];
+ const trailingDividerResult = normalizeRibbon(trailingDivider);
+ out.pure_trailingDivider_order = trailingDividerResult.map(function (x) { return x.type; }).join(',');
+ out.pure_trailingDivider_dropped = trailingDividerResult.every(function (x) { return x.type !== 'divider'; });
+
+ // 5b) A NON-trailing divider (still separating two other actions once refresh is gone) survives untouched.
+ const nonTrailingDivider = [action('refresh'), action('divider'), action('export', { buttons: ['copy'] })];
+ const nonTrailingDividerResult = normalizeRibbon(nonTrailingDivider);
+ out.pure_nonTrailingDivider_order = nonTrailingDividerResult.map(function (x) { return x.type; }).join(',');
+}
+
+// ------------------------------------------------------------------------------------------------------------------
+// DOM behavior: buildRibbon(viewDef, ctx), through the full render path (the real deliverable - the canaries in
+// ViewsMixin_Serving_Test only assert source substrings, none of which change shape when this normalizer lands).
+// ------------------------------------------------------------------------------------------------------------------
+
+function groupsOf(bar) {
+ return bar.childNodes.filter(function (c) { return c.className === 'juneau-view-ribbon-group'; });
+}
+
+function dividersOf(bar) {
+ return bar.childNodes.filter(function (c) { return c.className === 'juneau-view-ribbon-divider'; });
+}
+
+function buildBar(NS, ribbon) {
+ return NS.ribbon.build({ ribbon: ribbon }, { dataTable: {}, redraw: function () {} });
+}
+
+// Case 1 - no refresh action: unaffected. One export cluster, nothing trailing added.
+{
+ const { NS } = loadRibbon(true);
+ const bar = buildBar(NS, [action('export', { buttons: ['copy', 'csv'] })]);
+ const groups = groupsOf(bar);
+ out.dom_noRefresh_groupCount = groups.length;
+ out.dom_noRefresh_onlyGroupButtonCount = groups.length ? groups[0].childNodes.length : -1;
+}
+
+// Case 2 - exactly one refresh, declared FIRST (the console's actual today-shape): two groups after the fix,
+// exports first, refresh alone and last.
+{
+ const { NS } = loadRibbon(true);
+ const bar = buildBar(NS, [action('refresh'), action('export', { buttons: ['copy', 'csv'] })]);
+ const groups = groupsOf(bar);
+ out.dom_oneRefresh_groupCount = groups.length;
+ out.dom_oneRefresh_firstGroupButtonCount = groups.length > 0 ? groups[0].childNodes.length : -1;
+ out.dom_oneRefresh_lastGroupButtonCount = groups.length > 0 ? groups[groups.length - 1].childNodes.length : -1;
+ const lastGroupBtn = groups.length > 0 ? groups[groups.length - 1].childNodes[0] : null;
+ out.dom_oneRefresh_lastGroupIsRefreshGlyph = lastGroupBtn != null && lastGroupBtn.title === 'Refresh';
+ out.dom_oneRefresh_lastGroupIsLastChildOfBar = groups.length > 0 && bar.lastElementChild === groups[groups.length - 1];
+}
+
+// Case 3 - two refresh actions around an export cluster: both move into ONE trailing group, in relative order.
+{
+ const { NS } = loadRibbon(true);
+ const bar = buildBar(NS, [
+ action('refresh', { title: 'A' }), action('export', { buttons: ['copy'] }), action('refresh', { title: 'B' })
+ ]);
+ const groups = groupsOf(bar);
+ out.dom_twoRefresh_groupCount = groups.length;
+ const lastGroup = groups.length > 0 ? groups[groups.length - 1] : null;
+ out.dom_twoRefresh_lastGroupButtonCount = lastGroup ? lastGroup.childNodes.length : -1;
+ out.dom_twoRefresh_lastGroupTitles = lastGroup ? lastGroup.childNodes.map(function (b) { return b.title; }).join(',') : null;
+}
+
+// Case 4 - refresh carries an explicit group shared with a neighbour: opts out completely, stays put (here,
+// declared FIRST) rather than relocating to the end.
+{
+ const { NS } = loadRibbon(true);
+ const bar = buildBar(NS, [
+ action('refresh', { group: 'filters' }), action('columnSearchToggle', { group: 'filters' }),
+ action('export', { buttons: ['copy'] })
+ ]);
+ const groups = groupsOf(bar);
+ out.dom_explicitGroup_groupCount = groups.length;
+ const firstGroup = groups.length > 0 ? groups[0] : null;
+ out.dom_explicitGroup_firstGroupButtonCount = firstGroup ? firstGroup.childNodes.length : -1;
+ out.dom_explicitGroup_firstGroupTitles = firstGroup ? firstGroup.childNodes.map(function (b) { return b.title; }).join(',') : null;
+ out.dom_explicitGroup_isNotLastChildOfBar = groups.length > 0 && bar.lastElementChild !== groups[0];
+}
+
+// Case 5 - a divider immediately before a trailing refresh is dropped (no dangling seam); export cluster and the
+// refresh cluster both survive.
+{
+ const { NS } = loadRibbon(true);
+ const bar = buildBar(NS, [action('export', { buttons: ['copy'] }), action('divider'), action('refresh')]);
+ const groups = groupsOf(bar);
+ out.dom_trailingDivider_groupCount = groups.length;
+ out.dom_trailingDivider_dividerCount = dividersOf(bar).length;
+ out.dom_trailingDivider_lastGroupButtonCount = groups.length > 0 ? groups[groups.length - 1].childNodes.length : -1;
+}
+
+process.stdout.write(JSON.stringify(out));
diff --git a/juneau-rest/juneau-rest-server-widgets/src/main/java/org/apache/juneau/rest/server/widgets/CardBody.java b/juneau-rest/juneau-rest-server-widgets/src/main/java/org/apache/juneau/rest/server/widgets/CardBody.java
index 3ffe018fd1..16a75e3769 100644
--- a/juneau-rest/juneau-rest-server-widgets/src/main/java/org/apache/juneau/rest/server/widgets/CardBody.java
+++ b/juneau-rest/juneau-rest-server-widgets/src/main/java/org/apache/juneau/rest/server/widgets/CardBody.java
@@ -20,11 +20,11 @@ package org.apache.juneau.rest.server.widgets;
* The body-slot contract for a {@link Card}: the single, heterogeneous content a card hosts.
*
* <p>
- * This marker is the extension point future body types implement. The v1 emitter dispatches over a <b>closed</b>
- * set of known implementations (v1: {@link CardFieldList} only) and <b>fails closed</b> on any unknown
- * {@code CardBody}; a later body type is added by implementing this interface, patching the emitter's closed
- * dispatch set, and bringing its <b>own</b> server-render and (if stateful) its <b>own</b> data path — it does
- * not share {@link CardFieldList}'s refresh envelope.
+ * This marker is the extension point future body types implement. The emitter (in the views module,
+ * {@code CardGridTable}) dispatches over a <b>closed</b> set of known implementations and <b>fails closed</b> on
+ * any unknown {@code CardBody}; a new body type is added by implementing this interface, patching the emitter's
+ * closed dispatch set, and bringing its <b>own</b> server-render and (if stateful) its <b>own</b> data path
+ * — it does not share {@link CardFieldList}'s refresh envelope.
*
* @since 10.0.0
*/
diff --git a/juneau-rest/juneau-rest-server-widgets/src/main/java/org/apache/juneau/rest/server/widgets/CardContent.java b/juneau-rest/juneau-rest-server-widgets/src/main/java/org/apache/juneau/rest/server/widgets/CardContent.java
new file mode 100644
index 0000000000..89333370a6
--- /dev/null
+++ b/juneau-rest/juneau-rest-server-widgets/src/main/java/org/apache/juneau/rest/server/widgets/CardContent.java
@@ -0,0 +1,88 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.juneau.rest.server.widgets;
+
+import static org.apache.juneau.commons.utils.Shorts.*;
+
+/**
+ * A raw-markup {@link CardBody} — first-party prose or already-rendered markup hosted inside a card, emitted
+ * verbatim rather than escaped.
+ *
+ * <h5 class='section'>Ownership contract: template engine, trusted / first-party content only</h5>
+ * <p>
+ * This framework is a <b>template engine</b> on this path: <b>the caller is responsible for sanitizing
+ * {@link #content} before setting it; the framework performs no sanitization and emits the string exactly as
+ * given.</b> Nothing in this framework neutralizes {@code <script>}, {@code <style>}, inline event handlers, or
+ * {@code url(...)} sinks in this value — this is the same raw-panel-body contract this toolkit already ships
+ * for a page's tab/sub-tab panel content, applied here to a card body.
+ *
+ * <p>
+ * Accordingly, {@link #content} MUST carry <b>trusted, first-party content only</b> — markup the application
+ * itself authored or rendered from a trusted, non-attacker-controlled source (e.g. hand-written card prose, or
+ * HTML rendered from a first-party markdown document). {@link #content} MUST NOT carry live/remote/attacker-
+ * influenceable data (a request parameter, a third-party API response, any value derived from something an
+ * untrusted party can influence). Pouring such data into this sink is stored XSS in the page's own trusted origin.
+ * A card built from live data must use {@link CardFieldList} instead, whose field values are emitted as escaped
+ * text children, never through this body — a build-gating scanner enforces that separation for this
+ * framework's own sources (see the {@code RawContentSinkScanner} test-only guard in the views module's test tree).
+ *
+ * @since 10.0.0
+ */
+@SuppressWarnings({
+ "java:S1845" // Fluent-builder setters intentionally mirror field names (Juneau DSL convention).
+})
+public class CardContent implements CardBody {
+
+ /**
+ * The raw markup body. Emitted <b>verbatim</b> — unescaped — by the card emitter via the html5
+ * {@code rawText(...)} primitive (a plain {@code String} child would instead be entity-escaped and would
+ * break markup-bearing prose). See this class's javadoc for the full ownership contract.
+ */
+ public String content;
+
+ /**
+ * Creates an empty raw-markup body.
+ *
+ * @return A new {@link CardContent}.
+ */
+ public static CardContent create() {
+ return new CardContent();
+ }
+
+ /**
+ * Sets the raw markup body (see this class's javadoc for the full ownership contract — trusted /
+ * first-party content only, emitted verbatim).
+ *
+ * @param value The raw markup. Must not be <jk>null</jk>.
+ * @return This object.
+ */
+ public CardContent content(String value) {
+ content = value;
+ return this;
+ }
+
+ /**
+ * Fail-closed bean validation.
+ *
+ * @throws IllegalArgumentException If {@link #content} is not set.
+ */
+ @Override /* CardBody */
+ public void validate() {
+ if (content == null)
+ throw iaex("CardContent must declare content.");
+ }
+}
diff --git a/juneau-rest/juneau-rest-server-widgets/src/test/java/org/apache/juneau/rest/server/widgets/CardContent_Test.java b/juneau-rest/juneau-rest-server-widgets/src/test/java/org/apache/juneau/rest/server/widgets/CardContent_Test.java
new file mode 100644
index 0000000000..fddbae5d70
--- /dev/null
+++ b/juneau-rest/juneau-rest-server-widgets/src/test/java/org/apache/juneau/rest/server/widgets/CardContent_Test.java
@@ -0,0 +1,61 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.juneau.rest.server.widgets;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+import java.nio.file.*;
+
+import org.apache.juneau.*;
+import org.junit.jupiter.api.*;
+
+/**
+ * {@link CardContent} bean contract: the raw-markup {@link CardBody}. This widgets test must never import
+ * {@code ViewDef} (no widgets→views), mirroring {@code CardFieldList_Test}'s equivalent check.
+ */
+class CardContent_Test extends TestBase {
+
+ @Test void a01_builder_roundTrip() {
+ var c = CardContent.create().content("<p>Hello, <b>world</b>.</p>");
+ assertEquals("<p>Hello, <b>world</b>.</p>", c.content);
+ c.validate();
+ }
+
+ @Test void a02_nullContent_rejected() {
+ var c = CardContent.create();
+ var e = assertThrows(IllegalArgumentException.class, c::validate);
+ assertTrue(e.getMessage().contains("content"), e::getMessage);
+ }
+
+ @Test void a03_blankContent_isAccepted() {
+ // Mirrors the Tab/Subtab raw-content contract: a blank (non-null) body is not an error, only an absent one.
+ var c = CardContent.create().content(" ");
+ c.validate();
+ assertEquals(" ", c.content);
+ }
+
+ @Test void a04_source_doesNotImportViewsModule() throws Exception {
+ var root = Path.of("").toAbsolutePath();
+ var src = root;
+ if (!Files.isDirectory(src.resolve("src/main/java")))
+ src = root.resolve("juneau-rest/juneau-rest-server-widgets");
+ var f = src.resolve("src/main/java/org/apache/juneau/rest/server/widgets/CardContent.java");
+ for (var line : Files.readAllLines(f))
+ if (line.stripLeading().startsWith("import "))
+ assertFalse(line.contains("rest.server.views"), () -> "CardContent must not import any views type: " + line);
+ }
+}