Sunday, March 3, 2019

Lightning Web Components: A Tale of Two DOM's


The shadow DOM is a subtree that branches off the DOM (light DOM). It hides away the complexity of components from the rest of the page. It has actually been around for quite a while. In fact, all of these elements utilize the shadow DOM to hide their complex markup and styling away.

<input type="range" />
<video controls width="250"></video>
<input type="date" />

Because of the new concept of shadow DOM, we need to avoid the confusion between the DOM you knew before and this new shadow DOM. So you are going to see the term light DOM used to describe the DOM you have been familiar with and working with all these years. But before we dive into the shadow DOM, here's one more term, the logical DOM. So the logical DOM is an umbrella term, so the light DOM and shadow DOM together are a part of logical DOM.


To understand shadow DOM, let’s look at the HTML5 <video> element, which is a custom element with a shadow DOM. Because Show user agent shadow DOM is enabled in Chrome Developer Tools, you see the #shadow-root node and its child elements, which make up the shadow DOM. If you disable this option, you would see only the <video> tag, and none of its children.


There are a variety of terms that we need to understand when working with the shadow DOM.
  • Shadow Host: It is the element in the light DOM that is hosting the shadow DOM. So the shadow host, in this case, is the video tag, and it hosts the shadow root.
  • Shadow Root: It is labelled in Chrome dev tools with #shadow-root, and is the root node of the shadow tree, encapsulating a DOM subtree. All this markup within the shadow root is shadow DOM. You can also see a nested shadow tree here, which is also known as a DOM subtree. So one DOM subtree can end up hosting another DOM subtree
  • Shadow Boundary: It encapsulates styling rules that are defined within a given piece of shadow DOM. So in other words, a CSS selector that's applied in the shadow DOM doesn't apply to other elements outside of shadow DOM and vice versa. This is because styles in the shadow DOM do not cross over the shadow boundary. The shadow boundary exists at the shadow root. To clarify, the shadow boundary is a concept and is merely a term used to describe the boundary between the light DOM and shadow DOM.
Creating shadow DOM is a simple 3-step process.
  1. Select shadow host, which is an element in the light DOM that will wrap the shadow root.
  2. Create a shadow root
  3. Add elements to the shadow DOM using the same methods that you use to append elements to the light DOM: innerHTML and appendChild
In the code below, the style is only going to impact the light DOM.

<!DOCTYPE html>
<html lang="en">
<head>
    <style>
        h1 { color: red; }
    </style>
</head>
<body>
    <h1>Hello World from the light DOM</h1> 
    <div id="host"></div>

    <template>
        <h1>Hello World from the shadow DOM</h1>
    </template>

    <script>
        var template = document.querySelector('template');
        var host = document.getElementById('host');
        var root = host.attachShadow({mode: 'open'});
        root.appendChild(document.importNode(template.content, true));

        // Only going to get a reference to the light DOM
        console.log(document.querySelectorAll('h1'));

        // Only going to get a reference to the shadow DOM. For multiple pieces of shadow DOM in the page,
        // you need to get the shadow root that is appropriate for the element that you are trying to target
        console.log(root.querySelectorAll('h1'));
    </script>
</body>
</html>

Lightning Web Components

The shadow DOM for a Lightning web component is created automatically. The component author doesn’t have to implement it (no need to use the attachShadow() or appendChild() methods). Also since Lightning web components don’t use the native shadow DOM yet, you can’t view their shadow DOM in Chrome Developer Tools. Even if you enable Show user agent shadow DOM, you don’t see the shadow DOM.

Resources:
https://medium.com/front-end-weekly/the-rise-of-shadow-dom-84aa1f731e82
Share This:    Facebook Twitter

Monday, January 28, 2019

Salesforce Apex: Regular Expressions


Assume that you receive an email, and your task is to extract all the URLs present in the email body. Copy and paste is a tedious job, right? Using regex script, you can save yourself from the manual work.

You can refer the following code to extract all the URLs from an incoming email.
global class CreateTaskEmailExample implements Messaging.InboundEmailHandler {

  public static final String REGEX_URL = '(?i)\\b((?:[a-z][\\w-]+:(?:/{1,3}|[a-z0-9%])|www\\d{0,3}[.]|[a-z0-9.\\-]+[.][a-z]{2,4}/)(?:[^\\s()<>]+|\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\))+(?:\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\)|[^\\s`!()\\[\\]{};:\'".,<>?«»“”‘’]))';
 
  global Messaging.InboundEmailResult handleInboundEmail(Messaging.inboundEmail email, Messaging.InboundEnvelope env){
 
    Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();
    String plainTextBody = email.plainTextBody;

    Matcher m = Pattern.compile(REGEX_URL).matcher(plainTextBody);
    while (m.find()) {
      System.debug(m.group());
    }
    ...
    ...
    ...
    
   }
}

