Componentes de contêiner editáveis

IMPORTANT
O editor de SPA foi descontinuado para novos projetos. Ele continuará funcionando com projetos existentes da Adobe, mas não deve ser usado para novos projetos. Os editores preferidos para gerenciar conteúdo headless no AEM agora são:

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!

Editable container components

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 ResponsiveGrid component
  • 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:

  1. Open and edit react-app/src/components/Home.js

  2. Import the ResponsiveGrid component from @adobe/aem-react-editable-components and add it to the Home component.

  3. Set the following attributes on the <ResponsiveGrid...> component

    1. pagePath = '/content/wknd-app/us/en/home'
    2. itemPath = 'root/responsivegrid'

    This instructs the ResponsiveGrid component to retrieve its content from the AEM resource:

    1. /content/wknd-app/us/en/home/jcr:content/root/responsivegrid

    The itemPath maps to the responsivegrid node defined in the Remote SPA Page AEM Template and is automatically created on new AEM Pages created from the Remote SPA Page AEM Template.

    Update Home.js to 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:

Home.js

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

  1. Abra o projeto SPA no IDE

  2. Criar um componente React em src/components/editable/core/Text.js

  3. Adicionar o seguinte código a Text.js

    code 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;
    }
    
  4. Criar um componente editável do React em src/components/editable/EditableText.js

  5. Adicionar o seguinte código a EditableText.js

    code 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 texto editável

Componente de imagem

  1. Abra o projeto SPA no IDE

  2. Criar um componente React em src/components/editable/core/Image.js

  3. Adicionar o seguinte código a Image.js

    code 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>
        )
    };
    
  4. Criar um componente editável do React em src/components/editable/EditableImage.js

  5. 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;
  1. Crie um arquivo SCSS src/components/editable/EditableImage.scss que forneça estilos personalizados para o EditableImage.scss. Esses estilos têm como alvo as classes CSS do componente React editável.

  2. Adicionar o SCSS a seguir a EditableImage.scss

    code language-css
    .cmp-image__image {
        margin: 1rem 0;
        width: 100%;
        border: 0;
     }
    
  3. Importar EditableImage.scss em EditableImage.js

    code language-javascript
    ...
    import './EditableImage.scss';
    ...
    

A implementação do componente de Imagem editável deve ser semelhante a:

Componente de imagem editável

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

  1. Abra o projeto SPA no IDE

  2. Abra o arquivo src/Home.js

  3. Adicionar instruções de importação para AEMText e AEMImage

    code 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:

Home.js

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:

  • EditableTitle mapeado para wknd-app/components/title
  • EditableText mapeado para wknd-app/components/text
  • EditableImage mapeado para wknd-app/components/image

Para configurar o contêiner reponsivegrid do modelo da Página do SPA Remoto:

  1. Faça logon no AEM Author

  2. Navegue até Ferramentas > Geral > Modelos > Aplicativo WKND

  3. Editar Página de SPA do Relatório

    Políticas de Grade Responsivas

  4. Selecione Estrutura no alternador de modo na parte superior direita

  5. Toque para selecionar o Contêiner de layout

  6. Toque no ícone Política na barra pop-up

    Políticas de Grade Responsivas

  7. À direita, na guia Componentes Permitidos, expanda o APLICATIVO WKND - CONTEÚDO

  8. Certifique-se de que apenas os seguintes sejam selecionados:

    1. Imagem
    2. Texto
    3. Título

    Página do SPA Remoto

  9. 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.

  1. Faça logon no AEM Author

  2. Navigate to Sites > WKND App

  3. Tap Home and select Edit from the top action bar

    1. A "Hello World" Text component displays, as this was automatically added when generating the project from the AEM Project archetype
  4. Select Edit from the mode-selector in the top right of the Page Editor

  5. Locate the Layout Container editable area beneath the Title

  6. Open the Page Editor's side bar, and select the Components view

  7. Drag the following components into the Layout Container

    1. Imagem
    2. Título
  8. Drag the components to reorder them to the following order:

    1. Título
    2. Imagem
    3. Texto
  9. Author the Title component

    1. Tap the Title component, and tap the wrench icon to edit the Title component

    2. Add the following text:

      1. Title: Summer is coming, let's make the most of it!
      2. Type: H1
    3. Toque em Concluído

  10. Author the Image component

    1. Drag an image in from the Side bar (after switching to the Assets view) on the Image component
    2. Tap the Image component, and tap the wrench icon to edit
    3. Check the Image is decorative checkbox
    4. Toque em Concluído
  11. Author the Text component

    1. Edit the Text component by tapping the Text component, and tapping the wrench icon
    2. Add the following text:
      1. 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!
    3. Toque em Concluído
  12. Seus componentes agora foram criados, mas são empilhados verticalmente.

    Componentes criados

    Use o Modo de layout do AEM para permitir que ajustemos o tamanho e o layout dos componentes.

  13. Alternar para Modo de layout usando o seletor de modo no canto superior direito

  14. Redimensionar os componentes Imagem e Texto, de forma que fiquem lado a lado

    1. O componente Imagem deve ter 8 colunas de largura
    2. O componente Texto deve ter 3 colunas

    Componentes de layout

  15. Visualizar suas alterações no Editor de páginas do AEM

  16. Atualize o Aplicativo WKND em execução localmente em http://localhost:3000 para ver as alterações criadas!

    Componente de contêiner em SPA

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 ResponsiveGrid do 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.

recommendation-more-help
e25b6834-e87f-4ff3-ba56-4cd16cdfdec4