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.freemarker;
018
019import static org.apache.juneau.commons.utils.Shorts.*;
020
021import java.util.*;
022
023import org.apache.juneau.console.*;
024import org.apache.juneau.console.views.*;
025
026/**
027 * Type-agnostic card entry in the page contract: {@code id}, {@code type}, optional {@code src},
028 * {@code title}, {@code template}, plus a type-specific body map.
029 *
030 * <h2 class='section'>Example:</h2>
031 * <p class='bjava'>
032 *    CardSpec <jv>c</jv> = CardSpec.<jsm>html</jsm>(<js>"intro"</js>).title(<js>"Welcome"</js>).template(<js>"intro"</js>);
033 *    CardSpec <jv>t</jv> = CardSpec.<jsm>of</jsm>(<js>"datatables"</js>, <js>"releases"</js>)
034 *       .body(<js>"table"</js>, <js>"/rest/releases/data"</js>);
035 *    PageCapture.<jsm>of</jsm>(<jv>env</jv>).addCard(<jv>c</jv>, <js>"&lt;p&gt;Hello&lt;/p&gt;"</js>);
036 * </p>
037 *
038 * @since 10.0.0
039 */
040public final class CardSpec implements Handled<CardSpec> {
041
042   /** Card types whose schema definition has no {@code bare} property, so a bare card of that type would fail validation. */
043   private static final Set<String> BARE_UNSUPPORTED = Set.of("terminal-view", "terminal");
044
045   private final String type;
046   private final String id;
047   private String title;
048   private String src;
049   private String template;
050   private boolean bare;
051   private boolean sanitize;
052   private String cssClass;
053   private final Map<String,Object> body = new LinkedHashMap<>();
054   private final List<Map<String,Object>> publishes = new ArrayList<>();
055   private final List<Map<String,Object>> subscribes = new ArrayList<>();
056   private List<VisibilityRule> visibleWhen = List.of();
057   private final ModelBlock model;
058
059   private CardSpec(String type, String id) {
060      this.type = type;
061      this.id = id;
062      this.model = new ModelBlock("card", id);
063   }
064
065   @Override /* Handled */
066   public ModelBlock modelBlock() { return model; }
067
068   @Override /* Handled */
069   public CardSpec self() { return this; }
070
071   /** @param id The card id. @return A new {@code html} card. */
072   public static CardSpec html(String id) {
073      return new CardSpec("html", id);
074   }
075
076   /** @param type The card type. @param id The card id. @return A new card. */
077   public static CardSpec of(String type, String id) {
078      return new CardSpec(type, id);
079   }
080
081   /** @param v The card title. @return This object. */
082   public CardSpec title(String v) { title = v; return this; }
083
084   /** @param v A same-origin URL the card loads. @return This object. */
085   public CardSpec src(String v) { src = v; return this; }
086
087   /** @param templateId The id of a {@code <template data-card>} element. @return This object. */
088   public CardSpec template(String templateId) { template = templateId; return this; }
089
090   /**
091    * @param v
092    *    Whether the card drops its chrome: an html card is inserted with no wrapper element, any other type keeps a
093    *    wrapper element (class {@code jc-card-bare} instead of {@code jc-card}) but loses the card chrome and its
094    *    title.
095    * @return This object.
096    */
097   public CardSpec bare(boolean v) {
098      if (v && BARE_UNSUPPORTED.contains(type))
099         throw iaex("card '%s': a %s card does not support bare.", id, type);
100      bare = v;
101      return this;
102   }
103
104   /** @return Whether this card drops its chrome. */
105   boolean bare() { return bare; }
106
107   /** @return Whether this card declares any {@code publishes} topics. */
108   boolean hasPublishes() { return ! publishes.isEmpty(); }
109
110   /** @return Whether this card declares any {@code subscribes} entries. */
111   boolean hasSubscribes() { return ! subscribes.isEmpty(); }
112
113   /** @param v Whether an html card's fetched {@code src} fragment is rebuilt through the views attribute-allowlist sanitizer instead of being inserted as-is. @return This object. */
114   public CardSpec sanitize(boolean v) { sanitize = v; return this; }
115
116   /** @return Whether this card asks for its {@code src} fragment to be sanitized. */
117   boolean sanitize() { return sanitize; }
118
119   /** @param v Space-separated CSS class names stamped on the card wrapper element. @return This object. */
120   public CardSpec cssClass(String v) { cssClass = v; return this; }
121
122   /** @param key A type-specific field. @param value Its value. @return This object. */
123   public CardSpec body(String key, Object value) {
124      if ("publishes".equals(key) || "subscribes".equals(key) || "model".equals(key))
125         throw iaex("card '%s': '%s' is a base key; use %s(...)", id, key, key);
126      body.put(key, value);
127      return this;
128   }
129
130   /**
131    * Declares custom topics this card's JS publishes; repeatable, appends.
132    *
133    * @param v The declarations; each needs {@code retain} and must not set {@code publisher}.
134    * @return This object.
135    */
136   public CardSpec publishes(TopicDecl... v) {
137      for (var d : v)
138         publishes.add(d.toPublicationMap());
139      return this;
140   }
141
142   /**
143    * Sets card-level visibility rules.  The client evaluates them against the page's facts; this only serializes them.
144    *
145    * @param rules The rules, ANDed together.  None clears them.
146    * @return This object.
147    */
148   public CardSpec visibleWhen(VisibilityRule... rules) {
149      if (rules == null || Arrays.stream(rules).anyMatch(Objects::isNull))
150         throw iaex("CardSpec visibleWhen rules must not be null.");
151      visibleWhen = List.of(rules);
152      return this;
153   }
154
155   /**
156    * Wires topics to roles this card's type implements; repeatable, appends.
157    *
158    * @param v The subscriptions.
159    * @return This object.
160    */
161   public CardSpec subscribes(Subscription... v) {
162      for (var s : v)
163         subscribes.add(s.toMap());
164      return this;
165   }
166
167   /** @return The id. */
168   public String id() { return id; }
169
170   /** @return The type. */
171   public String type() { return type; }
172
173   /** @return An independent copy of this card, safe to mutate without affecting this one. */
174   CardSpec copy() {
175      var c = new CardSpec(type, id);
176      c.title = title;
177      c.src = src;
178      c.template = template;
179      c.bare = bare;
180      c.sanitize = sanitize;
181      c.cssClass = cssClass;
182      c.body.putAll(body);
183      return c.wiringFrom(this);
184   }
185
186   /** Wiring already lowered to contract maps (FTL attributes or a JSON5 body). */
187   CardSpec wiring(List<?> publishesMaps, List<?> subscribesMaps) {
188      if (publishesMaps != null) for (var o : publishesMaps) publishes.add(asMap(o));
189      if (subscribesMaps != null) for (var o : subscribesMaps) subscribes.add(asMap(o));
190      return this;
191   }
192
193   /** @param other The card whose {@code publishes} / {@code subscribes} are appended to this one's, and whose {@code visibleWhen} replaces (does not merge with) this one's when it has any. @return This object. */
194   CardSpec wiringFrom(CardSpec other) {
195      publishes.addAll(other.publishes);
196      subscribes.addAll(other.subscribes);
197      model.addAll(other.model);
198      if (! other.visibleWhen.isEmpty())
199         visibleWhen = other.visibleWhen;
200      return this;
201   }
202
203   @SuppressWarnings({
204      "unchecked" // Narrows the validated Map to Map<String,Object>; its keys are always strings.
205   })
206   private static Map<String,Object> asMap(Object o) {
207      if (! (o instanceof Map))
208         throw new IllegalArgumentException("card wiring entries must be objects; got " + (o == null ? "null" : o.getClass().getSimpleName()) + ".");
209      return (Map<String,Object>)o;
210   }
211
212   /** @return The template id, or <jk>null</jk>. */
213   String template() { return template; }
214
215   /** @return The title, or <jk>null</jk>. */
216   String title() { return title; }
217
218   /** @return The {@code src} URL, or <jk>null</jk>. */
219   String src() { return src; }
220
221   /** @return The wrapper CSS classes, or <jk>null</jk>. */
222   String cssClass() { return cssClass; }
223
224   /** @return An unmodifiable copy of the type-specific body fields, in insertion order. */
225   public Map<String,Object> bodyMap() { return Collections.unmodifiableMap(new LinkedHashMap<>(body)); }
226
227   /** @return The contract entry, common fields first. */
228   public Map<String,Object> toMap() {
229      var m = new LinkedHashMap<String,Object>();
230      m.put("id", id);
231      m.put("type", type);
232      if (nn(title)) m.put("title", title);
233      if (nn(src)) m.put("src", src);
234      if (nn(template)) m.put("template", template);
235      if (bare) m.put("bare", true);
236      if (sanitize) {
237         if (neq(type, "html") || ! nn(src))
238            throw iaex("card '%s': sanitize applies only to an html card with src.", id);
239         m.put("sanitize", true);
240      }
241      if (nn(cssClass)) m.put("class", cssClass);
242      if (! visibleWhen.isEmpty()) m.put("visibleWhen", visibleWhen.stream().map(VisibilityRule::toMap).toList());
243      if (! publishes.isEmpty()) m.put("publishes", List.copyOf(publishes));
244      if (! subscribes.isEmpty()) m.put("subscribes", List.copyOf(subscribes));
245      m.putAll(body);
246      var mm = model.toMap();
247      if (mm != null) m.put("model", mm);
248      return m;
249   }
250}