Describe the Lightning Component framework, its benefits, and the types of content that can be contained in a Lightning web component.

After studying this topic, you should be able to:

  • Describe what the Lightning Component framework is
  • Identify the benefits of the Lightning Component framework
  • Determine what a Lightning web component is
  • Describe the types of content that can be contained in a Lightning web component
  • Identify resources that can be accessed within a Lightning web component

Table of Contents

  • Lightning Component Framework
  • Framework Benefits
  • Content Types in Aura Components
  • Content Types in Lightning Web Components
  • Testing with UTAM
  • Lightning Web Security
  • Static Resources, Permissions, and Examples
  • Modal Notifications
  • Modal Component
  • Platform Events
  • Considerations

Introduction

  • Lightning Component framework enables developers to build and distribute custom applications on the Salesforce platform, such as in Lightning Experience, Salesforce Mobile App, and Experience Cloud sites
  • Lighting web components, built on the Lightning Web Components programming model provided by the framework, use the latest web standards that enables them to run natively on browsers
  • This topic outlines the benefits of the Lightning Component framework and describes the different types of content contained in a Lightning web component: HTML, JavaScript, CSS, SVG, configuration, and test files

Lightning Component Framework

  • Lightning Component framework is a UI framework used for building single-page apps with dynamic and responsive user interfaces in the Salesforce platform
    • Apex and Javascript: they use HTML, CSS, and JavaScript on the client side, and Apex on the server side
    • Programming Models: Aura Components and Lightning Web Components can coexist and interoperate on a page
    • Stateful and Stateless: utilizes a stateful client (JavaScript) and a stateless server (Apex) - client calls server only when absolutely necessary, resulting in fewer calls and more responsive, efficient apps
    • Responsive: Lightning Component framework exercises relative sizing which enables images, media, and other elements to scale flexibly. Custom styling can also be implemented easily.
  • Programming Models:
    • Features that were not available as a web standard before led to the building of custom frameworks into the Aura model
    • In 2019, web standards evolved which enable LWC to depend on fewer custom frameworks with the Lightning Web Component (LWC) model

  • Modular Components:
    • Lightning components, either Aura components or Lightning web components are modular, interoperable, reusable units

  • Event-Driven Software Architecture: utilizes event-drive or message-driven architecture which consists of event producers, event consumers and channels:
    • Decoupled: simplifies communication by decoupling of event producers from event consumers
    • Subscription: component can subscribe to an application event or a visible component event
    • Real Time: information can be obtained and processed in real time when the event occurs
    • An event producer publishes and event message to the event bus, and event consumers, or subscribers, receive the event message from the event bus

Framework Benefits

  • Increased Performance: intelligent utilization of browser, devices, server and network increases performance
    • Lightning components run on stateful and stateless architecture and use resources efficiently
    • Data Format: JSON format is used to exchange data between client and server
    • Client-side JavaScript: based on JavaScript on the client side to manage UI component metadata and data
  • Reduced Development Time: facilitates parallel design and utilizes encapsulated components
  • Multiple Use Cases: enables components to be supported in different tools and interfaces in the Salesforce platform: Visualforce pages, AppExchange, Mobile Access, Lightning App Builder, Experience Builder

