SharePoint Framework - Integrating Adaptive Cards With SPFx

Overview

 
SharePoint Framework (SPFx) based web parts support integration with various JavaScript frameworks and libraries. We can include the npm package in our solution to get started with the various functionalities offered by that npm package.
 
In this article, we will explore how we can use Adaptive Cards with SharePoint Framework client web parts.
 

Overview of Adaptive Cards

 
Adaptive Cards are a new way for the developers to exchange card content in a common and consistent way. Adaptive cards are a great fit for a Bot, however, they can be effectively used with SPFx to render the content. Read more about Adaptive Cards at https://adaptivecards.io/
 

Develop SharePoint Framework Web Part

 
Open the command prompt. Create a directory for SPFx solution.
  1. md react-adaptive-cards-image-gallery  
Navigate to the above-created directory.
  1. cd react-adaptive-cards-image-gallery  
Run Yeoman SharePoint Generator to create the solution.
  1. yo @microsoft/sharepoint  
The Yeoman generator will present you with the wizard by asking questions about the solution to be created.
 
SharePoint Framework - Integrating Adaptive Cards With SPFx
  
Solution Name: Hit Enter to have a default name (react-adaptive-cards-image-gallery in this case) or type in any other name for your solution.
Selected choice: Hit Enter
 
Target for component: Here, we can select the target environment where we are planning to deploy the client webpart, i.e., SharePoint Online or SharePoint OnPremise (SharePoint 2016 onwards).
Selected choice: SharePoint Online only (latest)
 
Place of files: We may choose to use the same folder or create a subfolder for our solution.
Selected choice: Same folder
 
Deployment option: Selecting Y will allow the app to deployed instantly to all sites and to be accessible everywhere.

Selected choice: N (install on each site explicitly)
 
Type of client-side component to create: We can choose to create a client-side webpart or an extension. Choose the webpart option.
Selected choice: WebPart
 
Web part name: Hit Enter to select the default name or type in any other name.

Selected choice: AdaptiveCardsImageGallery
 
Web part description: Hit Enter to select the default description or type in any other value.
Selected choice: Image Gallery implemented with Adaptive Cards
 
Framework to use: Select any JavaScript framework to develop the component. Available choices are - No JavaScript Framework, React, and Knockout.
 
Selected choice: React
 
Now, the Yeoman generator will perform scaffolding process to generate the solution. The scaffolding process will take a significant amount of time. Once the scaffolding process is completed, lock-down the version of the project dependencies by running the below command.
  1. npm shrinkwrap  
In the command prompt, type the below command to open the solution in a code editor of your choice.
  1. code .  

