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.console.*; 024import org.apache.juneau.marshall.collections.*; 025 026/** 027 * One ribbon (toolbar) entry above a table. 028 * 029 * <p> 030 * The ribbon runtime ({@code juneau-ribbon.js}) implements every behavior; this type only names it and carries its 031 * parameters. {@link #toMap()} produces the same {@code {type, ...}} entry the runtime reads from {@code viewDef.ribbon}. 032 * 033 * <p> 034 * Setters are not gated per item type, but {@link #toMap()} fails loudly rather than emit a key the runtime ignores 035 * for that type (for example {@code form} on a {@code refresh}, or {@code symbol} on an {@code optionGroup}), and 036 * checks the invariants the runtime cannot: a top-level {@code option} needs {@code column} or {@code param} (exactly 037 * one) plus a {@code value}, and a group's {@code default} must name a member. Group members take only 038 * {@code id}, {@code title}, {@code symbol}, {@code column}, {@code param} and {@code value}. 039 * 040 * <h2 class='section'>Example:</h2> 041 * <p class='bjava'> 042 * <jv>table</jv>.ribbon( 043 * RibbonItem.<jsm>collapseAll</jsm>(), 044 * RibbonItem.<jsm>export</jsm>(<js>"copy"</js>, <js>"csv"</js>).optional(<js>"excel"</js>, <js>"pdf"</js>), 045 * RibbonItem.<jsm>option</jsm>(<js>"dropped-only"</js>).title(<js>"Dropped only"</js>).column(<js>"status"</js>).value(<js>"$eq(DROPPED)"</js>).persist(<jk>true</jk>), 046 * RibbonItem.<jsm>optionGroup</jsm>(<js>"phase"</js>, 047 * RibbonItem.<jsm>option</jsm>(<js>"pending"</js>).column(<js>"phase"</js>).value(<js>"$in(Waiting)"</js>), 048 * RibbonItem.<jsm>option</jsm>(<js>"done"</js>).column(<js>"phase"</js>).value(<js>"$in(Completed)"</js>) 049 * ).defaultOption(<js>"pending"</js>), 050 * RibbonItem.<jsm>dialog</jsm>(<js>"add"</js>).title(<js>"Add repo"</js>).form(<js>"/rest/skill-repos/add-modal"</js>) 051 * .endpoint(<js>"/rest/skill-repos/new"</js>).method(RowAction.Method.<jsf>POST</jsf>) 052 * .onSuccess(RowAction.OnSuccess.<jsf>REDRAW</jsf>), 053 * RibbonItem.<jsm>refresh</jsm>()); 054 * 055 * RibbonItem.<jsm>refresh</jsm>().title(<js>"Refresh tasks"</js>).target(<js>"tasks"</js>); 056 * RibbonItem.<jsm>publish</jsm>(<js>"Focus east"</js>, <js>"app.region-picked"</js>, Map.<jsm>of</jsm>(<js>"region"</js>, <js>"east"</js>)); 057 * </p> 058 * 059 * @since 10.0.0 060 */ 061@SuppressWarnings({ 062 "java:S1192", // Repeated literals are contract wire keys; named constants would obscure the contract shape. 063 "java:S3776" // Validation and rendering chains many independent guards; splitting them adds no clarity. 064}) 065public final class RibbonItem implements Handled<RibbonItem> { 066 067 private static final List<String> EXPORT_BUTTONS = List.of("copy", "csv", "print", "excel", "pdf"); 068 private static final List<String> EXPORT_OPTIONAL = List.of("excel", "pdf"); 069 private static final List<String> APPEARANCES = List.of("icon"); 070 071 // The keys juneau-ribbon.js reads for each item type (everything else is ignored there, so toMap() rejects it). 072 private static final Set<String> COMMON = Set.of("type", "id", "title", "group", "appearance", "symbol", "visibleWhen", "model"); 073 private static final Map<String,Set<String>> ALLOWED = Map.ofEntries( 074 Map.entry("refresh", union(COMMON, "target")), 075 Map.entry("collapseAll", union(COMMON, "target")), 076 Map.entry("pausePolling", union(COMMON, "target")), 077 Map.entry("resetDefaults", COMMON), 078 Map.entry("search", Set.of("type", "id", "title", "group", "visibleWhen", "model")), 079 Map.entry("linkButton", COMMON), 080 Map.entry("columnSettings", COMMON), 081 Map.entry("dialog", union(COMMON, "form", "endpoint", "method", "onSuccess")), 082 Map.entry("export", Set.of("type", "id", "group", "appearance", "buttons", "optional", "visibleWhen", "model")), 083 Map.entry("option", union(COMMON, "column", "param", "value", "persist", "default", "target")), 084 Map.entry("optionGroup", Set.of("type", "id", "title", "group", "appearance", "persist", "default", "deselectable", "options", "target", "visibleWhen", "model")), 085 Map.entry("publish", union(COMMON, "topic", "payload")), 086 Map.entry("action", Set.of("type", "id", "icon", "label", "title", "appearance", "optional", "visibleWhen", "model")), 087 Map.entry("divider", Set.of("type", "visibleWhen", "model")) 088 ); 089 private static final java.util.regex.Pattern CARD_ID = java.util.regex.Pattern.compile("^[A-Za-z][A-Za-z0-9_-]{0,63}$"); 090 private static final Set<String> MEMBER_ALLOWED = Set.of("id", "title", "symbol", "column", "param", "value"); 091 092 private final String type; 093 private String id; 094 private boolean idExplicit; 095 private String icon; 096 private String label; 097 private final ModelBlock model; 098 private String title; 099 private String group; 100 private String appearance; 101 private String symbol; 102 private String form; 103 private String endpoint; 104 private String method; 105 private String onSuccess; 106 private List<String> buttons; 107 private List<String> optional; 108 private String column; 109 private String param; 110 private String value; 111 private Boolean persist; 112 private Object dflt; // Boolean for an option, String (member id) for an optionGroup. 113 private Boolean deselectable; 114 private List<RibbonItem> options; 115 private String target; 116 private List<VisibilityRule> visibleWhen; 117 private String topic; 118 private Map<String,Object> payload; 119 120 private RibbonItem(String type) { 121 this.type = type; 122 this.model = new ModelBlock("ribbonitem", type); 123 } 124 125 /** The stock item types whose id defaults to the type name; the same map the client applies. */ 126 static java.util.Map<String,String> defaultIds() { 127 var m = new java.util.LinkedHashMap<String,String>(); 128 for (var t : new String[]{"refresh", "collapseAll", "pausePolling", "resetDefaults", "export"}) 129 m.put(t, t); 130 m.put("search", "search"); 131 m.put("linkButton", "link"); 132 m.put("columnSettings", "columns"); 133 return m; 134 } 135 136 private static RibbonItem stockAs(String type, String defaultId) { 137 var r = new RibbonItem(type); 138 r.id = defaultId; 139 return r; 140 } 141 142 private static RibbonItem stock(String type) { 143 var r = new RibbonItem(type); 144 r.id = type; 145 return r; 146 } 147 148 @Override /* Handled */ 149 public ModelBlock modelBlock() { return model; } 150 151 @Override /* Handled */ 152 public RibbonItem self() { return this; } 153 154 /** 155 * A custom button whose click runs a handler declared with {@link #action(String,String,String)} or 156 * {@link #on(String,String)}. 157 * 158 * @param id The item's id. Must not be <jk>null</jk> or blank. 159 * @return A new {@link RibbonItem}. 160 * @throws IllegalArgumentException If {@code id} is <jk>null</jk> or blank. 161 */ 162 public static RibbonItem action(String id) { 163 if (ib(id)) 164 throw iaex("RibbonItem action id must not be null or blank."); 165 var r = new RibbonItem("action"); 166 r.id = id; 167 r.idExplicit = true; 168 return r; 169 } 170 171 /** 172 * Sets the icon of an {@code action} item. 173 * 174 * @param v The icon name. Can be <jk>null</jk> to unset. 175 * @return This object. 176 */ 177 public RibbonItem icon(String v) { 178 icon = v; 179 return this; 180 } 181 182 /** 183 * Sets the label of an {@code action} item. 184 * 185 * @param v The label. Can be <jk>null</jk> to unset. 186 * @return This object. 187 */ 188 public RibbonItem label(String v) { 189 label = v; 190 return this; 191 } 192 193 /** 194 * Validates a whole ribbon: every non-divider item has an id (a {@code publish} needs an explicit one), a second 195 * stock item of the same kind needs an explicit id, and ids are unique. 196 * 197 * @param tableId The owning table id, for messages. 198 * @param items The items, in order. 199 * @throws IllegalArgumentException If a rule is broken. 200 */ 201 static void validateList(String tableId, List<RibbonItem> items) { 202 var seen = new HashMap<String,Integer>(); 203 for (var i = 0; i < items.size(); i++) { 204 var it = items.get(i); 205 if ("divider".equals(it.type)) 206 continue; 207 if (it.id == null) 208 throw iaex("table '%s' ribbon item %s: a %s item needs an explicit id(...).", tableId, i, it.type); 209 var prev = seen.put(it.id, i); 210 if (prev != null) { 211 if (! it.idExplicit) 212 throw iaex("table '%s' ribbon item %s: a second %s item (also item %s) needs an explicit id(...).", tableId, i, it.type, prev); 213 throw iaex("table '%s' ribbon item %s: duplicate id '%s' (also item %s).", tableId, i, it.id, prev); 214 } 215 } 216 } 217 218 /** 219 * The table's search box. A slot the runtime fills with the table's search field; it takes no symbol or appearance. 220 * 221 * @return A new {@link RibbonItem}. 222 */ 223 public static RibbonItem search() { 224 return stockAs("search", "search"); 225 } 226 227 /** 228 * The copy-shareable-link button. 229 * 230 * @return A new {@link RibbonItem}. 231 */ 232 public static RibbonItem linkButton() { 233 return stockAs("linkButton", "link"); 234 } 235 236 /** 237 * The button that opens the column chooser (View Settings). 238 * 239 * @return A new {@link RibbonItem}. 240 */ 241 public static RibbonItem columnSettings() { 242 return stockAs("columnSettings", "columns"); 243 } 244 245 /** 246 * A visual separator between ribbon items; it also closes any open item cluster. 247 * 248 * @return A new {@link RibbonItem}. 249 */ 250 public static RibbonItem divider() { 251 return new RibbonItem("divider"); 252 } 253 254 /** 255 * The ribbon's reload-the-table button. 256 * 257 * @return A new {@link RibbonItem}. 258 */ 259 public static RibbonItem refresh() { 260 return stock("refresh"); 261 } 262 263 /** 264 * The ribbon's collapse-all-detail-rows button. 265 * 266 * @return A new {@link RibbonItem}. 267 */ 268 public static RibbonItem collapseAll() { 269 return stock("collapseAll"); 270 } 271 272 /** 273 * The ribbon's pause/resume auto-refresh toggle. 274 * 275 * @return A new {@link RibbonItem}. 276 */ 277 public static RibbonItem pausePolling() { 278 return stock("pausePolling"); 279 } 280 281 /** 282 * The ribbon's reset-to-defaults button: puts the table back on its built-in "Default" view (columns, sort, 283 * search and options) and applies it at once, with no dialog. 284 * 285 * <p> 286 * Consumers declare it in the {@code page} group. It acts on its own table only, so it takes no {@code target}. 287 * 288 * @return A new {@link RibbonItem}. 289 */ 290 public static RibbonItem resetDefaults() { 291 return stock("resetDefaults"); 292 } 293 294 /** 295 * The ribbon's export menu, offering the named buttons. 296 * 297 * <p> 298 * A button here is required: if its library is missing at runtime (JSZip for {@code excel}, pdfMake for 299 * {@code pdf}) it renders disabled and logs an error. Use {@link #optional(String...)} for buttons that should 300 * simply be omitted when their library is absent. The menu may consist of optional buttons alone, but 301 * {@link #toMap()} rejects one with no buttons at all. 302 * 303 * @param buttons The required buttons, each one of {@code copy}, {@code csv}, {@code print}, {@code excel} or 304 * {@code pdf}. 305 * @return A new {@link RibbonItem}. 306 * @throws IllegalArgumentException If {@code buttons} names a button not in that set. 307 */ 308 public static RibbonItem export(String...buttons) { 309 for (var b : buttons) 310 checkOneOf(b, EXPORT_BUTTONS, "export button"); 311 var r = stock("export"); 312 r.buttons = buttons.length == 0 ? null : List.of(buttons); 313 return r; 314 } 315 316 /** 317 * A ribbon button that opens a modal dialog. 318 * 319 * @param actionId This item's stable id (also the dialog's logical name). Must not be <jk>null</jk> or blank. 320 * @return A new {@link RibbonItem}. 321 * @throws IllegalArgumentException If {@code actionId} is <jk>null</jk> or blank. 322 */ 323 public static RibbonItem dialog(String actionId) { 324 if (ib(actionId)) 325 throw iaex("RibbonItem dialog action id must not be null or blank."); 326 var r = new RibbonItem("dialog"); 327 r.id = actionId; 328 r.idExplicit = true; 329 return r; 330 } 331 332 /** 333 * A server-query toggle button. 334 * 335 * <p> 336 * Set exactly one of {@link #column(String)} (a BeanQuery {@code $}-expression {@link #value(String) value} 337 * against that column) or {@link #param(String)} (a URL query parameter). Checked by {@link #toMap()}. 338 * 339 * @param id The toggle's stable id. Must not be <jk>null</jk> or blank. 340 * @return A new {@link RibbonItem}. 341 * @throws IllegalArgumentException If {@code id} is <jk>null</jk> or blank. 342 */ 343 public static RibbonItem option(String id) { 344 if (ib(id)) 345 throw iaex("RibbonItem option id must not be null or blank."); 346 var r = new RibbonItem("option"); 347 r.id = id; 348 r.idExplicit = true; 349 return r; 350 } 351 352 /** 353 * A group of mutually exclusive {@link #option(String) option} toggles. 354 * 355 * <p> 356 * A member may omit {@code column}/{@code param}/{@code value}; selecting it then applies no filter (an "All" 357 * member). 358 * 359 * @param id The group's stable id. Must not be <jk>null</jk> or blank. 360 * @param members The members, each created by {@link #option(String)}. Must not be empty. 361 * @return A new {@link RibbonItem}. 362 * @throws IllegalArgumentException If {@code id} is <jk>null</jk> or blank, or {@code members} is empty or 363 * holds anything other than an {@code option}. 364 */ 365 public static RibbonItem optionGroup(String id, RibbonItem...members) { 366 if (ib(id)) 367 throw iaex("RibbonItem optionGroup id must not be null or blank."); 368 if (members.length == 0) 369 throw iaex("RibbonItem optionGroup '%s' requires at least one option.", id); 370 for (var m : members) 371 if (! "option".equals(m.type)) 372 throw iaex("RibbonItem optionGroup '%s' member must be an option, not '%s'.", id, m.type); 373 var r = new RibbonItem("optionGroup"); 374 r.id = id; 375 r.idExplicit = true; 376 r.options = List.of(members); 377 return r; 378 } 379 380 /** 381 * A ribbon button that publishes a message when clicked. The topic must be a custom topic declared in the 382 * page's {@code topics} or a card's {@code publishes}, or {@code cmd:<cardId>}; the console's wiring check 383 * enforces that. Rendered only on a console page (no bus, no button). 384 * 385 * @param title The button label. 386 * @param topic The topic to publish. 387 * @param payload A JSON-serializable payload, or <jk>null</jk> for <code>{}</code>. 388 * @return A new {@link RibbonItem}. 389 * @throws IllegalArgumentException If {@code title} or {@code topic} is <jk>null</jk> or blank. 390 */ 391 public static RibbonItem publish(String title, String topic, Map<String,Object> payload) { 392 if (ib(title)) 393 throw iaex("RibbonItem publish requires a title."); 394 if (ib(topic)) 395 throw iaex("RibbonItem publish '%s' requires a topic.", title); 396 var i = new RibbonItem("publish"); 397 i.title = title; 398 i.topic = topic; 399 i.payload = payload == null ? null : new LinkedHashMap<>(payload); 400 return i; 401 } 402 403 /** 404 * Sends this item's command to another card instead of its own table. Accepted on {@code refresh}, 405 * {@code collapseAll}, {@code pausePolling}, {@code option} and {@code optionGroup}; {@link #toMap()} rejects it 406 * elsewhere. 407 * 408 * @param cardId The target card id; the console's wiring check verifies it names a card that handles the op. 409 * @return This object. 410 * @throws IllegalArgumentException If {@code cardId} is not a valid card id. 411 */ 412 public RibbonItem target(String cardId) { 413 if (cardId == null || ! CARD_ID.matcher(cardId).matches()) 414 throw iaex("RibbonItem target '%s' must match ^[A-Za-z][A-Za-z0-9_-]{0,63}$.", cardId); 415 target = cardId; 416 return this; 417 } 418 419 /** 420 * Hides this item unless every rule matches the console's facts. Evaluated by the client; this only serializes the 421 * rules. Accepted on every item type; not on an {@code optionGroup} member. 422 * 423 * @param rules The rules, ANDed together. None clears them. 424 * @return This object. 425 */ 426 public RibbonItem visibleWhen(VisibilityRule...rules) { 427 if (rules == null || Arrays.stream(rules).anyMatch(Objects::isNull)) 428 throw iaex("RibbonItem visibleWhen rules must not be null."); 429 visibleWhen = rules.length == 0 ? null : List.of(rules); 430 return this; 431 } 432 433 /** 434 * Sets this item's stable id. 435 * 436 * <p> 437 * The id is emitted on the item's ribbon entry, where it is scoped to its card (it is not stamped as a DOM id). 438 * {@link #toMap()} rejects an id on the types the runtime ignores it for 439 * ({@code divider}). 440 * 441 * @param v The id. Must not be <jk>null</jk> or blank. 442 * @return This object. 443 * @throws IllegalArgumentException If {@code v} is <jk>null</jk> or blank. 444 */ 445 public RibbonItem id(String v) { 446 if (ib(v)) 447 throw iaex("RibbonItem %s id must not be null or blank.", type); 448 id = v; 449 idExplicit = true; 450 return this; 451 } 452 453 /** 454 * Sets this item's title/label text. 455 * 456 * <p> 457 * On an {@code optionGroup} the title is not drawn; it becomes the group's accessible name 458 * ({@code role="group"} with {@code aria-label}). 459 * 460 * @param v The title. Can be <jk>null</jk> to unset. 461 * @return This object. 462 */ 463 public RibbonItem title(String v) { 464 title = v; 465 return this; 466 } 467 468 /** 469 * Clusters this item with adjacent items sharing the same group name. 470 * 471 * <p> 472 * The toolbar's canonical group ids are {@code search}, {@code entity}, {@code filter}, {@code export}, 473 * {@code viewing}, {@code page} and {@code status}. Groups using them are sorted into that order among the slots they already 474 * occupy; groups with any other name keep their declared position. An ungrouped {@code refresh} joins the 475 * {@code page} group, last, when one exists. 476 * 477 * @param v The group name. Can be <jk>null</jk> to unset. 478 * @return This object. 479 */ 480 public RibbonItem group(String v) { 481 group = v; 482 return this; 483 } 484 485 /** 486 * Sets how this item's button is drawn. 487 * 488 * @param v The appearance; currently only {@code icon}. Can be <jk>null</jk> to unset. 489 * @return This object. 490 * @throws IllegalArgumentException If {@code v} is not a known appearance. 491 */ 492 public RibbonItem appearance(String v) { 493 if (v != null) 494 checkOneOf(v, APPEARANCES, "appearance"); 495 appearance = v; 496 return this; 497 } 498 499 /** 500 * Sets the icon name overriding this item's default icon. 501 * 502 * @param v The icon name. Can be <jk>null</jk> to unset. 503 * @return This object. 504 */ 505 public RibbonItem symbol(String v) { 506 symbol = v; 507 return this; 508 } 509 510 /** 511 * Sets the form-source URL supplying a dialog item's input fields. 512 * 513 * @param url The form URL. Can be <jk>null</jk> to unset. 514 * @return This object. 515 */ 516 public RibbonItem form(String url) { 517 form = url; 518 return this; 519 } 520 521 /** 522 * Sets the URL a dialog item's form submits to. 523 * 524 * @param url The endpoint URL. Can be <jk>null</jk> to unset. 525 * @return This object. 526 */ 527 public RibbonItem endpoint(String url) { 528 endpoint = url; 529 return this; 530 } 531 532 /** 533 * Sets the non-safe HTTP method a dialog item's form submits with. 534 * 535 * @param m The method. Must not be <jk>null</jk>. 536 * @return This object. 537 */ 538 public RibbonItem method(RowAction.Method m) { 539 if (m == null) 540 throw iaex("RibbonItem method must not be null."); 541 method = m.wire(); 542 return this; 543 } 544 545 /** 546 * Sets what the runtime does with a successful dialog submission. 547 * 548 * @param s The success behavior. Must not be <jk>null</jk>. 549 * @return This object. 550 */ 551 public RibbonItem onSuccess(RowAction.OnSuccess s) { 552 if (s == null) 553 throw iaex("RibbonItem onSuccess must not be null."); 554 onSuccess = s.wire(); 555 return this; 556 } 557 558 /** 559 * Adds export buttons that are omitted, rather than rendered disabled, when their library is absent. 560 * 561 * @param names The buttons, each {@code excel} or {@code pdf}. 562 * @return This object. 563 * @throws IllegalArgumentException If a name is not one of those, or is already a required button. 564 */ 565 public RibbonItem optional(String...names) { 566 for (var n : names) { 567 checkOneOf(n, EXPORT_OPTIONAL, "optional export button"); 568 if (buttons != null && buttons.contains(n)) 569 throw iaex("RibbonItem export button '%s' is both required and optional.", n); 570 } 571 optional = names.length == 0 ? null : List.of(names); 572 return this; 573 } 574 575 /** 576 * Scopes an {@code option} to a table column. 577 * 578 * @param name The row-data column name. Can be <jk>null</jk> to unset. 579 * @return This object. 580 */ 581 public RibbonItem column(String name) { 582 column = name; 583 return this; 584 } 585 586 /** 587 * Scopes an {@code option} to a URL query parameter. 588 * 589 * @param name The parameter name. Can be <jk>null</jk> to unset. 590 * @return This object. 591 */ 592 public RibbonItem param(String name) { 593 param = name; 594 return this; 595 } 596 597 /** 598 * Sets an {@code option}'s value: a BeanQuery {@code $}-expression for a {@link #column(String) column}-scoped 599 * option, or the raw parameter value for a {@link #param(String) param}-scoped one. 600 * 601 * @param v The value. Can be <jk>null</jk> to unset. 602 * @return This object. 603 */ 604 public RibbonItem value(String v) { 605 value = v; 606 return this; 607 } 608 609 /** 610 * Sets whether this option's (or group's) state is remembered across page loads. 611 * 612 * @param v Whether to persist. 613 * @return This object. 614 */ 615 public RibbonItem persist(boolean v) { 616 persist = v; 617 return this; 618 } 619 620 /** 621 * Marks an {@code option} as on until the user (or persisted state) says otherwise. 622 * 623 * @return This object. 624 */ 625 public RibbonItem defaultOn() { 626 dflt = Boolean.TRUE; 627 return this; 628 } 629 630 /** 631 * Selects an {@code optionGroup} member until the user (or persisted state) says otherwise. 632 * 633 * @param memberId The member's id; checked against the members by {@link #toMap()}. 634 * @return This object. 635 * @throws IllegalArgumentException If this item is a plain {@code option} (use {@link #defaultOn()}). 636 */ 637 public RibbonItem defaultOption(String memberId) { 638 if ("option".equals(type)) 639 throw iaex("RibbonItem option '%s' cannot take defaultOption(); use defaultOn().", id); 640 dflt = memberId; 641 return this; 642 } 643 644 /** 645 * Lets an {@code optionGroup}'s selected member be clicked again to deselect it. 646 * 647 * @param v Whether the group is deselectable. 648 * @return This object. 649 */ 650 public RibbonItem deselectable(boolean v) { 651 deselectable = v; 652 return this; 653 } 654 655 /** 656 * Builds this item's ribbon entry. 657 * 658 * @return The entry, {@code type} first, then only the keys that were set. 659 * @throws IllegalArgumentException If the item sets a key the runtime ignores for its type, a top-level 660 * {@code option} sets neither or both of {@code column} and {@code param} or no {@code value}, an 661 * {@code export} has no buttons, or a {@code default} does not suit the item (an {@code option} takes 662 * {@link #defaultOn()}; an {@code optionGroup} takes {@link #defaultOption(String)} naming a member), or a 663 * {@code target} is set on a type the runtime does not route. 664 */ 665 public JsonMap toMap() { 666 var m = toMap(true); 667 check(m, null); 668 return m; 669 } 670 671 private JsonMap toMap(boolean withType) { 672 var m = new JsonMap(); 673 if (withType) 674 m.put("type", type); 675 if (id != null) 676 m.put("id", id); 677 if (icon != null) 678 m.put("icon", icon); 679 if (label != null) 680 m.put("label", label); 681 if (title != null) 682 m.put("title", title); 683 if (group != null) 684 m.put("group", group); 685 if (appearance != null) 686 m.put("appearance", appearance); 687 if (symbol != null) 688 m.put("symbol", symbol); 689 if (topic != null) 690 m.put("topic", topic); 691 if (payload != null) 692 m.put("payload", payload); 693 if (target != null) 694 m.put("target", target); 695 if (form != null) 696 m.put("form", form); 697 if (endpoint != null) 698 m.put("endpoint", endpoint); 699 if (method != null) 700 m.put("method", method); 701 if (onSuccess != null) 702 m.put("onSuccess", onSuccess); 703 if (buttons != null) 704 m.put("buttons", buttons); 705 if (optional != null) 706 m.put("optional", optional); 707 if (column != null) 708 m.put("column", column); 709 if (param != null) 710 m.put("param", param); 711 if (value != null) 712 m.put("value", value); 713 if (persist != null) 714 m.put("persist", persist); 715 if (dflt != null) 716 m.put("default", dflt); 717 if (deselectable != null) 718 m.put("deselectable", deselectable); 719 if (visibleWhen != null) 720 m.put("visibleWhen", VisibilityRule.toMaps(visibleWhen)); 721 if (options != null) { 722 m.put("options", new JsonList(options.stream().map(o -> o.toMap(false)).toList())); 723 } 724 var mm = model.toMap(); 725 if (mm != null) 726 m.put("model", mm); 727 return m; 728 } 729 730 /** 731 * Validates an authored ribbon item map (for example from a JSON5 card body) with exactly the rules 732 * {@link #toMap()} applies to a built item: a known {@code type}, only keys the runtime reads, an 733 * {@code export} with at least one valid button, an {@code option} with exactly one of {@code column} or 734 * {@code param} plus a {@code value}, a {@code default} that suits the item, a valid {@code appearance} and 735 * {@code target}, a well-formed {@code visibleWhen} (a list of {@code field}/{@code op} rules with a known op), and the same rules for each {@code optionGroup} member. 736 * 737 * @param item The authored item. Must not be <jk>null</jk>. 738 * @throws IllegalArgumentException If the item is not valid. 739 */ 740 public static void validate(Map<?,?> item) { 741 check(item, null); 742 } 743 744 // The one rule set behind toMap() and validate(). parentId is non-null only for an optionGroup member (a map with no 'type'). 745 private static void check(Map<?,?> m, String parentId) { 746 var isMember = parentId != null; 747 var t = m.get("type"); 748 var declaredType = t instanceof String ts ? ts : null; 749 var type = isMember ? "option" : declaredType; 750 if (! isMember && (type == null || ! ALLOWED.containsKey(type))) { 751 if (t == null) 752 throw iaex("RibbonItem requires a 'type'; one of '%s'.", String.join(", ", new TreeSet<>(ALLOWED.keySet()))); 753 if (! (t instanceof String)) 754 throw iaex("RibbonItem 'type' must be a string, not '%s'; one of '%s'.", t, String.join(", ", new TreeSet<>(ALLOWED.keySet()))); 755 throw iaex("RibbonItem type '%s' is not one of '%s'.", t, String.join(", ", new TreeSet<>(ALLOWED.keySet()))); 756 } 757 var id = m.get("id"); 758 if (! isMember) { 759 if ("export".equals(type)) { 760 if (m.get("buttons") == null && m.get("optional") == null) 761 throw iaex("RibbonItem export requires at least one button."); 762 checkAll(m.get("buttons"), EXPORT_BUTTONS, "export button"); 763 checkAll(m.get("optional"), EXPORT_OPTIONAL, "optional export button"); 764 } 765 if (m.get("appearance") != null) 766 checkOneOf(String.valueOf(m.get("appearance")), APPEARANCES, "appearance"); 767 if (m.get("target") != null && ! (m.get("target") instanceof String ts && CARD_ID.matcher(ts).matches())) 768 throw iaex("RibbonItem target '%s' must match ^[A-Za-z][A-Za-z0-9_-]{0,63}$.", m.get("target")); 769 } 770 if (isMember || "option".equals(type)) 771 checkScope(m, id, ! isMember); 772 if (! isMember && m.get("default") != null) 773 checkDefault(m, type, id); 774 if (! isMember && m.get("visibleWhen") != null) 775 checkVisibleWhen(m.get("visibleWhen"), type, id); 776 if ("optionGroup".equals(type) && m.get("options") != null) { 777 if (! (m.get("options") instanceof List<?> members)) 778 throw iaex("RibbonItem optionGroup '%s' options must be a list.", id); 779 for (var o : members) { 780 if (! (o instanceof Map<?,?> mm)) 781 throw iaex("RibbonItem optionGroup '%s' each option must be an object.", id); 782 check(mm, String.valueOf(id)); 783 } 784 } 785 var allowed = isMember ? MEMBER_ALLOWED : ALLOWED.get(type); 786 for (var k : m.keySet()) 787 if (! allowed.contains(String.valueOf(k))) { 788 if (isMember) 789 throw iaex("RibbonItem optionGroup '%s' member '%s' does not accept '%s'.", parentId, id, k); 790 throw iaex("RibbonItem %s%s does not accept '%s'.", type, id == null ? "" : " '" + id + "'", k); 791 } 792 } 793 794 private static void checkVisibleWhen(Object v, String type, Object id) { 795 var ok = v instanceof List<?> l && l.stream().allMatch(r -> r instanceof Map<?,?> rm 796 && rm.get("field") instanceof String f && ! f.isBlank() 797 && rm.get("op") instanceof String op && VisibilityRule.KNOWN_OPS.contains(op)); 798 if (! ok) 799 throw iaex("RibbonItem %s%s visibleWhen must be a list of {field, op[, value]} rules with a known op.", type, id == null ? "" : " '" + id + "'"); 800 } 801 802 private static void checkAll(Object v, List<String> allowed, String what) { 803 if (v == null) 804 return; 805 if (! (v instanceof List<?> l)) 806 throw iaex("RibbonItem %s list must be a list.", what); 807 for (var b : l) 808 checkOneOf(String.valueOf(b), allowed, what); 809 } 810 811 private static void checkScope(Map<?,?> m, Object id, boolean topLevel) { 812 var column = m.get("column"); 813 var param = m.get("param"); 814 if (column != null && param != null) 815 throw iaex("RibbonItem option '%s' sets both column '%s' and param '%s'.", id, column, param); 816 if (topLevel && column == null && param == null) 817 throw iaex("RibbonItem option '%s' sets neither column nor param.", id); 818 if (topLevel && m.get("value") == null) 819 throw iaex("RibbonItem option '%s' requires a value.", id); 820 } 821 822 private static void checkDefault(Map<?,?> m, String type, Object id) { 823 var d = m.get("default"); 824 if ("optionGroup".equals(type)) { 825 var ok = d instanceof String && m.get("options") instanceof List<?> l 826 && l.stream().anyMatch(o -> o instanceof Map<?,?> mm && d.equals(mm.get("id"))); 827 if (! ok) 828 throw iaex("RibbonItem optionGroup '%s' default '%s' is not one of its options.", id, d); 829 } else if ("option".equals(type) && ! Boolean.TRUE.equals(d)) { 830 throw iaex("RibbonItem option '%s' default '%s' must be on; use defaultOn().", id, d); 831 } 832 } 833 834 private static Set<String> union(Set<String> base, String...more) { 835 var s = new LinkedHashSet<>(base); 836 s.addAll(Arrays.asList(more)); 837 return Set.copyOf(s); 838 } 839 840 private static void checkOneOf(String v, List<String> allowed, String what) { 841 if (! allowed.contains(v)) 842 throw iaex("RibbonItem %s '%s' is not one of '%s'.", what, v, String.join(", ", allowed)); 843 } 844}