@nuvler/cli 0.5.10 → 0.5.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,20 @@
1
1
  "use client";
2
2
 
3
- import { useMemo, useState, type CSSProperties } from "react";
4
- import { productUrl, type NuvlerStoreThemeDefinition, type ThemeCartItem, type ThemeCategory, type ThemeEditorialItem, type ThemeHomeSection, type ThemeNavigationItem, type ThemePageSummary, type ThemeProduct, type ThemeRuntimeAdapters, type ThemeRuntimeSdk, type ThemeSite } from "@nuvler/theme-sdk";
3
+ import { useEffect, useMemo, useState, type CSSProperties } from "react";
4
+ import {
5
+ productUrl,
6
+ type NuvlerStoreThemeDefinition,
7
+ type ThemeCartItem,
8
+ type ThemeCategory,
9
+ type ThemeEditorialItem,
10
+ type ThemeHomeSection,
11
+ type ThemeNavigationItem,
12
+ type ThemePageSummary,
13
+ type ThemeProduct,
14
+ type ThemeRuntimeAdapters,
15
+ type ThemeRuntimeSdk,
16
+ type ThemeSite,
17
+ } from "@nuvler/theme-sdk";
5
18
  import { nuvlerDefaultTheme } from "./definition.js";
6
19
  import { ThemeInteractionProvider } from "./product-detail-interactive.js";
7
20
  import { plainText, ThemeImageView } from "./shared.js";
@@ -9,17 +22,50 @@ import { plainText, ThemeImageView } from "./shared.js";
9
22
  interface PreviewContext {
10
23
  store: { name: string; slug: string };
11
24
  site: { modules: string[]; settings: ThemeSite["settings"] };
12
- navigation: { pages: ThemePageSummary[]; categories: ThemeCategory[]; menu?: ThemeNavigationItem[]; headerButton?: import("@nuvler/theme-sdk").ThemeNavigationHeaderButton | null };
25
+ navigation: {
26
+ pages: ThemePageSummary[];
27
+ categories: ThemeCategory[];
28
+ menu?: ThemeNavigationItem[];
29
+ headerButton?:
30
+ import("@nuvler/theme-sdk").ThemeNavigationHeaderButton | null;
31
+ };
13
32
  home: { content: { sections: ThemeHomeSection[] } };
14
33
  catalog: { products: ThemeProduct[] };
15
- editorial: { posts: ThemeEditorialItem[]; services: ThemeEditorialItem[]; cases: ThemeEditorialItem[] };
34
+ editorial: {
35
+ posts: ThemeEditorialItem[];
36
+ services: ThemeEditorialItem[];
37
+ cases: ThemeEditorialItem[];
38
+ };
16
39
  }
17
40
 
18
41
  type PreviewRoute =
19
42
  | { type: "home" | "loading" | "not-found" | "page"; title?: string }
20
- | { type: "catalog"; products: ThemeProduct[]; pagination: { page: number; total: number; totalPages: number; hasPreviousPage: boolean; hasNextPage: boolean }; search: string; categorySlug: string | null; categoryPath: string[]; variants: string[]; facets: Array<{ name: string; values: Array<{ value: string; count: number }> }> }
43
+ | {
44
+ type: "catalog";
45
+ products: ThemeProduct[];
46
+ pagination: {
47
+ page: number;
48
+ total: number;
49
+ totalPages: number;
50
+ hasPreviousPage: boolean;
51
+ hasNextPage: boolean;
52
+ };
53
+ search: string;
54
+ categorySlug: string | null;
55
+ categoryPath: string[];
56
+ variants: string[];
57
+ facets: Array<{
58
+ name: string;
59
+ values: Array<{ value: string; count: number }>;
60
+ }>;
61
+ }
21
62
  | { type: "product"; product: ThemeProduct }
22
- | { type: "editorial-list"; title: string; basePath: string; items: ThemeEditorialItem[] }
63
+ | {
64
+ type: "editorial-list";
65
+ title: string;
66
+ basePath: string;
67
+ items: ThemeEditorialItem[];
68
+ }
23
69
  | { type: "editorial-detail"; basePath: string; item: ThemeEditorialItem };
24
70
 
