Lightning Components for Snap-In Minimized UI

Let’s discuss how to use lightningsnapin:minimizedUI interface in the when snap-in is minimized. This interface is used to indicate that a component can be used as the user interface for a minimized snap-in. This interface has no effect except when used within Snap-ins Chat hosted on a website, Visualforce page, or Community (using the Snap-ins Chat Community component). Without this interface, the component doesn’t appear as a minimized snap-in page option in Snap-ins Setup.

1.  Lightning Component 

Before you start, make sure that you have a Snap-ins deployment already set up. Next, go to the Developer Console and click File | New | Lightning Component. Enter a name and description for your component and click Submit. Here is the lightning component code

<aura:component implements="lightningsnapin:minimizedUI" description="Custom Minimized UI">
    <aura:handler name="init" value="{!this}" action="{!c.onInit}"/>
    <aura:attribute name="message" type="String" default="Chat with us!"/>
    
    <!-- For registering our minimized event handler and maximizing -->
    <lightningsnapin:minimizedAPI aura:id="minimizedAPI"/>
    <button onclick="{!c.handleMaximize}"  class="minimizedContainer">
        {!v.message}
    </button>  
</aura:component>

controller.js

({
	onInit: function(cmp, evt, hlp) {
        // Register the generic event handler for all the minimized events
        cmp.find("minimizedAPI").registerEventHandler( hlp.minimizedEventHandler.bind(hlp, cmp));
	},
    
    handleMaximize: function(cmp, evt, hlp) {
        cmp.find("minimizedAPI").maximize();
    }
})

helper.js

({
    /**
 * Function to handle maximizing the chat.Function to start a chat request (by accessing the chat API component)
 *
 * @param cmp - The component for this state
 * @param eventName - The name of the event fired.
 * @param eventData - The data associated with the event fired.
 */
    minimizedEventHandler: function(cmp, eventName, eventData) {
        switch(eventName) {
            case "prechatState":
                cmp.set("v.message", "Chat with an Expert!");
                Break;
            default:
                cmp.set("v.message", eventData.label);
        }
    },
});
.THIS {
    position: fixed;
    left: auto;
    bottom: 0;
    right: 12px;
    margin: 0;
    min-width: 12em;
    max-width: 14em;
    height: 46px;
    width: 192px;
    max-height: 100%;
    border-radius: 8px 8px 0 0;
    text-align: center;
    text-decoration: none;
    display: flex;
    flex-direction: center;
    justify-content: center;
    box-shadow: none;
    pointer-events: all;
    overflow: hidden;
    background-color: rgb(0, 112, 210);
    font-size: 16px;
}

.THIS.minimizedContainer:focus,
.THIS.minimizedContainer:hover {
    color: rgb(255, 255, 255);
    text-decoration: underline;
    outline: none;
    background-color: rgb(0, 95, 178);
    box-shadow: 0 0 12px 0 rgba(0, 0, 0, 0.5);
}

.THIS .messageContent {
    display: block;
    padding: 0 8px;
    height: 200%;
    color: rgb(123, 123, 123);
}

 

Understanding component 

1.The component implements the lightningsnapin:minimizedUI interface, which makes the component available to select as your minimized component from Snap-ins Setup.

<aura:component implements="lightningsnapin:minimizedUI">

2. The following code creates the minimized API component instance in your markup. 

<lightningsnapin:minimizedAPI aura:id="minimizedAPI"/>

3. Add an initialize aura handler that action gets called when the component is initialized.

<aura:handler name="init" value="{!this}" action="{!c.onInit}" />

4. Make sure to add a maximize container action so your customers can open the snap-in. Here is the code from the component.

<button onclick="{!c.handleMaximize}">
    {!v.message}
</button>

5. Add a handler for maximizing chat from the minimized component.Add a click handler to a button element. The customer uses this button to maximize chat.

