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.beanquery.*;
024import org.apache.juneau.marshall.collections.*;
025
026/**
027 * One datatable column's search configuration — its value {@link SearchType} and the optional
028 * per-column {@link SearchOperatorSet}.
029 *
030 * <h2 class='section'>Operator gating</h2>
031 * <p>
032 * A column's offerable operators are modeled by a single {@link SearchOperatorSet}, never a string allow-list or a
033 * separate custom-operator map.  A custom operator is simply a {@link SearchOperator} placed inside a set via
034 * {@link SearchOperatorSet#standard()}, {@link SearchOperatorSet#with(SearchOperator)}, or
035 * {@link SearchOperatorSet#of(SearchOperator...)}.
036 * <ul>
037 *    <li><b>Set absent</b> (default): the column offers the entire type-applicable {@link SearchOperatorSet#standard()
038 *       standard} universe (or, when resolved against a table, the table-level set &mdash; see {@link ViewDef}).
039 *    <li><b>Set present</b> ({@link #operators(SearchOperatorSet)}): the column's set entirely <b>replaces</b> the
040 *       table-level set for this column; the effective operators are that set's
041 *       {@link SearchOperatorSet#forType(SearchType) type-applicable} members.
042 * </ul>
043 * <p>
044 * An operator not on the effective set is a <b>reject</b> (the popup marks it invalid), never a silent rewrite
045 * &mdash; see {@link #offers(String)}.
046 *
047 * <h2 class='section'>Mutability</h2>
048 * <p>
049 * Deliberately mutable, like {@link ViewDef} and {@link RegionDef}: a {@link Column} is a server-side authoring
050 * bean built up once via fluent setters while constructing a view definition, not an
051 * immutable value object.  Callers must not mutate one concurrently from more than one thread, and must not reuse
052 * one across requests unless every request treats it as read-only after construction.
053 *
054 * <h2 class='section'>Example:</h2>
055 * <p class='bjava'>
056 *    <jc>// A searchable "status" column offering only $eq and $in, plus a custom "$mine" operator.</jc>
057 *    Column <jv>status</jv> = Column.<jsm>create</jsm>(<js>"status"</js>)
058 *       .label(<js>"Status"</js>)
059 *       .searchType(SearchType.<jsf>ID</jsf>)
060 *       .operators(SearchOperatorSet.<jsm>of</jsm>(
061 *          SearchOperatorSet.<jsm>standard</jsm>().get(<js>"$eq"</js>),
062 *          SearchOperatorSet.<jsm>standard</jsm>().get(<js>"$in"</js>),
063 *          SearchOperator.<jsm>create</jsm>(<js>"$mine"</js>, <js>"Assigned to me"</js>).types(SearchType.<jsf>ID</jsf>).build()));
064 * </p>
065 *
066 * <h2 class='section'>See Also:</h2>
067 * <ul>
068 *    <li class='jc'>{@link SearchOperator}
069 *    <li class='jc'>{@link SearchOperatorSet}
070 *    <li class='jc'>{@link ViewDef}
071 * </ul>
072 *
073 * @since 10.0.0
074 */
075@SuppressWarnings({
076   "java:S1168", // null (not an empty map) is the wire contract: a non-searchable column omits the search block; an empty map would read as searchable.
077   "java:S3776" // Validation and rendering chains many independent guards; splitting them adds no clarity.
078})
079public final class Column {
080
081   private final String name;
082   private String label;
083   private String description;
084   private SearchType searchType;
085   private SearchOperatorSet operators;  // null means "inherit the table-level set".
086   private Render render;
087   private String href;
088   private String className;
089   private boolean defaultVisible = true;
090   private boolean html;
091
092   private Column(String name) {
093      this.name = name;
094   }
095
096   /**
097    * Starts a new column definition.
098    *
099    * @param name The column name (matches the row-data key).  Must not be
100    *    <jk>null</jk> or blank.
101    * @return A new column, not searchable until a {@link #searchType(SearchType)} is set.
102    * @throws IllegalArgumentException If {@code name} is <jk>null</jk> or blank.
103    */
104   public static Column create(String name) {
105      req(inb(name), "Column name must not be null or blank.");
106      return new Column(name);
107   }
108
109   /**
110    * Sets the human-readable column label.
111    *
112    * @param value The label.  Can be <jk>null</jk>.
113    * @return This object.
114    */
115   public Column label(String value) {
116      label = value;
117      return this;
118   }
119
120   /**
121    * Sets optional help text for this column, shown in the View Settings dialog's detail strip when the column is
122    * selected.
123    *
124    * @param value The help text.  Can be <jk>null</jk> (no help text).
125    * @return This object.
126    */
127   public Column description(String value) {
128      description = value;
129      return this;
130   }
131
132   /**
133    * Sets the column's value type, which governs both leaf semantics and the offerable built-in operators.  A
134    * column with no search type is not searchable.
135    *
136    * @param value The value type.  Can be <jk>null</jk> to mark the column non-searchable.
137    * @return This object.
138    */
139   public Column searchType(SearchType value) {
140      searchType = value;
141      return this;
142   }
143
144   /**
145    * Sets this column's own {@link SearchOperatorSet} &mdash; it entirely replaces the table-level
146    * set for this column.
147    *
148    * @param value The operator set.  A <jk>null</jk> value clears it back to <i>absent</i> (inherit the table-level
149    *    set, or {@link SearchOperatorSet#standard()} when there is none).
150    * @return This object.
151    */
152   public Column operators(SearchOperatorSet value) {
153      operators = value;
154      return this;
155   }
156
157   /**
158    * Sets this column's cell renderer from the compact {@code "id:field"} string sugar.
159    *
160    * @param spec The render-id string, e.g. {@code "tag:status"}.  Must not be <jk>null</jk> or blank.
161    * @return This object.
162    */
163   public Column render(String spec) {
164      render = Render.parse(spec);
165      return this;
166   }
167
168   /**
169    * Sets this column's cell renderer.
170    *
171    * @param value The renderer.  Can be <jk>null</jk> to unset.
172    * @return This object.
173    */
174   public Column render(Render value) {
175      render = value;
176      return this;
177   }
178
179   /**
180    * Sets the row-data interpolation template this column's rendered cell links to.
181    *
182    * <p>
183    * An {@code href} with no {@link #render(String) render} implies {@code render("linked")}; the catalog entry
184    * ({@link #toCatalogMap()}) carries that render.  An explicit render always wins, whichever order the two are set in.
185    *
186    * @param template The href template, e.g. {@code "{incidentUrl}"}.  Can be <jk>null</jk> to unset.
187    * @return This object.
188    */
189   public Column href(String template) {
190      href = template;
191      return this;
192   }
193
194   /**
195    * Sets a CSS class applied to this column's cells.
196    *
197    * @param css The class name(s).  Can be <jk>null</jk> to unset.
198    * @return This object.
199    */
200   public Column className(String css) {
201      className = css;
202      return this;
203   }
204
205   /**
206    * Sets whether this column's cell values are rendered as raw HTML.
207    *
208    * <p>
209    * Defaults to <jk>false</jk>: a column without a {@link #render(Render) renderer} displays its values as escaped
210    * text. Only set this for columns whose values are trusted markup.
211    *
212    * @param v Whether cell values are raw HTML.
213    * @return This object.
214    */
215   public Column html(boolean v) {
216      html = v;
217      return this;
218   }
219
220   /**
221    * Sets whether this column starts visible.
222    *
223    * <p>
224    * Defaults to <jk>true</jk>; only {@code false} is ever emitted by {@link #toCatalogMap()}.
225    *
226    * <p>
227    * A {@code false} value only hides the column when the client's {@code columnConfig} (juneau-config.js) is on; without it
228    * the column stays visible.
229    *
230    * @param v Whether the column starts visible.
231    * @return This object.
232    */
233   public Column defaultVisible(boolean v) {
234      defaultVisible = v;
235      return this;
236   }
237
238   /**
239    * Builds this column's catalog entry: {@code key} and {@code label} (and {@code description} when set) plus the display ({@code render},
240    * {@code href}, {@code className}, {@code defaultVisible}) and search ({@code searchType},
241    * {@code searchOperators}, {@code customOperators}) metadata, flattened onto one entry, in the form the
242    * {@code datatables} card type resolves.
243    *
244    * <p>
245    * {@code searchOperators} is a list of operator <i>names</i> and {@code customOperators} a list of
246    * {@code {name,help}} maps for the custom ones.  Both are emitted only when this column has its own
247    * {@link #operators(SearchOperatorSet) operator set}; a column inheriting the table-level set emits just
248    * {@code searchType}, and a column with no search type emits neither.  See
249    * {@link #toCatalogMap(SearchOperatorSet)} to resolve the table-level set into the entry.
250    *
251    * <p>
252    * {@code label} falls back to {@link #name()} when unset.  A column with an {@code href} and no {@code render}
253    * emits {@code render} as the {@code linked} renderer.
254    *
255    * @return The catalog entry.
256    */
257   public JsonMap toCatalogMap() {
258      return toCatalogMap(null);
259   }
260
261   /**
262    * Builds this column's catalog entry like {@link #toCatalogMap()}, but emits the column's <i>effective</i>
263    * operator set: its own set if it has one, else {@code tableDefault}.
264    *
265    * <p>
266    * This is how a table-level set reaches the {@code datatables} card type, which reads operators per column.
267    * With no column set and a <jk>null</jk> {@code tableDefault}, only {@code searchType} is emitted.
268    *
269    * @param tableDefault The table-level operator set inherited by a column with none of its own.  Can be
270    *    <jk>null</jk>.
271    * @return The catalog entry.
272    */
273   public JsonMap toCatalogMap(SearchOperatorSet tableDefault) {
274      var m = new JsonMap();
275      m.put("key", name);
276      m.put("label", label != null ? label : name);
277      if (description != null)
278         m.put("description", description);
279      if (render != null)
280         m.put("render", render);
281      else if (href != null)
282         m.put("render", Render.of("linked"));
283      if (href != null)
284         m.put("href", href);
285      if (className != null)
286         m.put("className", className);
287      if (! defaultVisible)
288         m.put("defaultVisible", false);
289      if (html)
290         m.put("html", true);
291      if (searchType != null) {
292         m.put("searchType", searchType.wire());
293         var effective = operators != null ? operators : tableDefault;
294         if (effective != null) {
295            var names = new ArrayList<String>();
296            var customs = new ArrayList<Map<String,String>>();
297            for (var op : effective.forType(searchType)) {
298               names.add(op.name());
299               if (op.isCustom()) {
300                  var cm = new LinkedHashMap<String,String>();
301                  cm.put("name", op.name());
302                  cm.put("help", op.help());
303                  customs.add(cm);
304               }
305            }
306            m.put("searchOperators", names);
307            if (! customs.isEmpty())
308               m.put("customOperators", customs);
309         }
310      }
311      return m;
312   }
313
314   /** @return The column name. */
315   public String name() {
316      return name;
317   }
318
319   /** @return The column label, or <jk>null</jk>. */
320   public String label() {
321      return label;
322   }
323
324   /** @return The column help text, or <jk>null</jk>. */
325   public String description() {
326      return description;
327   }
328
329   /** @return The column value type, or <jk>null</jk> if the column is not searchable. */
330   public SearchType searchType() {
331      return searchType;
332   }
333
334   /**
335    * This column's own operator set, or <jk>null</jk> if absent (inherit the table-level set).
336    *
337    * @return The operator set, or <jk>null</jk>.
338    */
339   public SearchOperatorSet operators() {
340      return operators;
341   }
342
343   /** @return <jk>true</jk> if this column has a search type (and is therefore searchable). */
344   public boolean searchable() {
345      return searchType != null;
346   }
347
348   /**
349    * Resolves the effective operator set the header popup offers for this column, against the
350    * built-in {@link SearchOperatorSet#standard() standard} set as the fallback default.
351    *
352    * @return The effective operators, in the resolved set's order; empty when the column is not searchable.
353    */
354   public List<SearchOperator> effectiveOperators() {
355      return effectiveOperators(null);
356   }
357
358   /**
359    * Resolves the effective operator set the header popup offers for this column, inheriting the
360    * specified table-level set when this column has none of its own.
361    *
362    * @param tableDefault The table-level operator set to inherit when this column has none of its own.  Can be
363    *    <jk>null</jk>, in which case {@link SearchOperatorSet#standard()} is used.
364    * @return The effective operators, in the resolved set's order; empty when the column is not searchable.
365    */
366   public List<SearchOperator> effectiveOperators(SearchOperatorSet tableDefault) {
367      if (searchType == null)
368         return List.of();
369      var inherited = tableDefault != null ? tableDefault : SearchOperatorSet.standard();
370      var set = operators != null ? operators : inherited;
371      return set.forType(searchType);
372   }
373
374   /**
375    * Whether the named operator is on this column's effective set &mdash; i.e. whether the popup offers it (and
376    * accepts it rather than rejecting it as invalid).
377    *
378    * @param opName The operator name, including the leading {@code $}.  Can be <jk>null</jk>.
379    * @return <jk>true</jk> if the operator is offered for this column.
380    */
381   public boolean offers(String opName) {
382      if (opName == null)
383         return false;
384      for (var op : effectiveOperators())
385         if (op.name().equals(opName))
386            return true;
387      return false;
388   }
389
390   /**
391    * Builds the per-column {@code search} block for the {@code VIEW_META} wire contract
392    * directly from author-catalog inputs, without the caller having to touch the search-engine beans.
393    *
394    * <p>
395    * This is the entry point the chrome/authoring layer uses: it takes only the wire token, the optional
396    * allowed-operator names, and the custom operators as plain {@code {name,help}} maps &mdash; so a chrome-only
397    * module that must not depend on the search engine can still emit a column's search block by calling here.
398    * Internally this builds a single {@link SearchOperatorSet}: an allow-list becomes
399    * {@link SearchOperatorSet#of(SearchOperator...)} with exactly the named operators (customs preferred over
400    * same-named built-ins), while an absent allow-list becomes {@link SearchOperatorSet#standard()} with each
401    * custom appended via {@link SearchOperatorSet#with(SearchOperator)}.
402    *
403    * @param name The column name (row-data key).  Must not be <jk>null</jk> or blank.
404    * @param searchTypeWire The wire {@link SearchType} token, or <jk>null</jk>.
405    * @param operatorAllowList The explicit allowed-operator names, or <jk>null</jk> for the default
406    *    (the full type-applicable universe).
407    * @param customOperators Per-column custom operators as {@code {name,help}} maps; may be
408    *    <jk>null</jk> or empty.
409    * @return The {@code {type, operators:[...]}} block, or <jk>null</jk> when {@code searchTypeWire} names no known
410    *    type (a non-searchable column emits no search block).
411    */
412   @SuppressWarnings({
413      "java:S3776" // Allow-list vs. default branches with custom-operator merging read best inline.
414   })
415   public static JsonMap searchMeta(String name, String searchTypeWire, List<String> operatorAllowList, List<Map<String,String>> customOperators) {
416      var type = SearchType.fromWire(searchTypeWire);
417      if (type == null)
418         return null;
419      var customs = new LinkedHashMap<String,SearchOperator>();
420      if (customOperators != null)
421         for (var cm : customOperators)
422            customs.put(cm.get("name"), SearchOperator.create(cm.get("name"), cm.get("help")).types(type).build());
423      SearchOperatorSet set;
424      if (operatorAllowList != null) {
425         var ops = new ArrayList<SearchOperator>();
426         for (var n : operatorAllowList) {
427            var op = customs.get(n);
428            if (op == null)
429               op = SearchOperatorSet.standard().get(n);
430            if (op != null)
431               ops.add(op);
432         }
433         set = SearchOperatorSet.of(ops.toArray(new SearchOperator[0]));
434      } else {
435         set = SearchOperatorSet.standard();
436         for (var op : customs.values())
437            set = set.with(op);
438      }
439      return create(name).searchType(type).operators(set).searchMeta();
440   }
441
442   /**
443    * Serializes this column's effective search configuration to the {@code VIEW_META} {@code search} block: the wire
444    * {@link SearchType} token plus one entry per
445    * {@link #effectiveOperators() effective operator}, each carrying the metadata the header popup renders.
446    *
447    * <p>
448    * <c>help</c> is present only for custom operators; the popup supplies built-in help text from <c>juneau-search.js</c>.
449    *
450    * @return The {@code {type, operators:[{name,help,minArgs,maxArgs,combinator,custom}]}} block, or <jk>null</jk>
451    *    if this column is not searchable.
452    */
453   public JsonMap searchMeta() {
454      return searchMeta(null);
455   }
456
457   /**
458    * Serializes this column's effective search configuration to the {@code VIEW_META} {@code search} block, inheriting
459    * the specified table-level operator set when this column has none of its
460    * own.
461    *
462    * @param tableDefault The table-level operator set to inherit when this column has none of its own.  Can be
463    *    <jk>null</jk>, in which case {@link SearchOperatorSet#standard()} is used.
464    * @return The {@code {type, operators:[{name,help,minArgs,maxArgs,combinator,custom}]}} block, or <jk>null</jk>
465    *    if this column is not searchable.
466    */
467   public JsonMap searchMeta(SearchOperatorSet tableDefault) {
468      if (searchType == null)
469         return null;
470      var operatorList = new JsonList();
471      for (var op : effectiveOperators(tableDefault)) {
472         var o = new JsonMap();
473         o.put("name", op.name());
474         if (op.help() != null)
475            o.put("help", op.help());
476         o.put("minArgs", op.minArgs());
477         o.put("maxArgs", op.maxArgs());
478         o.put("combinator", op.isCombinator());
479         o.put("custom", op.isCustom());
480         operatorList.add(o);
481      }
482      var search = new JsonMap();
483      search.put("type", searchType.wire());
484      search.put("operators", operatorList);
485      return search;
486   }
487}