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.bean.*;
024import org.apache.juneau.console.widgets.*;
025
026/**
027 * A named cell-renderer reference in the {@code VIEW_META} wire contract.
028 *
029 * <p>
030 * Serializes to the canonical object form <c>{"id":"tag","meta":{"field":"status"}}</c>; the optional
031 * {@link #meta} and {@link #popover} members are omitted from the wire when unset.  The client
032 * {@code juneau-renders.js} registry looks up {@link #id} and invokes the matching renderer, passing the
033 * {@link #meta} map through as per-column context (and painting {@link #popover}, when present, from row data
034 * already on the client).  Typed factories exist for the renderers that take structured metadata:
035 * {@link #progress(int)} and {@link #pill(String)}.  Timestamp renderers ({@code ts-zulu}, {@code datetime})
036 * honor {@code meta.popup}: {@code off} disables the local/California hover popup; {@code ts-zulu} defaults
037 * the popup on, {@code datetime} defaults it off.
038 *
039 * <p>
040 * A compact string sugar is supported via {@link #parse(String)}: everything after the <b>first</b> colon becomes
041 * <c>meta.field</c> &mdash; e.g. <c>"tag:status"</c> &rarr; <c>{id:"tag", meta:{field:"status"}}</c> and
042 * <c>"date"</c> &rarr; <c>{id:"date"}</c>.
043 *
044 * <h2 class='section'>See Also:</h2>
045 * <ul>
046 *    <li class='jc'>{@link ViewTable}
047 * </ul>
048 *
049 * @since 10.0.0
050 */
051@BeanType(properties="id,meta,popover")
052@SuppressWarnings({
053   "java:S1845" // Fluent-builder setters intentionally mirror field names (Juneau DSL convention).
054})
055public class Render {
056
057   /** The renderer id (registry key in {@code juneau-renders.js}). */
058   public String id;
059
060   /** Optional per-column renderer metadata.  Omitted from the wire when absent. */
061   public Map<String,Object> meta;
062
063   /**
064    * Creates a renderer reference with the specified id and no metadata.
065    *
066    * @param id The renderer id.  Must not be <jk>null</jk>.
067    * @return A new {@link Render}.
068    */
069   public static Render of(String id) {
070      var r = new Render();
071      r.id = id;
072      return r;
073   }
074
075   /**
076    * Parses a render-id string into a {@link Render}, applying the <c>"id:field"</c> string sugar.
077    *
078    * <p>
079    * Everything after the <b>first</b> colon becomes <c>meta.field</c>; a bare id (no colon) yields a
080    * metadata-free renderer.
081    *
082    * @param s The render-id string.  Must not be <jk>null</jk> or blank.
083    * @return A new {@link Render}.
084    */
085   public static Render parse(String s) {
086      if (ib(s))
087         throw iaex("Render id must not be null or blank.");
088      var i = s.indexOf(':');
089      if (i < 0)
090         return of(s);
091      return of(s.substring(0, i)).meta("field", s.substring(i + 1));
092   }
093
094   /**
095    * Adds a metadata key/value pair to this renderer reference.
096    *
097    * @param key The metadata key.  Must not be <jk>null</jk>.
098    * @param value The metadata value.  Serialized as given, so a {@link Number} or {@link Boolean} stays a JSON
099    *    number or boolean (for example {@code meta("places", 2)}).
100    * @return This object.
101    */
102   public Render meta(String key, Object value) {
103      if (meta == null)
104         meta = m();
105      meta.put(key, value);
106      return this;
107   }
108
109   /**
110    * Maps one cell value to a status tone on a {@code pill} renderer.
111    *
112    * <p>
113    * Emits {@code meta.tones[value] = tone.wire()}.  Value matching is exact and case-sensitive against the string
114    * the chip displays.  Re-adding a value replaces its tone and keeps its position.
115    *
116    * <h4 class='section'>Precedence (first hit wins):</h4>
117    * <ol>
118    *    <li>An entry added here.
119    *    <li>A slot pinned with {@link #category(String,int)}.
120    *    <li>{@link #categorical()}: the value's hashed palette slot.
121    *    <li>The column-wide tone from {@link #pill(StatusTone)}.
122    *    <li>Otherwise no colour class; but in a column that uses {@code tone(...)} or {@code category(...)} an
123    *       unmapped value renders as a neutral (grey) chip.
124    * </ol>
125    *
126    * <h4 class='section'>Example:</h4>
127    * <p class='bjava'>
128    *    <jc>// Renders as {id:"pill",meta:{tones:{AVAILABLE:"success",SOLD:"neutral"}}}.</jc>
129    *    Render <jv>r</jv> = Render.<jsm>pill</jsm>()
130    *       .tone(<js>"AVAILABLE"</js>, StatusTone.<jsf>SUCCESS</jsf>)
131    *       .tone(<js>"SOLD"</js>, StatusTone.<jsf>NEUTRAL</jsf>);
132    * </p>
133    *
134    * @param value The cell value, case-sensitive.  Must not be <jk>null</jk> or blank.
135    * @param tone The status tone.  Must not be <jk>null</jk>.
136    * @return This object.
137    * @throws IllegalStateException If this is not a {@code pill} renderer.
138    * @throws IllegalArgumentException If {@code value} is <jk>null</jk> or blank, or {@code tone} is <jk>null</jk>.
139    * @since 10.0.0
140    */
141   public Render tone(String value, StatusTone tone) {
142      requirePill("tone");
143      if (! inb(value) || tone == null)
144         throw new IllegalArgumentException("tone(value, tone) requires a non-blank value and a non-null tone");
145      nested("tones").put(value, tone.wire());
146      return this;
147   }
148
149   /**
150    * Colours every distinct value of a {@code pill} column from the categorical palette.
151    *
152    * <p>
153    * Emits {@code meta.categorical = true}.  A value without an explicit {@link #tone(String,StatusTone)} or
154    * {@link #category(String,int)} entry gets a stable colour from {@link PillPalette#slot(String)}: the same value
155    * has the same colour on every page.  Hashing is case-sensitive, and hashing {@code N} values into
156    * {@link PillPalette#SIZE} slots can collide; pin a closed set with {@link #category(String,int)}.
157    * See {@link #tone(String,StatusTone)} for the full precedence.
158    *
159    * @return This object.
160    * @throws IllegalStateException If this is not a {@code pill} renderer.
161    * @since 10.0.0
162    */
163   public Render categorical() {
164      requirePill("categorical");
165      meta("categorical", true);
166      return this;
167   }
168
169   /**
170    * Pins one cell value of a {@code pill} column to a categorical palette slot.
171    *
172    * <p>
173    * Emits {@code meta.categories[value] = slot}.  Use it for a closed value set so the values get distinct colours
174    * instead of a hash collision.  Value matching is exact and case-sensitive.  See
175    * {@link #tone(String,StatusTone)} for the full precedence.
176    *
177    * @param value The cell value, case-sensitive.  Must not be <jk>null</jk> or blank.
178    * @param slot The palette slot, 1 through {@link PillPalette#SIZE}.
179    * @return This object.
180    * @throws IllegalStateException If this is not a {@code pill} renderer.
181    * @throws IllegalArgumentException If {@code value} is <jk>null</jk> or blank, or {@code slot} is out of range.
182    * @since 10.0.0
183    */
184   public Render category(String value, int slot) {
185      requirePill("category");
186      if (! inb(value) || slot < 1 || slot > PillPalette.SIZE)
187         throw new IllegalArgumentException("category(value, slot) requires a non-blank value and a slot from 1 to " + PillPalette.SIZE);
188      nested("categories").put(value, slot);
189      return this;
190   }
191
192   private void requirePill(String method) {
193      if (! "pill".equals(id))
194         throw new IllegalStateException(method + "(...) is only valid on a pill renderer, not '" + id + "'");
195   }
196
197   @SuppressWarnings("unchecked")
198   private Map<String,Object> nested(String key) {
199      if (meta == null)
200         meta = m();
201      return (Map<String,Object>)meta.computeIfAbsent(key, k -> new LinkedHashMap<String,Object>());
202   }
203
204   /**
205    * Optional per-cell popover, omitted from the wire when unset.
206    *
207    * <p>
208    * The runtime appends a sibling trigger next to the rendered cell and paints the popover from row data
209    * already on the client.  Never assigned {@code innerHTML}.
210    */
211   public CellPopover popover;
212
213   /**
214    * Sets the optional per-cell popover.
215    *
216    * @param value The popover definition.  Can be <jk>null</jk> to unset.
217    * @return This object.
218    */
219   public Render popover(CellPopover value) {
220      popover = value;
221      return this;
222   }
223
224   /**
225    * Creates a {@code progress} renderer with the given maximum (denominator).
226    *
227    * <p>
228    * Equivalent to {@code Render.of("progress").meta("max", String.valueOf(max))}.  Chain
229    * {@link #meta(String,Object)} for {@code label} / {@code field}.
230    *
231    * @param max The ratio denominator.  Serialized as the string {@code meta.max}.
232    * @return A new {@link Render}.
233    */
234   public static Render progress(int max) {
235      return of("progress").meta("max", String.valueOf(max));
236   }
237
238   /**
239    * Creates a {@code progress} renderer with maximum and optional warn/exceeds thresholds.
240    *
241    * <p>
242    * {@code warn} and {@code exceeds} are omitted from {@code meta} when <jk>null</jk>.  A boxed {@code 0} is a
243    * real threshold ({@code "0"}), not omitted.
244    *
245    * @param max The ratio denominator.
246    * @param warn Warn threshold in the same units as the cell value.  Can be <jk>null</jk>.
247    * @param exceeds Exceeds threshold in the same units as the cell value.  Can be <jk>null</jk>.
248    * @return A new {@link Render}.
249    */
250   public static Render progress(int max, Integer warn, Integer exceeds) {
251      var r = progress(max);
252      if (warn != null)
253         r.meta("warn", String.valueOf(warn));
254      if (exceeds != null)
255         r.meta("exceeds", String.valueOf(exceeds));
256      return r;
257   }
258
259   /**
260    * Creates a {@code pill} renderer with the leading dot on and the tone inherited from the chip theme.
261    *
262    * <p>
263    * Equivalent to {@code Render.of("pill")}.  The dot color follows the {@code .tag.<field>.<value>} theme
264    * ({@code currentColor}) until an explicit {@code tone} is chosen.  Chain {@link #meta(String,Object)} for
265    * {@code field}, {@code dot} ({@code on}|{@code off}) and {@code action} (a {@code rowActions} id).
266    *
267    * <p>
268    * {@code action} is optional and only meaningful on a table column: a pill named on a field-grid fill
269    * sink is unconditionally display-only and rejects an {@code action} outright.
270    *
271    * @return A new {@link Render}.
272    */
273   public static Render pill() {
274      return of("pill");
275   }
276
277   /**
278    * Creates a {@code pill} renderer with an explicit dot tone.
279    *
280    * <p>
281    * {@code tone} is one of the five status tones
282    * {@code info}|{@code success}|{@code warning}|{@code error}|{@code neutral} (see
283    * {@link StatusTone}).  A <jk>null</jk> or blank {@code tone} is omitted
284    * from {@code meta} (identical to {@link #pill()}); {@code neutral} is emitted verbatim and, like an absent tone,
285    * leaves the dot inheriting {@code currentColor}.  The tone is not validated server-side: the client
286    * (<c>NS._render.pillTones</c>) ignores an off-palette token, so the dot gets no tone class.  Prefer
287    * {@link #pill(StatusTone)} to stay on the palette.
288    *
289    * <p>
290    * Not to be confused with {@link #progress(int, Integer, Integer)}'s {@code warn}/{@code exceeds} meta, which are
291    * numeric thresholds rather than tone names and share no vocabulary with this palette.
292    *
293    * @param tone The explicit dot tone.  Can be <jk>null</jk> or blank to inherit.
294    * @return A new {@link Render}.
295    */
296   public static Render pill(String tone) {
297      var r = pill();
298      if (inb(tone))
299         r.meta("tone", tone);
300      return r;
301   }
302
303   /**
304    * Creates a {@code pill} renderer with an explicit dot tone taken from the {@link StatusTone} palette.
305    *
306    * <p>
307    * Equivalent to <c>pill(tone == <jk>null</jk> ? <jk>null</jk> : tone.wire())</c>; a <jk>null</jk> tone is
308    * omitted from {@code meta}, identical to {@link #pill()}.
309    *
310    * <h4 class='section'>Example:</h4>
311    * <p class='bjava'>
312    *    <jc>// Renders as {id:"pill",meta:{tone:"warning"}}.</jc>
313    *    Render <jv>r</jv> = Render.<jsm>pill</jsm>(StatusTone.<jsf>WARNING</jsf>);
314    * </p>
315    *
316    * @param tone The explicit dot tone.  Can be <jk>null</jk> to inherit.
317    * @return A new {@link Render}.
318    */
319   public static Render pill(StatusTone tone) {
320      return pill(tone == null ? null : tone.wire());
321   }
322}