Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(scaffold): update VE template generation #563

Merged
merged 4 commits into from
Jan 21, 2025
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 24 additions & 17 deletions packages/pages/src/scaffold/template/generate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,22 +27,27 @@ export const generateTemplate = async (
validateTemplateName(templateName, projectStructure) ||
"Please ensure the name provided isn't already used and is valid.",
},
// TODO: Add this back when hybrid VE templates are supported
// {
// type: "confirm",
// name: "isVisualEditor",
// message: "Is this a Visual Editor template?",
// initial: true,
// },
{
type: "confirm",
name: "isVisualEditor",
message: "Is this a Visual Editor template?",
initial: true,
},
{
type: (prev) => (prev ? null : "toggle"),
// type: (prev) => (prev ? null : "toggle"),
type: "toggle",
name: "isDynamic",
message: "Is this a static or dynamic template?",
initial: true,
active: "Dynamic",
inactive: "Static",
},
];

const entityScopeQuestions: PromptObject[] = [
{
type: (prev) => (prev ? "select" : null),
type: "select",
name: "entityScope",
message:
"How would you like you to define the entity scope for your template?",
Expand Down Expand Up @@ -83,9 +88,15 @@ export const generateTemplate = async (
if (response.isVisualEditor) {
await generateVETemplate(response, projectStructure);
} else {
response.isDynamic
? await generateDynamicTemplate(response, projectStructure)
: await generateStaticTemplate(response.templateName, projectStructure);
if (response.isDynamic) {
const subsequentResponse = await prompts(entityScopeQuestions);
await generateDynamicTemplate(
{ ...response, ...subsequentResponse },
projectStructure
);
} else {
await generateStaticTemplate(response.templateName, projectStructure);
}
}
};

Expand Down Expand Up @@ -140,11 +151,7 @@ const generateVETemplate = async (

fs.writeFileSync(
path.join(templatePath, `${templateFileName}.tsx`),
visualEditorTemplateCode(
templateFileName,
response.entityScope,
response.filter
)
visualEditorTemplateCode(templateFileName)
);
addVETemplateToConfig(templateFileName, projectStructure);

Expand Down Expand Up @@ -174,7 +181,7 @@ const addVEDependencies = async () => {
await updatePackageDependency("@yext/visual-editor", null, true);
await updatePackageDependency(
"@measured/puck",
"0.16.0-canary.39e7f40",
{ specificVersion: "0.17.1" },
true
);
await installDependencies();
Expand Down
41 changes: 13 additions & 28 deletions packages/pages/src/scaffold/template/sampleTemplates.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,14 @@ import {
visualEditorTemplateCode,
} from "./sampleTemplates.js";
import fs from "node:fs";
import { Project } from "ts-morph";
import { Diagnostic, Project, ts } from "ts-morph";

const filterOutModuleErrors = (d: Diagnostic<ts.Diagnostic>) => {
return (
!d.getMessageText().toString().includes("Cannot find module") &&
!d.getMessageText().toString().includes("Cannot use JSX")
);
};

describe("newConfigFile", () => {
it("confirm returned code has no warnings", () => {
Expand All @@ -19,13 +26,7 @@ describe("newConfigFile", () => {
project.addSourceFileAtPath(filePath);
const diagnostics = project
.getPreEmitDiagnostics()
.filter(
(d) =>
!d
.getMessageText()
.toString()
.includes("Cannot find module '@measured/puck'")
);
.filter(filterOutModuleErrors);
expect(diagnostics.length).toBe(0);
} finally {
if (fs.existsSync("test.tsx")) {
Expand All @@ -37,11 +38,7 @@ describe("newConfigFile", () => {

describe("visualEditorTemplateCode", () => {
it("confirm returned code has no warnings", () => {
const fileContent = visualEditorTemplateCode(
"testTemplate",
"entityTypes",
["location"]
);
const fileContent = visualEditorTemplateCode("testTemplate");
const filePath = "test.tsx";

try {
Expand All @@ -50,11 +47,7 @@ describe("visualEditorTemplateCode", () => {
project.addSourceFileAtPath(filePath);
const diagnostics = project
.getPreEmitDiagnostics()
.filter(
(d) =>
!d.getMessageText().toString().includes("Cannot find module") &&
!d.getMessageText().toString().includes("Cannot use JSX")
);
.filter(filterOutModuleErrors);
expect(diagnostics.length).toBe(0);
} finally {
if (fs.existsSync("test.tsx")) {
Expand All @@ -75,11 +68,7 @@ describe("staticTemplate", () => {
project.addSourceFileAtPath(filePath);
const diagnostics = project
.getPreEmitDiagnostics()
.filter(
(d) =>
!d.getMessageText().toString().includes("Cannot find module") &&
!d.getMessageText().toString().includes("Cannot use JSX")
);
.filter(filterOutModuleErrors);
expect(diagnostics.length).toBe(0);
} finally {
if (fs.existsSync("test.tsx")) {
Expand All @@ -102,11 +91,7 @@ describe("dynamicTemplate", () => {
project.addSourceFileAtPath(filePath);
const diagnostics = project
.getPreEmitDiagnostics()
.filter(
(d) =>
!d.getMessageText().toString().includes("Cannot find module") &&
!d.getMessageText().toString().includes("Cannot use JSX")
);
.filter(filterOutModuleErrors);
expect(diagnostics.length).toBe(0);
} finally {
if (fs.existsSync("test.tsx")) {
Expand Down
93 changes: 46 additions & 47 deletions packages/pages/src/scaffold/template/sampleTemplates.ts
Original file line number Diff line number Diff line change
@@ -1,74 +1,71 @@
export const visualEditorTemplateCode = (
templateName: string,
entityScope: string,
filter: string[]
): string => {
export const visualEditorTemplateCode = (templateName: string): string => {
const formattedTemplateName =
templateName.charAt(0).toUpperCase() + templateName.slice(1);
const filterCode = `${entityScope}: ${JSON.stringify(filter)},`;
const config = `${templateName}Config`;

return `import {
return `import "@yext/visual-editor/style.css";
import {
Template,
GetPath,
TemplateConfig,
TemplateProps,
TemplateRenderProps,
GetHeadConfig,
HeadConfig,
} from "@yext/pages";
import { Config, Render } from "@measured/puck";
import { Render } from "@measured/puck";
import { ${config} } from "../ve.config";
import { DocumentProvider } from "@yext/pages/util";
import { resolveVisualEditorData } from "@yext/visual-editor";

export const config: TemplateConfig = {
name: "${templateName}",
stream: {
$id: "${templateName}-stream",
filter: {
${filterCode}
},
fields: [
"id",
"name",
"slug",
"c_visualConfigurations",
"c_pages_layouts.c_visualConfiguration",
],
localization: {
locales: ["en"],
},
},
additionalProperties: {
isVETemplate: true,
}
};

export const transformProps = async (data: TemplateRenderProps) => {
return resolveVisualEditorData(data, "${templateName}");
};
import { applyTheme, VisualEditorProvider } from "@yext/visual-editor";
import { themeConfig } from "../../theme.config";
import { buildSchema } from "../utils/buildSchema";
mkilpatrick marked this conversation as resolved.
Show resolved Hide resolved
import { AnalyticsProvider } from "@yext/pages-components";

export const getHeadConfig: GetHeadConfig<TemplateRenderProps> = ({
document,
}): HeadConfig => {
return {
title: document.name,
charset: "UTF-8",
viewport: "width=device-width, initial-scale=1"
viewport: "width=device-width, initial-scale=1",
tags: [
{
type: "link",
attributes: {
rel: "icon",
type: "image/x-icon",
},
},
],
other: [applyTheme(document, themeConfig), buildSchema(document)].join(
"\\n"
),
};
};

export const getPath: GetPath<TemplateProps> = ({ document }) => {
return document.slug ? document.slug : "${templateName}/" + document.id;
const localePath = document.locale !== "en" ? \`\${document.locale}/\` : "";
return document.address
? \`\${localePath}\${document.address.region}/\${document.address.city}/\${document.address.line1}-\${document.id.toString()}\`
: \`\${localePath}\${document.id.toString()}\`;
};

const ${formattedTemplateName}: Template<TemplateRenderProps> = ({ document }) => {
const { visualTemplate } = document;
const ${formattedTemplateName}: Template<TemplateRenderProps> = (props) => {
const { document } = props;
// temporary: guard for generated repo-based static page
if (!document?.__?.layout) {
mkilpatrick marked this conversation as resolved.
Show resolved Hide resolved
return <></>;
}

return (
<DocumentProvider value={document}>
<Render config={${config} as Config} data={visualTemplate} />
</DocumentProvider>
<AnalyticsProvider
// @ts-expect-error ts(2304) the api key will be populated
apiKey={YEXT_PUBLIC_EVENTS_API_KEY}
templateData={props}
currency="USD"
>
<VisualEditorProvider document={document}>
<Render config={${config}} data={JSON.parse(document.__.layout)} />
</VisualEditorProvider>
</AnalyticsProvider>
);
};

Expand Down Expand Up @@ -153,6 +150,7 @@ export const getPath: GetPath<TemplateProps> = ({ document }) => {
};

const ${formattedTemplateName}: Template<TemplateRenderProps> = ({ document }) => {
console.log(document);
return (
mkilpatrick marked this conversation as resolved.
Show resolved Hide resolved
<div>${formattedTemplateName} page</div>
);
Expand All @@ -171,6 +169,7 @@ export const staticTemplate = (templateName: string) => {
TemplateProps,
TemplateRenderProps,
GetHeadConfig,
Template,
} from "@yext/pages";

export const getPath: GetPath<TemplateProps> = () => {
Expand All @@ -185,9 +184,9 @@ export const getHeadConfig: GetHeadConfig<TemplateRenderProps> = () => {
};
};

const ${formattedTemplateName} = (data: TemplateRenderProps) => {
const ${formattedTemplateName}: Template<TemplateRenderProps> = () => {
return (
<div>${templateName} page</div>
<div>${templateName} page</div>
);
};

Expand Down
Loading