Shadow DOM

The Shadow DOM is a way to create elements that are not affected by the same attributes and properties as those in the Light DOM. The Shadow DOM provides true scope encapsulation; your element’s CSS and JS are scoped to it alone! Think of the Shadow DOM as a lightweight version of an iframe.

The DOM is what most people are talking about when they are talking about a web page’s elements rendered in your browser. The DOM, or the Document Object Model, is the API that allows a web browser to interact with and render the HTML, CSS and Javascript to create a webpage.

When you think about creating a web page, we typically think about the HTML elements we structure and style and interactive with using CSS and JS. For the sake of simplicity, we will call the elements you see rendered as the Light DOM.

The Shadow DOM by contrast is a way to create elements that are not affected by the same attributes and properties as those in the Light DOM. The Shadow DOM provides true scope encapsulation; your element’s CSS and JS are scoped to it alone! Think of the Shadow DOM as a lightweight version of an iframe.

To render elements created via the Shadow DOM, you must ‘inject’ them into the Light DOM. We’ll cover some examples of this later in the post.

You have already seen the Shadow DOM

You might not even be aware, but you have already seen the Shadow DOM in action already. A lot of complex input elements rendered in the browser are actually created via the Shadow DOM due to the encapsulated styling and javascript scope.

The most common example is the Video Tag. Take this simple example tag:

<video src="Clipped_Red_Lexus.mov" controls></video>

This simple tag results in the following rendered HTML in your browser:

video_tag_example

Notice how much “extra” HTML is rendered under the “#shadow-root”. This code is generated by your browser automatically to give you these complex UI elements like the Play Button and the Volume Slider.

These elements have their own styling and event listeners that are not affected by the host DOM.

Why should we care about the Shadow DOM?

Using the Shadow DOM you can create truly re-usable pieces of code you know will act reliably no matter where you place them. Create one widget, and use it in any of your code, and stop worry about CSS and JS collisions!

Also, most importantly, the Shadow DOM is the base from which the modern web is being built upon.

When we talk about web components, we are talking about the implementation of the Shadow DOM. When you see those fancy ‘live’ updating forms in Angular2, again, Shadow DOM.

Clearly, understanding this is quite important to understanding these new web frameworks.

Example 1: Inserting Elements into a Host Root

Here is a very basic example illustrating using the Shadow DOM to inject elements into a host root.

Example 2: Isolated styles in a Shadow DOM Element

Here is a very basic example showing the isolated CSS styling when using the Shadow DOM.

Please note the injected element’s CSS does not affect the CSS in the host element. Only the injected elements are red.

Example 3: Insertion Points with “content” tags

Here is an example showing insertion points and querying using the content tag. (Please note, that in Shadow DOM v1, the content tag will be replaced by the slot selector, read more about this below in “Whats Next”)

This simple example shows how one can select some content from the host element, inject it into the Shadow DOM template, which in turn get injected into the host DOM.

Whats next?

We reviewed some concepts about the Shadow DOM laid out in what is commonly referred to as “Shadow DOM v0”. This is to say we are working with the very first iteration of the implementation.

The new spec for v1 has, for the most part, been agreed upon and the major browser publishers are working on implementing the new features.

Hayato Ito at Google has a great list explaining some of the changes we can expect along with simple examples showing these new features.

Conclusion

While I provided only simple examples of the Shadow DOM, I hope this inspires you to explore more yourself. Thanks for reading!

Go basics – Data Types

Today we are going to walk thru basics of Go language. Starting with a list of supported data types and defining custom types.

I’ll try to show you some examples of how to deal with basic Go stuff and compare with PHP as a reference.

Data types

Integer

Integers are numbers without a decimal component. Go lang support four types for integer based on the amount of bits can address, and three  extra types based on machine architecture.

Since computers use a base-2 for representation, 8, 16, 32 and 64 tell us how many bits each of the types use. Then for the first sub set of integers Go also split them on signed and unsigned.

Signed Integers: int8, int16, int32, int64.

Unsigned Integers: uint8, uint16, uint32, uint64.

Also, a byte is an alias for uint8 and a rune for int32.

For the second sub set, the machine dependent integers we have: uint, int and uintptr.

Floating Point Numbers

Generally known as Real Numbers, represents those numbers with decimal component.

Go has two floating point types : float32 and float64.

It also has two complex number types : complex64 and complex128.

String

This data type is represented by a sequence of characters with a definite length.

Literals in Go can be created in 2 ways, with double quotes, that allows the use of special characters like \n and \t, but cannot contain new lines, or with backticks quotes, that permits the use of new lines.

You can concatenate two or more strings, like lots of languages except PHP that use a dot (.), with plus sign (+), and each individual character can be obtained using indexes.

var example string = "weird\t string\n sample!”

otherway := `weird

sample!`

In comparison with PHP, here are a couple of examples of string operations:

 PHP
$part_1 = "weird"; 
$part_2 = "string"; 
$part_3 = "sample!";
Length in PHP
$stringLength = strlen($part_1); // 5
Length in Go!
var string_length int = len(example) 
Concatenations in PHP
$full_str = "{$part_1} {$part_2}";
$full_str .= $part_3
Concatenations in Go!
var full_str string
full_str = part_1 + " " + part_2

