diff --git a/nitrostack/widgets/route_templates.py b/nitrostack/widgets/route_templates.py
index 6b36120..b8fb7cd 100644
--- a/nitrostack/widgets/route_templates.py
+++ b/nitrostack/widgets/route_templates.py
@@ -1,833 +1,64 @@
-"""Built-in per-route widget HTML generated by Python (no npm/React build)."""
+"""Built-in per-route widget HTML generated by Python (no npm/React build).
-from __future__ import annotations
-
-from typing import Any, Callable, Dict, Optional
-
-from nitrostack.widgets.host_bridge import wrap_widget_page
-from nitrostack.widgets.views import missing_body, render_body
-
-
-def _generic_render_js() -> str:
- return """
-window.__nitroWidgetRender = function(data) {
- const root = document.getElementById("root");
- const meta = document.getElementById("meta");
- if (!root) return;
- if (!data) {
- if (meta) meta.textContent = "Waiting for tool result (host injects tool output).";
- return;
- }
- if (meta) meta.textContent = "Tool output";
- root.innerHTML = "";
- const pre = document.createElement("pre");
- pre.textContent = JSON.stringify(data, null, 2);
- root.appendChild(pre);
-};
-""".strip()
-
-
-_PIZZA_LIST_CSS = """
- :root { --ns-accent: #ea580c; --ns-accent-soft: #ffedd5; }
- .shop { min-width: 260px; max-width: 260px; scroll-snap-align: start; flex-shrink: 0; }
- .img { width: 100%; height: 120px; object-fit: cover; border-radius: 10px; margin-bottom: 8px; background: var(--ns-accent-soft); }
- .row { display: flex; justify-content: space-between; gap: 8px; align-items: baseline; }
- .name { font-weight: 700; }
- .addr { color: var(--ns-muted); font-size: 0.85rem; margin-top: 4px; }
-"""
-
-_PIZZA_MAP_CSS = """
- :root { --ns-accent: #ea580c; }
- html, body { width: 100%; height: 560px; }
- body { position: relative; min-height: 560px; background: #e5e7eb; }
- .meta { position: absolute; top: 12px; left: 12px; z-index: 3; margin: 0;
- background: color-mix(in srgb, var(--ns-surface) 92%, transparent); border-radius: 8px; padding: 6px 10px;
- box-shadow: var(--ns-shadow); }
- .map { position: absolute; inset: 0; width: 100%; height: 560px; min-height: 560px; }
- .map-live { position: absolute; inset: 0; }
- .static-map { position: absolute; inset: 0; z-index: 1; width: 100%; height: 560px;
- object-fit: cover; transition: opacity .4s ease; }
- .static-map.is-ready { opacity: 0; pointer-events: none; }
- .mapboxgl-map { width: 100%; height: 100%; }
- .cards { position: absolute; left: 16px; right: 16px; bottom: 8px; z-index: 3; }
- .map-card { min-width: 220px; max-width: 220px; flex-shrink: 0; scroll-snap-align: start; }
- .map-card .name { font-weight: 700; }
- .map-card .muted { margin-top: 4px; }
- .map-card .rating { margin-top: 4px; }
-"""
-
-_PIZZA_SHOP_CSS = """
- :root { --ns-accent: #e11d48; --ns-accent-soft: #ffe4e6; }
- .card { background: var(--ns-surface); border-radius: var(--ns-radius); padding: 16px; border: 1px solid var(--ns-border); }
- .hero { width: 100%; max-height: 180px; object-fit: cover; border-radius: 10px; margin-bottom: 12px; }
- .chips { margin-top: 10px; }
- .chip { margin: 0 4px 4px 0; }
-"""
-
-_CALC_CSS = """
- :root { --ns-accent: #15803d; }
- .card { background: var(--ns-surface); border: 1px solid var(--ns-border); border-radius: var(--ns-radius); padding: 20px; text-align: center; }
- .expr { font-size: 0.95rem; color: var(--ns-muted); margin-bottom: 8px; }
- .result { font-size: 2rem; font-weight: 800; color: var(--ns-accent); }
-"""
-
-_CARD_CSS = """
- .card { background: var(--ns-surface); border-radius: var(--ns-radius); padding: 20px; box-shadow: var(--ns-shadow); max-width: 320px; border: 1px solid var(--ns-border); }
- .card h2 { margin: 0 0 8px; font-size: 1.25rem; }
- .price { font-size: 1.5rem; }
- .desc { color: var(--ns-muted); margin-top: 8px; }
-"""
-
-_TABLE_CSS = """
- table { border-collapse: collapse; width: 100%; max-width: 480px; background: var(--ns-surface); border-radius: 10px; overflow: hidden; }
- th, td { border: 1px solid var(--ns-border); padding: 8px 12px; text-align: left; }
- th { background: var(--ns-accent-soft); }
-"""
-
-_CHART_CSS = """
- .chart { display: flex; align-items: flex-end; gap: 8px; height: 160px; }
- .bar-wrap { flex: 1; display: flex; flex-direction: column; align-items: center; }
- .bar { width: 100%; background: var(--ns-accent, #3b82f6); border-radius: 4px 4px 0 0; min-height: 4px; }
- .label { font-size: 12px; margin-top: 4px; color: var(--ns-muted); }
+This module is the route dispatcher. The templates live in route_templates_generic,
+route_templates_pizza and route_templates_flight and are re-exported here, so existing
+imports keep working.
"""
-_FLIGHT_CSS = """
- :root { --ns-accent: #0369a1; --ns-accent-soft: #e0f2fe; }
- .offer, .card, #list .row { background: var(--ns-surface); border: 1px solid var(--ns-border); border-radius: var(--ns-radius); padding: 12px; margin-bottom: 10px; }
- .row { display: flex; gap: 12px; align-items: center; }
- .id { font-size: 0.8rem; color: var(--ns-muted); }
- .code { font-size: 1.1rem; font-weight: 800; min-width: 3rem; }
- .slice { margin-top: 8px; }
- .seat-row { display: flex; gap: 6px; align-items: center; margin: 4px 0; }
- .rn { width: 2rem; font-size: 0.8rem; color: var(--ns-muted); }
- .seat { display: inline-block; min-width: 2.4rem; text-align: center; padding: 4px; border-radius: 6px; font-size: 0.75rem; }
-"""
-
-_GENERIC_CSS = """
- pre { background: var(--ns-surface); border: 1px solid var(--ns-border); border-radius: 8px; padding: 12px; overflow: auto; }
-"""
-
-_MISSING_CSS = """
- :root { --ns-bg: #fef2f2; --ns-text: #7f1d1d; }
- .meta { font-size: 0.9rem; line-height: 1.5; }
-"""
-
-_PIZZA_LIST_JS = """
-window.__nitroWidgetRender = function(data) {
- const list = document.getElementById("list");
- const meta = document.getElementById("meta");
- if (!list || !meta) return;
- list.innerHTML = "";
- if (!data || !Array.isArray(data.shops)) {
- meta.textContent = "Waiting for show_pizza_list result.";
- return;
- }
- const state = (window.openai && window.openai.widgetState) || {};
- const sort = state.sort || "rating";
- const shops = data.shops.slice().sort(function(a, b) {
- if (sort === "name") return String(a.name || "").localeCompare(String(b.name || ""));
- return (b.rating || 0) - (a.rating || 0);
- });
- document.querySelectorAll("#sorts [data-sort]").forEach(function(btn) {
- btn.classList.toggle("is-on", btn.getAttribute("data-sort") === sort);
- });
- const total = data.totalShops ?? data.shops.length;
- meta.textContent = total + " shop" + (total === 1 ? "" : "s");
- if (!shops.length) {
- list.innerHTML = '
No shops match these filters.
';
- return;
- }
- shops.forEach(function(shop) {
- const el = document.createElement("article");
- el.className = "shop ns-card";
- el.setAttribute("data-call-tool", "show_pizza_shop");
- el.setAttribute("data-args", JSON.stringify({ shopId: shop.id || "" }));
- el.setAttribute("role", "button");
- el.tabIndex = 0;
- const open = shop.openNow
- ? 'Open '
- : 'Closed ';
- const price = "$".repeat(shop.priceLevel || 1);
- let img = "";
- if (shop.image) {
- img = ' ';
- }
- el.innerHTML =
- img +
- '
' +
- '
' + open + '
';
- el.querySelector(".name").textContent = shop.name || shop.id || "Shop";
- el.querySelector(".rating").textContent = shop.rating != null ? "★ " + shop.rating : "";
- el.querySelector(".addr").textContent = shop.address || "";
- el.querySelector(".price").textContent = price;
- list.appendChild(el);
- });
-};
-document.addEventListener("click", function(ev) {
- const btn = ev.target.closest("#sorts [data-sort]");
- if (!btn || !window.nitrostack) return;
- const next = Object.assign({}, (window.openai && window.openai.widgetState) || {}, {
- sort: btn.getAttribute("data-sort")
- });
- window.nitrostack.setWidgetState(next);
- if (typeof window.__nitroWidgetRender === "function" && window.nitrostack.readHostData) {
- window.__nitroWidgetRender(window.nitrostack.readHostData());
- }
-});
-""".strip()
-
-_MAPBOX_HEAD = """
-
-
-""".strip()
-
-
-def _pizza_map_js() -> str:
- import json
-
- from nitrostack.widgets.html_util import get_mapbox_token
-
- token = json.dumps(get_mapbox_token())
- return f"""
-window.__NITRO_MAPBOX_TOKEN = {token};
-window.__nitroWidgetRender = function(data) {{
- const meta = document.getElementById("meta");
- const mapEl = document.getElementById("map-live") || document.getElementById("map");
- const cards = document.getElementById("cards");
- const staticEl = document.getElementById("static-map");
- if (!mapEl) return;
- if (!data || !Array.isArray(data.shops) || !data.shops.length) {{
- if (meta) meta.textContent = "Waiting for show_pizza_map result.";
- return;
- }}
- const shops = data.shops.filter(function(s) {{ return Array.isArray(s.coords) && s.coords.length === 2; }});
- const sig = (data.filter || "all") + "|" + shops.map(function(s) {{
- return (s.id || "") + ":" + s.coords[0] + "," + s.coords[1];
- }}).join(";");
- if (window.__nitroMapSig === sig && window.__nitroMap) return;
- if (meta) meta.textContent = (data.totalShops ?? data.shops.length) + " shops · filter: " + (data.filter || "all");
- if (cards && !cards.querySelector(".map-card")) {{
- data.shops.forEach(function(shop) {{
- const card = document.createElement("article");
- card.className = "map-card ns-card";
- card.setAttribute("data-shop-id", shop.id || "");
- card.setAttribute("data-call-tool", "show_pizza_shop");
- card.setAttribute("data-args", JSON.stringify({{ shopId: shop.id || "" }}));
- card.setAttribute("role", "button");
- card.tabIndex = 0;
- card.innerHTML = '
';
- card.querySelector(".name").textContent = shop.name || shop.id || "Shop";
- card.querySelector(".muted").textContent = shop.address || "";
- card.querySelector(".rating").textContent = shop.rating != null ? "★ " + shop.rating : "";
- cards.appendChild(card);
- }});
- }}
- function revealLive() {{
- if (staticEl) staticEl.classList.add("is-ready");
- }}
- function mountMap(attempt) {{
- if (window.__nitroMapSig === sig && window.__nitroMap) return;
- if (!window.__NITRO_MAPBOX_TOKEN) {{
- if (meta) meta.textContent = "Set MAPBOX_TOKEN in .env to load the map.";
- if (mapEl) {{
- mapEl.innerHTML = 'Set MAPBOX_TOKEN in .env (Mapbox public pk. token) to load the map.
';
- }}
- return;
- }}
- if (typeof mapboxgl === "undefined") {{
- if ((attempt || 0) < 80) {{
- setTimeout(function() {{ mountMap((attempt || 0) + 1); }}, 50);
- }}
- return;
- }}
- window.__nitroMapSig = sig;
- if (window.__nitroMap) {{
- window.__nitroMap.remove();
- window.__nitroMap = null;
- }}
- mapboxgl.accessToken = window.__NITRO_MAPBOX_TOKEN;
- const first = (shops[0] && shops[0].coords) || [-122.4194, 37.7749];
- const map = new mapboxgl.Map({{
- container: mapEl,
- style: "mapbox://styles/mapbox/streets-v12",
- center: first,
- zoom: 12,
- cooperativeGestures: false,
- fadeDuration: 0
- }});
- map.addControl(new mapboxgl.NavigationControl({{ showCompass: false }}), "top-right");
- map.addControl(new mapboxgl.FullscreenControl(), "top-right");
- shops.forEach(function(shop) {{
- const el = document.createElement("div");
- el.style.backgroundImage = "url(https://docs.mapbox.com/mapbox-gl-js/assets/custom_marker.png)";
- el.style.width = "30px";
- el.style.height = "40px";
- el.style.backgroundSize = "100%";
- el.style.cursor = "pointer";
- el.title = shop.name || shop.id || "";
- el.addEventListener("click", function() {{
- if (window.nitrostack) window.nitrostack.callTool("show_pizza_shop", {{ shopId: shop.id || "" }});
- }});
- new mapboxgl.Marker(el).setLngLat(shop.coords).addTo(map);
- }});
- if (shops.length > 1) {{
- const bounds = new mapboxgl.LngLatBounds();
- shops.forEach(function(s) {{ bounds.extend(s.coords); }});
- map.fitBounds(bounds, {{ padding: 60, maxZoom: 14, duration: 0 }});
- }}
- map.once("idle", function() {{
- try {{ map.resize(); }} catch (e) {{}}
- revealLive();
- }});
- window.__nitroMap = map;
- }}
- mountMap(0);
-}};
-""".strip()
-
-_PIZZA_SHOP_JS = """
-window.__nitroWidgetRender = function(data) {
- const shop = data && (data.shop || data);
- const hero = document.getElementById("hero");
- if (!shop || !shop.name) {
- const desc = document.getElementById("desc");
- if (desc) desc.textContent = "Waiting for show_pizza_shop result.";
- return;
- }
- if (shop.image && hero) {
- hero.src = shop.image;
- hero.style.display = "block";
- } else if (hero) {
- hero.style.display = "none";
- }
- document.getElementById("name").textContent = shop.name;
- document.getElementById("rating").textContent =
- shop.rating != null ? "★ " + shop.rating + " (" + (shop.reviews || 0) + " reviews)" : "";
- document.getElementById("desc").textContent = shop.description || "";
- document.getElementById("addr").textContent = shop.address || "";
- const hours = shop.hours ? (shop.hours.open + " – " + shop.hours.close) : "";
- document.getElementById("hours").textContent = hours ? "Hours: " + hours : "";
- document.getElementById("phone").textContent = shop.phone || "";
- const chips = document.getElementById("chips");
- chips.innerHTML = "";
- (shop.specialties || []).forEach(function(item) {
- const chip = document.createElement("span");
- chip.className = "chip";
- chip.textContent = item;
- chips.appendChild(chip);
- });
- const actions = document.getElementById("actions");
- if (actions) {
- actions.innerHTML = "";
- function addLink(label, url, primary) {
- if (!url) return;
- const a = document.createElement("a");
- a.className = primary ? "ns-btn ns-btn-primary" : "ns-btn";
- a.setAttribute("data-open-link", url);
- a.href = url;
- a.textContent = label;
- actions.appendChild(a);
- }
- let maps = "";
- if (Array.isArray(shop.coords) && shop.coords.length === 2) {
- maps = "https://www.google.com/maps/search/?api=1&query=" + shop.coords[1] + "," + shop.coords[0];
- } else if (shop.address) {
- maps = "https://www.google.com/maps/search/?api=1&query=" + encodeURIComponent(shop.address);
- }
- addLink("Maps", maps, false);
- if (shop.phone) {
- const tel = String(shop.phone).replace(/[^0-9+]/g, "");
- if (tel) addLink("Call", "tel:" + tel, false);
- }
- addLink("Website", shop.website || "", true);
- }
-};
-""".strip()
-
-_CALC_JS = """
-window.__nitroWidgetRender = function(data) {
- if (!data) return;
- const expr = document.getElementById("expr");
- const result = document.getElementById("result");
- if (data.expression) expr.textContent = data.expression;
- if (data.result != null) result.textContent = String(data.result);
- else if (data.value != null) result.textContent = String(data.value);
-};
-""".strip()
-
-_CARD_JS = """
-window.__nitroWidgetRender = function(data) {
- if (!data) return;
- const name = document.getElementById("name");
- const price = document.getElementById("price");
- const desc = document.getElementById("desc");
- if (name) name.textContent = data.name || "—";
- if (price) price.textContent = data.price != null ? "$" + Number(data.price).toFixed(2) : "—";
- if (desc) desc.textContent = data.description || "";
-};
-""".strip()
-
-_TABLE_JS = """
-window.__nitroWidgetRender = function(data) {
- if (!data || !Array.isArray(data.rows)) return;
- const cols = data.columns || Object.keys(data.rows[0] || {});
- const header = document.getElementById("header");
- const body = document.getElementById("body");
- if (!header || !body) return;
- header.innerHTML = "";
- body.innerHTML = "";
- cols.forEach(function(c) {
- const th = document.createElement("th");
- th.textContent = c;
- header.appendChild(th);
- });
- data.rows.forEach(function(row) {
- const tr = document.createElement("tr");
- cols.forEach(function(c) {
- const td = document.createElement("td");
- td.textContent = row[c] ?? "";
- tr.appendChild(td);
- });
- body.appendChild(tr);
- });
-};
-""".strip()
-
-_CHART_JS = """
-window.__nitroWidgetRender = function(data) {
- if (!data) return;
- const title = document.getElementById("title");
- const chart = document.getElementById("chart");
- if (title) title.textContent = data.title || "Chart";
- if (!chart) return;
- chart.innerHTML = "";
- const items = data.items || [];
- const max = Math.max.apply(null, items.map(function(i) { return i.value || 0; }).concat([1]));
- items.forEach(function(item) {
- const wrap = document.createElement("div");
- wrap.className = "bar-wrap";
- const bar = document.createElement("div");
- bar.className = "bar";
- bar.style.height = (((item.value || 0) / max) * 140) + "px";
- const label = document.createElement("div");
- label.className = "label";
- label.textContent = item.label || "";
- wrap.appendChild(bar);
- wrap.appendChild(label);
- chart.appendChild(wrap);
- });
-};
-""".strip()
-
-
-_FLIGHT_SEARCH_JS = """
-window.__nitroWidgetRender = function(data) {
- const list = document.getElementById("list");
- const meta = document.getElementById("meta");
- if (!list) return;
- const offers = (data && (data.offers || data.results)) || [];
- const params = (data && data.searchParams) || {};
- const total = (data && data.totalOffers != null) ? data.totalOffers : offers.length;
- if (meta) {
- meta.textContent = (params.origin && params.destination)
- ? (params.origin + " → " + params.destination + " · " + total + " offer" + (total === 1 ? "" : "s"))
- : (total + " offer" + (total === 1 ? "" : "s"));
- }
- list.innerHTML = "";
- if (!offers.length) {
- list.innerHTML = 'No flight offers.
';
- return;
- }
- function code(p) {
- if (!p) return "";
- if (typeof p === "string") return p;
- return p.iata_code || p.iataCode || p.code || "";
- }
- function legs(offer) {
- if (offer.slices && offer.slices.length) return offer.slices;
- const out = [];
- if (offer.outbound) out.push(offer.outbound);
- if (offer.return) out.push(offer.return);
- return out;
- }
- offers.forEach(function(offer) {
- const el = document.createElement("article");
- el.className = "offer ns-card";
- el.setAttribute("data-call-tool", "get_flight_details");
- el.setAttribute("data-args", JSON.stringify({ offerId: offer.id || "" }));
- el.setAttribute("role", "button");
- el.tabIndex = 0;
- const amount = offer.total_amount || offer.totalAmount || "";
- const currency = offer.total_currency || offer.totalCurrency || "";
- el.innerHTML = '
';
- el.querySelector(".price").textContent = amount + (currency ? " " + currency : "");
- el.querySelector(".id").textContent = offer.id || "";
- legs(offer).forEach(function(sl) {
- const s = document.createElement("div");
- s.className = "slice";
- s.textContent = code(sl.origin) + " → " + code(sl.destination) + " · " + (sl.duration || "");
- el.appendChild(s);
- });
- list.appendChild(el);
- });
-};
-""".strip()
-
-_AIRPORT_JS = """
-window.__nitroWidgetRender = function(data) {
- const list = document.getElementById("list");
- const meta = document.getElementById("meta");
- if (!list) return;
- const results = (data && (data.results || data.airports || data.places)) || [];
- if (meta) meta.textContent = "Query: " + ((data && data.query) || "") + " · " + results.length + " result(s)";
- list.innerHTML = "";
- if (!results.length) {
- list.innerHTML = 'No airports found.
';
- return;
- }
- results.forEach(function(item) {
- const el = document.createElement("div");
- el.className = "row";
- el.innerHTML = ' ';
- el.querySelector(".code").textContent = item.iata_code || item.iataCode || "";
- el.querySelector(".name").textContent = item.name || "";
- el.querySelector(".muted").textContent = (item.city_name || item.cityName || item.city || "") + " · " + (item.type || "airport");
- list.appendChild(el);
- });
-};
-""".strip()
-
-
-def _place_code_js() -> str:
- return """
- function code(p) {
- if (!p) return "";
- if (typeof p === "string") return p;
- return p.iata_code || p.iataCode || p.code || "";
- }
- function money(amount, currency) {
- if (amount == null || amount === "") return "";
- return String(amount) + (currency ? " " + currency : "");
- }
- function sliceHtml(sl) {
- const origin = code(sl.origin);
- const dest = code(sl.destination);
- const wrap = document.createElement("div");
- wrap.className = "slice";
- const title = document.createElement("strong");
- title.textContent = origin + " → " + dest;
- const times = document.createElement("div");
- times.className = "muted";
- times.textContent = (sl.departing_at || sl.departingAt || sl.departureTime || "") +
- " – " + (sl.arriving_at || sl.arrivingAt || sl.arrivalTime || "") +
- " · " + (sl.duration || "");
- wrap.appendChild(title);
- wrap.appendChild(times);
- return wrap;
- }
-""".strip()
-
-
-_FLIGHT_DETAILS_JS = f"""
-window.__nitroWidgetRender = function(data) {{
- const meta = document.getElementById("meta");
- const root = document.getElementById("root");
- if (!root) return;
- if (!data) {{
- if (meta) meta.textContent = "Waiting for get_flight_details result.";
- return;
- }}
-{_place_code_js()}
- const amount = data.total_amount || data.totalAmount || "";
- const currency = data.total_currency || data.totalCurrency || "";
- if (meta) meta.textContent = "Offer " + (data.id || "") + " · " + money(amount, currency);
- root.innerHTML = "";
- (data.slices || []).forEach(function(sl) {{ root.appendChild(sliceHtml(sl)); }});
- if (data.id) {{
- const actions = document.createElement("div");
- actions.className = "ns-actions";
- const btn = document.createElement("button");
- btn.type = "button";
- btn.className = "ns-btn ns-btn-primary";
- btn.setAttribute("data-call-tool", "get_seat_map");
- btn.setAttribute("data-args", JSON.stringify({{ offerId: data.id }}));
- btn.textContent = "Seat map";
- actions.appendChild(btn);
- root.appendChild(actions);
- }}
-}};
-""".strip()
-
-_ORDER_SUMMARY_JS = f"""
-window.__nitroWidgetRender = function(data) {{
- const root = document.getElementById("root");
- const card = document.querySelector(".card");
- if (!data) return;
-{_place_code_js()}
- const status = data.status || "held";
- const ref = data.booking_reference || data.bookingReference || "";
- const orderId = data.id || data.orderId || "";
- const amount = data.total_amount || data.totalAmount || "";
- const currency = data.total_currency || data.totalCurrency || "";
- const host = card || root;
- if (!host) return;
- host.innerHTML = "";
- const h1 = document.createElement("h1");
- h1.textContent = "Order " + status;
- const meta = document.createElement("div");
- meta.className = "meta";
- meta.textContent = "Ref " + ref + " · " + orderId;
- const price = document.createElement("div");
- price.className = "price";
- price.textContent = money(amount, currency);
- host.appendChild(h1);
- host.appendChild(meta);
- host.appendChild(price);
- const paxTitle = document.createElement("h2");
- paxTitle.textContent = "Passengers";
- host.appendChild(paxTitle);
- const passengers = data.passengers || [];
- if (!passengers.length) {{
- const empty = document.createElement("div");
- empty.className = "muted";
- empty.textContent = "None listed";
- host.appendChild(empty);
- }}
- passengers.forEach(function(p) {{
- const line = document.createElement("div");
- line.className = "muted";
- line.textContent = p.name || [p.given_name || p.givenName, p.family_name || p.familyName].filter(Boolean).join(" ") || p.id || "";
- host.appendChild(line);
- }});
- const itin = document.createElement("h2");
- itin.textContent = "Itinerary";
- host.appendChild(itin);
- (data.slices || []).forEach(function(sl) {{ host.appendChild(sliceHtml(sl)); }});
- if (orderId && String(status).toLowerCase().indexOf("cancel") < 0) {{
- const actions = document.createElement("div");
- actions.className = "ns-actions";
- const btn = document.createElement("button");
- btn.type = "button";
- btn.className = "ns-btn";
- btn.setAttribute("data-call-tool", "cancel_order");
- btn.setAttribute("data-args", JSON.stringify({{ orderId: orderId }}));
- btn.textContent = "Cancel order";
- actions.appendChild(btn);
- host.appendChild(actions);
- }}
-}};
-""".strip()
-
-_SEAT_JS = """
-window.__nitroWidgetRender = function(data) {
- const meta = document.getElementById("meta");
- const root = document.getElementById("root");
- if (!root) return;
- if (!data) {
- if (meta) meta.textContent = "Waiting for get_seat_map result.";
- return;
- }
- if (meta) meta.textContent = "Offer " + (data.offerId || data.offer_id || "");
- root.innerHTML = "";
- const cabins = data.cabins || [];
- if (!cabins.length) {
- root.innerHTML = 'No seat map data.
';
- return;
- }
- cabins.forEach(function(cabin) {
- const h2 = document.createElement("h2");
- h2.textContent = cabin.cabin_class || cabin.cabinClass || "cabin";
- root.appendChild(h2);
- (cabin.rows || []).forEach(function(row) {
- const line = document.createElement("div");
- line.className = "seat-row";
- const rn = document.createElement("span");
- rn.className = "rn";
- rn.textContent = row.row_number || row.rowNumber || "";
- line.appendChild(rn);
- let seats = row.seats || row.elements || [];
- if (!seats.length) {
- (row.sections || []).forEach(function(section) {
- seats = seats.concat(section.elements || []);
- });
- }
- seats.forEach(function(seat) {
- if (seat.type && seat.type !== "seat") return;
- const cell = document.createElement("span");
- const available = seat.available != null ? seat.available : (seat.available_services != null);
- cell.className = available ? "seat ok" : "seat no";
- cell.textContent = seat.designator || seat.id || seat.column || "";
- line.appendChild(cell);
- });
- root.appendChild(line);
- });
- });
-};
-""".strip()
-
-_CANCEL_JS = """
-window.__nitroWidgetRender = function(data) {
- const card = document.querySelector(".card");
- if (!card || !data) return;
- const status = data.status || "cancelled";
- const cid = data.id || data.cancellationId || "";
- const refund = data.refund_amount || data.refundAmount || "";
- const currency = data.refund_currency || data.refundCurrency || "";
- card.innerHTML = "";
- const h1 = document.createElement("h1");
- h1.textContent = "Booking cancelled";
- const meta = document.createElement("div");
- meta.className = "meta";
- meta.textContent = status + " · " + cid;
- const p = document.createElement("p");
- p.textContent = data.message || "Booking cancelled.";
- const price = document.createElement("div");
- price.className = "price";
- price.textContent = "Refund " + (refund ? (refund + (currency ? " " + currency : "")) : "n/a");
- card.appendChild(h1);
- card.appendChild(meta);
- card.appendChild(p);
- card.appendChild(price);
-};
-""".strip()
-
-
-def _page(
- title: str,
- styles: str,
- body: str,
- render_js: str,
- data: Any | None,
- extra_head: str = "",
- flush: bool = False,
- chrome: bool = True,
-) -> str:
- return wrap_widget_page(
- title=title,
- styles=styles,
- body=body,
- render_js=render_js,
- data=data,
- extra_head=extra_head,
- flush=flush,
- chrome=chrome,
- )
-
-
-def build_generic_widget(route: str, data: Any | None = None) -> str:
- return _page(route, _GENERIC_CSS, render_body(route, data), _generic_render_js(), data)
-
-
-def build_missing_widget(route: str, data: Any | None = None) -> str:
- return _page(
- f"Missing widget: {route}",
- _MISSING_CSS,
- missing_body(route),
- _generic_render_js(),
- data,
- )
-
-
-def build_pizza_list_widget(data: Any | None = None) -> str:
- return _page("Pizza shops", _PIZZA_LIST_CSS, render_body("pizza-list", data), _PIZZA_LIST_JS, data)
-
-
-def build_pizza_map_widget(data: Any | None = None) -> str:
- return _page(
- "Pizza map",
- _PIZZA_MAP_CSS,
- render_body("pizza-map", data),
- _pizza_map_js(),
- data,
- extra_head=_MAPBOX_HEAD,
- flush=True,
- )
-
-
-def build_pizza_shop_widget(data: Any | None = None) -> str:
- return _page("Pizza shop", _PIZZA_SHOP_CSS, render_body("pizza-shop", data), _PIZZA_SHOP_JS, data)
-
-
-def build_calculator_result_widget(data: Any | None = None) -> str:
- return _page(
- "Calculator result",
- _CALC_CSS,
- render_body("calculator-result", data),
- _CALC_JS,
- data,
- )
-
-
-def build_card_widget(data: Any | None = None) -> str:
- return _page("Product Card", _CARD_CSS, render_body("card", data), _CARD_JS, data)
-
-
-def build_table_widget(data: Any | None = None) -> str:
- return _page("Data Table", _TABLE_CSS, render_body("table", data), _TABLE_JS, data)
-
-
-def build_chart_widget(data: Any | None = None) -> str:
- return _page("Bar Chart", _CHART_CSS, render_body("chart", data), _CHART_JS, data)
-
-
-def build_flight_search_results_widget(data: Any | None = None) -> str:
- return _page(
- "Flight search",
- _FLIGHT_CSS,
- render_body("flight-search-results", data),
- _FLIGHT_SEARCH_JS,
- data,
- )
-
-
-def build_flight_details_widget(data: Any | None = None) -> str:
- return _page(
- "Flight details",
- _FLIGHT_CSS,
- render_body("flight-details", data),
- _FLIGHT_DETAILS_JS,
- data,
- )
-
-
-def build_airport_search_widget(data: Any | None = None) -> str:
- return _page(
- "Airport search",
- _FLIGHT_CSS,
- render_body("airport-search", data),
- _AIRPORT_JS,
- data,
- )
-
-
-def build_order_summary_widget(data: Any | None = None) -> str:
- return _page(
- "Order summary",
- _FLIGHT_CSS,
- render_body("order-summary", data),
- _ORDER_SUMMARY_JS,
- data,
- )
-
-
-def build_seat_selection_widget(data: Any | None = None) -> str:
- return _page(
- "Seat map",
- _FLIGHT_CSS,
- render_body("seat-selection", data),
- _SEAT_JS,
- data,
- )
+from __future__ import annotations
+from typing import Any, Callable, Dict, Optional
-def build_order_cancellation_widget(data: Any | None = None) -> str:
- return _page(
- "Cancellation",
- _FLIGHT_CSS,
- render_body("order-cancellation", data),
- _CANCEL_JS,
- data,
- )
+from nitrostack.widgets.host_bridge import wrap_widget_page # noqa: F401
+from nitrostack.widgets.views import missing_body, render_body # noqa: F401
+from nitrostack.widgets.route_templates_generic import ( # noqa: F401
+ _generic_render_js,
+ _CALC_CSS,
+ _CARD_CSS,
+ _TABLE_CSS,
+ _CHART_CSS,
+ _GENERIC_CSS,
+ _MISSING_CSS,
+ _CALC_JS,
+ _CARD_JS,
+ _TABLE_JS,
+ _CHART_JS,
+ _page,
+ build_generic_widget,
+ build_missing_widget,
+ build_calculator_result_widget,
+ build_card_widget,
+ build_table_widget,
+ build_chart_widget,
+)
+from nitrostack.widgets.route_templates_pizza import ( # noqa: F401
+ _PIZZA_LIST_CSS,
+ _PIZZA_MAP_CSS,
+ _PIZZA_SHOP_CSS,
+ _PIZZA_LIST_JS,
+ _MAPBOX_HEAD,
+ _pizza_map_js,
+ _PIZZA_SHOP_JS,
+ build_pizza_list_widget,
+ build_pizza_map_widget,
+ build_pizza_shop_widget,
+)
+from nitrostack.widgets.route_templates_flight import ( # noqa: F401
+ _FLIGHT_CSS,
+ _FLIGHT_SEARCH_JS,
+ _AIRPORT_JS,
+ _place_code_js,
+ _FLIGHT_DETAILS_JS,
+ _ORDER_SUMMARY_JS,
+ _SEAT_JS,
+ _CANCEL_JS,
+ build_flight_search_results_widget,
+ build_flight_details_widget,
+ build_airport_search_widget,
+ build_order_summary_widget,
+ build_seat_selection_widget,
+ build_order_cancellation_widget,
+)
_ROUTE_BUILDERS: Dict[str, Callable[[Any | None], str]] = {
diff --git a/nitrostack/widgets/route_templates_flight.py b/nitrostack/widgets/route_templates_flight.py
new file mode 100644
index 0000000..8736783
--- /dev/null
+++ b/nitrostack/widgets/route_templates_flight.py
@@ -0,0 +1,357 @@
+"""Flight and order widget templates (CSS and render JS)."""
+
+from __future__ import annotations
+
+from typing import Any
+
+from nitrostack.widgets.route_templates_generic import _page
+from nitrostack.widgets.views import render_body
+
+
+_FLIGHT_CSS = """
+ :root { --ns-accent: #0369a1; --ns-accent-soft: #e0f2fe; }
+ .offer, .card, #list .row { background: var(--ns-surface); border: 1px solid var(--ns-border); border-radius: var(--ns-radius); padding: 12px; margin-bottom: 10px; }
+ .row { display: flex; gap: 12px; align-items: center; }
+ .id { font-size: 0.8rem; color: var(--ns-muted); }
+ .code { font-size: 1.1rem; font-weight: 800; min-width: 3rem; }
+ .slice { margin-top: 8px; }
+ .seat-row { display: flex; gap: 6px; align-items: center; margin: 4px 0; }
+ .rn { width: 2rem; font-size: 0.8rem; color: var(--ns-muted); }
+ .seat { display: inline-block; min-width: 2.4rem; text-align: center; padding: 4px; border-radius: 6px; font-size: 0.75rem; }
+"""
+
+
+_FLIGHT_SEARCH_JS = """
+window.__nitroWidgetRender = function(data) {
+ const list = document.getElementById("list");
+ const meta = document.getElementById("meta");
+ if (!list) return;
+ const offers = (data && (data.offers || data.results)) || [];
+ const params = (data && data.searchParams) || {};
+ const total = (data && data.totalOffers != null) ? data.totalOffers : offers.length;
+ if (meta) {
+ meta.textContent = (params.origin && params.destination)
+ ? (params.origin + " → " + params.destination + " · " + total + " offer" + (total === 1 ? "" : "s"))
+ : (total + " offer" + (total === 1 ? "" : "s"));
+ }
+ list.innerHTML = "";
+ if (!offers.length) {
+ list.innerHTML = 'No flight offers.
';
+ return;
+ }
+ function code(p) {
+ if (!p) return "";
+ if (typeof p === "string") return p;
+ return p.iata_code || p.iataCode || p.code || "";
+ }
+ function legs(offer) {
+ if (offer.slices && offer.slices.length) return offer.slices;
+ const out = [];
+ if (offer.outbound) out.push(offer.outbound);
+ if (offer.return) out.push(offer.return);
+ return out;
+ }
+ offers.forEach(function(offer) {
+ const el = document.createElement("article");
+ el.className = "offer ns-card";
+ el.setAttribute("data-call-tool", "get_flight_details");
+ el.setAttribute("data-args", JSON.stringify({ offerId: offer.id || "" }));
+ el.setAttribute("role", "button");
+ el.tabIndex = 0;
+ const amount = offer.total_amount || offer.totalAmount || "";
+ const currency = offer.total_currency || offer.totalCurrency || "";
+ el.innerHTML = '
';
+ el.querySelector(".price").textContent = amount + (currency ? " " + currency : "");
+ el.querySelector(".id").textContent = offer.id || "";
+ legs(offer).forEach(function(sl) {
+ const s = document.createElement("div");
+ s.className = "slice";
+ s.textContent = code(sl.origin) + " → " + code(sl.destination) + " · " + (sl.duration || "");
+ el.appendChild(s);
+ });
+ list.appendChild(el);
+ });
+};
+""".strip()
+
+
+_AIRPORT_JS = """
+window.__nitroWidgetRender = function(data) {
+ const list = document.getElementById("list");
+ const meta = document.getElementById("meta");
+ if (!list) return;
+ const results = (data && (data.results || data.airports || data.places)) || [];
+ if (meta) meta.textContent = "Query: " + ((data && data.query) || "") + " · " + results.length + " result(s)";
+ list.innerHTML = "";
+ if (!results.length) {
+ list.innerHTML = 'No airports found.
';
+ return;
+ }
+ results.forEach(function(item) {
+ const el = document.createElement("div");
+ el.className = "row";
+ el.innerHTML = ' ';
+ el.querySelector(".code").textContent = item.iata_code || item.iataCode || "";
+ el.querySelector(".name").textContent = item.name || "";
+ el.querySelector(".muted").textContent = (item.city_name || item.cityName || item.city || "") + " · " + (item.type || "airport");
+ list.appendChild(el);
+ });
+};
+""".strip()
+
+
+def _place_code_js() -> str:
+ return """
+ function code(p) {
+ if (!p) return "";
+ if (typeof p === "string") return p;
+ return p.iata_code || p.iataCode || p.code || "";
+ }
+ function money(amount, currency) {
+ if (amount == null || amount === "") return "";
+ return String(amount) + (currency ? " " + currency : "");
+ }
+ function sliceHtml(sl) {
+ const origin = code(sl.origin);
+ const dest = code(sl.destination);
+ const wrap = document.createElement("div");
+ wrap.className = "slice";
+ const title = document.createElement("strong");
+ title.textContent = origin + " → " + dest;
+ const times = document.createElement("div");
+ times.className = "muted";
+ times.textContent = (sl.departing_at || sl.departingAt || sl.departureTime || "") +
+ " – " + (sl.arriving_at || sl.arrivingAt || sl.arrivalTime || "") +
+ " · " + (sl.duration || "");
+ wrap.appendChild(title);
+ wrap.appendChild(times);
+ return wrap;
+ }
+""".strip()
+
+
+_FLIGHT_DETAILS_JS = f"""
+window.__nitroWidgetRender = function(data) {{
+ const meta = document.getElementById("meta");
+ const root = document.getElementById("root");
+ if (!root) return;
+ if (!data) {{
+ if (meta) meta.textContent = "Waiting for get_flight_details result.";
+ return;
+ }}
+{_place_code_js()}
+ const amount = data.total_amount || data.totalAmount || "";
+ const currency = data.total_currency || data.totalCurrency || "";
+ if (meta) meta.textContent = "Offer " + (data.id || "") + " · " + money(amount, currency);
+ root.innerHTML = "";
+ (data.slices || []).forEach(function(sl) {{ root.appendChild(sliceHtml(sl)); }});
+ if (data.id) {{
+ const actions = document.createElement("div");
+ actions.className = "ns-actions";
+ const btn = document.createElement("button");
+ btn.type = "button";
+ btn.className = "ns-btn ns-btn-primary";
+ btn.setAttribute("data-call-tool", "get_seat_map");
+ btn.setAttribute("data-args", JSON.stringify({{ offerId: data.id }}));
+ btn.textContent = "Seat map";
+ actions.appendChild(btn);
+ root.appendChild(actions);
+ }}
+}};
+""".strip()
+
+
+_ORDER_SUMMARY_JS = f"""
+window.__nitroWidgetRender = function(data) {{
+ const root = document.getElementById("root");
+ const card = document.querySelector(".card");
+ if (!data) return;
+{_place_code_js()}
+ const status = data.status || "held";
+ const ref = data.booking_reference || data.bookingReference || "";
+ const orderId = data.id || data.orderId || "";
+ const amount = data.total_amount || data.totalAmount || "";
+ const currency = data.total_currency || data.totalCurrency || "";
+ const host = card || root;
+ if (!host) return;
+ host.innerHTML = "";
+ const h1 = document.createElement("h1");
+ h1.textContent = "Order " + status;
+ const meta = document.createElement("div");
+ meta.className = "meta";
+ meta.textContent = "Ref " + ref + " · " + orderId;
+ const price = document.createElement("div");
+ price.className = "price";
+ price.textContent = money(amount, currency);
+ host.appendChild(h1);
+ host.appendChild(meta);
+ host.appendChild(price);
+ const paxTitle = document.createElement("h2");
+ paxTitle.textContent = "Passengers";
+ host.appendChild(paxTitle);
+ const passengers = data.passengers || [];
+ if (!passengers.length) {{
+ const empty = document.createElement("div");
+ empty.className = "muted";
+ empty.textContent = "None listed";
+ host.appendChild(empty);
+ }}
+ passengers.forEach(function(p) {{
+ const line = document.createElement("div");
+ line.className = "muted";
+ line.textContent = p.name || [p.given_name || p.givenName, p.family_name || p.familyName].filter(Boolean).join(" ") || p.id || "";
+ host.appendChild(line);
+ }});
+ const itin = document.createElement("h2");
+ itin.textContent = "Itinerary";
+ host.appendChild(itin);
+ (data.slices || []).forEach(function(sl) {{ host.appendChild(sliceHtml(sl)); }});
+ if (orderId && String(status).toLowerCase().indexOf("cancel") < 0) {{
+ const actions = document.createElement("div");
+ actions.className = "ns-actions";
+ const btn = document.createElement("button");
+ btn.type = "button";
+ btn.className = "ns-btn";
+ btn.setAttribute("data-call-tool", "cancel_order");
+ btn.setAttribute("data-args", JSON.stringify({{ orderId: orderId }}));
+ btn.textContent = "Cancel order";
+ actions.appendChild(btn);
+ host.appendChild(actions);
+ }}
+}};
+""".strip()
+
+
+_SEAT_JS = """
+window.__nitroWidgetRender = function(data) {
+ const meta = document.getElementById("meta");
+ const root = document.getElementById("root");
+ if (!root) return;
+ if (!data) {
+ if (meta) meta.textContent = "Waiting for get_seat_map result.";
+ return;
+ }
+ if (meta) meta.textContent = "Offer " + (data.offerId || data.offer_id || "");
+ root.innerHTML = "";
+ const cabins = data.cabins || [];
+ if (!cabins.length) {
+ root.innerHTML = 'No seat map data.
';
+ return;
+ }
+ cabins.forEach(function(cabin) {
+ const h2 = document.createElement("h2");
+ h2.textContent = cabin.cabin_class || cabin.cabinClass || "cabin";
+ root.appendChild(h2);
+ (cabin.rows || []).forEach(function(row) {
+ const line = document.createElement("div");
+ line.className = "seat-row";
+ const rn = document.createElement("span");
+ rn.className = "rn";
+ rn.textContent = row.row_number || row.rowNumber || "";
+ line.appendChild(rn);
+ let seats = row.seats || row.elements || [];
+ if (!seats.length) {
+ (row.sections || []).forEach(function(section) {
+ seats = seats.concat(section.elements || []);
+ });
+ }
+ seats.forEach(function(seat) {
+ if (seat.type && seat.type !== "seat") return;
+ const cell = document.createElement("span");
+ const available = seat.available != null ? seat.available : (seat.available_services != null);
+ cell.className = available ? "seat ok" : "seat no";
+ cell.textContent = seat.designator || seat.id || seat.column || "";
+ line.appendChild(cell);
+ });
+ root.appendChild(line);
+ });
+ });
+};
+""".strip()
+
+
+_CANCEL_JS = """
+window.__nitroWidgetRender = function(data) {
+ const card = document.querySelector(".card");
+ if (!card || !data) return;
+ const status = data.status || "cancelled";
+ const cid = data.id || data.cancellationId || "";
+ const refund = data.refund_amount || data.refundAmount || "";
+ const currency = data.refund_currency || data.refundCurrency || "";
+ card.innerHTML = "";
+ const h1 = document.createElement("h1");
+ h1.textContent = "Booking cancelled";
+ const meta = document.createElement("div");
+ meta.className = "meta";
+ meta.textContent = status + " · " + cid;
+ const p = document.createElement("p");
+ p.textContent = data.message || "Booking cancelled.";
+ const price = document.createElement("div");
+ price.className = "price";
+ price.textContent = "Refund " + (refund ? (refund + (currency ? " " + currency : "")) : "n/a");
+ card.appendChild(h1);
+ card.appendChild(meta);
+ card.appendChild(p);
+ card.appendChild(price);
+};
+""".strip()
+
+
+def build_flight_search_results_widget(data: Any | None = None) -> str:
+ return _page(
+ "Flight search",
+ _FLIGHT_CSS,
+ render_body("flight-search-results", data),
+ _FLIGHT_SEARCH_JS,
+ data,
+ )
+
+
+def build_flight_details_widget(data: Any | None = None) -> str:
+ return _page(
+ "Flight details",
+ _FLIGHT_CSS,
+ render_body("flight-details", data),
+ _FLIGHT_DETAILS_JS,
+ data,
+ )
+
+
+def build_airport_search_widget(data: Any | None = None) -> str:
+ return _page(
+ "Airport search",
+ _FLIGHT_CSS,
+ render_body("airport-search", data),
+ _AIRPORT_JS,
+ data,
+ )
+
+
+def build_order_summary_widget(data: Any | None = None) -> str:
+ return _page(
+ "Order summary",
+ _FLIGHT_CSS,
+ render_body("order-summary", data),
+ _ORDER_SUMMARY_JS,
+ data,
+ )
+
+
+def build_seat_selection_widget(data: Any | None = None) -> str:
+ return _page(
+ "Seat map",
+ _FLIGHT_CSS,
+ render_body("seat-selection", data),
+ _SEAT_JS,
+ data,
+ )
+
+
+def build_order_cancellation_widget(data: Any | None = None) -> str:
+ return _page(
+ "Cancellation",
+ _FLIGHT_CSS,
+ render_body("order-cancellation", data),
+ _CANCEL_JS,
+ data,
+ )
diff --git a/nitrostack/widgets/route_templates_generic.py b/nitrostack/widgets/route_templates_generic.py
new file mode 100644
index 0000000..13deefc
--- /dev/null
+++ b/nitrostack/widgets/route_templates_generic.py
@@ -0,0 +1,206 @@
+"""Page wrapper plus the generic, missing, calculator, card, table and chart widget templates."""
+
+from __future__ import annotations
+
+from typing import Any
+
+from nitrostack.widgets.host_bridge import wrap_widget_page
+from nitrostack.widgets.views import missing_body, render_body
+
+
+def _generic_render_js() -> str:
+ return """
+window.__nitroWidgetRender = function(data) {
+ const root = document.getElementById("root");
+ const meta = document.getElementById("meta");
+ if (!root) return;
+ if (!data) {
+ if (meta) meta.textContent = "Waiting for tool result (host injects tool output).";
+ return;
+ }
+ if (meta) meta.textContent = "Tool output";
+ root.innerHTML = "";
+ const pre = document.createElement("pre");
+ pre.textContent = JSON.stringify(data, null, 2);
+ root.appendChild(pre);
+};
+""".strip()
+
+
+_CALC_CSS = """
+ :root { --ns-accent: #15803d; }
+ .card { background: var(--ns-surface); border: 1px solid var(--ns-border); border-radius: var(--ns-radius); padding: 20px; text-align: center; }
+ .expr { font-size: 0.95rem; color: var(--ns-muted); margin-bottom: 8px; }
+ .result { font-size: 2rem; font-weight: 800; color: var(--ns-accent); }
+"""
+
+
+_CARD_CSS = """
+ .card { background: var(--ns-surface); border-radius: var(--ns-radius); padding: 20px; box-shadow: var(--ns-shadow); max-width: 320px; border: 1px solid var(--ns-border); }
+ .card h2 { margin: 0 0 8px; font-size: 1.25rem; }
+ .price { font-size: 1.5rem; }
+ .desc { color: var(--ns-muted); margin-top: 8px; }
+"""
+
+
+_TABLE_CSS = """
+ table { border-collapse: collapse; width: 100%; max-width: 480px; background: var(--ns-surface); border-radius: 10px; overflow: hidden; }
+ th, td { border: 1px solid var(--ns-border); padding: 8px 12px; text-align: left; }
+ th { background: var(--ns-accent-soft); }
+"""
+
+
+_CHART_CSS = """
+ .chart { display: flex; align-items: flex-end; gap: 8px; height: 160px; }
+ .bar-wrap { flex: 1; display: flex; flex-direction: column; align-items: center; }
+ .bar { width: 100%; background: var(--ns-accent, #3b82f6); border-radius: 4px 4px 0 0; min-height: 4px; }
+ .label { font-size: 12px; margin-top: 4px; color: var(--ns-muted); }
+"""
+
+
+_GENERIC_CSS = """
+ pre { background: var(--ns-surface); border: 1px solid var(--ns-border); border-radius: 8px; padding: 12px; overflow: auto; }
+"""
+
+
+_MISSING_CSS = """
+ :root { --ns-bg: #fef2f2; --ns-text: #7f1d1d; }
+ .meta { font-size: 0.9rem; line-height: 1.5; }
+"""
+
+
+_CALC_JS = """
+window.__nitroWidgetRender = function(data) {
+ if (!data) return;
+ const expr = document.getElementById("expr");
+ const result = document.getElementById("result");
+ if (data.expression) expr.textContent = data.expression;
+ if (data.result != null) result.textContent = String(data.result);
+ else if (data.value != null) result.textContent = String(data.value);
+};
+""".strip()
+
+
+_CARD_JS = """
+window.__nitroWidgetRender = function(data) {
+ if (!data) return;
+ const name = document.getElementById("name");
+ const price = document.getElementById("price");
+ const desc = document.getElementById("desc");
+ if (name) name.textContent = data.name || "—";
+ if (price) price.textContent = data.price != null ? "$" + Number(data.price).toFixed(2) : "—";
+ if (desc) desc.textContent = data.description || "";
+};
+""".strip()
+
+
+_TABLE_JS = """
+window.__nitroWidgetRender = function(data) {
+ if (!data || !Array.isArray(data.rows)) return;
+ const cols = data.columns || Object.keys(data.rows[0] || {});
+ const header = document.getElementById("header");
+ const body = document.getElementById("body");
+ if (!header || !body) return;
+ header.innerHTML = "";
+ body.innerHTML = "";
+ cols.forEach(function(c) {
+ const th = document.createElement("th");
+ th.textContent = c;
+ header.appendChild(th);
+ });
+ data.rows.forEach(function(row) {
+ const tr = document.createElement("tr");
+ cols.forEach(function(c) {
+ const td = document.createElement("td");
+ td.textContent = row[c] ?? "";
+ tr.appendChild(td);
+ });
+ body.appendChild(tr);
+ });
+};
+""".strip()
+
+
+_CHART_JS = """
+window.__nitroWidgetRender = function(data) {
+ if (!data) return;
+ const title = document.getElementById("title");
+ const chart = document.getElementById("chart");
+ if (title) title.textContent = data.title || "Chart";
+ if (!chart) return;
+ chart.innerHTML = "";
+ const items = data.items || [];
+ const max = Math.max.apply(null, items.map(function(i) { return i.value || 0; }).concat([1]));
+ items.forEach(function(item) {
+ const wrap = document.createElement("div");
+ wrap.className = "bar-wrap";
+ const bar = document.createElement("div");
+ bar.className = "bar";
+ bar.style.height = (((item.value || 0) / max) * 140) + "px";
+ const label = document.createElement("div");
+ label.className = "label";
+ label.textContent = item.label || "";
+ wrap.appendChild(bar);
+ wrap.appendChild(label);
+ chart.appendChild(wrap);
+ });
+};
+""".strip()
+
+
+def _page(
+ title: str,
+ styles: str,
+ body: str,
+ render_js: str,
+ data: Any | None,
+ extra_head: str = "",
+ flush: bool = False,
+ chrome: bool = True,
+) -> str:
+ return wrap_widget_page(
+ title=title,
+ styles=styles,
+ body=body,
+ render_js=render_js,
+ data=data,
+ extra_head=extra_head,
+ flush=flush,
+ chrome=chrome,
+ )
+
+
+def build_generic_widget(route: str, data: Any | None = None) -> str:
+ return _page(route, _GENERIC_CSS, render_body(route, data), _generic_render_js(), data)
+
+
+def build_missing_widget(route: str, data: Any | None = None) -> str:
+ return _page(
+ f"Missing widget: {route}",
+ _MISSING_CSS,
+ missing_body(route),
+ _generic_render_js(),
+ data,
+ )
+
+
+def build_calculator_result_widget(data: Any | None = None) -> str:
+ return _page(
+ "Calculator result",
+ _CALC_CSS,
+ render_body("calculator-result", data),
+ _CALC_JS,
+ data,
+ )
+
+
+def build_card_widget(data: Any | None = None) -> str:
+ return _page("Product Card", _CARD_CSS, render_body("card", data), _CARD_JS, data)
+
+
+def build_table_widget(data: Any | None = None) -> str:
+ return _page("Data Table", _TABLE_CSS, render_body("table", data), _TABLE_JS, data)
+
+
+def build_chart_widget(data: Any | None = None) -> str:
+ return _page("Bar Chart", _CHART_CSS, render_body("chart", data), _CHART_JS, data)
diff --git a/nitrostack/widgets/route_templates_pizza.py b/nitrostack/widgets/route_templates_pizza.py
new file mode 100644
index 0000000..fa440fb
--- /dev/null
+++ b/nitrostack/widgets/route_templates_pizza.py
@@ -0,0 +1,303 @@
+"""Pizza list, map and shop widget templates (CSS and render JS)."""
+
+from __future__ import annotations
+
+from typing import Any
+
+from nitrostack.widgets.route_templates_generic import _page
+from nitrostack.widgets.views import render_body
+
+
+_PIZZA_LIST_CSS = """
+ :root { --ns-accent: #ea580c; --ns-accent-soft: #ffedd5; }
+ .shop { min-width: 260px; max-width: 260px; scroll-snap-align: start; flex-shrink: 0; }
+ .img { width: 100%; height: 120px; object-fit: cover; border-radius: 10px; margin-bottom: 8px; background: var(--ns-accent-soft); }
+ .row { display: flex; justify-content: space-between; gap: 8px; align-items: baseline; }
+ .name { font-weight: 700; }
+ .addr { color: var(--ns-muted); font-size: 0.85rem; margin-top: 4px; }
+"""
+
+
+_PIZZA_MAP_CSS = """
+ :root { --ns-accent: #ea580c; }
+ html, body { width: 100%; height: 560px; }
+ body { position: relative; min-height: 560px; background: #e5e7eb; }
+ .meta { position: absolute; top: 12px; left: 12px; z-index: 3; margin: 0;
+ background: color-mix(in srgb, var(--ns-surface) 92%, transparent); border-radius: 8px; padding: 6px 10px;
+ box-shadow: var(--ns-shadow); }
+ .map { position: absolute; inset: 0; width: 100%; height: 560px; min-height: 560px; }
+ .map-live { position: absolute; inset: 0; }
+ .static-map { position: absolute; inset: 0; z-index: 1; width: 100%; height: 560px;
+ object-fit: cover; transition: opacity .4s ease; }
+ .static-map.is-ready { opacity: 0; pointer-events: none; }
+ .mapboxgl-map { width: 100%; height: 100%; }
+ .cards { position: absolute; left: 16px; right: 16px; bottom: 8px; z-index: 3; }
+ .map-card { min-width: 220px; max-width: 220px; flex-shrink: 0; scroll-snap-align: start; }
+ .map-card .name { font-weight: 700; }
+ .map-card .muted { margin-top: 4px; }
+ .map-card .rating { margin-top: 4px; }
+"""
+
+
+_PIZZA_SHOP_CSS = """
+ :root { --ns-accent: #e11d48; --ns-accent-soft: #ffe4e6; }
+ .card { background: var(--ns-surface); border-radius: var(--ns-radius); padding: 16px; border: 1px solid var(--ns-border); }
+ .hero { width: 100%; max-height: 180px; object-fit: cover; border-radius: 10px; margin-bottom: 12px; }
+ .chips { margin-top: 10px; }
+ .chip { margin: 0 4px 4px 0; }
+"""
+
+
+_PIZZA_LIST_JS = """
+window.__nitroWidgetRender = function(data) {
+ const list = document.getElementById("list");
+ const meta = document.getElementById("meta");
+ if (!list || !meta) return;
+ list.innerHTML = "";
+ if (!data || !Array.isArray(data.shops)) {
+ meta.textContent = "Waiting for show_pizza_list result.";
+ return;
+ }
+ const state = (window.openai && window.openai.widgetState) || {};
+ const sort = state.sort || "rating";
+ const shops = data.shops.slice().sort(function(a, b) {
+ if (sort === "name") return String(a.name || "").localeCompare(String(b.name || ""));
+ return (b.rating || 0) - (a.rating || 0);
+ });
+ document.querySelectorAll("#sorts [data-sort]").forEach(function(btn) {
+ btn.classList.toggle("is-on", btn.getAttribute("data-sort") === sort);
+ });
+ const total = data.totalShops ?? data.shops.length;
+ meta.textContent = total + " shop" + (total === 1 ? "" : "s");
+ if (!shops.length) {
+ list.innerHTML = 'No shops match these filters.
';
+ return;
+ }
+ shops.forEach(function(shop) {
+ const el = document.createElement("article");
+ el.className = "shop ns-card";
+ el.setAttribute("data-call-tool", "show_pizza_shop");
+ el.setAttribute("data-args", JSON.stringify({ shopId: shop.id || "" }));
+ el.setAttribute("role", "button");
+ el.tabIndex = 0;
+ const open = shop.openNow
+ ? 'Open '
+ : 'Closed ';
+ const price = "$".repeat(shop.priceLevel || 1);
+ let img = "";
+ if (shop.image) {
+ img = ' ';
+ }
+ el.innerHTML =
+ img +
+ '
' +
+ '
' + open + '
';
+ el.querySelector(".name").textContent = shop.name || shop.id || "Shop";
+ el.querySelector(".rating").textContent = shop.rating != null ? "★ " + shop.rating : "";
+ el.querySelector(".addr").textContent = shop.address || "";
+ el.querySelector(".price").textContent = price;
+ list.appendChild(el);
+ });
+};
+document.addEventListener("click", function(ev) {
+ const btn = ev.target.closest("#sorts [data-sort]");
+ if (!btn || !window.nitrostack) return;
+ const next = Object.assign({}, (window.openai && window.openai.widgetState) || {}, {
+ sort: btn.getAttribute("data-sort")
+ });
+ window.nitrostack.setWidgetState(next);
+ if (typeof window.__nitroWidgetRender === "function" && window.nitrostack.readHostData) {
+ window.__nitroWidgetRender(window.nitrostack.readHostData());
+ }
+});
+""".strip()
+
+
+_MAPBOX_HEAD = """
+
+
+""".strip()
+
+
+def _pizza_map_js() -> str:
+ import json
+
+ from nitrostack.widgets.html_util import get_mapbox_token
+
+ token = json.dumps(get_mapbox_token())
+ return f"""
+window.__NITRO_MAPBOX_TOKEN = {token};
+window.__nitroWidgetRender = function(data) {{
+ const meta = document.getElementById("meta");
+ const mapEl = document.getElementById("map-live") || document.getElementById("map");
+ const cards = document.getElementById("cards");
+ const staticEl = document.getElementById("static-map");
+ if (!mapEl) return;
+ if (!data || !Array.isArray(data.shops) || !data.shops.length) {{
+ if (meta) meta.textContent = "Waiting for show_pizza_map result.";
+ return;
+ }}
+ const shops = data.shops.filter(function(s) {{ return Array.isArray(s.coords) && s.coords.length === 2; }});
+ const sig = (data.filter || "all") + "|" + shops.map(function(s) {{
+ return (s.id || "") + ":" + s.coords[0] + "," + s.coords[1];
+ }}).join(";");
+ if (window.__nitroMapSig === sig && window.__nitroMap) return;
+ if (meta) meta.textContent = (data.totalShops ?? data.shops.length) + " shops · filter: " + (data.filter || "all");
+ if (cards && !cards.querySelector(".map-card")) {{
+ data.shops.forEach(function(shop) {{
+ const card = document.createElement("article");
+ card.className = "map-card ns-card";
+ card.setAttribute("data-shop-id", shop.id || "");
+ card.setAttribute("data-call-tool", "show_pizza_shop");
+ card.setAttribute("data-args", JSON.stringify({{ shopId: shop.id || "" }}));
+ card.setAttribute("role", "button");
+ card.tabIndex = 0;
+ card.innerHTML = '
';
+ card.querySelector(".name").textContent = shop.name || shop.id || "Shop";
+ card.querySelector(".muted").textContent = shop.address || "";
+ card.querySelector(".rating").textContent = shop.rating != null ? "★ " + shop.rating : "";
+ cards.appendChild(card);
+ }});
+ }}
+ function revealLive() {{
+ if (staticEl) staticEl.classList.add("is-ready");
+ }}
+ function mountMap(attempt) {{
+ if (window.__nitroMapSig === sig && window.__nitroMap) return;
+ if (!window.__NITRO_MAPBOX_TOKEN) {{
+ if (meta) meta.textContent = "Set MAPBOX_TOKEN in .env to load the map.";
+ if (mapEl) {{
+ mapEl.innerHTML = 'Set MAPBOX_TOKEN in .env (Mapbox public pk. token) to load the map.
';
+ }}
+ return;
+ }}
+ if (typeof mapboxgl === "undefined") {{
+ if ((attempt || 0) < 80) {{
+ setTimeout(function() {{ mountMap((attempt || 0) + 1); }}, 50);
+ }}
+ return;
+ }}
+ window.__nitroMapSig = sig;
+ if (window.__nitroMap) {{
+ window.__nitroMap.remove();
+ window.__nitroMap = null;
+ }}
+ mapboxgl.accessToken = window.__NITRO_MAPBOX_TOKEN;
+ const first = (shops[0] && shops[0].coords) || [-122.4194, 37.7749];
+ const map = new mapboxgl.Map({{
+ container: mapEl,
+ style: "mapbox://styles/mapbox/streets-v12",
+ center: first,
+ zoom: 12,
+ cooperativeGestures: false,
+ fadeDuration: 0
+ }});
+ map.addControl(new mapboxgl.NavigationControl({{ showCompass: false }}), "top-right");
+ map.addControl(new mapboxgl.FullscreenControl(), "top-right");
+ shops.forEach(function(shop) {{
+ const el = document.createElement("div");
+ el.style.backgroundImage = "url(https://docs.mapbox.com/mapbox-gl-js/assets/custom_marker.png)";
+ el.style.width = "30px";
+ el.style.height = "40px";
+ el.style.backgroundSize = "100%";
+ el.style.cursor = "pointer";
+ el.title = shop.name || shop.id || "";
+ el.addEventListener("click", function() {{
+ if (window.nitrostack) window.nitrostack.callTool("show_pizza_shop", {{ shopId: shop.id || "" }});
+ }});
+ new mapboxgl.Marker(el).setLngLat(shop.coords).addTo(map);
+ }});
+ if (shops.length > 1) {{
+ const bounds = new mapboxgl.LngLatBounds();
+ shops.forEach(function(s) {{ bounds.extend(s.coords); }});
+ map.fitBounds(bounds, {{ padding: 60, maxZoom: 14, duration: 0 }});
+ }}
+ map.once("idle", function() {{
+ try {{ map.resize(); }} catch (e) {{}}
+ revealLive();
+ }});
+ window.__nitroMap = map;
+ }}
+ mountMap(0);
+}};
+""".strip()
+
+
+_PIZZA_SHOP_JS = """
+window.__nitroWidgetRender = function(data) {
+ const shop = data && (data.shop || data);
+ const hero = document.getElementById("hero");
+ if (!shop || !shop.name) {
+ const desc = document.getElementById("desc");
+ if (desc) desc.textContent = "Waiting for show_pizza_shop result.";
+ return;
+ }
+ if (shop.image && hero) {
+ hero.src = shop.image;
+ hero.style.display = "block";
+ } else if (hero) {
+ hero.style.display = "none";
+ }
+ document.getElementById("name").textContent = shop.name;
+ document.getElementById("rating").textContent =
+ shop.rating != null ? "★ " + shop.rating + " (" + (shop.reviews || 0) + " reviews)" : "";
+ document.getElementById("desc").textContent = shop.description || "";
+ document.getElementById("addr").textContent = shop.address || "";
+ const hours = shop.hours ? (shop.hours.open + " – " + shop.hours.close) : "";
+ document.getElementById("hours").textContent = hours ? "Hours: " + hours : "";
+ document.getElementById("phone").textContent = shop.phone || "";
+ const chips = document.getElementById("chips");
+ chips.innerHTML = "";
+ (shop.specialties || []).forEach(function(item) {
+ const chip = document.createElement("span");
+ chip.className = "chip";
+ chip.textContent = item;
+ chips.appendChild(chip);
+ });
+ const actions = document.getElementById("actions");
+ if (actions) {
+ actions.innerHTML = "";
+ function addLink(label, url, primary) {
+ if (!url) return;
+ const a = document.createElement("a");
+ a.className = primary ? "ns-btn ns-btn-primary" : "ns-btn";
+ a.setAttribute("data-open-link", url);
+ a.href = url;
+ a.textContent = label;
+ actions.appendChild(a);
+ }
+ let maps = "";
+ if (Array.isArray(shop.coords) && shop.coords.length === 2) {
+ maps = "https://www.google.com/maps/search/?api=1&query=" + shop.coords[1] + "," + shop.coords[0];
+ } else if (shop.address) {
+ maps = "https://www.google.com/maps/search/?api=1&query=" + encodeURIComponent(shop.address);
+ }
+ addLink("Maps", maps, false);
+ if (shop.phone) {
+ const tel = String(shop.phone).replace(/[^0-9+]/g, "");
+ if (tel) addLink("Call", "tel:" + tel, false);
+ }
+ addLink("Website", shop.website || "", true);
+ }
+};
+""".strip()
+
+
+def build_pizza_list_widget(data: Any | None = None) -> str:
+ return _page("Pizza shops", _PIZZA_LIST_CSS, render_body("pizza-list", data), _PIZZA_LIST_JS, data)
+
+
+def build_pizza_map_widget(data: Any | None = None) -> str:
+ return _page(
+ "Pizza map",
+ _PIZZA_MAP_CSS,
+ render_body("pizza-map", data),
+ _pizza_map_js(),
+ data,
+ extra_head=_MAPBOX_HEAD,
+ flush=True,
+ )
+
+
+def build_pizza_shop_widget(data: Any | None = None) -> str:
+ return _page("Pizza shop", _PIZZA_SHOP_CSS, render_body("pizza-shop", data), _PIZZA_SHOP_JS, data)
diff --git a/nitrostack/widgets/views.py b/nitrostack/widgets/views.py
index 9822cbf..9e84807 100644
--- a/nitrostack/widgets/views.py
+++ b/nitrostack/widgets/views.py
@@ -3,13 +3,17 @@
Hosts that inject data later still use the HTML document's small host-bridge
script. First paint (Inspector ``tools/call`` HTML, live preview) uses these
builders so the iframe matches the actual tool output — not sample JSON.
+
+This module is the route -> body dispatcher. The bodies live in views_common,
+views_pizza and views_flight and are re-exported here, so existing imports keep working.
"""
from __future__ import annotations
from typing import Any, Callable, Dict
-from nitrostack.widgets.html_util import (
+# Re-exported only so existing ``from nitrostack.widgets.views import ...`` lines keep working.
+from nitrostack.widgets.html_util import ( # noqa: F401
as_dict,
as_list,
esc,
@@ -20,529 +24,34 @@
place_code,
place_name,
)
-from nitrostack.widgets.ui import action_row, call_attrs, maps_url
-
-
-def _safe_int(
- value: Any,
- default: int = 0,
- *,
- minimum: int | None = None,
- maximum: int | None = None,
-) -> int:
- try:
- # OverflowError covers infinities: `json.loads("1e400")` yields `inf`, and
- # `int(float("inf"))` raises. NaN already surfaces as ValueError.
- n = int(float(value))
- except (TypeError, ValueError, OverflowError):
- n = default
- if minimum is not None:
- n = max(minimum, n)
- if maximum is not None:
- n = min(maximum, n)
- return n
-
-
-def _safe_float(value: Any, default: float = 0.0) -> float:
- try:
- n = float(value)
- except (TypeError, ValueError):
- return default
- if n != n or n in (float("inf"), float("-inf")):
- return default
- return n
-
-
-def pizza_list_body(data: Any | None) -> str:
- payload = as_dict(data)
- shops = as_list(payload.get("shops"))
- total = payload.get("totalShops")
- if total is None:
- total = len(shops)
- if data is None:
- meta = "Waiting for show_pizza_list result."
- cards = ""
- elif not shops:
- meta = f"{total} shops"
- cards = 'No shops match these filters.
'
- else:
- meta = f"{total} shop" + ("" if total == 1 else "s")
- parts = []
- for shop in shops:
- shop = as_dict(shop)
- open_cls = "open" if shop.get("openNow") else "closed"
- open_label = "Open" if shop.get("openNow") else "Closed"
- price = "$" * _safe_int(shop.get("priceLevel"), 1, minimum=1, maximum=4)
- img = ""
- if shop.get("image"):
- img = f' '
- rating = f"★ {esc(shop.get('rating'))}" if shop.get("rating") is not None else ""
- shop_id = shop.get("id") or ""
- parts.append(
- f''
- f"{img}"
- f'{esc(shop.get("name") or shop_id or "Shop")} '
- f'{rating}
'
- f'{esc(shop.get("address"))}
'
- f'{open_label} '
- f'{esc(price)}
'
- " "
- )
- cards = "".join(parts)
- return (
- "Pizza shops "
- f'{esc(meta)}
'
- ''
- 'Rating '
- 'Name '
- "
"
- f'{cards}
'
- '
'
- )
-
-
-def _pizza_map_card(shop: dict) -> str:
- name = shop.get("name") or shop.get("id") or "Shop"
- shop_id = shop.get("id") or ""
- rating = f"★ {esc(shop.get('rating'))}" if shop.get("rating") is not None else ""
- return (
- f''
- f'{esc(name)}
'
- f'{esc(shop.get("address"))}
'
- f'{rating}
'
- )
-
-
-def pizza_map_body(data: Any | None) -> str:
- payload = as_dict(data)
- shops = as_list(payload.get("shops"))
- static = ""
- if data is None or not shops:
- meta = "Waiting for show_pizza_map result."
- cards = ""
- else:
- filt = payload.get("filter") or "all"
- total = payload.get("totalShops")
- if total is None:
- total = len(shops)
- meta = f"{total} shops · filter: {filt}"
- cards = "".join(_pizza_map_card(as_dict(shop)) for shop in shops)
- static_src = mapbox_static_url(shops)
- static = (
- f' '
- if static_src
- else ""
- )
- return (
- f'{esc(meta)}
'
- f''
- f'{cards}
'
- '
'
- )
-
-
-def pizza_shop_body(data: Any | None) -> str:
- payload = as_dict(data)
- shop = as_dict(payload.get("shop") or payload if data is not None else {})
- if data is None or not shop.get("name"):
- return (
- ''
- '
'
- '
Pizza shop '
- '
'
- '
Waiting for show_pizza_shop result.
'
- '
'
- '
'
- '
'
- '
'
- '
'
- "
"
- '
'
- )
- img = ""
- if shop.get("image"):
- img = f' '
- else:
- img = ' '
- rating = ""
- if shop.get("rating") is not None:
- rating = f"★ {esc(shop.get('rating'))} ({esc(shop.get('reviews') or 0)} reviews)"
- hours = as_dict(shop.get("hours"))
- hours_text = ""
- if hours.get("open") or hours.get("close"):
- hours_text = f"Hours: {esc(hours.get('open'))} – {esc(hours.get('close'))}"
- chips = "".join(
- f'{esc(item)} ' for item in as_list(shop.get("specialties"))
- )
- actions = action_row(maps=maps_url(shop), phone=str(shop.get("phone") or ""), website=str(shop.get("website") or ""))
- return (
- ''
- f"{img}"
- f'
{esc(shop.get("name"))} '
- f'
{rating}
'
- f'
{esc(shop.get("description"))}
'
- f'
{esc(shop.get("address"))}
'
- f'
{hours_text}
'
- f'
{esc(shop.get("phone"))}
'
- f'
{chips}
'
- f"{actions}"
- "
"
- '
'
- )
-
-
-def calculator_result_body(data: Any | None) -> str:
- payload = as_dict(data)
- expr = payload.get("expression") or "—"
- result = payload.get("result")
- if result is None:
- result = payload.get("value")
- result_text = "—" if result is None else str(result)
- return (
- ''
- f'
{esc(expr)}
'
- f'
{esc(result_text)}
'
- "
"
- '
'
- '
'
- )
-
-
-def card_body(data: Any | None) -> str:
- payload = as_dict(data)
- name = payload.get("name") or "—"
- price = payload.get("price")
- price_text = f"${float(price):.2f}" if isinstance(price, (int, float)) else (str(price) if price else "—")
- desc = payload.get("description") or ""
- return (
- ''
- f'
{esc(name)} '
- f'
{esc(price_text)}
'
- f'
{esc(desc)}
'
- "
"
- )
-
-
-def table_body(data: Any | None) -> str:
- payload = as_dict(data)
- rows = as_list(payload.get("rows"))
- cols = as_list(payload.get("columns"))
- if not cols and rows:
- cols = list(as_dict(rows[0]).keys())
- header = "".join(f"{esc(c)} " for c in cols)
- body_rows = []
- for row in rows:
- row = as_dict(row)
- cells = "".join(f"{esc(row.get(c, ''))} " for c in cols)
- body_rows.append(f"{cells} ")
- return (
- ""
- f' '
- f'{"".join(body_rows)} '
- "
"
- )
-
-
-def chart_body(data: Any | None) -> str:
- payload = as_dict(data)
- title = payload.get("title") or "Chart"
- items = as_list(payload.get("items"))
- values = [_safe_float(as_dict(i).get("value"), 0.0) for i in items]
- max_v = max(values or [1], default=1) or 1
- bars = []
- for item, value in zip(items, values):
- item = as_dict(item)
- height = (value / max_v) * 140
- bars.append(
- ''
- f'
'
- f'
{esc(item.get("label"))}
'
- "
"
- )
- return f'{esc(title)} {"".join(bars)}
'
-
-
-def _offer_slice_html(sl: dict) -> str:
- origin = place_code(sl.get("origin"))
- dest = place_code(sl.get("destination"))
- duration = format_duration(sl.get("duration"))
- segs = as_list(sl.get("segments"))
- first = as_dict(segs[0] if segs else {})
- last = as_dict(segs[-1] if segs else first)
- dep = pick(first, "departing_at", "departingAt", "departureTime", default="") or pick(
- sl, "departing_at", "departingAt", "departureTime", default=""
- )
- arr = pick(last, "arriving_at", "arrivingAt", "arrivalTime", default="") or pick(
- sl, "arriving_at", "arrivingAt", "arrivalTime", default=""
- )
- carrier = first.get("marketing_carrier") or first.get("airline") or sl.get("airline")
- if isinstance(carrier, str):
- airline = carrier
- flight_no = pick(first, "marketing_carrier_flight_number", "flightNumber", default="") or pick(
- sl, "flightNumber", "marketing_carrier_flight_number", default=""
- )
- else:
- carrier = as_dict(carrier)
- airline = pick(carrier, "name", default="") or pick(first, "airline", default="") or pick(sl, "airline", default="")
- flight_no = pick(carrier, "flight_number", "flightNumber", default="") or pick(
- first, "marketing_carrier_flight_number", "flightNumber", default=""
- ) or pick(sl, "flightNumber", default="")
- return (
- f'{esc(origin)} → {esc(dest)} '
- f'
{esc(dep)} – {esc(arr)} · {esc(duration)}
'
- f'
{esc(airline)} {esc(flight_no)}
'
- )
-
-
-def _offer_itinerary_html(offer: dict) -> str:
- slices = as_list(offer.get("slices"))
- if slices:
- return "".join(_offer_slice_html(as_dict(s)) for s in slices)
- parts = []
- outbound = offer.get("outbound")
- if outbound:
- parts.append(_offer_slice_html(as_dict(outbound)))
- ret = offer.get("return")
- if ret:
- parts.append(_offer_slice_html(as_dict(ret)))
- return "".join(parts) or _offer_slice_html(offer)
-
-
-def flight_search_results_body(data: Any | None) -> str:
- payload = as_dict(data)
- offers = as_list(payload.get("offers") or payload.get("results"))
- if data is None:
- return (
- "Flight search "
- 'Waiting for search_flights result.
'
- '
'
- )
- params = as_dict(payload.get("searchParams"))
- total = payload.get("totalOffers")
- if total is None:
- total = len(offers)
- if params.get("origin") and params.get("destination"):
- meta = f"{params.get('origin')} → {params.get('destination')} · {total} offer" + ("" if total == 1 else "s")
- else:
- meta = f"{total} offer" + ("" if total == 1 else "s")
- cards = []
- for offer in offers:
- offer = as_dict(offer)
- amount = pick(offer, "total_amount", "totalAmount", default="")
- currency = pick(offer, "total_currency", "totalCurrency", default="")
- slice_html = _offer_itinerary_html(offer)
- offer_id = offer.get("id") or ""
- cards.append(
- f''
- f'{esc(money(amount, currency))} '
- f'{esc(offer_id)}
{slice_html} '
- )
- if not cards:
- cards.append('No flight offers.
')
- return (
- "Flight search "
- f'{esc(meta)}
'
- f'{"".join(cards)}
'
- )
-
-
-def flight_details_body(data: Any | None) -> str:
- payload = as_dict(data)
- if data is None or not payload:
- return (
- "Flight details "
- 'Waiting for get_flight_details result.
'
- '
'
- )
- amount = pick(payload, "total_amount", "totalAmount", default="")
- currency = pick(payload, "total_currency", "totalCurrency", default="")
- slices = as_list(payload.get("slices"))
- slice_html = "".join(_offer_slice_html(as_dict(s)) for s in slices)
- offer_id = payload.get("id") or ""
- seats = ""
- if offer_id:
- seats = (
- f'Seat map
'
- )
- return (
- "Flight details "
- f'Offer {esc(offer_id)} · {esc(money(amount, currency))}
'
- f'{slice_html}{seats}
'
- )
-
-
-def airport_search_body(data: Any | None) -> str:
- payload = as_dict(data)
- results = as_list(payload.get("results") or payload.get("airports") or payload.get("places"))
- query = payload.get("query") or ""
- if data is None:
- return (
- "Airport search "
- 'Waiting for search_airports result.
'
- '
'
- )
- rows = []
- for item in results:
- item = as_dict(item)
- code = pick(item, "iata_code", "iataCode", default="")
- name = pick(item, "name", default="")
- city = pick(item, "city_name", "cityName", "city", default="")
- kind = pick(item, "type", default="airport")
- rows.append(
- f'{esc(code)} '
- f'
{esc(name)}
'
- f'
{esc(city)} · {esc(kind)}
'
- )
- if not rows:
- rows.append('No airports found.
')
- return (
- "Airport search "
- f'Query: {esc(query)} · {len(results)} result(s)
'
- f'{"".join(rows)}
'
- )
-
-
-def order_summary_body(data: Any | None) -> str:
- payload = as_dict(data)
- if data is None or not payload:
- return (
- "Order summary "
- 'Waiting for order result.
'
- '
'
- )
- status = str(pick(payload, "status", default="held"))
- ref = pick(payload, "booking_reference", "bookingReference", default="")
- amount = pick(payload, "total_amount", "totalAmount", default="")
- currency = pick(payload, "total_currency", "totalCurrency", default="")
- passengers = as_list(payload.get("passengers"))
- pax = []
- for p in passengers:
- p = as_dict(p)
- name = pick(p, "name", default="") or " ".join(
- str(x) for x in (p.get("given_name") or p.get("givenName"), p.get("family_name") or p.get("familyName")) if x
- )
- pax.append(f'{esc(name or p.get("id"))}
')
- slices = "".join(_offer_slice_html(as_dict(s)) for s in as_list(payload.get("slices")))
- order_id = payload.get("id") or payload.get("orderId") or ""
- cancel = ""
- if order_id and status.lower() not in {"cancelled", "canceled"}:
- cancel = (
- f'Cancel order
'
- )
- return (
- ''
- f'
Order {esc(status)} '
- f'
Ref {esc(ref)} · {esc(order_id)}
'
- f'
{esc(money(amount, currency))}
'
- f'
Passengers {"".join(pax) or "
None listed
"}'
- f'
Itinerary {slices}'
- f"{cancel}"
- "
"
- '
'
- )
-
-
-def _seat_cells(cabin: dict) -> str:
- rows_html = []
- rows = as_list(cabin.get("rows"))
- if rows:
- for row in rows:
- row = as_dict(row)
- seats = as_list(row.get("seats") or row.get("elements"))
- if not seats:
- for section in as_list(row.get("sections")):
- seats.extend(as_list(as_dict(section).get("elements")))
- cells = []
- for seat in seats:
- seat = as_dict(seat)
- if seat.get("type") and seat.get("type") != "seat":
- continue
- designator = pick(seat, "designator", "id", "column", default="")
- available = seat.get("available")
- if available is None:
- available = bool(seat.get("available_services") is not None)
- cls = "seat ok" if available else "seat no"
- cells.append(f'{esc(designator)} ')
- rows_html.append(
- f'{esc(row.get("row_number") or row.get("rowNumber") or "")} '
- f"{''.join(cells)}
"
- )
- return "".join(rows_html)
-
-
-def seat_selection_body(data: Any | None) -> str:
- payload = as_dict(data)
- cabins = as_list(payload.get("cabins"))
- if data is None:
- return (
- "Seat map "
- 'Waiting for get_seat_map result.
'
- '
'
- )
- blocks = []
- for cabin in cabins:
- cabin = as_dict(cabin)
- klass = pick(cabin, "cabin_class", "cabinClass", default="cabin")
- blocks.append(f'{esc(klass)} {_seat_cells(cabin)}')
- if not blocks:
- blocks.append('No seat map data.
')
- return (
- "Seat map "
- f'Offer {esc(payload.get("offerId") or payload.get("offer_id"))}
'
- f'{"".join(blocks)}
'
- )
-
-
-def order_cancellation_body(data: Any | None) -> str:
- payload = as_dict(data)
- if data is None or not payload:
- return (
- "Cancellation "
- 'Waiting for cancel_order result.
'
- '
'
- )
- refund = pick(payload, "refund_amount", "refundAmount", default="")
- currency = pick(payload, "refund_currency", "refundCurrency", default="")
- status = pick(payload, "status", default="cancelled")
- msg = pick(payload, "message", default="Booking cancelled.")
- cid = pick(payload, "id", "cancellationId", default="")
- return (
- ''
- "
Booking cancelled "
- f'
{esc(status)} · {esc(cid)}
'
- f'
{esc(msg)}
'
- f'
Refund {esc(money(refund, currency) or "n/a")}
'
- "
"
- '
'
- )
-
-
-def generic_body(route: str, data: Any | None) -> str:
- import json
-
- if data is None:
- preview = "Waiting for host to send tool output…"
- else:
- preview = json.dumps(data, indent=2, default=str)
- return (
- f"{esc(route)} "
- 'Tool output
'
- f'{esc(preview)} '
- )
-
-
-def missing_body(route: str) -> str:
- return (
- "Widget template missing "
- f'No HTML found for route {esc(route)} . '
- f"Create widgets/out/{esc(route)}.html or run nitrostack-py init again.
"
- '
'
- )
+from nitrostack.widgets.ui import action_row, call_attrs, maps_url # noqa: F401
+from nitrostack.widgets.views_common import ( # noqa: F401
+ _safe_int,
+ _safe_float,
+ calculator_result_body,
+ card_body,
+ table_body,
+ chart_body,
+ generic_body,
+ missing_body,
+)
+from nitrostack.widgets.views_pizza import ( # noqa: F401
+ pizza_list_body,
+ _pizza_map_card,
+ pizza_map_body,
+ pizza_shop_body,
+)
+from nitrostack.widgets.views_flight import ( # noqa: F401
+ _offer_slice_html,
+ _offer_itinerary_html,
+ flight_search_results_body,
+ flight_details_body,
+ airport_search_body,
+ order_summary_body,
+ _seat_cells,
+ seat_selection_body,
+ order_cancellation_body,
+)
BODY_BUILDERS: Dict[str, Callable[[Any | None], str]] = {
diff --git a/nitrostack/widgets/views_common.py b/nitrostack/widgets/views_common.py
new file mode 100644
index 0000000..f5fb8c5
--- /dev/null
+++ b/nitrostack/widgets/views_common.py
@@ -0,0 +1,131 @@
+"""Shared view helpers and the generic, calculator, card, table and chart widget bodies."""
+
+from __future__ import annotations
+
+from typing import Any
+
+from nitrostack.widgets.html_util import as_dict, as_list, esc
+
+
+def _safe_int(
+ value: Any,
+ default: int = 0,
+ *,
+ minimum: int | None = None,
+ maximum: int | None = None,
+) -> int:
+ try:
+ # OverflowError covers infinities: `json.loads("1e400")` yields `inf`, and
+ # `int(float("inf"))` raises. NaN already surfaces as ValueError.
+ n = int(float(value))
+ except (TypeError, ValueError, OverflowError):
+ n = default
+ if minimum is not None:
+ n = max(minimum, n)
+ if maximum is not None:
+ n = min(maximum, n)
+ return n
+
+
+def _safe_float(value: Any, default: float = 0.0) -> float:
+ try:
+ n = float(value)
+ except (TypeError, ValueError):
+ return default
+ if n != n or n in (float("inf"), float("-inf")):
+ return default
+ return n
+
+
+def calculator_result_body(data: Any | None) -> str:
+ payload = as_dict(data)
+ expr = payload.get("expression") or "—"
+ result = payload.get("result")
+ if result is None:
+ result = payload.get("value")
+ result_text = "—" if result is None else str(result)
+ return (
+ ''
+ f'
{esc(expr)}
'
+ f'
{esc(result_text)}
'
+ "
"
+ '
'
+ '
'
+ )
+
+
+def card_body(data: Any | None) -> str:
+ payload = as_dict(data)
+ name = payload.get("name") or "—"
+ price = payload.get("price")
+ price_text = f"${float(price):.2f}" if isinstance(price, (int, float)) else (str(price) if price else "—")
+ desc = payload.get("description") or ""
+ return (
+ ''
+ f'
{esc(name)} '
+ f'
{esc(price_text)}
'
+ f'
{esc(desc)}
'
+ "
"
+ )
+
+
+def table_body(data: Any | None) -> str:
+ payload = as_dict(data)
+ rows = as_list(payload.get("rows"))
+ cols = as_list(payload.get("columns"))
+ if not cols and rows:
+ cols = list(as_dict(rows[0]).keys())
+ header = "".join(f"{esc(c)} " for c in cols)
+ body_rows = []
+ for row in rows:
+ row = as_dict(row)
+ cells = "".join(f"{esc(row.get(c, ''))} " for c in cols)
+ body_rows.append(f"{cells} ")
+ return (
+ ""
+ f' '
+ f'{"".join(body_rows)} '
+ "
"
+ )
+
+
+def chart_body(data: Any | None) -> str:
+ payload = as_dict(data)
+ title = payload.get("title") or "Chart"
+ items = as_list(payload.get("items"))
+ values = [_safe_float(as_dict(i).get("value"), 0.0) for i in items]
+ max_v = max(values or [1], default=1) or 1
+ bars = []
+ for item, value in zip(items, values):
+ item = as_dict(item)
+ height = (value / max_v) * 140
+ bars.append(
+ ''
+ f'
'
+ f'
{esc(item.get("label"))}
'
+ "
"
+ )
+ return f'{esc(title)} {"".join(bars)}
'
+
+
+def generic_body(route: str, data: Any | None) -> str:
+ import json
+
+ if data is None:
+ preview = "Waiting for host to send tool output…"
+ else:
+ preview = json.dumps(data, indent=2, default=str)
+ return (
+ f"{esc(route)} "
+ 'Tool output
'
+ f'{esc(preview)} '
+ )
+
+
+def missing_body(route: str) -> str:
+ return (
+ "Widget template missing "
+ f'No HTML found for route {esc(route)} . '
+ f"Create widgets/out/{esc(route)}.html or run nitrostack-py init again.
"
+ '
'
+ )
diff --git a/nitrostack/widgets/views_flight.py b/nitrostack/widgets/views_flight.py
new file mode 100644
index 0000000..6b72c62
--- /dev/null
+++ b/nitrostack/widgets/views_flight.py
@@ -0,0 +1,273 @@
+"""Flight search, details, airport, order, seat and cancellation widget bodies."""
+
+from __future__ import annotations
+
+from typing import Any
+
+from nitrostack.widgets.html_util import (
+ as_dict,
+ as_list,
+ esc,
+ format_duration,
+ money,
+ pick,
+ place_code,
+)
+from nitrostack.widgets.ui import call_attrs
+
+
+def _offer_slice_html(sl: dict) -> str:
+ origin = place_code(sl.get("origin"))
+ dest = place_code(sl.get("destination"))
+ duration = format_duration(sl.get("duration"))
+ segs = as_list(sl.get("segments"))
+ first = as_dict(segs[0] if segs else {})
+ last = as_dict(segs[-1] if segs else first)
+ dep = pick(first, "departing_at", "departingAt", "departureTime", default="") or pick(
+ sl, "departing_at", "departingAt", "departureTime", default=""
+ )
+ arr = pick(last, "arriving_at", "arrivingAt", "arrivalTime", default="") or pick(
+ sl, "arriving_at", "arrivingAt", "arrivalTime", default=""
+ )
+ carrier = first.get("marketing_carrier") or first.get("airline") or sl.get("airline")
+ if isinstance(carrier, str):
+ airline = carrier
+ flight_no = pick(first, "marketing_carrier_flight_number", "flightNumber", default="") or pick(
+ sl, "flightNumber", "marketing_carrier_flight_number", default=""
+ )
+ else:
+ carrier = as_dict(carrier)
+ airline = pick(carrier, "name", default="") or pick(first, "airline", default="") or pick(sl, "airline", default="")
+ flight_no = pick(carrier, "flight_number", "flightNumber", default="") or pick(
+ first, "marketing_carrier_flight_number", "flightNumber", default=""
+ ) or pick(sl, "flightNumber", default="")
+ return (
+ f'{esc(origin)} → {esc(dest)} '
+ f'
{esc(dep)} – {esc(arr)} · {esc(duration)}
'
+ f'
{esc(airline)} {esc(flight_no)}
'
+ )
+
+
+def _offer_itinerary_html(offer: dict) -> str:
+ slices = as_list(offer.get("slices"))
+ if slices:
+ return "".join(_offer_slice_html(as_dict(s)) for s in slices)
+ parts = []
+ outbound = offer.get("outbound")
+ if outbound:
+ parts.append(_offer_slice_html(as_dict(outbound)))
+ ret = offer.get("return")
+ if ret:
+ parts.append(_offer_slice_html(as_dict(ret)))
+ return "".join(parts) or _offer_slice_html(offer)
+
+
+def flight_search_results_body(data: Any | None) -> str:
+ payload = as_dict(data)
+ offers = as_list(payload.get("offers") or payload.get("results"))
+ if data is None:
+ return (
+ "Flight search "
+ 'Waiting for search_flights result.
'
+ '
'
+ )
+ params = as_dict(payload.get("searchParams"))
+ total = payload.get("totalOffers")
+ if total is None:
+ total = len(offers)
+ if params.get("origin") and params.get("destination"):
+ meta = f"{params.get('origin')} → {params.get('destination')} · {total} offer" + ("" if total == 1 else "s")
+ else:
+ meta = f"{total} offer" + ("" if total == 1 else "s")
+ cards = []
+ for offer in offers:
+ offer = as_dict(offer)
+ amount = pick(offer, "total_amount", "totalAmount", default="")
+ currency = pick(offer, "total_currency", "totalCurrency", default="")
+ slice_html = _offer_itinerary_html(offer)
+ offer_id = offer.get("id") or ""
+ cards.append(
+ f''
+ f'{esc(money(amount, currency))} '
+ f'{esc(offer_id)}
{slice_html} '
+ )
+ if not cards:
+ cards.append('No flight offers.
')
+ return (
+ "Flight search "
+ f'{esc(meta)}
'
+ f'{"".join(cards)}
'
+ )
+
+
+def flight_details_body(data: Any | None) -> str:
+ payload = as_dict(data)
+ if data is None or not payload:
+ return (
+ "Flight details "
+ 'Waiting for get_flight_details result.
'
+ '
'
+ )
+ amount = pick(payload, "total_amount", "totalAmount", default="")
+ currency = pick(payload, "total_currency", "totalCurrency", default="")
+ slices = as_list(payload.get("slices"))
+ slice_html = "".join(_offer_slice_html(as_dict(s)) for s in slices)
+ offer_id = payload.get("id") or ""
+ seats = ""
+ if offer_id:
+ seats = (
+ f'Seat map
'
+ )
+ return (
+ "Flight details "
+ f'Offer {esc(offer_id)} · {esc(money(amount, currency))}
'
+ f'{slice_html}{seats}
'
+ )
+
+
+def airport_search_body(data: Any | None) -> str:
+ payload = as_dict(data)
+ results = as_list(payload.get("results") or payload.get("airports") or payload.get("places"))
+ query = payload.get("query") or ""
+ if data is None:
+ return (
+ "Airport search "
+ 'Waiting for search_airports result.
'
+ '
'
+ )
+ rows = []
+ for item in results:
+ item = as_dict(item)
+ code = pick(item, "iata_code", "iataCode", default="")
+ name = pick(item, "name", default="")
+ city = pick(item, "city_name", "cityName", "city", default="")
+ kind = pick(item, "type", default="airport")
+ rows.append(
+ f'{esc(code)} '
+ f'
{esc(name)}
'
+ f'
{esc(city)} · {esc(kind)}
'
+ )
+ if not rows:
+ rows.append('No airports found.
')
+ return (
+ "Airport search "
+ f'Query: {esc(query)} · {len(results)} result(s)
'
+ f'{"".join(rows)}
'
+ )
+
+
+def order_summary_body(data: Any | None) -> str:
+ payload = as_dict(data)
+ if data is None or not payload:
+ return (
+ "Order summary "
+ 'Waiting for order result.
'
+ '
'
+ )
+ status = str(pick(payload, "status", default="held"))
+ ref = pick(payload, "booking_reference", "bookingReference", default="")
+ amount = pick(payload, "total_amount", "totalAmount", default="")
+ currency = pick(payload, "total_currency", "totalCurrency", default="")
+ passengers = as_list(payload.get("passengers"))
+ pax = []
+ for p in passengers:
+ p = as_dict(p)
+ name = pick(p, "name", default="") or " ".join(
+ str(x) for x in (p.get("given_name") or p.get("givenName"), p.get("family_name") or p.get("familyName")) if x
+ )
+ pax.append(f'{esc(name or p.get("id"))}
')
+ slices = "".join(_offer_slice_html(as_dict(s)) for s in as_list(payload.get("slices")))
+ order_id = payload.get("id") or payload.get("orderId") or ""
+ cancel = ""
+ if order_id and status.lower() not in {"cancelled", "canceled"}:
+ cancel = (
+ f'Cancel order
'
+ )
+ return (
+ ''
+ f'
Order {esc(status)} '
+ f'
Ref {esc(ref)} · {esc(order_id)}
'
+ f'
{esc(money(amount, currency))}
'
+ f'
Passengers {"".join(pax) or "
None listed
"}'
+ f'
Itinerary {slices}'
+ f"{cancel}"
+ "
"
+ '
'
+ )
+
+
+def _seat_cells(cabin: dict) -> str:
+ rows_html = []
+ rows = as_list(cabin.get("rows"))
+ if rows:
+ for row in rows:
+ row = as_dict(row)
+ seats = as_list(row.get("seats") or row.get("elements"))
+ if not seats:
+ for section in as_list(row.get("sections")):
+ seats.extend(as_list(as_dict(section).get("elements")))
+ cells = []
+ for seat in seats:
+ seat = as_dict(seat)
+ if seat.get("type") and seat.get("type") != "seat":
+ continue
+ designator = pick(seat, "designator", "id", "column", default="")
+ available = seat.get("available")
+ if available is None:
+ available = bool(seat.get("available_services") is not None)
+ cls = "seat ok" if available else "seat no"
+ cells.append(f'{esc(designator)} ')
+ rows_html.append(
+ f'{esc(row.get("row_number") or row.get("rowNumber") or "")} '
+ f"{''.join(cells)}
"
+ )
+ return "".join(rows_html)
+
+
+def seat_selection_body(data: Any | None) -> str:
+ payload = as_dict(data)
+ cabins = as_list(payload.get("cabins"))
+ if data is None:
+ return (
+ "Seat map "
+ 'Waiting for get_seat_map result.
'
+ '
'
+ )
+ blocks = []
+ for cabin in cabins:
+ cabin = as_dict(cabin)
+ klass = pick(cabin, "cabin_class", "cabinClass", default="cabin")
+ blocks.append(f'{esc(klass)} {_seat_cells(cabin)}')
+ if not blocks:
+ blocks.append('No seat map data.
')
+ return (
+ "Seat map "
+ f'Offer {esc(payload.get("offerId") or payload.get("offer_id"))}
'
+ f'{"".join(blocks)}
'
+ )
+
+
+def order_cancellation_body(data: Any | None) -> str:
+ payload = as_dict(data)
+ if data is None or not payload:
+ return (
+ "Cancellation "
+ 'Waiting for cancel_order result.
'
+ '
'
+ )
+ refund = pick(payload, "refund_amount", "refundAmount", default="")
+ currency = pick(payload, "refund_currency", "refundCurrency", default="")
+ status = pick(payload, "status", default="cancelled")
+ msg = pick(payload, "message", default="Booking cancelled.")
+ cid = pick(payload, "id", "cancellationId", default="")
+ return (
+ ''
+ "
Booking cancelled "
+ f'
{esc(status)} · {esc(cid)}
'
+ f'
{esc(msg)}
'
+ f'
Refund {esc(money(refund, currency) or "n/a")}
'
+ "
"
+ '
'
+ )
diff --git a/nitrostack/widgets/views_pizza.py b/nitrostack/widgets/views_pizza.py
new file mode 100644
index 0000000..cc8691d
--- /dev/null
+++ b/nitrostack/widgets/views_pizza.py
@@ -0,0 +1,155 @@
+"""Pizza list, map and shop widget bodies."""
+
+from __future__ import annotations
+
+from typing import Any
+
+from nitrostack.widgets.html_util import (
+ as_dict,
+ as_list,
+ esc,
+ mapbox_static_url,
+)
+from nitrostack.widgets.ui import action_row, call_attrs, maps_url
+from nitrostack.widgets.views_common import _safe_int
+
+
+def pizza_list_body(data: Any | None) -> str:
+ payload = as_dict(data)
+ shops = as_list(payload.get("shops"))
+ total = payload.get("totalShops")
+ if total is None:
+ total = len(shops)
+ if data is None:
+ meta = "Waiting for show_pizza_list result."
+ cards = ""
+ elif not shops:
+ meta = f"{total} shops"
+ cards = 'No shops match these filters.
'
+ else:
+ meta = f"{total} shop" + ("" if total == 1 else "s")
+ parts = []
+ for shop in shops:
+ shop = as_dict(shop)
+ open_cls = "open" if shop.get("openNow") else "closed"
+ open_label = "Open" if shop.get("openNow") else "Closed"
+ price = "$" * _safe_int(shop.get("priceLevel"), 1, minimum=1, maximum=4)
+ img = ""
+ if shop.get("image"):
+ img = f' '
+ rating = f"★ {esc(shop.get('rating'))}" if shop.get("rating") is not None else ""
+ shop_id = shop.get("id") or ""
+ parts.append(
+ f''
+ f"{img}"
+ f'{esc(shop.get("name") or shop_id or "Shop")} '
+ f'{rating}
'
+ f'{esc(shop.get("address"))}
'
+ f'{open_label} '
+ f'{esc(price)}
'
+ " "
+ )
+ cards = "".join(parts)
+ return (
+ "Pizza shops "
+ f'{esc(meta)}
'
+ ''
+ 'Rating '
+ 'Name '
+ "
"
+ f'{cards}
'
+ '
'
+ )
+
+
+def _pizza_map_card(shop: dict) -> str:
+ name = shop.get("name") or shop.get("id") or "Shop"
+ shop_id = shop.get("id") or ""
+ rating = f"★ {esc(shop.get('rating'))}" if shop.get("rating") is not None else ""
+ return (
+ f''
+ f'{esc(name)}
'
+ f'{esc(shop.get("address"))}
'
+ f'{rating}
'
+ )
+
+
+def pizza_map_body(data: Any | None) -> str:
+ payload = as_dict(data)
+ shops = as_list(payload.get("shops"))
+ static = ""
+ if data is None or not shops:
+ meta = "Waiting for show_pizza_map result."
+ cards = ""
+ else:
+ filt = payload.get("filter") or "all"
+ total = payload.get("totalShops")
+ if total is None:
+ total = len(shops)
+ meta = f"{total} shops · filter: {filt}"
+ cards = "".join(_pizza_map_card(as_dict(shop)) for shop in shops)
+ static_src = mapbox_static_url(shops)
+ static = (
+ f' '
+ if static_src
+ else ""
+ )
+ return (
+ f'{esc(meta)}
'
+ f''
+ f'{cards}
'
+ '
'
+ )
+
+
+def pizza_shop_body(data: Any | None) -> str:
+ payload = as_dict(data)
+ shop = as_dict(payload.get("shop") or payload if data is not None else {})
+ if data is None or not shop.get("name"):
+ return (
+ ''
+ '
'
+ '
Pizza shop '
+ '
'
+ '
Waiting for show_pizza_shop result.
'
+ '
'
+ '
'
+ '
'
+ '
'
+ '
'
+ "
"
+ '
'
+ )
+ img = ""
+ if shop.get("image"):
+ img = f' '
+ else:
+ img = ' '
+ rating = ""
+ if shop.get("rating") is not None:
+ rating = f"★ {esc(shop.get('rating'))} ({esc(shop.get('reviews') or 0)} reviews)"
+ hours = as_dict(shop.get("hours"))
+ hours_text = ""
+ if hours.get("open") or hours.get("close"):
+ hours_text = f"Hours: {esc(hours.get('open'))} – {esc(hours.get('close'))}"
+ chips = "".join(
+ f'{esc(item)} ' for item in as_list(shop.get("specialties"))
+ )
+ actions = action_row(maps=maps_url(shop), phone=str(shop.get("phone") or ""), website=str(shop.get("website") or ""))
+ return (
+ ''
+ f"{img}"
+ f'
{esc(shop.get("name"))} '
+ f'
{rating}
'
+ f'
{esc(shop.get("description"))}
'
+ f'
{esc(shop.get("address"))}
'
+ f'
{hours_text}
'
+ f'
{esc(shop.get("phone"))}
'
+ f'
{chips}
'
+ f"{actions}"
+ "
"
+ '
'
+ )