Content Types in Aura Components

  • Bundle contents: at most, an Aura component bundle contains up to eight different types of resources
    • App or Component: bundle can contain a component or an application, but not both
      • A Lightning App (*.app) is created to make the application available outside Lightning Experience as a standalone app and will have its own URL
      • A Lightning component (*.cmp) is build to exist within Lightning Experience
      • Apps can contain components, but apps cannot contain other apps
  • Resources in the bundles are summarized below:
    • Component (.cmp) or Application (*.app)
      • Layout: contains component or application markup that defines its layout
      • Files: includes or references files such as stylesheets and JavaScript
      • Attributes: contains optional system attributes that instruct the framework how to configure the app
      • Required: only required file in the bundle
    • Controller (*.js)
      • Define actions: client-side controller used for defining the function for all the component’s actions
      • Handle events: handles client-side events in the component markup
      • Key-Value pairs: represents a JavaScript object containing a map of key-value pairs, in which the key represents a client function and the value contains the code for the associated action
      • Action parameters
        • cmp: component to which the controller belongs
        • event: event being handled by the action
        • helper: component’s helper
    • Helper (*.js)
      • Functions: helper contains utility or shared JavaScript functions
      • Accessible: called by any JavaScript code in the Aura component bundle
    • Stylesheet (*.css)
      • Styling: stylesheet contains CSS that is readily available to the component markup
      • Markup: styleing only affects the markup resource with which it is included
    • Design (*.design)
      • Configuration options: design resource
      • Custom attributes: these are used for creating custom attributes with values that can be edited in tools such as Lightning App Builder
      • Device Support: can be used to control which types of devices the component will only support
      • Page support: can be used to restrict the components to display only in the record page of a standard or custom object
    • Documentation (*.auradoc)
      • Resource contains technical documentation about the Aura component
      • Access via URL: https://<myDomain>.lightning.force.com/componentReference/suite.app
    • Renderer (*.js)
      • Modify DOM: renderer resource contains code that can modify the DOM elements generated by the Aura component
      • Render phases: rendering phases are render, rerender, afterRender, and unrender, and they are executed in the same order
    • Scalable Vector Graphic (*.svg)
      • Custom Icon: SVG resource is used to set a custom icon for the component using SVG
      • Component Pane: custom icon is visible in the component pane in Lightning App Builder
  • Aura Component Example: following is markup of an Aura component that allows users to add checklist items and specify due dates
<aura:component controller="AuraChecklistController" 
     implements="flexiPage:availableForAllPageTypes">
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    <aura:attribute name="Items" type="Object"/>
    <aura:attribute name="Name" type="String" />
    <aura:attribute name="DueDate" type="Date" />
    <aura:attribute name="Today" type="Date" />
    <lightning:card title="Checklist" iconName="custom:custom63">
        <div class="slds-grid slds-gutters">
            <div class="slds-col"><div aura:id="formDiv" class="slds-p-around_medium">
                <lightning:input type="String" label="Name" value="{!v.Name}" />
                <lightning:input type="Date" label="Due Date" value="{!v.DueDate}" 
                min="{!v.Today}"/>
                <lightning:button class="slds-m-top_small" label="Create Item" 
                variant="brand" onclick="{!c.saveItem}"/>
            </div>
        </div>
        <div class="slds-col">
            <div aura:id="formDiv" class="slds-p-around_medium">
                <aura:iteration items="{!v.Items}" var="i">
                    <divclass="slds-border--top slds-border--bottom">
                        <label class="card-detail-label">{!i.Name}</label>
                        <span class="card-detail-value">{!i.Due_Date__c}</span>
                    </div>
                </aura:iteration>
            </div>
        </div>
    </lightning:card>
</aura:component>
  • Current Aura Component controller: following shows the available methods in the client-side controller
({
    doInit : function(component,event,helper){
        var now = new Date(); // date today
        var dateToday = now.getFullYear() + '-' + (now.getMonth() + 1) + '-' + now.getDate();
        component.set('v.Today', dateToday);
        helper.getData(component, event, helper); // populate {!v.Items}
    },
    saveItem : function(component, event, helper){
        var action = component.get('c.insertItem');
        var name = component.get('v.Name');
        var dueDate = component.get('v.DueDate');
        action.setParams({ name : name, dueDate: dueDate }); // pass parameters to server
        action.setCallback(this, $A.getCallback(function (response) {
            var state = response.getState();
            if (state == 'SUCCESS') {
                var toast = $A.get('e.force:showToast'); 
                var message = response.getReturnValue() == true ? 'Record created!' : 
                'An error occurred.'; 
                var toastType = response.getReturnValue() == true ? 'Success' : 'Error';
                toast.setParams({'type' : toastType, 'message' : message, 'mode' : 'sticky'});
                toast.fire();
            } else console.log('An unexpected error was encountered!');        
        }));       
        $A.enqueueAction(action);   
    }
})
  • Following shows the helper of the Aura component that contains a method that is called during its initialization
({   
    getData : function(component, event, helper){
        var action = component.get('c.loadItems');
        action.setCallback(this,function(response){
            var state = response.getState();
            if(state == 'SUCCESS'){
                var items = response.getReturnValue();
                component.set('v.Items', items);
            } else {
                console.log('An error was encountered');
            }
        });
        $A.enqueueAction(action);
    }
})