Similarly you can use the following regex expression for email addresses:
String REGEX_EMAIL = '(?:[a-z0-9!#$%&\'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&\'*+/=?^_`{|}~-]+)*|"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])';

and this one for phone numbers
String REGEX_PHONE = '(?:(?:\\+?([1-9]|[0-9][0-9]|[0-9][0-9][0-9])\\s*(?:[.-]\\s*)?)?(?:\\(\\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\\s*\\)|([0-9][1-9]|[0-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\\s*(?:[.-]\\s*)?)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\\s*(?:[.-]\\s*)?([0-9]{4})(?:\\s*(?:#|x\\.?|ext\\.?|extension)\\s*(\\d+))?';

Share This:    Facebook Twitter

Sunday, January 27, 2019

Javascript: Preventing Object Modification


All objects you create are extensible by default, meaning new properties can be added to the object at any time. By setting Extensible attribute on an object to false, you can prevent new properties from being added to an object. There are three different ways to accomplish this.

Preventing Extensions

One way to create a nonextensible object is with Object.preventExtensions(). In the code below, as person1 is nonextensible, the sayName() method is never added to it.
var person1 = {
   name: "Nicholas"
};

console.log(Object.isExtensible(person1));  // true

Object.preventExtensions(person1);
console.log(Object.isExtensible(person1));  // false

person1.sayName = function() {
   console.log(this.name);
};

console.log("sayName" in person1);   // false

Sealing Objects

You can use the Object.seal() method on an object to seal it. A sealed object is nonextensible, and all of its properties are nonconfigurable. That means not only can you not add new properties to the object, but you also can’t remove properties or change their type.
var person1 = {
   name: "Nicholas"
};

console.log(Object.isExtensible(person1));  // true
console.log(Object.isSealed(person1));   // false

Object.seal(person1);
console.log(Object.isExtensible(person1));  // false
console.log(Object.isSealed(person1));   // true

person1.sayName = function() {
   console.log(this.name);
};

console.log("sayName" in person1);   // false

person1.name = "Greg";
console.log(person1.name);    // "Greg"

delete person1.name;
console.log("name" in person1);   // true
console.log(person1.name);    // "Greg"

var descriptor = Object.getOwnPropertyDescriptor(person1, "name");
console.log(descriptor.configurable);   // false

Freezing Objects

If an object is frozen, you can’t add or remove properties, you can’t change properties’ types, and you can’t write to any data properties. In essence, a frozen object is a sealed object where data properties are also read-only. Frozen objects can’t become unfrozen, so they remain in the state they were in when they became frozen.
var person1 = {
   name: "Nicholas"
};
console.log(Object.isExtensible(person1));  // true
console.log(Object.isSealed(person1));   // false
console.log(Object.isFrozen(person1));   // false

Object.freeze(person1);
console.log(Object.isExtensible(person1));  // false
console.log(Object.isSealed(person1));   // true
console.log(Object.isFrozen(person1));   // true

person1.sayName = function() {
   console.log(this.name);
};

console.log("sayName" in person1);   // false

person1.name = "Greg";
console.log(person1.name);    // "Nicholas"

delete person1.name;
console.log("name" in person1);   // true
console.log(person1.name);    // "Nicholas"

var descriptor = Object.getOwnPropertyDescriptor(person1, "name");
console.log(descriptor.configurable);   // false
console.log(descriptor.writable);   // false

Share This:    Facebook Twitter

Monday, January 21, 2019

Javascript modules, named and default exports


Take this code where we have multiple classes defined in the same file.
class Person {
  constructor(name) {
    this.name = name;
  }

  walk() {
    console.log("Walk");
  }
}


class Teacher extends Person {
  constructor(name, degree) {
    super(name);
    this.degree = degree;
  }

  teach() {
    console.log("Teach");
  }
}

const teacher = new Teacher("John", "MA");
teacher.walk();

If we can split this code across multiple files, we call it modularity, and each file is known as module. So let's modularize this code as below so that each class will be in a separate file. The objects we define in a module are private by default. To make it public, we use the export keyword, and to use it we use the import keyword.

person.js
export class Person {
  constructor(name) {
    this.name = name;
  }

  walk() {
    console.log("Walk");
  }
}

teacher.js
import { Person } from "./person";

class Teacher extends Person {
  constructor(name, degree) {
    super(name);
    this.degree = degree;
  }

