Skip to content

Commit

Permalink
[Personalize][Initializers] Move XP tracking API examples to separate…
Browse files Browse the repository at this point in the history
… add-on initializer (#980)

* [Personalize][Initializers] Move XP tracking API examples to separate add-on initializer

* add empty line

* refactoring

* use common message

* remove unused variable

* Add type

* add new line

* formatting

* Update packages/create-sitecore-jss/src/initializers/nextjs/index.ts

Co-authored-by: Adam Brauer <400763+ambrauer@users.noreply.github.com>
  • Loading branch information
illiakovalenko and ambrauer authored Apr 18, 2022
1 parent 6f3f4d0 commit 7b1babd
Show file tree
Hide file tree
Showing 21 changed files with 596 additions and 78 deletions.
9 changes: 8 additions & 1 deletion packages/create-sitecore-jss/src/common/index.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,21 @@
export { ClientAppArgs, BaseArgs } from './args/base';
export { StyleguideArgs } from './args/styleguide';

export { ClientAppAnswer, clientAppPrompts, DEFAULT_APPNAME } from './prompts/base';
export {
ClientAppAnswer,
clientAppPrompts,
DEFAULT_APPNAME,
incompatibleAddonsMsg,
missingAddonMsg,
} from './prompts/base';
export { StyleguideAnswer, styleguidePrompts } from './prompts/styleguide';

export {
isDevEnvironment,
openPackageJson,
writePackageJson,
getBaseTemplates,
saveConfiguration,
} from './utils/helpers';

export { Initializer } from './Initializer';
Expand Down
10 changes: 10 additions & 0 deletions packages/create-sitecore-jss/src/common/prompts/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,3 +84,13 @@ export const clientAppPrompts: DistinctQuestion<ClientAppAnswer>[] = [
},
},
];

export const missingAddonMsg = (source: string, missingAddon: string) =>
chalk.yellow(
`Warning: ${source} add-on cannot be used without the ${missingAddon} add-on. This may cause unexpected results.`
);

export const incompatibleAddonsMsg = (source: string, incompatibleAddon: string) =>
chalk.yellow(
`Warning: ${source} add-on is not compatible with ${incompatibleAddon} add-on. This may cause unexpected results.`
);
25 changes: 25 additions & 0 deletions packages/create-sitecore-jss/src/common/utils/helpers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
sortKeys,
getBaseTemplates,
getAppPrefix,
saveConfiguration,
} from './helpers';
import { JsonObjectType } from '../processes/transform';
import testPackage from '../test-data/test.package.json';
Expand Down Expand Up @@ -140,6 +141,30 @@ describe('helpers', () => {
});
});

describe('saveConfiguration', () => {
let log: SinonStub;
let writeFileSync: SinonStub;

afterEach(() => {
log?.restore();
writeFileSync?.restore();
});

it('should save configuration', () => {
writeFileSync = sinon.stub(fs, 'writeFileSync');
const pkgPath = path.resolve('src', 'common', 'test-data', 'test.package.json');
const pkg = openPackageJson(pkgPath);
const templates = ['nextjs', 'nextjs-styleguide'];

saveConfiguration(templates, pkgPath);

expect(writeFileSync.calledOnce).to.equal(true);
expect(writeFileSync.getCall(0).args[1]).to.equal(
JSON.stringify({ ...pkg, config: { ...pkg.config, templates } }, null, 2)
);
});
});

