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.petstore.console.pages;
018
019import static org.apache.juneau.commons.utils.StringUtils.*;
020
021import java.util.*;
022import java.util.stream.*;
023
024import org.apache.juneau.marshall.collections.*;
025import org.apache.juneau.petstore.console.dev.*;
026import org.apache.juneau.petstore.console.dev.flavors.*;
027import org.apache.juneau.console.*;
028import org.apache.juneau.console.TopicDecl.*;
029import org.apache.juneau.console.freemarker.*;
030import org.apache.juneau.console.freemarker.DataSourceDef.*;
031import org.apache.juneau.console.views.*;
032import org.apache.juneau.console.views.TableSpec.*;
033
034/**
035 * Builder twins of the Developer pages: Custom cards ({@code cards.ftlh}), Rendering flavors ({@code flavors.ftlh},
036 * {@code flavors-react.ftlh}), Secure ({@code secure.ftlh}), Themes ({@code themes.ftlh}), Charts (builder only),
037 * Data sources (builder only), Dialogs (builder only) and Dashboard (builder only).
038 *
039 * <h2 class='section'>Example:</h2>
040 * <p class='bjava'>
041 *    <jk>return</jk> <jsm>twin</jsm>(<jv>req</jv>, DevPageBuilders.<jsm>secure</jsm>());
042 * </p>
043 */
044@SuppressWarnings({
045   "java:S1192" // Page-definition ids and labels repeat as inline literals by design.
046})
047public final class DevPageBuilders {
048
049   private DevPageBuilders() {}
050
051   /**
052    * Custom cards.
053    *
054    * <p>
055    * The gauge card's body is the same {@code {species, low, high}} the FTL page authors: {@link PageSpec} runs it
056    * through the registered {@link InventoryGaugeCardType}, so both pages carry the same validated fragment.
057    *
058    * @return The page spec.
059    */
060   public static PageSpec cards() {
061      var gauge = CardSpec.of(InventoryGaugeCardType.TYPE, "gauge").title("Dog inventory")
062         .body("species", "DOG").body("low", 20).body("high", 120);
063      var bands = ChartDef.bar("bands").title("Stock by species").src("/console/dev/cards/inventory/all")
064         .x("species").series("available", "Available").series("pending", "Pending").series("sold", "Sold", "ok")
065         .stacked(true).horizontal().decorate("petstore.stockTotals", null).on("click", "app.band-picked").dataTab().toCardSpec();
066      var prices = ChartDef.scatter("prices").title("Prices by pet").src("/console/dev/cards/prices")
067         .x("id", "number", "Pet").series("price", "Price")
068         .option("{dataZoom:[{type:'inside'},{type:'slider'}]}").publishZoom().toCardSpec();
069      return PageSpec.create().tab("dev/cards").init("/console/dev/cards/petstore-cards.js")
070         .card(SwitcherDef.create("cards-sw").style(SwitcherDef.STYLE_SLIDER).initialView("bands")
071            .view("available", "Pets available", v -> v.section(CardSpec.of("kpi", "available").title("Pets available")
072               .body("label", "Pets available").body("dataUrl", "/console/dev/cards/stats/available")))
073            .view("gauge", "Dog inventory", v -> v.section(gauge))
074            .view("bands", "Stock by species", v -> v.section(bands))
075            .view("prices", "Prices by pet", v -> v.section(prices))
076            .view("toolbar", "Card API", v -> v.section(CardSpec.html("toolbar").title("Card API").src("/console/dev/cards/fragments/toolbar")))
077            .view("how", "Writing a card type", v -> v.section(CardSpec.html("how").title("Writing a card type").src("/console/dev/cards/fragments/how")))
078            .toCardSpec());
079   }
080
081   /**
082    * One Rendering flavors page.
083    *
084    * @param flavor The flavor.
085    * @return The page spec.
086    */
087   public static PageSpec flavor(Flavor flavor) {
088      var p = PageSpec.create().tab("dev/flavors/" + flavor.id()).toolkit("views")
089         .html("caption", flavor.label(), "<div class=\"jc-prose\"><p>%s</p><p><a href=\"%s\">View source</a></p></div>"
090            .formatted(escapeHtml(flavor.caption()), escapeHtml(flavor.sourceUrl())));
091      if (flavor == Flavor.REACT)
092         return p.html("flavor", "React app",
093            "<iframe src=\"/petstore-ui\" title=\"Petstore React app\" class=\"petstore-flavor-frame\" width=\"100%\" height=\"640\"></iframe>");
094      return p.htmlSrc("flavor", "Pets", "/console/dev/flavors/" + flavor.id() + "/fragment");
095   }
096
097   /**
098    * Secure.
099    *
100    * @return The page spec.
101    */
102   public static PageSpec secure() {
103      return PageSpec.create().tab("dev/secure").init("/console/dev/secure/secure.js")
104         .html("about", "Bearer-token guard", """
105            <div class="jc-prose">
106            <p>This page is open. The API under <code>/console/dev/secure/api</code> is not: every call needs an
107            <code>Authorization: Bearer &lt;token&gt;</code> header, checked by a fail-closed guard.</p>
108            <p>Demo tokens: <code>petstore-user</code> (alice) and <code>petstore-admin</code> (admin). Anything else is a 401.</p>
109            <pre><code>curl -H 'Authorization: Bearer petstore-user' http://localhost:10000/console/dev/secure/api/pets</code></pre>
110            </div>""")
111         .html("try", "Try it", """
112            <div class="jc-prose">
113            <p>
114            <button type="button" data-secure-call="none" data-secure-url="/console/dev/secure/api/whoami">Without a token</button>
115            <button type="button" data-secure-call="petstore-user" data-secure-url="/console/dev/secure/api/whoami">With the demo token</button>
116            <button type="button" data-secure-call="wrong-token" data-secure-url="/console/dev/secure/api/whoami">With a wrong token</button>
117            </p>
118            <pre><output id="secure-result" aria-live="polite"></output></pre>
119            </div>""");
120   }
121
122   /**
123    * Themes.
124    *
125    * <p>
126    * The theme itself is drawn by the chrome ({@code base.ftlh}), so the spec carries the same
127    * {@code petstoreTheme} / {@code petstoreCustomTheme} attributes the FTL page does.
128    *
129    * @param theme The stock theme to draw in (the custom theme's seed when {@code custom}).
130    * @param custom Whether the custom tokens are applied.
131    * @param choices The theme names to offer.
132    * @return The page spec.
133    */
134   public static PageSpec themes(String theme, boolean custom, List<String> choices) {
135      var links = choices.stream().map(x -> escapeHtml(x)).map(x -> "<li><a href=\"/console/dev/themes?theme=" + x + "\">" + x + "</a></li>")
136         .collect(Collectors.joining());
137      return PageSpec.create().tab("dev/themes")
138         .attr("petstoreTheme", theme).attr("petstoreCustomTheme", custom)
139         .html("swatches", "This theme", """
140            <div class="jc-prose">
141            <p>The page is drawn in <strong>%s</strong>%s.</p>
142            <p>
143            <span class="tag stage released">Available</span>
144            <span class="tag stage pending">Pending</span>
145            <span class="tag stage failed">Sold</span>
146            </p>
147            </div>""".formatted(escapeHtml(theme), custom ? ", with custom tokens" : ""))
148         .html("picker", "Pick a theme", """
149            <div class="jc-prose">
150            <ul>
151            %s
152            </ul>
153            </div>""".formatted(links))
154         .html("authoring", "Writing a custom theme", """
155            <div class="jc-prose">
156            <p>Seed from the page theme and override tokens. A <code>value</code> sets a token; an <code>alias</code> makes it
157            follow another token. Add <code>scheme="dark"</code> to set a token for the dark scheme only.</p>
158            <pre><code>&lt;@theme&gt;
159            &lt;@token name="--jc-pill-red-bg" value="#fdeceb"/&gt;
160            &lt;@token name="--jc-tab-bar-bg" alias="var(--jc-card-bg)"/&gt;
161            &lt;@token name="--jc-link" value="#d9a65c" scheme="dark"/&gt;
162            &lt;/@theme&gt;</code></pre>
163            </div>""");
164   }
165
166   /**
167    * Charts (builder only): a line chart with markers, a threshold and a click topic, and a table whose ribbon highlights a point.
168    *
169    * @return The page spec.
170    */
171   public static PageSpec charts() {
172      var rows = "/console/dev/charts/daily";
173      return PageSpec.create().tab("dev").toolkit("views")
174         .card(ChartDef.line("trend").title("Orders this week").src(rows).x("day")
175            .series("placed", "Placed").series("delivered", "Delivered")
176            .decorate(Markers.values(List.of(Map.of("at", "Wed", "label", "Restock"))))
177            .decorate(Thresholds.at(6).label("Target").tone("ok"))
178            .on("click", "app.day-picked")
179            .toCardSpec())
180         .table(TableSpec.create("days").dataMode(DataMode.CLIENT).dataUrl(rows)
181            .columns(Column.create("day").label("Day"), Column.create("placed").label("Placed"), Column.create("delivered").label("Delivered"))
182            .ribbon(RibbonItem.publish("Highlight Monday", "cmd:trend",
183               Map.of("schemaVersion", 1, "op", "highlight", "options", Map.of("seriesId", "placed", "dataIndex", 0))).id("highlight-monday")),
184            "Days");
185   }
186
187   /**
188    * Dialogs (builder only): a table whose ribbon opens a {@code ModalDef.steps} wizard and a {@code nav:"folder"} dialog.
189    *
190    * @return The page spec.
191    */
192   public static PageSpec dialogs() {
193      var base = "/console/dev/dialogs";
194      return PageSpec.create().tab("dev").toolkit("views")
195         .table(TableSpec.create("dialogs").dataMode(DataMode.CLIENT).dataUrl(base + "/rows")
196            .columns(Column.create("style").label("Style"), Column.create("steps").label("Parts"))
197            .ribbon(
198               RibbonItem.dialog("wizard").title("Wizard").form(base + "/wizard-form").endpoint(base + "/submit").method(org.apache.juneau.console.views.RowAction.Method.POST).group("entity"),
199               RibbonItem.dialog("folder").title("Folder tabs").form(base + "/folder-form").endpoint(base + "/submit").method(org.apache.juneau.console.views.RowAction.Method.POST).group("entity"),
200               RibbonItem.refresh()),
201            "Dialogs");
202   }
203
204   /**
205    * Data sources (builder only): an hourly CSV source chunked by UTC day and cached in IndexedDB, over a range the
206    * page script publishes, drawn by a line chart.
207    *
208    * @return The page spec.
209    */
210   public static PageSpec data() {
211      var range = Topics.custom("petstore", "range");
212      return PageSpec.create().tab("dev").toolkit("views").init("/console/dev/data/data.js")
213         .topic(TopicDecl.of(range).retain(true).publisher(Publisher.SCRIPT))
214         .data(DataSourceDef.create("orders").url("/console/dev/data/orders").format(Format.CSV)
215            .columns("t:time", "placed:number")
216            .params(Subscription.to(range).as("params").map("start", "start").map("end", "end"))
217            .chunk(Chunking.byDay("start", "end")).cache(Cache.indexedDb()))
218         .card(ChartDef.line("ordersChart").title("Orders by hour").source(Topics.data("orders")).x("t")
219            .series("placed", "Placed").toCardSpec());
220   }
221
222   /**
223    * Dashboard (builder only): a rail of every section kind over a 2-column grid of charts, bound to one CSV source.
224    *
225    * @param variant The source variant: {@code ok}, {@code slow}, {@code truncated}, {@code error} or {@code right} (the {@code ok} source with the rail on the right).
226    * @param version The persist version; bumping it discards saved state.
227    * @return The page spec.
228    */
229   public static PageSpec dashboard(String variant, int version) {
230      var base = "/console/dev/dashboard";
231      var share = ChartDef.donut("share").title("Share by reason").src(base + "/reasons").label("reason").value("orders");
232      return PageSpec.create().tab("dev").toolkit("views").init(base + "/dashboard.js")
233         // An array param (reasons) repeats its key in the query, which the endpoint reads with getAll.
234         .data(DataSourceDef.create("orders").url(base + "/series/" + variant).format(Format.CSV)
235            .columns("day:time", "reason:string", "orders:number")
236            .params(
237               Subscription.to(Topics.filter("range")).as("params").map("start", "start").map("end", "end"),
238               Subscription.to(Topics.filter("q")).as("params").map("q", "search"),
239               Subscription.to(Topics.filter("reasons")).as("params").map("reasons", "columns.reason"),
240               Subscription.to(Topics.filter("late")).as("params").map("lateOnly", "options.lateOnly"))
241            .chunk(Chunking.none()).cache(Cache.none()))
242         .dashboard(DashboardSpec.create("overview").title("Order issues")
243            .rail(("right".equals(variant) ? Rail.right() : Rail.left()).sections(
244               RangeSection.quick("7d", "30d", "ytd").custom(true).defaultPreset("30d").publishes(Topics.filter("range")),
245               SearchSection.create().placeholder("Reason contains").publishes(Topics.filter("q")),
246               ChoiceSection.fromDim("orders", "reason").label("Reasons").publishes(Topics.filter("reasons")),
247               CardSection.of(share),
248               Section.custom("petstore.late", JsonMap.of("label", "Late only")).publishes(Topics.filter("late"))))
249            .grid(2)
250            .panel(ChartDef.line("daily").title("Orders per day").source(Topics.data("orders")).x("day", "time", "Day")
251               .series("orders", "Orders").publishZoom().patch("{dataZoom:[{type:'inside'},{type:'slider'}]}"), 2)
252            .panel(ChartDef.bar("by-reason").title("Orders by reason").src(base + "/reasons").x("reason").series("orders", "Orders"))
253            .panel(ChartDef.bar("by-weekday").title("Orders by weekday").src(base + "/weekdays").x("weekday").series("orders", "Orders"))
254            .status(Topics.data("orders"))
255            .persist(PersistSpec.page("petstore.dashboard").version(version)
256               .topics(Topics.filter("range"), Topics.filter("q"), Topics.filter("reasons"), Topics.zoom("daily")).shareLink()));
257   }
258}