handleMaximize: function(cmp, evt, hlp) {
    cmp.find("minimizedAPI").maximize();
},

 

2. Configure the component in snap-ins 

Now go to your snap-ins deployment and include a component in custom component for the minimized snap-in as shown below.

3. Configure the Snap-ins in community 

Now go and configure the snap-ins in your community. this example I am testing this snap-ins from the community. After configuring the snap-ins from your community you can able to the start the chat with the agent.

 

Now minimize the snap-in chat window from the community and you will be able to see the minimized window is works based on the component as shown below.

Customize the Pre-Chat Page UI with Lightning Components

Add Snap-ins Chat to your website so customers can quickly get answers to their questions by chatting with an agent while browsing your site. Snap-ins Chat uses a Live Agent deployment that you can quickly configure. Then, simply add the chat code to the web pages where you want the chat snap-in to be available. When agents chat with customers via Snap-ins Chat, the agents use Live Agent in their console. In this post, we will see how to create a pre-chat form by using the lightning components. You can able to Customize the fields, layout, buttons, images, validation, or any other part of the user interface for pre-chat using a custom Lightning component by using Pre chat API. I  am assuming that you have live agent deployments is available to use the snap-ins

prerequisites

To set up Snap-ins Chat, your org must meet these prerequisites:

  • Lightning Experience must be enabled to set up snap-ins
  • Service Cloud License
  • Live Agent License
  • Live Agent must be enabled in your Org
  • A Live Agent chat button and a Live Agent deployment must be set up and available in your Org
  • A Salesforce Community (preferable) or a Salesforce Site must be set up on your org and available for guest user access.

Create a Snap-Ins Deployment

we need to create a Snap-in deployment for each snap-in that you’re using on your website. In this example, the Snap-ins Chat setup uses a Salesforce Community. From Setup, find Snap-ins and click New Deployment and enter details as shown below In the Site Endpoint menu, select a Salesforce community or Salesforce Site where you want to host the snap-ins.

After saving the snap-ins deployment, you need to enable the live agent setting. Go to the snap-ins which you configured and select view. In the Snap-ins configuration page, go to the Live Agent settings section and click Start.

  1. In the Live Agent Deployment menu, select the Live Agent configuration that you want to use with the chat snap-in from the dropdown list.
  2. In the Live Agent Button menu, select the Live Agent chat button or automated invitation that you want to use with the chat snap-in from the dropdown list.
  3. Select Show queue position if you want to display the customer’s place in line while they wait for a support agent. Make sure that the Live Agent chat button you selected has Enable Queue selected in your Live Agent chat button settings.
  4. Click Save.

To set up the pre-chat form

From the snap-in deployment, you can able to add the pre-chat form that will be able to the user before the chat starts.

  1. In the Pre-chat section, move the radio button to Active.
  2. Click Edit.
  3. Select the use case for the pre-chat form.
After saving the pre-chat form go and override the pre-chat form with the below code. 
PreChatCmp.cmp
Here is the lightning component that we will use to override the pre-chat form.
<aura:component implements="lightningsnapin:prechatUI" description="Sample custom pre-chat component for Snap-ins. Implemented using Aura.">
    <!-- You must implement "lightningsnapin:prechatUI" for this component to appear in the "Pre-chat Component" customization dropdown in the Snap-ins setup -->
    
    <!-- Pre-chat field components to render -->
    <aura:attribute name="prechatFieldComponents" type="List" description="An array of objects representing the pre-chat fields specified in pre-chat setup."/>
    
    <!-- Handler for when this component is initialized -->
    <aura:handler name="init" value="{!this}" action="{!c.onInit}" />
    
    <!-- For Aura performance -->
    <aura:locator target="startButton" description="Pre-chat form submit button."/>
    
    <!-- Contains methods for getting pre-chat fields, starting a chat, and validating fields -->
    <lightningsnapin:prechatAPI aura:id="prechatAPI"/>
    
    <h2>Prechat form</h2>
    <div class="prechatUI">
        <div class="prechatContent">
            <ul class="fieldsList">
                <!-- Look in the controller's onInit function. This component dynamically creates the pre-chat field components -->
                {!v.prechatFieldComponents}
            </ul>
        </div>
        <div class="startButtonWrapper">
            <ui:button aura:id="startButton" class="startButton" label="{!$Label.LiveAgentPrechat.StartChat}" press="{!c.handleStartButtonClick}"/>
        </div>
    </div>
    