  teach() {
    console.log("Teach");
  }
}

index.js
import { Teacher } from "./Person";

const teacher = new Teacher("John", "MA");
teacher.walk();

The way we have used the export keyword, we call it named exports. To use default exports, modify person.js as follows:
export default class Person {
  constructor(name) {
    this.name = name;
  }

  walk() {
    console.log("Walk");
  }
}

and in teacher.js file, import Teacher module as below:
import Person from "./person";

...
...

Share This:    Facebook Twitter

Wednesday, January 9, 2019

Javascript: Destructuring

Destructuring Objects

With destructuring, you can extract multiple pieces of data at the same time via patterns in locations that receive data.

const person = {
   first: "John",
   last: "Doe",
   links: {
      social: {
         twitter: "https://twitter.com/john.ca",
         facebook: "https://facebook.com/johndoe"
      },
      web: {
         blog: "https://johndoe.com"
      }
   }
};

const { twitter, facebook } = person.links.social;

Rename the variables as you destructure
const { twitter: tweet, facebook: fb } = person.links.social;

Set fallback or default value
const settings = { width: 300, color: "black" };
const { width = 100, height = 100, color = "blue", fontSize = 25 } = settings;

Destructuring arrays

const details = ["John Doe", 123, "johndoe.com"];
const [name, id, website] = details;
console.log(name, id, website);

Destructuring comma separated string

const data = "Basketball,Sports,90210,23,John,Doe,cool";
const [itemName, category, sku, inventory] = data.split(",");

Destructuring into Rest - an example using rest parameter

const team = ["John", "Harry", "Sarah", "Keegan", "Riker"];
const [captain, assistant, ...players] = team;

Swapping Variables with Destructuring

let inRing = "Hulk Hogan";
let onSide = "The Rock";

[inRing, onSide] = [onSide, inRing];

To make order of arguments independent, wrap these 3 arguments in , and then pass an object in tipCalc function so that it destructures the object.

function tipCalc({ total = 100, tip = 0.15, tax = 0.13 }) {
   return total + tip * total + tax * total;
}

const bill = tipCalc({ tip: 0.2, total: 200 });
console.log(bill);

What is we don't pass anything in tipcalc?

function tipCalcDefault({ total = 100, tip = 0.15, tax = 0.13 } = {}) {
   return total + tip * total + tax * total;
}

const newBill = tipCalcDefault();
console.log(newBill);
Share This:    Facebook Twitter

Total Pageviews

My Social Profiles

View Sonal's profile on LinkedIn

Tags

__proto__ $Browser Access Grants Accessor properties Admin Ajax AllowsCallouts Apex Apex Map Apex Sharing AssignmentRuleHeader AsyncApexJob Asynchronous Auth Provider AWS Callbacks Connected app constructor Cookie CPU Time CSP Trusted Sites CSS Custom settings CustomLabels Data properties Database.Batchable Database.BatchableContext Database.query Describe Result Destructuring Dynamic Apex Dynamic SOQL Einstein Analytics enqueueJob Enterprise Territory Management Enumeration escapeSingleQuotes featured Flows geolocation getGlobalDescribe getOrgDefaults() getPicklistValues getRecordTypeId() getRecordTypeInfosByName() getURLParameters Google Maps Governor Limits hasOwnProperty() Heap Heap Size IIFE Immediately Invoked Function Expression Interview questions isCustom() Javascript Javascript Array jsForce Lightning Lightning Components Lightning Events lightning-record-edit-form lightning:combobox lightning:icon lightning:input lightning:select LockerService Lookup LWC Manual Sharing Map Modal Module Pattern Named Credentials NodeJS OAuth Object.freeze() Object.keys() Object.preventExtensions() Object.seal() Organization Wide Defaults Override PDF Reader Performance performance.now() Permission Sets Picklist Platform events Popup Postman Primitive Types Profiles Promise propertyIsEnumerable() prototype Query Selectivity Queueable Record types Reference Types Regex Regular Expressions Relationships Rest API Rest Operator Revealing Module Pattern Role Hierarchy Salesforce Salesforce Security Schema.DescribeFieldResult Schema.DescribeSObjectResult Schema.PicklistEntry Schema.SObjectField Schema.SObjectType Security Service Components Shadow DOM Sharing Sharing Rules Singleton Slots SOAP API SOAP Web Services SOQL SOQL injection Spread Operator Star Rating stripInaccessible svg svgIcon Synchronous this Token Triggers uiObjectInfoApi Upload Files VSCode Web Services XHR
Scroll To Top