@nuvler/cli 0.5.5 → 0.5.7

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.
Files changed (33) hide show
  1. package/dist/nuvler.js +49 -9
  2. package/dist/nuvler.js.map +1 -1
  3. package/dist/preview/launcher.js +4 -3
  4. package/dist/preview/launcher.js.map +1 -1
  5. package/dist/templates/nuvler-default/nuvler.theme.json +150 -7
  6. package/dist/templates/nuvler-default/package.json +1 -1
  7. package/dist/templates/nuvler-default/src/assets/not-found-cloud.png +0 -0
  8. package/dist/templates/nuvler-default/src/assets/not-found-cloud.svg +131 -0
  9. package/dist/templates/nuvler-default/src/assets/not-found-illustration.png +0 -0
  10. package/dist/templates/nuvler-default/src/banner-carousel.tsx +11 -0
  11. package/dist/templates/nuvler-default/src/carousel-frame.tsx +8 -4
  12. package/dist/templates/nuvler-default/src/definition.ts +2 -1
  13. package/dist/templates/nuvler-default/src/footer.tsx +4 -2
  14. package/dist/templates/nuvler-default/src/header-interactions.tsx +30 -17
  15. package/dist/templates/nuvler-default/src/header.tsx +25 -10
  16. package/dist/templates/nuvler-default/src/home.tsx +37 -25
  17. package/dist/templates/nuvler-default/src/index.ts +2 -0
  18. package/dist/templates/nuvler-default/src/not-found.tsx +29 -0
  19. package/dist/templates/nuvler-default/src/product-carousel.tsx +1 -1
  20. package/dist/templates/nuvler-default/src/product-detail-interactive.tsx +7 -1
  21. package/dist/templates/nuvler-default/src/product-detail.tsx +27 -5
  22. package/dist/templates/nuvler-default/src/products.tsx +13 -2
  23. package/dist/templates/nuvler-default/src/server-shell.tsx +5 -5
  24. package/dist/templates/nuvler-default/src/styles.d.ts +15 -0
  25. package/dist/templates/nuvler-default/src/theme-component.tsx +27 -8
  26. package/dist/templates/nuvler-default/src/theme-config.ts +12 -12
  27. package/dist/templates/nuvler-default/src/theme.css +1724 -169
  28. package/package.json +1 -1
  29. package/preview-host/src/main.tsx +16 -1
  30. package/preview-host/src/preview-path.d.mts +4 -1
  31. package/preview-host/src/preview-path.mjs +32 -1
  32. package/preview-host/vendor/theme-runtime/default-theme.tsx +128 -3
  33. package/preview-host/vendor/theme-runtime/index.ts +1 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nuvler/cli",
3
- "version": "0.5.5",
3
+ "version": "0.5.7",
4
4
  "description": "CLI oficial para criação, validação, preview e empacotamento de temas Nuvler",
5
5
  "type": "module",
