Componentes de contêiner editáveis
- O editor universal para editar conteúdo headless visualmente.
- O editor de fragmentos de conteúdo para editar conteúdo headless com base em formulários.
Fixed components provide some flexibility for authoring SPA content, however this approach is rigid and requires developers to define the exact composition of the editable content. To support the creation of exceptional experiences by authors, SPA Editor supports the use of container components in the SPA. Container components allow authors to drag and drop allowed components into the container, and author them, just like they can in traditional AEM Sites authoring!
In this chapter, we add an editable container to the home view allowing authors to compose and layout rich content experiences using Editable React components directly in the SPA.
Update the WKND App
To add a container component to the Home view:
- Import the AEM React Editable Component's
ResponsiveGridcomponent - Import and register custom Editable React Components (Text and Image) for use in the ResponsiveGrid component
Use the ResponsiveGrid component
To add an editable area to the Home view:
-
Open and edit
react-app/src/components/Home.js -
Import the
ResponsiveGridcomponent from@adobe/aem-react-editable-componentsand add it to theHomecomponent. -
Set the following attributes on the
<ResponsiveGrid...>componentpagePath = '/content/wknd-app/us/en/home'itemPath = 'root/responsivegrid'
This instructs the
ResponsiveGridcomponent to retrieve its content from the AEM resource:/content/wknd-app/us/en/home/jcr:content/root/responsivegrid
The
itemPathmaps to theresponsivegridnode defined in theRemote SPA PageAEM Template and is automatically created on new AEM Pages created from theRemote SPA PageAEM Template.Update
Home.jsto add the<ResponsiveGrid...>component.code language-javascript ... import { ResponsiveGrid } from '@adobe/aem-react-editable-components'; ... function Home() { return ( <div className="Home"> <ResponsiveGrid pagePath='/content/wknd-app/us/en/home' itemPath='root/responsivegrid'/> <EditableTitle pagePath='/content/wknd-app/us/en/home' itemPath='title'/> <Adventures /> </div> ); }
The Home.js file should look like:
Create editable components
To get the full effect of the flexible authoring experience containers provide in SPA Editor. We've already create an editable Title component, but let's make a few more that allow authors to use editable Text and Image components in the newly added ResponsiveGrid component.
Os novos componentes editáveis Texto e Imagem React são criados usando o padrão de definição do componente editável exportado em componentes editáveis fixos.
Componente de texto editável
-
Abra o projeto SPA no IDE
-
Criar um componente React em
src/components/editable/core/Text.js -
Adicionar o seguinte código a
Text.jscode language-javascript import React from 'react' const TextPlain = (props) => <div className={props.baseCssClass}><p className="cmp-text__paragraph">{props.text}</p></div>; const TextRich = (props) => { const text = props.text; const id = (props.id) ? props.id : (props.cqPath ? props.cqPath.substr(props.cqPath.lastIndexOf('/') + 1) : ""); return <div className={props.baseCssClass} id={id} data-rte-editelement dangerouslySetInnerHTML={{ __html: text }} /> }; export const Text = (props) => { if (!props.baseCssClass) { props.baseCssClass = 'cmp-text' } const { richText = false } = props return richText ? <TextRich {...props} /> : <TextPlain {...props} /> } export function textIsEmpty(props) { return props.text == null || props.text.length === 0; } -
Criar um componente editável do React em
src/components/editable/EditableText.js -
Adicionar o seguinte código a
EditableText.jscode language-javascript import React from 'react' import { EditableComponent, MapTo } from '@adobe/aem-react-editable-components'; import { Text, textIsEmpty } from "./core/Text"; import { withConditionalPlaceHolder } from "./core/util/withConditionalPlaceholder"; import { withStandardBaseCssClass } from "./core/util/withStandardBaseCssClass"; const RESOURCE_TYPE = "wknd-app/components/text"; const EditConfig = { emptyLabel: "Text", isEmpty: textIsEmpty, resourceType: RESOURCE_TYPE }; export const WrappedText = (props) => { const Wrapped = withConditionalPlaceHolder(withStandardBaseCssClass(Text, "cmp-text"), textIsEmpty, "Text V2") return <Wrapped {...props} /> }; const EditableText = (props) => <EditableComponent config={EditConfig} {...props}><WrappedText /></EditableComponent> MapTo(RESOURCE_TYPE)(EditableText); export default EditableText;
A implementação do componente de Texto editável deve ser semelhante a:
Componente de imagem
-
Abra o projeto SPA no IDE
-
Criar um componente React em
src/components/editable/core/Image.js -
Adicionar o seguinte código a
Image.jscode language-javascript import React from 'react' import { RoutedLink } from "./RoutedLink"; export const imageIsEmpty = (props) => (!props.src) || props.src.trim().length === 0 const ImageInnerContents = (props) => { return (<> <img src={props.src} className={props.baseCssClass + '__image'} alt={props.alt} /> { !!(props.title) && <span className={props.baseCssClass + '__title'} itemProp="caption">{props.title}</span> } { props.displayPopupTitle && (!!props.title) && <meta itemProp="caption" content={props.title} /> } </>); }; const ImageContents = (props) => { if (props.link && props.link.trim().length > 0) { return ( <RoutedLink className={props.baseCssClass + '__link'} isRouted={props.routed} to={props.link}> <ImageInnerContents {...props} /> </RoutedLink> ) } return <ImageInnerContents {...props} /> }; export const Image = (props) => { if (!props.baseCssClass) { props.baseCssClass = 'cmp-image' } const { isInEditor = false } = props; const cssClassName = (isInEditor) ? props.baseCssClass + ' cq-dd-image' : props.baseCssClass; return ( <div className={cssClassName}> <ImageContents {...props} /> </div> ) }; -
Criar um componente editável do React em
src/components/editable/EditableImage.js -
Adicionar o seguinte código a
EditableImage.js
import { EditableComponent, MapTo } from '@adobe/aem-react-editable-components';
import { Image, imageIsEmpty } from "./core/Image";
import React from 'react'
import { withConditionalPlaceHolder } from "./core/util/withConditionalPlaceholder";
import { withStandardBaseCssClass } from "./core/util/withStandardBaseCssClass";
const RESOURCE_TYPE = "wknd-app/components/image";
const EditConfig = {
emptyLabel: "Image",
isEmpty: imageIsEmpty,
resourceType: RESOURCE_TYPE
};
const WrappedImage = (props) => {
const Wrapped = withConditionalPlaceHolder(withStandardBaseCssClass(Image, "cmp-image"), imageIsEmpty, "Image V2");
return <Wrapped {...props}/>
}
const EditableImage = (props) => <EditableComponent config={EditConfig} {...props}><WrappedImage /></EditableComponent>
MapTo(RESOURCE_TYPE)(EditableImage);
export default EditableImage;
-
Crie um arquivo SCSS
src/components/editable/EditableImage.scssque forneça estilos personalizados para oEditableImage.scss. Esses estilos têm como alvo as classes CSS do componente React editável. -
Adicionar o SCSS a seguir a
EditableImage.scsscode language-css .cmp-image__image { margin: 1rem 0; width: 100%; border: 0; } -
Importar
EditableImage.scssemEditableImage.jscode language-javascript ... import './EditableImage.scss'; ...
A implementação do componente de Imagem editável deve ser semelhante a:
Importar os componentes editáveis
Os componentes do React EditableText e EditableImage recém-criados são referenciados no SPA e são dinamicamente instanciados com base no JSON retornado pelo AEM. Para garantir que esses componentes estejam disponíveis para o SPA, crie instruções de importação para eles em Home.js
-
Abra o projeto SPA no IDE
-
Abra o arquivo
src/Home.js -
Adicionar instruções de importação para
AEMTexteAEMImagecode language-javascript ... // The following need to be imported, so that MapTo is run for the components import EditableText from './editable/EditableText'; import EditableImage from './editable/EditableImage'; ...
O resultado deve ser semelhante a:
Se essas importações forem não adicionadas, o código EditableText e EditableImage não será chamado pelo SPA e, portanto, os componentes não serão mapeados para os tipos de recursos fornecidos.
Configuração do container no AEM
Os componentes de contêiner do AEM usam políticas para ditar seus componentes permitidos. Essa é uma configuração crítica ao usar o Editor de SPA, já que somente os Componentes do AEM que têm equivalentes de componentes de SPA mapeados podem ser renderizados pelo SPA. Verifique se somente os componentes para os quais fornecemos implementações de SPA são permitidos:
EditableTitlemapeado parawknd-app/components/titleEditableTextmapeado parawknd-app/components/textEditableImagemapeado parawknd-app/components/image
Para configurar o contêiner reponsivegrid do modelo da Página do SPA Remoto:
-
Faça logon no AEM Author
-
Navegue até Ferramentas > Geral > Modelos > Aplicativo WKND
-
Editar Página de SPA do Relatório
-
Selecione Estrutura no alternador de modo na parte superior direita
-
Toque para selecionar o Contêiner de layout
-
Toque no ícone Política na barra pop-up
-
À direita, na guia Componentes Permitidos, expanda o APLICATIVO WKND - CONTEÚDO
-
Certifique-se de que apenas os seguintes sejam selecionados:
- Imagem
- Texto
- Título
-
Toque em Concluído
Criação do container no AEM
Depois que o SPA foi atualizado para incorporar o <ResponsiveGrid...>, invólucros para três componentes editáveis do React (EditableTitle, EditableText e EditableImage), e o AEM foi atualizado com uma política de Modelo correspondente, podemos começar a criar conteúdo no componente de contêiner.
-
Faça logon no AEM Author
-
Navigate to Sites > WKND App
-
Tap Home and select Edit from the top action bar
- A "Hello World" Text component displays, as this was automatically added when generating the project from the AEM Project archetype
-
Select Edit from the mode-selector in the top right of the Page Editor
-
Locate the Layout Container editable area beneath the Title
-
Open the Page Editor's side bar, and select the Components view
-
Drag the following components into the Layout Container
- Imagem
- Título
-
Drag the components to reorder them to the following order:
- Título
- Imagem
- Texto
-
Author the Title component
-
Tap the Title component, and tap the wrench icon to edit the Title component
-
Add the following text:
- Title: Summer is coming, let's make the most of it!
- Type: H1
-
Toque em Concluído
-
-
Author the Image component
- Drag an image in from the Side bar (after switching to the Assets view) on the Image component
- Tap the Image component, and tap the wrench icon to edit
- Check the Image is decorative checkbox
- Toque em Concluído
-
Author the Text component
- Edit the Text component by tapping the Text component, and tapping the wrench icon
- Add the following text:
- Right now, you can get 15% on all 1-week adventures, and 20% off on all adventures that are 2 weeks or longer! At checkout, add the campaign code SUMMERISCOMING to get your discounts!
- Toque em Concluído
-
Seus componentes agora foram criados, mas são empilhados verticalmente.
Use o Modo de layout do AEM para permitir que ajustemos o tamanho e o layout dos componentes.
-
Alternar para Modo de layout usando o seletor de modo no canto superior direito
-
Redimensionar os componentes Imagem e Texto, de forma que fiquem lado a lado
- O componente Imagem deve ter 8 colunas de largura
- O componente Texto deve ter 3 colunas
-
Visualizar suas alterações no Editor de páginas do AEM
-
Atualize o Aplicativo WKND em execução localmente em http://localhost:3000 para ver as alterações criadas!
Parabéns!
Você adicionou um componente de contêiner que permite que os componentes editáveis sejam adicionados pelos autores ao aplicativo WKND! Agora você sabe como:
- Usar o componente
ResponsiveGriddo componente editável do AEM React no SPA - Criar e registrar componentes editáveis do React (Texto e Imagem) para uso no SPA por meio do componente de contêiner
- Configure o modelo Página de SPA Remoto para permitir os componentes habilitados para SPA
- Adicionar componentes editáveis ao componente do contêiner
- Componentes de autor e layout no Editor SPA
Próximas etapas
A próxima etapa usa a mesma técnica para adicionar um componente editável a uma rota de Detalhes de Aventura no SPA.