</aura:component>

Controller.js

({
    /**
     * On initialization of this component, set the prechatFields attribute and render pre-chat fields.
     * 
     * @param cmp - The component for this state.
     * @param evt - The Aura event.
     * @param hlp - The helper for this state.
     */
	onInit: function(cmp, evt, hlp) {
        // Get pre-chat fields defined in setup using the prechatAPI component
		var prechatFields = cmp.find("prechatAPI").getPrechatFields();
        // Get pre-chat field types and attributes to be rendered
        var prechatFieldComponentsArray = hlp.getPrechatFieldAttributesArray(prechatFields);
        
        // Make asynchronous Aura call to create pre-chat field components
        $A.createComponents(
            prechatFieldComponentsArray,
            function(components, status, errorMessage) {
                if(status === "SUCCESS") {
                    cmp.set("v.prechatFieldComponents", components);
                }
            }
        );
    },
    
    /**
     * Event which fires when start button is clicked in pre-chat
     * 
     * @param cmp - The component for this state.
     * @param evt - The Aura event.
     * @param hlp - The helper for this state.
     */
    handleStartButtonClick: function(cmp, evt, hlp) {
        hlp.onStartButtonClick(cmp);
    }
});

helper.js

({
    /**
	 * Map of pre-chat field label to pre-chat field name (can be found in Setup)
	 */
    fieldLabelToName: {
        "First Name": "FirstName",
        "Last Name": "LastName",
        "Email": "Email",
        "Subject": "Subject",
        "Type": "Type",
        "Priority": "Priority"
    },
    
    /**
	 * Event which fires the function to start a chat request (by accessing the chat API component)
	 *
	 * @param cmp - The component for this state.
	 */
    onStartButtonClick: function(cmp) {
        var prechatFieldComponents = cmp.find("prechatField");
        var fields;
        
        // Make an array of field objects for the library
        fields = this.createFieldsArray(prechatFieldComponents);
        
        // If the pre-chat fields pass validation, start a chat
        if(cmp.find("prechatAPI").validateFields(fields).valid) {
            cmp.find("prechatAPI").startChat(fields);
        } else {
            console.warn("Prechat fields did not pass validation!");
        }
    },
    
    /**
	 * Create an array of field objects to start a chat from an array of pre-chat fields
	 * 
	 * @param fields - Array of pre-chat field Objects.
	 * @returns An array of field objects.
	 */
    createFieldsArray: function(fields) {
        if(fields.length) {
            return fields.map(function(fieldCmp) {
                return {
                    label: fieldCmp.get("v.label"),
                    value: fieldCmp.get("v.value"),
                    name: this.fieldLabelToName[fieldCmp.get("v.label")]
                };
            }.bind(this));
        } else {
            return [];
        }
    },
    
    /**
     * Create an array in the format $A.createComponents expects
     * 
     * Example:
     * [["componentType", {attributeName: "attributeValue", ...}]]
     * 
	 * @param prechatFields - Array of pre-chat field Objects.
	 * @returns Array that can be passed to $A.createComponents
     */
    getPrechatFieldAttributesArray: function(prechatFields) {
        // $A.createComponents first parameter is an array of arrays. Each array contains the type of component being created, and an Object defining the attributes.
        var prechatFieldsInfoArray = [];
        
        // For each field, prepare the type and attributes to pass to $A.createComponents
        prechatFields.forEach(function(field) {
            var componentName = (field.type === "inputSplitName") ? "inputText" : field.type;
            var componentInfoArray = ["ui:" + componentName];
            var attributes = {
                "aura:id": "prechatField",
                required: field.required,
                label: field.label,
                disabled: field.readOnly,
                maxlength: field.maxLength,
                class: field.className,
                value: field.value
            };
            
            // Special handling for options for an input:select (picklist) component
            if(field.type === "inputSelect" && field.picklistOptions) attributes.options = field.picklistOptions;
            
            // Append the attributes Object containing the required attributes to render this pre-chat field
            componentInfoArray.push(attributes);
            
            // Append this componentInfoArray to the fieldAttributesArray
            prechatFieldsInfoArray.push(componentInfoArray);
        });
        
        return prechatFieldsInfoArray;
    }
});