NPM Packages

 
adaptivecards (https://www.npmjs.com/package/adaptivecards)
 
On the command prompt, run the below command to include the npm package.
  1. npm install adaptivecards --save  
SP PnP JS
 
On the command prompt, run the below command to install sp-pnp-js.
  1. npm install sp-pnp-js --save  

SharePoint Information Architecture

 
A SharePoint list (named "Adaptive Card Images") is provisioned to store the image information. The schema of the list is shown below.
SharePoint Framework - Integrating Adaptive Cards With SPFx
  • The "Image Link" column stores the URL of the image to be displayed in an adaptive card.
  • The "Navigation URL" column represents the URL to navigate by clicking on an image in the adaptive card.
  • The "Sort Order" column represents the order in which these images will be displayed in the adaptive card.

Define State

Add file IAdaptiveCardsImageGalleryState.ts under “\src\webparts\adaptiveCardsImageGallery\components\” folder.
  1. export interface IAdaptiveCardsImageGalleryState {  
  2.     galleryItems: any[];  
  3.     isLoading: boolean;  
  4.     showErrorMessage: boolean;  
  5. }  

Define Properties

Update IAdaptiveCardsImageGalleryProps.ts under “\src\webparts\adaptiveCardsImageGallery\components\” folder as below.
  1. import { ServiceScope } from '@microsoft/sp-core-library';  
  2.   
  3. export interface IAdaptiveCardsImageGalleryProps {  
  4.   serviceScope: ServiceScope;  
  5.   imageGalleryName: string;  
  6.   imagesToDisplay: number;  
  7. }  

Define Service

Define a service to retrieve the information from SharePoint list.
  1. import { ServiceKey, ServiceScope } from '@microsoft/sp-core-library';  
  2. import { PageContext } from '@microsoft/sp-page-context';  
  3. import { SPHttpClient, SPHttpClientResponse } from '@microsoft/sp-http';  
  4. import * as pnp from "sp-pnp-js";  
  5.   
  6. export interface IImageGalleryService {  
  7.     getGalleryImages: (listName: string, rowLimit: number) => Promise<any[]>;  
  8. }  
  9.   
  10. export class ImageGalleryService implements IImageGalleryService {  
  11.     public static readonly serviceKey: ServiceKey<IImageGalleryService> = ServiceKey.create<IImageGalleryService>('ImageGallery:ImageGalleryService', ImageGalleryService);  
  12.     private _pageContext: PageContext;      
  13.   
  14.     constructor(serviceScope: ServiceScope) {  
  15.         serviceScope.whenFinished(() => {  
  16.             this._pageContext = serviceScope.consume(PageContext.serviceKey);  
  17.         });  
  18.     }  
  19.   
  20.     public getGalleryImages(listName: string, rowLimit: number): Promise<any[]> {  
  21.         const xml = `<View>  
  22.                         <ViewFields>  
  23.                             <FieldRef Name='ID' />  
  24.                             <FieldRef Name='Title' />  
  25.                             <FieldRef Name='ImageLink' />  
  26.                             <FieldRef Name='NavigationURL' />  
  27.                         </ViewFields>  
  28.                         <Query>  
  29.                             <OrderBy>  
  30.                                 <FieldRef Name='SortOrder' />  
  31.                             </OrderBy>  
  32.                         </Query>  
  33.                         <RowLimit>` + rowLimit + `</RowLimit>  
  34.                     </View>`;  
  35.   
  36.         const q: any = {  
  37.             ViewXml: xml,  
  38.         };  
  39.   
  40.         return this._ensureList(listName).then((list) => {  
  41.             if (list) {  
  42.                 return pnp.sp.web.lists.getByTitle(listName).getItemsByCAMLQuery(q).then((items: any[]) => {  
  43.                     return Promise.resolve(items);  
  44.                 });  
  45.             }  
  46.         });  
  47.     }  
  48.   
  49.     private _ensureList(listName: string): Promise<pnp.List> {  
  50.         if (listName) {  
  51.             return pnp.sp.web.lists.ensure(listName).then((listEnsureResult) => Promise.resolve(listEnsureResult.list));  
  52.         }  
  53.     }  
  54. }  
Code the WebPart
 
Open the main webpart AdaptiveCardsImageGallery.tsx under “\src\webparts\adaptiveCardsImageGallery\components\” and add the below imports.
  1. import * as React from 'react';  
  2. import styles from './AdaptiveCardsImageGallery.module.scss';  
  3. import { IAdaptiveCardsImageGalleryProps } from './IAdaptiveCardsImageGalleryProps';  
  4. import { IAdaptiveCardsImageGalleryState } from './IAdaptiveCardsImageGalleryState';  
  5. import { escape } from '@microsoft/sp-lodash-subset';  
  6.   
  7. import * as AdaptiveCards from "adaptivecards";  
  8. import { ImageGalleryService, IImageGalleryService } from '../services/ImageGalleryService';  
  9. import { ServiceScope, Environment, EnvironmentType } from '@microsoft/sp-core-library';  
  10. import { Spinner, SpinnerSize } from 'office-ui-fabric-react/lib/Spinner';  
Define render method.
  1. public render(): React.ReactElement<IAdaptiveCardsImageGalleryProps> {  
  2.     return (  
  3.       <div className={styles.adaptiveCardsImageGallery}>  
  4.         <div className={styles.container}>  
  5.           {this.state.isLoading && <Spinner className={styles.spinner} size={SpinnerSize.large} />}  
  6.           {!this.state.isLoading && <div ref={(n) => { n && n.appendChild(this.renderedCard) }} />}  
  7.         </div>  
  8.       </div>  
  9.     );  
  10. }  
In the constructor, create an AdaptiveCard instance as below.
  1. // Create an AdaptiveCard instance  
  2. var adaptiveCard = new AdaptiveCards.AdaptiveCard();  
  3.   
  4. // Set its hostConfig property unless you want to use the default Host Config  
  5. // Host Config defines the style and behavior of a card  
  6. adaptiveCard.hostConfig = new AdaptiveCards.HostConfig({  
  7.        fontFamily: "Segoe UI, Helvetica Neue, sans-serif"  
  8. });  
  9.   
  10. // Set the adaptive card's event handlers. onExecuteAction is invoked  
  11. // whenever an action is clicked in the card  
  12. adaptiveCard.onExecuteAction = function(action) {   
  13.         window.location.href = action.iconUrl;  
  14. };  
  15.   
  16. // Parse the card  
  17. adaptiveCard.parse(this.card);  
  18.   
  19. // Render the card to an HTML element  
  20. this.renderedCard = adaptiveCard.render();  
Define the card as below.
  1. this.card = {  
  2.         "$schema""http://adaptivecards.io/schemas/adaptive-card.json",  
  3.         "type""AdaptiveCard",  
  4.         "version""1.0",  
  5.         "body": [  
  6.           {  
  7.             "type""TextBlock",  
  8.             "text""Adaptive Image Gallery",  
  9.             "size""medium"  
  10.           },  
  11.           {  
  12.             "type""ImageSet",  
  13.             "imageSize""medium",  
  14.             "images"this.imagesJSON  
  15.           }  
  16.         ]  
  17.       };  
Get the data from the service as below.
  1. let serviceScope: ServiceScope;  
  2. serviceScope = this.props.serviceScope;  
  3.   
  4. // Based on the type of environment, return the correct instance of the ImageGalleryServiceInstance interface  
  5. if (Environment.type == EnvironmentType.SharePoint || Environment.type == EnvironmentType.ClassicSharePoint) {  
  6.   // Mapping to be used when webpart runs in SharePoint.  
  7.   this.ImageGalleryServiceInstance = serviceScope.consume(ImageGalleryService.serviceKey);  
  8. }  
  9.   
  10. this.ImageGalleryServiceInstance.getGalleryImages(this._galleryListName, this._noOfItems).then((galleryImages: any[]) => {  
  11.   galleryImages.forEach(adaptiveImage => {  
  12.     let image = {};  
  13.     image["type"] = "Image";  
  14.     image["url"] = adaptiveImage.ImageLink.Url;          
  15.   
  16.     // Compose image action  
  17.     let imageAction = {};  
  18.     imageAction["title"] = adaptiveImage.NavigationURL.Description;  
  19.     imageAction["type"] = "Action.OpenUrl";  
  20.     imageAction["url"] = adaptiveImage.NavigationURL.Url;  
  21.     imageAction["iconUrl"] = adaptiveImage.NavigationURL.Url;  
  22.   
  23.     image["selectAction"] = imageAction;  
  24.     this.imagesJSON.push(image);  
  25.   });  

Run the SPFx WebPart

  1. On the command prompt, type “gulp serve”.
  2. Open SharePoint site.
  3. Navigate to /_layouts/15/workbench.aspx.
  4. Add the webpart to the page.

    SharePoint Framework - Integrating Adaptive Cards With SPFx

  5. Edit the web part and update the Image Gallery along with the number of images to display properties.

    SharePoint Framework - Integrating Adaptive Cards With SPFx

Summary

 
Adaptive Cards are a new way for the developers to exchange card content in a common and consistent way. This example demonstrates the capability of using Adaptive Cards (https://adaptivecards.io/) with SharePoint Framework.