Content Types in Lightning Web Components

  • Currently, two types of Lightning Web Components:
    • UI Component: custom component that users can interact with via a user interface such as clicking a button, filling out a form, etc
      • Requires HTML, JavaScript, and metadata configuration files
    • Service Component: serves a helper library and is called a service component. Created to have variables or functions that can be shared between components.
      • Requires JavaScript and metadata configuration files only

  • Directory Structure: a folder contains all the files needed in a Lightning web component
    • Folder and its files must have the same name


  • Component HTML File: serves as the presentation layer of the Lightning web component
    • Root tag: root tag in HTML file is <template>, which is used to encapsulate the Lightning web component’s HTML and other markup
    • File name: naming convention is <componentName>.html, IE searchForm.html for searchForm component
    • Namespace: when component renders, the <template> tag is replaced with the name of the component that uses “c” as the default namespace

  • Component JavaScript File: required in any type of Lightning web component. It contains the client controller that includes the properties and functions of the component
    • File name: convention is <componentName>.js such as searchForm.js
    • Class name: convention is Pascal Case such as SearchForm
    • Import: import statement is used to import a class, function, or variable declared in a module
    • Modules: JavaScript files in Lightning web components are ES6 modules. Everything declared in an ES6 module is local or scoped to the module
    • Should extend from LightningElement, which is a custom wrapper of the standard HTML element
    • Fields or member variables in the JavaScript class are reactive - so, if the value is updated in the controller, the component automatically rerenders to display the new value

  • Additional JavaScript Files: more than one JavaScript file can be contained in a Lightning web component

  • Component Configuration File: configuration file is required for every Lightning web component
    • Metadata: defines the metadata values for the component including the supported targets (form factor, page type, object, etc) and design configuration
    • Filename: <componentName>.js-meta.xml such as searchForm.js-meta.xml

  • Component CSS Files: cascading style sheets can be include in a Lightning web component to implement CSS styling
    • Filename: <componentName>.css such as searchForm.css
    • Scoped: styles defined in the CSS files are scoped to the component
    • Standard: standard CSS syntax, with most CSS selectors allowed
    • Encapsulated: styles defined in CSS file does not override other styles in other parts of a page
    • Automatic: applied automatically
    • Single: only one CSS file is allowed per Lightning web component

  • Lightning Design System Design Tokens: CSS styling can be used on Lightning web components using global design tokens available in the Salesforce Lightning Design System framework

  • Custom Aura Design Tokens: custom Aura tokens, which are created to style Aura components, can also be used and applied in the CSS file of a Lightning web component

  • CSS Modules: Lightning web components that contain only a CSS file and a configuration file can be created and then imported by the component that needs to apply its styles
    • To import a CSS module, use an @import statement defined in the CSS file of the target component

  • CSS Styling Hooks: Lightning web component support CSS custom properties to create styling hooks

  • Component SVG Icon: svg file can be added to customize the icon that represents the Lightning web component
    • Filename: <componentName>.svg such as searchForm.svg
    • Single: only one SVG file is allowed per Lightning web component
    • Location: SVG file is added to the top-level component folder
    • Visibility: icon is visible in Lightning App Builder and Experience Builder

  • Component Tests: test files are contained in a subfolder inside the component’s folder
    • Framework: run using Jest, a third-party JavaScript testing framework
    • Independent: Jest tests are created locally and run independently, unlike Aura tests or Apex tests that depend on Salesforce to run them
    • Folder Name: subfolder where the Jest tests will be saved should be named __tests__
    • Folders/Files: a single test file can be created to include all component tests, or multiple test files and subfolders can be used to manage tests
    • Filename: <componentName>.test.js or searchForm.test.js
  • Dependencies Tree Viewer: tool available for Lightning web components for viewing the dependencies of the current component, such as custom components and Apex classes

Testing with UTAM

  • UI Test Automation Model (UTAM) is an open-source tool built by Salesforce that can be used to test any web page and is ideally suited for writing JavaScript or Java UI tests for Lightning web components

  • Following shows a simplified example of how UTAM is used in testing a user interface