Boolean

Booleans are a special 1 bit integer type used to indicate True or False.

The logical operators which can be used on booleans are:

and &&

or ||

not !

Arrays, Slices, Maps

Array is a set of elements of an specific type. [n]T is an array of n elements of type T, where n is the length of the set and T represents the type, i.e. to create an array of ten element length of string, it should looks like [10]string.

Examples:

  var a [10]int

  x := [5]float64 {
       34,
       63,
       56,
       84,
       23
  }

The above example in PHP looks like:

$x = array(34, 63, 56, 84, 23);

or just

$x = [34, 63, 56, 84, 23];

Slice is a segment, not fixed of an Array.

Creation of slice is via make command.

x := make([]int, 5)

It also can be initialized from array by indexes.

 

x := a[3:] //the first 3 elements of a

x := a[2:5] // specific range, elements from 2 to 5

A map is an unordered collection of key-value pairs. Also known as an associative array, a hash table or a dictionary, maps are used to look up a value by its associated key.

var x map[string]int

x["Hello"] = 1

Custom Data Types

Struct:

A structure is a user defined data type which contains named fields. In Go structs are used to represents object by the association of method to pointer of this type.

type dog struct {
	breed string
	age int
	owner string
}

type cow struct {
	age int
	farm string
}

The dot operator is used to access each field by name. The above example in PHP will look like:

<?php
class Dog {
    private $breed;
    private $age;
    private $owner;
}

class Cow {
    private $age;
    private $owner;
}
Interfaces:

In Go an interface is two things: it is a set of methods, but it is also a type.
The interface{} type, the empty interface, is the source of much confusion. The interface{} type is the interface that has no methods. Since there is no implements keyword, all types implement at least zero methods, and satisfying an interface is done automatically, all types satisfy the empty interface. That means that if you write a function that takes an interface{} value as a parameter, you can supply that function with any value.

We’ll talk about Loops, Control Structures and some design patterns in future posts. Thanks for reading

TypeScript

Intro

TypeScript is an open source compiled superset language of Javascript maintained by Microsoft. Introduced in 2012 after several internal iterations, the project was born out of the desire to add some variable typing to Javascript. Hence, TypeScript.
While you may first recoil at the idea of another transpiled javascript library, let me explain some of the great features and speed increases you can get by including it in your workflow and you might change your mind.

How it Works

TypeScript is just a superset of JS that compiles to ES3, ES5 or ES6. Think of this as a higher level language that normalizes the features of ES5 & ES6 into a version compatible with your target language and polyfills missing features.
This means, if you are compiling to ES3, TS will turn your fancy ES6 class into the syntactic sugar required to replicate it in ES3. Also, it will do it better than you.

Why TypeScript is a good thing: you can have ES6 features, now

ES6 compatibility is woefully lacking for most browsers found in the wild, which is definitely appealing if you want to use some of those cool features you hear about… especially the ones that most people gripe about the lack of in JS (classes and inheritance) when compared to most other OOP languages.
Classes and Modules are now available to you, and down compiled . You can use the super cool (and often confusing on your first encounter) “arrow” functions notation for your Anonymous Functions. Rest functions where you can finally make your functions as flexible as you want them.
When you let TypeScript transpile your code you can have all of those amazing ES6 features with your current user base’s browsers! Yes, even Safari!

Why TypeScript is a good thing: You get type hints, type checking at compile time

Loose typing has always been a gripe of higher level languages like PHP and Javascript. At its core, the argument really comes down to keeping your code clean and safe by asserting you pass and ask for the correct types of variables. If your reading this, and enjoying it, I’m sure you have encountered the terrible spiral of type juggling and the concept of ‘falsy’ when looking for an optional variable input in a function.
Type annotations allow you to specify the exact type of input and output you are passing around your functions. This not only leads to implicit assertions of your types, but also allows for great real-time syntax checking if you are using an editor that supports it.
Also, the next time you try and pass a boolean variable to a function expecting a string, your compiler will complain “LOUDLY” and refuse to compile your crap code. Using explicit variable types is the best documentation you can provide and its built into the code you are writing.

How to Install / Use It

Install TSC via NPM
npm install -g typescript
Then follow along in the easy to understand QuickStart / HelloWorld from the TS team: http://www.typescriptlang.org/docs/tutorial.html
If you cannot install it, you can also try the TS playground: http://www.typescriptlang.org/docs/tutorial.html

Who is really using TypeScript?

Well, for one, Microsoft is using it on quite a few internal projects. The Angular 2 team actually wrote the majority of the new framework using TypeScript. Also, the popular project management tool Asana’s team made a rather well publicized switch to TypeScript recently.

Should I use TypeScript?

The simple answer is, sure. Why not. I would give it a shot and try and work it into your workflow and see how it goes. Thankfully it plays nice with vanilla JS as well.
Leave us a note in the comments if you actually use TypeScript, or have a good reason not to use TypeScript, in your work.