@nuvler/cli 0.4.4 → 0.5.0
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.
- package/README.md +10 -5
- package/dist/commands/theme/create.js +2 -2
- package/dist/commands/theme/dev.js +3 -1
- package/dist/commands/theme/dev.js.map +1 -1
- package/dist/commands/theme/migrate.js +7 -0
- package/dist/commands/theme/migrate.js.map +1 -1
- package/dist/index.js +1 -1
- package/dist/migrate/analysis/dependency-classifier.js +41 -0
- package/dist/migrate/analysis/dependency-classifier.js.map +1 -0
- package/dist/migrate/analysis/dependency-graph.js +210 -0
- package/dist/migrate/analysis/dependency-graph.js.map +1 -0
- package/dist/migrate/analyzer.js +18 -8
- package/dist/migrate/analyzer.js.map +1 -1
- package/dist/migrate/asset-copier.js +2 -2
- package/dist/migrate/asset-copier.js.map +1 -1
- package/dist/migrate/classifier.js +4 -0
- package/dist/migrate/classifier.js.map +1 -1
- package/dist/migrate/generation/fidelity-pass.js +223 -0
- package/dist/migrate/generation/fidelity-pass.js.map +1 -0
- package/dist/migrate/generator.js +1413 -57
- package/dist/migrate/generator.js.map +1 -1
- package/dist/migrate/resolvers/import-resolver.js +91 -0
- package/dist/migrate/resolvers/import-resolver.js.map +1 -0
- package/dist/migrate/transform/source-transformer.js +373 -0
- package/dist/migrate/transform/source-transformer.js.map +1 -0
- package/dist/migrate/transformer.js +297 -11
- package/dist/migrate/transformer.js.map +1 -1
- package/dist/nuvler.js +3427 -303
- package/dist/nuvler.js.map +1 -1
- package/dist/preview/prepare.js +84 -1
- package/dist/preview/prepare.js.map +1 -1
- package/dist/templates/nuvler-atelier/nuvler.theme.json +1 -1
- package/dist/templates/nuvler-atelier/package.json +2 -2
- package/dist/templates/nuvler-default/nuvler.theme.json +1 -1
- package/dist/templates/nuvler-default/package.json +1 -1
- package/dist/templates/nuvler-default/src/home.tsx +79 -2
- package/dist/templates/nuvler-default/src/theme-component.tsx +4 -3
- package/dist/templates/nuvler-default/src/theme.css +149 -0
- package/dist/templates/starter/nuvler.theme.json +1 -1
- package/dist/templates/starter/package.json +2 -2
- package/package.json +4 -4
- package/preview-host/package.json +1 -1
- package/preview-host/src/app/globals.css +5 -15
- package/preview-host/src/main.tsx +55 -5
- package/preview-host/vendor/theme-runtime/default-theme.tsx +131 -3
- package/preview-host/vite.config.ts +4 -0
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
|
|
2
2
|
import path from "node:path";
|
|
3
|
+
import ts from "typescript";
|
|
3
4
|
import { themeCreate } from "../commands/theme/create.js";
|
|
4
5
|
import { copyMigrationAssets } from "./asset-copier.js";
|
|
6
|
+
import { mergeFidelityDependencies, runFidelityPass } from "./generation/fidelity-pass.js";
|
|
5
7
|
function portable(file) {
|
|
6
8
|
return file.split(path.sep).join("/");
|
|
7
9
|
}
|
|
@@ -14,11 +16,6 @@ function profile(plan, role) {
|
|
|
14
16
|
media: "", grid: "", card: "", content: "",
|
|
15
17
|
};
|
|
16
18
|
}
|
|
17
|
-
function sourceText(plan, role, fallback) {
|
|
18
|
-
const text = plan.selected[role]?.component.text
|
|
19
|
-
.find((candidate) => candidate.length >= 3 && candidate.length <= 140);
|
|
20
|
-
return text || fallback;
|
|
21
|
-
}
|
|
22
19
|
function headerSource(plan) {
|
|
23
20
|
const style = profile(plan, "HEADER");
|
|
24
21
|
return `import type { HeaderProps } from "@nuvler/theme-sdk";
|
|
@@ -53,7 +50,7 @@ export function Footer({ site, pages, template }: FooterProps) {
|
|
|
53
50
|
const name = site.settings?.siteName || site.tenant.name;
|
|
54
51
|
return <footer className=${classes("nuvler-migrated-footer", style.root)}>
|
|
55
52
|
<div className=${classes("nuvler-migrated-footer-inner", style.content)}>
|
|
56
|
-
<div><strong className=${classes("nuvler-migrated-footer-brand", style.brand)}>{name}</strong
|
|
53
|
+
<div><strong className=${classes("nuvler-migrated-footer-brand", style.brand)}>{name}</strong>{site.settings?.description && <p className=${classes("nuvler-migrated-copy", style.text)}>{site.settings.description}</p>}</div>
|
|
57
54
|
<nav className=${classes("nuvler-migrated-footer-nav", style.navigation)} aria-label={template.footerNavigationLabel}>
|
|
58
55
|
<a href="/">Início</a>
|
|
59
56
|
{site.modules.includes("PRODUCTS") && <a href="/produtos">Produtos</a>}
|
|
@@ -64,7 +61,7 @@ export function Footer({ site, pages, template }: FooterProps) {
|
|
|
64
61
|
{site.settings?.contact.email && <a href={\`mailto:\${site.settings.contact.email}\`}>{site.settings.contact.email}</a>}
|
|
65
62
|
</div>
|
|
66
63
|
</div>
|
|
67
|
-
<small>{template.footerNote}</small>
|
|
64
|
+
{template.footerNote && <small>{template.footerNote}</small>}
|
|
68
65
|
</footer>;
|
|
69
66
|
}
|
|
70
67
|
`;
|
|
@@ -130,52 +127,437 @@ export function ProductDetail({ product, descriptionContent, onAddToCart }: Prod
|
|
|
130
127
|
}
|
|
131
128
|
`;
|
|
132
129
|
}
|
|
133
|
-
function
|
|
130
|
+
function fidelityHomeSource(fidelity) {
|
|
131
|
+
if (!fidelity.entryImportPath || !fidelity.entryExportName)
|
|
132
|
+
return null;
|
|
133
|
+
const pageImport = fidelity.entryDefaultExport
|
|
134
|
+
? `import MigratedPage from ${JSON.stringify(fidelity.entryImportPath)};`
|
|
135
|
+
: `import { ${fidelity.entryExportName} as MigratedPage } from ${JSON.stringify(fidelity.entryImportPath)};`;
|
|
136
|
+
const layoutImports = fidelity.layoutImports.map((layout, index) => (layout.defaultExport
|
|
137
|
+
? `import MigratedLayout${index} from ${JSON.stringify(layout.importPath)};`
|
|
138
|
+
: `import { ${layout.exportName} as MigratedLayout${index} } from ${JSON.stringify(layout.importPath)};`)).join("\n");
|
|
139
|
+
const content = fidelity.layoutImports.reduceRight((child, _layout, index) => `<MigratedLayout${index}>${child}</MigratedLayout${index}>`, "<MigratedPage />");
|
|
140
|
+
return `import type { HomeProps } from "@nuvler/theme-sdk";
|
|
141
|
+
import { MigratedContentProvider } from "../migrated-content.js";
|
|
142
|
+
${pageImport}
|
|
143
|
+
${layoutImports}
|
|
144
|
+
|
|
145
|
+
/** Fidelity Pass: a árvore original permanece ativa; somente o conteúdo é fornecido pelo Nuvler. */
|
|
146
|
+
export function Home(props: HomeProps) {
|
|
147
|
+
return <MigratedContentProvider {...props}>${content}</MigratedContentProvider>;
|
|
148
|
+
}
|
|
149
|
+
`;
|
|
150
|
+
}
|
|
151
|
+
function homeSource(plan, fidelity) {
|
|
152
|
+
const preserved = fidelityHomeSource(fidelity);
|
|
153
|
+
if (preserved)
|
|
154
|
+
return preserved;
|
|
134
155
|
const home = profile(plan, "HOME");
|
|
135
|
-
const hero = profile(plan, "HERO");
|
|
136
156
|
const section = profile(plan, "SECTION");
|
|
137
|
-
const
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
return `import type { HomeProps, ThemeHomeSection } from "@nuvler/theme-sdk";
|
|
157
|
+
const bindings = plan.contentBindings.map(({ id, type, order, componentKey, classes: bindingClasses }) => ({
|
|
158
|
+
id, type, order, componentKey, classes: bindingClasses,
|
|
159
|
+
}));
|
|
160
|
+
return `import { useState, type FormEvent } from "react";
|
|
161
|
+
import type { HomeProps, ThemeContactSubmissionInput, ThemeEditorialItem, ThemeHomeSection } from "@nuvler/theme-sdk";
|
|
143
162
|
import { ProductGrid } from "../components/ProductGrid.js";
|
|
144
163
|
|
|
145
|
-
|
|
164
|
+
type Binding = {
|
|
165
|
+
id: string;
|
|
166
|
+
type: ThemeHomeSection["type"];
|
|
167
|
+
order: number;
|
|
168
|
+
componentKey?: string;
|
|
169
|
+
classes: Record<"root" | "brand" | "navigation" | "title" | "text" | "action" | "media" | "grid" | "card" | "content", string>;
|
|
170
|
+
};
|
|
146
171
|
|
|
147
|
-
|
|
148
|
-
|
|
172
|
+
const migratedBindings: Binding[] = ${JSON.stringify(bindings, null, 2)};
|
|
173
|
+
|
|
174
|
+
function cx(...values: Array<string | undefined>): string {
|
|
175
|
+
return values.filter(Boolean).join(" ");
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function value(data: Record<string, unknown>, key: string): string {
|
|
179
|
+
const candidate = data[key];
|
|
149
180
|
return typeof candidate === "string" ? candidate : "";
|
|
150
181
|
}
|
|
151
182
|
|
|
152
|
-
|
|
183
|
+
function limit(data: Record<string, unknown>): number {
|
|
184
|
+
const candidate = data.limit;
|
|
185
|
+
return typeof candidate === "number" && candidate > 0 ? Math.min(candidate, 24) : 8;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
function record(value: unknown): Record<string, unknown> | null {
|
|
189
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : null;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
function media(data: Record<string, unknown>): { url: string; alt: string } | null {
|
|
193
|
+
const image = record(data.image);
|
|
194
|
+
const url = image ? value(image, "url") : value(data, "imageUrl");
|
|
195
|
+
if (!url) return null;
|
|
196
|
+
return { url, alt: (image ? value(image, "alt") : "") || value(data, "imageAlt") };
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
function bindingFor(section: ThemeHomeSection, index: number, sections: ThemeHomeSection[]): Binding | undefined {
|
|
200
|
+
if (section.id) {
|
|
201
|
+
const exact = migratedBindings.find((binding) => binding.id === section.id);
|
|
202
|
+
if (exact) return exact;
|
|
203
|
+
}
|
|
204
|
+
if (section.type === "theme-component" && typeof section.data.componentKey === "string") {
|
|
205
|
+
const custom = migratedBindings.find((binding) => binding.componentKey === section.data.componentKey);
|
|
206
|
+
if (custom) return custom;
|
|
207
|
+
}
|
|
208
|
+
const occurrence = sections.slice(0, index).filter((candidate) => candidate.type === section.type).length;
|
|
209
|
+
return migratedBindings.filter((binding) => binding.type === section.type)[occurrence]
|
|
210
|
+
?? migratedBindings[index];
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
function heading(section: ThemeHomeSection, binding: Binding | undefined) {
|
|
214
|
+
const eyebrow = value(section.data, "eyebrow");
|
|
215
|
+
const title = value(section.data, "title");
|
|
216
|
+
if (!eyebrow && !title) return null;
|
|
217
|
+
return <header className="nuvler-migrated-section-heading">
|
|
218
|
+
{eyebrow && <span>{eyebrow}</span>}
|
|
219
|
+
{title && <h2 className={cx("nuvler-migrated-section-title", binding?.classes.title)}>{title}</h2>}
|
|
220
|
+
</header>;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
function TextSection({ section, binding }: { section: ThemeHomeSection; binding?: Binding }) {
|
|
224
|
+
const eyebrow = value(section.data, "eyebrow");
|
|
225
|
+
const title = value(section.data, "title");
|
|
226
|
+
const description = value(section.data, "description") || value(section.data, "text") || value(section.data, "content");
|
|
227
|
+
const buttonLabel = value(section.data, "buttonLabel");
|
|
228
|
+
const buttonUrl = value(section.data, "buttonUrl");
|
|
229
|
+
const image = media(section.data);
|
|
230
|
+
if (!eyebrow && !title && !description && !image && !(buttonLabel && buttonUrl)) return null;
|
|
231
|
+
const hero = section.type === "hero";
|
|
232
|
+
return <section className={cx(hero ? "nuvler-migrated-hero" : "nuvler-migrated-section nuvler-migrated-generic", binding?.classes.root)} data-image-position={value(section.data, "imagePosition") || undefined}>
|
|
233
|
+
<div className={cx(hero ? "nuvler-migrated-hero-content" : "nuvler-migrated-section-content", binding?.classes.content)}>
|
|
234
|
+
{eyebrow && <span>{eyebrow}</span>}
|
|
235
|
+
{title && (hero
|
|
236
|
+
? <h1 className={cx("nuvler-migrated-hero-title", binding?.classes.title)}>{title}</h1>
|
|
237
|
+
: <h2 className={cx("nuvler-migrated-section-title", binding?.classes.title)}>{title}</h2>)}
|
|
238
|
+
{description && <p className={cx("nuvler-migrated-copy", binding?.classes.text)}>{description}</p>}
|
|
239
|
+
{buttonLabel && buttonUrl && <a className={cx("nuvler-migrated-action", binding?.classes.action)} href={buttonUrl}>{buttonLabel}</a>}
|
|
240
|
+
</div>
|
|
241
|
+
{image && <div className={cx(hero ? "nuvler-migrated-hero-media" : "nuvler-migrated-section-media", binding?.classes.media)}><img src={image.url} alt={image.alt || title} /></div>}
|
|
242
|
+
</section>;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
function ThemeComponent({ section, binding, submitContact }: { section: ThemeHomeSection; binding?: Binding; submitContact?: HomeProps["submitContact"] }) {
|
|
246
|
+
const props = record(section.data.props) ?? {};
|
|
247
|
+
const componentKey = value(section.data, "componentKey");
|
|
248
|
+
if (componentKey === "video") return <section className={cx("nuvler-migrated-section", binding?.classes.root)}><div className={binding?.classes.content}>{value(props, "eyebrow") && <span>{value(props, "eyebrow")}</span>}{value(props, "title") && <h2>{value(props, "title")}</h2>}{value(props, "description") && <p>{value(props, "description")}</p>}{value(props, "videoUrl") && <video className="nuvler-migrated-video" controls playsInline poster={value(props, "posterImageUrl") || undefined} src={value(props, "videoUrl")} />}</div></section>;
|
|
249
|
+
if (componentKey !== "contact-form") return <TextSection section={{ ...section, data: props }} binding={binding} />;
|
|
250
|
+
const configuredFields = Array.isArray(props.fields)
|
|
251
|
+
? props.fields.map(record).filter((field): field is Record<string, unknown> => Boolean(field))
|
|
252
|
+
: [];
|
|
253
|
+
const fields = configuredFields.length ? configuredFields : [
|
|
254
|
+
{ key: "name", label: "Nome", type: "text", required: true },
|
|
255
|
+
{ key: "email", label: "E-mail", type: "email", required: true },
|
|
256
|
+
{ key: "phone", label: "Telefone", type: "tel", required: false },
|
|
257
|
+
{ key: "message", label: "Mensagem", type: "textarea", required: true },
|
|
258
|
+
];
|
|
259
|
+
const [status, setStatus] = useState<"idle" | "sending" | "success" | "error">("idle");
|
|
260
|
+
const [error, setError] = useState("");
|
|
261
|
+
const submit = async (event: FormEvent<HTMLFormElement>) => {
|
|
262
|
+
event.preventDefault();
|
|
263
|
+
if (!submitContact) { setStatus("error"); setError("O envio de contatos ainda não está disponível."); return; }
|
|
264
|
+
const element = event.currentTarget;
|
|
265
|
+
const form = new FormData(element);
|
|
266
|
+
const values: ThemeContactSubmissionInput["values"] = {};
|
|
267
|
+
fields.forEach((field) => {
|
|
268
|
+
const key = value(field, "key");
|
|
269
|
+
if (!key) return;
|
|
270
|
+
if (value(field, "type") === "checkbox") { values[key] = form.has(key); return; }
|
|
271
|
+
const entries = form.getAll(key).map(String);
|
|
272
|
+
values[key] = entries.length > 1 ? entries : entries[0] ?? "";
|
|
273
|
+
});
|
|
274
|
+
setStatus("sending"); setError("");
|
|
275
|
+
try {
|
|
276
|
+
await submitContact({ formKey: componentKey, sectionId: section.id, values, pathname: typeof window === "undefined" ? undefined : window.location.pathname });
|
|
277
|
+
element.reset(); setStatus("success");
|
|
278
|
+
} catch (cause) {
|
|
279
|
+
setStatus("error"); setError(cause instanceof Error ? cause.message : "Não foi possível enviar o contato.");
|
|
280
|
+
}
|
|
281
|
+
};
|
|
282
|
+
return <section className={cx("nuvler-migrated-section nuvler-migrated-contact-form-section", binding?.classes.root)}>
|
|
283
|
+
<div className="nuvler-migrated-contact-form-copy">{value(props, "eyebrow") && <span>{value(props, "eyebrow")}</span>}<h2>{value(props, "title") || "Fale com nossa equipe"}</h2>{value(props, "description") && <p>{value(props, "description")}</p>}</div>
|
|
284
|
+
<form className="nuvler-migrated-contact-form" onSubmit={(event) => void submit(event)}>{fields.map((field) => {
|
|
285
|
+
const key = value(field, "key"); const type = value(field, "type") || "text"; const label = value(field, "label") || key; const required = field.required === true;
|
|
286
|
+
if (!key) return null;
|
|
287
|
+
if (type === "checkbox") return <label className="nuvler-migrated-form-wide nuvler-migrated-checkbox" key={key}><input name={key} required={required} type="checkbox" value="true" /><span>{label}</span></label>;
|
|
288
|
+
if (type === "select") { const options = Array.isArray(field.options) ? field.options.map(record).filter((item): item is Record<string, unknown> => Boolean(item)) : []; return <label key={key}><span>{label}</span><select name={key} required={required}>{options.map((option) => <option key={value(option, "value")} value={value(option, "value")}>{value(option, "label") || value(option, "value")}</option>)}</select></label>; }
|
|
289
|
+
return <label className={type === "textarea" ? "nuvler-migrated-form-wide" : ""} key={key}><span>{label}</span>{type === "textarea" ? <textarea name={key} placeholder={value(field, "placeholder")} required={required} rows={5} /> : <input name={key} placeholder={value(field, "placeholder")} required={required} type={["email", "tel", "url", "number"].includes(type) ? type : "text"} />}</label>;
|
|
290
|
+
})}<div className="nuvler-migrated-form-wide"><button className="nuvler-migrated-action" disabled={status === "sending"} type="submit">{status === "sending" ? "Enviando…" : value(props, "submitLabel") || "Enviar contato"}</button>{status === "success" && <p role="status">{value(props, "successMessage") || "Contato enviado com sucesso."}</p>}{status === "error" && <p role="alert">{error}</p>}</div></form>
|
|
291
|
+
</section>;
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
function Banners({ section, binding }: { section: ThemeHomeSection; binding?: Binding }) {
|
|
295
|
+
const banners = Array.isArray(section.data.banners)
|
|
296
|
+
? section.data.banners.map(record).filter((item): item is Record<string, unknown> => Boolean(item))
|
|
297
|
+
: [];
|
|
298
|
+
const configured = banners.map((banner) => ({ banner, image: media(banner) })).filter(({ image }) => Boolean(image));
|
|
299
|
+
if (!configured.length) return null;
|
|
300
|
+
return <section className={cx("nuvler-migrated-banners", binding?.classes.root)}>
|
|
301
|
+
{configured.map(({ banner, image }, index) => <article className={cx("nuvler-migrated-banner", binding?.classes.card)} key={value(banner, "id") || index}>
|
|
302
|
+
<img className={cx("nuvler-migrated-banner-media", binding?.classes.media)} src={image!.url} alt={image!.alt || value(banner, "title")} />
|
|
303
|
+
<div className={cx("nuvler-migrated-banner-content", binding?.classes.content)}>
|
|
304
|
+
{value(banner, "title") && <h2 className={binding?.classes.title}>{value(banner, "title")}</h2>}
|
|
305
|
+
{value(banner, "description") && <p className={binding?.classes.text}>{value(banner, "description")}</p>}
|
|
306
|
+
{value(banner, "buttonLabel") && value(banner, "buttonUrl") && <a className={cx("nuvler-migrated-action", binding?.classes.action)} href={value(banner, "buttonUrl")}>{value(banner, "buttonLabel")}</a>}
|
|
307
|
+
</div>
|
|
308
|
+
</article>)}
|
|
309
|
+
</section>;
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
function Products({ section, binding, products, site }: { section: ThemeHomeSection; binding?: Binding; products: HomeProps["products"]; site: HomeProps["site"] }) {
|
|
313
|
+
const category = value(section.data, "categorySlug");
|
|
314
|
+
const visible = products.filter((product) => !category || product.categories.some((item) => item.slug === category) || product.categoryPath?.includes(category)).slice(0, limit(section.data));
|
|
315
|
+
if (!visible.length) return null;
|
|
316
|
+
return <section className={cx("nuvler-migrated-section", binding?.classes.root)}>
|
|
317
|
+
{heading(section, binding)}
|
|
318
|
+
<div className={binding?.classes.grid}><ProductGrid products={visible} columns={site.settings?.catalog?.desktopColumns || 3} showCategory={site.settings?.catalog?.showCategory} showDescription={site.settings?.catalog?.showDescription} /></div>
|
|
319
|
+
</section>;
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
function EditorialCards({ section, binding, items, basePath }: { section: ThemeHomeSection; binding?: Binding; items: ThemeEditorialItem[]; basePath: string }) {
|
|
323
|
+
const visible = items.slice(0, limit(section.data));
|
|
324
|
+
if (!visible.length) return null;
|
|
325
|
+
return <section className={cx("nuvler-migrated-section", binding?.classes.root)}>
|
|
326
|
+
{heading(section, binding)}
|
|
327
|
+
<div className={cx("nuvler-migrated-editorial-grid", binding?.classes.grid)}>{visible.map((item) => {
|
|
328
|
+
const image = item.image ?? item.thumbnail ?? item.coverImage;
|
|
329
|
+
return <article className={cx("nuvler-migrated-editorial-card", binding?.classes.card)} key={item.slug}>
|
|
330
|
+
{image?.url && <a className={binding?.classes.media} href={\`\${basePath}/\${item.slug}\`}><img src={image.url} alt={image.alt || item.title} /></a>}
|
|
331
|
+
<div className={binding?.classes.content}><h3 className={binding?.classes.title}><a href={\`\${basePath}/\${item.slug}\`}>{item.title}</a></h3>{item.description && <p className={binding?.classes.text}>{item.description}</p>}</div>
|
|
332
|
+
</article>;
|
|
333
|
+
})}</div>
|
|
334
|
+
</section>;
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
function ConfiguredSection({ section, binding, products, posts, services, cases, site, submitContact }: { section: ThemeHomeSection; binding?: Binding } & Pick<HomeProps, "products" | "posts" | "services" | "cases" | "site" | "submitContact">) {
|
|
338
|
+
if (section.type === "theme-component") return <ThemeComponent section={section} binding={binding} submitContact={submitContact} />;
|
|
339
|
+
if (section.type === "banner-carousel") return <Banners section={section} binding={binding} />;
|
|
340
|
+
if (section.type === "products-grid" || section.type === "products-carousel") return <Products section={section} binding={binding} products={products} site={site} />;
|
|
341
|
+
if (section.type === "services-grid") return <EditorialCards section={section} binding={binding} items={services} basePath="/servicos" />;
|
|
342
|
+
if (section.type === "blog-grid") return <EditorialCards section={section} binding={binding} items={posts} basePath="/blog" />;
|
|
343
|
+
if (section.type === "cases-grid") return <EditorialCards section={section} binding={binding} items={cases} basePath="/cases" />;
|
|
344
|
+
return <TextSection section={section} binding={binding} />;
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
export function Home({ sections, products, posts, services, cases, site, submitContact }: HomeProps) {
|
|
153
348
|
const enabled = sections.filter((item) => item.enabled).sort((left, right) => left.order - right.order);
|
|
154
|
-
const heroSection = enabled.find((item) => item.type === "hero" || item.type === "banner-carousel");
|
|
155
|
-
const productSection = enabled.find((item) => item.type === "products-grid" || item.type === "products-carousel");
|
|
156
|
-
const name = site.settings?.siteName || site.tenant.name;
|
|
157
|
-
const action = template.primaryAction(site.modules);
|
|
158
349
|
return <main className=${classes("nuvler-migrated-home", home.root)}>
|
|
159
|
-
<section
|
|
160
|
-
<div className=${classes("nuvler-migrated-hero-content", hero.content)}>
|
|
161
|
-
<span>{${JSON.stringify(heroText)}}</span>
|
|
162
|
-
<h1 className=${classes("nuvler-migrated-hero-title", hero.title)}>{value(heroSection, "title") || name}</h1>
|
|
163
|
-
<p className=${classes("nuvler-migrated-copy", hero.text)}>{value(heroSection, "description") || site.settings?.description || "Conheça nossos produtos e soluções."}</p>
|
|
164
|
-
<a className=${classes("nuvler-migrated-action", hero.action)} href={value(heroSection, "buttonUrl") || action.href}>{value(heroSection, "buttonLabel") || action.label}</a>
|
|
165
|
-
</div>
|
|
166
|
-
{migratedHeroAsset && <div className=${classes("nuvler-migrated-hero-media", hero.media)}><img src={migratedHeroAsset} alt="" /></div>}
|
|
167
|
-
</section>
|
|
168
|
-
{site.modules.includes("PRODUCTS") && <section className=${classes("nuvler-migrated-section", section.root)}>
|
|
169
|
-
<header><span>Destaques</span><h2 className=${classes("nuvler-migrated-section-title", section.title)}>{value(productSection, "title") || "Produtos em destaque"}</h2></header>
|
|
170
|
-
<ProductGrid products={products} columns={site.settings?.catalog?.desktopColumns || 3} showCategory={site.settings?.catalog?.showCategory} showDescription={site.settings?.catalog?.showDescription} />
|
|
171
|
-
</section>}
|
|
172
|
-
{enabled.filter((item) => ["image-text", "rich-text", "cta"].includes(item.type)).map((item) => <section className=${classes("nuvler-migrated-section nuvler-migrated-generic", section.content)} key={item.id || \`\${item.type}-\${item.order}\`}><h2>{value(item, "title")}</h2><p>{value(item, "description") || value(item, "content")}</p>{value(item, "buttonUrl") && <a className="nuvler-migrated-action" href={value(item, "buttonUrl")}>{value(item, "buttonLabel") || "Saiba mais"}</a>}</section>)}
|
|
350
|
+
{enabled.map((item, index) => <ConfiguredSection section={item} binding={bindingFor(item, index, enabled)} products={products} posts={posts} services={services} cases={cases} site={site} submitContact={submitContact} key={item.id || \`\${item.type}-\${item.order}\`} />)}
|
|
173
351
|
</main>;
|
|
174
352
|
}
|
|
175
353
|
`;
|
|
176
354
|
}
|
|
355
|
+
function migratedContentSource(plan) {
|
|
356
|
+
const metadata = plan.contentBindings.map(({ id, type, order, componentKey }) => ({ id, type, order, componentKey }));
|
|
357
|
+
return `import { createContext, useContext, type FormEvent, type ReactNode } from "react";
|
|
358
|
+
import type { HomeProps, ThemeHomeSection } from "@nuvler/theme-sdk";
|
|
359
|
+
|
|
360
|
+
const MigratedContentContext = createContext<HomeProps | null>(null);
|
|
361
|
+
const bindingMetadata: ReadonlyArray<{ id: string; type: ThemeHomeSection["type"]; order: number; componentKey?: string }> = ${JSON.stringify(metadata, null, 2)};
|
|
362
|
+
|
|
363
|
+
export function MigratedContentProvider({ children, ...props }: HomeProps & { children: ReactNode }) {
|
|
364
|
+
return <MigratedContentContext.Provider value={props}>{children}</MigratedContentContext.Provider>;
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
function configuredSection(id: string, sections: ThemeHomeSection[]): ThemeHomeSection | undefined {
|
|
368
|
+
const exact = sections.find((section) => section.id === id);
|
|
369
|
+
if (exact) return exact;
|
|
370
|
+
const binding = bindingMetadata.find((candidate) => candidate.id === id);
|
|
371
|
+
if (!binding) return undefined;
|
|
372
|
+
if (binding.type === "theme-component" && binding.componentKey) {
|
|
373
|
+
const custom = sections.find((section) => section.enabled
|
|
374
|
+
&& section.type === "theme-component"
|
|
375
|
+
&& section.data.componentKey === binding.componentKey);
|
|
376
|
+
if (custom) return custom;
|
|
377
|
+
}
|
|
378
|
+
const occurrence = bindingMetadata.filter((candidate) => candidate.type === binding.type && candidate.order < binding.order).length;
|
|
379
|
+
return sections.filter((section) => section.enabled && section.type === binding.type).sort((left, right) => left.order - right.order)[occurrence];
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
export function useMigratedSection(id: string): Record<string, unknown> {
|
|
383
|
+
const context = useContext(MigratedContentContext);
|
|
384
|
+
if (!context) return {};
|
|
385
|
+
if (id === "__header" || id === "__footer") {
|
|
386
|
+
const name = context.site.settings?.siteName || context.site.tenant.name;
|
|
387
|
+
return {
|
|
388
|
+
title: name,
|
|
389
|
+
description: context.site.settings?.description || "",
|
|
390
|
+
image: context.site.settings?.logo || null,
|
|
391
|
+
imageUrl: context.site.settings?.logo?.url || "",
|
|
392
|
+
imageAlt: context.site.settings?.logo?.alt || name,
|
|
393
|
+
buttonLabel: "",
|
|
394
|
+
buttonUrl: "",
|
|
395
|
+
};
|
|
396
|
+
}
|
|
397
|
+
const section = configuredSection(id, context.sections);
|
|
398
|
+
if (!section) return {};
|
|
399
|
+
if (section.type === "theme-component") {
|
|
400
|
+
const props = section.data.props;
|
|
401
|
+
return props && typeof props === "object" && !Array.isArray(props)
|
|
402
|
+
? props as Record<string, unknown>
|
|
403
|
+
: {};
|
|
404
|
+
}
|
|
405
|
+
return section.data;
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
export function useMigratedContactForm(id: string) {
|
|
409
|
+
const context = useContext(MigratedContentContext);
|
|
410
|
+
return async (event: FormEvent<HTMLFormElement>): Promise<void> => {
|
|
411
|
+
event.preventDefault();
|
|
412
|
+
const element = event.currentTarget;
|
|
413
|
+
if (!context?.submitContact) {
|
|
414
|
+
element.dataset.nuvlerStatus = "unavailable";
|
|
415
|
+
element.dispatchEvent(new CustomEvent("nuvler:contact-error", { detail: { message: "Envio de contatos indisponível." } }));
|
|
416
|
+
return;
|
|
417
|
+
}
|
|
418
|
+
const section = configuredSection(id, context.sections);
|
|
419
|
+
const form = new FormData(element);
|
|
420
|
+
const values: Record<string, string | boolean | string[]> = {};
|
|
421
|
+
const configuredFields = section?.type === "theme-component" && section.data.props && typeof section.data.props === "object" && !Array.isArray(section.data.props)
|
|
422
|
+
? migratedItems(section.data.props as Record<string, unknown>, "fields")
|
|
423
|
+
: [];
|
|
424
|
+
for (const field of configuredFields) {
|
|
425
|
+
const key = stringValue(field, "key");
|
|
426
|
+
if (key && stringValue(field, "type") === "checkbox") values[key] = form.has(key);
|
|
427
|
+
}
|
|
428
|
+
for (const key of new Set([...form.keys()])) {
|
|
429
|
+
const entries = form.getAll(key).filter((value): value is string => typeof value === "string");
|
|
430
|
+
values[key] = entries.length > 1 ? entries : entries[0] ?? "";
|
|
431
|
+
}
|
|
432
|
+
element.dataset.nuvlerStatus = "sending";
|
|
433
|
+
try {
|
|
434
|
+
const result = await context.submitContact({
|
|
435
|
+
formKey: section?.type === "theme-component" && typeof section.data.componentKey === "string" ? section.data.componentKey : "contact-form",
|
|
436
|
+
sectionId: section?.id,
|
|
437
|
+
values,
|
|
438
|
+
pathname: typeof window === "undefined" ? undefined : window.location.pathname,
|
|
439
|
+
});
|
|
440
|
+
element.reset();
|
|
441
|
+
element.dataset.nuvlerStatus = "success";
|
|
442
|
+
element.dispatchEvent(new CustomEvent("nuvler:contact-success", { detail: result }));
|
|
443
|
+
} catch (cause) {
|
|
444
|
+
const message = cause instanceof Error ? cause.message : "Não foi possível enviar o contato.";
|
|
445
|
+
element.dataset.nuvlerStatus = "error";
|
|
446
|
+
element.dispatchEvent(new CustomEvent("nuvler:contact-error", { detail: { message } }));
|
|
447
|
+
}
|
|
448
|
+
};
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
export function migratedItems(data: Record<string, unknown>, field = "items"): Record<string, unknown>[] {
|
|
452
|
+
const value = data[field];
|
|
453
|
+
return Array.isArray(value)
|
|
454
|
+
? value.filter((item): item is Record<string, unknown> => Boolean(item) && typeof item === "object" && !Array.isArray(item))
|
|
455
|
+
: [];
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
export function MigratedContactFields({ data }: { data: Record<string, unknown> }) {
|
|
459
|
+
const configured = migratedItems(data, "fields");
|
|
460
|
+
const fields = configured.length ? configured : [
|
|
461
|
+
{ key: "name", label: "Nome", type: "text", required: true },
|
|
462
|
+
{ key: "email", label: "E-mail", type: "email", required: true },
|
|
463
|
+
{ key: "phone", label: "Telefone", type: "tel", required: false },
|
|
464
|
+
{ key: "message", label: "Mensagem", type: "textarea", required: true },
|
|
465
|
+
];
|
|
466
|
+
return <>
|
|
467
|
+
{fields.map((field) => {
|
|
468
|
+
const key = stringValue(field, "key");
|
|
469
|
+
const type = stringValue(field, "type") || "text";
|
|
470
|
+
if (!key) return null;
|
|
471
|
+
if (type === "checkbox") return <label className="nuvler-migrated-form-wide nuvler-migrated-checkbox" data-field-key={key} key={key}>
|
|
472
|
+
<input name={key} required={field.required === true} type="checkbox" value="true" />
|
|
473
|
+
<span>{stringValue(field, "label") || key}{field.required === true ? " *" : ""}</span>
|
|
474
|
+
</label>;
|
|
475
|
+
if (type === "select") return <label data-field-key={key} key={key}>
|
|
476
|
+
<span>{stringValue(field, "label") || key}{field.required === true ? " *" : ""}</span>
|
|
477
|
+
<select name={key} required={field.required === true}>{migratedItems(field, "options").map((option) => <option key={stringValue(option, "value")} value={stringValue(option, "value")}>{stringValue(option, "label") || stringValue(option, "value")}</option>)}</select>
|
|
478
|
+
</label>;
|
|
479
|
+
return <label data-field-key={key} key={key}>
|
|
480
|
+
<span>{stringValue(field, "label") || key}{field.required === true ? " *" : ""}</span>
|
|
481
|
+
{type === "textarea"
|
|
482
|
+
? <textarea name={key} placeholder={stringValue(field, "placeholder")} required={field.required === true} rows={5} />
|
|
483
|
+
: <input name={key} placeholder={stringValue(field, "placeholder")} required={field.required === true} type={["email", "tel", "url", "number"].includes(type) ? type : "text"} />}
|
|
484
|
+
</label>;
|
|
485
|
+
})}
|
|
486
|
+
<button type="submit">{stringValue(data, "submitLabel") || "Enviar contato"}</button>
|
|
487
|
+
</>;
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
function stringValue(data: Record<string, unknown>, key: string): string {
|
|
491
|
+
const candidate = data[key];
|
|
492
|
+
return typeof candidate === "string" ? candidate : "";
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
export function migratedText(data: Record<string, unknown>, field: string): string {
|
|
496
|
+
if (field === "description") return stringValue(data, "description") || stringValue(data, "text") || stringValue(data, "content");
|
|
497
|
+
return stringValue(data, field);
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
export function migratedImage(data: Record<string, unknown>): string | undefined {
|
|
501
|
+
const image = data.image && typeof data.image === "object" && !Array.isArray(data.image)
|
|
502
|
+
? data.image as Record<string, unknown>
|
|
503
|
+
: null;
|
|
504
|
+
return (image ? stringValue(image, "url") : "") || stringValue(data, "imageUrl") || stringValue(data, "posterImageUrl") || undefined;
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
export function migratedVideo(data: Record<string, unknown>): string | undefined {
|
|
508
|
+
return stringValue(data, "videoUrl") || undefined;
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
export function migratedLink(data: Record<string, unknown>): string | undefined {
|
|
512
|
+
return stringValue(data, "buttonUrl") || undefined;
|
|
513
|
+
}
|
|
514
|
+
`;
|
|
515
|
+
}
|
|
516
|
+
function migratedNextImageSource() {
|
|
517
|
+
return `import type { CSSProperties, ImgHTMLAttributes } from "react";
|
|
518
|
+
|
|
519
|
+
type StaticImage = { src: string; width?: number; height?: number };
|
|
520
|
+
type MigratedNextImageProps = Omit<ImgHTMLAttributes<HTMLImageElement>, "src"> & {
|
|
521
|
+
src: string | StaticImage;
|
|
522
|
+
alt: string;
|
|
523
|
+
fill?: boolean;
|
|
524
|
+
priority?: boolean;
|
|
525
|
+
quality?: number;
|
|
526
|
+
placeholder?: string;
|
|
527
|
+
blurDataURL?: string;
|
|
528
|
+
onLoadingComplete?: (image: HTMLImageElement) => void;
|
|
529
|
+
};
|
|
530
|
+
|
|
531
|
+
/** Adaptador browser-safe para projetos Next.js executados no preview Vite. */
|
|
532
|
+
export default function MigratedNextImage({
|
|
533
|
+
src, alt, fill, priority, quality: _quality, placeholder: _placeholder,
|
|
534
|
+
blurDataURL: _blurDataURL, onLoadingComplete, style, ...props
|
|
535
|
+
}: MigratedNextImageProps) {
|
|
536
|
+
const url = typeof src === "string" ? src : src?.src;
|
|
537
|
+
if (!url) return null;
|
|
538
|
+
const fillStyle: CSSProperties | undefined = fill
|
|
539
|
+
? { position: "absolute", inset: 0, width: "100%", height: "100%", ...style }
|
|
540
|
+
: style;
|
|
541
|
+
return <img
|
|
542
|
+
{...props}
|
|
543
|
+
src={url}
|
|
544
|
+
alt={alt || ""}
|
|
545
|
+
loading={priority ? "eager" : props.loading}
|
|
546
|
+
style={fillStyle}
|
|
547
|
+
onLoad={onLoadingComplete ? (event) => onLoadingComplete(event.currentTarget) : props.onLoad}
|
|
548
|
+
/>;
|
|
549
|
+
}
|
|
550
|
+
`;
|
|
551
|
+
}
|
|
177
552
|
function definitionSource(plan) {
|
|
178
553
|
const tokens = plan.tokens;
|
|
554
|
+
const fallbackSections = plan.contentBindings.map((binding) => ({
|
|
555
|
+
id: binding.id,
|
|
556
|
+
type: binding.type,
|
|
557
|
+
enabled: true,
|
|
558
|
+
order: binding.order,
|
|
559
|
+
data: blankBindingData(binding),
|
|
560
|
+
}));
|
|
179
561
|
return `import manifestData from "../nuvler.theme.json" with { type: "json" };
|
|
180
562
|
import { defineTheme, type ThemeHomeSection, type ThemeManifest } from "@nuvler/theme-sdk";
|
|
181
563
|
import { Footer } from "./components/Footer.js";
|
|
@@ -184,9 +566,7 @@ import { ProductDetail } from "./components/ProductDetail.js";
|
|
|
184
566
|
import { ProductGrid } from "./components/ProductGrid.js";
|
|
185
567
|
import { Home } from "./sections/Home.js";
|
|
186
568
|
|
|
187
|
-
|
|
188
|
-
return { id, type, enabled: true, order, data: {} };
|
|
189
|
-
}
|
|
569
|
+
const migratedSections: ThemeHomeSection[] = ${JSON.stringify(fallbackSections, null, 2)};
|
|
190
570
|
|
|
191
571
|
export const manifest = manifestData as ThemeManifest;
|
|
192
572
|
export const themeDefinition = defineTheme({
|
|
@@ -203,13 +583,13 @@ export const themeDefinition = defineTheme({
|
|
|
203
583
|
layout: ${JSON.stringify({ containerWidth: tokens.containerWidth, borderRadius: tokens.borderRadius })},
|
|
204
584
|
},
|
|
205
585
|
template: {
|
|
206
|
-
announcement:
|
|
207
|
-
footerTagline: "
|
|
586
|
+
announcement: "",
|
|
587
|
+
footerTagline: "",
|
|
208
588
|
footerNavigationLabel: "Navegação",
|
|
209
|
-
footerNote:
|
|
589
|
+
footerNote: "",
|
|
210
590
|
socialLabel: "Redes sociais",
|
|
211
591
|
benefits: [],
|
|
212
|
-
fallbackSections: () =>
|
|
592
|
+
fallbackSections: () => migratedSections.map((section) => ({ ...section, data: { ...section.data } })),
|
|
213
593
|
primaryAction: (modules) => modules.includes("PRODUCTS") ? { label: "Ver produtos", href: "/produtos" } : { label: "Saiba mais", href: "/" },
|
|
214
594
|
},
|
|
215
595
|
components: { Header, Footer, Home, ProductGrid, ProductDetail },
|
|
@@ -258,7 +638,7 @@ function statePageSource() {
|
|
|
258
638
|
}
|
|
259
639
|
`;
|
|
260
640
|
}
|
|
261
|
-
function themeSource() {
|
|
641
|
+
function themeSource(hasFidelityHome) {
|
|
262
642
|
return `import type { CSSProperties } from "react";
|
|
263
643
|
import type { NuvlerThemeProps, ThemeSite } from "@nuvler/theme-sdk";
|
|
264
644
|
import { themeDefinition } from "./definition.js";
|
|
@@ -297,16 +677,916 @@ export default function Theme({ context, route = { type: "home" }, sdk }: Nuvler
|
|
|
297
677
|
"--theme-radius": \`\${tokens.layout.borderRadius}px\`,
|
|
298
678
|
"--theme-container": \`\${tokens.layout.containerWidth}px\`,
|
|
299
679
|
} as CSSProperties;
|
|
680
|
+
const homeSections = context.home.content.sections.length
|
|
681
|
+
? context.home.content.sections
|
|
682
|
+
: themeDefinition.template.fallbackSections();
|
|
300
683
|
let content;
|
|
301
|
-
if (route.type === "home") content = <Home sections={
|
|
684
|
+
if (route.type === "home") content = <Home sections={homeSections} 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} />;
|
|
302
685
|
else if (route.type === "catalog") content = <CatalogPage route={route} site={site} />;
|
|
303
686
|
else if (route.type === "product") content = <ProductPage route={route} site={site} cart={sdk?.cart} />;
|
|
304
687
|
else if (route.type === "editorial-list" || route.type === "editorial-detail") content = <EditorialPage route={route} />;
|
|
305
688
|
else content = <StatePage title={route.type === "loading" ? "Carregando…" : route.type === "page" ? route.title : "Conteúdo não encontrado"} pathname={"pathname" in route ? route.pathname : undefined} />;
|
|
689
|
+
if (${JSON.stringify(hasFidelityHome)} && route.type === "home") {
|
|
690
|
+
return <div className="nuvler-migrated-theme nuvler-migrated-fidelity" style={style}>{content}</div>;
|
|
691
|
+
}
|
|
306
692
|
return <div className="nuvler-migrated-theme" style={style}><Header site={site} categories={context.navigation.categories} pages={context.navigation.pages} template={themeDefinition.template} /><div className="nuvler-migrated-page">{content}</div><Footer site={site} pages={context.navigation.pages} template={themeDefinition.template} /></div>;
|
|
307
693
|
}
|
|
308
694
|
`;
|
|
309
695
|
}
|
|
696
|
+
function blankSectionData(type) {
|
|
697
|
+
if (type === "banner-carousel")
|
|
698
|
+
return { banners: [], autoplay: true };
|
|
699
|
+
if (type === "hero")
|
|
700
|
+
return { eyebrow: "", title: "", description: "", imageId: "", imageUrl: "", imageAlt: "", buttonLabel: "", buttonUrl: "" };
|
|
701
|
+
if (type === "image-text")
|
|
702
|
+
return { eyebrow: "", title: "", description: "", imageId: "", imageUrl: "", imageAlt: "", imagePosition: "left" };
|
|
703
|
+
if (type === "rich-text")
|
|
704
|
+
return { eyebrow: "", title: "", text: "" };
|
|
705
|
+
if (type === "cta")
|
|
706
|
+
return { eyebrow: "", title: "", description: "", buttonLabel: "", buttonUrl: "" };
|
|
707
|
+
if (type === "products-grid" || type === "products-carousel")
|
|
708
|
+
return { eyebrow: "", title: "", limit: 6, categorySlug: "" };
|
|
709
|
+
if (type === "theme-component")
|
|
710
|
+
return { componentKey: "custom-component", schemaVersion: 1, props: {} };
|
|
711
|
+
return { eyebrow: "", title: "", limit: 6 };
|
|
712
|
+
}
|
|
713
|
+
function blankBindingData(binding) {
|
|
714
|
+
if (binding.type !== "theme-component" || !binding.componentDefinition || !binding.componentKey) {
|
|
715
|
+
return blankSectionData(binding.type);
|
|
716
|
+
}
|
|
717
|
+
const props = {};
|
|
718
|
+
for (const field of binding.componentDefinition.fields) {
|
|
719
|
+
if (field.defaultValue !== undefined)
|
|
720
|
+
props[field.key] = field.defaultValue;
|
|
721
|
+
else if (field.control === "repeater")
|
|
722
|
+
props[field.key] = [];
|
|
723
|
+
else if (field.control === "contact-fields")
|
|
724
|
+
props[field.key] = [
|
|
725
|
+
{ key: "name", label: "Nome", type: "text", required: true },
|
|
726
|
+
{ key: "email", label: "E-mail", type: "email", required: true },
|
|
727
|
+
{ key: "phone", label: "Telefone", type: "tel", required: false },
|
|
728
|
+
{ key: "message", label: "Mensagem", type: "textarea", required: true },
|
|
729
|
+
];
|
|
730
|
+
else if (field.control === "boolean")
|
|
731
|
+
props[field.key] = false;
|
|
732
|
+
else if (field.control === "number")
|
|
733
|
+
props[field.key] = field.min ?? 0;
|
|
734
|
+
else
|
|
735
|
+
props[field.key] = "";
|
|
736
|
+
}
|
|
737
|
+
return {
|
|
738
|
+
componentKey: binding.componentKey,
|
|
739
|
+
schemaVersion: binding.componentDefinition.schemaVersion,
|
|
740
|
+
props,
|
|
741
|
+
};
|
|
742
|
+
}
|
|
743
|
+
/** Mirrors the labels shown by the Gestão Home builder. */
|
|
744
|
+
const PANEL_SECTION_DEFINITIONS = {
|
|
745
|
+
hero: {
|
|
746
|
+
name: "Banner principal",
|
|
747
|
+
category: "Destaques",
|
|
748
|
+
description: "Uma abertura marcante com imagem, texto e botão.",
|
|
749
|
+
controls: [
|
|
750
|
+
{ label: "Imagem do banner principal", fields: ["imageId", "imageUrl", "imageAlt"], note: "Ao escolher a imagem, URL e texto alternativo são preenchidos pelo painel." },
|
|
751
|
+
{ label: "Chamada pequena", fields: ["eyebrow"] },
|
|
752
|
+
{ label: "Título da seção", fields: ["title"] },
|
|
753
|
+
{ label: "Descrição", fields: ["description"] },
|
|
754
|
+
{ label: "Texto do botão", fields: ["buttonLabel"] },
|
|
755
|
+
{ label: "Destino do botão", fields: ["buttonUrl"] },
|
|
756
|
+
],
|
|
757
|
+
},
|
|
758
|
+
"banner-carousel": {
|
|
759
|
+
name: "Carrossel de banners",
|
|
760
|
+
category: "Destaques",
|
|
761
|
+
description: "Vários destaques alternando no topo da página.",
|
|
762
|
+
controls: [
|
|
763
|
+
{ label: "Troca automática", fields: ["autoplay"] },
|
|
764
|
+
{ label: "Banner 1, Banner 2…", fields: ["banners"], note: "Em cada banner: Imagem, Título, Descrição, Texto do botão e Destino do botão." },
|
|
765
|
+
],
|
|
766
|
+
},
|
|
767
|
+
"image-text": {
|
|
768
|
+
name: "Imagem e texto",
|
|
769
|
+
category: "Conteúdo",
|
|
770
|
+
description: "Apresente uma história com conteúdo lado a lado.",
|
|
771
|
+
controls: [
|
|
772
|
+
{ label: "Imagem da seção", fields: ["imageId", "imageUrl", "imageAlt"], note: "Ao escolher a imagem, URL e texto alternativo são preenchidos pelo painel." },
|
|
773
|
+
{ label: "Chamada pequena", fields: ["eyebrow"] },
|
|
774
|
+
{ label: "Título da seção", fields: ["title"] },
|
|
775
|
+
{ label: "Texto", fields: ["description"] },
|
|
776
|
+
{ label: "Posição da imagem", fields: ["imagePosition"] },
|
|
777
|
+
],
|
|
778
|
+
},
|
|
779
|
+
"rich-text": {
|
|
780
|
+
name: "Bloco de texto",
|
|
781
|
+
category: "Conteúdo",
|
|
782
|
+
description: "Um título e texto livre para explicar o que quiser.",
|
|
783
|
+
controls: [
|
|
784
|
+
{ label: "Chamada pequena", fields: ["eyebrow"] },
|
|
785
|
+
{ label: "Título da seção", fields: ["title"] },
|
|
786
|
+
{ label: "Conteúdo", fields: ["text"] },
|
|
787
|
+
],
|
|
788
|
+
},
|
|
789
|
+
cta: {
|
|
790
|
+
name: "Chamada para ação",
|
|
791
|
+
category: "Conteúdo",
|
|
792
|
+
description: "Convide a pessoa a dar o próximo passo.",
|
|
793
|
+
controls: [
|
|
794
|
+
{ label: "Chamada pequena", fields: ["eyebrow"] },
|
|
795
|
+
{ label: "Título da seção", fields: ["title"] },
|
|
796
|
+
{ label: "Descrição", fields: ["description"] },
|
|
797
|
+
{ label: "Texto do botão", fields: ["buttonLabel"] },
|
|
798
|
+
{ label: "Destino do botão", fields: ["buttonUrl"] },
|
|
799
|
+
],
|
|
800
|
+
},
|
|
801
|
+
"services-grid": {
|
|
802
|
+
name: "Grade de serviços",
|
|
803
|
+
category: "Conteúdo automático",
|
|
804
|
+
description: "Mostra automaticamente os serviços cadastrados.",
|
|
805
|
+
controls: [
|
|
806
|
+
{ label: "Chamada pequena", fields: ["eyebrow"] },
|
|
807
|
+
{ label: "Título da seção", fields: ["title"] },
|
|
808
|
+
{ label: "Quantidade de itens", fields: ["limit"] },
|
|
809
|
+
],
|
|
810
|
+
contentSource: {
|
|
811
|
+
location: "Serviços → Lista de serviços",
|
|
812
|
+
description: "Os cards, textos e imagens da grade vêm dos serviços cadastrados.",
|
|
813
|
+
},
|
|
814
|
+
},
|
|
815
|
+
"blog-grid": {
|
|
816
|
+
name: "Últimos do blog",
|
|
817
|
+
category: "Conteúdo automático",
|
|
818
|
+
description: "Mantém as publicações recentes em evidência.",
|
|
819
|
+
controls: [
|
|
820
|
+
{ label: "Chamada pequena", fields: ["eyebrow"] },
|
|
821
|
+
{ label: "Título da seção", fields: ["title"] },
|
|
822
|
+
{ label: "Quantidade de itens", fields: ["limit"] },
|
|
823
|
+
],
|
|
824
|
+
contentSource: {
|
|
825
|
+
location: "Blog → Postagens",
|
|
826
|
+
description: "Os cards, textos e imagens da grade vêm das postagens publicadas.",
|
|
827
|
+
},
|
|
828
|
+
},
|
|
829
|
+
"cases-grid": {
|
|
830
|
+
name: "Cases de sucesso",
|
|
831
|
+
category: "Conteúdo automático",
|
|
832
|
+
description: "Exibe projetos e resultados já cadastrados.",
|
|
833
|
+
controls: [
|
|
834
|
+
{ label: "Chamada pequena", fields: ["eyebrow"] },
|
|
835
|
+
{ label: "Título da seção", fields: ["title"] },
|
|
836
|
+
{ label: "Quantidade de itens", fields: ["limit"] },
|
|
837
|
+
],
|
|
838
|
+
contentSource: {
|
|
839
|
+
location: "Cases → Cases",
|
|
840
|
+
description: "Os cards, textos e imagens da grade vêm dos cases publicados.",
|
|
841
|
+
},
|
|
842
|
+
},
|
|
843
|
+
"products-grid": {
|
|
844
|
+
name: "Grade de produtos",
|
|
845
|
+
category: "Conteúdo automático",
|
|
846
|
+
description: "Uma vitrine organizada de produtos cadastrados.",
|
|
847
|
+
controls: [
|
|
848
|
+
{ label: "Chamada pequena", fields: ["eyebrow"] },
|
|
849
|
+
{ label: "Título da seção", fields: ["title"] },
|
|
850
|
+
{ label: "Quantidade de itens", fields: ["limit"] },
|
|
851
|
+
{ label: "Categoria de produtos", fields: ["categorySlug"] },
|
|
852
|
+
],
|
|
853
|
+
contentSource: {
|
|
854
|
+
location: "Produtos → Produtos",
|
|
855
|
+
description: "Os cards, textos e imagens da grade vêm dos produtos cadastrados.",
|
|
856
|
+
},
|
|
857
|
+
},
|
|
858
|
+
"products-carousel": {
|
|
859
|
+
name: "Carrossel de produtos",
|
|
860
|
+
category: "Conteúdo automático",
|
|
861
|
+
description: "Uma vitrine compacta para navegar pelos produtos.",
|
|
862
|
+
controls: [
|
|
863
|
+
{ label: "Chamada pequena", fields: ["eyebrow"] },
|
|
864
|
+
{ label: "Título da seção", fields: ["title"] },
|
|
865
|
+
{ label: "Quantidade de itens", fields: ["limit"] },
|
|
866
|
+
{ label: "Categoria de produtos", fields: ["categorySlug"] },
|
|
867
|
+
],
|
|
868
|
+
contentSource: {
|
|
869
|
+
location: "Produtos → Produtos",
|
|
870
|
+
description: "Os cards, textos e imagens do carrossel vêm dos produtos cadastrados.",
|
|
871
|
+
},
|
|
872
|
+
},
|
|
873
|
+
"theme-component": {
|
|
874
|
+
name: "Componente do tema",
|
|
875
|
+
category: "Conteúdo",
|
|
876
|
+
description: "Componente configurável declarado pelo tema ativo.",
|
|
877
|
+
controls: [],
|
|
878
|
+
},
|
|
879
|
+
};
|
|
880
|
+
function panelDefinition(binding) {
|
|
881
|
+
const custom = binding.componentDefinition;
|
|
882
|
+
if (!custom)
|
|
883
|
+
return PANEL_SECTION_DEFINITIONS[binding.type];
|
|
884
|
+
return {
|
|
885
|
+
name: custom.name,
|
|
886
|
+
category: custom.category,
|
|
887
|
+
description: custom.description,
|
|
888
|
+
controls: custom.fields.map((field) => ({
|
|
889
|
+
label: field.label,
|
|
890
|
+
fields: [field.key],
|
|
891
|
+
note: field.control === "repeater"
|
|
892
|
+
? "Lista repetível controlada pelo cliente no Gestão."
|
|
893
|
+
: field.control === "contact-fields"
|
|
894
|
+
? "Permite escolher, ordenar e tornar obrigatórios os campos do formulário."
|
|
895
|
+
: undefined,
|
|
896
|
+
})),
|
|
897
|
+
};
|
|
898
|
+
}
|
|
899
|
+
function panelCompatibility(binding) {
|
|
900
|
+
if (binding.type === "theme-component") {
|
|
901
|
+
return {
|
|
902
|
+
level: "direct",
|
|
903
|
+
label: "Direto",
|
|
904
|
+
note: "O tema declara este componente e seus campos editáveis para o Construtor da Home.",
|
|
905
|
+
};
|
|
906
|
+
}
|
|
907
|
+
if (binding.type !== "rich-text") {
|
|
908
|
+
return {
|
|
909
|
+
level: "direct",
|
|
910
|
+
label: "Direto",
|
|
911
|
+
note: "Existe um bloco equivalente no Construtor da Home.",
|
|
912
|
+
};
|
|
913
|
+
}
|
|
914
|
+
const component = binding.component.toLowerCase();
|
|
915
|
+
if (/(video|faq|form|benefit|number|stat|metric|feature|evaluation|avali|app|forwhom|quem)/.test(component)) {
|
|
916
|
+
return {
|
|
917
|
+
level: "v1-fallback",
|
|
918
|
+
label: "Fallback V1",
|
|
919
|
+
note: "O Gestão ainda não possui um bloco nativo para esta estrutura; na V1 apenas título e texto ficam configuráveis como Bloco de texto.",
|
|
920
|
+
};
|
|
921
|
+
}
|
|
922
|
+
return {
|
|
923
|
+
level: "direct",
|
|
924
|
+
label: "Direto",
|
|
925
|
+
note: "O conteúdo textual pode ser configurado diretamente como Bloco de texto.",
|
|
926
|
+
};
|
|
927
|
+
}
|
|
928
|
+
function sourceKind(file) {
|
|
929
|
+
const extension = path.extname(file).toLowerCase();
|
|
930
|
+
if (extension === ".tsx")
|
|
931
|
+
return ts.ScriptKind.TSX;
|
|
932
|
+
if (extension === ".jsx")
|
|
933
|
+
return ts.ScriptKind.JSX;
|
|
934
|
+
if ([".js", ".mjs", ".cjs"].includes(extension))
|
|
935
|
+
return ts.ScriptKind.JS;
|
|
936
|
+
return ts.ScriptKind.TS;
|
|
937
|
+
}
|
|
938
|
+
function unwrappedExpression(expression) {
|
|
939
|
+
if (ts.isAsExpression(expression) || ts.isTypeAssertionExpression(expression) || ts.isParenthesizedExpression(expression)) {
|
|
940
|
+
return unwrappedExpression(expression.expression);
|
|
941
|
+
}
|
|
942
|
+
return expression;
|
|
943
|
+
}
|
|
944
|
+
function propertyKey(property) {
|
|
945
|
+
if (!(ts.isPropertyAssignment(property) || ts.isShorthandPropertyAssignment(property)))
|
|
946
|
+
return null;
|
|
947
|
+
const name = property.name;
|
|
948
|
+
return ts.isIdentifier(name) || ts.isStringLiteralLike(name) || ts.isNumericLiteral(name) ? name.text : null;
|
|
949
|
+
}
|
|
950
|
+
function propertyValue(object, key) {
|
|
951
|
+
const property = object.properties.find((candidate) => propertyKey(candidate) === key);
|
|
952
|
+
return property && ts.isPropertyAssignment(property) ? property.initializer : null;
|
|
953
|
+
}
|
|
954
|
+
function flattenStringObject(object, prefix = "", result = new Map()) {
|
|
955
|
+
for (const property of object.properties) {
|
|
956
|
+
if (!ts.isPropertyAssignment(property))
|
|
957
|
+
continue;
|
|
958
|
+
const key = propertyKey(property);
|
|
959
|
+
if (!key)
|
|
960
|
+
continue;
|
|
961
|
+
const compound = prefix ? `${prefix}.${key}` : key;
|
|
962
|
+
const value = unwrappedExpression(property.initializer);
|
|
963
|
+
if (ts.isStringLiteralLike(value) || ts.isNoSubstitutionTemplateLiteral(value))
|
|
964
|
+
result.set(compound, value.text);
|
|
965
|
+
else if (ts.isObjectLiteralExpression(value))
|
|
966
|
+
flattenStringObject(value, compound, result);
|
|
967
|
+
}
|
|
968
|
+
return result;
|
|
969
|
+
}
|
|
970
|
+
function translationValues(source) {
|
|
971
|
+
const result = new Map();
|
|
972
|
+
function visit(node) {
|
|
973
|
+
if (ts.isVariableDeclaration(node)
|
|
974
|
+
&& ts.isIdentifier(node.name)
|
|
975
|
+
&& /^(?:translations?|messages?|dictionary|locales?)$/i.test(node.name.text)
|
|
976
|
+
&& node.initializer) {
|
|
977
|
+
const initializer = unwrappedExpression(node.initializer);
|
|
978
|
+
if (ts.isObjectLiteralExpression(initializer)) {
|
|
979
|
+
const locale = ["pt", "pt-BR", "pt_BR", "default"]
|
|
980
|
+
.map((key) => propertyValue(initializer, key))
|
|
981
|
+
.find((value) => Boolean(value));
|
|
982
|
+
const selected = locale ? unwrappedExpression(locale) : initializer;
|
|
983
|
+
if (ts.isObjectLiteralExpression(selected)) {
|
|
984
|
+
for (const [key, value] of flattenStringObject(selected))
|
|
985
|
+
result.set(key, value);
|
|
986
|
+
}
|
|
987
|
+
}
|
|
988
|
+
}
|
|
989
|
+
ts.forEachChild(node, visit);
|
|
990
|
+
}
|
|
991
|
+
visit(source);
|
|
992
|
+
return result;
|
|
993
|
+
}
|
|
994
|
+
function contentField(key) {
|
|
995
|
+
const normalized = key.toLowerCase();
|
|
996
|
+
const last = normalized.split(".").at(-1) ?? normalized;
|
|
997
|
+
if (/^(?:eyebrow|overline|kicker)$/.test(last))
|
|
998
|
+
return "eyebrow";
|
|
999
|
+
if (/^(?:title|headline|heading)$/.test(last))
|
|
1000
|
+
return "title";
|
|
1001
|
+
if (/^(?:subtitle|subheadline|description|desc|text|content)$/.test(last))
|
|
1002
|
+
return "description";
|
|
1003
|
+
if (/(?:^|\.)(?:cta|button|action)(?:\.|$)/.test(normalized) || /^(?:cta|button|label)$/.test(last))
|
|
1004
|
+
return "buttonLabel";
|
|
1005
|
+
return undefined;
|
|
1006
|
+
}
|
|
1007
|
+
function jsxTagForText(node) {
|
|
1008
|
+
const parent = node.parent;
|
|
1009
|
+
return ts.isJsxElement(parent) ? parent.openingElement.tagName.getText() : "text";
|
|
1010
|
+
}
|
|
1011
|
+
function fieldForTag(tag) {
|
|
1012
|
+
if (/^h[1-6]$/i.test(tag))
|
|
1013
|
+
return "title";
|
|
1014
|
+
if (/^(?:p|blockquote)$/i.test(tag))
|
|
1015
|
+
return "description";
|
|
1016
|
+
if (/^(?:a|button)$/i.test(tag))
|
|
1017
|
+
return "buttonLabel";
|
|
1018
|
+
if (/^(?:span|small)$/i.test(tag))
|
|
1019
|
+
return "eyebrow";
|
|
1020
|
+
return undefined;
|
|
1021
|
+
}
|
|
1022
|
+
function markdownCell(value) {
|
|
1023
|
+
return value.replace(/\|/g, "\\|").replace(/\r?\n/g, "<br>");
|
|
1024
|
+
}
|
|
1025
|
+
async function extractContentCatalog(plan) {
|
|
1026
|
+
const sources = new Map();
|
|
1027
|
+
const translations = new Map();
|
|
1028
|
+
const constantNodes = new Map();
|
|
1029
|
+
const constants = new Map();
|
|
1030
|
+
for (const module of plan.analysis.sourceGraph.modules.filter(({ kind }) => kind === "SOURCE")) {
|
|
1031
|
+
const content = await readFile(module.absolutePath, "utf8");
|
|
1032
|
+
const source = ts.createSourceFile(module.absolutePath, content, ts.ScriptTarget.Latest, true, sourceKind(module.absolutePath));
|
|
1033
|
+
sources.set(module.file, { source, content });
|
|
1034
|
+
for (const [key, value] of translationValues(source))
|
|
1035
|
+
translations.set(key, value);
|
|
1036
|
+
function collectConstants(node) {
|
|
1037
|
+
if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name) && node.initializer) {
|
|
1038
|
+
constantNodes.set(node.name.text, node.initializer);
|
|
1039
|
+
}
|
|
1040
|
+
ts.forEachChild(node, collectConstants);
|
|
1041
|
+
}
|
|
1042
|
+
collectConstants(source);
|
|
1043
|
+
}
|
|
1044
|
+
function resolvedString(expression, stack = new Set()) {
|
|
1045
|
+
const value = unwrappedExpression(expression);
|
|
1046
|
+
if (ts.isStringLiteralLike(value) || ts.isNoSubstitutionTemplateLiteral(value))
|
|
1047
|
+
return value.text;
|
|
1048
|
+
if (ts.isIdentifier(value)) {
|
|
1049
|
+
if (constants.has(value.text))
|
|
1050
|
+
return constants.get(value.text);
|
|
1051
|
+
if (stack.has(value.text))
|
|
1052
|
+
return null;
|
|
1053
|
+
const initializer = constantNodes.get(value.text);
|
|
1054
|
+
if (!initializer)
|
|
1055
|
+
return null;
|
|
1056
|
+
const next = new Set(stack).add(value.text);
|
|
1057
|
+
const resolved = resolvedString(initializer, next);
|
|
1058
|
+
if (resolved !== null)
|
|
1059
|
+
constants.set(value.text, resolved);
|
|
1060
|
+
return resolved;
|
|
1061
|
+
}
|
|
1062
|
+
if (ts.isTemplateExpression(value)) {
|
|
1063
|
+
let output = value.head.text;
|
|
1064
|
+
for (const span of value.templateSpans) {
|
|
1065
|
+
const resolved = resolvedString(span.expression, stack);
|
|
1066
|
+
if (resolved === null)
|
|
1067
|
+
return null;
|
|
1068
|
+
output += resolved + span.literal.text;
|
|
1069
|
+
}
|
|
1070
|
+
return output;
|
|
1071
|
+
}
|
|
1072
|
+
if (ts.isBinaryExpression(value) && value.operatorToken.kind === ts.SyntaxKind.PlusToken) {
|
|
1073
|
+
const left = resolvedString(value.left, stack);
|
|
1074
|
+
const right = resolvedString(value.right, stack);
|
|
1075
|
+
return left === null || right === null ? null : left + right;
|
|
1076
|
+
}
|
|
1077
|
+
return null;
|
|
1078
|
+
}
|
|
1079
|
+
for (const [name, expression] of constantNodes) {
|
|
1080
|
+
const value = resolvedString(expression);
|
|
1081
|
+
if (value !== null)
|
|
1082
|
+
constants.set(name, value);
|
|
1083
|
+
}
|
|
1084
|
+
const sections = plan.contentBindings.map((binding) => {
|
|
1085
|
+
const parsed = sources.get(binding.file);
|
|
1086
|
+
const values = [];
|
|
1087
|
+
const formFields = [];
|
|
1088
|
+
const seen = new Set();
|
|
1089
|
+
const counters = new Map();
|
|
1090
|
+
const importedAssets = new Map();
|
|
1091
|
+
const add = (candidate) => {
|
|
1092
|
+
const value = candidate.value.trim().replace(/\s+/g, " ");
|
|
1093
|
+
if (!value || seen.has(`${candidate.kind}:${candidate.key}:${value}`))
|
|
1094
|
+
return;
|
|
1095
|
+
seen.add(`${candidate.kind}:${candidate.key}:${value}`);
|
|
1096
|
+
values.push({ ...candidate, value });
|
|
1097
|
+
};
|
|
1098
|
+
if (parsed) {
|
|
1099
|
+
const source = parsed.source;
|
|
1100
|
+
const attributeValue = (attributes, name) => {
|
|
1101
|
+
const attribute = attributes.properties.find((candidate) => (ts.isJsxAttribute(candidate) && candidate.name.getText(source) === name));
|
|
1102
|
+
if (!attribute?.initializer)
|
|
1103
|
+
return null;
|
|
1104
|
+
if (ts.isStringLiteral(attribute.initializer))
|
|
1105
|
+
return attribute.initializer.text;
|
|
1106
|
+
if (ts.isJsxExpression(attribute.initializer) && attribute.initializer.expression) {
|
|
1107
|
+
return resolvedString(attribute.initializer.expression);
|
|
1108
|
+
}
|
|
1109
|
+
return null;
|
|
1110
|
+
};
|
|
1111
|
+
const hasAttribute = (attributes, name) => attributes.properties.some((candidate) => (ts.isJsxAttribute(candidate) && candidate.name.getText(source) === name));
|
|
1112
|
+
const nodeText = (node) => {
|
|
1113
|
+
const chunks = [];
|
|
1114
|
+
const collect = (candidate) => {
|
|
1115
|
+
if (ts.isJsxText(candidate) && candidate.text.trim())
|
|
1116
|
+
chunks.push(candidate.text);
|
|
1117
|
+
else if (ts.isJsxExpression(candidate) && candidate.expression) {
|
|
1118
|
+
const value = resolvedString(candidate.expression);
|
|
1119
|
+
if (value)
|
|
1120
|
+
chunks.push(value);
|
|
1121
|
+
}
|
|
1122
|
+
ts.forEachChild(candidate, collect);
|
|
1123
|
+
};
|
|
1124
|
+
collect(node);
|
|
1125
|
+
return chunks.join(" ").trim().replace(/\s+/g, " ");
|
|
1126
|
+
};
|
|
1127
|
+
const fieldLabelText = (node) => {
|
|
1128
|
+
const chunks = [];
|
|
1129
|
+
const collect = (candidate) => {
|
|
1130
|
+
if ((ts.isJsxElement(candidate) || ts.isJsxSelfClosingElement(candidate))) {
|
|
1131
|
+
const tag = (ts.isJsxElement(candidate) ? candidate.openingElement.tagName : candidate.tagName).getText(source).toLowerCase();
|
|
1132
|
+
if (["input", "textarea", "select", "option"].includes(tag))
|
|
1133
|
+
return;
|
|
1134
|
+
}
|
|
1135
|
+
if (ts.isJsxText(candidate) && candidate.text.trim())
|
|
1136
|
+
chunks.push(candidate.text);
|
|
1137
|
+
else if (ts.isJsxExpression(candidate) && candidate.expression) {
|
|
1138
|
+
const value = resolvedString(candidate.expression);
|
|
1139
|
+
if (value)
|
|
1140
|
+
chunks.push(value);
|
|
1141
|
+
}
|
|
1142
|
+
ts.forEachChild(candidate, collect);
|
|
1143
|
+
};
|
|
1144
|
+
collect(node);
|
|
1145
|
+
return chunks.join(" ").trim().replace(/\s+/g, " ");
|
|
1146
|
+
};
|
|
1147
|
+
const nearbyFieldLabel = (node, type) => {
|
|
1148
|
+
let ancestor = node.parent;
|
|
1149
|
+
while (ancestor && !ts.isFunctionLike(ancestor)) {
|
|
1150
|
+
if (ts.isJsxElement(ancestor) && ancestor.openingElement.tagName.getText(source).toLowerCase() === "label") {
|
|
1151
|
+
const label = fieldLabelText(ancestor);
|
|
1152
|
+
if (label)
|
|
1153
|
+
return label;
|
|
1154
|
+
}
|
|
1155
|
+
if (ts.isJsxElement(ancestor)) {
|
|
1156
|
+
const index = ancestor.children.findIndex((child) => child === node || child.pos <= node.pos && child.end >= node.end);
|
|
1157
|
+
if (index >= 0) {
|
|
1158
|
+
const before = ancestor.children.slice(0, index).reverse();
|
|
1159
|
+
const after = ancestor.children.slice(index + 1);
|
|
1160
|
+
const siblings = type === "checkbox"
|
|
1161
|
+
? [...after, ...before]
|
|
1162
|
+
: [...before, ...after];
|
|
1163
|
+
for (const sibling of siblings) {
|
|
1164
|
+
if (!sibling)
|
|
1165
|
+
continue;
|
|
1166
|
+
const label = fieldLabelText(sibling);
|
|
1167
|
+
if (label)
|
|
1168
|
+
return label;
|
|
1169
|
+
}
|
|
1170
|
+
}
|
|
1171
|
+
}
|
|
1172
|
+
ancestor = ancestor.parent;
|
|
1173
|
+
}
|
|
1174
|
+
return "";
|
|
1175
|
+
};
|
|
1176
|
+
const collectFormField = (node) => {
|
|
1177
|
+
if (binding.componentKey !== "contact-form")
|
|
1178
|
+
return;
|
|
1179
|
+
const opening = ts.isJsxElement(node) ? node.openingElement : node;
|
|
1180
|
+
const tag = opening.tagName.getText(source).toLowerCase();
|
|
1181
|
+
if (!["input", "textarea", "select"].includes(tag))
|
|
1182
|
+
return;
|
|
1183
|
+
const key = attributeValue(opening.attributes, "name")?.trim();
|
|
1184
|
+
if (!key || formFields.some((field) => field.key === key))
|
|
1185
|
+
return;
|
|
1186
|
+
const rawType = tag === "textarea" ? "textarea" : tag === "select" ? "select" : attributeValue(opening.attributes, "type") ?? "text";
|
|
1187
|
+
const type = ["text", "email", "tel", "url", "number", "textarea", "select", "checkbox"].includes(rawType)
|
|
1188
|
+
? rawType
|
|
1189
|
+
: "text";
|
|
1190
|
+
const label = nearbyFieldLabel(node, type) || key;
|
|
1191
|
+
const field = {
|
|
1192
|
+
key,
|
|
1193
|
+
label,
|
|
1194
|
+
type,
|
|
1195
|
+
required: hasAttribute(opening.attributes, "required"),
|
|
1196
|
+
};
|
|
1197
|
+
const placeholder = attributeValue(opening.attributes, "placeholder")?.trim();
|
|
1198
|
+
if (placeholder)
|
|
1199
|
+
field.placeholder = placeholder;
|
|
1200
|
+
if (tag === "select" && ts.isJsxElement(node)) {
|
|
1201
|
+
const options = [];
|
|
1202
|
+
const visitOption = (candidate) => {
|
|
1203
|
+
if (ts.isJsxElement(candidate) && candidate.openingElement.tagName.getText(source).toLowerCase() === "option") {
|
|
1204
|
+
const optionLabel = nodeText(candidate);
|
|
1205
|
+
const optionValue = attributeValue(candidate.openingElement.attributes, "value") ?? optionLabel;
|
|
1206
|
+
if (optionLabel)
|
|
1207
|
+
options.push({ label: optionLabel, value: optionValue });
|
|
1208
|
+
return;
|
|
1209
|
+
}
|
|
1210
|
+
ts.forEachChild(candidate, visitOption);
|
|
1211
|
+
};
|
|
1212
|
+
visitOption(node);
|
|
1213
|
+
if (options.length)
|
|
1214
|
+
field.options = options;
|
|
1215
|
+
}
|
|
1216
|
+
formFields.push(field);
|
|
1217
|
+
};
|
|
1218
|
+
for (const statement of source.statements.filter(ts.isImportDeclaration)) {
|
|
1219
|
+
const specifier = statement.moduleSpecifier;
|
|
1220
|
+
if (!ts.isStringLiteralLike(specifier) || !statement.importClause)
|
|
1221
|
+
continue;
|
|
1222
|
+
const extension = path.extname(specifier.text).toLowerCase();
|
|
1223
|
+
if (!/[.](?:avif|gif|jpe?g|png|svg|webp|mp4|webm|ogg)$/i.test(extension))
|
|
1224
|
+
continue;
|
|
1225
|
+
const assetReference = specifier.text.startsWith(".")
|
|
1226
|
+
? portable(path.normalize(path.join(path.dirname(binding.file), specifier.text)))
|
|
1227
|
+
: specifier.text;
|
|
1228
|
+
if (statement.importClause.name)
|
|
1229
|
+
importedAssets.set(statement.importClause.name.text, assetReference);
|
|
1230
|
+
if (statement.importClause.namedBindings && ts.isNamedImports(statement.importClause.namedBindings)) {
|
|
1231
|
+
for (const item of statement.importClause.namedBindings.elements)
|
|
1232
|
+
importedAssets.set(item.name.text, assetReference);
|
|
1233
|
+
}
|
|
1234
|
+
}
|
|
1235
|
+
function componentName(node) {
|
|
1236
|
+
if ("name" in node && node.name && ts.isIdentifier(node.name))
|
|
1237
|
+
return node.name.text;
|
|
1238
|
+
const parent = node.parent;
|
|
1239
|
+
return ts.isVariableDeclaration(parent) && ts.isIdentifier(parent.name) ? parent.name.text : null;
|
|
1240
|
+
}
|
|
1241
|
+
function visitContent(node) {
|
|
1242
|
+
if (ts.isJsxElement(node) || ts.isJsxSelfClosingElement(node))
|
|
1243
|
+
collectFormField(node);
|
|
1244
|
+
if (binding.componentKey === "feature-list" && ts.isArrayLiteralExpression(node)) {
|
|
1245
|
+
for (const element of node.elements) {
|
|
1246
|
+
const item = resolvedString(element);
|
|
1247
|
+
if (item)
|
|
1248
|
+
add({ key: "data.item", value: item, kind: "text" });
|
|
1249
|
+
}
|
|
1250
|
+
}
|
|
1251
|
+
if (ts.isCallExpression(node)
|
|
1252
|
+
&& ts.isIdentifier(node.expression)
|
|
1253
|
+
&& node.expression.text === "t"
|
|
1254
|
+
&& node.arguments[0]
|
|
1255
|
+
&& ts.isStringLiteralLike(node.arguments[0])) {
|
|
1256
|
+
const key = node.arguments[0].text;
|
|
1257
|
+
add({ key, value: translations.get(key) ?? `[tradução não localizada: ${key}]`, kind: "text", field: contentField(key) });
|
|
1258
|
+
return;
|
|
1259
|
+
}
|
|
1260
|
+
if (ts.isJsxText(node) && node.text.trim()) {
|
|
1261
|
+
const tag = jsxTagForText(node);
|
|
1262
|
+
const count = (counters.get(tag) ?? 0) + 1;
|
|
1263
|
+
counters.set(tag, count);
|
|
1264
|
+
add({ key: `jsx.${tag}.${count}`, value: node.text, kind: "text", field: fieldForTag(tag) });
|
|
1265
|
+
return;
|
|
1266
|
+
}
|
|
1267
|
+
if (ts.isPropertyAssignment(node)) {
|
|
1268
|
+
const key = propertyKey(node);
|
|
1269
|
+
const value = resolvedString(node.initializer);
|
|
1270
|
+
if (key && value !== null && /^(?:title|headline|heading|subtitle|description|desc|text|content|label|cta|price|period|badge|question|answer|q|a|name|value|number|metric|num|role|email|phone|tel)$/i.test(key)) {
|
|
1271
|
+
add({ key: `data.${key}`, value, kind: "text", field: contentField(key) });
|
|
1272
|
+
}
|
|
1273
|
+
}
|
|
1274
|
+
if (ts.isJsxAttribute(node) && node.initializer) {
|
|
1275
|
+
const name = node.name.getText(source);
|
|
1276
|
+
const tag = node.parent.parent.tagName.getText(source).toLowerCase();
|
|
1277
|
+
let expression = null;
|
|
1278
|
+
if (ts.isStringLiteral(node.initializer))
|
|
1279
|
+
expression = node.initializer;
|
|
1280
|
+
else if (ts.isJsxExpression(node.initializer) && node.initializer.expression)
|
|
1281
|
+
expression = node.initializer.expression;
|
|
1282
|
+
const literal = expression ? resolvedString(expression) : null;
|
|
1283
|
+
const imported = expression && ts.isIdentifier(expression) ? importedAssets.get(expression.text) : undefined;
|
|
1284
|
+
const value = literal ?? imported ?? null;
|
|
1285
|
+
if (value && name === "href" && (tag === "a" || tag === "button"))
|
|
1286
|
+
add({ key: `${tag}.href`, value, kind: "link", field: "buttonUrl" });
|
|
1287
|
+
if (value && ["src", "poster"].includes(name) && ["img", "image", "video", "source", "iframe"].includes(tag)) {
|
|
1288
|
+
const field = name === "poster"
|
|
1289
|
+
? "posterImageUrl"
|
|
1290
|
+
: binding.componentKey === "video" && (tag === "video" || tag === "source" || tag === "iframe")
|
|
1291
|
+
? "videoUrl"
|
|
1292
|
+
: "imageUrl";
|
|
1293
|
+
add({ key: `${tag}.${name}`, value, kind: "media", field });
|
|
1294
|
+
}
|
|
1295
|
+
if (value && name === "alt" && ["img", "image"].includes(tag))
|
|
1296
|
+
add({ key: `${tag}.alt`, value, kind: "text", field: "imageAlt" });
|
|
1297
|
+
}
|
|
1298
|
+
ts.forEachChild(node, visitContent);
|
|
1299
|
+
}
|
|
1300
|
+
function findComponent(node) {
|
|
1301
|
+
if ((ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) || ts.isArrowFunction(node))
|
|
1302
|
+
&& componentName(node) === binding.component
|
|
1303
|
+
&& node.body) {
|
|
1304
|
+
visitContent(node.body);
|
|
1305
|
+
return;
|
|
1306
|
+
}
|
|
1307
|
+
ts.forEachChild(node, findComponent);
|
|
1308
|
+
}
|
|
1309
|
+
findComponent(source);
|
|
1310
|
+
}
|
|
1311
|
+
const sectionData = blankBindingData(binding);
|
|
1312
|
+
const data = binding.type === "theme-component"
|
|
1313
|
+
? sectionData.props
|
|
1314
|
+
: sectionData;
|
|
1315
|
+
const availableFields = new Set(binding.fields);
|
|
1316
|
+
const selected = new Set();
|
|
1317
|
+
const assign = (field, candidate) => {
|
|
1318
|
+
if (!candidate || !availableFields.has(field))
|
|
1319
|
+
return;
|
|
1320
|
+
data[field] = candidate.kind === "media" ? "" : candidate.value;
|
|
1321
|
+
selected.add(candidate.key);
|
|
1322
|
+
};
|
|
1323
|
+
const rank = (field, item) => {
|
|
1324
|
+
if (field === "title" && /^jsx\.h[1-6]\./.test(item.key))
|
|
1325
|
+
return 0;
|
|
1326
|
+
if (field === "description" && /^jsx\.(?:p|blockquote)\./.test(item.key))
|
|
1327
|
+
return 0;
|
|
1328
|
+
if (field === "buttonLabel" && /^jsx\.(?:button|a)\./.test(item.key))
|
|
1329
|
+
return 0;
|
|
1330
|
+
if (field === "eyebrow" && /^jsx\.(?:span|small)\./.test(item.key))
|
|
1331
|
+
return 0;
|
|
1332
|
+
if (item.key.startsWith("jsx."))
|
|
1333
|
+
return 1;
|
|
1334
|
+
if (item.key.startsWith("data."))
|
|
1335
|
+
return 3;
|
|
1336
|
+
return 2;
|
|
1337
|
+
};
|
|
1338
|
+
const ranked = (field) => values
|
|
1339
|
+
.filter((item) => item.field === field && !(field === "eyebrow" && /(?:lgpd|consent|privacidade|tratamento dos meus dados|autorizo)/i.test(item.value)))
|
|
1340
|
+
.sort((left, right) => rank(field, left) - rank(field, right) || left.key.split(".").length - right.key.split(".").length)[0];
|
|
1341
|
+
const inferredEyebrow = ranked("eyebrow") ?? values.find((item) => (/^jsx\.div\./.test(item.key)
|
|
1342
|
+
&& item.value.length <= 100
|
|
1343
|
+
&& item.value === item.value.toLocaleUpperCase("pt-BR")
|
|
1344
|
+
&& /[A-ZÀ-Ü]/.test(item.value)
|
|
1345
|
+
&& !/(?:lgpd|consent|privacidade|tratamento dos meus dados|autorizo)/i.test(item.value)));
|
|
1346
|
+
assign("eyebrow", inferredEyebrow);
|
|
1347
|
+
assign("title", ranked("title"));
|
|
1348
|
+
const description = ranked("description");
|
|
1349
|
+
assign(availableFields.has("description") ? "description" : "text", description);
|
|
1350
|
+
assign("buttonLabel", ranked("buttonLabel"));
|
|
1351
|
+
assign("buttonUrl", ranked("buttonUrl"));
|
|
1352
|
+
assign("imageAlt", ranked("imageAlt"));
|
|
1353
|
+
assign("videoUrl", ranked("videoUrl"));
|
|
1354
|
+
assign("posterImageUrl", ranked("posterImageUrl"));
|
|
1355
|
+
if (binding.componentKey === "contact-form" && formFields.length && availableFields.has("fields")) {
|
|
1356
|
+
data.fields = formFields;
|
|
1357
|
+
}
|
|
1358
|
+
const media = ranked("imageUrl");
|
|
1359
|
+
if (media && availableFields.has("imageUrl"))
|
|
1360
|
+
selected.add(media.key);
|
|
1361
|
+
if (availableFields.has("text") && !data.text) {
|
|
1362
|
+
const remaining = values.filter(({ kind, key }) => kind === "text" && !selected.has(key) && !key.includes("tradução não localizada"));
|
|
1363
|
+
data.text = remaining.map(({ value }) => value).join("\n\n");
|
|
1364
|
+
}
|
|
1365
|
+
if (binding.type === "theme-component" && availableFields.has("items")) {
|
|
1366
|
+
const properties = values.filter(({ key, kind }) => key.startsWith("data.") && kind === "text");
|
|
1367
|
+
const items = [];
|
|
1368
|
+
if (binding.componentKey === "faq") {
|
|
1369
|
+
for (let index = 0; index < properties.length; index += 1) {
|
|
1370
|
+
const question = properties[index];
|
|
1371
|
+
if (!/(?:question|q)$/.test(question.key.toLowerCase()))
|
|
1372
|
+
continue;
|
|
1373
|
+
const answer = properties.slice(index + 1).find(({ key }) => /(?:answer|a)$/.test(key.toLowerCase()));
|
|
1374
|
+
items.push({ question: question.value, answer: answer?.value ?? "" });
|
|
1375
|
+
}
|
|
1376
|
+
}
|
|
1377
|
+
else if (binding.componentKey === "metrics") {
|
|
1378
|
+
let current = {};
|
|
1379
|
+
for (const property of properties) {
|
|
1380
|
+
const key = property.key.toLowerCase();
|
|
1381
|
+
if (/(?:value|number|metric)$/.test(key)) {
|
|
1382
|
+
if (Object.keys(current).length)
|
|
1383
|
+
items.push(current);
|
|
1384
|
+
current = { value: property.value };
|
|
1385
|
+
}
|
|
1386
|
+
else if (/(?:title|label|name)$/.test(key) && !current.title)
|
|
1387
|
+
current.title = property.value;
|
|
1388
|
+
else if (/(?:description|desc|text)$/.test(key) && !current.description)
|
|
1389
|
+
current.description = property.value;
|
|
1390
|
+
}
|
|
1391
|
+
if (Object.keys(current).length)
|
|
1392
|
+
items.push(current);
|
|
1393
|
+
}
|
|
1394
|
+
else if (binding.componentKey === "steps") {
|
|
1395
|
+
let current = {};
|
|
1396
|
+
for (const property of properties) {
|
|
1397
|
+
const key = property.key.toLowerCase();
|
|
1398
|
+
if (/(?:num|number|value)$/.test(key)) {
|
|
1399
|
+
if (Object.keys(current).length)
|
|
1400
|
+
items.push(current);
|
|
1401
|
+
current = { num: property.value };
|
|
1402
|
+
}
|
|
1403
|
+
else if (/(?:title|label|name)$/.test(key))
|
|
1404
|
+
current.title = property.value;
|
|
1405
|
+
else if (/(?:description|desc|text)$/.test(key))
|
|
1406
|
+
current.desc = property.value;
|
|
1407
|
+
}
|
|
1408
|
+
if (Object.keys(current).length)
|
|
1409
|
+
items.push(current);
|
|
1410
|
+
}
|
|
1411
|
+
else if (binding.componentKey === "contacts") {
|
|
1412
|
+
let current = {};
|
|
1413
|
+
for (const property of properties) {
|
|
1414
|
+
const key = property.key.toLowerCase();
|
|
1415
|
+
if (/(?:role)$/.test(key)) {
|
|
1416
|
+
if (Object.keys(current).length)
|
|
1417
|
+
items.push(current);
|
|
1418
|
+
current = { role: property.value };
|
|
1419
|
+
}
|
|
1420
|
+
else if (/(?:name)$/.test(key))
|
|
1421
|
+
current.name = property.value;
|
|
1422
|
+
else if (/(?:email)$/.test(key))
|
|
1423
|
+
current.email = property.value;
|
|
1424
|
+
else if (/(?:phone|tel)$/.test(key))
|
|
1425
|
+
current.phone = property.value;
|
|
1426
|
+
}
|
|
1427
|
+
if (Object.keys(current).length)
|
|
1428
|
+
items.push(current);
|
|
1429
|
+
}
|
|
1430
|
+
else if (binding.componentKey === "feature-list") {
|
|
1431
|
+
items.push(...values.filter(({ key }) => key === "data.item").map(({ value }) => ({ title: value })));
|
|
1432
|
+
}
|
|
1433
|
+
else {
|
|
1434
|
+
let current = {};
|
|
1435
|
+
for (const property of properties) {
|
|
1436
|
+
const key = property.key.toLowerCase();
|
|
1437
|
+
if (/(?:title|label|name)$/.test(key)) {
|
|
1438
|
+
if (current.title)
|
|
1439
|
+
items.push(current);
|
|
1440
|
+
current = { title: property.value };
|
|
1441
|
+
}
|
|
1442
|
+
else if (/(?:description|desc|text)$/.test(key) && current.title && !current.description) {
|
|
1443
|
+
current.description = property.value;
|
|
1444
|
+
}
|
|
1445
|
+
}
|
|
1446
|
+
if (Object.keys(current).length)
|
|
1447
|
+
items.push(current);
|
|
1448
|
+
}
|
|
1449
|
+
data.items = items;
|
|
1450
|
+
}
|
|
1451
|
+
return { id: binding.id, component: binding.component, file: binding.file, type: binding.type, order: binding.order, data: sectionData, sourceContent: values };
|
|
1452
|
+
});
|
|
1453
|
+
return {
|
|
1454
|
+
version: 1,
|
|
1455
|
+
locale: translations.size ? "pt" : "original",
|
|
1456
|
+
note: "Conteúdo de referência extraído do projeto original. Cadastre-o no painel; este arquivo não é carregado pelo tema em runtime.",
|
|
1457
|
+
sections,
|
|
1458
|
+
};
|
|
1459
|
+
}
|
|
1460
|
+
function homeConfiguration(plan) {
|
|
1461
|
+
return `${JSON.stringify({
|
|
1462
|
+
version: 1,
|
|
1463
|
+
sections: plan.contentBindings.map((binding) => ({ id: binding.id, type: binding.type, enabled: true, order: binding.order, data: blankBindingData(binding) })),
|
|
1464
|
+
}, null, 2)}\n`;
|
|
1465
|
+
}
|
|
1466
|
+
function contentMap(plan, catalog) {
|
|
1467
|
+
return `${JSON.stringify({
|
|
1468
|
+
version: 1,
|
|
1469
|
+
sourceProject: plan.analysis.projectName,
|
|
1470
|
+
note: "Preencha estes campos no painel Nuvler. Os valores extraídos estão em migration-content-seed.json; o tema não os publica hardcoded.",
|
|
1471
|
+
management: {
|
|
1472
|
+
location: "Home → Construtor",
|
|
1473
|
+
mode: "Montar",
|
|
1474
|
+
finalAction: "Salvar rascunho e Publicar",
|
|
1475
|
+
},
|
|
1476
|
+
sections: plan.contentBindings.map((binding) => {
|
|
1477
|
+
const serializableBinding = {
|
|
1478
|
+
id: binding.id,
|
|
1479
|
+
component: binding.component,
|
|
1480
|
+
file: binding.file,
|
|
1481
|
+
type: binding.type,
|
|
1482
|
+
order: binding.order,
|
|
1483
|
+
fields: binding.fields,
|
|
1484
|
+
componentKey: binding.componentKey,
|
|
1485
|
+
componentDefinition: binding.componentDefinition,
|
|
1486
|
+
};
|
|
1487
|
+
const definition = panelDefinition(binding);
|
|
1488
|
+
const compatibility = panelCompatibility(binding);
|
|
1489
|
+
return {
|
|
1490
|
+
...serializableBinding,
|
|
1491
|
+
visualLink: `${binding.component} → ${definition.name} → ${binding.type}`,
|
|
1492
|
+
panel: {
|
|
1493
|
+
location: "Home → Construtor → Montar",
|
|
1494
|
+
category: definition.category,
|
|
1495
|
+
name: definition.name,
|
|
1496
|
+
description: definition.description,
|
|
1497
|
+
sectionId: binding.id,
|
|
1498
|
+
type: binding.type,
|
|
1499
|
+
order: binding.order,
|
|
1500
|
+
compatibility,
|
|
1501
|
+
controls: definition.controls,
|
|
1502
|
+
contentSource: definition.contentSource ?? null,
|
|
1503
|
+
data: blankBindingData(binding),
|
|
1504
|
+
},
|
|
1505
|
+
template: {
|
|
1506
|
+
hook: `useMigratedSection(${JSON.stringify(binding.id)})`,
|
|
1507
|
+
reads: binding.fields.map((field) => ({
|
|
1508
|
+
field,
|
|
1509
|
+
accessor: binding.type === "theme-component"
|
|
1510
|
+
? `section.data.props.${field}`
|
|
1511
|
+
: `section.data.${field}`,
|
|
1512
|
+
})),
|
|
1513
|
+
},
|
|
1514
|
+
extractedContent: catalog.sections.find(({ id }) => id === binding.id)?.sourceContent ?? [],
|
|
1515
|
+
};
|
|
1516
|
+
}),
|
|
1517
|
+
}, null, 2)}\n`;
|
|
1518
|
+
}
|
|
1519
|
+
function contentGuide(plan, catalog) {
|
|
1520
|
+
const rows = plan.contentBindings.map((binding) => {
|
|
1521
|
+
const definition = panelDefinition(binding);
|
|
1522
|
+
const compatibility = panelCompatibility(binding);
|
|
1523
|
+
const source = definition.contentSource?.location ?? "Nesta própria seção";
|
|
1524
|
+
return `| ${binding.order + 1} | ${binding.component} | **${definition.name}** | \`${binding.type}\` | ${compatibility.label} | ${source} |`;
|
|
1525
|
+
}).join("\n");
|
|
1526
|
+
const details = catalog.sections.map((section) => {
|
|
1527
|
+
const binding = plan.contentBindings.find(({ id }) => id === section.id);
|
|
1528
|
+
const definition = binding ? panelDefinition(binding) : PANEL_SECTION_DEFINITIONS[section.type];
|
|
1529
|
+
const compatibility = binding ? panelCompatibility(binding) : null;
|
|
1530
|
+
const populatedData = Object.fromEntries(Object.entries(section.data).filter(([, value]) => value !== ""));
|
|
1531
|
+
const detected = section.sourceContent.map(({ key, value, kind, field }) => (`| \`${markdownCell(key)}\` | ${markdownCell(value)} | ${kind === "media" ? "mídia: faça upload no painel" : field ? `\`${field}\`` : "conteúdo adicional"} |`)).join("\n");
|
|
1532
|
+
const controls = definition.controls.map((control) => (`| ${control.label} | ${control.fields.map((field) => `\`${field}\``).join(", ")} | ${control.note ?? "-"} |`)).join("\n");
|
|
1533
|
+
const contentSource = definition.contentSource
|
|
1534
|
+
? `\n**Conteúdo dos itens:** abra **${definition.contentSource.location}**. ${definition.contentSource.description}\n`
|
|
1535
|
+
: "";
|
|
1536
|
+
return `## ${section.order + 1}. ${section.component} → ${definition.name}
|
|
1537
|
+
|
|
1538
|
+
No Gestão: **Home → Construtor → Montar → ${definition.category} → ${definition.name}**.
|
|
1539
|
+
O nome técnico enviado pela API é \`${section.type}\`.
|
|
1540
|
+
${compatibility ? `\n**Compatibilidade:** ${compatibility.label}. ${compatibility.note}\n` : ""}
|
|
1541
|
+
${contentSource}
|
|
1542
|
+
| Rótulo que aparece no Gestão | Chave na API | Observação |
|
|
1543
|
+
| --- | --- | --- |
|
|
1544
|
+
${controls}
|
|
1545
|
+
|
|
1546
|
+
Valores encontrados no projeto original para copiar no painel:
|
|
1547
|
+
|
|
1548
|
+
\`\`\`json
|
|
1549
|
+
${JSON.stringify(populatedData, null, 2)}
|
|
1550
|
+
\`\`\`
|
|
1551
|
+
|
|
1552
|
+
Conteúdo encontrado no projeto original:
|
|
1553
|
+
|
|
1554
|
+
| Origem | Valor original | Destino sugerido |
|
|
1555
|
+
| --- | --- | --- |
|
|
1556
|
+
${detected || "| - | Nenhum valor literal localizado | revise o componente original |"}
|
|
1557
|
+
`;
|
|
1558
|
+
}).join("\n");
|
|
1559
|
+
return `# Configuração de conteúdo no Nuvler
|
|
1560
|
+
|
|
1561
|
+
Este tema mantém os componentes e a estilização do projeto original. Textos,
|
|
1562
|
+
imagens e links são lidos das seções configuradas em **Home** no painel Nuvler.
|
|
1563
|
+
|
|
1564
|
+
No Gestão, abra **Home → Construtor**, mantenha o modo **Montar** e escolha os
|
|
1565
|
+
blocos pelos nomes da coluna **Bloco no Gestão**. Depois use **Salvar rascunho**
|
|
1566
|
+
e **Publicar**. Não procure por nomes técnicos como \`hero\`: na tela ele aparece
|
|
1567
|
+
como **Banner principal**.
|
|
1568
|
+
|
|
1569
|
+
Crie as seções abaixo na mesma ordem. O tema prioriza o ID descrito em
|
|
1570
|
+
\`nuvler.home.json\`; quando o painel gerar outro ID, ele associa por tipo e
|
|
1571
|
+
ocorrência na ordem da Home.
|
|
1572
|
+
|
|
1573
|
+
| Ordem | Componente no projeto | Bloco no Gestão | Tipo técnico/API | Compatibilidade | Onde cadastrar os itens |
|
|
1574
|
+
| ---: | --- | --- | --- | --- | --- |
|
|
1575
|
+
${rows || "| - | Nenhuma seção detectada | - | - | - | - |"}
|
|
1576
|
+
|
|
1577
|
+
O arquivo \`nuvler.home.json\` é o blueprint vazio usado para conferir a estrutura.
|
|
1578
|
+
\`migration-content-seed.json\` guarda os valores extraídos para cadastro no painel,
|
|
1579
|
+
sem incluí-los no runtime do tema. \`migration-content-map.json\` documenta a ligação
|
|
1580
|
+
entre o componente, o painel e o template.
|
|
1581
|
+
|
|
1582
|
+
Referências de mídia apontam para o arquivo do projeto original. Faça o upload no
|
|
1583
|
+
painel e use a URL ou o ID retornado pelo Nuvler. Conteúdos adicionais sem campo
|
|
1584
|
+
equivalente ficam documentados abaixo; repeaters e schemas customizados continuam
|
|
1585
|
+
fora da V1.
|
|
1586
|
+
|
|
1587
|
+
${details}
|
|
1588
|
+
`;
|
|
1589
|
+
}
|
|
310
1590
|
function baseCss(plan) {
|
|
311
1591
|
return `/* Fallback estrutural do adaptador Nuvler. Os estilos extraídos vêm depois deste bloco. */
|
|
312
1592
|
* { box-sizing: border-box; }
|
|
@@ -326,6 +1606,16 @@ body { margin: 0; }
|
|
|
326
1606
|
.nuvler-migrated-hero-media, .nuvler-migrated-product-media, .nuvler-migrated-detail-media { overflow: hidden; border-radius: var(--theme-radius); }
|
|
327
1607
|
.nuvler-migrated-hero-media img, .nuvler-migrated-product-media img, .nuvler-migrated-detail-media img { display: block; width: 100%; height: 100%; object-fit: cover; }
|
|
328
1608
|
.nuvler-migrated-section { padding-block: 56px; }
|
|
1609
|
+
.nuvler-migrated-contact-form-section { display: grid; grid-template-columns: minmax(0, .8fr) minmax(0, 1.2fr); align-items: start; gap: 48px; }
|
|
1610
|
+
.nuvler-migrated-contact-form-copy h2 { margin-block: 10px; }
|
|
1611
|
+
.nuvler-migrated-contact-form-copy p { color: var(--theme-text-muted); line-height: 1.7; }
|
|
1612
|
+
.nuvler-migrated-contact-form { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 16px; border: 1px solid var(--theme-border); border-radius: var(--theme-radius); background: var(--theme-surface); padding: 24px; }
|
|
1613
|
+
.nuvler-migrated-contact-form label { display: grid; gap: 7px; }
|
|
1614
|
+
.nuvler-migrated-contact-form input, .nuvler-migrated-contact-form textarea, .nuvler-migrated-contact-form select { width: 100%; border: 1px solid var(--theme-border); border-radius: var(--theme-radius); background: var(--theme-background); color: var(--theme-text); padding: 12px 14px; font: inherit; }
|
|
1615
|
+
.nuvler-migrated-form-wide { grid-column: 1 / -1; }
|
|
1616
|
+
.nuvler-migrated-contact-form .nuvler-migrated-checkbox { display: flex; flex-direction: row; align-items: flex-start; gap: 10px; line-height: 1.55; }
|
|
1617
|
+
.nuvler-migrated-contact-form .nuvler-migrated-checkbox input { width: 18px; height: 18px; margin-top: 2px; padding: 0; accent-color: var(--theme-primary); }
|
|
1618
|
+
.nuvler-migrated-video { display: block; width: 100%; max-height: 720px; margin-top: 24px; border-radius: var(--theme-radius); background: #000; }
|
|
329
1619
|
.nuvler-migrated-product-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 20px; }
|
|
330
1620
|
.nuvler-migrated-product-grid[data-columns="4"] { grid-template-columns: repeat(4, minmax(0, 1fr)); }
|
|
331
1621
|
.nuvler-migrated-product-card { overflow: hidden; border: 1px solid var(--theme-border); border-radius: var(--theme-radius); background: var(--theme-surface); }
|
|
@@ -337,7 +1627,7 @@ body { margin: 0; }
|
|
|
337
1627
|
.nuvler-migrated-footer { margin-top: 64px; background: var(--theme-footer-background); color: var(--theme-footer-text); padding: 56px max(16px, calc((100% - var(--theme-container)) / 2)); }
|
|
338
1628
|
.nuvler-migrated-footer-inner { width: 100%; display: grid; grid-template-columns: 2fr 1fr 1fr; gap: 40px; }
|
|
339
1629
|
.nuvler-migrated-footer-nav, .nuvler-migrated-contact { display: grid; gap: 8px; }
|
|
340
|
-
@media (max-width: 850px) { .nuvler-migrated-header-inner, .nuvler-migrated-hero { grid-template-columns: 1fr; flex-direction: column; align-items: stretch; } .nuvler-migrated-nav { overflow-x: auto; flex-wrap: nowrap; } .nuvler-migrated-search input { width: 100%; min-width: 0; } .nuvler-migrated-product-grid, .nuvler-migrated-product-grid[data-columns="4"], .nuvler-migrated-product-detail, .nuvler-migrated-footer-inner { grid-template-columns: 1fr; } }
|
|
1630
|
+
@media (max-width: 850px) { .nuvler-migrated-header-inner, .nuvler-migrated-hero, .nuvler-migrated-contact-form-section, .nuvler-migrated-contact-form { grid-template-columns: 1fr; flex-direction: column; align-items: stretch; } .nuvler-migrated-form-wide { grid-column: auto; } .nuvler-migrated-nav { overflow-x: auto; flex-wrap: nowrap; } .nuvler-migrated-search input { width: 100%; min-width: 0; } .nuvler-migrated-product-grid, .nuvler-migrated-product-grid[data-columns="4"], .nuvler-migrated-product-detail, .nuvler-migrated-footer-inner { grid-template-columns: 1fr; } }
|
|
341
1631
|
|
|
342
1632
|
:root {
|
|
343
1633
|
--theme-primary: ${plan.tokens.primary};
|
|
@@ -369,13 +1659,17 @@ function copiedAssetFor(style, reference, plan, copied) {
|
|
|
369
1659
|
function preservedCss(plan, copied) {
|
|
370
1660
|
return plan.styles.map((style) => {
|
|
371
1661
|
let content = style.content;
|
|
372
|
-
content = content.replace(/@import\s+(["'])(
|
|
1662
|
+
content = content.replace(/@import\s+(?:url\(\s*)?(["'])(?:https?:\/\/[^"']+)\1\s*\)?[^;]*;?/gi, "");
|
|
1663
|
+
content = content.replace(/@import\s+(?:url\(\s*)?(["'])(?!https?:)(?!tailwindcss)([^"']+)\1\s*\)?[^;\r\n]*(?:;|$)/gim, "");
|
|
373
1664
|
content = content.replace(/@tailwind\s+(?:base|components|utilities)\s*;?/gi, "");
|
|
374
|
-
content = content.replace(/@import\s+["']tailwindcss["']\s
|
|
1665
|
+
content = content.replace(/@import\s+(?:url\(\s*)?["']tailwindcss["']\s*\)?[^;\r\n]*(?:;|$)/gim, "");
|
|
375
1666
|
content = content.replace(/:global\(([^)]+)\)/g, "$1");
|
|
376
1667
|
content = content.replace(/url\(\s*(["']?)([^)'"\s]+)\1\s*\)/gi, (full, _quote, reference) => {
|
|
377
1668
|
if (/^(?:data:|https?:|#)/i.test(reference))
|
|
378
1669
|
return full;
|
|
1670
|
+
const sourceAsset = sourceAssetFor(style, reference, plan);
|
|
1671
|
+
if (sourceAsset && sourceAsset.kind !== "font")
|
|
1672
|
+
return "none";
|
|
379
1673
|
const asset = copiedAssetFor(style, reference, plan, copied);
|
|
380
1674
|
if (!asset)
|
|
381
1675
|
return full;
|
|
@@ -389,6 +1683,23 @@ function preservedCss(plan, copied) {
|
|
|
389
1683
|
return `/* Origem: ${style.file}${style.module ? " (CSS Module convertido para CSS comum)" : ""} */\n${content}`;
|
|
390
1684
|
}).join("\n\n");
|
|
391
1685
|
}
|
|
1686
|
+
function sourceAssetFor(style, reference, plan) {
|
|
1687
|
+
const absolute = reference.startsWith("/")
|
|
1688
|
+
? path.join(plan.analysis.sourceDirectory, "public", reference.replace(/^\/+/, ""))
|
|
1689
|
+
: path.resolve(path.dirname(style.absolutePath), reference);
|
|
1690
|
+
return plan.assets.find((asset) => path.resolve(asset.absolutePath) === path.resolve(absolute));
|
|
1691
|
+
}
|
|
1692
|
+
function classCatalog(plan) {
|
|
1693
|
+
const classNames = plan.analysis.components
|
|
1694
|
+
.flatMap((component) => component.jsx.flatMap((node) => node.classes))
|
|
1695
|
+
.filter((className) => !className.includes("url("));
|
|
1696
|
+
return `/** Classes observadas no projeto original. Mantém utilitários visuais sem copiar conteúdo. */\nexport const migratedClassCatalog = ${JSON.stringify([...new Set(classNames)].join(" "))};\n`;
|
|
1697
|
+
}
|
|
1698
|
+
function externalCssImports(plan) {
|
|
1699
|
+
const imports = plan.styles.flatMap(({ content }) => ([...content.matchAll(/@import\s+(?:url\(\s*)?(["'])(?:https?:\/\/[^"']+)\1\s*\)?[^;]*;?/gi)]
|
|
1700
|
+
.map((match) => match[0].trim())));
|
|
1701
|
+
return [...new Set(imports)].join("\n");
|
|
1702
|
+
}
|
|
392
1703
|
async function configureTailwind(plan, directory) {
|
|
393
1704
|
if (!plan.analysis.tailwind.detected)
|
|
394
1705
|
return "";
|
|
@@ -402,7 +1713,11 @@ async function configureTailwind(plan, directory) {
|
|
|
402
1713
|
metadata.devDependencies["@tailwindcss/postcss"] = plan.analysis.dependencies["@tailwindcss/postcss"] || "^4.0.0";
|
|
403
1714
|
await writeFile(path.join(directory, "postcss.config.mjs"), "export default { plugins: { \"@tailwindcss/postcss\": {} } };\n", "utf8");
|
|
404
1715
|
await writeFile(packageFile, `${JSON.stringify(metadata, null, 2)}\n`, "utf8");
|
|
405
|
-
|
|
1716
|
+
// The production build reaches the copied TSX through the theme entry and
|
|
1717
|
+
// Tailwind discovers its classes automatically. The preview imports the
|
|
1718
|
+
// stylesheet from a Vite virtual module, so it needs an explicit source or
|
|
1719
|
+
// only the preview host's own classes are generated.
|
|
1720
|
+
return '@import "tailwindcss";\n@source "../**/*.{ts,tsx,js,jsx}";\n';
|
|
406
1721
|
}
|
|
407
1722
|
metadata.devDependencies.autoprefixer = plan.analysis.dependencies.autoprefixer || "^10.4.0";
|
|
408
1723
|
const migratedColors = JSON.stringify(plan.analysis.tailwind.colors);
|
|
@@ -426,26 +1741,59 @@ export async function generateMigratedTheme(plan, directory) {
|
|
|
426
1741
|
mkdir(path.join(directory, "src", "styles"), { recursive: true }),
|
|
427
1742
|
mkdir(path.join(directory, "src", "pages"), { recursive: true }),
|
|
428
1743
|
]);
|
|
429
|
-
const
|
|
1744
|
+
const fidelityEnabled = Boolean(plan.analysis.sourceGraph.entrypoint);
|
|
1745
|
+
const styleFiles = new Set(plan.styles.map((style) => style.file));
|
|
1746
|
+
const legacyAssets = fidelityEnabled
|
|
1747
|
+
? plan.assets.filter((asset) => asset.kind === "font" && asset.referencedBy.some((file) => styleFiles.has(file)))
|
|
1748
|
+
: plan.assets;
|
|
1749
|
+
const copiedAssets = await copyMigrationAssets(plan, directory, legacyAssets);
|
|
1750
|
+
const fidelity = await runFidelityPass(plan, directory);
|
|
1751
|
+
await mergeFidelityDependencies(plan, directory);
|
|
1752
|
+
for (const file of fidelity.adaptedBusinessFiles) {
|
|
1753
|
+
plan.warnings.push(`${file}: regra de negócio isolada pela Nuvler Adaptation Pass; apresentação dependente preservada.`);
|
|
1754
|
+
}
|
|
430
1755
|
const tailwindHeader = await configureTailwind(plan, directory);
|
|
1756
|
+
const extractedContent = await extractContentCatalog(plan);
|
|
431
1757
|
await Promise.all([
|
|
432
1758
|
writeFile(path.join(directory, "src/components/Header.tsx"), headerSource(plan), "utf8"),
|
|
433
1759
|
writeFile(path.join(directory, "src/components/Footer.tsx"), footerSource(plan), "utf8"),
|
|
434
1760
|
writeFile(path.join(directory, "src/components/ProductCard.tsx"), productCardSource(plan), "utf8"),
|
|
435
1761
|
writeFile(path.join(directory, "src/components/ProductGrid.tsx"), productGridSource(plan), "utf8"),
|
|
436
1762
|
writeFile(path.join(directory, "src/components/ProductDetail.tsx"), productDetailSource(plan), "utf8"),
|
|
437
|
-
writeFile(path.join(directory, "src/sections/Home.tsx"), homeSource(plan,
|
|
1763
|
+
writeFile(path.join(directory, "src/sections/Home.tsx"), homeSource(plan, fidelity), "utf8"),
|
|
438
1764
|
writeFile(path.join(directory, "src/pages/CatalogPage.tsx"), catalogPageSource(), "utf8"),
|
|
439
1765
|
writeFile(path.join(directory, "src/pages/ProductPage.tsx"), productPageSource(), "utf8"),
|
|
440
1766
|
writeFile(path.join(directory, "src/pages/EditorialPage.tsx"), editorialPageSource(), "utf8"),
|
|
441
1767
|
writeFile(path.join(directory, "src/pages/StatePage.tsx"), statePageSource(), "utf8"),
|
|
442
1768
|
writeFile(path.join(directory, "src/definition.tsx"), definitionSource(plan), "utf8"),
|
|
443
|
-
writeFile(path.join(directory, "src/theme.tsx"), themeSource(), "utf8"),
|
|
444
|
-
writeFile(path.join(directory, "src/
|
|
445
|
-
writeFile(path.join(directory, "src/
|
|
1769
|
+
writeFile(path.join(directory, "src/theme.tsx"), themeSource(Boolean(fidelity.entryImportPath)), "utf8"),
|
|
1770
|
+
writeFile(path.join(directory, "src/migrated-content.tsx"), migratedContentSource(plan), "utf8"),
|
|
1771
|
+
writeFile(path.join(directory, "src/migrated-next-image.tsx"), migratedNextImageSource(), "utf8"),
|
|
1772
|
+
writeFile(path.join(directory, "src/migrated-class-catalog.ts"), classCatalog(plan), "utf8"),
|
|
1773
|
+
writeFile(path.join(directory, "nuvler.home.json"), homeConfiguration(plan), "utf8"),
|
|
1774
|
+
writeFile(path.join(directory, "migration-content-seed.json"), `${JSON.stringify(extractedContent, null, 2)}\n`, "utf8"),
|
|
1775
|
+
writeFile(path.join(directory, "migration-content-map.json"), contentMap(plan, extractedContent), "utf8"),
|
|
1776
|
+
writeFile(path.join(directory, "CONTENT_SETUP.md"), contentGuide(plan, extractedContent), "utf8"),
|
|
1777
|
+
writeFile(path.join(directory, "src/styles/theme.css"), `${externalCssImports(plan)}\n${tailwindHeader}${baseCss(plan)}\n${preservedCss(plan, copiedAssets)}\n`, "utf8"),
|
|
1778
|
+
writeFile(path.join(directory, "src/styles.d.ts"), `declare module "*.module.css" { const classes: Record<string, string>; export default classes; }
|
|
1779
|
+
declare module "*.css";
|
|
1780
|
+
declare module "*.scss";
|
|
1781
|
+
declare module "*.sass";
|
|
1782
|
+
declare module "*.less";
|
|
1783
|
+
declare module "*.svg" { const url: string; export default url; }
|
|
1784
|
+
declare module "*.png" { const url: string; export default url; }
|
|
1785
|
+
declare module "*.jpg" { const url: string; export default url; }
|
|
1786
|
+
declare module "*.jpeg" { const url: string; export default url; }
|
|
1787
|
+
declare module "*.webp" { const url: string; export default url; }
|
|
1788
|
+
declare module "*.gif" { const url: string; export default url; }
|
|
1789
|
+
declare module "*.mp4" { const url: string; export default url; }
|
|
1790
|
+
declare module "*.webm" { const url: string; export default url; }
|
|
1791
|
+
`, "utf8"),
|
|
446
1792
|
]);
|
|
447
1793
|
const manifestFile = path.join(directory, "nuvler.theme.json");
|
|
448
1794
|
const manifest = JSON.parse(await readFile(manifestFile, "utf8"));
|
|
1795
|
+
const homeComponents = [...new Map(plan.contentBindings
|
|
1796
|
+
.flatMap((binding) => binding.componentDefinition ? [[binding.componentDefinition.key, binding.componentDefinition]] : [])).values()];
|
|
449
1797
|
manifest.entry = "src/theme.tsx";
|
|
450
1798
|
manifest.styles = ["src/styles/theme.css"];
|
|
451
1799
|
manifest.presentation = {
|
|
@@ -472,6 +1820,7 @@ export async function generateMigratedTheme(plan, directory) {
|
|
|
472
1820
|
containerWidth: plan.tokens.containerWidth,
|
|
473
1821
|
borderRadius: plan.tokens.borderRadius,
|
|
474
1822
|
},
|
|
1823
|
+
...(homeComponents.length ? { homeComponents } : {}),
|
|
475
1824
|
};
|
|
476
1825
|
await writeFile(manifestFile, `${JSON.stringify(manifest, null, 2)}\n`, "utf8");
|
|
477
1826
|
const selectedComponents = {};
|
|
@@ -487,8 +1836,15 @@ export async function generateMigratedTheme(plan, directory) {
|
|
|
487
1836
|
sourceRoots: plan.analysis.sourceRoots,
|
|
488
1837
|
componentsAnalyzed: plan.analysis.components.length,
|
|
489
1838
|
selectedComponents,
|
|
490
|
-
|
|
491
|
-
|
|
1839
|
+
contentBindings: plan.contentBindings.map(({ classes: _classes, ...binding }) => binding),
|
|
1840
|
+
assetsCopied: fidelity.copiedAssets + copiedAssets.length,
|
|
1841
|
+
styleFilesPreserved: new Set([
|
|
1842
|
+
...plan.styles.map((style) => style.file),
|
|
1843
|
+
...plan.analysis.sourceGraph.modules.filter((module) => module.kind === "STYLE").map((module) => module.file),
|
|
1844
|
+
]).size,
|
|
1845
|
+
sourceFilesPreserved: fidelity.copiedFiles,
|
|
1846
|
+
entrypoint: plan.analysis.sourceGraph.entrypoint,
|
|
1847
|
+
dependencies: plan.analysis.sourceGraph.dependencies,
|
|
492
1848
|
tailwind: plan.analysis.tailwind,
|
|
493
1849
|
ignoredFiles: plan.analysis.ignoredFiles,
|
|
494
1850
|
warnings: [...new Set(plan.warnings)],
|