Lightning Web Security

  • Lightning Web Security, a client-side security architecture designed for Lightning web components, prevents the components from accessing data or interfering with components from other namespaces

  • With Lightning Web Security, Lightning web components run in their namespace’s own virtual environment, where each is a replica of the host environment but with limited access to specific resources
    • Host Environment: The host environment is the browser and runs multiple virtual environments simultaneously
    • Virtualization Engine: Lightning web security is the virtualization engine and creates and manages virtual environments for each namespace accordingly
    • Virtual Environment: Also referred to as a JavaScript“sandbox”, components of the same namespace run in this environment and have access to specific browser resources
  • Lightning Web Security prevents unsafe behavior by altering running code in the JavaScript sandbox. This technique is called “distortion” and dynamically modifies code at the JavaScript API level in order to:
    • Content: Prevent the API from altering content and data outside the JavaScript sandbox
    • Boundary: Ensure that code executes only within the boundaries of the JavaScript sandbox
    • Resources: Restrict or reduce access to DOM and shared global objects in the JavaScript sandbox
  • LWS Distortion Viewer: Since Lightning Web Security distorts certain JavaScript APIs, Lightning web components may break if they’re not ready. The LWS Distortion Viewer can be used to learn which APIs are distorted and how
  • Lightning Web Security Console: tool that can be used to test and determine the impact of Lightning Web Security on JavaScript code when it is enabled

Static Resources, Permissions, and Examples

  • Access to Resources: a Lightning web component has access to Static Resources, SVG Resources, Content Asset Files, Labels, Internationalization Properties, Current User Information, and Client Form Factor
    • Static Resources: archives (*.zip and *.jar), images, style sheets, javaScript, etc in static resources can be imported using @salesforce/resourceUrl
    • Content asset files: can be imported using @salesforce/contentAssetUrl
    • SVG resources: embed in the component HTML or upload using Static resources then import
    • Labels: custom labels can be imported using @salesforce/label scoped module
    • Internationalization Properties: import using @salesforce/i18n scoped module
    • Client form factor: determine by importing the @salesforce/client/formFactor scoped module
    • Current user information: retrieve using @salesforce/user scoped module
  • Checking User Permissions: use @salesforce/userPermission and @salesforce/customPermission
    • Static reference to the permission evaluates to true or false

  • Sample code snippets of a Search Form
    • Aside from rendering page elements, component markup can also contain logic such as if statements or for loop blocks

  • Alert, Confirm, and Prompt modules can be used by Lightning web components to replace the soon-to-be deprecated native alert(), confirm(), and prompt() APIs of the window object.
    • LightningAlert: The open() method available in the LightningAlert module is used to asynchronously display an alert modal window
    • LightningConfirm: The open() method available in the LightningConfirm module is used to asynchronously display a confirmation modal window
    • LightningPrompt: The open() method available in the LightningPrompt module is used to asynchronously display a modal window that contains an input text field
  • Following shows code snippets of the handler function that invokes the alert, confirm, and prompt modal notifications

  • The following shows screenshot examples of the Lightning web component that invokes modal notifications. These notification feature is also available for Aura components.

  • A Lightning web component can be created as a modal component, which is a reusable modal overlay, for providing functionality that can be shared across several Lightning components

  • Modal Component Configuration: The modal component uses lightning-modal-* components in its markup. While the lightning-modal-body is required, the header and footer components are optional.
    • The following shows an example Lightning web component that calls the modal component

  • A calling Lightning component can send data to the modal component using public properties. A modal component can return data to the Lightning component using its close method.

Platform Events

  • Subscribing to Aura component: An Aura component can be created to subscribe to a platform event. The lightning:empApi component, which enables listening to event messages, requires to be added to the Aura component markup.

  • The lightning:empAPI subscribe and unsubscribe methods are then called in the client controller

  • A Lightning web component can be created to subscribe to a platform event

Considerations

  • Indistinguishable: Both Lightning web components and Aura components will appear as Lightning components and indistinguishable to the admin and end user
  • Load Methods: The methods loadScript and loadStyle that are available through the platformResourceLoader module can be used to load Javascript and CSS files respectively
  • Referencing Files: Unlike Aura components, referencing of Javascript and CSS files in Lightning web components is handled in the client controller instead of the template or component markup