Forcelandia is August 8 and 9 at McMenamins Kennedy School in Portland. Click to register for this two-day event of Salesforce innovation, learning, conversations with fellow Salesforce developers and architects.
Sorry to Interrupt: Troubleshooting and Debugging Lightning Component Issues
As a Lightning Developer, you’re probably spending a good portion of your time troubleshooting component issues. This session is for those seeking tips to make debugging easier. I’ll focus on:
Categorizing Lightning component issues
Developing your debugging flow
Demonstrating available tools
Tips for debugging CSS styling issues
Tips for troubleshooting actions and server-side issues
The session will immediately follow Zayne Turner’s opening keynote on August 8, 2018, from 9:10 to 9:50AM in the Jordan Room.
Base Lightning components, introduced with the Winter ’17 release, provide developers with granular and reusable “out of the box” components that can be used to render HTML for everything from navigation menus, to form fields, to data tables, and many other UI patterns in between.
The primary value add of base Lightning components is that they apply the Salesforce Lightning Design System (SLDS) styling to the HTML that is output when the components render.
Another value add is that many of the base Lightning components raise events that can be handled within your component hierarchy.
By now you should realize that the Lightning Component Framework is an event driven architecture, and how you manage events is a critical aspect to Lightning application design.
Thankfully, raising and handling events from base Lightning components is in itself fairly straightforward and handles many of the use cases requiring events to be raised from user interaction.
What I have found in my own development experience is that there are certain edge use cases where the events raised by base Lightning components do not go far enough.
It just takes a deeper understanding of how events are raised and handled to find an elegant solution that incorporates base Lightning components and a minimal amount of custom HTML.
I would like to propose a simple solution for when you run into situations where you need a more robust set of events than what are raised by base Lightning components, and provide some background on “how” and “why” this works.
A Common Pattern: Onfocus and Onblur
One of the things that I have noticed with the architecture of base Lightning Components is that many of them share a common pattern in the way in which they raise events.
While some base Lightning components do not raise any events of their own, many components in the lightning: namespace have event attributes that can be used to raise and handle events within the component hierarchy.
Of the base components that do raise events, such as <lightning:input>, <lightning:select>, <lightning:button> and others, share the same two component event attributes: onfocus and onblur.
The focus event is raised when an element is in focus – meaning a user has clicked on or tabbed to that particular element.
blur is the opposite of focus. When an element is currently in focus and the user then clicks on or tabs to a new element, the blur event fires on the previously focused element while the focus event fires on the newly focused element.
The focus and blur events are typically associated with HTML elements such as <select>, <input> and <a>, but it is important to note that the onfocus and onblur event attributes for base Lightning components do not raise the focus or blur Document Object Model (DOM) events.
When a base Lightning component includes the onfocus or onblur event attributes in its definition, what it actually raises is an event that is custom to the Lightning Component Framework and can only be handled by another Lightning component.
Beyond Blur: Additional Base Lightning Component Event Attributes
Most of the components that raise the focus and blur events will also raise another complementary event specific to the way in which a user interacts with the component itself.
For example, in addition to the onfocus and onblur event attributes, <lightning:button> can raise a third event called click by including the onclick event attribute with a reference to a controller function.
This is because the expected interaction with the <lightning:button> component is for a user to click on it.
The <lighting:select> component, which displays a picklist of options, raises a third event called change by including the onchange event attribute in the reference to the component.
Again, this is because the expected interaction with <lightning:select> is for a user to select an option from a dropdown list, and if the newly selected value is different from the previously selected value, that may be of significance from a UX perspective and require the firing of an event.
Remember, when base Lightning components fire events, they are not DOM events – they are component events raised by the Lightning Component Framework.
While they may not be DOM events, they follow a similar propagation pattern in that the events “bubble up” through the component hierarchy and can be handled by any component in the ancestry starting from the component that fired the event all the way up to the root (top level) component. We’ll cover the concept of bubbling a little later to understand how all of this works.
The reason why it is great that Salesforce provides these event attributes for base Lightning components is because the focus and blur DOM events do not bubble and must be handled by event listeners defined at the level of the specific HTML element that raises the event.
These component events are powerful and handle most use cases for firing events directly from base Lightning components based on specific user interactions, but how does it work if you want to handle events other than focus, blur, change or click?
Base Lightning Components and DOM Events
What happens when you want to handle DOM events such as keyup or mouseover from a <lightning:input> component? How can you handle the dblclick event for a <lightning:formattedText> component?
Well…in a nutshell, you can’t. Why? Because there are no attributes defined for these events in base Lightning components.
Lightning components only support events explicitly listed in the documentation. If <lightning:input> only lists onfocus, onblur and onchange as event attributes, then those are the only events that it raises and can be handled by the parent component.
Not to worry, though. There is a solution if you want to handle DOM events that are not explicitly supported by base Lightning component event attributes.
Handling DOM Events Raised by Base Lightning Components
To handle an event that is not supported for a given base Lightning component, you simply need wrap the component in a containing HTML element. This will typically be a <div>, and you will handle the DOM event there.
For example, if you want to handle the dblclick event when a user double clicks the mouse on a <lightning:formattedText> component, simply wrap it in a <div> and include the ondblclick event attribute in the reference to the containing <div> as illustrated:
<lightning:formattedText value=“Double click on me!“ />
Why does this work?
To understand why this works, you first have to understand something called “bubbling.”
The concept of bubbling is fairly straightforward. When an event that supports bubbling is fired from an HTML element, that event can be first be handled by the actual element raising the event if it has a handler defined for the event.
Note: Not all events support bubbling. As mentioned previously, the focus and blur events do not bubble.
If the HTML element raising the event has not added a listener for the event, or if it does handle the event but does not explicitly stop bubbling by referencing the stopPropagation() function on the Event object, the event will bubble to the parent element of the element that raised the event.
Following the same pattern, the event will continue to raise its way through the DOM tree starting with the parent HTML element and continuing until bubbling is explicitly stopped or the event reaches the root of the HTML document without being handled.
How Does DOM Event Propagation Apply to Base Lightning Components?
Earlier we mentioned that base Lightning components do not support the raising of DOM events, only component events that are raised and handled within the Lightning Component Framework itself.
So what does DOM event bubbling have to do with base Lightning components?
The answer is simple if you think about what base Lightning components actually do – base components exist to simplify the process of generating HTML for UI elements that implement SLDS for you automatically.
Rather than having to hand write all of the HTML and CSS to implement SLDS prototype components such as buttons or form input fields, base Lightning components allow developers to control the styling and behavior of the rendered output by setting attribute values in the definition of the base component.
Base Lightning components, in turn, render HTML elements with references to CSS classes defined in the SLDS external stylesheet.
For example, the following reference to a base Lightning component:
<lightning:input name="mySampleComponent" label="This is a sample lightning:input component" />
To break this down, at the core of the rendered output we have an HTML <input> element that is contained by a <div> element. We also have a <span> element, which is the child of a <label> element.
The containing <div> element for the <input> as well as the <label> element are themselves wrapped by a top-level containing <div>.
That’s a lot of nesting! This complex output is simplified by the use of the <lightning:input> component, but how does this apply to raising and handling DOM events?
How Does This Work?
Let’s say that we want to handle the focus event for the <lightning:input> base Lightning component in the previous example. This would be simple because <lightning:input> has an event attribute called onfocus.
All we would need to do in order to handle focus is include the onfocus attribute and reference a controller function like this:
So now let’s say we wanted to handle the keyup event that gets raised from the <input> element when a user presses and releases a key on the keyboard.
When this event is raised we want to call a function to check whether the user pressed the “tab” or “enter” keys.
How do we do that since onkeyup is not listed as an event attribute in the documentation for <lightning:input>?
This is where we want to wrap our base Lightning component with an HTML element such as a <div> and have the containing element handle the event.
Remember, most DOM events support bubbling. In this example, the keyup event will be raised by the HTML <input> element generated by the <lightning:input> component when it is rendered.
The keyup event will not be handled by the <input> element itself, nor will it be handled by the <div> that contains it or the top-level <div> rendered by the component.
It will bubble up to our wrapper <div> and we will handle the keyup event there by calling the controller function referenced in the onkeyup event attribute.
Here’s what this would look like in your custom component markup:
<lightning:input name="mySampleComponent" label="This is a sample lightning:input component" />
Handling the DOM Event
When we handle raised events that are native to the Lightning Component Framework, we get access to more robust event handling functionality, such as getting access to the component that raised the event by using event.getSource().
Unfortunately when we raise and handle DOM events like we are doing here, referencing event.getSource() will return an ‘undefined’ value.
event.target references the HTML element that actually fired the event. In our use case, event.target will reference the <input> element where the keyup event occurred.
event.currentTarget references the HTML element that is currently handling the fired event. In our use case, event.currentTarget will reference the <div> that we used to wrap the <lightning:input> component.
Additional Considerations for Using event.target and event.currentTarget
Learning how to use event.target and event.currentTarget for DOM events and event.getSource() for component events will enable you to design a robust event-driven architecture in your custom Lightning components.
So why not just use event.target and event.currentTarget to handle all events, including DOM events and Lightning component or application events?
You can thank Locker Service for throwing cold water on that idea. event.target and event.currentTarget are not available when handling Lightning component events because of Locker Service restrictions.
Without going into the gory details, Locker Service wraps each Lightning component in a secure document that renders the HTML for that component within a virtual DOM.
Using event.target or event.currentTarget would essentially allow you to reach into the DOM for the source component, breaking encapsulation.
CSS supports an assortment of units for measuring length. Some units are absolute, some are relative to the length of other values.
Length is expressed as a number value followed by a unit of measurement, an example of an absolute value being 16px, or a relative value being 1em.
Absolute Length Units
Absolute length CSS units are used to represent fixed, physical lengths. Some units, such as the px and pt unit, are relative to physical lengths. The px unit can also be relative to the output device, where 1px can equal one device pixel. The pica, or pc unit, is relative to pt units even though it is considered an absolute length.
Absolute lengths are great to use when you know the exact dimensions of where your content will be output, such as a printer, but for Lightning Components and Applications, you will be better suited to use relative units more times than not.
This is because there is no way to anticipate the pixel density of the devices that will be interacting with your components, and your goal as a Lightning developer is to create responsive applications that are agnostic to the device in which they are displayed.
Absolute lengths can be measured by the following units:
mm – One millimeter
cm – One centimeter (equivalent to 10mm)
in – One inch (equivalent to 2.54cm)
px – One pixel (equivalent to 1/96 of an inch)
pt – One point (equivalent to 1/72 of an inch)
pc – One pica (equivalent to 12 points)
Relative Length Units
Relative length CSS units are used to represent lengths relative to other length values. This allows you to easily make elements smaller or larger than reference elements without having to hardcode specific length values.
Relative length units, for all intents and purposes, break down into two categories – units that are relative to a font size, and units that are relative to the viewport size.
Units Relative to Font Size
The most commonly used relative units calculate length based on the font size of an element. Other more esoteric units calculate length based on the size of specific characters within a font.
The units relative to font size include:
em – This is the most common relative unit and the one you should become most familiar with, as it will help you create the most scalable layouts for your components. For any property other than the font-size property itself, em is a multiple of the font-size of the current element, with 1em being equivalent to the font-size of the current element. For example, if the font-size of an element is 10px, then 1em would equal 10px, 0.5em would equal 5px, 2em would equal 20px, and so on. If no font size is specified, 1em is equal to 16px, or 12pt.
rem – Very similar to em, the rem unit is also a multiple of font-size, but instead of being relative to the current element (or the parent element in the case of the font-size property itself), rem calculates length relative to the root element of the HTML document. If you prefer to have everything in your components scale perfectly from a single value rather than from cascading values, rem may be a better option for you than em.
ex – This is one of the esoteric units mentioned above, and it is not commonly used. Known as a typographic measurement, ex is relative to the x-height of the current font – literally the height of the “x” character contained in the font. If there is no “x” character, ex defaults to 0.5em.
ch – Another fairly esoteric unit that is not commonly used, ch is similar to ex in that it is a typographic measurement, but in this case it is based on the width of the “0” (zero) character of a font.
If an em unit is used on the actual font-size property, the value is calculated based on the inherited font-size of the parent element.
Units Relative to Viewport
While having units relative to the percentage of the viewport (the visible area of a document in a browser) makes logical sense for specifying length values for elements that make up the layout of a page, in practical terms these units have not been widely adopted and I am only going to give them a brief mention for the sake of reference:
vw – The “viewport width” unit. 1vw is the equivalent of 1% of the viewport width
vh – The “viewport height” unit. 1vw is the equivalent of 1% of the viewport height