Now override the Pre Chat component with this lightning component. 

Adding Your Snap-In to a Website

Now go to the community builder and add the out of box lightning component Snap-ins to the builder as show below.

Here we are configuring the Snap-ins Chat deployment and configure as shown below.

Add Your Website to the CORS Whitelist

Add the URLs of the web pages where you intend to add the snap-in to the CORS whitelist in your Org. The web page where you add the snap-in is the page that customers use to access chat.

Testing 

You can able to see the Pre chat form from the community as shown below. Before going to snap-ins, make sure at least one agent in on live agent with available status.

Once the user submits the form it’s going to create a case as shown below and the agent will able to chat with the user.

Lightning Custom Pre-Chat Component Using JavaScript

Add Snap-ins Chat to your website so customers can quickly get answers to their questions by chatting with an agent while browsing your site. Snap-ins Chat uses a Live Agent deployment that you can quickly configure. Then, simply add the chat code to the web pages where you want the chat snap-in to be available. When agents chat with customers via Snap-ins Chat, the agents use Live Agent in their console. In this post, we will see how to create a pre-chat form by using the lightning components. You can able to Customize the fields, layout, buttons, images, validation, or any other part of the user interface for pre-chat using a custom Lightning component by using Pre chat API. I  am assuming that you have live agent deployments is available to use the snap-ins

prerequisites

To set up Snap-ins Chat, your org must meet these prerequisites:

  • Lightning Experience must be enabled to set up snap-ins
  • Service Cloud License
  • Live Agent License
  • Live Agent must be enabled in your Org
  • A Live Agent chat button and a Live Agent deployment must be set up and available in your Org
  • A Salesforce Community (preferable) or a Salesforce Site must be set up on your org and available for guest user access.

Create a Snap-Ins Deployment

we need to create a Snap-in deployment for each snap-in that you’re using on your website. In this example, the Snap-ins Chat setup uses a Salesforce Community. From Setup, find Snap-ins and click New Deployment and enter details as shown below In the Site Endpoint menu, select a Salesforce community or Salesforce Site where you want to host the snap-ins.

After saving the snap-ins deployment, you need to enable the live agent setting. Go to the snap-ins which you configured and select view. In the Snap-ins configuration page, go to the Live Agent settings section and click Start.

  1. In the Live Agent Deployment menu, select the Live Agent configuration that you want to use with the chat snap-in from the dropdown list.
  2. In the Live Agent Button menu, select the Live Agent chat button or automated invitation that you want to use with the chat snap-in from the dropdown list.
  3. Select Show queue position if you want to display the customer’s place in line while they wait for a support agent. Make sure that the Live Agent chat button you selected has Enable Queue selected in your Live Agent chat button settings.
  4. Click Save.

To set up the pre-chat form

From the snap-in deployment, you can able to add the pre-chat form that will be able to the user before the chat starts.

  1. In the Pre-chat section, move the radio button to Active.
  2. Click Edit.
  3. Select the use case for the pre-chat form.
