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.freemarker; 018 019import static org.apache.juneau.commons.utils.Shorts.*; 020 021import java.io.*; 022import java.util.*; 023import java.util.function.*; 024import java.util.regex.*; 025import java.util.stream.*; 026 027import org.apache.juneau.commons.http.*; 028import org.apache.juneau.marshall.collections.*; 029import org.apache.juneau.marshall.marshaller.*; 030import org.apache.juneau.console.*; 031import org.apache.juneau.console.views.*; 032 033import freemarker.core.*; 034import freemarker.template.*; 035import freemarker.template.utility.*; 036 037/** 038 * Typed, per-render capture of one console page: theme, header, footer, nav tree, active nav, cards 039 * and slot templates, held as FreeMarker {@link Environment} custom state (see {@link #KEY}) so every 040 * directive in the render shares one instance. {@code <@console>} serializes it as the {@code #juneau-page} 041 * contract. 042 * 043 * <h2 class='section'>Example:</h2> 044 * <p class='bjava'> 045 * <jc>// Inside a custom directive that contributes a card:</jc> 046 * <jk>public void</jk> execute(Environment <jv>env</jv>, Map <jv>params</jv>, TemplateModel[] <jv>loop</jv>, 047 * TemplateDirectiveBody <jv>body</jv>) <jk>throws</jk> TemplateException, IOException { 048 * PageCapture <jv>page</jv> = PageCapture.<jsm>of</jsm>(<jv>env</jv>); 049 * <jv>page</jv>.addCard(CardSpec.<jsm>html</jsm>(<js>"intro"</js>).title(<js>"Welcome"</js>), 050 * PageCapture.<jsm>render</jsm>(<jv>body</jv>)); 051 * } 052 * 053 * <jc>// In a test, after rendering:</jc> 054 * String <jv>json</jv> = PageCapture.<jsm>get</jsm>(<jv>env</jv>).toContractJson(); 055 * </p> 056 * 057 * @since 10.0.0 058 */ 059@SuppressWarnings({ 060 "java:S1192", // Duplicated literals read more clearly inline than as constants 061 "java:S3776" // Validation and rendering chains many independent guards; splitting them adds no clarity. 062}) 063public final class PageCapture { 064 065 /** Environment custom-state key. */ 066 public static final String KEY = PageCapture.class.getName(); 067 068 /** The contract version this server writes. */ 069 public static final String CONTRACT_VERSION = "1"; 070 071 //----------------------------------------------------------------------------------------------------------------- 072 // Header / footer specs 073 //----------------------------------------------------------------------------------------------------------------- 074 075 /** 076 * Mutable header fields; mirrors {@code $defs/header}. 077 * 078 * <h2 class='section'>Example:</h2> 079 * <p class='bjava'> 080 * <jv>page</jv>.header(<jv>h</jv> -> <jv>h</jv>.title(<js>"My App"</js>).logo(<js>"/img/logo.svg"</js>, <js>"/"</js>, <js>"My App"</js>).chrome(<jk>true</jk>)); 081 * </p> 082 */ 083 public static final class HeaderSpec { 084 String title; 085 String subtitle; 086 String logoSrc; 087 String logoSymbol; 088 String logoHref; 089 String logoAlt; 090 boolean chrome; 091 final List<Map<String,Object>> links = new ArrayList<>(); 092 Map<String,Object> userMenu; 093 094 /** @param v The header title. @return This object. */ 095 public HeaderSpec title(String v) { title = v; return this; } 096 /** @param v The subtitle. @return This object. */ 097 public HeaderSpec subtitle(String v) { subtitle = v; return this; } 098 /** @param src Logo URL. @param href Link target, or <jk>null</jk>. @param alt Alt text, or <jk>null</jk>. @return This object. */ 099 public HeaderSpec logo(String src, String href, String alt) { logoSrc = src; logoHref = href; logoAlt = alt; return this; } 100 /** @param name Built-in symbol name used as the logo. @param href Link target, or <jk>null</jk>. @param alt Alt text, or <jk>null</jk>. @return This object. */ 101 public HeaderSpec logoSymbol(String name, String href, String alt) { logoSymbol = name; logoHref = href; logoAlt = alt; return this; } 102 /** @param v Whether the header and nav share the sticky {@code .jc-chrome} wrapper. @return This object. */ 103 public HeaderSpec chrome(boolean v) { chrome = v; return this; } 104 /** @param label Link label. @param href Link target. @return This object. */ 105 public HeaderSpec link(String label, String href) { links.add(link0(label, href)); return this; } 106 /** @param v A {@code $defs/userMenu} map. @return This object. */ 107 public HeaderSpec userMenu(Map<String,Object> v) { userMenu = v; return this; } 108 } 109 110 /** 111 * Mutable footer fields; mirrors {@code $defs/footer}. 112 * 113 * <h2 class='section'>Example:</h2> 114 * <p class='bjava'> 115 * <jv>page</jv>.footer(<jv>f</jv> -> <jv>f</jv>.text(<js>"Sandbox Support Console"</js>).link(<js>"Docs"</js>, <js>"/docs"</js>)); 116 * </p> 117 */ 118 public static final class FooterSpec { 119 String text; 120 final List<Map<String,Object>> links = new ArrayList<>(); 121 122 /** @param v Trusted, author-supplied HTML rendered as-is by the console shell (entities decode, markup becomes real elements); must be a literal template/config value, never request data. @return This object. */ 123 public FooterSpec text(String v) { text = v; return this; } 124 /** @param label Link label. @param href Link target. @return This object. */ 125 public FooterSpec link(String label, String href) { links.add(link0(label, href)); return this; } 126 } 127 128 private static Map<String,Object> link0(String label, String href) { 129 var m = new LinkedHashMap<String,Object>(); 130 m.put("label", label); 131 m.put("href", href); 132 return m; 133 } 134 135 //----------------------------------------------------------------------------------------------------------------- 136 // State 137 //----------------------------------------------------------------------------------------------------------------- 138 139 private String title = ""; 140 private String theme; 141 private boolean themeFromDirective; 142 private String scheme; 143 private boolean schemeToggle; 144 private boolean themeSelector; 145 private String tab = ""; 146 private String navLayout; 147 private String shellUrl; 148 private final HeaderSpec header = new HeaderSpec(); 149 private final FooterSpec footer = new FooterSpec(); 150 private final NavNode navRoot = NavNode.root(); 151 private List<String> selected; 152 private List<String> activeNav = List.of(); 153 private final List<CardSpec> cards = new ArrayList<>(); 154 private boolean allowInline; 155 private boolean emitScripts; 156 private Map<String,Object> rootModel; 157 private final Map<String,Map<String,Object>> topics = new LinkedHashMap<>(); 158 private final Map<String,String> topicWhere = new HashMap<>(); 159 private final Map<String,Map<String,Object>> bridges = new LinkedHashMap<>(); 160 /** The {@code dashboard} contract object ({@code PageSpec.dashboard}), or <jk>null</jk>. */ 161 private Map<String,Object> dashboard; 162 private final Map<String,Map<String,Object>> dataSources = new LinkedHashMap<>(); 163 private final Map<String,BadgeDef> badges = new LinkedHashMap<>(); 164 private Map<String,Object> javaFacts = Map.of(); 165 private Map<String,Object> chromeFacts = Map.of(); 166 private Map<String,Object> facts = Map.of(); 167 // Cards from a PageSpec, held until placed or the page closes. builtCards: not yet placed, in declaration order. 168 // builtCardIds: every id ever registered here, kept after placement. 169 private final Map<String,CardSpec> builtCards = new LinkedHashMap<>(); 170 private final Set<String> builtCardIds = new LinkedHashSet<>(); 171 private final Map<String,String> templates = new LinkedHashMap<>(); 172 private final Map<String,Map<String,String>> slots = new LinkedHashMap<>(); 173 private List<String> toolkits = List.of(); 174 private List<String> init = List.of(); 175 private List<String> css = List.of(); 176 private boolean assetsResolved; 177 private List<String> vendorCss = List.of(); 178 private List<String> vendorJs = List.of(); 179 private List<String> runtimeCss = List.of(); 180 private List<String> runtimeJs = List.of(); 181 private final Set<String> requiredPacks = new LinkedHashSet<>(); 182 private int segments; 183 private int mainCount; 184 private int autoCards; 185 // Stable writers: <@page>/<@console> render their bodies straight into these, so flushSegment()/markMain() 186 // reset them in place instead of swapping in new instances. 187 private final StringWriter pageBuffer = new StringWriter(); 188 private final StringWriter consoleBuffer = new StringWriter(); 189 190 // Package-private server-side slots (not in the contract). 191 String head; 192 String headBeforePageCss; 193 String scripts; 194 String scriptsAfterToolkit; 195 String bodyAttrs; 196 String ftlBodyAttrs; 197 String themeCssUrl; 198 /** The validated {@code <@console theme=>} value, or <jk>null</jk>; the seed for a nameless {@code <@theme>}. */ 199 String consoleTheme; 200 String themeOverrideBlock; 201 ThemeBuildContext themeBuild; 202 final Deque<NavNode> navCursor = new ArrayDeque<>(); 203 boolean navOpen; 204 boolean consoleOpen; 205 boolean pageOpen; 206 boolean consoleDone; 207 boolean cardOpen; 208 boolean underRootOpen; 209 boolean slotOpen; 210 String underRootParent = ""; 211 NavNode underRootSelected; 212 213 /** 214 * A nav-tree mutation deferred until the chrome's nav tree exists. Unlike a plain {@link Consumer}, it may 215 * throw {@link TemplateModelException}, which {@link NavNode#add(String, String, String)} does on a duplicate 216 * sibling id. 217 */ 218 @FunctionalInterface 219 public interface NavAdder { 220 /** 221 * @param parent The resolved ancestor node. 222 * @throws TemplateModelException If adding under {@code parent} fails. 223 */ 224 void accept(NavNode parent) throws TemplateModelException; 225 } 226 227 /** One pending nav addition: a child to add under an existing chrome node, resolved at {@code </@console>} 228 * because the chrome's own nav tree may not exist yet when the addition is recorded. */ 229 record PendingNavAdd(String parentIdPath, NavAdder adder) {} 230 231 final List<PendingNavAdd> pendingNavAdds = new ArrayList<>(); 232 233 PageCapture() {} 234 235 /** 236 * Returns the capture for this render, creating it on first use. 237 * 238 * <p> 239 * On create, a {@link PageSpec} carried in the data model under {@link PageSpec#ATTR} is applied to the new 240 * capture before any directive writes to it, and marked adopted. 241 * 242 * @param env The FreeMarker environment. 243 * @return The capture, never <jk>null</jk>. 244 * @throws TemplateModelException If seeding a {@link PageSpec} from the data model fails. 245 */ 246 public static PageCapture of(Environment env) throws TemplateModelException { 247 var c = (PageCapture)env.getCustomState(KEY); 248 if (n(c)) { 249 c = new PageCapture(); 250 var tm = env.getDataModel().get(PageSpec.ATTR); 251 if (nn(tm) && DeepUnwrap.unwrap(tm) instanceof PageSpec.Seed seed) { 252 var cardModel = env.getConfiguration().getSharedVariable(CardDirectiveModel.NAME); 253 seed.adoptInto(c, cardModel instanceof CardDirectiveModel m ? m : null); 254 } 255 env.setCustomState(KEY, c); // Only after a successful seed, so a failed one leaves nothing half-applied. 256 } 257 return c; 258 } 259 260 /** 261 * Returns the capture for this render, if one exists. 262 * 263 * @param env The FreeMarker environment. 264 * @return The capture, or <jk>null</jk>. 265 */ 266 public static PageCapture get(Environment env) { 267 return (PageCapture)env.getCustomState(KEY); 268 } 269 270 /** 271 * Renders a directive body to a string. 272 * 273 * @param body The body, or <jk>null</jk>. 274 * @return The rendered markup, or {@code ""} when the body is <jk>null</jk>. 275 * @throws TemplateException On a template error. 276 * @throws IOException On an I/O error. 277 */ 278 public static String render(TemplateDirectiveBody body) throws TemplateException, IOException { 279 if (n(body)) 280 return ""; 281 var sw = new StringWriter(); 282 body.render(sw); 283 return sw.toString(); 284 } 285 286 //----------------------------------------------------------------------------------------------------------------- 287 // Setters 288 //----------------------------------------------------------------------------------------------------------------- 289 290 /** @param v The page title. @return This object. */ 291 public PageCapture title(String v) { title = v; return this; } 292 293 /** 294 * Sets the title only when none has been set yet. A page-spec title always wins over the chrome's own 295 * {@code <@console title>} or {@code brand=} default; this is the one deliberate silent override in the merge rules. 296 * 297 * @param fallback The chrome-resolved default. A <jk>null</jk> is treated as blank. 298 * @return This object. 299 */ 300 PageCapture titleDefault(String fallback) { 301 if (title.isEmpty()) 302 title = fallback == null ? "" : fallback; 303 return this; 304 } 305 306 /** @param name A stock theme name. @return This object. */ 307 public PageCapture theme(String name) { theme = name; return this; } 308 309 /** @param name A colour-scheme pin: {@code auto}, {@code light} or {@code dark}. @return This object. */ 310 public PageCapture scheme(String name) { scheme = name; return this; } 311 312 /** @param value Whether the visitor's stored scheme choice is honoured. @return This object. */ 313 public PageCapture schemeToggle(boolean value) { schemeToggle = value; return this; } 314 315 /** @param value Whether the header offers a stock-theme selector. @return This object. */ 316 public PageCapture themeSelector(boolean value) { themeSelector = value; return this; } 317 318 /** @param v The {@code <@page tab>} value. @return This object. */ 319 public PageCapture tab(String v) { tab = n(v) ? "" : v; return this; } 320 321 /** @param names Toolkit names from {@code <@page toolkit>}. @return This object. */ 322 public PageCapture toolkit(List<String> names) { toolkits = List.copyOf(names); return this; } 323 324 /** @param c Mutates the header. @return This object. */ 325 public PageCapture header(Consumer<HeaderSpec> c) { c.accept(header); return this; } 326 327 /** @param c Mutates the footer. @return This object. */ 328 public PageCapture footer(Consumer<FooterSpec> c) { c.accept(footer); return this; } 329 330 /** @param horizontalOrVertical The nav layout. @return This object. */ 331 public PageCapture navLayout(String horizontalOrVertical) { navLayout = horizontalOrVertical; return this; } 332 333 /** @return The synthetic nav root; its children are the contract's {@code nav[]}. */ 334 public NavNode navRoot() { return navRoot; } 335 336 /** 337 * Explicitly selects a nav path ({@code <@node selected="true">}). 338 * 339 * @param idPath The root-first id path. 340 * @return This object. 341 * @throws TemplateModelException If a path is already selected (E-6). 342 */ 343 public PageCapture select(List<String> idPath) throws TemplateModelException { 344 if (nn(selected)) 345 throw FtlAttrLists.reject(f("<@node id='%s'> selected=true but '%s' is already selected.", 346 idPath.get(idPath.size() - 1), String.join("/", selected))); 347 selected = List.copyOf(idPath); 348 return this; 349 } 350 351 /** 352 * Appends a card. 353 * 354 * @param card The card. 355 * @param markupOrNull Markup emitted as {@code <template data-card="{id}">}, or <jk>null</jk>. 356 * @return This object. 357 * @throws TemplateModelException On a duplicate card id (E-9). 358 */ 359 public PageCapture addCard(CardSpec card, String markupOrNull) throws TemplateModelException { 360 checkSrc(card); 361 for (var c : cards) 362 if (c.id().equals(card.id())) 363 throw FtlAttrLists.reject(f("<@card id='%s'> duplicates an existing card id.", card.id())); 364 if (builtCardIds.contains(card.id())) 365 throw FtlAttrLists.reject(f("<@card id='%s'> duplicates an existing card id.", card.id())); 366 if (nn(markupOrNull)) { 367 card.template(card.id()); 368 templates.put(card.id(), markupOrNull); 369 } 370 cards.add(card); 371 return this; 372 } 373 374 // Every card reaching the page passes through here: <@card> html cards, PageSpec.html / PageSpec.card, and direct 375 // addCard callers. Checks, in order: (1) a card's src is fetched by the browser, so it must be a same-origin path 376 // ({token} placeholders allowed); (2) sanitize= is valid only on an html card with a src. The src check wins when both fail. 377 private static void checkSrc(CardSpec card) throws TemplateModelException { 378 var src = card.src(); 379 if (nn(src) && ! SafePathTemplate.isSameOriginPath(src)) 380 throw FtlAttrLists.reject(f("<@card id='%s'> type='%s' src must be a same-origin path (no scheme, '//', backslash, control character, edge space or '..' segment); got '%s'.", 381 card.id(), card.type(), src)); 382 if (card.sanitize() && (neq(card.type(), "html") || ! nn(src))) 383 throw FtlAttrLists.reject(f("<@card id='%s'> sanitize= applies only to an html card with src=.", card.id())); 384 } 385 386 /** 387 * Registers a card built by a {@code PageSpec}. It is held apart from the authored cards until placed or the 388 * page closes, so a spec's cards follow the template's cards in declaration order. 389 * 390 * @param card The card. 391 * @param markupOrNull Markup emitted as {@code <template data-card="{id}">}, or <jk>null</jk>. 392 * @throws TemplateModelException On a duplicate card id, checked against placed and unplaced cards. 393 */ 394 void addBuiltCard(CardSpec card, String markupOrNull) throws TemplateModelException { 395 checkSrc(card); 396 for (var c : cards) 397 if (c.id().equals(card.id())) 398 throw FtlAttrLists.reject(f("<@card id='%s'> duplicates an existing card id.", card.id())); 399 if (builtCards.containsKey(card.id()) || builtCardIds.contains(card.id())) 400 throw FtlAttrLists.reject(f("<@card id='%s'> duplicates an existing card id.", card.id())); 401 if (nn(markupOrNull)) { 402 card.template(card.id()); 403 templates.put(card.id(), markupOrNull); 404 } 405 builtCards.put(card.id(), card); 406 builtCardIds.add(card.id()); 407 } 408 409 /** 410 * Places a built card at the current position in the card order. 411 * 412 * @param id The built card id. 413 * @throws TemplateModelException If the card was already placed, or no built card has that id. 414 */ 415 void placeBuiltCard(String id) throws TemplateModelException { 416 var card = builtCards.remove(id); 417 if (n(card)) { 418 if (builtCardIds.contains(id)) 419 throw FtlAttrLists.reject(f("<@card ref='%s'> places a PageSpec card that was already placed.", id)); 420 throw FtlAttrLists.reject(f("<@card ref='%s'> names no PageSpec card; declared: '%s'.", id, 421 String.join(", ", builtCardIds))); 422 } 423 cards.add(card); 424 } 425 426 /** Appends every still-unplaced built card after the authored and placed cards, in declaration order. */ 427 void flushUnplacedBuiltCards() { 428 cards.addAll(builtCards.values()); 429 builtCards.clear(); 430 } 431 432 /** 433 * Adds a header or footer slot template. 434 * 435 * @param scope {@code header} or {@code footer}. 436 * @param name The slot name. 437 * @param markup The slot markup. 438 * @return This object. 439 */ 440 public PageCapture addSlot(String scope, String name, String markup) { 441 var id = scope + "." + name; 442 slots.computeIfAbsent(scope, k -> new LinkedHashMap<>()).put(name, id); 443 templates.put(id, markup); 444 return this; 445 } 446 447 /** 448 * Adds a top-level {@code topics} entry. Java ({@code PageSpec.topic}) and FTL ({@code <@topic>}) declarations 449 * union; the same topic again with the same {@code retain} is a no-op. 450 * 451 * @param decl A {@code TopicDecl.toMap()} entry. 452 * @param where Where it was declared, for the E-46 message, for example {@code "<@topic>"}. 453 * @return This object. 454 * @throws IllegalArgumentException E-46 if the topic is already declared with a different {@code retain}. 455 */ 456 PageCapture addTopic(Map<String,Object> decl, String where) { 457 var topic = (String)decl.get("topic"); 458 var prior = topics.get(topic); 459 if (prior == null) { 460 topics.put(topic, decl); 461 topicWhere.put(topic, where); 462 } else if (neq(prior.get("retain"), decl.get("retain"))) { 463 throw iaex("topic '%s' is declared with retain=%s here and retain=%s at %s", 464 topic, decl.get("retain"), prior.get("retain"), topicWhere.get(topic)); 465 } else if (neq(prior.get("publisher"), decl.get("publisher"))) { 466 throw iaex("topic '%s' is declared with publisher=%s here and publisher=%s at %s", 467 topic, decl.get("publisher"), prior.get("publisher"), topicWhere.get(topic)); 468 } 469 return this; 470 } 471 472 /** 473 * Adds a top-level {@code bridges} entry, with {@code session} already resolved. 474 * 475 * @param bridge A {@code BridgeDecl.toMap()} entry. 476 * @return This object. 477 * @throws IllegalArgumentException E-51 on a duplicate bridge id. 478 */ 479 PageCapture addBridge(Map<String,Object> bridge) { 480 var id = (String)bridge.get("id"); 481 if (bridges.containsKey(id)) 482 throw iaex("bridge '%s': %s", id, "duplicate id"); 483 bridges.put(id, bridge); 484 return this; 485 } 486 487 /** 488 * Adds a top-level {@code dataSources} entry. 489 * 490 * @param source A {@code DataSourceDef.toMap()} or {@code Derived.toMap()} entry. 491 * @return This object. 492 * @throws IllegalArgumentException E-76 on a duplicate data source id. 493 */ 494 PageCapture addDataSource(Map<String,Object> source) { 495 var id = (String)source.get("id"); 496 if (dataSources.containsKey(id)) 497 throw iaex(DataSourceDef.E76, id, "duplicate id"); 498 dataSources.put(id, source); 499 return this; 500 } 501 502 /** 503 * Runs R-10 and R-11 over the captured page; called at {@code </@console>} and by {@code PageSpec.view}. 504 * 505 * @param registry The card types the page may use: the {@code ConsoleFreemarkerMixin}'s registry, so custom 506 * {@code Builder.cardType(...)} handlers are seen. 507 * @throws IllegalArgumentException With the first problem's message. 508 */ 509 void checkWiring(CardTypeRegistry registry) { 510 List<BusWiringValidator.Problem> problems; 511 try { 512 problems = BusWiringValidator.validate(JsonMap.ofString(toContractJson()), registry); 513 } catch (Exception e) { 514 throw new IllegalStateException(e); 515 } 516 if (! problems.isEmpty()) 517 throw new IllegalArgumentException(problems.get(0).message()); 518 } 519 520 /** 521 * Appends a header badge. 522 * 523 * @param badge The badge. Must not be <jk>null</jk>. 524 * @return This object. 525 * @throws TemplateModelException On a duplicate badge id. 526 */ 527 public PageCapture addBadge(BadgeDef badge) throws TemplateModelException { 528 var id = (String)badge.toContractMap().get("id"); 529 if (badges.containsKey(id)) 530 throw FtlAttrLists.reject(f("Badge id '%s' is declared twice (PageSpec and/or <@badge>).", id)); 531 badges.put(id, badge); 532 return this; 533 } 534 535 /** 536 * Non-strict, last-wins merge: same-side repeats of facts, and the base of the strict Java-vs-chrome merge. 537 * 538 * @param base The base map. 539 * @param overlay The overlay; its values win. 540 * @return A new merged map. 541 */ 542 static Map<String,Object> mergeFactsLastWins(Map<String,Object> base, Map<String,Object> overlay) { 543 var out = new LinkedHashMap<String,Object>(base); 544 out.putAll(overlay); 545 return out; 546 } 547 548 /** 549 * Sets the page's dashboard. 550 * 551 * @param v The {@code dashboard} contract object built by {@code DashboardSpec.toJson}. 552 * @throws IllegalArgumentException E-77 if the page already has one. 553 */ 554 void dashboard(Map<String,Object> v) { 555 if (dashboard != null) 556 throw new IllegalArgumentException("E-77: " + f(BusWiringValidator.E77, v.get("id"), "a page has at most one dashboard")); 557 dashboard = v; 558 } 559 560 /** @param v Facts seeded from a {@code PageSpec}; merged last-wins with earlier seeds. */ 561 void seedJavaFacts(Map<String,Object> v) { 562 javaFacts = mergeFactsLastWins(javaFacts, v); 563 } 564 565 /** @param v Facts from {@code <@console facts=>} or {@code <@facts>}; merged last-wins with earlier ones. @return This object. */ 566 PageCapture mergeChromeFacts(Map<String,Object> v) throws TemplateModelException { 567 try { 568 PageSpec.checkFactTypes("", v); 569 } catch (IllegalArgumentException e) { 570 throw FtlAttrLists.reject(e.getMessage()); 571 } 572 chromeFacts = mergeFactsLastWins(chromeFacts, v); 573 return this; 574 } 575 576 /** 577 * {@code </@console>}: strictly deep-merges the Java and chrome facts, naming the dotted path of any leaf set by both. 578 * 579 * @throws TemplateModelException On a leaf set by both sides. 580 */ 581 void resolveFacts() throws TemplateModelException { 582 facts = deepMergeFacts("", javaFacts, chromeFacts); 583 } 584 585 @SuppressWarnings({ 586 "unchecked" // Narrows a JSON-shaped Map<?,?> to Map<String,Object>; its keys are always strings. 587 }) 588 private static Map<String,Object> deepMergeFacts(String prefix, Map<String,Object> a, Map<String,Object> b) throws TemplateModelException { 589 var out = new LinkedHashMap<String,Object>(a); 590 for (var e : b.entrySet()) { 591 var path = prefix.isEmpty() ? e.getKey() : prefix + "." + e.getKey(); 592 if (! out.containsKey(e.getKey())) { 593 out.put(e.getKey(), e.getValue()); 594 continue; 595 } 596 var existing = out.get(e.getKey()); 597 if (existing instanceof Map<?,?> && e.getValue() instanceof Map<?,?>) 598 out.put(e.getKey(), deepMergeFacts(path, (Map<String,Object>)existing, (Map<String,Object>)e.getValue())); 599 else 600 throw FtlAttrLists.reject(f("Fact '%s' is set by both PageSpec.facts and the chrome; set it in one place.", path)); 601 } 602 return out; 603 } 604 605 /** 606 * {@code </@console>}: checks each badge against the finished page. {@code table} and every {@code refreshes} 607 * entry (except those also in {@code refreshesAllowMissing}) must name a card on the page; when {@code scope.by} is 608 * {@code nav}, each {@code scope.values} key must name a node in the resolved nav tree. 609 * 610 * @throws TemplateModelException On an unknown card id or nav node. 611 */ 612 @SuppressWarnings({ 613 "unchecked" // Narrows a JSON-shaped Map<?,?> to Map<String,Object>; its keys are always strings. 614 }) 615 void checkBadges() throws TemplateModelException { 616 var cardIds = new HashSet<String>(builtCardIds); 617 for (var c : cards) 618 cardIds.add(c.id()); 619 var navIds = new HashSet<String>(); 620 collectNavIds(navRoot, navIds); 621 for (var b : badges.values()) { 622 var m = b.toContractMap(); 623 var id = (String)m.get("id"); 624 for (var card : badgeCardRefs(m)) 625 if (! cardIds.contains(card)) 626 throw FtlAttrLists.reject(f(BADGE_CARD_MSG, id, card)); 627 if (m.get("scope") instanceof Map<?,?> scope && "nav".equals(scope.get("by")) && scope.get("values") instanceof Map<?,?> values) 628 for (var key : ((Map<String,Object>)values).keySet()) 629 if (! navIds.contains(key)) 630 throw FtlAttrLists.reject(f(BADGE_NAV_MSG, id, key)); 631 } 632 } 633 634 static final String BADGE_CARD_MSG = "<@badge id='%s'> references card '%s', which is not on the page."; 635 static final String BADGE_NAV_MSG = "<@badge id='%s'> scope names nav node '%s', which is not in the nav tree."; 636 637 /** 638 * @param badge A badge's contract map. 639 * @return Its {@code table} followed by its {@code refreshes} entries, minus those listed in 640 * {@code refreshesAllowMissing}. 641 */ 642 static List<String> badgeCardRefs(Map<String,Object> badge) { 643 var out = new ArrayList<String>(); 644 if (badge.get("table") instanceof String t) 645 out.add(t); 646 var optional = badge.get("refreshesAllowMissing") instanceof List<?> a ? a : List.of(); 647 if (badge.get("refreshes") instanceof List<?> r) 648 for (var e : r) 649 if (! optional.contains(e)) 650 out.add(String.valueOf(e)); 651 return out; 652 } 653 654 private static void collectNavIds(NavNode node, Set<String> out) { 655 if (nn(node.id())) 656 out.add(node.id()); 657 for (var c : node.children()) 658 collectNavIds(c, out); 659 } 660 661 /** 662 * Records a child to add under an existing chrome nav node, resolved later by {@link #applyPendingNavAdds()}. 663 * 664 * @param parentIdPath The root-first id path to the existing ancestor node. 665 * @param adder Receives the resolved ancestor and adds its children to it. 666 */ 667 public void addPendingNavUnder(String parentIdPath, NavAdder adder) { 668 pendingNavAdds.add(new PendingNavAdd(parentIdPath, adder)); 669 } 670 671 /** 672 * Resolves every pending nav addition recorded by {@link #addPendingNavUnder}, in declaration order. The 673 * pending list is cleared first, so a second call does nothing. 674 * 675 * @throws TemplateModelException If a {@code parentIdPath} does not match an existing node. 676 */ 677 public void applyPendingNavAdds() throws TemplateModelException { 678 var batch = List.copyOf(pendingNavAdds); 679 pendingNavAdds.clear(); 680 for (var p : batch) { 681 var parent = navRoot.find(List.of(p.parentIdPath().split("/"))); 682 if (parent.isEmpty()) 683 throw FtlAttrLists.reject(f( 684 "Nav addition under '%s' does not match a <@node> path in the chrome; known paths: '%s'.", 685 p.parentIdPath(), String.join(", ", navRoot.paths()))); 686 p.adder().accept(parent.get()); 687 } 688 } 689 690 /** 691 * Merge-aware twin of {@link #tab(String)}: first writer wins, and any second non-blank writer is rejected, even with the 692 * same value. 693 * 694 * @param tab The {@code <@page tab>} value. Blank is a no-op. 695 * @return This object. 696 * @throws TemplateModelException If a non-blank tab was already set. 697 */ 698 public PageCapture mergeTab(String tab) throws TemplateModelException { 699 if (ib(tab)) 700 return this; 701 if (this.tab.isEmpty()) { 702 this.tab = tab; 703 return this; 704 } 705 throw FtlAttrLists.reject(f( 706 "PageSpec sets tab='%s' and <@page tab='%s'> also sets it; set it in one place.", this.tab, tab)); 707 } 708 709 /** 710 * Merge-aware twin of {@link #theme(String)}: first writer wins, a repeat of the same value is a no-op, and a 711 * differing second writer is rejected. 712 * 713 * @param name The {@code <@theme name>} value. Blank is a no-op. 714 * @return This object. 715 * @throws TemplateModelException If a different, non-blank theme was already set. 716 */ 717 public PageCapture mergeTheme(String name) throws TemplateModelException { 718 if (ib(name)) 719 return this; 720 if (ib(theme)) { 721 theme = name; 722 themeFromDirective = true; 723 return this; 724 } 725 if (theme.equals(name)) 726 return this; 727 if (themeFromDirective) 728 throw FtlAttrLists.reject(f( 729 "<@theme name='%s'> conflicts with an earlier <@theme name='%s'> on this page; use one.", name, theme)); 730 throw FtlAttrLists.reject(f( 731 "PageSpec theme '%s' conflicts with <@theme name='%s'>; remove name= from <@theme> to inherit the " 732 + "page theme.", theme, name)); 733 } 734 735 /** @return The current theme name, or <jk>null</jk> if neither a spec nor a directive has set one yet. */ 736 String themeOrNull() { return theme; } 737 738 /** 739 * Merge-aware setter for the raw {@code <@body>} attribute text: union by attribute name, existing (spec) text 740 * first and then the new text. The same attribute name on both sides is always rejected, even when the values 741 * agree. Called once, from {@link #checkConsoleClose()}, with the text {@code <@body>} captured into 742 * {@link #ftlBodyAttrs}. 743 * 744 * @param attrs The raw {@code <@body>} attribute text. Blank is a no-op. 745 * @return This object. 746 * @throws TemplateModelException If an attribute name already set is set again. 747 */ 748 public PageCapture mergeBodyAttrs(String attrs) throws TemplateModelException { 749 if (ib(attrs)) 750 return this; 751 if (ib(bodyAttrs)) { 752 bodyAttrs = attrs; 753 return this; 754 } 755 var existing = bodyAttrNames(bodyAttrs); 756 for (var name : bodyAttrNames(attrs)) 757 if (existing.contains(name)) 758 throw FtlAttrLists.reject(f( 759 "PageSpec body attribute '%s' is also set by <@body>; set it in one place.", name)); 760 bodyAttrs = (bodyAttrs + " " + attrs).strip(); 761 return this; 762 } 763 764 private static final Pattern BODY_ATTR_NAME = Pattern.compile("[A-Za-z_:][-A-Za-z0-9_:.]*"); 765 766 /** One attribute found by {@link #tokenizeBodyAttrs(String)}: its span in the text, its name, and whether it has a value. */ 767 private record BodyAttr(int start, int end, String name, boolean hasValue) {} 768 769 // <@body> markup is raw, so a value can be double-quoted, single-quoted or unquoted. Tokenizing (rather than 770 // regex-searching the whole text) means a name is only ever read where an attribute can start, never from inside 771 // another attribute's quoted value, e.g. title="data-juneau-csrf=x". 772 private static List<BodyAttr> tokenizeBodyAttrs(String text) { 773 var out = new ArrayList<BodyAttr>(); 774 var n = text.length(); 775 var i = 0; 776 while (i < n) { 777 if (Character.isWhitespace(text.charAt(i))) { 778 i++; 779 continue; 780 } 781 var start = i; 782 while (i < n && ! Character.isWhitespace(text.charAt(i)) && text.charAt(i) != '=') 783 i++; 784 var name = text.substring(start, i); 785 var j = i; 786 while (j < n && Character.isWhitespace(text.charAt(j))) 787 j++; 788 var hasValue = false; 789 if (j < n && text.charAt(j) == '=') { 790 j++; 791 while (j < n && Character.isWhitespace(text.charAt(j))) 792 j++; 793 if (j < n && (text.charAt(j) == '"' || text.charAt(j) == '\'')) { 794 var close = text.indexOf(text.charAt(j), j + 1); 795 j = close < 0 ? n : close + 1; 796 } else { 797 while (j < n && ! Character.isWhitespace(text.charAt(j))) 798 j++; 799 } 800 hasValue = true; 801 i = j; 802 } else if (i == start) { 803 i++; // A stray '=': step over it so the scan always advances. 804 } 805 if (BODY_ATTR_NAME.matcher(name).matches()) 806 out.add(new BodyAttr(start, i, name, hasValue)); 807 } 808 return out; 809 } 810 811 private static Set<String> bodyAttrNames(String text) { 812 return tokenizeBodyAttrs(text).stream().filter(BodyAttr::hasValue).map(BodyAttr::name) 813 .collect(Collectors.toCollection(() -> new TreeSet<>(String.CASE_INSENSITIVE_ORDER))); 814 } 815 816 /** 817 * Whether the merged body-attribute text already sets {@code name}. Used so a spec- or {@code <@body>}-authored 818 * CSRF attribute is not emitted a second time by the request-attribute auto-detection. 819 * 820 * @param name An HTML attribute name. 821 * @return Whether the merged text sets it. 822 */ 823 boolean hasBodyAttr(String name) { 824 return bodyAttrs != null && tokenizeBodyAttrs(bodyAttrs).stream().anyMatch(a -> a.hasValue() && a.name().equalsIgnoreCase(name)); 825 } 826 827 /** 828 * The merged body-attribute text with the named attributes taken out, for a response that must not carry them. 829 * 830 * @param names The HTML attribute names to drop. 831 * @return The remaining text, possibly blank, or <jk>null</jk> if no body attributes were set. 832 */ 833 String bodyAttrsWithout(String...names) { 834 if (bodyAttrs == null) 835 return null; 836 var s = new StringBuilder(bodyAttrs); 837 var attrs = tokenizeBodyAttrs(bodyAttrs); 838 for (var k = attrs.size() - 1; k >= 0; k--) { 839 var a = attrs.get(k); 840 if (! a.hasValue() || Arrays.stream(names).noneMatch(a.name()::equalsIgnoreCase)) 841 continue; 842 var from = a.start(); 843 while (from > 0 && Character.isWhitespace(s.charAt(from - 1))) 844 from--; 845 s.delete(from, a.end()); 846 } 847 return s.toString().strip(); 848 } 849 850 /** 851 * Union merge for {@link #toolkit(List)}: appends any name not already present, in first-seen order. 852 * 853 * @param names The names to union in. 854 * @return This object. 855 */ 856 public PageCapture mergeToolkit(List<String> names) { 857 toolkits = mergeUnion(toolkits, names); 858 return this; 859 } 860 861 /** 862 * Union merge for the page stylesheets: appends any URL not already present, in first-seen order. 863 * 864 * @param hrefs The URLs to union in. 865 * @return This object. 866 */ 867 public PageCapture mergeCss(List<String> hrefs) { 868 css = mergeUnion(css, hrefs); 869 return this; 870 } 871 872 /** 873 * Union merge for the page init scripts: appends any URL not already present, in first-seen order. 874 * 875 * @param srcs The URLs to union in. 876 * @return This object. 877 */ 878 public PageCapture mergeInit(List<String> srcs) { 879 for (var u : srcs) 880 if (! u.startsWith("context:") && ! u.startsWith("servlet:") && ! SafePathTemplate.isSameOriginPath(u)) 881 throw iaex("page script must be a same-origin path; got '%s'.", u); 882 init = mergeUnion(init, srcs); 883 return this; 884 } 885 886 // Dedupes within a single list too, not only across the two sources: css=["a.css","a.css"] yields one link. 887 private static List<String> mergeUnion(List<String> existing, List<String> additions) { 888 var out = tl(existing); 889 for (var a : additions) 890 if (! out.contains(a)) 891 out.add(a); 892 return List.copyOf(out); 893 } 894 895 void css(List<String> v) { css = List.copyOf(v); } 896 void init(List<String> v) { init = List.copyOf(v); } 897 void toolkitAssets(ToolkitPackRegistry.Resolved r) { 898 assetsResolved = true; 899 vendorCss = r.vendorCss(); 900 vendorJs = r.vendorJs(); 901 runtimeCss = r.runtimeCss(); 902 runtimeJs = r.runtimeJs(); 903 } 904 void shellUrl(String v) { shellUrl = v; } 905 boolean hasBadges() { return ! badges.isEmpty(); } 906 StringWriter pageBuffer() { return pageBuffer; } 907 StringWriter consoleBuffer() { return consoleBuffer; } 908 List<String> cssHrefs() { return css; } 909 List<String> initScripts() { return init; } 910 void emitScripts(boolean v) { emitScripts = v; } 911 void allowInlineHandlers(boolean v) { allowInline = v; } 912 boolean allowInlineHandlers() { return allowInline; } 913 void rootModel(Map<String,Object> v) { rootModel = v; } 914 boolean assetsResolved() { return assetsResolved; } 915 List<String> vendorCss() { return vendorCss; } 916 List<String> vendorJs() { return vendorJs; } 917 List<String> runtimeCss() { return runtimeCss; } 918 List<String> runtimeJs() { return runtimeJs; } 919 920 /** 921 * Records toolkit packs the page needs, in first-seen order. Called by {@code <@card>} for each authored card 922 * and by other directives that emit markup needing a pack. 923 * 924 * @param packs The pack names. 925 * @return This object. 926 */ 927 public PageCapture require(Collection<String> packs) { 928 requiredPacks.addAll(packs); 929 return this; 930 } 931 932 /** @return The recorded pack names, in first-seen order. */ 933 public Set<String> requiredPacks() { return u(requiredPacks); } 934 935 /** @return <jk>true</jk> while a {@code <@page>} body is rendering. */ 936 public boolean inPage() { return pageOpen; } 937 String title() { return title; } 938 List<CardSpec> unplacedCards() { return List.copyOf(builtCards.values()); } 939 String theme() { return theme; } 940 String scheme() { return scheme; } 941 boolean schemeToggle() { return schemeToggle; } 942 boolean themeSelector() { return themeSelector; } 943 String headerSubtitle() { return header.subtitle; } 944 Map<String,Object> headerUserMenu() { return header.userMenu; } 945 boolean hasHeaderTitle() { return nn(header.title); } 946 947 //----------------------------------------------------------------------------------------------------------------- 948 // Lifecycle hooks used by the directives 949 //----------------------------------------------------------------------------------------------------------------- 950 951 /** Turns pending non-blank {@code <@page>} body markup into a bare {@code jc-seg-N} card. */ 952 void flushSegment() throws TemplateModelException { 953 var s = pageBuffer.toString(); 954 pageBuffer.getBuffer().setLength(0); 955 if (s.isBlank()) 956 return; 957 var id = "jc-seg-" + (++segments); 958 addCard(CardSpec.html(id).bare(true), s); 959 } 960 961 /** The next {@code jc-card-N} id for a {@code <@card>} without {@code id=}. */ 962 String nextCardId() { 963 return "jc-card-" + (++autoCards); 964 } 965 966 /** {@code <@main/>}: the console buffer so far is the banner. */ 967 void markMain() { 968 mainCount++; 969 var s = consoleBuffer.toString(); 970 consoleBuffer.getBuffer().setLength(0); 971 if (! s.isBlank()) 972 addSlot("header", "banner", s); 973 } 974 975 /** {@code </@console>}: E-13 then E-12, then merge the {@code <@body>} attributes with any spec-supplied ones, then 976 * resolve pending nav additions (E-B8), all before the caller's own {@code resolveActiveNav()}. */ 977 void checkConsoleClose() throws TemplateModelException { 978 if (mainCount != 1) 979 throw FtlAttrLists.reject(f("<@console> requires exactly one <@main/>; found '%s'.", mainCount)); 980 if (! consoleBuffer.toString().isBlank()) 981 throw FtlAttrLists.reject("<@console> has markup after <@main/>; move it into <@footer> or <@scripts>."); 982 if (ftlBodyAttrs != null) 983 mergeBodyAttrs(ftlBodyAttrs); 984 applyPendingNavAdds(); 985 flushUnplacedBuiltCards(); 986 resolveFacts(); 987 checkBadges(); 988 } 989 990 /** Explicit selection, else tab (E-7 when it does not resolve), else empty. */ 991 void resolveActiveNav() throws TemplateModelException { 992 if (nn(selected)) { 993 activeNav = selected; 994 return; 995 } 996 if (tab.isEmpty()) { 997 activeNav = List.of(); 998 return; 999 } 1000 var path = List.of(tab.split("/")); 1001 if (navRoot.find(path).isEmpty()) 1002 throw FtlAttrLists.reject(f("<@page tab='%s'> does not match a visible <@node> path; known paths: '%s'.", 1003 tab, String.join(", ", navRoot.paths()))); 1004 activeNav = path; 1005 } 1006 1007 //----------------------------------------------------------------------------------------------------------------- 1008 // Getters / output 1009 //----------------------------------------------------------------------------------------------------------------- 1010 1011 /** @return The {@code <@page tab>} value, {@code ""} when absent. */ 1012 public String tab() { return tab; } 1013 1014 /** @return The toolkit names. */ 1015 public List<String> toolkits() { return toolkits; } 1016 1017 /** @return The resolved active path (empty until {@code <@console>} closes, or when there is no selection). */ 1018 public List<String> activeNav() { return activeNav; } 1019 1020 /** @return The cards, in page order. */ 1021 public List<CardSpec> cards() { return u(cards); } 1022 1023 /** @return Template id to markup, in emit order. */ 1024 public Map<String,String> templates() { return u(templates); } 1025 1026 /** 1027 * Serializes the contract. 1028 * 1029 * @return Script-safe contract JSON (every {@code <} written as the JSON unicode escape). 1030 */ 1031 public String toContractJson() { 1032 var m = new LinkedHashMap<String,Object>(); 1033 m.put("contractVersion", CONTRACT_VERSION); 1034 m.put("title", title); 1035 if (nn(theme)) 1036 m.put("theme", Map.of("name", theme)); 1037 var h = headerMap(); 1038 if (! h.isEmpty()) 1039 m.put("header", h); 1040 var f = footerMap(); 1041 if (! f.isEmpty()) 1042 m.put("footer", f); 1043 if (nn(navLayout)) 1044 m.put("navLayout", navLayout); 1045 m.put("nav", navRoot.toList()); 1046 m.put("activeNav", activeNav); 1047 var cardMaps = cards.stream().map(CardSpec::toMap).toList(); 1048 m.put("cards", cardMaps); 1049 if (! init.isEmpty() && (emitScripts || usesModel(cardMaps))) 1050 m.put("scripts", List.copyOf(init)); 1051 if (allowInline) 1052 m.put("allowInlineHandlers", true); 1053 if (nn(rootModel)) 1054 m.put("model", rootModel); 1055 if (usesModel(cardMaps)) 1056 m.put("modelVersion", "1"); 1057 if (! topics.isEmpty()) 1058 m.put("topics", List.copyOf(topics.values())); 1059 if (! bridges.isEmpty()) 1060 m.put("bridges", List.copyOf(bridges.values())); 1061 if (! dataSources.isEmpty()) 1062 m.put("dataSources", List.copyOf(dataSources.values())); 1063 if (! facts.isEmpty()) 1064 m.put("facts", facts); 1065 if (dashboard != null) 1066 m.put("dashboard", dashboard); 1067 return scriptSafeJson(Json.DEFAULT.write(m)); 1068 } 1069 1070 /** Whether any model block or handler action/subscription is present, so that legacy pages stay byte-identical. */ 1071 private boolean usesModel(Object cardMaps) { 1072 return nn(rootModel) || allowInline || emitScripts || containsModel(cardMaps); 1073 } 1074 1075 // Only the structural places a model block or handler action can live; a publish payload, option or data map that 1076 // happens to carry a "model" key must not flip a legacy page. 1077 private static boolean containsModel(Object o) { 1078 if (o instanceof Collection<?> c) 1079 return c.stream().anyMatch(PageCapture::containsModel); 1080 if (! (o instanceof Map<?,?> mp)) 1081 return false; 1082 if (mp.get("model") instanceof Map) 1083 return true; 1084 if (mp.get("subscribes") instanceof Collection<?> subs && subs.stream().anyMatch(x -> x instanceof Map<?,?> sm && sm.get("handler") != null)) 1085 return true; 1086 if (mp.get("ribbon") instanceof Collection<?> rb && rb.stream().anyMatch(x -> x instanceof Map<?,?> im && "handler".equals(im.get("type")))) 1087 return true; 1088 for (var k : List.of("table", "detail", "tabs", "ribbon", "region")) 1089 if (containsModel(mp.get(k))) 1090 return true; 1091 return false; 1092 } 1093 1094 /** 1095 * Writes the contract island, the templates and the shell script tag. 1096 * 1097 * @param out The writer. 1098 * @throws IOException On an I/O error. 1099 */ 1100 public void writeBody(Writer out) throws IOException { 1101 out.write("<script type=\"application/json\" id=\"juneau-page\">"); 1102 out.write(toContractJson()); 1103 out.write("</script>"); 1104 for (var e : templates.entrySet()) { 1105 var attr = e.getKey().contains(".") ? "data-slot" : "data-card"; 1106 out.write("<template " + attr + "=\"" + e.getKey() + "\">"); 1107 out.write(e.getValue()); 1108 out.write("</template>"); 1109 } 1110 out.write("<script src=\"" + shellUrl + "\"></script>"); 1111 } 1112 1113 static String scriptSafeJson(String json) { 1114 return json.replace("<", "\\u003c"); 1115 } 1116 1117 private Map<String,Object> headerMap() { 1118 var m = new LinkedHashMap<String,Object>(); 1119 if (nn(header.title)) m.put("title", header.title); 1120 if (nn(header.subtitle)) m.put("subtitle", header.subtitle); 1121 if (nn(header.logoSrc) || nn(header.logoSymbol)) { 1122 var l = new LinkedHashMap<String,Object>(); 1123 if (nn(header.logoSymbol)) l.put("symbol", header.logoSymbol); 1124 else l.put("src", header.logoSrc); 1125 if (nn(header.logoHref)) l.put("href", header.logoHref); 1126 if (nn(header.logoAlt)) l.put("alt", header.logoAlt); 1127 m.put("logo", l); 1128 } 1129 if (! header.links.isEmpty()) m.put("links", header.links); 1130 if (nn(header.userMenu)) m.put("userMenu", header.userMenu); 1131 if (header.chrome) m.put("chrome", true); 1132 if (slots.containsKey("header")) m.put("slots", slots.get("header")); 1133 if (! badges.isEmpty()) m.put("badges", badges.values().stream().map(BadgeDef::toContractMap).toList()); 1134 return m; 1135 } 1136 1137 private Map<String,Object> footerMap() { 1138 var m = new LinkedHashMap<String,Object>(); 1139 if (nn(footer.text)) m.put("text", footer.text); 1140 if (! footer.links.isEmpty()) m.put("links", footer.links); 1141 if (slots.containsKey("footer")) m.put("slots", slots.get("footer")); 1142 return m; 1143 } 1144}