describe('sortKeys', () => {
it('should sort the keys of an object alphabetically', () => {
const obj: JsonObjectType = {
Expand Down
11 changes: 11 additions & 0 deletions packages/create-sitecore-jss/src/common/utils/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,17 @@ export const writePackageJson = (data: { [key: string]: unknown }, pkgPath?: str
}
};

/**
* Save configuration params to the package.json
* @param {string[]} templates templates applied to the sample
* @param {string} [pkgPath] path to the package.json
*/
export const saveConfiguration = (templates: string[], pkgPath?: string) => {
const pkg = openPackageJson(pkgPath);

writePackageJson({ ...pkg, config: { ...pkg.config, templates } }, pkgPath);
};

export const sortKeys = (obj: JsonObjectType) => {
const sorted: any = {};
Object.keys(obj)
Expand Down
2 changes: 1 addition & 1 deletion packages/create-sitecore-jss/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ const main = async () => {
}

try {
await initRunner(templates, { ...argv, destination, templates });
await initRunner(templates.slice(), { ...argv, destination, templates });
} catch (error) {
console.log(chalk.red('An error occurred: ', error));
process.exit(1);
Expand Down
10 changes: 9 additions & 1 deletion packages/create-sitecore-jss/src/init-runner.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import chalk from 'chalk';
import { installPackages, lintFix, nextSteps, BaseArgs } from './common';
import path, { sep } from 'path';
import { installPackages, lintFix, nextSteps, BaseArgs, saveConfiguration } from './common';
import { InitializerFactory } from './InitializerFactory';

export const initRunner = async (initializers: string[], args: BaseArgs) => {
Expand All @@ -22,13 +23,20 @@ export const initRunner = async (initializers: string[], args: BaseArgs) => {

// process any returned initializers
if (response.initializers && response.initializers.length > 0) {
// provide info for addons to see other addons used.
// add-ons will not have information about the initial
// list of templates, as it has `nextjs` initializer for example
args.templates.push(...response.initializers);

await runner(response.initializers);
}
}
};

await runner(initializers);

saveConfiguration(args.templates, path.resolve(`${args.destination}${sep}package.json`));

// final steps (install, lint, etc)
if (!args.noInstall) {
installPackages(args.destination, args.silent);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
transform,
DEFAULT_APPNAME,
ClientAppArgs,
incompatibleAddonsMsg,
} from '../../common';

export default class NextjsPersonalizeInitializer implements Initializer {
Expand All @@ -28,6 +29,13 @@ export default class NextjsPersonalizeInitializer implements Initializer {

await transform(templatePath, mergedArgs);

if (
args.templates.includes('nextjs-styleguide-tracking') ||
pkg.config?.templates?.includes('nextjs-styleguide-tracking')
) {
console.log(incompatibleAddonsMsg('nextjs-personalize', 'nextjs-styleguide-tracking'));
}

const response = {
nextSteps: [],
appName: mergedArgs.appName,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import path, { sep } from 'path';
import {
Initializer,
openPackageJson,
transform,
DEFAULT_APPNAME,
ClientAppArgs,
missingAddonMsg,
incompatibleAddonsMsg,
} from '../../common';

export default class NextjsStyleguideInitializer implements Initializer {
get isBase(): boolean {
return false;
}

async init(args: ClientAppArgs) {
const pkg = openPackageJson(`${args.destination}${sep}package.json`);

const mergedArgs = {
...args,
appName: args.appName || pkg?.config?.appName || DEFAULT_APPNAME,
appPrefix: args.appPrefix || pkg?.config?.prefix || false,
};

const templatePath = path.resolve(__dirname, '../../templates/nextjs-styleguide-tracking');

await transform(templatePath, mergedArgs);

if (
!args.templates.includes('nextjs-styleguide') &&
!pkg.config?.templates?.includes('nextjs-styleguide')
) {
console.log(missingAddonMsg('nextjs-styleguide-tracking', 'nextjs-styleguide'));
}

if (
args.templates.includes('nextjs-personalize') ||
pkg.config?.templates?.includes('nextjs-personalize')
) {
console.log(incompatibleAddonsMsg('nextjs-styleguide-tracking', 'nextjs-personalize'));
}

const response = {
nextSteps: [],
appName: mergedArgs.appName,
};

return response;
}
}
15 changes: 11 additions & 4 deletions packages/create-sitecore-jss/src/initializers/nextjs/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import chalk from 'chalk';
import path, { sep } from 'path';
import { prompt } from 'inquirer';
import { prompts, NextjsAnswer } from './prompts';
import inquirer, { prompt } from 'inquirer';
import { prompts, NextjsAnswer, NextjsCheckbox } from './prompts';
import {
Initializer,
transform,
Expand All @@ -12,6 +12,8 @@ import {
import { removeDevDependencies } from './remove-dev-dependencies';
import { NextjsArgs } from './args';

inquirer.registerPrompt('nextjs-checkbox', NextjsCheckbox);

export default class NextjsInitializer implements Initializer {
get isBase(): boolean {
return true;
Expand All @@ -20,7 +22,9 @@ export default class NextjsInitializer implements Initializer {
async init(args: NextjsArgs) {
const answers = await prompt<NextjsAnswer>(prompts, args);

const pkgPath = path.resolve(`${answers.destination}${sep}package.json`);
const templatePath = path.resolve(__dirname, '../../templates/nextjs');

await transform(templatePath, { ...args, ...answers });

if (!isDevEnvironment(args.destination)) {
Expand All @@ -33,7 +37,7 @@ export default class NextjsInitializer implements Initializer {
// multiple via --templates (assume they know what they're doing)
if (!args.yes && args.templates.length === 1) {
const addInitAnswer = await prompt({
type: 'checkbox',
type: 'nextjs-checkbox' as 'checkbox',
name: 'addInitializers',
message: 'Would you like to include any add-on initializers?',
choices: [
Expand All @@ -42,6 +46,10 @@ export default class NextjsInitializer implements Initializer {
'nextjs-styleguide - Includes example components and setup for working disconnected',
value: 'nextjs-styleguide',
},
{
name: 'nextjs-styleguide-tracking - Includes example (Sitecore XP) tracking component',
value: 'nextjs-styleguide-tracking',
},
{
name: 'nextjs-sxa - Includes example components and setup for working using SXA',
value: 'nextjs-sxa',
Expand All @@ -60,7 +68,6 @@ export default class NextjsInitializer implements Initializer {
!addInitializers.includes('nextjs-styleguide') &&
!args.templates.includes('nextjs-styleguide')
) {
const pkgPath = path.resolve(`${answers.destination}${sep}package.json`);
const pkg = openPackageJson(pkgPath);

pkg.scripts.bootstrap = pkg.scripts.bootstrap.replace(' && graphql-let', '');
Expand Down
28 changes: 27 additions & 1 deletion packages/create-sitecore-jss/src/initializers/nextjs/prompts.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { QuestionCollection } from 'inquirer';
import CheckboxPrompt from 'inquirer/lib/prompts/checkbox';

import { clientAppPrompts, ClientAppAnswer } from '../../common';
import { clientAppPrompts, ClientAppAnswer, incompatibleAddonsMsg } from '../../common';

export enum Prerender {
SSG = 'SSG',
Expand Down Expand Up @@ -29,3 +30,28 @@ export const prompts: QuestionCollection<NextjsAnswer> = [
},
},
];

/**
* Custom `inquirer` control to support error messages
*/
export class NextjsCheckbox extends CheckboxPrompt {
onSpaceKey() {
super.onSpaceKey();

const isSelected = (initializer: string) =>
this.opt.choices.choices.find((ch) => {
const { value, checked } = ch as { [key: string]: unknown };

return value === initializer && checked;
});

const isPersonalizeSelected = isSelected('nextjs-personalize');
const isTrackingSelected = isSelected('nextjs-styleguide-tracking');

if (isPersonalizeSelected && isTrackingSelected) {
this.onError({
isValid: incompatibleAddonsMsg('nextjs-styleguide-tracking', 'nextjs-personalize'),
});
}
}
}

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import CdpIntegrationScript from 'components/CdpIntegrationScript';

const Scripts = (): JSX.Element => {
return (
<>
<CdpIntegrationScript />
</>
);
};

export default Scripts;
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
styleguide-sample: This is a dictionary entry in English as a demonstration
Documentation: Documentation
Styleguide: Styleguide
GraphQL: GraphQL
Tracking: Tracking
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
fields:
pageTitle: Styleguide Tracking | Sitecore JSS
placeholders:
<%- helper.getAppPrefix(appPrefix, appName) %>jss-main:
- componentName: Styleguide-Tracking
fields:
heading: Tracking
description: <p><small>JSS supports tracking Sitecore analytics events from within apps. Give it a try with this handy interactive demo.</small></p>
Loading

0 comments on commit 7b1babd

Please sign in to comment.