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.views; 018 019import static org.apache.juneau.commons.utils.Shorts.*; 020 021import java.util.*; 022 023import org.apache.juneau.commons.http.*; 024import org.apache.juneau.terminal.report.TerminalViewChecks; 025 026/** 027 * A page "region": a named container whose contents a client-side populator fills in, chosen by name via 028 * {@link #populate} rather than declared inline. 029 * 030 * <p> 031 * Beyond the identity/populator core, this bean also carries the <b>declarative descriptor</b>: a data source ({@link 032 * #dataUrl} / {@link #params}), an inline renderer ({@link #renderer}), 033 * lazy activation ({@link #lazy}), a refresh interval ({@link #refreshMs}), and a field/title projection 034 * ({@link #fields} / {@link #titleFields}). A descriptor that omits {@link #populate} resolves to the 035 * Juneau-shipped declarative default ({@code JuneauViews.regions.defaultPopulate}), which reads exactly 036 * this descriptor (via {@code ctx.declared}) and nothing else. 037 * 038 * <h2 class='section'>Mutability</h2> 039 * <p> 040 * Deliberately mutable, like {@link Column} and {@link ViewDef} (the same rule, stated here since this class 041 * predates it): a {@link RegionDef} is a server-side authoring bean built up once via its public fields and 042 * fluent setters while constructing a page, not an immutable value object. Callers must not 043 * mutate one concurrently from more than one thread, and must not reuse one across requests unless every request 044 * treats it as read-only after construction. 045 * 046 * <h2 class='section'>Example:</h2> 047 * <p class='bjava'> 048 * <jc>// A lazily-activated row-detail region backed by a data URL, refreshing every 30 seconds.</jc> 049 * RegionDef <jv>region</jv> = RegionDef.<jsm>create</jsm>(<js>"release-notes"</js>) 050 * .type(RegionDef.<jsf>TYPE_ROW_DETAIL</jsf>) 051 * .dataUrl(<js>"/api/releases/{id}/notes"</js>) 052 * .lazy(<jk>true</jk>) 053 * .refreshMs(30_000L); 054 * </p> 055 * 056 * @since 10.0.0 057 */ 058@SuppressWarnings({ 059 "java:S1192", // The "chart" literal at the toContractMap call is a map key, not the region type. 060 "java:S1845", // Fluent-builder setters intentionally mirror field names (Juneau DSL convention). 061 "java:S3776" // validate*() and toContractMap() (also in Field) chain many independent null/blank guards; each is trivial, so splitting adds no clarity 062}) 063public class RegionDef { 064 065 /** 066 * The frozen contract version for the region envelope. 067 * 068 * <p> 069 * Deliberately independent of {@link ViewsMixin#CONTRACT_VERSION}: a region-contract revision must never 070 * force a view-sidecar bump, or vice-versa. 071 */ 072 public static final String CONTRACT_VERSION = "1"; 073 074 /** Wire token for a row-detail region. */ 075 public static final String TYPE_ROW_DETAIL = "row-detail"; 076 077 /** Wire token for a card-body region. */ 078 public static final String TYPE_CARD_BODY = "card-body"; 079 080 /** Wire token for a tab-body region. */ 081 public static final String TYPE_TAB_BODY = "tab-body"; 082 083 /** Wire token for a chart region (drawn by the built-in {@code chart} populator). */ 084 public static final String TYPE_CHART = "chart"; 085 086 private static final Set<String> TYPES = st(TYPE_ROW_DETAIL, TYPE_CARD_BODY, TYPE_TAB_BODY, TYPE_CHART); 087 088 private static final Set<String> CHART_KINDS = st("line", "bar"); 089 090 private String chartKind = "line"; 091 private String chartX; 092 private final List<String[]> chartSeries = new ArrayList<>(); 093 private int chartHeight; 094 095 /** The reserved renderer name that requires a non-empty {@link #fields} catalog. */ 096 private static final String RENDERER_FIELD_GRID = "field-grid"; 097 098 /** 099 * The minimum honored {@link #refreshMs}, in milliseconds. 100 * 101 * <p> 102 * A declared interval below this floor is clamped up to it rather than honored as configured — the same 103 * reasoning and the same shared floor as {@link SafePathTemplate#MIN_POLL_INTERVAL_MS}. 104 */ 105 public static final long MIN_REFRESH_MS = SafePathTemplate.MIN_POLL_INTERVAL_MS; 106 107 /** This region's own id, unique within its host. */ 108 public String id; 109 110 /** 111 * The name of the client populator to resolve via {@code JuneauViews.regions.resolve(name)}, or <jk>null</jk> 112 * for the reserved declarative default (<js>"default"</js>, see {@link PopulatorAllowlist#BUILTIN_IDS}). 113 * 114 * <p> 115 * This is a name looked up in the client registry rather than an inline function for two reasons: an inline 116 * function cannot survive the JSON sidecar this envelope travels in, and a name — unlike an arbitrary 117 * function body — is the one shape a server-side allowlist ({@link PopulatorAllowlist}) can meaningfully 118 * constrain at all. 119 */ 120 public String populate; 121 122 /** 123 * This region's type: {@link #TYPE_ROW_DETAIL}, {@link #TYPE_CARD_BODY}, or {@link #TYPE_TAB_BODY}. 124 * 125 * <p> 126 * Set by the enclosing host (a detail panel, a card, or a tab body) rather than by the region's own author in 127 * the common case; exposed here (rather than only in the sidecar) because {@link #validate()} needs it to 128 * enforce the type-scoped field-catalog rules — a {@link #TYPE_ROW_DETAIL} region must 129 * carry no {@link #fields}, and a {@link #TYPE_CARD_BODY}/{@link #TYPE_TAB_BODY} region using the 130 * {@code "field-grid"} {@link #renderer} under the reserved default must carry at least one. 131 */ 132 public String type; 133 134 /** 135 * A same-origin path from which the declarative default (and {@code ctx.fetchDeclared()}) fetches this 136 * region's payload. <jk>null</jk> means "no declared fetch" — legal, and the normal state for a custom 137 * populator that fetches its own way or paints with no fetch at all. 138 * 139 * <p> 140 * Validated with {@link #isSafeDetailEndpoint(String)} (same-origin, no scheme, no leading {@code //}, 141 * no {@code ..} segment). 142 */ 143 public String dataUrl; 144 145 /** 146 * Author-declared request parameters, opaque to the framework as a <b>payload</b> (nothing routes or branches 147 * on their contents) but not opaque to the query-string serializer that appends them to {@link #dataUrl}. Use a 148 * {@link LinkedHashMap} (or an equivalent ordered map) when key order matters to 149 * the endpoint: the serialization walks {@link Map#entrySet()} in the map's own iteration order. 150 */ 151 public Map<String,Object> params; 152 153 /** 154 * The name of the {@code JuneauViews.helpers} function the declarative default paints with, 155 * e.g. <js>"field-grid"</js>. <jk>null</jk> when a custom {@link #populate} does its own painting. 156 */ 157 public String renderer; 158 159 /** 160 * Whether this region's first populate is deferred until it becomes visible. 161 * 162 * <p> 163 * <jk>null</jk> means "use the per-region-type default": <jk>false</jk> for {@link #TYPE_ROW_DETAIL} and 164 * {@link #TYPE_CARD_BODY}, <jk>true</jk> for {@link #TYPE_TAB_BODY} — see {@link #effectiveLazy()}. 165 */ 166 public Boolean lazy; 167 168 /** 169 * The declared auto-refresh interval, in milliseconds, or <jk>null</jk> for no polling. 170 * 171 * <p> 172 * A value below {@link #MIN_REFRESH_MS} is silently clamped up to the floor rather than rejected. 173 */ 174 public Long refreshMs; 175 176 /** 177 * The field catalog: labels, renderers, hrefs, spans and per-field action-bar ids, declared once per region 178 * rather than repeated per row/refresh. Projects onto {@code ctx.declared.fields}. 179 * 180 * <p> 181 * <b>Card and tab regions only.</b> A {@link #TYPE_ROW_DETAIL} region's catalog is an author-declared JS 182 * literal handed straight to {@code fieldGrid} client-side; declaring {@link #fields} on a 183 * {@link #TYPE_ROW_DETAIL} region fails {@link #validate()}. 184 */ 185 public List<Field> fields; 186 187 /** 188 * Chrome's declared title-key allowlist — the one descriptor field whose only 189 * reader is the framework's own title painter, never the populate (see the 190 * three-way partition; the declarative default's source must not reference this field). 191 */ 192 public List<String> titleFields; 193 194 /** 195 * App-approved populator names allowed on {@link #populate} in addition to 196 * {@link PopulatorAllowlist#BUILTIN_IDS}. Blank entries fail {@link #validate()}. 197 * 198 * <p> 199 * Opting a name in here is authoring discipline, not a security boundary — see 200 * {@link PopulatorAllowlist}'s class Javadoc. 201 */ 202 public Set<String> allowedPopulators; 203 204 /** 205 * Creates a region with the given id. 206 * 207 * <p> 208 * The identity plus populator name. Page slots do not go through this factory — author HTML plus 209 * {@code JuneauViews.regions.mount({ id: populatorName })}. Not {@code @Deprecated}. 210 * </p> 211 * 212 * @param id This region's own id, unique within its host. Must not be <jk>null</jk> or blank. 213 * @return A new {@link RegionDef}. 214 */ 215 public static RegionDef create(String id) { 216 var r = new RegionDef(); 217 r.id = id; 218 return r; 219 } 220 221 /** 222 * Creates a chart region fed by a same-origin endpoint that returns row records. 223 * 224 * <p> 225 * Configure it with {@link #kind(String)}, {@link #x(String)}, {@link #series(String,String)} and 226 * {@link #height(int)}. A chart region uses the built-in {@code chart} populator and carries no field catalog. 227 * 228 * @param id This region's own id. 229 * @param dataUrl The same-origin path the chart fetches its records from. 230 * @return A new {@link RegionDef} of type {@link #TYPE_CHART}. 231 */ 232 public static RegionDef chart(String id, String dataUrl) { 233 var r = create(id); 234 r.type = TYPE_CHART; 235 r.dataUrl = dataUrl; 236 return r; 237 } 238 239 /** 240 * Sets the chart kind (chart regions only). 241 * 242 * @param value {@code "line"} (the default) or {@code "bar"}. 243 * @return This object. 244 */ 245 public RegionDef kind(String value) { 246 chartKind = value; 247 return this; 248 } 249 250 /** 251 * Sets the record field plotted on the x axis (chart regions only). 252 * 253 * @param field The field name. 254 * @return This object. 255 */ 256 public RegionDef x(String field) { 257 chartX = field; 258 return this; 259 } 260 261 /** 262 * Adds a plotted series (chart regions only). Repeatable. 263 * 264 * @param field The record field holding the series values. 265 * @param label The series label. 266 * @return This object. 267 */ 268 public RegionDef series(String field, String label) { 269 chartSeries.add(new String[] { field, label }); 270 return this; 271 } 272 273 /** 274 * Sets the chart height in pixels (chart regions only). 275 * 276 * @param value The height; must be positive. Zero (the default) leaves the height to the client. 277 * @return This object. 278 */ 279 public RegionDef height(int value) { 280 chartHeight = value; 281 return this; 282 } 283 284 /** 285 * Sets the name of the client populator to resolve. 286 * 287 * @param value A populator name, or <jk>null</jk> to use the reserved declarative default. 288 * @return This object. 289 */ 290 public RegionDef populate(String value) { 291 populate = value; 292 return this; 293 } 294 295 /** 296 * Sets this region's type. 297 * 298 * @param value One of {@link #TYPE_ROW_DETAIL}, {@link #TYPE_CARD_BODY}, {@link #TYPE_TAB_BODY}. 299 * @return This object. 300 */ 301 public RegionDef type(String value) { 302 type = value; 303 return this; 304 } 305 306 /** 307 * Sets the same-origin data-fetch endpoint. 308 * 309 * @param value The path. Must be a same-origin path template (no {@code ://}, no leading {@code //}, no 310 * scheme colon-before-slash, no {@code ..} segment) — enforced at {@link #validate()}. 311 * @return This object. 312 */ 313 public RegionDef dataUrl(String value) { 314 dataUrl = value; 315 return this; 316 } 317 318 /** 319 * Sets the author-declared request parameters. 320 * 321 * @param value The parameters. A {@link LinkedHashMap} (or equivalent ordered map) when key order matters. 322 * @return This object. 323 */ 324 public RegionDef params(Map<String,Object> value) { 325 params = value; 326 return this; 327 } 328 329 /** 330 * Sets the author-declared request parameters from key/value pairs, preserving call order. 331 * 332 * @param keyValuePairs An even-length {@code key, value, key, value, ...} sequence. 333 * @return This object. 334 */ 335 public RegionDef params(Object...keyValuePairs) { 336 if (keyValuePairs.length % 2 != 0) 337 throw iaex("RegionDef.params(...) requires an even number of key/value arguments."); 338 var m = new LinkedHashMap<String,Object>(); 339 for (var i = 0; i < keyValuePairs.length; i += 2) 340 m.put(String.valueOf(keyValuePairs[i]), keyValuePairs[i + 1]); 341 params = m; 342 return this; 343 } 344 345 /** 346 * Sets the helper name the declarative default paints with. 347 * 348 * @param value A {@code JuneauViews.helpers} function name, e.g. <js>"field-grid"</js>. 349 * @return This object. 350 */ 351 public RegionDef renderer(String value) { 352 renderer = value; 353 return this; 354 } 355 356 /** 357 * Sets whether this region's first populate is deferred until it becomes visible. 358 * 359 * @param value <jk>true</jk>/<jk>false</jk>, or leave unset (<jk>null</jk>) for the per-region-type default. 360 * @return This object. 361 */ 362 public RegionDef lazy(boolean value) { 363 lazy = value; 364 return this; 365 } 366 367 /** 368 * Declares that this region should be polled (re-fetched and re-populated) on the given interval. 369 * 370 * <p> 371 * A value below {@link #MIN_REFRESH_MS} is silently clamped up to the floor rather than rejected. 372 * 373 * @param intervalMs The desired polling interval, in milliseconds. Must be positive. 374 * @return This object. 375 */ 376 public RegionDef refreshMs(long intervalMs) { 377 if (intervalMs <= 0) 378 throw iaex("RegionDef.refreshMs(...) interval must be positive."); 379 refreshMs = SafePathTemplate.clampPollInterval(intervalMs); 380 return this; 381 } 382 383 /** 384 * The rules that must all match for the whole region to render. <jk>null</jk> or empty means always visible. 385 * See {@link RowAction#visibleWhen} for the shared semantics and evaluation-map convention. 386 */ 387 public List<VisibilityRule> visibleWhen; 388 389 /** 390 * Hides this region unless every rule matches. 391 * 392 * @param rules The rules; all must match. Replaces any rules set by an earlier call. 393 * @return This object. 394 */ 395 public RegionDef visibleWhen(VisibilityRule...rules) { 396 visibleWhen = l(rules); 397 return this; 398 } 399 400 /** 401 * Populator-owned structured configuration. <jk>null</jk> or empty means none. 402 * 403 * <p> 404 * Unlike {@link #params}, nested maps and lists are allowed, and the value is never appended to {@link #dataUrl} 405 * nor sent back to the server: it reaches the client only as {@code ctx.declared.config}. Its shape belongs to 406 * the populator that reads it (for example {@link JobLogRegion}); {@link #validate()} only checks that it is 407 * JSON-serializable (string keys, no cycles). 408 */ 409 public Map<String,Object> config; 410 411 /** 412 * Sets the populator-owned structured configuration. 413 * 414 * @param value The configuration; see {@link #config}. 415 * @return This object. 416 */ 417 public RegionDef config(Map<String,Object> value) { 418 config = value; 419 return this; 420 } 421 422 /** 423 * Sets the field catalog. 424 * 425 * @param value The catalog, in declaration order. Card/tab regions only — see {@link #fields}. 426 * @return This object. 427 */ 428 public RegionDef fields(Field...value) { 429 fields = l(value); 430 return this; 431 } 432 433 /** 434 * Sets chrome's declared title-key allowlist. 435 * 436 * @param value The allowlisted keys. 437 * @return This object. 438 */ 439 public RegionDef titleFields(String...value) { 440 titleFields = l(value); 441 return this; 442 } 443 444 /** 445 * Opts in app-approved populator names for {@link #populate}, in addition to 446 * {@link PopulatorAllowlist#BUILTIN_IDS}. 447 * 448 * @param value Populator names. Must not contain blank entries. 449 * @return This object. 450 */ 451 public RegionDef allowPopulators(String...value) { 452 allowedPopulators = st(value); 453 return this; 454 } 455 456 /** 457 * The effective {@link #lazy} value once the per-region-type default is applied. 458 * 459 * <p> 460 * <jk>false</jk> for {@link #TYPE_ROW_DETAIL} (the one region populates on expand, not lazily) and 461 * {@link #TYPE_CARD_BODY} (a card is visible when its grid is); <jk>true</jk> for {@link #TYPE_TAB_BODY} 462 * (preserving today's init-on-activate). An explicit {@link #lazy} value always wins over the per-type 463 * default, for any {@link #type} including <jk>null</jk>. 464 * 465 * @return The effective lazy flag. 466 */ 467 public boolean effectiveLazy() { 468 if (lazy != null) 469 return lazy; 470 return eq(type, TYPE_TAB_BODY); 471 } 472 473 /** 474 * Fail-closed bean validation. 475 * 476 * <p> 477 * Beyond the original id/populator checks, this now also enforces: a same-origin {@link #dataUrl}; a 478 * recognized {@link #type} (when set); no nested-map {@link #params} value and no {@link #params} key 479 * colliding with a key already present in {@link #dataUrl}'s own query string; the 480 * card/tab-only field catalog and its two startup rejections; and 481 * no blank {@link #titleFields} entry. 482 * 483 * @throws IllegalArgumentException If this definition is not well-formed. 484 */ 485 public void validate() { 486 if (ib(id)) 487 throw iaex("RegionDef id must not be null or blank."); 488 if (allowedPopulators != null) 489 for (var name : allowedPopulators) 490 if (ib(name)) 491 throw iaex("allowPopulators entry must not be blank."); 492 if (populate != null) 493 PopulatorAllowlist.assertAllowed(populate, allowedPopulators); 494 if (type != null && !TYPES.contains(type)) 495 throw iaex("RegionDef '%s' type must be one of %s, was '%s'.", id, TYPES, type); 496 validateDataUrlAndParams(); 497 validateTitleFields(); 498 validateFields(); 499 validateChart(); 500 validateConfig(); 501 } 502 503 /** 504 * Whether {@code endpoint} is a same-origin path template: no {@code ://} , no {@code //} prefix, no scheme 505 * colon-before-slash, and no {@code ..} path segments. 506 * 507 * @param endpoint The candidate template. May be <jk>null</jk>. 508 * @return <jk>true</jk> if the string is a same-origin path template. 509 */ 510 public static boolean isSafeDetailEndpoint(String endpoint) { 511 return TerminalViewChecks.isSameOriginPath(endpoint); 512 } 513 514 private void validateDataUrlAndParams() { 515 if (inb(dataUrl) && !isSafeDetailEndpoint(dataUrl)) 516 throw iaex("RegionDef '%s' dataUrl must be a same-origin path (no scheme, no leading '//', no '..' " 517 + "segment): %s", id, dataUrl); 518 if (ie(params)) 519 return; 520 for (var e : params.entrySet()) { 521 if (e.getValue() instanceof Map) 522 throw iaex("RegionDef '%s' params entry '%s' must not be a nested map/object; encode it into a " 523 + "string value yourself if you need structure.", id, e.getKey()); 524 } 525 var dataUrlKeys = queryKeysOf(dataUrl); 526 for (var key : params.keySet()) 527 if (dataUrlKeys.contains(key)) 528 throw iaex("RegionDef '%s' params key '%s' collides with a key already present in dataUrl's own " 529 + "query string.", id, key); 530 } 531 532 private void validateTitleFields() { 533 if (titleFields == null) 534 return; 535 for (var f : titleFields) 536 if (ib(f)) 537 throw iaex("RegionDef '%s' titleFields entry must not be blank.", id); 538 } 539 540 private void validateFields() { 541 if (eq(type, TYPE_ROW_DETAIL) && fields != null && !fields.isEmpty()) 542 throw iaex("RegionDef '%s' is type '%s' and must not declare fields; a row-detail region's catalog " 543 + "is an author JS literal, never a projected one.", id, TYPE_ROW_DETAIL); 544 if (eq(type, TYPE_CHART) && fields != null && !fields.isEmpty()) 545 throw iaex("RegionDef '%s' is type '%s' and must not declare fields.", id, TYPE_CHART); 546 if (fields != null) { 547 var keys = new HashSet<String>(); 548 for (var f : fields) { 549 if (f == null) 550 throw iaex("RegionDef '%s' fields entry must not be null.", id); 551 f.validate(id); 552 if (!keys.add(f.data)) 553 throw iaex("RegionDef '%s' duplicate field data key '%s'.", id, f.data); 554 } 555 } 556 var isDefaultPopulate = populate == null || eq(populate, "default"); 557 var isCardOrTab = eqa(type, TYPE_CARD_BODY, TYPE_TAB_BODY); 558 if (isDefaultPopulate && isCardOrTab && eq(renderer, RENDERER_FIELD_GRID) && (ie(fields))) 559 throw iaex("RegionDef '%s' declares renderer 'field-grid' under the default populator but no fields; " 560 + "a field-grid with no catalog would silently paint an unlabeled/empty grid.", id); 561 } 562 563 private void validateChart() { 564 if (! eq(type, TYPE_CHART)) 565 return; 566 if (ib(dataUrl)) 567 throw iaex("RegionDef '%s' is a chart and needs a dataUrl.", id); 568 if (! CHART_KINDS.contains(chartKind)) 569 throw iaex("RegionDef '%s' chart kind must be one of %s, was '%s'.", id, CHART_KINDS, chartKind); 570 if (ib(chartX)) 571 throw iaex("RegionDef '%s' chart needs an x field.", id); 572 if (chartSeries.isEmpty()) 573 throw iaex("RegionDef '%s' chart needs at least one series.", id); 574 for (var sr : chartSeries) 575 if (ib(sr[0]) || ib(sr[1])) 576 throw iaex("RegionDef '%s' chart series needs a field and a label.", id); 577 if (chartHeight < 0) 578 throw iaex("RegionDef '%s' chart height must not be negative.", id); 579 } 580 581 private void validateConfig() { 582 if (config != null) 583 checkSerializable(config, Collections.newSetFromMap(new IdentityHashMap<>())); 584 } 585 586 private void checkSerializable(Object v, Set<Object> path) { 587 if (v instanceof Map<?,?> || v instanceof Collection<?>) { 588 if (! path.add(v)) 589 throw iaex("RegionDef '%s' config must not contain a cycle.", id); 590 if (v instanceof Map<?,?> m) { 591 for (var e : m.entrySet()) { 592 if (! (e.getKey() instanceof String)) 593 throw iaex("RegionDef '%s' config keys must be strings.", id); 594 checkSerializable(e.getValue(), path); 595 } 596 } else { 597 for (var x : (Collection<?>)v) 598 checkSerializable(x, path); 599 } 600 path.remove(v); 601 return; 602 } 603 if (v == null || v instanceof String || v instanceof Number || v instanceof Boolean) 604 return; 605 throw iaex("RegionDef '%s' config values must be maps, lists, strings, numbers, booleans or null; got %s.", id, 606 v.getClass().getSimpleName()); 607 } 608 609 /** Extracts the query-string keys already present in {@code url}'s own {@code ?...} portion, if any. */ 610 private static Set<String> queryKeysOf(String url) { 611 if (url == null) 612 return Set.of(); 613 var q = url.indexOf('?'); 614 if (q < 0 || q == url.length() - 1) 615 return Set.of(); 616 var keys = new HashSet<String>(); 617 for (var pair : url.substring(q + 1).split("&")) { 618 if (pair.isEmpty()) 619 continue; 620 var eq = pair.indexOf('='); 621 keys.add(eq < 0 ? pair : pair.substring(0, eq)); 622 } 623 return keys; 624 } 625 626 /** 627 * Serializes this descriptor to the compact JSON envelope the {@code data-juneau-region-contract} sidecar 628 * attribute carries, hand-built (rather than reflected) so the key set, order, and each 629 * nested {@link Field}'s wire shape are exactly the ones the contract specifies. 630 * 631 * @return An ordered {@link Map} ready for {@code Json.of(...)}. 632 */ 633 public Map<String,Object> toContractMap() { 634 var m = new LinkedHashMap<String,Object>(); 635 m.put("contractVersion", CONTRACT_VERSION); 636 m.put("id", id); 637 if (type != null) 638 m.put("type", type); 639 if (populate != null) 640 m.put("populate", populate); 641 if (dataUrl != null) 642 m.put("dataUrl", dataUrl); 643 if (params != null && !params.isEmpty()) 644 m.put("params", params); 645 if (renderer != null) 646 m.put("renderer", renderer); 647 m.put("lazy", effectiveLazy()); 648 if (refreshMs != null) 649 m.put("refreshMs", refreshMs); 650 if (titleFields != null && !titleFields.isEmpty()) 651 m.put("titleFields", titleFields); 652 if (fields != null && !fields.isEmpty()) { 653 m.put("fields", fields.stream().map(Field::toContractMap).toList()); 654 } 655 if (eq(type, TYPE_CHART)) { 656 var c = new LinkedHashMap<String,Object>(); 657 c.put("kind", chartKind); 658 c.put("x", chartX); 659 c.put("series", chartSeries.stream().map(sr -> { 660 var e = new LinkedHashMap<String,Object>(); 661 e.put("field", sr[0]); 662 e.put("label", sr[1]); 663 return e; 664 }).toList()); 665 if (chartHeight > 0) 666 c.put("height", chartHeight); 667 m.put("chart", c); 668 } 669 if (visibleWhen != null && !visibleWhen.isEmpty()) 670 m.put("visibleWhen", VisibilityRule.toMaps(visibleWhen)); 671 if (config != null && !config.isEmpty()) 672 m.put("config", config); 673 return m; 674 } 675 676 /** 677 * One entry in the field catalog: a label, an optional named renderer and its meta, an 678 * optional href template, a paint format, a grid span, and per-field action-bar ids. 679 * 680 * <p> 681 * Card and tab regions only — see {@link RegionDef#fields}. 682 * 683 * @since 10.0.0 684 */ 685 public static class Field { 686 687 /** The key into {@code ctx.data}'s values map. Unique across the enclosing {@link RegionDef}. */ 688 public String data; 689 690 /** The label shown above the value. <jk>null</jk> falls back to {@link #data} at paint time. */ 691 public String label; 692 693 /** Optional named renderer id, resolved against the same {@code NS._renderers} registry as today. */ 694 public String render; 695 696 /** Optional metadata handed to {@link #render}'s renderer function. */ 697 public Map<String,Object> renderMeta; 698 699 /** Optional {@code {property}} URL template consumed by the {@code linked} renderer (and any renderer 700 * that reads it). Independent of {@link #render}. */ 701 public String href; 702 703 /** How the value is painted. <jk>null</jk> means {@link FieldFormat#TEXT}. */ 704 public FieldFormat format; 705 706 /** How many of the grid's columns this field occupies. <jk>null</jk> means {@link FieldSpan#ONE}. */ 707 public FieldSpan span; 708 709 /** 710 * Action ids painted beside this field's value. Ids only — the bar itself is rendered by the 711 * client helper, not by this bean. 712 */ 713 public List<String> actions; 714 715 /** 716 * Creates a field bound to the specified values-map key. 717 * 718 * @param data The {@code ctx.data} key. Must not be <jk>null</jk> or blank. 719 * @return A new {@link Field}. 720 */ 721 public static Field of(String data) { 722 if (ib(data)) 723 throw iaex("RegionDef.Field data must not be null or blank."); 724 var f = new Field(); 725 f.data = data; 726 return f; 727 } 728 729 /** 730 * Sets the label. 731 * 732 * @param value The label. An empty string suppresses it (full-width markdown/sanitizedHtml body). 733 * @return This object. 734 */ 735 public Field label(String value) { 736 label = value; 737 return this; 738 } 739 740 /** 741 * Sets the named renderer id. 742 * 743 * @param value The renderer id. 744 * @return This object. 745 */ 746 public Field render(String value) { 747 render = value; 748 return this; 749 } 750 751 /** 752 * Sets the renderer's metadata. 753 * 754 * @param value The metadata. 755 * @return This object. 756 */ 757 public Field renderMeta(Map<String,Object> value) { 758 renderMeta = value; 759 return this; 760 } 761 762 /** 763 * Sets the declarative {@code {property}} URL template. 764 * 765 * @param value The template. 766 * @return This object. 767 */ 768 public Field href(String value) { 769 href = value; 770 return this; 771 } 772 773 /** 774 * Sets the paint format. 775 * 776 * @param value The format. <jk>null</jk> means {@link FieldFormat#TEXT}. 777 * @return This object. 778 */ 779 public Field format(FieldFormat value) { 780 format = value; 781 return this; 782 } 783 784 /** 785 * Sets the grid span. 786 * 787 * @param value The span. <jk>null</jk> means {@link FieldSpan#ONE}. 788 * @return This object. 789 */ 790 public Field span(FieldSpan value) { 791 span = value; 792 return this; 793 } 794 795 /** 796 * Sets the per-field action ids. 797 * 798 * @param value The action ids. 799 * @return This object. 800 */ 801 public Field actions(String...value) { 802 actions = l(value); 803 return this; 804 } 805 806 /** 807 * The rules that must all match for this one detail field to render. <jk>null</jk> or empty means always 808 * visible. See {@link RowAction#visibleWhen} for the shared semantics. 809 */ 810 public List<VisibilityRule> visibleWhen; 811 812 /** 813 * Hides this field unless every rule matches. 814 * 815 * @param rules The rules; all must match. Replaces any rules set by an earlier call. 816 * @return This object. 817 */ 818 public Field visibleWhen(VisibilityRule...rules) { 819 visibleWhen = l(rules); 820 return this; 821 } 822 823 /** 824 * Fail-closed validation of this one entry: a non-blank {@link #data}. 825 * 826 * @param regionId The enclosing region's id, for the error message only. 827 */ 828 void validate(String regionId) { 829 if (ib(data)) 830 throw iaex("RegionDef '%s' field data must not be null or blank.", regionId); 831 } 832 833 /** 834 * Serializes this entry to the compact JSON shape of the sidecar contract. 835 * 836 * @return An ordered {@link Map} ready for {@code Json.of(...)}. 837 */ 838 public Map<String,Object> toContractMap() { 839 var m = new LinkedHashMap<String,Object>(); 840 m.put("data", data); 841 if (label != null) 842 m.put("label", label); 843 if (render != null) 844 m.put("render", render); 845 if (renderMeta != null && !renderMeta.isEmpty()) 846 m.put("renderMeta", renderMeta); 847 if (href != null) 848 m.put("href", href); 849 if (format != null && format != FieldFormat.TEXT) 850 m.put("format", format.wire()); 851 if (span == FieldSpan.FULL) 852 m.put("span", "full"); 853 if (actions != null && !actions.isEmpty()) 854 m.put("actions", actions); 855 if (visibleWhen != null && !visibleWhen.isEmpty()) 856 m.put("visibleWhen", VisibilityRule.toMaps(visibleWhen)); 857 return m; 858 } 859 } 860}