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

[sitecore-jss-angular] Angular placeholder support for SXA components #1870

Merged
merged 4 commits into from
Aug 1, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ Our versioning strategy is as follows:
* `[create-sitecore-jss]` Rework Angular initializer to support XMCloud and SXP journeys ([#1845](https://github.com/Sitecore/jss/pull/1845))([#1858](https://github.com/Sitecore/jss/pull/1858))
* `[create-sitecore-jss]` Allows proxy apps to be installed alongside main apps ([#1858](https://github.com/Sitecore/jss/pull/1858))
* `nodeAppDestination` arg can be passed into `create-sitecore-jss` command to define path for proxy to be installed in
* `[sitecore-jss-angular]` Angular placeholder now supports SXA components ([#1870](https://github.com/Sitecore/jss/pull/1870))

### 🛠 Breaking Change

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,13 @@
import { Component, DebugElement, EventEmitter, Injectable, Input, Output } from '@angular/core';
import {
Component,
DebugElement,
EventEmitter,
Injectable,
Input,
Output,
TemplateRef,
ViewChild,
} from '@angular/core';
import { Router } from '@angular/router';
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
import { Location } from '@angular/common';
Expand All @@ -10,6 +19,9 @@ import { convertedData as eeData } from '../test-data/ee-data';
import {
convertedDevData as nonEeDevData,
convertedLayoutServiceData as nonEeLsData,
sxaRenderingData,
sxaRenderingDynamicPlaceholderData,
sxaRenderingDoubleDigitDynamicPlaceholderData,
} from '../test-data/non-ee-data';
import { LazyComponent } from '../test-data/lazy-loading/lazy-component.component';
import { JssCanActivate, JssCanActivateFn, JssResolve } from '../services/placeholder.token';
Expand Down Expand Up @@ -675,3 +687,160 @@ describe('<sc-placeholder /> with lazy loaded modules', () => {
});
});
});

@Component({
selector: 'test-rich-text',
template: `
<ng-template #default>
<span class="default">Rich text</span>
</ng-template>

<ng-template #withTitle>
<div class="title" *scText="rendering.fields.Title"></div>
<div class="text" *scText="rendering.fields.Text"></div>
</ng-template>

<div class="rendering-variant {{ rendering.params.styles }}">
<ng-container [ngTemplateOutlet]="variant"></ng-container>
</div>
`,
})
class TestRichTextComponent {
@Input() rendering: ComponentRendering;
@ViewChild('default', { static: true }) defaultVariant: TemplateRef<any>;
@ViewChild('withTitle', { static: true }) withTitleVariant: TemplateRef<any>;
public get variant(): TemplateRef<any> {
return this.rendering.params?.FieldNames === 'WithTitle'
? this.withTitleVariant
: this.defaultVariant;
}
}

describe('SXA components', () => {
let fixture: ComponentFixture<TestPlaceholderComponent>;
let de: DebugElement;
let comp: TestPlaceholderComponent;

beforeEach(
waitForAsync(() => {
TestBed.configureTestingModule({
declarations: [TestPlaceholderComponent, TestRichTextComponent],
imports: [
RouterTestingModule,
JssModule.withComponents([{ name: 'RichText', type: TestRichTextComponent }]),
],
providers: [],
});

fixture = TestBed.createComponent(TestPlaceholderComponent);
de = fixture.debugElement;

comp = fixture.componentInstance;
fixture.detectChanges();
})
);

it(
'should render',
waitForAsync(async () => {
const component = sxaRenderingData.sitecore.route;
const phKey = 'main';
comp.name = phKey;
comp.rendering = (component as unknown) as ComponentRendering;
fixture.detectChanges();

await fixture.whenStable();
fixture.detectChanges();

expect(de.children.length).toBe(1);

const richText = de.query(By.directive(TestRichTextComponent));
expect(richText).not.toBeNull();
expect(richText.nativeElement.innerHTML).toContain('rendering-variant');

const container = de.query(By.css('.rendering-variant'));
expect(container).not.toBeNull();
expect(container.attributes.class).toEqual(
'col-9|col-sm-10|col-md-12|col-lg-6|col-xl-7|col-xxl-8 rendering-variant test-css-class-x'
);

const title = de.query(By.css('.title'));
expect(title).not.toBeNull();
expect(title.nativeElement.innerHTML).toEqual('Rich Text Rendering Variant');

const text = de.query(By.css('.text'));
expect(text).not.toBeNull();
expect(text.nativeElement.innerHTML).toEqual('Test RichText');
})
);

it(
'should render another rendering variant',
waitForAsync(async () => {
const component = sxaRenderingData.sitecore.route;
const phKey = 'main-second';
comp.name = phKey;
comp.rendering = (component as unknown) as ComponentRendering;
fixture.detectChanges();

await fixture.whenStable();
fixture.detectChanges();

expect(de.children.length).toBe(1);

const richText = de.query(By.directive(TestRichTextComponent));
expect(richText).not.toBeNull();
expect(richText.nativeElement.innerHTML).toContain('rendering-variant');

const container = de.query(By.css('.rendering-variant'));
expect(container).not.toBeNull();
expect(container.attributes.class).toEqual(
'col-9|col-sm-10|col-md-12|col-lg-6|col-xl-7|col-xxl-8 rendering-variant test-css-class-y'
);

const span = de.query(By.css('.default'));
expect(span).not.toBeNull();
expect(span.nativeElement.innerHTML).toEqual('Rich text');
})
);

it(
'should render with container-{*} type dynamic placeholder',
waitForAsync(async () => {
const component = sxaRenderingDynamicPlaceholderData.sitecore.route;
const phKey = 'container-1';
comp.name = phKey;
comp.rendering = (component as unknown) as ComponentRendering;
fixture.detectChanges();

await fixture.whenStable();
fixture.detectChanges();

expect(de.children.length).toBe(1);

const richText = de.query(By.directive(TestRichTextComponent));
expect(richText).not.toBeNull();
expect(richText.nativeElement.innerHTML).toContain('rendering-variant');
})
);

it(
'should render with dynamic-1-{*} type dynamic placeholder',
waitForAsync(async () => {
const component = sxaRenderingDoubleDigitDynamicPlaceholderData.sitecore.route;
const phKey = 'dynamic-1-{*}';
comp.name = phKey;
comp.rendering = (component as unknown) as ComponentRendering;
fixture.detectChanges();

await fixture.whenStable();
fixture.detectChanges();

expect(de.children.length).toBe(1);

const richText = de.query(By.directive(TestRichTextComponent));
expect(richText).not.toBeNull();
expect(richText.nativeElement.innerHTML).toContain('rendering-variant');
})
);
});
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,12 @@ import {
ViewContainerRef,
} from '@angular/core';
import { Data, Router, UrlTree } from '@angular/router';
import { ComponentRendering, HtmlElementRendering } from '@sitecore-jss/sitecore-jss/layout';
import {
ComponentRendering,
HtmlElementRendering,
LayoutServiceContextData,
EditMode,
} from '@sitecore-jss/sitecore-jss/layout';
import { Observable } from 'rxjs';
import { takeWhile } from 'rxjs/operators';
import { JssCanActivateRedirectError } from '../services/jss-can-activate-error';
Expand All @@ -40,6 +45,10 @@ import {
PLACEHOLDER_MISSING_COMPONENT_COMPONENT,
} from '../services/placeholder.token';
import { constants } from '@sitecore-jss/sitecore-jss';
import {
isDynamicPlaceholder,
getDynamicPlaceholderPattern,
} from '@sitecore-jss/sitecore-jss/layout';
import { PlaceholderLoadingDirective } from './placeholder-loading.directive';
import { RenderEachDirective } from './render-each.directive';
import { RenderEmptyDirective } from './render-empty.directive';
Expand All @@ -48,10 +57,34 @@ import { isRawRendering } from './rendering';
/**
* @param {ComponentRendering} rendering
* @param {string} name
* @param {EditMode} [editMode]
*/
function getPlaceholder(rendering: ComponentRendering, name: string) {
function getPlaceholder(rendering: ComponentRendering, name: string, editMode?: EditMode) {
let phName = name.slice();

/**
* Process (SXA) dynamic placeholders
* Find and replace the matching dynamic placeholder e.g 'nameOfContainer-{*}' with the requested e.g. 'nameOfContainer-1'.
* For Metadata EditMode, we need to keep the raw placeholder name in place.
*/
rendering?.placeholders &&
Object.keys(rendering.placeholders).forEach((placeholder) => {
const patternPlaceholder = isDynamicPlaceholder(placeholder)
? getDynamicPlaceholderPattern(placeholder)
: null;

if (patternPlaceholder && patternPlaceholder.test(phName)) {
if (editMode === EditMode.Metadata) {
phName = placeholder;
} else {
rendering.placeholders![phName] = rendering.placeholders![placeholder];
delete rendering.placeholders![placeholder];
}
}
});

if (rendering && rendering.placeholders && Object.keys(rendering.placeholders).length > 0) {
return rendering.placeholders[name];
return rendering.placeholders[phName];
}
return null;
}
Expand All @@ -77,6 +110,7 @@ export class PlaceholderComponent implements OnInit, OnChanges, DoCheck, OnDestr
@Input() renderings?: Array<ComponentRendering | HtmlElementRendering>;
@Input() outputs: { [k: string]: (eventType: unknown) => void };
@Input() clientOnly = false;
@Input() sitecore: LayoutServiceContextData;
ambrauer marked this conversation as resolved.
Show resolved Hide resolved

@Output() loaded = new EventEmitter<string | undefined>();
@Output() failed = new EventEmitter<Error>();
Expand All @@ -95,6 +129,7 @@ export class PlaceholderComponent implements OnInit, OnChanges, DoCheck, OnDestr
private _componentInstances: { [prop: string]: unknown }[] = [];
private destroyed = false;
private parentStyleAttribute = '';
private editMode?: EditMode = undefined;

constructor(
private differs: KeyValueDiffers,
Expand Down Expand Up @@ -144,6 +179,7 @@ export class PlaceholderComponent implements OnInit, OnChanges, DoCheck, OnDestr
if (changes.rendering || changes.renderings) {
this._render();
}
this.editMode = this.sitecore?.context?.editMode;
}

ngDoCheck() {
Expand Down Expand Up @@ -208,7 +244,8 @@ export class PlaceholderComponent implements OnInit, OnChanges, DoCheck, OnDestr
return;
}

const placeholder = this.renderings || getPlaceholder(this.rendering, this.name || '');
const placeholder =
this.renderings || getPlaceholder(this.rendering, this.name || '', this.editMode);

if (!placeholder) {
console.warn(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ export class JssComponentFactoryService {

if (loadedComponent) {
return Promise.resolve({
componentDefinition: component,
componentDefinition: this.applySXAParams(component),
componentImplementation: loadedComponent.type,
canActivate: loadedComponent.canActivate,
resolve: loadedComponent.resolve,
Expand Down Expand Up @@ -85,7 +85,7 @@ export class JssComponentFactoryService {
}

return {
componentDefinition: component,
componentDefinition: this.applySXAParams(component),
componentImplementation: componentType,
componentModuleRef: moduleRef,
canActivate: lazyComponent.canActivate,
Expand Down Expand Up @@ -116,4 +116,21 @@ export class JssComponentFactoryService {
componentDefinition: component,
});
}

private applySXAParams(rendering: ComponentRendering) {
if (!rendering.params?.FieldNames) {
// Not SXA component
return rendering;
}
// Provide aggregated SXA styles on params 'styles'
const styles = [];
if (rendering.params.GridParameters) {
styles.push(rendering.params.GridParameters);
}
if (rendering.params.Styles) {
styles.push(rendering.params.Styles);
}
rendering.params.styles = styles.join(' ');
return rendering;
}
}
Loading
Loading