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.*; 022import java.util.logging.*; 023import java.util.regex.*; 024 025import org.apache.juneau.commons.beanquery.*; 026import org.apache.juneau.console.*; 027import org.apache.juneau.marshall.collections.*; 028import org.apache.juneau.marshall.marshaller.Json; 029import org.apache.juneau.console.widgets.Op; 030 031/** 032 * Java description of one datatables view: data source, columns, ribbon, row styling, row actions, row detail, 033 * selection and bulk actions. It replaces hand-written {@code <@card type="datatables">} JSON5 034 * for apps that build pages in Java, and {@link #toCardBody()} serializes to exactly the card body the FTL path 035 * produces. All behavior (paging, search, rendering, actions) stays in {@code juneau-views.js}; this type never 036 * calls a card-type handler directly — see the class's rendering note on {@link #toCardBody()}. 037 * 038 * <p> 039 * {@link Column#defaultVisible(boolean) Column.defaultVisible(false)} only hides a column when the client's 040 * {@code columnConfig} (juneau-config.js) is on. 041 * 042 * <h2 class='section'>Example:</h2> 043 * <p class='bjava'> 044 * TableSpec <jv>t</jv> = TableSpec.<jsm>create</jsm>(<js>"slo"</js>) 045 * .rowType(SloPod.<jk>class</jk>) 046 * .dataUrl(<js>"/rest/slo/data"</js>) 047 * .defaultOrder(<js>"pod"</js>, TableSpec.Sort.<jsf>ASC</jsf>) 048 * .columns( 049 * Column.<jsm>create</jsm>(<js>"pod"</js>).label(<js>"Pod"</js>).className(<js>"ssc-id-cell"</js>), 050 * Column.<jsm>create</jsm>(<js>"incidentKey"</js>).label(<js>"Incident"</js>).render(<js>"linked"</js>).href(<js>"{incidentUrl}"</js>), 051 * Column.<jsm>create</jsm>(<js>"rootCause"</js>).label(<js>"Root cause"</js>).defaultVisible(<jk>false</jk>)) 052 * .ribbon(RibbonItem.<jsm>refresh</jsm>(), RibbonItem.<jsm>export</jsm>(<js>"copy"</js>, <js>"csv"</js>)) 053 * .rowClass(<js>"analysisState"</js>, Op.<jsf>EQ</jsf>, <js>"degraded"</js>, <js>"row-degraded"</js>) 054 * .rowActions(RowAction.<jsm>create</jsm>(<js>"analyze"</js>).label(<js>"Analyze pod"</js>) 055 * .endpoint(<js>"/rest/slo/analyze"</js>).method(RowAction.Method.<jsf>POST</jsf>)) 056 * .detail(RowDetail.<jsm>create</jsm>(<js>"/rest/slo/data/{id}"</js>).title(<js>"{pod}"</js>) 057 * .region(RegionDef.<jsm>create</jsm>(<js>"slo-detail"</js>).populate(<js>"slo-detail"</js>))); 058 * <jv>t</jv>.validate(); 059 * Map<String,Object> <jv>body</jv> = <jv>t</jv>.toCardBody(); // the unwrapped catalog 060 * </p> 061 * 062 * @since 10.0.0 063 */ 064@SuppressWarnings({ 065 "java:S1192", // Duplicated literals read more clearly inline than as constants. 066 "java:S3776" // Validation and rendering chains many independent guards; splitting them adds no clarity. 067}) 068public final class TableSpec implements Handled<TableSpec> { 069 070 /** Where a view's rows come from. Wire tokens are lowercase. */ 071 public enum DataMode { 072 073 /** Paging, sorting and search run client-side, against the full {@code dataUrl} payload. */ 074 CLIENT("client"), 075 076 /** Paging, sorting and search are delegated to {@code dataUrl} on every draw. */ 077 SERVER("server"); 078 079 private final String wire; 080 081 DataMode(String wire) { 082 this.wire = wire; 083 } 084 085 /** @return The lowercase wire token. */ 086 public String wire() { 087 return wire; 088 } 089 } 090 091 /** A default-sort direction. Wire tokens are lowercase. */ 092 public enum Sort { 093 094 /** Ascending. */ 095 ASC("asc"), 096 097 /** Descending. */ 098 DESC("desc"); 099 100 private final String wire; 101 102 Sort(String wire) { 103 this.wire = wire; 104 } 105 106 /** @return The lowercase wire token. */ 107 public String wire() { 108 return wire; 109 } 110 } 111 112 /** Id grammar shared with cards and nav nodes. Mirrors {@code $defs/id} in {@code juneau-page.schema.json}. */ 113 private static final Set<String> URL_STATE_BUILTINS = Set.of("day", "ids", "window"); 114 private static final Pattern ID_PATTERN = Pattern.compile("^[A-Za-z][A-Za-z0-9_-]{0,63}$"); 115 116 private static final Logger LOG = Logger.getLogger(TableSpec.class.getName()); 117 118 private final String id; 119 private String rowType; 120 private String dataUrl; 121 private DataMode dataMode; 122 private final List<JsonMap> defaultOrder = new ArrayList<>(); 123 private final List<Column> columns = new ArrayList<>(); 124 private SearchOperatorSet operators; 125 private boolean noSearchTypesWarned; 126 private final List<RibbonItem> ribbon = new ArrayList<>(); 127 private final List<JsonMap> rowClassRules = new ArrayList<>(); 128 private final List<RowAction> rowActions = new ArrayList<>(); 129 private RowDetail detail; 130 private SelectionDef selection; 131 private String rowIdField; 132 private BulkMutateDef bulk; 133 private Long pollIntervalMs; 134 private String columnSearchHelpUrl; 135 private String quickStatsId; 136 private List<QuickStat> quickStats; 137 private boolean primary; 138 private Object columnConfig; 139 private Boolean copyLink; 140 private Boolean savedViewsInRibbon; 141 private Boolean cleanAddress; 142 private Boolean pausePollingWhileEditing; 143 private String cssClass; 144 private final Map<String,Map<String,Object>> urlState = new LinkedHashMap<>(); 145 146 private final ModelBlock model; 147 148 private TableSpec(String id) { 149 this.id = id; 150 this.model = new ModelBlock("table", id); 151 } 152 153 @Override /* Handled */ 154 public ModelBlock modelBlock() { return model; } 155 156 @Override /* Handled */ 157 public TableSpec self() { return this; } 158 159 /** @return Whether this table, its row detail or any of its ribbon items holds an inline handler reference. */ 160 public boolean hasInlineHandlers() { 161 return model.hasInline() || ribbon.stream().anyMatch(r -> r.modelBlock().hasInline()) || (detail != null && detail.modelBlock().hasInline()); 162 } 163 164 /** 165 * Starts a new table definition. 166 * 167 * @param id The table's card id. Must not be <jk>null</jk> or blank, and must match 168 * {@code ^[A-Za-z][A-Za-z0-9_-]{0,63}$}. 169 * @return A new {@link TableSpec}, with no columns or {@code dataUrl} yet set. 170 * @throws IllegalArgumentException If {@code id} is <jk>null</jk>, blank, or malformed. 171 */ 172 public static TableSpec create(String id) { 173 if (ib(id)) 174 throw iaex("TableSpec id must not be null or blank."); 175 if (! ID_PATTERN.matcher(id).matches()) 176 throw iaex("TableSpec id '%s' must match ^[A-Za-z][A-Za-z0-9_-]{0,63}$.", id); 177 return new TableSpec(id); 178 } 179 180 /** 181 * Sets the row type by its simple name, as {@code TableCatalog} did — documentation metadata only; it has no 182 * effect on rendering or validation. 183 * 184 * @param type The row type. Can be <jk>null</jk> to unset. 185 * @return This object. 186 */ 187 public TableSpec rowType(Class<?> type) { 188 rowType = type == null ? null : type.getSimpleName(); 189 return this; 190 } 191 192 /** 193 * Sets the row type by name directly. 194 * 195 * @param name The row type name. Can be <jk>null</jk> to unset. 196 * @return This object. 197 */ 198 public TableSpec rowType(String name) { 199 rowType = name; 200 return this; 201 } 202 203 /** 204 * Sets the table's data source URL. 205 * 206 * @param url The URL. Required by {@link #validate()}. 207 * @return This object. 208 */ 209 public TableSpec dataUrl(String url) { 210 dataUrl = url; 211 return this; 212 } 213 214 /** 215 * Sets whether paging/sorting/search run client-side or against {@code dataUrl} on every draw. 216 * 217 * @param mode The mode. Defaults to {@link DataMode#CLIENT} when never called (omitted from the wire, since 218 * {@code juneau-views.js} already defaults to client mode). 219 * @return This object. 220 */ 221 public TableSpec dataMode(DataMode mode) { 222 dataMode = mode; 223 return this; 224 } 225 226 /** 227 * Appends one default sort column. Repeatable — later calls add secondary sort keys. 228 * 229 * @param column The column name. Must not be <jk>null</jk> or blank. 230 * @param dir The sort direction. Must not be <jk>null</jk>. 231 * @return This object. 232 * @throws IllegalArgumentException If {@code column} is <jk>null</jk>/blank, or {@code dir} is <jk>null</jk>. 233 */ 234 public TableSpec defaultOrder(String column, Sort dir) { 235 if (ib(column)) 236 throw iaex("TableSpec defaultOrder column must not be null or blank."); 237 if (dir == null) 238 throw iaex("TableSpec defaultOrder direction must not be null."); 239 var m = new JsonMap(); 240 m.put("key", column); 241 m.put("dir", dir.wire()); 242 defaultOrder.add(m); 243 return this; 244 } 245 246 /** 247 * Appends columns, in display order. 248 * 249 * @param cols The columns. Must not be <jk>null</jk>. 250 * @return This object. 251 * @throws IllegalArgumentException If {@code cols} names a {@link Column#name()} already appended by an 252 * earlier call. 253 */ 254 public TableSpec columns(Column...cols) { 255 for (var c : cols) { 256 for (var existing : columns) 257 if (existing.name().equals(c.name())) 258 throw iaex("TableSpec '%s' declares column '%s' twice.", id, c.name()); 259 columns.add(c); 260 } 261 return this; 262 } 263 264 /** 265 * Sets the table-level default {@link SearchOperatorSet}, inherited by any searchable column that declares 266 * none of its own. 267 * 268 * @param table The operator set. Can be <jk>null</jk> to clear it back to absent. 269 * @return This object. 270 */ 271 public TableSpec operators(SearchOperatorSet table) { 272 operators = table; 273 return this; 274 } 275 276 /** 277 * Appends ribbon (toolbar) items, in display order. 278 * 279 * @param items The items. Must not be <jk>null</jk>. 280 * @return This object. 281 */ 282 public TableSpec ribbon(RibbonItem...items) { 283 var next = new ArrayList<>(ribbon); 284 next.addAll(List.of(items)); 285 RibbonItem.validateList(id, next); 286 ribbon.addAll(List.of(items)); 287 return this; 288 } 289 290 /** 291 * Appends the ribbon items of a list, such as the result of {@link Ribbons.Standard#build()}. 292 * 293 * @param items The items. Must not be <jk>null</jk>. 294 * @return This object. 295 */ 296 public TableSpec ribbon(List<RibbonItem> items) { 297 return ribbon(items.toArray(RibbonItem[]::new)); 298 } 299 300 /** 301 * Appends a value-based row-class rule ({@code juneau-views.js}'s {@code evaluateRowClassRules}): 302 * a row whose {@code field} is {@link Op#EQ eq}/{@link Op#NE ne} the given value gets {@code cssClass} added 303 * to its {@code <tr>}. 304 * 305 * @param field The row-data field to test. Must not be <jk>null</jk> or blank. 306 * @param op The operator. Must be {@link Op#EQ} or {@link Op#NE}. 307 * @param value The comparison value. Must not be <jk>null</jk>. 308 * @param cssClass The CSS class to add on a match (serialized as the wire key {@code class}). Must not be 309 * <jk>null</jk> or blank. 310 * @return This object. 311 * @throws IllegalArgumentException If any argument is missing, or {@code op} does not take a value. 312 */ 313 public TableSpec rowClass(String field, Op op, Object value, String cssClass) { 314 checkRowClassCommon(field, op, cssClass); 315 if (! op.requiresValue()) 316 throw iaex("TableSpec '%s' rowClass on '%s': op '%s' takes no value.", id, field, op.wire()); 317 if (value == null) 318 throw iaex("TableSpec '%s' rowClass on '%s': op '%s' requires a value.", id, field, op.wire()); 319 var m = new JsonMap(); 320 m.put("field", field); 321 m.put("op", op.wire()); 322 m.put("value", value); 323 m.put("class", cssClass); 324 rowClassRules.add(m); 325 return this; 326 } 327 328 /** 329 * Appends a presence-based row-class rule: a row whose {@code field} is {@link Op#PRESENT present}/ 330 * {@link Op#ABSENT absent} gets {@code cssClass} added to its {@code <tr>}. 331 * 332 * @param field The row-data field to test. Must not be <jk>null</jk> or blank. 333 * @param op The operator. Must be {@link Op#PRESENT} or {@link Op#ABSENT}. 334 * @param cssClass The CSS class to add on a match (serialized as the wire key {@code class}). Must not be 335 * <jk>null</jk> or blank. 336 * @return This object. 337 * @throws IllegalArgumentException If any argument is missing, or {@code op} requires a value. 338 */ 339 public TableSpec rowClass(String field, Op op, String cssClass) { 340 checkRowClassCommon(field, op, cssClass); 341 if (op.requiresValue()) 342 throw iaex("TableSpec '%s' rowClass on '%s': op '%s' requires a value.", id, field, op.wire()); 343 var m = new JsonMap(); 344 m.put("field", field); 345 m.put("op", op.wire()); 346 m.put("class", cssClass); 347 rowClassRules.add(m); 348 return this; 349 } 350 351 private void checkRowClassCommon(String field, Op op, String cssClass) { 352 if (ib(field)) 353 throw iaex("TableSpec '%s' rowClass field must not be null or blank.", id); 354 if (op == null) 355 throw iaex("TableSpec '%s' rowClass op must not be null.", id); 356 if (op.isCollectionOp()) 357 throw iaex("TableSpec '%s' rowClass on '%s': op '%s' is not supported; use eq, ne, present or absent.", id, field, op.wire()); 358 if (ib(cssClass)) 359 throw iaex("TableSpec '%s' rowClass cssClass must not be null or blank.", id); 360 } 361 362 /** 363 * Appends row actions, in menu order. 364 * 365 * @param actions The actions. Must not be <jk>null</jk>. 366 * @return This object. 367 */ 368 public TableSpec rowActions(RowAction...actions) { 369 rowActions.addAll(List.of(actions)); 370 return this; 371 } 372 373 /** 374 * Appends row actions from a list, in menu order. 375 * 376 * @param actions The actions. Must not be <jk>null</jk>. 377 * @return This object. 378 */ 379 public TableSpec rowActions(List<RowAction> actions) { 380 rowActions.addAll(actions); 381 return this; 382 } 383 384 /** 385 * Sets the per-row detail panel. 386 * 387 * @param value The detail config. Can be <jk>null</jk> to clear it. 388 * @return This object. 389 */ 390 public TableSpec detail(RowDetail value) { 391 detail = value == null ? null : value.copy(); 392 return this; 393 } 394 395 /** 396 * Sets the row-selection opt-in. 397 * 398 * @param value The selection config. Can be <jk>null</jk> to clear it. 399 * @return This object. 400 */ 401 public TableSpec selection(SelectionDef value) { 402 selection = value; 403 return this; 404 } 405 406 /** 407 * Sets the row-id field without enabling selection. 408 * 409 * <p> 410 * Names the row-data key that identifies each row, so a {@link #detail(RowDetail) row detail} can address its row 411 * on a table that has no selection column. The detail resolves its row id from this field first, then from the 412 * {@link #selection(SelectionDef) selection}'s row-id field, then from a column named <js>"id"</js> or 413 * <js>"name"</js>. When a selection is also set, both must name the same field. 414 * 415 * @param value The row-data key. Can be <jk>null</jk> to clear it. 416 * @return This object. 417 */ 418 public TableSpec rowIdField(String value) { 419 rowIdField = value; 420 return this; 421 } 422 423 /** 424 * Sets the bulk-mutate opt-in. Requires {@link #selection(SelectionDef)} to also be set. 425 * 426 * @param value The bulk config. Can be <jk>null</jk> to clear it. 427 * @return This object. 428 */ 429 public TableSpec bulk(BulkMutateDef value) { 430 bulk = value; 431 return this; 432 } 433 434 /** 435 * Sets the help link shown in the column-search popover. 436 * 437 * @param v An {@code http(s)} URL or a root-relative path. 438 * @return This object. 439 * @throws IllegalArgumentException If {@code v} is blank or uses any other scheme. 440 */ 441 public TableSpec columnSearchHelpUrl(String v) { 442 if (ib(v) || ! (v.startsWith("https://") || v.startsWith("http://") || (v.startsWith("/") && ! v.startsWith("//")))) 443 throw iaex("TableSpec '%s' columnSearchHelpUrl must be an http(s) URL or a root-relative path, not '%s'.", id, v); 444 columnSearchHelpUrl = v; 445 return this; 446 } 447 448 /** 449 * Sets the auto-refresh poll interval. 450 * 451 * @param ms The interval in milliseconds. Must be positive. 452 * @return This object. 453 * @throws IllegalArgumentException If {@code ms} is not positive. 454 */ 455 public TableSpec pollIntervalMs(long ms) { 456 if (ms <= 0) 457 throw iaex("TableSpec '%s' pollIntervalMs must be positive.", id); 458 pollIntervalMs = ms; 459 return this; 460 } 461 462 /** 463 * Sets the table's quick-stats strip. 464 * 465 * @param id The strip's own id, serialized as {@code quickStats.id}. Must not be <jk>null</jk> or blank. 466 * @param items The tiles, in display order. Must not be empty. 467 * @return This object. 468 * @throws IllegalArgumentException If {@code id} is <jk>null</jk>/blank, or {@code items} is empty. 469 */ 470 public TableSpec quickStats(String id, QuickStat...items) { 471 if (ib(id)) 472 throw iaex("TableSpec quickStats id must not be null or blank."); 473 if (items.length == 0) 474 throw iaex("TableSpec quickStats requires at least one item."); 475 quickStatsId = id; 476 quickStats = List.of(items); 477 return this; 478 } 479 480 /** 481 * Declares URL-state directives this table's address bar carries, so their values reach the table's server requests. 482 * 483 * <p> 484 * Each name selects one of the built-in directives ({@code day}, {@code ids} or {@code window}); any other name is 485 * refused, because this method does not register codecs and the page contract only carries the built-ins. A name 486 * not yet declared is emitted as an empty configuration object, which means the directive's defaults; a name already 487 * declared keeps its configuration (for example a {@code day} param set by {@link #urlStateDayParam(String)}). This 488 * method never clears configuration. Directives are emitted in the order they were first declared. The call is 489 * atomic: every name is validated before any is declared, so if one is refused nothing is changed. 490 * 491 * @param names The directive names; each one of {@code day}, {@code ids} or {@code window}. 492 * @return This object. 493 * @throws IllegalArgumentException If a name is null, blank or not a built-in directive. 494 */ 495 public TableSpec urlState(String...names) { 496 for (var n : names) 497 checkUrlStateName(n); 498 for (var n : names) 499 urlState.putIfAbsent(n, new LinkedHashMap<>()); 500 return this; 501 } 502 503 /** 504 * Declares the {@code day} URL-state directive and names the request query parameter it sends the selected day under. 505 * 506 * <p> 507 * {@code urlState("day")} sends the day as a {@code day} parameter; this form is for a server whose parameter has 508 * another name. The directive is emitted as {@code urlState.day.param}, in the position {@code day} was first 509 * declared. Calling this again replaces the parameter name (the last call wins). 510 * 511 * @param param The query-parameter name; must match {@code ^[A-Za-z][A-Za-z0-9_-]{0,63}$}. 512 * @return This object. 513 * @throws IllegalArgumentException If {@code param} is null, blank, or malformed. 514 */ 515 public TableSpec urlStateDayParam(String param) { 516 if (ib(param)) 517 throw iaex("urlState day param must not be null or blank."); 518 checkUrlStateParam("day param", param); 519 urlState.computeIfAbsent("day", k -> new LinkedHashMap<>()).put("param", param); 520 return this; 521 } 522 523 /** 524 * Declares a URL-state directive together with its options. 525 * 526 * <p> 527 * This is the configurable form of {@link #urlState(String...)} for the three built-in directives; every option the 528 * client's built-in codecs accept can be expressed, so a page needs no hand-written map to configure one: 529 * <ul> 530 * <li>{@code ids} — {@code param} (request parameter name, default {@code ids}) and {@code max} (an integer 531 * >= 1, default 200). 532 * <li>{@code window} — {@code params}, a map that may hold {@code start} and/or {@code end} (the request 533 * parameter names, defaults {@code start}/{@code end}). 534 * <li>{@code day} — {@code param} (request parameter name, default {@code day}); same as 535 * {@link #urlStateDayParam(String)}. 536 * </ul> 537 * Any other directive name is refused: this method does not register codecs, and the page contract only carries the 538 * built-ins. 539 * 540 * <p> 541 * Restrictions (deliberate, so the wire contract and the builder agree): every parameter name must match 542 * {@code ^[A-Za-z][A-Za-z0-9_-]{0,63}$} (the same grammar as {@code day.param}), and {@code max} must be an integer 543 * (Integer, Long, Short or Byte) of at least 1. The client's own fallbacks for a falsy, string or fractional 544 * {@code max}, or for an unusual parameter name, are refused here rather than reproduced. The result is the same 545 * value an FTL page writes as {@code urlState: {ids:{param:'pid',max:50}}}. 546 * 547 * <p> 548 * <b>Merge, not replace.</b> The options are merged into any entry already declared for {@code name}: each option 549 * given here overwrites the same option declared earlier (the last call wins, as with {@link #urlStateDayParam(String)}), 550 * options not named here are kept, and {@code window.params} is merged key by key. Like {@link #urlState(String...)} 551 * this never clears configuration, and an empty map just declares the directive. The directive keeps the position it 552 * was first declared in. The call is atomic: if any option is refused, nothing is changed. 553 * 554 * @param name The directive name; one of {@code day}, {@code ids} or {@code window}. 555 * @param config The directive options; deep-copied, so later changes to the map have no effect. Must not be null. 556 * @return This object. 557 * @throws IllegalArgumentException If the name is null, blank or not a built-in directive, the config is null, or an option is unknown for a 558 * built-in directive, mistyped, or out of range (a parameter name that is malformed, a {@code max} that is not a 559 * positive integer, a {@code window.params} key other than {@code start}/{@code end}). 560 */ 561 @SuppressWarnings({ 562 "unchecked" // the only nested values are the Map<String,Object> copies checkUrlStateOption builds for window.params 563 }) 564 public TableSpec urlState(String name, Map<String,Object> config) { 565 checkUrlStateName(name); 566 if (config == null) 567 throw iaex("urlState '%s' config must not be null.", name); 568 var checked = new LinkedHashMap<String,Object>(); 569 for (var e : config.entrySet()) { 570 var key = e.getKey(); 571 if (ib(key)) 572 throw iaex("urlState '%s' option name must not be blank.", name); 573 checked.put(key, checkUrlStateOption(name, key, e.getValue())); 574 } 575 var target = urlState.computeIfAbsent(name, k -> new LinkedHashMap<>()); 576 checked.forEach((k, v) -> { 577 if ("window".equals(name) && "params".equals(k) && target.get(k) instanceof Map<?,?> old) { 578 var merged = new LinkedHashMap<String,Object>(); 579 old.forEach((ok, ov) -> merged.put((String)ok, ov)); 580 merged.putAll((Map<String,Object>)v); 581 target.put(k, merged); 582 } else { 583 target.put(k, v); 584 } 585 }); 586 return this; 587 } 588 589 private static void checkUrlStateName(String name) { 590 if (ib(name)) 591 throw iaex("urlState name must not be blank."); 592 if (! URL_STATE_BUILTINS.contains(name)) 593 throw iaex("urlState '%s' is not a built-in directive; expected day, ids or window.", name); 594 } 595 596 private static JsonMap copyUrlStateConfig(Map<String,Object> cfg) { 597 var out = new JsonMap(); 598 cfg.forEach((k, v) -> out.put(k, v instanceof Map<?,?> m ? new JsonMap(m) : v)); 599 return out; 600 } 601 602 private static Object checkUrlStateOption(String name, String key, Object value) { 603 switch (name) { 604 case "day": 605 if (! "param".equals(key)) 606 throw iaex("urlState day: unknown option '%s'; expected param.", key); 607 return checkUrlStateParam("day param", value); 608 case "ids": 609 if ("param".equals(key)) 610 return checkUrlStateParam("ids param", value); 611 if ("max".equals(key)) { 612 if (! (value instanceof Integer || value instanceof Long || value instanceof Short || value instanceof Byte) || ((Number)value).longValue() < 1) 613 throw iaex("urlState ids max must be a positive integer but was %s.", value); 614 return value; 615 } 616 throw iaex("urlState ids: unknown option '%s'; expected param or max.", key); 617 case "window": 618 if (! "params".equals(key)) 619 throw iaex("urlState window: unknown option '%s'; expected params.", key); 620 if (! (value instanceof Map<?,?> m)) 621 throw iaex("urlState window params must be a map of start/end parameter names but was %s.", value); 622 var out = new LinkedHashMap<String,Object>(); 623 for (var e : m.entrySet()) { 624 var k = e.getKey(); 625 if (! "start".equals(k) && ! "end".equals(k)) 626 throw iaex("urlState window params: unknown key '%s'; expected start or end.", k); 627 out.put((String)k, checkUrlStateParam("window params." + k, e.getValue())); 628 } 629 return out; 630 default: 631 throw iaex("urlState '%s' is not a built-in directive; expected day, ids or window.", name); 632 } 633 } 634 635 private static String checkUrlStateParam(String what, Object param) { 636 if (! (param instanceof String s) || ! ID_PATTERN.matcher(s).matches()) 637 throw iaex("urlState %s '%s' must match ^[A-Za-z][A-Za-z0-9_-]{0,63}$.", what, param); 638 return s; 639 } 640 641 /** 642 * Sets whether this table is the page's primary table (affects layout only). 643 * 644 * @param v The new value. 645 * @return This object. 646 */ 647 public TableSpec primary(boolean v) { 648 primary = v; 649 return this; 650 } 651 652 /** 653 * Sets whether this table offers the View Settings dialog (column chooser, search and sort settings). 654 * 655 * @param v The new value. 656 * @return This object. 657 */ 658 public TableSpec columnConfig(boolean v) { 659 columnConfig = v; 660 return this; 661 } 662 663 /** 664 * Sets the View Settings dialog options, serialized as the {@code columnConfig} object (for example 665 * {@code {"chooser": true}}). 666 * 667 * @param options The options, copied at call time. Must not be <jk>null</jk>. 668 * @return This object. 669 */ 670 public TableSpec columnConfig(Map<String,Object> options) { 671 columnConfig = new LinkedHashMap<>(rnn(options)); 672 return this; 673 } 674 675 /** 676 * Sets whether the table offers a copy-link control for its current view state. 677 * 678 * @param v The new value. 679 * @return This object. 680 */ 681 public TableSpec copyLink(boolean v) { 682 copyLink = v; 683 return this; 684 } 685 686 /** 687 * Sets whether the ribbon shows a saved-views drop-down (when the table has two or more views); on by default. 688 * 689 * @param v The new value. 690 * @return This object. 691 */ 692 public TableSpec savedViewsInRibbon(boolean v) { 693 savedViewsInRibbon = v; 694 return this; 695 } 696 697 /** 698 * Sets whether the browser address bar is cleaned of the table's view-state parameters. 699 * 700 * @param v The new value. 701 * @return This object. 702 */ 703 public TableSpec cleanAddress(boolean v) { 704 cleanAddress = v; 705 return this; 706 } 707 708 /** 709 * Sets whether polling pauses while an editing surface (an open detail row or action dialog) is bound to this table. 710 * 711 * @param v The new value. 712 * @return This object. 713 */ 714 public TableSpec pausePollingWhileEditing(boolean v) { 715 pausePollingWhileEditing = v; 716 return this; 717 } 718 719 /** 720 * Sets the CSS class applied to this table's card. It is carried on the card placement, not in the card body 721 * returned by {@link #toCardBody()}. 722 * 723 * @param value The class list. Can be <jk>null</jk> to unset. 724 * @return This object. 725 */ 726 public TableSpec cssClass(String value) { 727 cssClass = value; 728 return this; 729 } 730 731 /** @return This table's id. */ 732 public String id() { 733 return id; 734 } 735 736 /** @return The columns, in display order. */ 737 public List<Column> columns() { 738 return Collections.unmodifiableList(columns); 739 } 740 741 /** @return The row actions, in menu order. */ 742 public List<RowAction> rowActions() { 743 return Collections.unmodifiableList(rowActions); 744 } 745 746 /** @return The card CSS class, or <jk>null</jk>. */ 747 public String cssClass() { 748 return cssClass; 749 } 750 751 /** @return The per-row detail panel, if set. */ 752 public Optional<RowDetail> detail() { 753 return Optional.ofNullable(detail); 754 } 755 756 /** 757 * Validates this table. A duplicate column and a rowClass op/value mismatch are checked eagerly by 758 * {@link #columns(Column...)} and {@link #rowClass(String,Op,Object,String) rowClass}, and an unknown export button 759 * by {@link RibbonItem#export(String...)}, so none of those can be seen here. 760 * 761 * @throws IllegalStateException If any check fails. 762 */ 763 public void validate() { 764 if (ib(dataUrl)) 765 throw isex("TableSpec '%s' requires dataUrl.", id); 766 if (columns.isEmpty()) 767 throw isex("TableSpec '%s' requires at least one column.", id); 768 var names = columns.stream().map(Column::name).toList(); 769 for (var o : defaultOrder) 770 if (! names.contains(o.get("key"))) 771 throw isex("TableSpec '%s' defaultOrder column '%s' is not a column; columns: '%s'.", 772 id, o.get("key"), String.join(", ", names)); 773 for (var item : ribbon) { 774 var m = item.toMap(); 775 if ("dialog".equals(m.get("type")) && (m.get("form") == null || m.get("endpoint") == null)) 776 throw isex("TableSpec '%s' ribbon dialog '%s' requires form and endpoint.", id, m.get("id")); 777 } 778 var actionIds = new HashSet<String>(); 779 for (var a : rowActions) 780 if (! actionIds.add(a.id)) 781 throw isex("TableSpec '%s' declares row action '%s' twice.", id, a.id); 782 if (bulk != null && selection == null) 783 throw isex("TableSpec '%s' sets bulk without selection.", id); 784 if (rowIdField != null && ib(rowIdField)) 785 throw isex("TableSpec '%s' rowIdField must not be blank.", id); 786 if (rowIdField != null && selection != null && ! rowIdField.equals(selection.rowIdField())) 787 throw isex("TableSpec '%s' rowIdField '%s' differs from selection rowIdField '%s'.", id, rowIdField, selection.rowIdField()); 788 if (bulk != null && (bulk.actions == null || bulk.actions.isEmpty())) 789 throw isex("TableSpec '%s' sets bulk with no actions.", id); 790 for (var a : rowActions) 791 if (a.href == null && (a.endpoint == null || a.endpoint.isBlank())) 792 throw isex("TableSpec '%s' row action '%s' requires an endpoint.", id, a.id); 793 if (bulk != null && bulk.actions != null) 794 for (var a : bulk.actions) 795 if (a.endpoint == null || a.endpoint.isBlank()) 796 throw isex("TableSpec '%s' bulk action '%s' requires an endpoint.", id, a.id); 797 for (var c : columns) 798 if (c.searchable() && dataMode == DataMode.SERVER && c.operators() == null && operators == null) 799 throw isex("TableSpec '%s' column '%s' sets searchType but dataMode is '%s' and the table " 800 + "declares no operators.", id, c.name(), dataMode.wire()); 801 warnIfSearchWithoutTypes(); 802 } 803 804 // Dev-mode aid: a SERVER table with the search box but no typed column falls back to popover help that advertises 805 // operators the server rejects. Logged once per table; never throws and never runs outside dev mode. 806 private void warnIfSearchWithoutTypes() { 807 if (noSearchTypesWarned || dataMode != DataMode.SERVER || ! Boolean.getBoolean("juneau.console.devMode")) 808 return; 809 if (ribbon.stream().noneMatch(i -> "search".equals(i.toMap().get("type"))) || columns.stream().anyMatch(Column::searchable)) 810 return; 811 noSearchTypesWarned = true; 812 LOG.log(Level.WARNING, () -> "TableSpec '" + id + "' is SERVER mode with search on but no column declares a search type or operators; " 813 + "the column-search help will advertise operators the server rejects."); 814 } 815 816 /** 817 * Builds this table's catalog-form card body, with no {@code contractVersion} anywhere (the client stamps every 818 * contract version). This is the only place in this type that knows the datatables wire shape. The result is 819 * the unwrapped catalog the {@code datatables} card type reads, and is rendered the same single way 820 * {@code <@card>} is, by the page mixin's {@code cardTypes.toCard(CardSource.create("datatables", id()) 821 * .bodyMap(toCardBody()).build())}; this type never calls a card-type handler directly. 822 * 823 * <p> 824 * The body holds only plain data (maps, lists, strings, numbers, booleans), the same shape a parsed body has. 825 * 826 * <p> 827 * Each column carries its effective operator set (its own, else {@link #operators(SearchOperatorSet)}). 828 * 829 * @return The catalog, with keys in a fixed order and absent optional values omitted. 830 */ 831 public JsonMap toCardBody() { 832 var t = new JsonMap(); 833 t.put("dataUrl", dataUrl); 834 t.put("columns", plain(columns.stream().map(c -> c.toCatalogMap(operators)).toList())); 835 if (dataMode != null) 836 t.put("dataMode", dataMode.wire()); 837 if (! defaultOrder.isEmpty()) 838 t.put("defaultOrder", List.copyOf(defaultOrder)); 839 if (! ribbon.isEmpty()) 840 t.put("ribbon", ribbon.stream().map(RibbonItem::toMap).toList()); 841 if (rowType != null) 842 t.put("rowType", rowType); 843 if (pollIntervalMs != null) 844 t.put("pollIntervalMs", pollIntervalMs); 845 if (columnSearchHelpUrl != null) 846 t.put("columnSearchHelpUrl", columnSearchHelpUrl); 847 if (primary) 848 t.put("primary", true); 849 if (columnConfig != null) 850 t.put("columnConfig", columnConfig); 851 if (copyLink != null) 852 t.put("copyLink", copyLink); 853 if (savedViewsInRibbon != null && ! savedViewsInRibbon) 854 t.put("savedViewsInRibbon", false); 855 if (cleanAddress != null) 856 t.put("cleanAddress", cleanAddress); 857 if (pausePollingWhileEditing != null) 858 t.put("pausePollingWhileEditing", pausePollingWhileEditing); 859 if (! urlState.isEmpty()) { 860 var u = new JsonMap(); 861 urlState.forEach((n, cfg) -> u.put(n, copyUrlStateConfig(cfg))); 862 t.put("urlState", u); 863 } 864 if (! rowClassRules.isEmpty()) 865 t.put("rowClassRules", List.copyOf(rowClassRules)); 866 if (rowActions.stream().anyMatch(a -> a.href == null)) 867 t.put("rowActions", plain(rowActions.stream().filter(a -> a.href == null).toList())); 868 if (rowIdField != null) 869 t.put("rowIdField", rowIdField); 870 if (selection != null) { 871 var s = new JsonMap(); 872 s.put("rowIdField", selection.rowIdField()); 873 s.put("selectAll", selection.selectAll()); 874 s.put("scope", selection.scope().wire()); 875 if (selection.labelField() != null) 876 s.put("labelField", selection.labelField()); 877 if (selection.selectableWhen() != null) 878 s.put("selectableWhen", plain(selection.selectableWhen())); 879 t.put("selection", s); 880 } 881 if (bulk != null) { 882 var b = new JsonMap(); 883 b.put("actions", plain(bulk.actions)); 884 t.put("bulk", b); 885 } 886 if (detail != null) { 887 var detailRowIdField = rowIdField; 888 if (detailRowIdField == null && selection != null) 889 detailRowIdField = selection.rowIdField(); 890 t.put("detail", detail.toMap(id, columns, detailRowIdField)); 891 } 892 var mm = model.toMap(); 893 if (mm != null) 894 t.put("model", mm); 895 if (quickStats != null) { 896 var q = new JsonMap(); 897 q.put("id", quickStatsId); 898 q.put("items", quickStats.stream().map(QuickStat::toMap).toList()); 899 t.put("quickStats", q); 900 } 901 return t; 902 } 903 904 /** Converts a bean (or list of beans) to the plain maps, lists and scalars a parsed JSON body would hold. */ 905 private static Object plain(Object bean) { 906 return Json.to(Json.of(bean), Object.class); 907 } 908}