001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.apache.juneau.console; 018 019import static org.apache.juneau.commons.utils.Shorts.*; 020 021import java.util.*; 022import java.util.regex.*; 023 024/** 025 * The validated token model behind the console's FTL {@code <@theme>}/{@code <@token>} directives: an immutable theme 026 * name, an ordered map of leaf tokens (literals) and an ordered map of alias tokens (live {@code var()} references). 027 * 028 * <p> 029 * Applications don't build themes in Java. They author them in their FreeMarker chrome, and the directives build 030 * this object: 031 * 032 * <h2 class='section'>Example:</h2> 033 * <p class='bftl'> 034 * <@console> 035 * <@theme name="light-red"> 036 * <#-- A leaf: a literal (or a var() resolved to one at build time). --> 037 * <@token name="--jc-pill-red-bg" value="#fdeceb"/> 038 * <#-- An alias: a reference that stays live in the browser's cascade. --> 039 * <@token name="--jc-tab-bar-bg" alias="var(--jc-card-bg)"/> 040 * </@theme> 041 * <@main/> 042 * </@console> 043 * </p> 044 * 045 * <p> 046 * That is equivalent to the following, which is what {@code <@theme>} does internally after seeding the builder 047 * from the stock palette: 048 * 049 * <p class='bjava'> 050 * Theme <jv>theme</jv> = Theme.<jsm>create</jsm>(<js>"light-red"</js>) 051 * .token(<js>"--jc-pill-red-bg"</js>, <js>"#fdeceb"</js>) 052 * .alias(<js>"--jc-tab-bar-bg"</js>, <js>"var(--jc-card-bg)"</js>) 053 * .build(); 054 * String <jv>css</jv> = ConsoleChromeMixin.<jsm>overrideBlock</jsm>(<jv>theme</jv>); 055 * <jc>// html:root{--jc-pill-red-bg:#fdeceb;--jc-tab-bar-bg:var(--jc-card-bg);}</jc> 056 * </p> 057 * 058 * <p> 059 * The five stock palettes ({@link #OPEN}, {@link #LIGHT_RED}, {@link #LIGHT_BROWN}, {@link #RED}, {@link #GRAY}) 060 * are selected by name: {@code <@theme name="gray">} in FTL, or {@code ConsoleChromeMixin.create().theme("gray")} 061 * for the served {@code chrome.css}. 062 * 063 * <h2 class='section'>The two channels:</h2> 064 * <p> 065 * The contract in one sentence: <b>a leaf is always a literal; an alias is always a reference; and no token name 066 * is declared by both.</b> The two channels are disjoint by <i>value shape</i> rather than by convention, and each 067 * carries its own validation: 068 * 069 * <table class='styled'> 070 * <caption>Leaf tokens compared with alias tokens</caption> 071 * <tr><th> </th><th>leaf ({@link #getTokens()})</th><th>alias ({@link #getAliases()})</th></tr> 072 * <tr><td>example</td><td><c>--jc-accent: #b45309</c></td><td><c>--jc-tab-bar-bg: var(--jc-card-bg)</c></td></tr> 073 * <tr><td>value shape</td><td>literal</td><td>reference</td></tr> 074 * <tr><td>validated by</td><td>{@code CssValueGrammar}'s accept-known-safe allowlist</td><td>the anchored 075 * {@code var(--jc-name)} recognizer ({@link Builder#alias(String, String)})</td></tr> 076 * <tr><td>emitted</td><td>escaped, via {@code CssValueEscaper}</td><td>verbatim — see 077 * <i>Injection safety</i> below</td></tr> 078 * </table> 079 * 080 * <p> 081 * The rule a theme author needs to remember: <b>a literal belongs in {@link Builder#token(String, String)}; a 082 * reference belongs in {@link Builder#alias(String, String)}.</b> To make {@code --jc-tab-bar-bg} be {@code #fff}, 083 * declare it with {@code token()}. To make it <i>follow</i> {@code --jc-card-bg} through the live cascade, 084 * {@link Builder#alias(String, String) alias} it. 085 * 086 * <h2 class='section'>Why the alias channel exists at all:</h2> 087 * <p> 088 * A leaf cannot carry a derived token. {@link Builder#build()} recognizes a {@code var(--jc-name)} value as a 089 * reference and <b>resolves it to a frozen literal</b>, which snapshots the live CSS cascade at composition time 090 * — so a token that must <i>keep following</i> its target can never be a leaf. {@code 091 * ConsoleChromeMixin.OPEN_ROLE_ALIASES} is the framework's own answer to the same problem, but those are 092 * unconditional framework defaults rather than per-theme derivations. The alias map is the third channel: 093 * <b>consumer-authored derivations that survive to the wire as references.</b> 094 * 095 * <h2 class='section'>The var() asymmetry — read this before "unifying" the two paths:</h2> 096 * <p> 097 * These two adjacent channels have <b>opposite</b> {@code var()} semantics, deliberately: 098 * <ul class='spaced-list'> 099 * <li>A {@code var()} in a <b>leaf</b> is <b>resolved away</b> before the wire ({@link Builder#build()}), so the 100 * served declaration carries the literal. That is asserted by {@code 101 * ConsoleChromeMixin_OverrideBlock_Test.a05}, which pins that {@code --jc-tag-red-text:var(} never appears in 102 * the body. 103 * <li>A {@code var()} in an <b>alias</b> must <b>survive as a reference</b> in the served declaration. Freezing 104 * it to a literal would defeat the entire purpose of the channel. 105 * </ul> 106 * <p> 107 * So a change that "unifies the two {@code var()} paths" silently destroys this type's reason to exist. The same 108 * warning is repeated at the emission site ({@code ConsoleChromeMixin.overrideBlock}), because that is the other 109 * place the mistake is reachable from. 110 * 111 * <h2 class='section'>The dark channel:</h2> 112 * <p> 113 * A theme may also declare <b>dark accents</b> with {@link Builder#dark(String, String)}, read back through 114 * {@link #getDarkTokens()}. They apply on top of the shared dark neutral layer, when the page is in the dark scheme. 115 * Only literals are accepted: a {@code var()} would resolve against the light palette, which would bake the wrong 116 * value into the dark scheme. The stock themes use the channel to keep their link, focus and accent colours 117 * legible on a dark surface. 118 * 119 * <h2 class='section'>Security:</h2> 120 * <p> 121 * Identifiers (theme name, token name, alias name) are rejected fail-closed by anchored {@code String.matches(...)} 122 * guards. Leaf values are validated by {@code CssValueGrammar}'s accept-known-safe allowlist grammar (not a 123 * {@code url(}-blocklist) and are escaped at emission time by {@code CssValueEscaper}. A leaf may also be a 124 * {@code var(--jc-name)} reference to another known token; {@link Builder#build() build()} resolves it to a 125 * concrete literal (own tokens shadowing {@link #OPEN}'s), so {@code var(} never appears in a {@link #getTokens()} 126 * value. An unknown reference, a cycle, or a chain longer than the resolution depth cap is a loud {@code build()} 127 * failure, never a silent fallback. Declared names in the reserved {@code --jc-chrome-*} namespace are rejected 128 * (see {@code rejectReservedChromeDeclaration}). 129 * 130 * <h2 class='section'>Injection safety of the alias channel:</h2> 131 * <p> 132 * Every alias value must match the fully-anchored {@code var(--jc-name)} shape ({@code VAR_REFERENCE}), which 133 * admits <b>exactly</b> this alphabet and nothing else: the three letters of {@code var} in either case, an opening 134 * paren, optional ASCII spaces, the literal {@code --jc-}, one or more of {@code [a-z0-9-]}, optional ASCII spaces, 135 * and a closing paren. (The recognizer's whitespace class can only ever match a plain space here, because every 136 * other character it would accept — tab, newline, carriage return, form feed, vertical tab — is a C0 137 * control character that {@code CssValueGrammar}'s belt has already rejected on the raw value, before this 138 * recognizer runs.) 139 * 140 * <p> 141 * So not one of {@code ;}, <code>}</code>, {@code "}, {@code '}, {@code \}, <code>/*</code>, {@code url(} or a 142 * control character is <i>representable</i> in an accepted value — the emitted text is provably safe with 143 * <b>no escaper at all</b>. That is a strictly stronger claim than the leaf channel's "safe because we escape it", 144 * and it is the reason the channel is restricted to references rather than given an escaper of its own (escaping a 145 * {@code var()} reference would corrupt its parens). 146 * 147 * <p> 148 * A corollary worth stating: because an alias cannot carry a literal, the alias channel is <b>structurally</b> 149 * incapable of smuggling in a colour value, a font stack, or any other palette content. It can only ever point one 150 * name at another. 151 * 152 * @since 10.0.0 153 */ 154@SuppressWarnings({ 155 "java:S1192" // Duplicated literals are CSS custom-property / theme-token values; constants would obscure the token map. 156}) 157public final class Theme { 158 159 /** Anchored (full-string) guard for a theme name. Anchoring matters: an unanchored {@code find()} would accept {@code "--jc-foo;--bar"}-shaped garbage as a substring match. */ 160 private static final String NAME_PATTERN = "^[a-z][a-z0-9-]*$"; 161 162 /** Anchored (full-string) guard for a CSS custom-property token name. */ 163 private static final String TOKEN_NAME_PATTERN = "^--jc-[a-z0-9-]+$"; 164 165 /** 166 * Anchored recognizer for a {@code var(--jc-name)} Theme-layer reference, run on the post-belt (control-char 167 * rejected, comment-stripped, trimmed) value. 168 * 169 * <p> 170 * Fully anchored ({@code ^...$}) so a reference can only ever be the <b>entire</b> value, never a prefix or 171 * suffix of some larger value: {@code linear-gradient(var(--jc-a), #fff)} never matches this and is rejected by 172 * the unchanged grammar. There is no fallback branch — {@code var(--jc-x, #fff)} simply fails to match 173 * (comma inside the parens) and falls through to grammar rejection. 174 */ 175 static final Pattern VAR_REFERENCE = Pattern.compile("^[Vv][Aa][Rr]\\(\\s*(--jc-[a-z0-9-]+)\\s*\\)$"); 176 177 /** The reserved token-name prefix guarded by {@link #rejectReservedChromeDeclaration(String, String)}. */ 178 static final String CHROME_TOKEN_PREFIX = "--jc-chrome-"; 179 180 /** 181 * The maximum number of reference hops resolved before {@code build()} fails, enforced independently of cycle 182 * detection so a long <i>acyclic</i> chain is bounded too. 183 */ 184 private static final int MAX_REFERENCE_HOPS = 8; 185 186 /** 187 * The default, "open" theme. 188 * 189 * <p> 190 * Ships with the framework so out-of-the-box adoption needs zero theme configuration: an Inter/system-ui font 191 * stack, a neutral blue-gray page gradient, and blue accents. Its token set is exactly the set 192 * {@code chrome.css} references — see {@code ConsoleChromeMixin_Test}'s bidirectional cross-check (every 193 * token here is a {@code var(--jc-*)} in {@code chrome.css}, and vice versa). 194 */ 195 public static final Theme OPEN = create("open") 196 .token("--jc-font", "'Inter', 'Source Sans 3', system-ui, sans-serif") 197 .token("--jc-page-bg", "linear-gradient(180deg, #b0c4df 0%, #c7d5e8 22%, #e4eaf2 55%, #f5f6f9 100%)") 198 .token("--jc-header-icon-color", "#747474") 199 .token("--jc-accent", "#1589EE") 200 .token("--jc-accent-wash", "rgba(21,137,238,0.1)") 201 .token("--jc-tab-selected-bg", "#e8f3fd") 202 .token("--jc-link", "#015194") 203 .token("--jc-search-help-fg", "#2b6cb0") 204 .token("--jc-text", "#080707") 205 .token("--jc-text-soft", "#080707cc") 206 .token("--jc-text-muted", "#706e6b") 207 .token("--jc-border", "#dddbda") 208 .token("--jc-border-2", "#888c90") 209 .token("--jc-card-bg", "#ffffff") 210 .token("--jc-chrome-bg", "#f3f2f2") 211 .token("--jc-white", "#ffffff") 212 .token("--jc-btn-primary", "#1a5297") 213 .token("--jc-btn-primary-hover", "#005fb2") 214 .token("--jc-danger", "#c23934") 215 .token("--jc-success", "#2e844a") 216 .token("--jc-avatar-bg", "linear-gradient(135deg, #1589EE, #1a5297)") 217 .token("--jc-radius", "0.25rem") 218 // Pill palette: the CANONICAL status-chip colour family the client `pill` catalog renderer 219 // paints from - the ".tag.<domain>.<value>" palette rules in chrome.css consume these directly. Declared 220 // before the legacy --jc-tag-* triads so those can be authored as var(--jc-pill-*) references to this single 221 // source of truth. Values are the exact literals the --jc-tag-* tokens use. 222 .token("--jc-pill-green-bg", "#b8e6c4") 223 .token("--jc-pill-green-text", "#155724") 224 .token("--jc-pill-green-border", "#9fd6ad") 225 .token("--jc-pill-blue-bg", "#dceefb") 226 .token("--jc-pill-blue-text", "#0c5460") 227 .token("--jc-pill-blue-border", "#c3e0f3") 228 .token("--jc-pill-amber-bg", "#fff3cd") 229 .token("--jc-pill-amber-text", "#856404") 230 .token("--jc-pill-amber-border", "#ffe69c") 231 .token("--jc-pill-neutral-bg", "#e2e3e5") 232 .token("--jc-pill-neutral-text", "#383d41") 233 .token("--jc-pill-neutral-border", "#c6c8ca") 234 .token("--jc-pill-red-bg", "#f8d7da") 235 .token("--jc-pill-red-text", "#721c24") 236 .token("--jc-pill-red-border", "#f5c6cb") 237 // Categorical pill palette: ten pale-wash/dark-ink triads used by the pill renderer's per-value colouring. 238 // Slots 3 and 5 are brown and cyan (not green/red) so a categorical colour never reads as a status. 239 .token("--jc-pill-cat-1-bg", "#dbe9fb") 240 .token("--jc-pill-cat-1-text", "#0b3d7a") 241 .token("--jc-pill-cat-1-border", "#b5d0f0") 242 .token("--jc-pill-cat-2-bg", "#fde6d0") 243 .token("--jc-pill-cat-2-text", "#7a3a05") 244 .token("--jc-pill-cat-2-border", "#f3c9a0") 245 .token("--jc-pill-cat-3-bg", "#eadfd3") 246 .token("--jc-pill-cat-3-text", "#5c3a1e") 247 .token("--jc-pill-cat-3-border", "#d6c4b0") 248 .token("--jc-pill-cat-4-bg", "#efdcf7") 249 .token("--jc-pill-cat-4-text", "#5b1f73") 250 .token("--jc-pill-cat-4-border", "#dcbfe9") 251 .token("--jc-pill-cat-5-bg", "#d3eefa") 252 .token("--jc-pill-cat-5-text", "#0b4a63") 253 .token("--jc-pill-cat-5-border", "#a9dcf0") 254 .token("--jc-pill-cat-6-bg", "#d0f0f0") 255 .token("--jc-pill-cat-6-text", "#0b5252") 256 .token("--jc-pill-cat-6-border", "#a6dcdc") 257 .token("--jc-pill-cat-7-bg", "#f3eccb") 258 .token("--jc-pill-cat-7-text", "#5a4a00") 259 .token("--jc-pill-cat-7-border", "#e3d99e") 260 .token("--jc-pill-cat-8-bg", "#e1e4f7") 261 .token("--jc-pill-cat-8-text", "#2f3a8a") 262 .token("--jc-pill-cat-8-border", "#c3c9ee") 263 .token("--jc-pill-cat-9-bg", "#fbdcec") 264 .token("--jc-pill-cat-9-text", "#7d1d52") 265 .token("--jc-pill-cat-9-border", "#f2bcd8") 266 .token("--jc-pill-cat-10-bg", "#e4e6e8") 267 .token("--jc-pill-cat-10-text", "#33383d") 268 .token("--jc-pill-cat-10-border", "#c9cdd1") 269 // Legacy status/tag palette - RETAINED as var(--jc-pill-*) aliases (never renamed away): the .jc-badge / 270 // .jc-avatar-status-* chrome here AND the frozen widgets calendar palette (juneau-calendar.css, out of v1) 271 // still consume --jc-tag-*, so aliasing keeps one source of truth without a cross-module rename. build() 272 // resolves each reference to the pill literal, so getTokens()/the served :root still carry a 6-hex value. 273 .token("--jc-tag-green-bg", "var(--jc-pill-green-bg)") 274 .token("--jc-tag-green-text", "var(--jc-pill-green-text)") 275 .token("--jc-tag-green-border", "var(--jc-pill-green-border)") 276 .token("--jc-tag-blue-bg", "var(--jc-pill-blue-bg)") 277 .token("--jc-tag-blue-text", "var(--jc-pill-blue-text)") 278 .token("--jc-tag-blue-border", "var(--jc-pill-blue-border)") 279 .token("--jc-tag-amber-bg", "var(--jc-pill-amber-bg)") 280 .token("--jc-tag-amber-text", "var(--jc-pill-amber-text)") 281 .token("--jc-tag-amber-border", "var(--jc-pill-amber-border)") 282 .token("--jc-tag-neutral-bg", "var(--jc-pill-neutral-bg)") 283 .token("--jc-tag-neutral-text", "var(--jc-pill-neutral-text)") 284 .token("--jc-tag-neutral-border", "var(--jc-pill-neutral-border)") 285 .token("--jc-tag-red-bg", "var(--jc-pill-red-bg)") 286 .token("--jc-tag-red-text", "var(--jc-pill-red-text)") 287 .token("--jc-tag-red-border", "var(--jc-pill-red-border)") 288 // Probe palette (client-side status probes). A separate family from the pill/tag triads: probes SHOW a status 289 // dot and carry their own light status wash + ink, keyed to the four probe statuses success/error/warning/neutral. Each 290 // status sets a background wash, a text (ink) colour, and the dot fill. The selected-state ring reuses the 291 // existing --jc-accent-selected token (no new ring token). Values are the measured status palette, independent 292 // of both the pill palette and the theme accent (neutral is a neutral grey, not the accent). 293 .token("--jc-probe-success-bg", "#d1fae5") 294 .token("--jc-probe-success-text", "#065f46") 295 .token("--jc-probe-success-dot", "#10b981") 296 .token("--jc-probe-error-bg", "#fee2e2") 297 .token("--jc-probe-error-text", "#991b1b") 298 .token("--jc-probe-error-dot", "#dc2626") 299 .token("--jc-probe-warning-bg", "#fef3c7") 300 .token("--jc-probe-warning-text", "#92400e") 301 .token("--jc-probe-warning-dot", "#f59e0b") 302 .token("--jc-probe-neutral-bg", "#e5e7eb") 303 .token("--jc-probe-neutral-text", "#374151") 304 .token("--jc-probe-neutral-dot", "#6b7280") 305 // --jc-font must stay first and each tag triad contiguous; see Theme_TokenOrdering_Test. 306 .token("--jc-header-height", "56px") // (a) keeps .jc-header height and .jc-nav sticky offset in sync 307 .token("--jc-nav-indicator-width", "3px") // (g) .jc-nav floor, .jc-nav-tab top bar, HTML-slot page-nav floor + selected-section top 308 .token("--jc-page-nav-hairline", "2px") // line between page-nav sections row and children row 309 .token("--jc-page-nav-section-font-size", "13px") // Page Tabs (top row) type; independent of children 310 .token("--jc-page-nav-child-font-size", "12px") // page-nav children (second row) type; independent of sections 311 .token("--jc-nav-tab-padding-block", "8px") // Page Tab (and HTML-slot section) vertical padding; with line-height and the indicator border sets tab height 312 .token("--jc-nav-tab-padding-inline", "10px") // Page Tab horizontal padding 313 .token("--jc-nav-tab-line-height", "1.5") // Page Tab / Page Subtab line box (unitless multiple of the font size) 314 .token("--jc-page-nav-child-padding-block", "6px") // Page Subtab vertical padding; less than the tab's 8px so the strip stays subordinate 315 .token("--jc-page-nav-child-padding-inline", "10px") // Page Subtab horizontal padding 316 .token("--jc-card-shadow", "0 2px 2px rgba(0, 0, 0, 0.05)") // (c) content-card / title-card elevation; table-chrome clears it 317 .token("--jc-danger-wash", "#fdeceb") // (d) themeable .jc-btn-danger:hover fill (was a hardcoded hex) 318 .token("--jc-danger-strong", "#a12f2b") // .jc-btn-destructive:hover fill: darker than --jc-danger (7.1:1 under white ink); invariant in dark like --jc-danger 319 .token("--jc-success-wash", "#eaf6ee") // (d) themeable .jc-btn-success:hover fill (was a hardcoded hex) 320 .token("--jc-space-1", "4px") // (e) spacing scale seam (consumed by the .jc-prose rhythm) 321 .token("--jc-space-2", "8px") 322 .token("--jc-space-3", "12px") 323 .token("--jc-space-4", "16px") 324 .token("--jc-space-5", "24px") 325 .token("--jc-space-6", "32px") 326 // Accessibility: a themeable focus-ring colour so the generic :focus-visible rule in chrome.css 327 // gives every interactive control a WCAG 2.4.7-compliant keyboard-focus indicator by default. A darker 328 // shade of the blue accent, so the ring still reads as the accent colour but clears 3:1 on the page 329 // gradient's lightest-blue top stop, not only on white. 330 .token("--jc-focus", "#116ab9") 331 // Accessibility: the ribbon-format selected-state face (WCAG 1.4.11 non-text 3:1 remedy). A new, OPAQUE 332 // token rather than a re-valued --jc-accent-wash: the wash has 13 hover/table-wash consumers in chrome.css 333 // that must stay untouched, so the selected face is confined to this independent token instead. 334 // Same literal as --jc-accent at this theme's baseline (the shipped colour choice does not change, only 335 // the mechanism, wash to opaque) - but tracked separately: a consumer overriding --jc-accent will NOT move 336 // this token; it must be overridden on its own. A permanent widening of the theming surface. 337 .token("--jc-accent-selected", "#1589EE") 338 .token("--jc-table-stripe-bg", "#f3f3f3") 339 .token("--jc-main-bg", "#f5f6f9") // inner-main well; not a retarget of old card tints 340 .token("--jc-card-padding", "16px 16px 8px") // content-card / title-card inset; --jc-space-4 / --jc-space-4 / --jc-space-2 341 .token("--jc-chrome-icon", "#666666") // idle ribbon / paging glyph; not --jc-text-soft (body ink) 342 // Chart tokens, read by juneau-charts.js when it registers the ECharts theme (series palette, then roles). 343 .token("--jc-chart-1", "#1b6ac9") 344 .token("--jc-chart-2", "#e07a1f") 345 .token("--jc-chart-3", "#2e8540") 346 .token("--jc-chart-4", "#9b3fb5") 347 .token("--jc-chart-5", "#c23934") 348 .token("--jc-chart-6", "#0e8a8a") 349 .token("--jc-chart-7", "#7a6a00") 350 .token("--jc-chart-8", "#5a5a5a") 351 .token("--jc-chart-bg", "transparent") 352 .token("--jc-chart-text", "#080707") 353 .token("--jc-chart-axis", "#dddbda") 354 .token("--jc-chart-grid", "#ececec") 355 .token("--jc-chart-tooltip-bg", "#ffffff") 356 .token("--jc-chart-tooltip-text", "#080707") 357 .token("--jc-chart-mark", "#5a5a5a") 358 .token("--jc-chart-band", "rgba(0, 0, 0, 0.06)") 359 .token("--jc-chart-heat-low", "#e8f1fb") 360 .token("--jc-chart-heat-high", "#1b6ac9") 361 // Dark accents: lighter blues than the light palette, legible on the shared dark neutral layer. 362 .dark("--jc-link", "#6cb4ff") 363 .dark("--jc-focus", "#4aa3ff") 364 .dark("--jc-accent-selected", "#4aa3ff") 365 .dark("--jc-accent-wash", "rgba(21,137,238,0.22)") 366 .dark("--jc-tab-selected-bg", "#213d58") 367 .build(); 368 369 /** 370 * A warm, light-brown ("parchment") retint of {@link #OPEN}'s structure. 371 * 372 * <p> 373 * Recolors the chrome, accent, links, text, borders, and primary button to a warm brown palette, while keeping 374 * every one of {@link #OPEN}'s semantic status/tag tokens (info blue, success green, error red, warning amber, 375 * neutral gray) verbatim — a brown "error" pill would stop reading as an error, so the status palette is 376 * deliberately untouched. Authored as seeded from {@link #OPEN}, overriding 377 * only the 15 browned tokens below; the other 40 — including all five tag triads and every structural 378 * token — are inherited from {@link #OPEN} unchanged, so this theme's token <i>key</i> set is provably 379 * identical to {@link #OPEN}'s. 380 * 381 * <p> 382 * Caveat: like {@link #OPEN}'s own {@code --jc-accent}, this theme's {@code --jc-accent} (<c>#a9772f</c>) clears 383 * WCAG AA only for non-text/large-surface use (its {@code --jc-focus}/{@code --jc-accent-selected} consumers); a 384 * consumer repurposing it as small body text should use {@code --jc-link} (<c>#754d16</c>) instead, which 385 * passes AA normal-text contrast. 386 */ 387 public static final Theme LIGHT_BROWN = deriveFrom("light-brown", OPEN).resetDark() 388 .token("--jc-page-bg", "linear-gradient(180deg, #dccaa6 0%, #e8dcc4 22%, #f2ebdc 55%, #faf6ee 100%)") 389 .token("--jc-accent", "#a9772f") 390 .token("--jc-accent-wash", "rgba(169,119,47,0.1)") 391 .token("--jc-tab-selected-bg", "#f6f1ea") 392 .token("--jc-link", "#754d16") 393 .token("--jc-text", "#2e2415") 394 .token("--jc-text-soft", "#2e2415cc") 395 .token("--jc-text-muted", "#7a6a4f") 396 .token("--jc-border", "#d8cbb0") 397 .token("--jc-border-2", "#977f4e") 398 .token("--jc-chrome-bg", "#efe6d4") 399 .token("--jc-btn-primary", "#8a6d3b") 400 .token("--jc-btn-primary-hover", "#74592f") 401 .token("--jc-avatar-bg", "linear-gradient(135deg, #a9772f, #8a6d3b)") 402 .token("--jc-focus", "#926729") 403 .token("--jc-accent-selected", "#a9772f") 404 // Dark accents: a lighter link, a lighter accent (so the selected/hover edge clears 3:1 on its wash) and the lighter focus ring. 405 .dark("--jc-link", "#d9a65c") 406 .dark("--jc-accent", "#b17d31") 407 .dark("--jc-focus", "#a9772f") 408 .dark("--jc-accent-wash", "rgba(169,119,47,0.25)") 409 .dark("--jc-tab-selected-bg", "#453b2e") 410 .build(); 411 412 /** 413 * A light-chrome red retint of {@link #OPEN}'s structure — the sibling of {@link #LIGHT_BROWN}. 414 * 415 * <p> 416 * Recolors the chrome, accent, links, text, borders, and primary button to a wine/rose palette, while keeping 417 * every one of {@link #OPEN}'s semantic status/tag tokens (info blue, success green, error red, warning amber, 418 * neutral gray) verbatim — a red "error" pill that matched the brand would stop reading as an error, so 419 * the status palette is deliberately untouched. Seeded from {@link #OPEN}, overriding only the 15 recolored 420 * tokens below; the other 40 — including all five tag triads and every structural token — are 421 * inherited from {@link #OPEN} unchanged, so this theme's token <i>key</i> set is 422 * provably identical to {@link #OPEN}'s. 423 * 424 * <p> 425 * Like {@link #RED}, this theme keeps a <b>light</b> {@code --jc-chrome-bg} (a rose tint, not a saturated red) for the 426 * page-chrome fallback, hover fill, and dialog chrome. Header and page-nav rows stay white via 427 * {@code --jc-header-bg} → {@code --jc-white}; red is reserved for accent, links, focus, and the primary 428 * button. 429 * 430 * <p> 431 * Caveat: {@link #RED}'s {@code --jc-btn-primary} sits close in hue to {@link #OPEN}'s unchanged semantic 432 * {@code --jc-danger} (<c>#c23934</c>). This theme avoids that collision by using a darker wine primary 433 * (<c>#6B1D2A</c>) rather than danger red or the mockup placeholder <c>#a31f34</c>; {@code --jc-danger} itself 434 * is deliberately left untouched. A consumer still should not reuse {@code --jc-danger} as brand. 435 */ 436 public static final Theme LIGHT_RED = deriveFrom("light-red", OPEN).resetDark() 437 .token("--jc-page-bg", "linear-gradient(180deg, #e8cfd3 0%, #f0dfe3 22%, #f6eef0 55%, #faf7f8 100%)") 438 .token("--jc-accent", "#B42348") 439 .token("--jc-accent-wash", "rgba(180,35,72,0.1)") 440 .token("--jc-tab-selected-bg", "#f8e9ed") 441 .token("--jc-link", "#8B1538") 442 .token("--jc-text", "#2a181c") 443 .token("--jc-text-soft", "#2a181ccc") 444 .token("--jc-text-muted", "#6e585c") 445 .token("--jc-border", "#e4d4d7") 446 .token("--jc-border-2", "#a37c85") 447 .token("--jc-chrome-bg", "#f3ecee") 448 .token("--jc-btn-primary", "#6B1D2A") 449 .token("--jc-btn-primary-hover", "#541620") 450 .token("--jc-avatar-bg", "linear-gradient(135deg, #B42348, #6B1D2A)") 451 .token("--jc-focus", "#B42348") 452 .token("--jc-accent-selected", "#B42348") 453 // Dark accents: lighter rose so the link and accent stay legible on a dark surface. 454 .dark("--jc-link", "#f78fab") 455 .dark("--jc-accent", "#e0557a") 456 .dark("--jc-focus", "#e0557a") 457 .dark("--jc-accent-selected", "#e0557a") 458 .dark("--jc-accent-wash", "rgba(224,85,122,0.22)") 459 .dark("--jc-tab-selected-bg", "#4d313f") 460 .build(); 461 462 /** 463 * A Jira-inspired red retint of {@link #OPEN}'s structure. 464 * 465 * <p> 466 * "Jira-inspired" describes the structural feel — white content, a white header and page-nav with a 467 * distinctly-colored accent floor, subtle neutral borders, a restrained accent — rendered in a red key 468 * color (Jira's own brand is blue); no 469 * Atlassian trademark appears in this theme's name or token values. Recolors the chrome, accent, links, brand, 470 * text, and borders, while keeping every one of {@link #OPEN}'s semantic status/tag tokens (info blue, success 471 * green, error red, warning amber, neutral gray) verbatim, so status pills stay unambiguous. Authored as 472 * seeded from {@link #OPEN}, overriding only the 16 recolored tokens below; 473 * the other 35 — including all five tag triads and every structural token — are inherited from 474 * {@link #OPEN} unchanged, so this theme's token <i>key</i> set is provably identical to {@link #OPEN}'s. 475 * 476 * <p> 477 * Caveat: {@code --jc-btn-primary} (<c>#BF2600</c>) sits close in hue to {@link #OPEN}'s unchanged semantic 478 * {@code --jc-danger} (<c>#c23934</c>); a primary button and a danger button rendered side by side rely on 479 * shape/label conventions (solid brand vs. danger-wash hover), not color alone, to stay distinguishable — 480 * {@code --jc-danger} itself is deliberately left untouched. 481 */ 482 public static final Theme RED = deriveFrom("red", OPEN).resetDark() 483 .token("--jc-page-bg", "linear-gradient(180deg, #f4f5f7 0%, #fafbfc 55%, #ffffff 100%)") 484 .token("--jc-accent", "#ff481f") // darker than the brand #FF5630 so the selected/hover edge clears 3:1 on its wash 485 .token("--jc-accent-wash", "rgba(255,86,48,0.1)") 486 .token("--jc-tab-selected-bg", "#ffeeea") 487 .token("--jc-link", "#BF2600") 488 .token("--jc-text", "#172B4D") 489 .token("--jc-text-soft", "#172B4Dcc") 490 .token("--jc-text-muted", "#5E6C84") 491 .token("--jc-border", "#DFE1E6") 492 .token("--jc-border-2", "#727f94") 493 // Chrome-scale token consumed by --jc-hover-bg and dialog chrome. Header / page-nav rows stay white 494 // (--jc-header-bg → --jc-white); table headers stay white (--jc-table-header-bg → --jc-white). 495 .token("--jc-chrome-bg", "#ffd9cf") 496 .token("--jc-btn-primary", "#BF2600") 497 .token("--jc-btn-primary-hover", "#a01f00") 498 .token("--jc-avatar-bg", "linear-gradient(135deg, #FF5630, #BF2600)") 499 .token("--jc-radius", "0.1875rem") 500 .token("--jc-focus", "#ff481f") 501 .token("--jc-accent-selected", "#FF5630") 502 // Dark accents: a lighter link and a tint of the chrome red; the accent itself reads on dark unchanged. 503 .dark("--jc-link", "#ff8a70") 504 .dark("--jc-chrome-bg", "#7a1a05") 505 .dark("--jc-accent-wash", "rgba(255,86,48,0.22)") 506 .dark("--jc-tab-selected-bg", "#54312e") 507 .build(); 508 509 /** 510 * A neutral, general-purpose light-gray retint of {@link #OPEN}'s structure — the ASF Jira-inspired 511 * "clean neutral" member of the stock-theme set. 512 * 513 * <p> 514 * Neutralizes the chrome, page background, text, and borders to a coherent grayscale ramp, while keeping 515 * every one of {@link #OPEN}'s semantic status/tag tokens (info blue, success green, danger red, warning 516 * amber, neutral gray) <b>and</b> {@link #OPEN}'s blue interactive affordances (accent, link, primary button, 517 * focus ring, avatar gradient) verbatim — a pure-grayscale accent would make links/buttons stop reading 518 * as clickable, so the restrained blue affordance set is deliberately left untouched (this is the 519 * "7 grayed / 48 kept" derivation; see the design item for the vetoed all-monochrome alternative). Authored 520 * as seeded from {@link #OPEN}, overriding only the 7 grayed tokens below; 521 * the other 48 — including all five tag triads, every structural token, and the blue affordance set 522 * — are inherited from {@link #OPEN} unchanged, so this theme's token <i>key</i> set is provably 523 * identical to {@link #OPEN}'s. 524 * 525 * <p> 526 * Caveat: like {@link #OPEN}'s own {@code --jc-accent}, this theme's (unchanged, kept-from-OPEN) 527 * {@code --jc-accent} clears WCAG AA only for non-text/large-surface use; a consumer repurposing it as small 528 * body text should use {@code --jc-link} instead, which passes AA normal-text contrast. 529 */ 530 public static final Theme GRAY = deriveFrom("gray", OPEN) 531 .token("--jc-page-bg", "linear-gradient(180deg, #e8e8e8 0%, #f0f0f0 55%, #ffffff 100%)") 532 .token("--jc-text", "#262626") 533 .token("--jc-text-soft", "#262626cc") 534 .token("--jc-text-muted", "#737373") 535 .token("--jc-border", "#e0e0e0") 536 .token("--jc-border-2", "#8a8a8a") 537 .token("--jc-chrome-bg", "#f4f4f4") 538 .build(); 539 540 private final String name; 541 private final Map<String,String> tokens; 542 private final Map<String,String> aliases; 543 private final Map<String,String> darkTokens; 544 545 private Theme(String name, Map<String,String> tokens, Map<String,String> aliases, Map<String,String> darkTokens) { 546 this.name = name; 547 // Insertion-ordered rather than Map.copyOf: ConsoleChromeMixin emits this map's iteration order directly as 548 // the served stylesheet's :root{} declarations, and Map.copyOf's order is perturbed by a per-JVM salt - which 549 // would make the response body differ between two processes serving an identical token set. cp(Map) is 550 // contractually a LinkedHashMap copy, so it preserves that order; do not swap it for an unordered copy. 551 this.tokens = u(cp(tokens)); 552 this.aliases = u(cp(aliases)); 553 this.darkTokens = u(cp(darkTokens)); 554 } 555 556 /** 557 * Starts building a new named theme. 558 * 559 * @param name The theme name. Must not be <jk>null</jk> and must match {@code ^[a-z][a-z0-9-]*$}. 560 * @return A new builder. 561 * @throws IllegalArgumentException If the name is <jk>null</jk>, empty, or not in the legal shape (e.g. contains 562 * uppercase, whitespace, or a path-traversal-shaped segment like {@code "../evil"} — gated here, not 563 * just at classpath-asset-resolution time, so a later fast-follow that interpolates the name into an asset 564 * path doesn't need to re-gate). 565 */ 566 public static Builder create(String name) { 567 if (name == null || ! name.matches(NAME_PATTERN)) 568 throw iaex("Invalid theme name: '%s'. Must match %s.", name, NAME_PATTERN); 569 return new Builder(name); 570 } 571 572 /** 573 * Seeds a builder with every token of {@code seed} under a new name. Used to author the stock palettes 574 * ({@link #LIGHT_RED}, {@link #LIGHT_BROWN}, {@link #RED}, {@link #GRAY}) from {@link #OPEN} without restating 575 * the whole map. 576 * 577 * <p> 578 * The seed's dark tokens are copied too. A derived theme that declares its own accents should call 579 * {@code resetDark()} first, or it inherits the seed's dark accents. 580 */ 581 private static Builder deriveFrom(String name, Theme seed) { 582 if (seed == null) 583 throw iaex("Invalid theme seed: null."); 584 var b = create(name); 585 for (var e : seed.getTokens().entrySet()) 586 b.token(e.getKey(), e.getValue()); 587 for (var e : seed.getDarkTokens().entrySet()) 588 b.dark(e.getKey(), e.getValue()); 589 return b; 590 } 591 592 /** 593 * Returns this theme's name. 594 * 595 * @return This theme's name. 596 */ 597 public String getName() { return name; } 598 599 /** 600 * Returns this theme's token overrides. 601 * 602 * @return 603 * An immutable map of token name (e.g. {@code "--jc-accent"}) to CSS value, iterating in the order the tokens 604 * were declared on the builder. Never <jk>null</jk>. 605 */ 606 public Map<String,String> getTokens() { return tokens; } 607 608 /** 609 * Returns this theme's dark accent tokens: name to a literal CSS value, applied on top of the shared dark neutral 610 * layer when the page is in the dark scheme. 611 * 612 * <p> 613 * Every value is a literal. A {@code var()} is rejected at {@link Builder#dark(String, String)}, because it could 614 * only resolve against the light palette. 615 * 616 * @return An immutable, insertion-ordered map of token name to CSS value. Never <jk>null</jk>. 617 */ 618 public Map<String,String> getDarkTokens() { return darkTokens; } 619 620 /** 621 * Returns this theme's alias tokens: name to a live {@code var(--jc-*)} reference. 622 * 623 * <p> 624 * Unlike a {@link #getTokens() leaf}, an alias is never resolved at build time. It reaches the browser verbatim, 625 * so it follows its target through the cascade, including any later override of the target. The map is 626 * insertion-ordered (the order {@link Builder#alias(String, String)} was called in), which keeps the emitted 627 * block byte-stable, and it is unmodifiable. It is empty for every stock theme. 628 * 629 * <p> 630 * This is a {@code Map}, not a rendered {@code String}, on purpose: the leaf half and the alias half of an 631 * override block are escaped differently (see {@link ConsoleChromeMixin#overrideBlock(Theme)}), so the 632 * emitter needs the two halves apart. Do not simplify this into a rendered string. 633 * 634 * @return The alias tokens. Never <jk>null</jk>. 635 */ 636 public Map<String,String> getAliases() { 637 return aliases; 638 } 639 640 /** 641 * The single shared, fail-closed guard rejecting a declaration of a reserved chrome-scale token name, invoked on 642 * <b>every</b> path by which a token declaration can reach the served stylesheet. 643 * 644 * <p> 645 * <b>What it protects.</b> {@code juneau-views.css} declares one shared control-scale ladder 646 * ({@code --jc-chrome-control-height}, {@code --jc-chrome-font-size-1}, {@code --jc-chrome-glyph-size}, ...) at 647 * {@code :root}, and a contract test in that module pins it as declared exactly once so that every surface 648 * shares one ladder. A token block emitted here sits at {@code html:root}, which out-specifies that 649 * {@code :root} — so a consumer redeclaring a ladder step would win, render perfectly, and turn that 650 * contract into decoration with no test failing anywhere. Documentation is not a mitigation for that, so the 651 * rejection lives here. 652 * 653 * <p> 654 * <b>Where it fires.</b> 655 * <ul class='spaced-list'> 656 * <li>{@link Builder#token(String, String)} and {@link Builder#alias(String, String)}, at declaration — 657 * the only way a name enters a theme. 658 * <li>{@code ConsoleChromeMixin.overrideBlock(Theme)}, at emission — defense in depth; unreachable for a 659 * theme built by this class. 660 * </ul> 661 * 662 * <p> 663 * <b>It fires on the declared name only, never on a target.</b> Aliasing a stock-theme token <i>to</i> a ladder step 664 * is legal and useful; <i>declaring</i> a ladder step is not. 665 * 666 * <p> 667 * <b>The {@link Theme#OPEN} exemption.</b> The reserved namespace is {@code --jc-chrome-*} <i>except</i> the 668 * names {@link Theme#OPEN} itself already declares. Two names are exempt today: 669 * {@code --jc-chrome-bg} (page-chrome grey that predates the ladder) and {@code --jc-chrome-icon} (idle 670 * ribbon / paging glyph ink). Both are consumed by {@code chrome.css} and are legitimately overridable. 671 * Without the exemption this guard would reject {@link Theme#OPEN}'s own token 672 * set — and therefore every stock palette seeded from {@link Theme#OPEN}, which is the normal way 673 * to author a palette. The exemption is expressed against 674 * {@link Theme#OPEN} rather than as a hardcoded name list so it cannot drift: it needs no copy of the ladder's 675 * names (which live in a module this one deliberately cannot see), it stays correct if a chrome-named leaf is 676 * ever added to or removed from {@link Theme#OPEN}, and it fails <i>closed</i> for every new name — no 677 * ladder step is a {@link Theme#OPEN} token, and adding one could only ever happen through a reviewed edit to 678 * {@link Theme#OPEN} that its own pinned token count would surface. 679 * 680 * <p> 681 * A prefix test rather than an anchored {@code matches(...)}: by the time a name reaches here it has already 682 * passed a full-string {@code ^--jc-[a-z0-9-]+$} shape guard, so its alphabet is closed and 683 * {@link String#startsWith(String)} is total — there is no string that passes the shape guard, begins with 684 * the reserved prefix, and escapes this check. 685 * 686 * <p>While {@link #OPEN} itself is being built, {@code OPEN} is still {@code null} and the guard is skipped: the 687 * stock palette is the source of the exemption list, not subject to it. 688 * 689 * @param name The declared token name. Already shape-validated by the caller. 690 * @param source A short description of the channel the declaration arrived through, for the failure message. 691 * @throws IllegalArgumentException If {@code name} is a reserved chrome-scale token name. 692 */ 693 static void rejectReservedChromeDeclaration(String name, String source) { 694 if (OPEN == null) 695 return; 696 if (name.startsWith(CHROME_TOKEN_PREFIX) && ! OPEN.getTokens().containsKey(name)) 697 throw iaex("Cannot declare reserved token '%s' (%s). The '%s' namespace is the shared control-scale ladder declared by juneau-views.css; a token block served here out-specifies it. Referencing one of these tokens is legal - declaring one is not.", 698 name, source, CHROME_TOKEN_PREFIX); 699 } 700 701 /** 702 * Builder for {@link Theme}. 703 */ 704 public static final class Builder { 705 private final String name; 706 private final Map<String,String> tokens = new LinkedHashMap<>(); 707 private final Map<String,String> aliases = new LinkedHashMap<>(); 708 private final Map<String,String> darkTokens = new LinkedHashMap<>(); 709 710 private Builder(String name) { this.name = name; } 711 712 /** 713 * Adds (or overrides) a single CSS custom-property token. 714 * 715 * <p> 716 * The value may be either a <b>literal</b> or a {@code var(--jc-name)} <b>reference</b> to another known 717 * token: 718 * <ul class='spaced-list'> 719 * <li>A literal is validated eagerly here by {@code CssValueGrammar}'s accept-known-safe allowlist grammar 720 * after normalization (trim → reject C0/C1/DEL → strip comments → reject {@code url(} in 721 * any spelling → grammar). 722 * <li>A value that, after that same normalization belt, matches {@code var(--jc-name)} is recognized as a 723 * reference and stored <i>unresolved</i> — it is resolved to a concrete literal at {@link #build()} 724 * time (its target may not be defined yet, e.g. a forward reference). {@code var()} is never a 725 * {@code CssValueGrammar} value shape; it is Theme-layer syntax recognized one layer above the grammar. 726 * </ul> 727 * Escaping happens later, at emission time, via {@code CssValueEscaper} (see {@code ConsoleChromeMixin}). 728 * 729 * <p>A declared name in the reserved {@code --jc-chrome-*} namespace that {@link Theme#OPEN} does not already 730 * declare is rejected. 731 * 732 * @param name The token name. Must not be <jk>null</jk> and must match {@code ^--jc-[a-z0-9-]+$}. 733 * @param value 734 * The CSS value — a literal, or a {@code var(--jc-name)} reference. 735 * @return This object. 736 * @throws IllegalArgumentException 737 * If the name is not in the legal shape (full-string {@code String.matches(...)}, not {@code find(...)} 738 * — {@code "--jc-foo;--bar"} must REJECT even though {@code "--jc-foo"} matches as a leading 739 * substring), if the value contains a control character or a {@code url(} production, or if the value is 740 * neither a {@code var(--jc-name)} reference nor one of the allowlisted CSS value shapes. A reference whose 741 * target is unknown, cyclic, or too deeply chained is instead reported at {@link #build()} time. 742 */ 743 public Builder token(String name, String value) { 744 if (name == null || ! name.matches(TOKEN_NAME_PATTERN)) 745 throw iaex("Invalid theme token name: '%s'. Must match %s.", name, TOKEN_NAME_PATTERN); 746 rejectReservedChromeDeclaration(name, "theme '" + this.name + "' leaf token"); 747 // Recognition runs on the SAME post-belt string the grammar would see (one shared belt, no second 748 // comment-stripping pass). A reference is stored unresolved; a literal is validated eagerly, exactly 749 // as before this feature existed. 750 var normalized = CssValueGrammar.normalize(value); 751 if (referencedName(normalized) != null) 752 tokens.put(name, normalized); 753 else 754 tokens.put(name, CssValueGrammar.normalizeAndValidate(value)); 755 return this; 756 } 757 758 /** 759 * Adds (or overrides) a dark accent token: a literal applied on top of the shared dark neutral layer when the 760 * page is in the dark scheme. 761 * 762 * <p> 763 * The name and value go through the same guards as {@link #token(String, String)}, with one difference: the 764 * value must be a <b>literal</b>. A {@code var()} reference is rejected, because the only thing it could 765 * resolve against is the light palette, which would bake the wrong value into the dark scheme. 766 * 767 * @param name The token name. Must match {@code ^--jc-[a-z0-9-]+$}. 768 * @param value The CSS literal. 769 * @return This object. 770 * @throws IllegalArgumentException 771 * If the name is malformed or in the reserved {@code --jc-chrome-*} namespace without being a {@link Theme#OPEN} 772 * token, or if the value is a {@code var()} reference or is not one of the allowlisted CSS value shapes. 773 */ 774 public Builder dark(String name, String value) { 775 if (name == null || ! name.matches(TOKEN_NAME_PATTERN)) 776 throw iaex("Invalid theme dark token name: '%s'. Must match %s.", name, TOKEN_NAME_PATTERN); 777 rejectReservedChromeDeclaration(name, "theme '" + this.name + "' dark token"); 778 // Literal only: CssValueGrammar has no var() shape, so a reference fails here rather than being resolved. 779 darkTokens.put(name, CssValueGrammar.normalizeAndValidate(value)); 780 return this; 781 } 782 783 /** Drops every dark accent, for a derived theme that declares its own set instead of inheriting its seed's. */ 784 private Builder resetDark() { 785 darkTokens.clear(); 786 return this; 787 } 788 789 /** 790 * Declares an alias token: a name whose value is a live reference to another {@code --jc-*} token. 791 * 792 * <p> 793 * The target must be exactly one {@code var(--jc-name)} reference, with no fallback, no surrounding value 794 * and no second reference. It is stored after the shared normalization belt (trim and comment strip, with 795 * control characters rejected on the raw value) and emitted verbatim. Nothing dangerous is representable in 796 * that shape, so an alias needs no escaper. A literal belongs in {@link #token(String, String)}. A 797 * {@code var()} given to {@code token()} is resolved to its literal at build time; one given here is not. 798 * 799 * <p> 800 * A name may be declared by only one channel: {@link #build()} rejects a name given to both 801 * {@code token()} and {@code alias()}, in either order. 802 * 803 * <h4 class='section'>Example:</h4> 804 * <p class='bjava'> 805 * <jc>// Follows --jc-card-bg live, including any later override of it.</jc> 806 * <jv>builder</jv>.alias(<js>"--jc-tab-bar-bg"</js>, <js>"var(--jc-card-bg)"</js>); 807 * 808 * <jc>// Rejected: a literal belongs in token(), not alias().</jc> 809 * <jv>builder</jv>.alias(<js>"--jc-tab-bar-bg"</js>, <js>"#fff"</js>); 810 * </p> 811 * 812 * <p>A declared name in the reserved {@code --jc-chrome-*} namespace that {@link Theme#OPEN} does not already 813 * declare is rejected. 814 * 815 * @param name The alias name. Must match {@code ^--jc-[a-z0-9-]+$}. 816 * @param target The reference. Must be a single {@code var(--jc-name)}. 817 * @return This object. 818 * @throws IllegalArgumentException If the name or the target is malformed. 819 */ 820 public Builder alias(String name, String target) { 821 if (name == null || ! name.matches(TOKEN_NAME_PATTERN)) 822 throw iaex("Invalid theme alias name: '%s'. Must match %s.", name, TOKEN_NAME_PATTERN); 823 rejectReservedChromeDeclaration(name, "theme '" + this.name + "' alias"); 824 if (target == null) 825 throw iaex("Invalid theme alias target for '%s': null.", name); 826 var normalized = CssValueGrammar.normalize(target); 827 if (! VAR_REFERENCE.matcher(normalized).matches()) 828 throw iaex("Invalid theme alias target for '%s': '%s'. Must be a var(--jc-name) reference.", name, target); 829 aliases.put(name, normalized); 830 return this; 831 } 832 833 /** 834 * Builds the immutable {@link Theme}, resolving every {@code var(--jc-name)} reference to a concrete literal. 835 * 836 * <p> 837 * Resolution scope is this builder's own tokens, shadowing {@link Theme#OPEN}'s tokens (exact shadowing: a 838 * name defined on this builder wins outright, even if resolving that entry then fails — there is no 839 * silent fall-through to {@code Theme.OPEN}'s value for a shadowed name). Resolution runs on a copy of the 840 * token map, so a failed {@code build()} leaves this builder unchanged and retryable. 841 * 842 * <p>Rejects a name declared by both {@link #token(String, String)} and {@link #alias(String, String)}. 843 * 844 * @return A new {@link Theme} whose every token value is a resolved six-shape literal (the substring 845 * {@code var(} appears in none of them). 846 * @throws IllegalArgumentException 847 * If a reference names an unknown token, forms a cycle (the message carries the cycle path), or exceeds the 848 * resolution depth cap. 849 */ 850 public Theme build() { 851 var resolved = resolveReferences(); 852 for (var n : aliases.keySet()) 853 if (tokens.containsKey(n)) 854 throw iaex("Theme '%s' declares '%s' as both a leaf token and an alias. A name may be declared by only one channel.", name, n); 855 return new Theme(name, resolved, aliases, darkTokens); 856 } 857 858 /** Resolves every reference in a copy of the token map, preserving declaration order; never mutates {@link #tokens}. */ 859 private Map<String,String> resolveReferences() { 860 var resolved = new LinkedHashMap<String,String>(); 861 for (var e : tokens.entrySet()) { 862 var target = referencedName(e.getValue()); 863 resolved.put(e.getKey(), target == null ? e.getValue() : resolveReference(e.getKey(), target)); 864 } 865 return resolved; 866 } 867 868 /** 869 * Iteratively walks a reference chain from {@code firstTarget} to the literal it names, with exact shadowing 870 * (own tokens win over {@link Theme#OPEN}'s), cycle detection, and an independent hop cap; re-validates the 871 * resolved literal against the grammar as defense-in-depth. 872 */ 873 private String resolveReference(String definingName, String firstTarget) { 874 // Theme.OPEN is null only while Theme.OPEN itself is being built - and it has no references, so this 875 // fallback map is never actually consulted during that construction. 876 var openTokens = Theme.OPEN == null ? Collections.<String,String>emptyMap() : Theme.OPEN.getTokens(); 877 var visited = new LinkedHashSet<String>(); 878 visited.add(definingName); 879 var target = firstTarget; 880 var hops = 0; 881 while (true) { 882 if (visited.contains(target)) 883 throw iaex("Theme token '%s' contains a cyclic reference: %s.", definingName, cyclePath(visited, target)); 884 if (++hops > MAX_REFERENCE_HOPS) 885 throw iaex("Theme token '%s' exceeds the maximum reference depth of %d hops.", definingName, MAX_REFERENCE_HOPS); 886 visited.add(target); 887 888 String targetValue; 889 if (tokens.containsKey(target)) 890 targetValue = tokens.get(target); // own map wins outright (exact shadowing) 891 else if (openTokens.containsKey(target)) 892 targetValue = openTokens.get(target); 893 else 894 throw iaex("Theme token '%s' references unknown token '%s'.", definingName, target); 895 896 var next = referencedName(targetValue); 897 if (next == null) 898 // The resolved literal - and only that literal, with no var() present - is re-validated by the 899 // unchanged grammar as defense-in-depth against a bad value hiding under a referenceable name. 900 return CssValueGrammar.normalizeAndValidate(targetValue); 901 target = next; 902 } 903 } 904 905 /** Returns the {@code --jc-name} a {@code var(--jc-name)} reference points at, or <jk>null</jk> if {@code value} is not a reference. */ 906 private static String referencedName(String value) { 907 var m = VAR_REFERENCE.matcher(value); 908 return m.matches() ? m.group(1) : null; 909 } 910 911 /** Renders a cycle path like {@code --jc-a -> --jc-b -> --jc-a} for a build-failure message. */ 912 private static String cyclePath(Set<String> visited, String repeated) { 913 return String.join(" -> ", visited) + " -> " + repeated; 914 } 915 } 916}