Componentes de contenedor editables
- El Editor universal para editar contenido sin encabezado de forma visual.
- El Editor de fragmentos de contenido para la edición de contenido sin encabezado basada en formularios.
Los componentes fijos proporcionan cierta flexibilidad para la creación de contenido de SPA; sin embargo, este enfoque es rígido y requiere que los desarrolladores definan la composición exacta del contenido editable. Para admitir la creación de experiencias excepcionales por parte de los autores, el Editor de SPA admite el uso de componentes de contenedor en la SPA. Los componentes de contenedor permiten a los autores arrastrar y soltar los componentes permitidos en el contenedor y crearlos, tal como lo pueden hacer en la creación tradicional de AEM Sites.
En este capítulo, agregamos un contenedor editable a la vista de inicio que permite a los autores componer y diseñar experiencias de contenido enriquecido mediante componentes de React editables directamente en la SPA.
Actualización de la aplicación WKND
Para agregar un componente de contenedor a la vista Inicio:
- Import the AEM React Editable Component's
ResponsiveGridcomponent - Importar y registrar componentes React editables personalizados (texto e imagen) para utilizarlos en el componente Cuadrícula interactiva
Uso del componente Cuadrícula interactiva
Para agregar un área editable a la vista Inicio:
-
Abrir y editar
react-app/src/components/Home.js -
Importar el componente
ResponsiveGriddesde@adobe/aem-react-editable-componentsy agregarlo al componenteHome. -
Establezca los siguientes atributos en el componente
<ResponsiveGrid...>pagePath = '/content/wknd-app/us/en/home'itemPath = 'root/responsivegrid'
Esto indica al componente
ResponsiveGridque recupere su contenido del recurso de AEM:/content/wknd-app/us/en/home/jcr:content/root/responsivegrid
itemPathse asigna al nodoresponsivegriddefinido en la plantilla de AEMRemote SPA Pagey se crea automáticamente en las nuevas páginas de AEM creadas a partir de la plantilla de AEMRemote SPA Page.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> ); }
El archivo Home.js debe tener el siguiente aspecto:
Create editable components
Para obtener el efecto completo de la flexibilidad que ofrecen los contenedores de experiencia de creación en el Editor de SPA. Ya hemos creado un componente Título editable, pero vamos a hacer algunos más que permitan a los autores utilizar componentes Texto e Imagen editables en el componente Cuadrícula interactiva recién agregado.
Los nuevos componentes Texto editable y Reacción de imagen se crean utilizando el patrón de definición de componente editable exportado en componentes fijos editables.
Componente de texto editable
-
Abra el proyecto SPA en su IDE
-
Crear un componente de React en
src/components/editable/core/Text.js -
Agregar el siguiente 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; } -
Crear un componente React editable en
src/components/editable/EditableText.js -
Agregar el siguiente 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;
La implementación del componente Texto editable debería tener un aspecto similar al siguiente:
Componente de imagen
-
Abra el proyecto SPA en su IDE
-
Crear un componente de React en
src/components/editable/core/Image.js -
Agregar el siguiente 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> ) }; -
Crear un componente React editable en
src/components/editable/EditableImage.js -
Agregar el siguiente 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;
-
Cree un archivo SCSS
src/components/editable/EditableImage.scssque proporcione estilos personalizados paraEditableImage.scss. Estos estilos se dirigen a las clases CSS del componente React editable. -
Agregar el SCSS siguiente a
EditableImage.scsscode language-css .cmp-image__image { margin: 1rem 0; width: 100%; border: 0; } -
Importar
EditableImage.scssenEditableImage.jscode language-javascript ... import './EditableImage.scss'; ...
La implementación del componente Imagen editable debe tener un aspecto similar al siguiente:
Importar los componentes editables
Se hace referencia en la SPA a los componentes EditableText y EditableImage React recién creados y se crean instancias de forma dinámica en función del JSON devuelto por AEM. Para asegurarse de que estos componentes están disponibles para la SPA, cree instrucciones de importación para ellos en Home.js
-
Abra el proyecto SPA en su IDE
-
Abra el archivo
src/Home.js -
Agregar instrucciones de importación para
AEMTextyAEMImagecode 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'; ...
El resultado debería ser similar al siguiente:
Si se agregan estas importaciones no, la SPA no invocará el código EditableText y EditableImage y, por lo tanto, los componentes no están asignados a los tipos de recursos proporcionados.
Configuración del contenedor en AEM
Los componentes de contenedor de AEM utilizan directivas para dictar los componentes permitidos. Esta configuración es crítica al utilizar el Editor de SPA, ya que solo los componentes de AEM que tienen equivalentes de componentes de SPA asignados se pueden procesar mediante la SPA. Asegúrese de que solo se permiten los componentes para los que hemos proporcionado implementaciones de SPA:
EditableTitlese asignó awknd-app/components/titleEditableTextse asignó awknd-app/components/textEditableImagese asignó awknd-app/components/image
Para configurar el contenedor de cuadrícula adaptable de la plantilla de la SPA remota:
-
Iniciar sesión en AEM Author
-
Vaya a Herramientas > General > Plantillas > Aplicación WKND
-
Editar página de SPA de informe
-
Seleccione Estructura en el conmutador de modo en la parte superior derecha
-
Pulse para seleccionar Contenedor de diseño
-
Pulse el icono Directiva en la barra emergente
-
A la derecha, en la ficha Componentes permitidos, expanda WKND APP - CONTENT
-
Asegúrese de que solo están seleccionadas las siguientes opciones:
- Imagen
- Texto
- Título
-
Pulse Listo
Creación del contenedor en AEM
Después de actualizar el SPA para incrustar <ResponsiveGrid...>, los contenedores de tres componentes React editables (EditableTitle, EditableText y EditableImage) y de actualizar AEM con una directiva de plantilla coincidente, se puede empezar a crear contenido en el componente contenedor.
-
Log in to 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
- Imagen
- Título
-
Drag the components to reorder them to the following order:
- Título
- Imagen
- 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
-
Tap Done
-
-
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
- Tap Done
-
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!
- Tap Done
-
Your components are now authored, but stack vertically.
Use AEM's Layout Mode to allow us to adjust the size and layout of the components.
-
Switch to Layout Mode using the mode-selector in the top-right
-
Resize the Image and Text components, such that they are side by side
- Image component should be 8 columns wide
- Text component should be 3 columns wide
-
Preview your changes in AEM Page Editor
-
Refresh the WKND App running locally on http://localhost:3000 to see the authored changes!
Enhorabuena.
You've added a container component that allows for editable components to be added by authors to the WKND App! You now know how to:
- Use the AEM React Editable Component's
ResponsiveGridcomponent in the SPA - Create and register editable React components (Text and Image) for use in the SPA via the container component
- Configure the Remote SPA Page template to allow the SPA-enabled components
- Add editable components to the container component
- Author and layout components in SPA Editor
Próximos pasos
The next step uses this same technique to add an editable component to an Adventure Details route in the SPA.