25
71
  export interface NuvlerDefaultThemeProps {
@@ -34,106 +80,716 @@ interface PreviewCartItem extends ThemeCartItem {
34
80
  quantity: number;
35
81
  }
36
82
 
83
+ function readStoredCart(storageKey: string): PreviewCartItem[] {
84
+ const stored = window.localStorage.getItem(storageKey);
85
+ if (!stored) return [];
86
+
87
+ const parsed: unknown = JSON.parse(stored);
88
+ if (!Array.isArray(parsed)) return [];
89
+
90
+ return parsed.flatMap((candidate) => {
91
+ if (
92
+ !candidate ||
93
+ typeof candidate !== "object" ||
94
+ !("productSlug" in candidate) ||
95
+ typeof candidate.productSlug !== "string" ||
96
+ !("title" in candidate) ||
97
+ typeof candidate.title !== "string" ||
98
+ !("sku" in candidate) ||
99
+ typeof candidate.sku !== "string"
100
+ ) {
101
+ return [];
102
+ }
103
+
104
+ const item = candidate as ThemeCartItem & {
105
+ key?: unknown;
106
+ quantity?: unknown;
107
+ };
108
+ const key = `${item.productSlug}::${item.variantId || "parent"}`;
109
+ const quantity =
110
+ typeof item.quantity === "number" && Number.isFinite(item.quantity)
111
+ ? Math.min(99, Math.max(1, Math.trunc(item.quantity)))
112
+ : 1;
113
+
114
+ return [{ ...item, key, quantity }];
115
+ }).slice(-30);
116
+ }
117
+
37
118
  function money(value: number): string {
38
- return new Intl.NumberFormat("pt-BR", { style: "currency", currency: "BRL" }).format(value);
119
+ return new Intl.NumberFormat("pt-BR", {
120
+ style: "currency",
121
+ currency: "BRL",
122
+ }).format(value);
39
123
  }
40
124
 
41
- function catalogHref(route: Extract<PreviewRoute, { type: "catalog" }>, page: number): string {
125
+ function catalogHref(
126
+ route: Extract<PreviewRoute, { type: "catalog" }>,
127
+ page: number,
128
+ ): string {
42
129
  const params = new URLSearchParams();
43
130
  if (route.search) params.set("busca", route.search);
44
131
  route.variants.forEach((variant) => params.append("variante", variant));
45
132
  if (page > 1) params.set("pagina", String(page));
46
- const pathname = route.categoryPath.length ? `/${route.categoryPath.map(encodeURIComponent).join("/")}` : "/produtos";
133
+ const pathname = route.categoryPath.length
134
+ ? `/${route.categoryPath.map(encodeURIComponent).join("/")}`
135
+ : "/produtos";
47
136
  return params.size ? `${pathname}?${params}` : pathname;
48
137
  }
49
138
 
50
139
  function editorialMeta(basePath: string) {
51
- if (basePath === "/servicos") return { eyebrow: "Soluções", action: "Conhecer serviço", empty: "Nenhum serviço publicado" };
52
- if (basePath === "/cases") return { eyebrow: "Cases", action: "Ver case", empty: "Nenhum case publicado" };
53
- return { eyebrow: "Conteúdo", action: "Ler artigo", empty: "Nenhum conteúdo publicado" };
140
+ if (basePath === "/servicos")
141
+ return {
142
+ eyebrow: "Soluções",
143
+ action: "Conhecer serviço",
144
+ empty: "Nenhum serviço publicado",
145
+ };
146
+ if (basePath === "/cases")
147
+ return {
148
+ eyebrow: "Cases",
149
+ action: "Ver case",
150
+ empty: "Nenhum case publicado",
151
+ };
152
+ return {
153
+ eyebrow: "Conteúdo",
154
+ action: "Ler artigo",
155
+ empty: "Nenhum conteúdo publicado",
156
+ };
54
157
  }
55
158
 
56
159
  function publishedDate(value: string | null) {
57
160
  if (!value) return null;
58
161
  const date = new Date(value);
59
- return Number.isNaN(date.getTime()) ? null : new Intl.DateTimeFormat("pt-BR", { dateStyle: "medium" }).format(date);
162
+ return Number.isNaN(date.getTime())
163
+ ? null
164
+ : new Intl.DateTimeFormat("pt-BR", { dateStyle: "medium" }).format(date);
60
165
  }
61
166
 
62
- function EditorialPreview({ items, basePath }: { items: ThemeEditorialItem[]; basePath: string }) {
167
+ function EditorialPreview({
168
+ items,
169
+ basePath,
170
+ }: {
171
+ items: ThemeEditorialItem[];
172
+ basePath: string;
173
+ }) {
63
174
  const meta = editorialMeta(basePath);
64
- if (!items.length) return <div className="empty-state"><span>7</span><h2>{meta.empty}</h2><p>Novas publicações aparecerão aqui quando estiverem disponíveis.</p></div>;
65
- return <div className="editorial-grid editorial-list-grid">{items.map((item) => <article className="editorial-card" key={item.slug}><a className="editorial-card-image" href={`${basePath}/${item.slug}`}><ThemeImageView image={item.image || item.thumbnail || item.coverImage} fallbackAlt={item.title} sizes="(max-width: 720px) 92vw, 33vw" fallbackWidth={720} fallbackHeight={480} /></a><div className="editorial-card-content">{(item.category?.title || item.category?.name) && <span>{item.category.title || item.category.name}</span>}<h2><a href={`${basePath}/${item.slug}`}>{item.title}</a></h2>{publishedDate(item.publishedAt) && <small className="editorial-card-date">{publishedDate(item.publishedAt)}</small>}<p>{item.description}</p><a className="text-link" href={`${basePath}/${item.slug}`}>{meta.action} <span>→</span></a></div></article>)}</div>;
175
+ if (!items.length)
176
+ return (
177
+ <div className="empty-state">
178
+ <span>7</span>
179
+ <h2>{meta.empty}</h2>
180
+ <p>Novas publicações aparecerão aqui quando estiverem disponíveis.</p>
181
+ </div>
182
+ );
183
+ return (
184
+ <div className="editorial-grid editorial-list-grid">
185
+ {items.map((item) => (
186
+ <article className="editorial-card" key={item.slug}>
187
+ <a className="editorial-card-image" href={`${basePath}/${item.slug}`}>
188
+ <ThemeImageView
189
+ image={item.image || item.thumbnail || item.coverImage}
190
+ fallbackAlt={item.title}
191
+ sizes="(max-width: 720px) 92vw, 33vw"
192
+ fallbackWidth={720}
193
+ fallbackHeight={480}
194
+ />
195
+ </a>
196
+ <div className="editorial-card-content">
197
+ {(item.category?.title || item.category?.name) && (
198
+ <span>{item.category.title || item.category.name}</span>
199
+ )}
200
+ <h2>
201
+ <a href={`${basePath}/${item.slug}`}>{item.title}</a>
202
+ </h2>
203
+ {publishedDate(item.publishedAt) && (
204
+ <small className="editorial-card-date">
205
+ {publishedDate(item.publishedAt)}
206
+ </small>
207
+ )}
208
+ <p>{item.description}</p>
209
+ <a className="text-link" href={`${basePath}/${item.slug}`}>
210
+ {meta.action} <span>→</span>
211
+ </a>
212
+ </div>
213
+ </article>
214
+ ))}
215
+ </div>
216
+ );
66
217
  }
67
218
 
68
- export function createNuvlerDefaultRuntime(themeDefinition: NuvlerStoreThemeDefinition) {
69
- function Theme({ context, route = { type: "home" }, adapters, sdk }: NuvlerDefaultThemeProps) {
70
- const [cartItems, setCartItems] = useState<PreviewCartItem[]>([]);
71
- const [cartOpen, setCartOpen] = useState(false);
72
- const { Header, Footer, Home, ProductDetail, ProductGrid, NotFound } = themeDefinition.components;
73
- const site: ThemeSite = { tenant: context.store, modules: context.site.modules, settings: context.site.settings };
74
- const configured = site.settings?.theme;
75
- const tokens = {
76
- colors: { ...themeDefinition.tokens.colors, ...configured?.colors },
77
- layout: { ...themeDefinition.tokens.layout, ...configured?.layout },
78
- };
79
- const containerWidth = Math.min(1600, Math.max(960, Number(tokens.layout.containerWidth) || 1280));
80
- const borderRadius = Math.min(32, Math.max(0, Number(tokens.layout.borderRadius) || 0));
81
- const style = {
82
- "--color-primary": tokens.colors.primary,
83
- "--color-primary-text": tokens.colors.primaryText,
84
- "--color-secondary": tokens.colors.secondary,
85
- "--color-secondary-text": tokens.colors.secondaryText,
86
- "--color-accent": tokens.colors.accent,
87
- "--store-background": tokens.colors.background,
88
- "--store-surface": tokens.colors.surface,
89
- "--store-surface-alt": tokens.colors.surfaceAlt,
90
- "--store-text": tokens.colors.text,
91
- "--store-muted": tokens.colors.textMuted,
92
- "--store-line": tokens.colors.border,
93
- "--store-header-background": tokens.colors.headerBackground,
94
- "--store-header-text": tokens.colors.headerText,
95
- "--store-footer-background": tokens.colors.footerBackground,
96
- "--store-footer-text": tokens.colors.footerText,
97
- "--container-width": `${containerWidth}px`,
98
- "--border-radius": `${borderRadius}px`,
99
- } as CSSProperties;
100
- const showPrices = site.settings?.catalog?.showPrices ?? true;
101
- const cartCount = cartItems.reduce((total, item) => total + item.quantity, 0);
102
- const cartTotal = cartItems.reduce((total, item) => total + (item.unitPrice ?? 0) * item.quantity, 0);
103
- const hasCompletePrices = cartItems.length > 0 && cartItems.every(({ unitPrice }) => typeof unitPrice === "number");
104
- const cartMessage = useMemo(() => {
105
- const lines = cartItems.map((item, index) => {
106
- const price = showPrices && typeof item.unitPrice === "number" ? `\nValor unitário: ${money(item.unitPrice)}` : "";
107
- return `${index + 1}. ${item.quantity}x ${item.title}${item.variantName ? ` (${item.variantName})` : ""}${item.sku ? ` — ref. ${item.sku}` : ""}${price}`;
108
- });
109
- const summary = showPrices && hasCompletePrices ? `\n\nTotal estimado: ${money(cartTotal)}` : "";
110
- return `Olá! Gostaria de solicitar um orçamento para os itens abaixo:\n\n${lines.join("\n\n")}${summary}`;
111
- }, [cartItems, cartTotal, hasCompletePrices, showPrices]);
112
- const whatsapp = site.settings?.contact.whatsapp?.replace(/\D/g, "");
113
- const checkoutUrl = whatsapp && cartItems.length
114
- ? `https://wa.me/${whatsapp}?text=${encodeURIComponent(cartMessage)}`
115
- : null;
116
- const addToCart = (item: ThemeCartItem) => {
117
- const key = `${item.productSlug}::${item.variantId || "parent"}`;
118
- setCartItems((current) => {
119
- const existing = current.find((candidate) => candidate.key === key);
120
- if (existing) return current.map((candidate) => candidate.key === key ? { ...candidate, quantity: Math.min(99, candidate.quantity + 1) } : candidate);
121
- return [...current, { ...item, key, quantity: 1 }];
122
- });
123
- setCartOpen(true);
124
- };
125
- const cartButton = <button type="button" className="cart-button" onClick={() => setCartOpen(true)} aria-label={`Abrir carrinho com ${cartCount} itens`}><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M3 4h2l2 11h10l2-8H6M9 20h.01M17 20h.01" /></svg>{cartCount > 0 && <span>{Math.min(cartCount, 99)}</span>}</button>;
126
- let content;
127
- if (route.type === "home") content = <main><Home sections={context.home.content.sections} products={context.catalog.products} posts={context.editorial.posts} services={context.editorial.services} cases={context.editorial.cases} site={site} submitContact={sdk?.contact?.submit} template={themeDefinition.template} /></main>;
128
- else if (route.type === "product") content = <main className="product-page"><div className="store-container"><nav className="breadcrumbs" aria-label="Navegação estrutural"><a href="/">Início</a><span>/</span><a href="/produtos">Produtos</a><span>/</span><strong>{route.product.title}</strong></nav><ProductDetail product={route.product} showPrices={showPrices} contact={site.settings?.contact} productUrl={window.location.href} descriptionContent={<p>{plainText(route.product.description)}</p>} onAddToCart={addToCart} /></div></main>;
129
- else if (route.type === "catalog") content = <main className="catalog-page"><section className="catalog-hero"><div className="store-container"><span>Nosso catálogo</span><h1>{route.search ? `Busca por “${route.search}”` : "Todos os produtos"}</h1><p>{route.pagination.total} produto(s)</p></div></section><div className="store-container catalog-layout"><aside className="category-filter catalog-filters"><form action={route.categoryPath.length ? `/${route.categoryPath.join("/")}` : "/produtos"} className="catalog-filter-form"><label htmlFor="preview-catalog-search">Buscar no catálogo</label><div className="catalog-filter-search"><input id="preview-catalog-search" name="busca" type="search" defaultValue={route.search} placeholder="Nome do produto" /><button type="submit" aria-label="Pesquisar">⌕</button></div></form>{route.facets.length > 0 && <form className="catalog-variant-filters">{route.search && <input type="hidden" name="busca" value={route.search} />}{route.facets.map((facet) => <fieldset className="catalog-filter-section" key={facet.name}><legend>{facet.name}</legend>{facet.values.map(({ value, count }) => { const token = `${facet.name}::${value}`; return <label className="catalog-filter-checkbox" key={token}><input type="checkbox" name="variante" value={token} defaultChecked={route.variants.includes(token)} /><span>{value}</span><small>{count}</small></label>; })}</fieldset>)}<button type="submit" className="button button-primary button-block">Aplicar filtros</button></form>}</aside><section className="catalog-results"><ProductGrid products={route.products} columns={site.settings?.catalog?.desktopColumns || 3} showPrices={showPrices} showCategory={site.settings?.catalog?.showCategory} showDescription={site.settings?.catalog?.showDescription} />{route.pagination.totalPages > 1 && <nav className="catalog-pagination" aria-label="Paginação dos produtos"><a className={route.pagination.hasPreviousPage ? "" : "disabled"} href={catalogHref(route, Math.max(1, route.pagination.page - 1))}><span>‹</span> Anterior</a><div className="catalog-pagination-pages"><span className="catalog-pagination-item"><a className="active" href={catalogHref(route, route.pagination.page)}>{route.pagination.page}</a></span></div><a className={route.pagination.hasNextPage ? "" : "disabled"} href={catalogHref(route, Math.min(route.pagination.totalPages, route.pagination.page + 1))}>Próxima <span>›</span></a></nav>}</section></div></main>;
130
- else if (route.type === "editorial-list") { const meta = editorialMeta(route.basePath); content = <main className="editorial-list-page"><section className="theme-page-hero"><div className="store-container"><span className="page-kicker">{meta.eyebrow}</span><h1>{route.title}</h1></div></section><section className="store-section"><div className="store-container"><EditorialPreview items={route.items} basePath={route.basePath} /></div></section></main>; }
131
- else if (route.type === "editorial-detail") { const meta = editorialMeta(route.basePath); const image = route.item.image || route.item.coverImage || route.item.thumbnail; content = <main className="article-page"><article className="store-container article-shell"><nav className="breadcrumbs" aria-label="Navegação estrutural"><a href="/">Início</a><span>/</span><a href={route.basePath}>{route.basePath === "/blog" ? "Blog" : route.basePath === "/servicos" ? "Serviços" : "Cases"}</a><span>/</span><strong>{route.item.title}</strong></nav><header className="article-header">{(route.item.category?.title || route.item.category?.name) ? <span>{route.item.category.title || route.item.category.name}</span> : <span>{meta.eyebrow}</span>}<h1>{route.item.title}</h1>{route.item.description && <p>{route.item.description}</p>}{publishedDate(route.item.publishedAt) && <small>{publishedDate(route.item.publishedAt)}</small>}</header>{image && <ThemeImageView image={image} fallbackAlt={route.item.title} className="article-cover" priority sizes="(max-width: 1100px) 100vw, 1040px" fallbackWidth={1600} fallbackHeight={900} />}<div className="article-content"><a className="text-link" href={route.basePath}>← Voltar para {route.basePath === "/blog" ? "o blog" : route.basePath === "/servicos" ? "serviços" : "cases"}</a></div></article></main>; }
132
- else if (route.type === "not-found") content = NotFound ? <NotFound homeHref="/" /> : <main className="not-found-page"><div className="not-found-card"><span>404</span><h1>Conteúdo não encontrado</h1></div></main>;
133
- else content = <main className="not-found-page"><div className="not-found-card"><span>Carregando</span><h1>{route.title || "Buscando conteúdo da loja"}</h1></div></main>;
134
- // A 404 mantém a mesma moldura das demais páginas, inclusive o footer.
135
- const isNotFound = false;
136
- return <ThemeInteractionProvider onAddToCart={addToCart}><div className="store-shell nuvler-default-theme" data-theme-id={themeDefinition.manifest.id} data-theme-version={themeDefinition.manifest.version} style={style}><Header site={site} categories={context.navigation.categories} pages={context.navigation.pages} menu={context.navigation.menu} headerButton={context.navigation.headerButton} template={themeDefinition.template} searchProducts={adapters?.searchProducts} cart={cartButton} /><div className={`store-page${isNotFound ? " store-page-not-found" : ""}`}>{content}</div>{!isNotFound && <Footer site={site} pages={context.navigation.pages} template={themeDefinition.template} />}{cartOpen && <div className="cart-backdrop" role="presentation" onPointerDown={(event) => event.target === event.currentTarget && setCartOpen(false)}><aside className="cart-drawer" aria-label="Carrinho de orçamento"><div className="cart-heading"><div><small>Seu orçamento</small><strong>{cartCount} {cartCount === 1 ? "item" : "itens"}</strong></div><button type="button" onClick={() => setCartOpen(false)} aria-label="Fechar carrinho">×</button></div><div className="cart-items">{!cartItems.length && <div className="cart-empty"><strong>Seu carrinho está vazio</strong><p>Abra um produto e adicione-o para montar a solicitação.</p><button type="button" onClick={() => setCartOpen(false)}>Continuar navegando</button></div>}{cartItems.map((item) => <article className="cart-item" key={item.key}><a href={item.productUrl || productUrl({ slug: item.productSlug })} onClick={() => setCartOpen(false)}><ThemeImageView image={item.image} fallbackAlt={item.title} /></a><div><strong>{item.title}</strong>{item.variantName && <small>{item.variantName}</small>}{item.sku && <small>Ref. {item.sku}</small>}{showPrices && typeof item.unitPrice === "number" && <b>{money(item.unitPrice)}</b>}<div className="cart-quantity"><button type="button" onClick={() => setCartItems((current) => current.flatMap((candidate) => candidate.key !== item.key ? [candidate] : candidate.quantity > 1 ? [{ ...candidate, quantity: candidate.quantity - 1 }] : []))}>−</button><span>{item.quantity}</span><button type="button" onClick={() => setCartItems((current) => current.map((candidate) => candidate.key === item.key ? { ...candidate, quantity: Math.min(99, candidate.quantity + 1) } : candidate))}>+</button><button type="button" className="cart-remove" onClick={() => setCartItems((current) => current.filter((candidate) => candidate.key !== item.key))}>Remover</button></div></div></article>)}</div>{cartItems.length > 0 && <footer className="cart-footer">{showPrices && hasCompletePrices && <div><span>Total estimado</span><strong>{money(cartTotal)}</strong></div>}<p>O valor e a disponibilidade serão confirmados pela loja.</p>{checkoutUrl ? <a className="button button-primary button-block" href={checkoutUrl} target="_blank" rel="noreferrer">Enviar orçamento pelo WhatsApp</a> : <p className="cart-warning">Configure o WhatsApp da loja para enviar o orçamento.</p>}</footer>}</aside></div>}</div></ThemeInteractionProvider>;
219
+ export function createNuvlerDefaultRuntime(
220
+ themeDefinition: NuvlerStoreThemeDefinition,
221
+ ) {
222
+ function Theme({
223
+ context,
224
+ route = { type: "home" },
225
+ adapters,
226
+ sdk,
227
+ }: NuvlerDefaultThemeProps) {
228
+ const [cartItems, setCartItems] = useState<PreviewCartItem[]>([]);
229
+ const [cartOpen, setCartOpen] = useState(false);
230
+ const [hydratedCartKey, setHydratedCartKey] = useState<string | null>(null);
231
+ const cartStorageKey = `nuvler:cart:${context.store.slug}`;
232
+
233
+ useEffect(() => {
234
+ try {
235
+ setCartItems(readStoredCart(cartStorageKey));
236
+ } catch {
237
+ setCartItems([]);
238
+ window.localStorage.removeItem(cartStorageKey);
239
+ }
240
+ setHydratedCartKey(cartStorageKey);
241
+ }, [cartStorageKey]);
242
+
243
+ useEffect(() => {
244
+ if (hydratedCartKey !== cartStorageKey) return;
245
+ window.localStorage.setItem(cartStorageKey, JSON.stringify(cartItems));
246
+ }, [cartItems, cartStorageKey, hydratedCartKey]);
247
+
248
+ const { Header, Footer, Home, ProductDetail, ProductGrid, NotFound } =
249
+ themeDefinition.components;
250
+ const site: ThemeSite = {
251
+ tenant: context.store,
252
+ modules: context.site.modules,
253
+ settings: context.site.settings,
254
+ };
255
+ const configured = site.settings?.theme;
256
+ const tokens = {
257
+ colors: { ...themeDefinition.tokens.colors, ...configured?.colors },
258
+ layout: { ...themeDefinition.tokens.layout, ...configured?.layout },
259
+ };
260
+ const containerWidth = Math.min(
261
+ 1600,
262
+ Math.max(960, Number(tokens.layout.containerWidth) || 1280),
263
+ );
264
+ const borderRadius = Math.min(
265
+ 32,
266
+ Math.max(0, Number(tokens.layout.borderRadius) || 0),
267
+ );
268
+ const style = {
269
+ "--color-primary": tokens.colors.primary,
270
+ "--color-primary-text": tokens.colors.primaryText,
271
+ "--color-secondary": tokens.colors.secondary,
272
+ "--color-secondary-text": tokens.colors.secondaryText,
273
+ "--color-accent": tokens.colors.accent,
274
+ "--store-background": tokens.colors.background,
275
+ "--store-surface": tokens.colors.surface,
276
+ "--store-surface-alt": tokens.colors.surfaceAlt,
277
+ "--store-text": tokens.colors.text,
278
+ "--store-muted": tokens.colors.textMuted,
279
+ "--store-line": tokens.colors.border,
280
+ "--store-header-background": tokens.colors.headerBackground,
281
+ "--store-header-text": tokens.colors.headerText,
282
+ "--store-footer-background": tokens.colors.footerBackground,
283
+ "--store-footer-text": tokens.colors.footerText,
284
+ "--container-width": `${containerWidth}px`,
285
+ "--border-radius": `${borderRadius}px`,
286
+ } as CSSProperties;
287
+ const showPrices = site.settings?.catalog?.showPrices ?? true;
288
+ const cartCount = cartItems.reduce(
289
+ (total, item) => total + item.quantity,
290
+ 0,
291
+ );
292
+ const cartTotal = cartItems.reduce(
293
+ (total, item) => total + (item.unitPrice ?? 0) * item.quantity,
294
+ 0,
295
+ );
296
+ const hasCompletePrices =
297
+ cartItems.length > 0 &&
298
+ cartItems.every(({ unitPrice }) => typeof unitPrice === "number");
299
+ const cartMessage = useMemo(() => {
300
+ const lines = cartItems.map((item, index) => {
301
+ const price =
302
+ showPrices && typeof item.unitPrice === "number"
303
+ ? `\nValor unitário: ${money(item.unitPrice)}`
304
+ : "";
305
+ return `${index + 1}. ${item.quantity}x ${item.title}${item.variantName ? ` (${item.variantName})` : ""}${item.sku ? ` — ref. ${item.sku}` : ""}${price}`;
306
+ });
307
+ const summary =
308
+ showPrices && hasCompletePrices
309
+ ? `\n\nTotal estimado: ${money(cartTotal)}`
310
+ : "";
311
+ return `Olá! Gostaria de solicitar um orçamento para os itens abaixo:\n\n${lines.join("\n\n")}${summary}`;
312
+ }, [cartItems, cartTotal, hasCompletePrices, showPrices]);
313
+ const whatsapp = site.settings?.contact.whatsapp?.replace(/\D/g, "");
314
+ const checkoutUrl =
315
+ whatsapp && cartItems.length
316
+ ? `https://wa.me/${whatsapp}?text=${encodeURIComponent(cartMessage)}`
317
+ : null;
318
+ const addToCart = (item: ThemeCartItem) => {
319
+ const key = `${item.productSlug}::${item.variantId || "parent"}`;
320
+ setCartItems((current) => {
321
+ const existing = current.find((candidate) => candidate.key === key);
322
+ if (existing)
323
+ return current.map((candidate) =>
324
+ candidate.key === key
325
+ ? { ...candidate, quantity: Math.min(99, candidate.quantity + 1) }
326
+ : candidate,
327
+ );
328
+ return [...current, { ...item, key, quantity: 1 }];
329
+ });
330
+ setCartOpen(true);
331
+ };
332
+ const cartButton = (
333
+ <button
334
+ type="button"
335
+ className="cart-button"
336
+ onClick={() => setCartOpen(true)}
337
+ aria-label={`Abrir carrinho com ${cartCount} itens`}
338
+ >
339
+ <svg viewBox="0 0 24 24" aria-hidden="true">
340
+ <path d="M3 4h2l2 11h10l2-8H6M9 20h.01M17 20h.01" />
341
+ </svg>
342
+ {cartCount > 0 && <span>{Math.min(cartCount, 99)}</span>}
343
+ </button>
344
+ );
345
+ let content;
346
+ if (route.type === "home")
347
+ content = (
348
+ <main>
349
+ <Home
350
+ sections={context.home.content.sections}
351
+ products={context.catalog.products}
352
+ posts={context.editorial.posts}
353
+ services={context.editorial.services}
354
+ cases={context.editorial.cases}
355
+ site={site}
356
+ submitContact={sdk?.contact?.submit}
357
+ template={themeDefinition.template}
358
+ />
359
+ </main>
360
+ );
361
+ else if (route.type === "product")
362
+ content = (
363
+ <main className="product-page">
364
+ <div className="store-container">
365
+ <nav className="breadcrumbs" aria-label="Navegação estrutural">
366
+ <a href="/">Início</a>
367
+ <span>/</span>
368
+ <a href="/produtos">Produtos</a>
369
+ <span>/</span>
370
+ <strong>{route.product.title}</strong>
371
+ </nav>
372
+ <ProductDetail
373
+ product={route.product}
374
+ showPrices={showPrices}
375
+ contact={site.settings?.contact}
376
+ productUrl={window.location.href}
377
+ descriptionContent={<p>{plainText(route.product.description)}</p>}
378
+ onAddToCart={addToCart}
379
+ />
380
+ </div>
381
+ </main>
382
+ );
383
+ else if (route.type === "catalog")
384
+ content = (
385
+ <main className="catalog-page">
386
+ <section className="catalog-hero">
387
+ <div className="store-container">
388
+ <span>Nosso catálogo</span>
389
+ <h1>
390
+ {route.search
391
+ ? `Busca por “${route.search}”`
392
+ : "Todos os produtos"}
393
+ </h1>
394
+ <p>{route.pagination.total} produto(s)</p>
395
+ </div>
396
+ </section>
397
+ <div className="store-container catalog-layout">
398
+ <aside className="category-filter catalog-filters">
399
+ <form
400
+ action={
401
+ route.categoryPath.length
402
+ ? `/${route.categoryPath.join("/")}`
403
+ : "/produtos"
404
+ }
405
+ className="catalog-filter-form"
406
+ >
407
+ <label htmlFor="preview-catalog-search">
408
+ Buscar no catálogo
409
+ </label>
410
+ <div className="catalog-filter-search">
411
+ <input
412
+ id="preview-catalog-search"
413
+ name="busca"
414
+ type="search"
415
+ defaultValue={route.search}
416
+ placeholder="Nome do produto"
417
+ />
418
+ <button type="submit" aria-label="Pesquisar">
419
+ ⌕
420
+ </button>
421
+ </div>
422
+ </form>
423
+ {route.facets.length > 0 && (
424
+ <form className="catalog-variant-filters">
425
+ {route.search && (
426
+ <input type="hidden" name="busca" value={route.search} />
427
+ )}
428
+ {route.facets.map((facet) => (
429
+ <fieldset
430
+ className="catalog-filter-section"
431
+ key={facet.name}
432
+ >
433
+ <legend>{facet.name}</legend>
434
+ {facet.values.map(({ value, count }) => {
435
+ const token = `${facet.name}::${value}`;
436
+ return (
437
+ <label
438
+ className="catalog-filter-checkbox"
439
+ key={token}
440
+ >
441
+ <input
442
+ type="checkbox"
443
+ name="variante"
444
+ value={token}
445
+ defaultChecked={route.variants.includes(token)}
446
+ />
447
+ <span>{value}</span>
448
+ <small>{count}</small>
449
+ </label>
450
+ );
451
+ })}
452
+ </fieldset>
453
+ ))}
454
+ <button
455
+ type="submit"
456
+ className="button button-primary button-block"
457
+ >
458
+ Aplicar filtros
459
+ </button>
460
+ </form>
461
+ )}
462
+ </aside>
463
+ <section className="catalog-results">
464
+ <ProductGrid
465
+ products={route.products}
466
+ columns={site.settings?.catalog?.desktopColumns || 3}
467
+ showPrices={showPrices}
468
+ showCategory={site.settings?.catalog?.showCategory}
469
+ showDescription={site.settings?.catalog?.showDescription}
470
+ />
471
+ {route.pagination.totalPages > 1 && (
472
+ <nav
473
+ className="catalog-pagination"
474
+ aria-label="Paginação dos produtos"
475
+ >
476
+ <a
477
+ className={
478
+ route.pagination.hasPreviousPage ? "" : "disabled"
479
+ }
480
+ href={catalogHref(
481
+ route,
482
+ Math.max(1, route.pagination.page - 1),
483
+ )}
484
+ >
485
+ <span>‹</span> Anterior
486
+ </a>
487
+ <div className="catalog-pagination-pages">
488
+ <span className="catalog-pagination-item">
489
+ <a
490
+ className="active"
491
+ href={catalogHref(route, route.pagination.page)}
492
+ >
493
+ {route.pagination.page}
494
+ </a>
495
+ </span>
496
+ </div>
497
+ <a
498
+ className={route.pagination.hasNextPage ? "" : "disabled"}
499
+ href={catalogHref(
500
+ route,
501
+ Math.min(
502
+ route.pagination.totalPages,
503
+ route.pagination.page + 1,
504
+ ),
505
+ )}
506
+ >
507
+ Próxima <span>›</span>
508
+ </a>
509
+ </nav>
510
+ )}
511
+ </section>
512
+ </div>
513
+ </main>
514
+ );
515
+ else if (route.type === "editorial-list") {
516
+ const meta = editorialMeta(route.basePath);
517
+ content = (
518
+ <main className="editorial-list-page">
519
+ <section className="theme-page-hero">
520
+ <div className="store-container">
521
+ <span className="page-kicker">{meta.eyebrow}</span>
522
+ <h1>{route.title}</h1>
523
+ </div>
524
+ </section>
525
+ <section className="store-section">
526
+ <div className="store-container">
527
+ <EditorialPreview items={route.items} basePath={route.basePath} />
528
+ </div>
529
+ </section>
530
+ </main>
531
+ );
532
+ } else if (route.type === "editorial-detail") {
533
+ const meta = editorialMeta(route.basePath);
534
+ const image =
535
+ route.item.image || route.item.coverImage || route.item.thumbnail;
536
+ content = (
537
+ <main className="article-page">
538
+ <article className="store-container article-shell">
539
+ <nav className="breadcrumbs" aria-label="Navegação estrutural">
540
+ <a href="/">Início</a>
541
+ <span>/</span>
542
+ <a href={route.basePath}>
543
+ {route.basePath === "/blog"
544
+ ? "Blog"
545
+ : route.basePath === "/servicos"
546
+ ? "Serviços"
547
+ : "Cases"}
548
+ </a>
549
+ <span>/</span>
550
+ <strong>{route.item.title}</strong>
551
+ </nav>
552
+ <header className="article-header">
553
+ {route.item.category?.title || route.item.category?.name ? (
554
+ <span>
555
+ {route.item.category.title || route.item.category.name}
556
+ </span>
557
+ ) : (
558
+ <span>{meta.eyebrow}</span>
559
+ )}
560
+ <h1>{route.item.title}</h1>
561
+ {route.item.description && <p>{route.item.description}</p>}
562
+ {publishedDate(route.item.publishedAt) && (
563
+ <small>{publishedDate(route.item.publishedAt)}</small>
564
+ )}
565
+ </header>
566
+ {image && (
567
+ <ThemeImageView
568
+ image={image}
569
+ fallbackAlt={route.item.title}
570
+ className="article-cover"
571
+ priority
572
+ sizes="(max-width: 1100px) 100vw, 1040px"
573
+ fallbackWidth={1600}
574
+ fallbackHeight={900}
575
+ />
576
+ )}
577
+ <div className="article-content">
578
+ <a className="text-link" href={route.basePath}>
579
+ ← Voltar para{" "}
580
+ {route.basePath === "/blog"
581
+ ? "o blog"
582
+ : route.basePath === "/servicos"
583
+ ? "serviços"
584
+ : "cases"}
585
+ </a>
586
+ </div>
587
+ </article>
588
+ </main>
589
+ );
590
+ } else if (route.type === "not-found")
591
+ content = NotFound ? (
592
+ <NotFound homeHref="/" />
593
+ ) : (
594
+ <main className="not-found-page">
595
+ <div className="not-found-card">
596
+ <span>404</span>
597
+ <h1>Conteúdo não encontrado</h1>
598
+ </div>
599
+ </main>
600
+ );
601
+ else
602
+ content = (
603
+ <main className="not-found-page">
604
+ <div className="not-found-card">
605
+ <span>Carregando</span>
606
+ <h1>{route.title || "Buscando conteúdo da loja"}</h1>
607
+ </div>
608
+ </main>
609
+ );
610
+ // A 404 mantém a mesma moldura das demais páginas, inclusive o footer.
611
+ const isNotFound = false;
612
+ return (
613
+ <ThemeInteractionProvider onAddToCart={addToCart}>
614
+ <div
615
+ className="store-shell nuvler-default-theme"
616
+ data-theme-id={themeDefinition.manifest.id}
617
+ data-theme-version={themeDefinition.manifest.version}
618
+ style={style}
619
+ >
620
+ <Header
621
+ site={site}
622
+ categories={context.navigation.categories}
623
+ pages={context.navigation.pages}
624
+ menu={context.navigation.menu}
625
+ headerButton={context.navigation.headerButton}
626
+ template={themeDefinition.template}
627
+ searchProducts={adapters?.searchProducts}
628
+ cart={cartButton}
629
+ />
630
+ <div
631
+ className={`store-page${isNotFound ? " store-page-not-found" : ""}`}
632
+ >
633
+ {content}
634
+ </div>
635
+ {!isNotFound && (
636
+ <Footer
637
+ site={site}
638
+ pages={context.navigation.pages}
639
+ template={themeDefinition.template}
640
+ />
641
+ )}
642
+ {cartOpen && (
643
+ <div
644
+ className="cart-backdrop"
645
+ role="presentation"
646
+ onPointerDown={(event) =>
647
+ event.target === event.currentTarget && setCartOpen(false)
648
+ }
649
+ >
650
+ <aside className="cart-drawer" aria-label="Carrinho de orçamento">
651
+ <div className="cart-heading">
652
+ <div>
653
+ <small>Seu orçamento</small>
654
+ <strong>
655
+ {cartCount} {cartCount === 1 ? "item" : "itens"}
656
+ </strong>
657
+ </div>
658
+ <button
659
+ type="button"
660
+ onClick={() => setCartOpen(false)}
661
+ aria-label="Fechar carrinho"
662
+ >
663
+ ×
664
+ </button>
665
+ </div>
666
+ <div className="cart-items">
667
+ {!cartItems.length && (
668
+ <div className="cart-empty">
669
+ <strong>Seu carrinho está vazio</strong>
670
+ <p>
671
+ Abra um produto e adicione-o para montar a solicitação.
672
+ </p>
673
+ <button type="button" onClick={() => setCartOpen(false)}>
674
+ Continuar navegando
675
+ </button>
676
+ </div>
677
+ )}
678
+ {cartItems.map((item) => (
679
+ <article className="cart-item" key={item.key}>
680
+ <a
681
+ href={
682
+ item.productUrl ||
683
+ productUrl({ slug: item.productSlug })
684
+ }
685
+ onClick={() => setCartOpen(false)}
686
+ >
687
+ <ThemeImageView
688
+ image={item.image}
689
+ fallbackAlt={item.title}
690
+ />
691
+ </a>
692
+ <div>
693
+ <strong>{item.title}</strong>
694
+ {item.variantName && <small>{item.variantName}</small>}
695
+ {item.sku && <small>Ref. {item.sku}</small>}
696
+ {showPrices && typeof item.unitPrice === "number" && (
697
+ <b>{money(item.unitPrice)}</b>
698
+ )}
699
+ <div className="cart-quantity">
700
+ <button
701
+ type="button"
702
+ onClick={() =>
703
+ setCartItems((current) =>
704
+ current.flatMap((candidate) =>
705
+ candidate.key !== item.key
706
+ ? [candidate]
707
+ : candidate.quantity > 1
708
+ ? [
709
+ {
710
+ ...candidate,
711
+ quantity: candidate.quantity - 1,
712
+ },
713
+ ]
714
+ : [],
715
+ ),
716
+ )
717
+ }
718
+ >
719
+ −
720
+ </button>
721
+ <span>{item.quantity}</span>
722
+ <button
723
+ type="button"
724
+ onClick={() =>
725
+ setCartItems((current) =>
726
+ current.map((candidate) =>
727
+ candidate.key === item.key
728
+ ? {
729
+ ...candidate,
730
+ quantity: Math.min(
731
+ 99,
732
+ candidate.quantity + 1,
733
+ ),
734
+ }
735
+ : candidate,
736
+ ),
737
+ )
738
+ }
739
+ >
740
+ +
741
+ </button>
742
+ <button
743
+ type="button"
744
+ className="cart-remove"
745
+ onClick={() =>
746
+ setCartItems((current) =>
747
+ current.filter(
748
+ (candidate) => candidate.key !== item.key,
749
+ ),
750
+ )
751
+ }
752
+ >
753
+ Remover
754
+ </button>
755
+ </div>
756
+ </div>
757
+ </article>
758
+ ))}
759
+ </div>
760
+ {cartItems.length > 0 && (
761
+ <footer className="cart-footer">
762
+ {showPrices && hasCompletePrices && (
763
+ <div>
764
+ <span>Total estimado</span>
765
+ <strong>{money(cartTotal)}</strong>
766
+ </div>
767
+ )}
768
+ <p>
769
+ O valor e a disponibilidade serão confirmados pela loja.
770
+ </p>
771
+ {checkoutUrl ? (
772
+ <a
773
+ className="button button-primary button-block"
774
+ href={checkoutUrl}
775
+ target="_blank"
776
+ rel="noreferrer"
777
+ >
778
+ Enviar orçamento pelo WhatsApp
779
+ </a>
780
+ ) : (
781
+ <p className="cart-warning">
782
+ Configure o WhatsApp da loja para enviar o orçamento.
783
+ </p>
784
+ )}
785
+ </footer>
786
+ )}
787
+ </aside>
788
+ </div>
789
+ )}
790
+ </div>
791
+ </ThemeInteractionProvider>
792
+ );
137
793
  }
138
794
 
139
795
  Theme.displayName = `NuvlerThemeRuntime(${themeDefinition.manifest.id})`;