6
6
  "bin": {
@@ -22,8 +22,22 @@ function PreviewImage({ image, fallbackAlt, className }: ThemeImageProps) {
22
22
  return <img className={className} src={image.url} alt={image.alt || fallbackAlt} />;
23
23
  }
24
24
 
25
+ function categoryPathFromNavigation(slug: string, categories: typeof context.navigation.categories, path: string[] = []): string[] | null {
26
+ for (const category of categories) {
27
+ const currentPath = [...path, category.slug];
28
+ if (category.slug === slug) return currentPath;
29
+ const match = categoryPathFromNavigation(slug, category.children ?? [], currentPath);
30
+ if (match) return match;
31
+ }
32
+ return null;
33
+ }
34
+
25
35
  function normalizeProduct(value: unknown): ThemeProduct {
26
36
  const product = value as Partial<ThemeProduct>;
37
+ const explicitCategoryPath = product.categoryPath?.filter(Boolean) ?? [];
38
+ const categoryPath = explicitCategoryPath.length > 0
39
+ ? explicitCategoryPath
40
+ : product.categories?.map((category) => categoryPathFromNavigation(category.slug, context.navigation.categories)).find(Boolean) ?? [];
27
41
  return {
28
42
  title: product.title || "Produto",
29
43
  slug: product.slug || "produto",
@@ -38,6 +52,7 @@ function normalizeProduct(value: unknown): ThemeProduct {
38
52
  image: product.image || null,
39
53
  images: product.images || [],
40
54
  categories: product.categories || [],
55
+ categoryPath,
41
56
  variantOptions: product.variantOptions || [],
42
57
  variants: product.variants || [],
43
58
  publishedAt: product.publishedAt ?? null,
@@ -112,7 +127,7 @@ function PreviewApp() {
112
127
  if (localRoute) { setRoute(localRoute); return; }
113
128
  setRoute({ type: "loading", pathname: url.pathname });
114
129
  try {
115
- const target = classifyPreviewPath(url.pathname);
130
+ const target = classifyPreviewPath(url.pathname, context.navigation.categories);
116
131
  if (target.type === "product") {
117
132
  const slug = target.slug;
118
133
  const product = normalizeProduct(await previewApi<unknown>(`products/${encodeURIComponent(slug)}`));
@@ -1,4 +1,7 @@
1
- export function classifyPreviewPath(pathname: string):
1
+ export function classifyPreviewPath(
2
+ pathname: string,
3
+ categories?: Array<{ slug: string; children?: unknown[] }>,
4
+ ):
2
5
  | { type: "catalog"; categoryPath: string[] }
3
6
  | { type: "page" | "product"; slug: string }
4
7
  | { type: "not-found" };
@@ -1,4 +1,18 @@
1
- export function classifyPreviewPath(pathname) {
1
+ function matchedCategoryPath(segments, categories) {
2
+ const path = [];
3
+ let current = Array.isArray(categories) ? categories : [];
4
+
5
+ for (const segment of segments) {
6
+ const category = current.find((item) => item?.slug === segment);
7
+ if (!category) break;
8
+ path.push(category.slug);
9
+ current = Array.isArray(category.children) ? category.children : [];
10
+ }
11
+
12
+ return path;
13
+ }
14
+
15
+ export function classifyPreviewPath(pathname, categories = []) {
2
16
  const segments = pathname.split("/").filter(Boolean).map(decodeURIComponent);
3
17
  if (segments.length === 1 && segments[0] === "produtos") {
4
18
  return { type: "catalog", categoryPath: [] };
@@ -9,6 +23,23 @@ export function classifyPreviewPath(pathname) {
9
23
  if (segments[0] === "produto" && segments.length === 2) {
10
24
  return { type: "product", slug: segments[1] };
11
25
  }
26
+
27
+ // As categorias do tenant podem ser links de primeiro nível, como `/casa`.
28
+ // Somente um caminho que corresponda integralmente à árvore é um catálogo;
29
+ // o segmento seguinte é o slug do produto.
30
+ const categoryPath = matchedCategoryPath(segments, categories);
31
+ if (categoryPath.length === segments.length && categoryPath.length > 0) {
32
+ return { type: "catalog", categoryPath };
33
+ }
34
+ if (categoryPath.length > 0 && segments.length === categoryPath.length + 1) {
35
+ return { type: "product", slug: segments.at(-1) };
36
+ }
37
+
38
+ // A URL canônica do Theme SDK preserva o caminho da categoria antes do slug
39
+ // do produto (por exemplo, /moveis/mesas/mesa-de-jantar).
40
+ if (segments.length > 1) {
41
+ return { type: "product", slug: segments.at(-1) };
42
+ }
12
43
  if (segments.length === 1) return { type: "page", slug: segments[0] };
13
44
  return { type: "not-found" };
14
45
  }
@@ -6,6 +6,7 @@ import type {
6
6
  ThemeHomeSection,
7
7
  ThemeHomeSectionType,
8
8
  ThemeEditorialItem,
9
+ NotFoundProps,
9
10
  ThemeProduct,
10
11
  ThemeRuntimeSdk,
11
12
  ThemeSiteColors,
@@ -421,12 +422,109 @@ function formatWhatsapp(value: string): string {
421
422
  : `(${digits.slice(0, 2)}) ${number.slice(0, 5)}-${number.slice(5)}`;
422
423
  }
423
424
 
425
+ function formatCep(value: string): string {
426
+ const digits = value.replace(/\D/g, "").slice(0, 8);
427
+ return digits.length > 5 ? `${digits.slice(0, 5)}-${digits.slice(5)}` : digits;
428
+ }
429
+
430
+ function formatDocument(value: string, mask: string): string {
431
+ if (mask === "rg-br") {
432
+ const chars = value.toUpperCase().replace(/[^0-9X]/g, "").slice(0, 9);
433
+ return chars.replace(/^(\d{2})(\d{1,3})?(\d{1,3})?([0-9X])?$/, (_, a: string, b?: string, c?: string, d?: string) =>
434
+ [a, b, c].filter(Boolean).join(".") + (d ? `-${d}` : ""));
435
+ }
436
+ const digits = value.replace(/\D/g, "").slice(0, mask === "cpf-br" ? 11 : 14);
437
+ if (mask === "cpf-br" || mask === "cpf-cnpj-br" && digits.length <= 11) {
438
+ return digits.replace(/^(\d{3})(\d{1,3})?(\d{1,3})?(\d{1,2})?$/, (_, a: string, b?: string, c?: string, d?: string) =>
439
+ a + (b ? `.${b}` : "") + (c ? `.${c}` : "") + (d ? `-${d}` : ""));
440
+ }
441
+ return digits.replace(/^(\d{2})(\d{1,3})?(\d{1,3})?(\d{1,4})?(\d{1,2})?$/, (_, a: string, b?: string, c?: string, d?: string, e?: string) =>
442
+ a + (b ? `.${b}` : "") + (c ? `.${c}` : "") + (d ? `/${d}` : "") + (e ? `-${e}` : ""));
443
+ }
444
+
445
+ const addressFieldAliases = {
446
+ address: ["address", "endereco", "logradouro"],
447
+ district: ["district", "bairro"],
448
+ city: ["city", "cidade", "municipio"],
449
+ state: ["state", "estado", "uf"],
450
+ } as const;
451
+
424
452
  function ContactFormComponent({ section, sdk }: ThemeSectionRendererProps) {
425
453
  const props = dataRecord(section.data, "props");
426
454
  const configuredFields = dataRecords(props, "fields");
427
455
  const fields = configuredFields;
428
456
  const [status, setStatus] = useState<"idle" | "sending" | "success" | "error">("idle");
429
457
  const [error, setError] = useState("");
458
+ const [cepStatus, setCepStatus] = useState<"idle" | "loading" | "success" | "error">("idle");
459
+ const [cepMessage, setCepMessage] = useState("");
460
+ const formRef = useRef<HTMLFormElement>(null);
461
+ const lastSearchedCep = useRef("");
462
+ const cepController = useRef<AbortController | null>(null);
463
+
464
+ useEffect(() => () => {
465
+ cepController.current?.abort();
466
+ cepController.current = null;
467
+ }, []);
468
+
469
+ const searchCep = async (value: string) => {
470
+ const cleanCep = value.replace(/\D/g, "");
471
+ if (cleanCep.length !== 8) {
472
+ cepController.current?.abort();
473
+ cepController.current = null;
474
+ lastSearchedCep.current = "";
475
+ setCepStatus("idle");
476
+ setCepMessage("");
477
+ return;
478
+ }
479
+ if (cleanCep === lastSearchedCep.current) return;
480
+
481
+ cepController.current?.abort();
482
+ const controller = new AbortController();
483
+ cepController.current = controller;
484
+ lastSearchedCep.current = cleanCep;
485
+ const timeout = window.setTimeout(() => controller.abort(), 5000);
486
+ setCepStatus("loading");
487
+ setCepMessage("Buscando endereço…");
488
+
489
+ try {
490
+ const response = await fetch(`https://viacep.com.br/ws/${cleanCep}/json/`, {
491
+ signal: controller.signal,
492
+ });
493
+ if (!response.ok) throw new Error("CEP_FETCH_FAILED");
494
+ const data = await response.json() as { erro?: boolean; logradouro?: string; bairro?: string; localidade?: string; uf?: string };
495
+ if (data.erro) {
496
+ setCepStatus("error");
497
+ setCepMessage("CEP não encontrado. Confira o número ou preencha o endereço manualmente.");
498
+ return;
499
+ }
500
+
501
+ const addressValues = {
502
+ address: data.logradouro || "",
503
+ district: data.bairro || "",
504
+ city: data.localidade || "",
505
+ state: data.uf || "",
506
+ };
507
+ const configuredKeys = new Set(fields.map((field) => dataString(field, "key")));
508
+ for (const [part, aliases] of Object.entries(addressFieldAliases)) {
509
+ const targetKey = aliases.find((alias) => configuredKeys.has(alias));
510
+ const nextValue = addressValues[part as keyof typeof addressValues];
511
+ const target = targetKey
512
+ ? formRef.current?.elements.namedItem(targetKey)
513
+ : null;
514
+ if (nextValue && target instanceof HTMLInputElement) target.value = nextValue;
515
+ }
516
+ setCepStatus("success");
517
+ setCepMessage("Endereço preenchido. Confira os dados e informe o número, se necessário.");
518
+ } catch {
519
+ if (controller.signal.aborted && cepController.current !== controller) return;
520
+ setCepStatus("error");
521
+ setCepMessage(controller.signal.aborted
522
+ ? "A consulta demorou demais. Você pode preencher o endereço manualmente."
523
+ : "Não foi possível consultar o CEP. Preencha o endereço manualmente.");
524
+ } finally {
525
+ window.clearTimeout(timeout);
526
+ }
527
+ };
430
528
 
431
529
  const submit = async (event: FormEvent<HTMLFormElement>) => {
432
530
  event.preventDefault();
@@ -439,9 +537,15 @@ function ContactFormComponent({ section, sdk }: ThemeSectionRendererProps) {
439
537
  setError("");
440
538
  const form = new FormData(event.currentTarget);
441
539
  const values: Record<string, string | boolean | string[]> = {};
540
+ const attachments: Record<string, File> = {};
442
541
  for (const field of fields) {
443
542
  const key = dataString(field, "key");
444
543
  if (!key) continue;
544
+ if (dataString(field, "type") === "file") {
545
+ const file = form.get(key);
546
+ if (file instanceof File && file.size) attachments[key] = file;
547
+ continue;
548
+ }
445
549
  if (dataString(field, "type") === "checkbox") {
446
550
  values[key] = form.has(key);
447
551
  continue;
@@ -454,9 +558,13 @@ function ContactFormComponent({ section, sdk }: ThemeSectionRendererProps) {
454
558
  formKey: dataString(section.data, "componentKey", "contact-form"),
455
559
  sectionId: section.id,
456
560
  values,
561
+ ...(Object.keys(attachments).length ? { attachments } : {}),
457
562
  pathname: typeof window === "undefined" ? undefined : window.location.pathname,
458
563
  });
459
564
  event.currentTarget.reset();
565
+ lastSearchedCep.current = "";
566
+ setCepStatus("idle");
567
+ setCepMessage("");
460
568
  setStatus("success");
461
569
  } catch (cause) {
462
570
  setStatus("error");
@@ -470,7 +578,7 @@ function ContactFormComponent({ section, sdk }: ThemeSectionRendererProps) {
470
578
  <h2>{dataString(props, "title", "Fale com nossa equipe")}</h2>
471
579
  {dataString(props, "description") && <p>{dataString(props, "description")}</p>}
472
580
  </div>
473
- <form className="contact-form" onSubmit={(event) => void submit(event)}>
581
+ <form className="contact-form" ref={formRef} onSubmit={(event) => void submit(event)}>
474
582
  {fields.map((field) => {
475
583
  const key = dataString(field, "key");
476
584
  if (!key) return null;
@@ -481,6 +589,11 @@ function ContactFormComponent({ section, sdk }: ThemeSectionRendererProps) {
481
589
  <input name={key} required={required} type="checkbox" value="true" />
482
590
  <span>{label}{required && <small aria-hidden="true"> *</small>}</span>
483
591
  </label>;
592
+ if (type === "file") return <label className="contact-form-wide" key={key}>
593
+ <span>{label}{required && <small aria-hidden="true"> *</small>}</span>
594
+ <input name={key} required={required} type="file" accept=".pdf,.jpg,.jpeg,.png,application/pdf,image/jpeg,image/png" />
595
+ <small>PDF, JPG ou PNG, até 4 MB no total.</small>
596
+ </label>;
484
597
  if (type === "select") return <label key={key}>
485
598
  <span>{label}{required && <small aria-hidden="true"> *</small>}</span>
486
599
  <select name={key} required={required}>{dataRecords(field, "options").map((option) => <option key={dataString(option, "value")} value={dataString(option, "value")}>{dataString(option, "label", dataString(option, "value"))}</option>)}</select>
@@ -489,10 +602,11 @@ function ContactFormComponent({ section, sdk }: ThemeSectionRendererProps) {
489
602
  <span>{label}{required && <small aria-hidden="true"> *</small>}</span>
490
603
  {type === "textarea"
491
604
  ? <textarea name={key} placeholder={dataString(field, "placeholder")} required={required} rows={5} />
492
- : <input name={key} placeholder={dataString(field, "placeholder")} required={required} type={["email", "tel", "url", "number"].includes(type) ? type : "text"} maxLength={dataString(field, "mask") === "whatsapp-br" ? 15 : undefined} onInput={dataString(field, "mask") === "whatsapp-br" ? (event) => { event.currentTarget.value = formatWhatsapp(event.currentTarget.value); } : undefined} />}
605
+ : <input name={key} placeholder={dataString(field, "placeholder")} required={required} type={["email", "tel", "url", "number"].includes(type) ? type : "text"} maxLength={dataString(field, "mask") === "whatsapp-br" ? 15 : dataString(field, "mask") === "cep-br" ? 9 : dataString(field, "mask") === "cpf-br" ? 14 : dataString(field, "mask") === "cnpj-br" || dataString(field, "mask") === "cpf-cnpj-br" ? 18 : dataString(field, "mask") === "rg-br" ? 12 : undefined} inputMode={["cep-br", "cpf-br", "cnpj-br", "cpf-cnpj-br"].includes(dataString(field, "mask")) ? "numeric" : undefined} autoComplete={dataString(field, "mask") === "cep-br" ? "postal-code" : undefined} onInput={dataString(field, "mask") === "whatsapp-br" ? (event) => { event.currentTarget.value = formatWhatsapp(event.currentTarget.value); } : dataString(field, "mask") === "cep-br" ? (event) => { event.currentTarget.value = formatCep(event.currentTarget.value); void searchCep(event.currentTarget.value); } : ["cpf-br", "cnpj-br", "cpf-cnpj-br", "rg-br"].includes(dataString(field, "mask")) ? (event) => { event.currentTarget.value = formatDocument(event.currentTarget.value, dataString(field, "mask")); } : undefined} />}
493
606
  </label>;
494
607
  })}
495
608
  <div className="contact-form-wide">
609
+ {cepStatus !== "idle" && <p className={`contact-form-feedback${cepStatus === "error" ? " contact-form-error" : ""}`} role={cepStatus === "error" ? "alert" : "status"}>{cepMessage}</p>}
496
610
  <button className="button button-primary" disabled={status === "sending"} type="submit">
497
611
  {status === "sending" ? "Enviando…" : dataString(props, "submitLabel", "Enviar contato")}
498
612
  </button>
@@ -698,6 +812,17 @@ function ProductPage({ product, context, adapters }: {
698
812
  </div></main>;
699
813
  }
700
814
 
815
+ /** Fallback seguro para consumidores que usam um tema sem componente NotFound. */
816
+ export function DefaultNotFound({ homeHref = "/" }: NotFoundProps) {
817
+ return <main className="not-found-page">
818
+ <div className="not-found-card">
819
+ <span>404</span>
820
+ <h1>Conteúdo não encontrado</h1>
821
+ <a className="button button-primary" href={homeHref}>Voltar ao início</a>
822
+ </div>
823
+ </main>;
824
+ }
825
+
701
826
  function RouteContent({ route, context, adapters, home, sdk }: {
702
827
  route: ThemeRoute;
703
828
  context: ThemeContext;
@@ -707,7 +832,7 @@ function RouteContent({ route, context, adapters, home, sdk }: {
707
832
  }) {
708
833
  if (route.type === "home") return home;
709
834
  if (route.type === "loading") return <main className="not-found-page"><div className="not-found-card"><span>Carregando</span><h1>Buscando conteúdo da loja</h1></div></main>;
710
- if (route.type === "not-found") return <main className="not-found-page"><div className="not-found-card"><span>404</span><h1>Conteúdo não encontrado</h1><adapters.Link className="button button-primary" href="/">Voltar ao início</adapters.Link></div></main>;
835
+ if (route.type === "not-found") return <DefaultNotFound homeHref="/" />;
711
836
  if (route.type === "catalog") return <CatalogPage adapters={adapters} context={context} route={route} />;
712
837
  if (route.type === "product") return <ProductPage adapters={adapters} context={context} product={route.product} />;
713
838
  if (route.type === "editorial-list") return <main className="catalog-page"><section className="catalog-hero"><div className="store-container"><span>Conteúdo</span><h1>{route.title}</h1></div></section><section className="store-section"><div className="store-container"><EditorialCards adapters={adapters} basePath={route.basePath} items={route.items} /></div></section></main>;
@@ -17,7 +17,7 @@ export type {
17
17
  ThemeRuntimeAdapters,
18
18
  } from "@nuvler/theme-sdk";
19
19
 
20
- export { DefaultTheme, defaultSectionRegistry } from "./default-theme.js";
20
+ export { DefaultNotFound, DefaultTheme, defaultSectionRegistry } from "./default-theme.js";
21
21
  export type {
22
22
  ThemeSectionRenderer,
23
23
  ThemeSectionRendererProps,