After saving the pre-chat form go and override the pre-chat form with the below code. 
PreChatCmp.cmp
Here is the lightning component that we will use to override the pre-chat form.
<aura:component 
                description="Sample pre-chat component that uses Aura only when absolutely necessary"
                implements="lightningsnapin:prechatUI">
    <!-- Contains methods for getting pre-chat fields, starting a chat, and validating fields -->
    <lightningsnapin:prechatAPI aura:id="prechatAPI"/>
    <!-- After this component has rendered, call the controller's onRender function -->
    <aura:handler name="render" value="{!this}" action="{!c.onRender}"/>
    <div class="prechatUI">
        Prechat Form
        <div class="prechatFields">
            <!-- Add pre-chat field HTML elements in the controller's onInit function -->
        </div>
        <button class="startChatButton" onclick="{!c.onStartButtonClick}">
            Start Chat
        </button>
    </div>
    
</aura:component>

Controller.js

({
    /**
	 * After this component has rendered, create an  input fields
	 *
	 * @param component - This prechat UI component.
	 * @param event - The Aura event.
	 * @param helper - This component's helper.
	 */
    onRender: function(component, event, helper) {
        // Get array of pre-chat fields defined in Setup using the prechatAPI component
        var prechatFields = component.find("prechatAPI").getPrechatFields();
        console.log('prechatFields'+JSON.stringify(prechatFields));
        // Append an input element to the prechatForm div.
        helper.renderField(prechatFields);
    },
    
    /**
	 * Handler for when the start chat button is clicked
	 *
	 * @param component - This prechat UI component.
	 * @param event - The Aura event.
	 * @param helper - This component's helper.
	 */
    onStartButtonClick: function(component, event, helper) {
        var prechatInfo = helper.createStartChatDataArray();
        
        if(component.find("prechatAPI").validateFields(prechatInfo).valid) {
            component.find("prechatAPI").startChat(prechatInfo);
        } else {
            console.log('error'+component);
        }
    }
});

helper.js

({
    /**
	 * Create an HTML input element, set necessary attributes, add the element to the DOM
	 *
	 * @param fields - pre-chat fields object with attributes needed to render
	 */
    renderField: function(fields) {
        // Dynamically create input HTML element
        // 
        fields.forEach(function(field) {
            
            //console.log(field);
            console.log('field---'+field);
            var componentName = (field.type === "inputSplitName") ? "inputText" : field.type;
            var input = document.createElement("input");
            // Set general attributes
            input.type = componentName;
            input.class = field.label;
            input.placeholder = "Your"+field.label+" here.";
            // Set attributes required for starting a chat
            input.name = field.name;
            input.label = field.label;
            input.options = field.picklistOptions
            input.required= field.required;
            
            // Add email input to the DOM
            document.querySelector(".prechatFields").appendChild(input);
            
            
        })
    },
    
    /**
	 * Create an array of data to pass to the prechatAPI component's startChat function
     */
    createStartChatDataArray: function() {
        console.log('input');
        var inputs = document.querySelector(".prechatFields").childNodes;
        console.log('input');
        var infos=[] ;
        for (var i = 0; i < inputs.length; i++) {
            
            var info = {
                name: inputs[i].name,
                label: inputs[i].label,
                value: inputs[i].value
            };
            infos.push(info) ;
        }
        return infos;
    }
});

Now override the Pre Chat component with this lightning component. 

Adding Your Snap-In to a Website

Now go to the community builder and add the out of box lightning component Snap-ins to the builder as show below.

Here we are configuring the Snap-ins Chat deployment and configure as shown below.

Add Your Website to the CORS Whitelist

Add the URLs of the web pages where you intend to add the snap-in to the CORS whitelist in your Org. The web page where you add the snap-in is the page that customers use to access chat.

Testing 

You can able to see the Pre chat form from the community as shown below . Before going to snap-ins, make sure at least one agent in on live agent with available status.

Once the user submits the form it’s going to create a case as shown below and the agent will able to chat with the user.