Monthly Archives: July 2015

New regular expression features in ECMAScript 6

By Axel Rauschmayer

This blog post explains new regular expression features in ECMAScript 6. It helps if you are familiar with ES5 regular expression features and Unicode. Consult the following two chapters of “Speaking JavaScript” if you aren’t:

Overview

The following regular expression features are new in ECMAScript 6:

  • The new flag /y (sticky) anchors each match of a regular expression to the end of the previous match.

  • The new flag /u (unicode) handles surrogate pairs (such as uD83DuDE80) as code points and lets you use Unicode code point escapes (such as u{1F680}) in regular expressions.

  • The new data property flags gives you access to the flags of a regular expression, just like source already gives you access to the pattern in ES5:

        > /abc/ig.source // ES5
        'abc'
        > /abc/ig.flags // ES6
        'gi'
    
  • You can use the constructor RegExp() to make a copy of a regular expression:

        > new RegExp(/abc/ig).flags
        'gi'
        > new RegExp(/abc/ig, 'i').flags // change flags
        'i'
    

New flag /y (sticky)

The new flag /y changes two things while matching a regular expression re against a string:

  • Anchored to re.lastIndex: The match must start at re.lastIndex (the index after the previous match). This behavior is similar to the ^ anchor, but with that anchor, matches must always start at index 0.
  • Match repeatedly: If a match was found, re.lastIndex is set to the index after the match. This behavior is similar to the /g flag. Like /g, /y is normally used to match multiple times.

The following function implements the sticky flag for RegExp.prototype.exec().

    function execSticky(regex, str) {
        // Anchor the regex to the beginning of the string
        let matchSource = regex.source;
        if (!matchSource.startsWith('^')) {
            matchSource = '^' + matchSource;
        }
        // Ensure that instance property `lastIndex` is updated
        let matchFlags = regex.flags; // ES6 feature!
        if (!regex.global) {
            matchFlags = matchFlags + 'g';
        }
        let matchRegex = new RegExp(matchSource, matchFlags);
    
        // Ensure we start matching `str` at `regex.lastIndex`
        const matchOffset = regex.lastIndex;
        const matchStr = str.slice(matchOffset);
        let match = matchRegex.exec(matchStr);
    
        // Translate indices from `matchStr` to `str`
        regex.lastIndex = matchRegex.lastIndex + matchOffset;
        match.index = match.index + matchOffset;
        return match;
    }

Let’s look at how various regular expression operations react to the /y flag. The following tables give an overview. I’ll provide more details afterwards, followed by an example of what sticky matching can be used for.

Methods of regular expressions (re is the regular expression that a method is invoked on):

Flags Start matching Anchored to Result if match No match re.lastIndex
exec() 0 Match object null unchanged
/g re.lastIndex Match object null index after match
/y re.lastIndex re.lastIndex Match object null index after match
/gy re.lastIndex re.lastIndex Match object null index after match
test() (Any) (like exec()) (like exec()) true false (like exec())

Methods of strings (str is the string that a method is invoked on, re is the regular expression parameter):

Flags Start matching Anchored to Result if match No match re.lastIndex
search() –, /g 0 Index of match -1 unchanged
/y, /gy 0 0 Index of match -1 unchanged
match() 0 Match object null unchanged
/y re.lastIndex re.lastIndex Match object null index after match
/g After prev. match (loop) Array with matches null 0
/gy After prev. match (loop) After prev. match Array with matches null 0
split() –, /g After prev. match (loop) Array with strings between matches [str] unchanged
/y, /gy After prev. match (loop) After prev. match Array with empty strings between matches [str] unchanged
replace() 0 First match replaced No repl. unchanged
/y 0 0 First match replaced No repl. unchanged
/g After prev. match (loop) All matches replaced No repl. unchanged
/gy After prev. match (loop) After prev. match All matches replaced No repl. unchanged

RegExp.prototype.exec(str)

If /g is not set, matching always starts at the beginning, but skips ahead until a match is found. REGEX.lastIndex is not changed.

    const REGEX = /a/;
    
    REGEX.lastIndex = 7; // ignored
    const match = REGEX.exec('xaxa');
    console.log(match.index); // 1
    console.log(REGEX.lastIndex); // 7 (unchanged)

If /g is set, matching starts at REGEX.lastIndex and skips ahead until a match is found. REGEX.lastIndex is set to the position after the match. That means that you receive all matches if you loop until exec() returns null.

    const REGEX = /a/g;
    
    REGEX.lastIndex = 2;
    const match = REGEX.exec('xaxa');
    console.log(match.index); // 3
    console.log(REGEX.lastIndex); // 4 (updated)
    
    // No match at index 4 or later
    console.log(REGEX.exec('xaxa')); // null

If only /y is set, matching starts at REGEX.lastIndex and is anchored to that position (no skipping ahead until a match is found). REGEX.lastIndex is updated similarly to when /g is set.

    const REGEX = /a/y;
    
    // No match at index 2
    REGEX.lastIndex = 2;
    console.log(REGEX.exec('xaxa')); // null
    
    // Match at index 3
    REGEX.lastIndex = 3;
    const match = REGEX.exec('xaxa');
    console.log(match.index); // 3
    console.log(REGEX.lastIndex); // 4

Setting both /y and /g is the same as only setting /y.

RegExp.prototype.test(str)

test() works the same as exec(), but it returns true or false (instead of a match object or null) when matching succeeds or fails:

    const REGEX = /a/y;
    
    REGEX.lastIndex = 2;
    console.log(REGEX.test('xaxa')); // false
    
    REGEX.lastIndex = 3;
    console.log(REGEX.test('xaxa')); // true
    console.log(REGEX.lastIndex); // 4

String.prototype.search(regex)

search() ignores the flag /g and lastIndex (which is not changed, either). Starting at the beginning of the string, it looks for the first match and returns its index (or -1 if there was no match):

    const REGEX = /a/;
    
    REGEX.lastIndex = 2; // ignored
    console.log('xaxa'.search(REGEX)); // 1

If you set the flag /y, lastIndex is still ignored, but the regular expression is now anchored to index 0.

    const REGEX = /a/y;
    
    REGEX.lastIndex = 1; // ignored
    console.log('xaxa'.search(REGEX)); // -1 (no match)

String.prototype.match(regex)

match() has two modes:

  • If /g is not set, it works like exec().
  • If /g is set, it returns an Array with the string parts that matched, or null.

If the flag /g is not set, match() captures groups like exec():

    {
        const REGEX = /a/;
    
        REGEX.lastIndex = 7; // ignored
        console.log('xaxa'.match(REGEX).index); // 1
        console.log(REGEX.lastIndex); // 7 (unchanged)
    }
    {
        const REGEX = /a/y;
    
        REGEX.lastIndex = 2;
        console.log('xaxa'.match(REGEX)); // null
    
        REGEX.lastIndex = 3;
        console.log('xaxa'.match(REGEX).index); // 3
        console.log(REGEX.lastIndex); // 4
    }

If only the flag /g is set then match() returns all matching substrings in an Array (or null). Matching always starts at position 0.

    const REGEX = /a|b/g;
    REGEX.lastIndex = 7;
    console.log('xaxb'.match(REGEX)); // ['a', 'b']
    console.log(REGEX.lastIndex); // 0

If you additionally set the flag /y, then matching is still performed repeatedly, while anchoring the regular expression to the index after the previous match (or 0).

    const REGEX = /a|b/gy;
    
    REGEX.lastIndex = 0; // ignored
    console.log('xab'.match(REGEX)); // null
    REGEX.lastIndex = 1; // ignored
    console.log('xab'.match(REGEX)); // null
    
    console.log('ab'.match(REGEX)); // ['a', 'b']
    console.log('axb'.match(REGEX)); // ['a']

String.prototype.split(separator, limit)

The complete details of split() are explained in Speaking JavaScript.

For ES6, it is interesting to see how things change if you use the flag /y.

With /y, the string must start with a separator:

    > 'x##'.split(/#/y) // no match
    [ 'x##' ]
    > '##x'.split(/#/y) // 2 matches
    [ '', '', 'x' ]

Subsequent separators are only recognized if they immediately follow the first separator:

    > '#x#'.split(/#/y) // 1 match
    [ '', 'x#' ]
    > '##'.split(/#/y) // 2 matches
    [ '', '', '' ]

That means that the string before the first separator and the strings between separators are always empty.

As usual, you can use groups to put parts of the separators into the result array:

    > '##'.split(/(#)/y)
    [ '', '#', '', '#', '' ]

String.prototype.replace(search, replacement)

Without the flag /g, replace() only replaces the first match:

    const REGEX = /a/;
    
    // One match
    console.log('xaxa'.replace(REGEX, '-')); // 'x-xa'

If only /y is set, you also get at most one match, but that match is always anchored to the beginning of the string. lastIndex is ignored and unchanged.

    const REGEX = /a/y;
    
    // Anchored to beginning of string, no match
    REGEX.lastIndex = 1; // ignored
    console.log('xaxa'.replace(REGEX, '-')); // 'xaxa'
    console.log(REGEX.lastIndex); // 1 (unchanged)
    
    // One match
    console.log('axa'.replace(REGEX, '-')); // '-xa'

With /g set, replace() replaces all matches:

    const REGEX = /a/g;
    
    // Multiple matches
    console.log('xaxa'.replace(REGEX, '-')); // 'x-x-'

With /gy set, replace() replaces all matches, but each match is anchored to the end of the previous match:

    const REGEX = /a/gy;
    
    // Multiple matches
    console.log('aaxa'.replace(REGEX, '-')); // '--xa'

The parameter replacement can also be a function, consult “Speaking JavaScript” for details.

Example: using sticky matching for tokenizing

The main use case for sticky matching is tokenizing, turning a text into a sequence of tokens. One important trait about tokenizing is that tokens are fragments of the text and that there must be no gaps between them. Therefore, sticky matching is perfect here.

    function tokenize(TOKEN_REGEX, str) {
        let result = [];
        let match;
        while (match = TOKEN_REGEX.exec(str)) {
            result.push(match[1]);
        }
        return result;
    }
    
    const TOKEN_GY = /s*(+|[0-9]+)s*/gy;
    const TOKEN_G  = /s*(+|[0-9]+)s*/g;

In a legal sequence of tokens, sticky matching and non-sticky matching produce the same output:

    > tokenize(TOKEN_GY, '3 + 4')
    [ '3', '+', '4' ]
    > tokenize(TOKEN_G, '3 + 4')
    [ '3', '+', '4' ]

If, however, there is non-token text in the string then sticky matching stops tokenizing, while non-sticky matching skips the non-token text:

    > tokenize(TOKEN_GY, '3x + 4')
    [ '3' ]
    > tokenize(TOKEN_G, '3x + 4')
    [ '3', '+', '4' ]

The behavior of sticky matching during tokenizing helps with error handling.

New flag /u (unicode)

The flag /u switches on a special Unicode mode for a regular expression. That mode has two features:

  1. You can use Unicode code point escape sequences such as u{1F42A} for specifying characters via code points. Normal Unicode escapes such as u03B1 only have a range of four hexadecimal digits (which equals the basic multilingual plane).

  2. “characters” in the regular expression pattern and the string are code points (not UTF-16 code units). Code units are converted into code points.

A later section has more information on escape sequences. I’ll explain the consequences of feature 2 next. Instead of Unicode code point escapes (e.g., u{1F680}), I’m using two UTF-16 code units (e.g., uD83DuDE80). That makes it clear that surrogate pairs are grouped in Unicode mode and works in both Unicode mode and non-Unicode mode.

    > 'u{1F680}' === 'uD83DuDE80' // Unicode code point vs. two surrogate pairs
    true

Consequence: you can’t search for individual surrogates, anymore

If the string contains surrogate pairs such as uD83DuDC2A in Unicode mode then those become code points. Therefore, neither one of the surrogates will be found in the string:

    > /^uD83D/u.test('uD83DuDC2A')
    false
    > /^uD83D/.test('uD83DuDC2A')
    true

Consequence: you can put code points in character classes

In Unicode mode, you can put code points into character classes and they won’t be interpreted as two characters, anymore.

    > /^[uD83DuDC2A]$/u.test('uD83DuDC2A')
    true
    > /^[uD83DuDC2A]$/.test('uD83DuDC2A')
    false
    
    > /^[uD83DuDC2A]$/u.test('uD83D')
    false
    > /^[uD83DuDC2A]$/.test('uD83D')
    true

Consequence: the dot operator (.) matches code points, not code units

In Unicode mode, the dot operator matches code points (one or two code units). In non-Unicode mode, it matches single code units. For example:

    > 'uD83DuDE80'.match(/./gu).length
    1
    > 'uD83DuDE80'.match(/./g).length
    2

Consequence: quantifiers apply to code points, not code units

In Unicode mode, quantifiers apply to code points (one or two code units). In non-Unicode mode, they apply to single code units. For example:

    > /uD83DuDE80{2}/u.test('uD83DuDE80uD83DuDE80')
    true
    
    > /uD83DuDE80{2}/.test('uD83DuDE80uD83DuDE80')
    false
    > /uD83DuDE80{2}/.test('uD83DuDE80uDE80')
    true

New data property flags

In ECMAScript 6, regular expressions have the following data properties:

  • The pattern: source
  • The flags: flags
  • Individual flags: global, ignoreCase, multiline, sticky, unicode
  • Other: lastIndex

As an aside, lastIndex is the only instance property now, all other data properties are implemented via internal instance properties and getters such as get RegExp.prototype.global.

The property source (which already existed in ES5) contains the regular expression pattern as a string:

    > /abc/ig.source
    'abc'

The property flags is new, it contains the flags as a string, with one character per flag:

    > /abc/ig.flags
    'gi'

You can’t change the flags of an existing regular expression (ignoreCase etc. have always been immutable), but flags allows you to make a copy where the flags are changed:

    function copyWithIgnoreCase(regex) {
        return new RegExp(regex.source, regex.flags+'i');
    }

The next section explains another way to make modified copies of regular expressions.

RegExp() can be used as a copy constructor

In ES6 there are two variants of the constructor RegExp() (the second one is new):

  • new RegExp(pattern : string, flags = '')
    A new regular expression is created as specified via pattern. If flags is missing, the empty string '' is used.

  • new RegExp(regex : RegExp, flags = regex.flags)
    regex is cloned. If flags is provided then it determines the flags of the copy.

The following interaction demonstrates the latter variant:

    > new RegExp(/abc/ig).flags
    'gi'
    > new RegExp(/abc/ig, 'i').flags // change flags
    'i'

Therefore, the RegExp constructor gives us another way to change flags:

    function copyWithIgnoreCase(regex) {
        return new RegExp(regex, regex.flags+'i');
    }

Escape sequences in JavaScript

There are three parameterized escape sequences for representing characters in JavaScript:

  • Hex escape (exactly two hexadecimal digits): xHH

        > 'x7A' === 'z'
        true
    
  • Unicode escape (exactly four hexadecimal digits): uHHHH

        > 'u007A' === 'z'
        true
    
  • Unicode code point escape (1 or more hexadecimal digits): u{···}

        > 'u{7A}' === 'z'
        true
    

Unicode code point escapes are new in ES6.

The escape sequences can be used in the following locations:

uHHHH u{···} xHH
Identifiers
String literals
Template literals
Regular expression literals Only with flag /u

Identifiers:

  • A 4-digit Unicode escape uHHHH becomes a single code point.
  • A Unicode code point escape u{···} becomes a single code point.
    > let hello = 123;
    > hellu{6F}
    123

String literals:

  • Strings are internally stored as UTF-16 code units.
  • A hex escape xHH contributes a UTF-16 code unit.
  • A 4-digit Unicode escape uHHHH contributes a UTF-16 code unit.
  • A Unicode code point escape u{···} contributes the UTF-16 encoding of its code point (one or two UTF-16 code units).

Template literals:

  • In template literals, escape sequences are handled like in string literals.
  • In tagged templates, how escape sequences are interpreted depends on the tag function. It can choose between two interpretations:
    • Cooked: escape sequences are handled like in string literals.
    • Raw: escape sequences are handled as a sequence of characters.
    > `hellu{6F}` // cooked
    'hello'
    > String.raw`hellu{6F}` // raw
    'hellu{6F}'

Regular expressions:

  • Unicode code point escapes are only allowed if the flag /u is set, because u{3} is interpreted as three times the character u, otherwise:

        > /^u{3}$/.test('uuu')
        true
    

Escape sequences in the ES6 spec

Various information:

  • The spec treats source code as a sequence of Unicode code points: “Source Text

  • Unicode escape sequences sequences in identifiers: “Names and Keywords

  • Strings are internally stored as sequences of UTF-16 code units: “String Literals

  • Strings – how various escape sequences are translated to UTF-16 code units: “Static Semantics: SV

  • Template literals – how various escape sequences are translated to UTF-16 code units: “Static Semantics: TV and TRV

Regular expressions

The spec distinguishes between BMP patterns (flag /u not set) and Unicode patterns (flag /u set). Sect. “Pattern Semantics” explains that they are handled differently and how.

As a reminder, here is how grammar rules are be parameterized in the spec:

  • If a grammar rule R has the subscript [U] then that means there are two versions of it: R and R_U.
  • Parts of the rule can pass on the subscript via [?U].
  • If a part of a rule has the prefix [+U] it only exists if the subscript [U] is present.
  • If a part of a rule has the prefix [~U] it only exists if the subscript [U] is not present.

You can see this parameterization in action in Sect. “Patterns”, where the subscript [U] creates separate grammars for BMP patterns and Unicode patterns:

  • IdentityEscape: In BMP patterns, many characters can be prefixed with a backslash and are interpreted as themselves (for example: if u is not followed by four hexadecimal digits, it is interpreted as u). In Unicode patterns that only works for the following characters (which frees up u for Unicode code point escapes): ^ $ . * + ? ( ) [ ] { } |

  • RegExpUnicodeEscapeSequence: "u{" HexDigits "}" is only allowed in Unicode patterns. In those patterns, lead and trail surrogates are also grouped to help with UTF-16 decoding.

Sect. “CharacterEscape” explains how various escape sequences are translated to characters (roughly: either code units or code points).

String methods using regular expressions delegate to regular expression methods

The following string methods now delegate their work to regular expression methods:

  • String.prototype.match calls RegExp.prototype[Symbol.match].
  • String.prototype.replace calls RegExp.prototype[Symbol.replace].
  • String.prototype.search calls RegExp.prototype[Symbol.search].
  • String.prototype.split calls RegExp.prototype[Symbol.split].

Support in engines and transpilers

As usual, consult the compatibility table by kangax to find out what is supported where:

Further reading

If you want to know in more detail how the regular expression flag /u works, I recommend the article “Unicode-aware regular expressions in ECMAScript 6” by Mathias Bynens.

Source:: 2ality

Learn LESS in 10 Minutes (or Less)

By Danny Markov

learn-less-in-10-minutes-or-less

We all know CSS can be a bit frustrating to write, especially when it comes to more serious projects with thousands of lines of code. You end up duplicating the same rules all over the place and using your editor’s search and replace for every color change. It takes a lot of effort and discipline to keep your CSS maintainable. But it doesn’t have to be this way.

Luckily, the web development community has solved this problem. We now have CSS pre-processors such as Less, Sass and Stylus. They give us a number of benefits over plain CSS:

  • Variables, so that you can define and easily change values throughout your stylesheet. (This is actually coming to CSS some day.)
  • Dynamically calculated values. (In CSS we recently got calc, but it is only for length units.)
  • Mixins, which enable you to reuse and combine styles. They even support passing arguments.
  • Functions, which give you a number of handy utilities for manipulating color, converting images to data-uris and more.

The negative aspect is that if you use one of these pre-processors, you will need to compile your stylesheets down to regular CSS so that it works in browsers.

In this quick lesson we are going to cover the basics of Less. It is the most widely used CSS pre-processor at the moment, with hugely popular projects like Bootstrap adopting it.

1. Getting Started

Less is written in JavaScript, and needs either Node.js or a web browser to run. You can include less.js in your web site and it can compile all the linked .less stylesheets in real time, but this is slow and is not recommended. The recommended way is to compile your less stylesheets ahead of time and deploy a regular CSS file online. There are also a number of free graphical programs that can compile .less files for you, but in this article we will cover node.js.

If you have node installed, and you know what a terminal is, go ahead and open one. Then install less using NPM:

npm install -g less

This will give you access to the lessc command from any open terminal, enabling you to compile your .less files into vanilla CSS like this:

lessc styles.less > styles.css

Let’s say we’ve written all our stylesheet rules with LESS in styles.less. With the above line, our code will be transformed to plain CSS in styles.css. All that is left is to link this css file our HTML. If there was a compilation mistake, it will show up in your terminal.

2. Variables

One of the main features of Less is the ability to create variables just like you would in a standard programming language. They can store any type of value you find yourself using frequently: colors, dimensions, selectors, font names, URLs and so on. The philosophy of less is to reuse the CSS syntax where possible.

Here, we define two variables, one for background color and one for text color, both containing hexadecimal codes.

@background-color: #ffffff;
@text-color: #1A237E;

p{
  background-color: @background-color;
  color: @text-color;
  padding: 15px;
}

ul{
  background-color: @background-color;
}

li{
  color: @text-color;
}

Which converted to CSS looks like this:

p{
  background-color: #ffffff;
  color: #1A237E;
  padding: 15px;
}

ul{
  background-color: #ffffff;
}

li{
  color: #1A237E;
}

In the example above, the background color is white, while the text is dark. If, let’s say, we want to switch them around and have dark elements with white text, we can simply change the values of the variables, instead of manually replacing every occurrence.

For more about variables in Less read here.

3. Mixins

LESS enables us to use an existing class or ids and apply all it’s styles directly to another selector. The following example will clear things up:

#circle{
  background-color: #4CAF50;
  border-radius: 100%;
}

#small-circle{
  width: 50px;
  height: 50px;
  #circle
}

#big-circle{
  width: 100px;
  height: 100px;
  #circle
}

Which translates to the following CSS:

#circle {
  background-color: #4CAF50;
  border-radius: 100%;
}
#small-circle {
  width: 50px;
  height: 50px;
  background-color: #4CAF50;
  border-radius: 100%;
}
#big-circle {
  width: 100px;
  height: 100px;
  background-color: #4CAF50;
  border-radius: 100%;
}

If you don’t want the mixin to appear as a rule in the CSS you can place parentheses after it:

#circle(){
  background-color: #4CAF50;
  border-radius: 100%;
}

#small-circle{
  width: 50px;
  height: 50px;
  #circle
}

#big-circle{
  width: 100px;
  height: 100px;
  #circle
}

Which results in:

#small-circle {
  width: 50px;
  height: 50px;
  background-color: #4CAF50;
  border-radius: 100%;
}
#big-circle {
  width: 100px;
  height: 100px;
  background-color: #4CAF50;
  border-radius: 100%;
}

Another cool thing mixins can do is receive parameters. In the following example we add an argument for the width and height of our circles, with a default value of 25 pixels.

#circle(@size: 25px){
  background-color: #4CAF50;
  border-radius: 100%;

  width: @size;
  height: @size;
}

#small-circle{
  #circle
}

#big-circle{
  #circle(100px)
}

This will create a small circle 25×25 and a big one 100×100 pixels.

#small-circle {
  background-color: #4CAF50;
  border-radius: 100%;
  width: 25px;
  height: 25px;
}
#big-circle {
  background-color: #4CAF50;
  border-radius: 100%;
  width: 100px;
  height: 100px;
}

Read more about Less mixins in their official documentation.

4. Nesting and Scope

Nesting can be used to structure your stylesheet in a way that matches the HTML structure of the page, while reducing the chance of conflicts. Here is an example of an unordered list and its children:

ul{
  background-color: #03A9F4;
  padding: 10px;
  list-style: none;

  li{
    background-color: #fff;
    border-radius: 3px;
    margin: 10px 0;
  }
}

And the CSS will look like so:

ul {
  background-color: #03A9F4;
  padding: 10px;
  list-style: none;
}
ul li {
  background-color: #fff;
  border-radius: 3px;
  margin: 10px 0;
}

Just like in programming languages, in Less variables receive their values depending on the scope. If the value isn’t specified in the specific scope, LESS will look for it in upper blocks until it finds the nearest declaration.

@text-color: #000000;

ul{
  @text-color: #fff;
  background-color: #03A9F4;
  padding: 10px;
  list-style: none;

  li{
    color: @text-color;
    border-radius: 3px;
    margin: 10px 0;
  }
}

Translated to CSS, our li will have white colored text, since we’ve predefined @text-color in the ul rules.

ul {
  background-color: #03A9F4;
  padding: 10px;
  list-style: none;
}
ul li {
  color: #ffffff;
  border-radius: 3px;
  margin: 10px 0;
}

Learn more about scope here.

5. Operations

You can do basic math operations to numerical values and colors. Lets say we want to have two divs placed next to each other, the second one being twice as wide and with a different background.

@div-width: 100px;
@color: #03A9F4;

div{
  height: 50px;
  display: inline-block;
}

#left{
  width: @div-width;
  background-color: @color - 100;
}

#right{
  width: @div-width * 2;
  background-color: @color;
}

LESS knows what the measuring units are and won’t mess them up.

div {
  height: 50px;
  display: inline-block;
}
#left {
  width: 100px;
  background-color: #004590;
}
#right {
  width: 200px;
  background-color: #03a9f4;
}

6. Functions

LESS has functions too! It’s starting to look more and more like a programming language, isn’t it?

Let’s take a look at fadeout, a function that decreases the opacity of a color.

@var: #004590;

div{
  height: 50px;
  width: 50px;
  background-color: @var;

  &:hover{
    background-color: fadeout(@var, 50%)
  }
}

The ampersand (&) is replaced with the parent selector, which results in this CSS:

div {
  height: 50px;
  width: 50px;
  background-color: #004590;
}
div:hover {
  background-color: rgba(0, 69, 144, 0.5);
}

With the code above, when our div is hovered it will turn halfway transparent making mouse over transitions easier than ever. There are a lot of other useful functions for manipulating colors, detecting the size of images and even embedding assets as data-uri in the stylesheet. See the full list of functions here.

Further reading

You now know enough of Less to get started! Every CSS file is a valid Less stylesheet, so you can start cleaning up that old and unwieldy .css right away. As you learn more, you will be able to make the code even better. Here is what we recommend that you read next:

  • All the language features – link
  • LESS function reference – link
  • Editor and compiler in the browser – link

Source:: Tutorialzine.com

What do ES6 modules export?

By Axel Rauschmayer

CommonJS modules export values, while ES6 modules export immutable bindings. This blog post explains what that means.

You should be loosely familiar with ES6 modules. If you aren’t, you can consult the chapter on modules in “Exploring ES6”.

CommonJS modules export values

With CommonJS (Node.js) modules, things work in familiar ways.

Importing a value into a variable works like an assignment and means that you get a snapshot of that value:

    //------ lib.js ------
    var mutableValue = 3;
    function incMutableValue() {
        mutableValue++;
    }
    module.exports = {
        mutableValue: mutableValue,
        incMutableValue: incMutableValue,
    };
    
    //------ main1.js ------
    var mutableValue = require('./lib').mutableValue;
    var incMutableValue = require('./lib').incMutableValue;
    
    // The imported value is a (disconnected) snapshot
    console.log(mutableValue); // 3
    incMutableValue();
    console.log(mutableValue); // 3
    
    // The imported value can be changed
    mutableValue++;
    console.log(mutableValue); // 4

The same thing happens if you access the value via the exports object:

    //------ main2.js ------
    var lib = require('./lib');
    
    // The imported value is a (disconnected) snapshot
    console.log(lib.mutableValue); // 3
    lib.incMutableValue();
    console.log(lib.mutableValue); // 3
    
    // The imported value can be changed
    lib.mutableValue++;
    console.log(lib.mutableValue); // 4

ES6 modules export immutable bindings

In contrast to CommonJS modules, ES6 modules export bindings, live connections to values. The following code demonstrates how that works:

    //------ lib.js ------
    export let mutableValue = 3;
    export function incMutableValue() {
        mutableValue++;
    }
    
    //------ main1.js ------
    import { mutableValue, incMutableValue } from './lib';
    
    // The imported value is live
    console.log(mutableValue); // 3
    incMutableValue();
    console.log(mutableValue); // 4
    
    // The imported value can't be changed
    mutableValue++; // TypeError

If you import the module object via the asterisk (*), you get similar results:

    //------ main2.js ------
    import * as lib from './lib';
    
    // The imported value is live
    console.log(lib.mutableValue); // 3
    lib.incMutableValue();
    console.log(lib.mutableValue); // 4
    
    // The imported value can't be changed
    lib.mutableValue++; // TypeError

Why export bindings?

Given that exporting bindings is different from how data is normally transported in JavaScript – why do it this way? It has the benefit of making it easier to deal with cyclic dependencies. The following code is an example of a cyclic dependency:

    //------ a.js ------
    import {bar} from 'b';
    export function foo() {
        bar();
    }
    
    //------ b.js ------
    import {foo} from 'a';
    export function bar() {
        if (Math.random()) foo();
    }

a.js imports bar from b.js, which means that b.js is executed before a.js. But how can b.js access foo then, if a.js hasn’t provided a value for it, yet? b.js imports a binding, which initially refers to an empty slot. Once a.js is executed, it fills in that slot. Therefore, b.js only has a problem if it uses foo in the top level of its body, while it is executed. Using foo in entities that are accessed after the evaluation of a.js are fine. One such entity is the function bar().

This may seem like an theoretical exercise, but cyclic dependencies can happen relatively easily in large code bases, especially during refactoring. Cycles tend to be longer (for example: m1 imports m2 imports m3 imports m4 imports m1), but the problem is the same.

Exporting bindings

How are bindings handled by JavaScript? Exports are managed via the data structure export entry. All export entries (except those for re-exports) have the following two names:

  • Local name: is the name under which the export is stored inside the module.
  • Export name: is the name that importing modules need to use to access the export.

After you have imported an entity, that entity is always accessed via a pointer that has the two components module and local name. In other words, that pointer refers to a binding inside a module.

Let’s examine the export names and local names created by various kinds of exporting.

Export clause

    function foo() {}
    export { foo };
  • Local name: foo
  • Export name: foo
    function foo() {}
    export { foo as bar };
  • Local name: foo
  • Export name: bar

Inline exports

This is an inline export:

    export function foo() {}

It is equivalent to the following code:

    function foo() {}
    export { foo };

Therefore, we have the following names:

  • Local name: foo
  • Export name: foo

Default exports

There are two kinds of default exports:

  • Default exports of hoistable declarations (function declarations, generator declarations) and class declarations are similar to normal inline exports in that named local entities are created and tagged.
  • All other default exports are about exporting the results of expressions.
Default-exporting expressions

The following code default-exports the result of the expression 123:

    export default 123;

It is equivalent to:

    let *default* = 123; // *not* legal JavaScript
    export { *default* as default };

If you default-export an expression, you get:

  • Local name: *default*
  • Export name: default

The local name was chosen so that is wouldn’t clash with any other local name.

Note that a default export still leads to a binding being exported. But, due to *default* not being a legal identifier, you can’t access that binding from inside the module.

Default-exporting hoistable declarations and class declarations

The following code default-exports a function declaration:

    export default function foo() {}

It is equivalent to:

    function foo() {}
    export { foo as default };

The names are:

  • Local name: foo
  • Export name: default

That means that you can change the value of the default export from within the module, by assigning a different value to foo.

(Only) for default exports, you can also omit the name of a function declaration:

    export default function () {}

That is very similar to default-exporting an expression and therefore equivalent to:

    function *default*() {} // *not* legal JavaScript
    export { *default* as default };

The names are:

  • Local name: *default*
  • Export name: default

Default-exporting generator declarations and class declarations works similarly to default-exporting function declarations.

Re-exports

Re-exports are handled differently from normal exports. A re-export does not have a local name, it refers to the re-exported entity via that entity’s module and export name.

Exported bindings in the spec

This section gives pointers into the ECMAScript 2015 (ES6) language specification.

Managing imported bindings:

The export names and local names created by the various kinds of exports are shown in table 42 in the section “Source Text Module Records”. The section “Static Semantics: ExportEntries” has more details. You can see that export entries are set up statically (before evaluating the module), evaluating export statements is described in the section “Runtime Semantics: Evaluation”.

Be careful with ES6 transpilers

ES6 transpilers compile ES6 modules to ES5. Due to the completely new way of passing on data (via bindings), you should expect the ES5 version to not always be completely compliant with the ES6 spec. Things are even trickier when transpiled ES6 code has to interoperate with native CommonJS or AMD modules.

That being said, Babel hews pretty close to the spec, as you can see in the GitHub repository for this blog post.

Source:: 2ality

What are your favorite JavaScript ES6 features?

By Axel Rauschmayer

I’ve created a survey to find out what ES6 (a.k.a. ECMAScript 2015) features people like most:

I previously asked the same question on Twitter and one feature stood out: Classes were the only feature that some people disliked, but they were also liked by a few people (I cover their pros and cons in “Exploring ES6”). On Twitter, the top 10 most liked features were:

  1. Arrow functions
  2. Modules
  3. Destructuring
  4. Generators
  5. Promises
  6. Template literals
  7. Spread operator
  8. New object literal features (including method definitions)
  9. let and const
  10. Rest parameters

Source:: 2ality

Comparing Bootstrap With Google’s New Material Design Lite

By Danny Markov

comparing-bootstrap-with-material-design-lite

Since Google announced Material Design with the introduction of Android 5.0, a large number of frontend frameworks emerged with the goal of bringing the concept to web apps. We had Mui, Material-UI, and even Google’s own Polymer framework. Some of the critiques against them is that they are difficult to use or don’t fully conform to the Material Design guidelines.

This is why, in the beginning of July, Google publicly released a new framework that is easy to use and has no additional dependencies. It’s called Material Design Lite (MDL for short), and it is aimed straight at the hugely popular Bootstrap framework. But which is better? Let’s find out.

Key Differences

Before we dive into the examples, let’s brake down the major differences between Bootstrap and Material Design Lite:

Philosophy

  • Bootstrap was originally built by Twitter with the purpose of making it easy to build responsive websites. It gives you a lot of components and customization options for making web apps.
  • Material Design Lite is a way for Google to spread its material design concept to the web. It gives you only the base building blocks for building material apps. The rest is up to the developer.

Development Experience

  • Bootstrap has a very detailed documentation. Development involves copy pasting from the examples and getting a usable result fast.
  • MDL is built around BEM, and components are built by combining multiple classes. This approach gives a great deal of control, but can sometimes lead to unwieldy HTML.

Components

  • In Bootstrap, almost all built-in HTML elements are styled and can fit nicely together in a layout. It gives you a great number of additional components for any type of design.
  • MDL gives you fewer components than Bootstrap, but they are all focused on building modern Material Design applications. They come with animations and beautiful default styles.

Layout

  • Bootstrap has an advanced grid system with offsets, column wrapping, hiding and reordering of columns.
  • MDL has a more primitive grid that gets the job done most of the time, but doesn’t support advanced features.

Design

  • Bootstrap gives you a passable default design which we have grown tired of by now, but there are plenty of wonderful themes to chose from.
  • MDL looks fresh and features bold colors and animations. It dictates exactly how your web app should look like and gives you a limited opportunity for customization by choosing base and accent colors.

Community

  • Bootstrap has been around for quite some time and has an enormous community, which produces themes, plugins and blog posts.
  • MDL came out only recently but has already become quite popular on GitHub. However it is still in its early days, and most of the time you are on your own.

But how do these frameworks compare in practice? This is a more difficult question to answer. This is why we’ve prepared a number of examples implemented in both frameworks that will help you compare what they are capable of. Click the images to see the examples side by side.

1. Grid

Arguably, the grid is the most important building block for a modern web page. It makes it possible for a design to scale from smartphones to large desktops.

The Bootstrap grid splits the page into 12 equally sized columns. Depending on the viewport width, four different size classes are applied – extra small (from 0 to 768px wide), small (768px to 992px), medium (992px to 1200px), and large (1200px+).

MDL has a similar grid system, but it only has three sizes – phone (0 to 480px), tablet (480px to 840px) and desktop (840px+). MDL desktop has 12 columns, tablet has 8 columns and phone has only 4 columns.

Grid Example (Click To View)

The Boostrap grid offers a lot more control. You can offset, hide and reorder columns, which helps with responsive design. In MDL we have to resort to empty columns to achieve offsets, but hopefully this will be fixed in the next versions.

Docs: Bootstrap Grid | MDL Grid

2. Header Navigation

Headers in Bootstrap are called Navbars. They begin collapsed in mobile views and become horizontal when there is enough space for them. Inside, you can nest an array of different elements that can be positioned with the help of classes.

Similarly, MDL header navigations start off collapsed behind a hamburger menu and expand with the growth of the viewport. They too have different stylings and possible positions.

Header Example

Headers (Click To View)

Docs: Bootstrap Navbars | MDL Navigation

3. Footer

Bootstrap doesn’t actually have separate footer components, while Material Design Lite has two options, a mini and a mega footer. For this example, we’ve translated the default MDL design to Bootstrap, using the grid and a bit of extra CSS.

Footer Example

Footers (Click To View)

Notice that on small viewports, MDL’s columns collapse and can be toggled one by one. For this effect to work, they’ve used a CSS only checkbox hack, instead of going for a JavaScript solution.

Docs: MDL Footers

4. Tabs

Both frameworks use pretty simillar syntax to create selectable tabs with different content. A number of links for swapping between the tabs, and an array of divs, selectable by id, for storing the content. They also both require JavaScript to work (Bootstrap requires jQuery as well).

Tabs Example

Tabs (Click To View)

Docs: Bootstrap Tabs | MDL Tabs

5. Buttons

Bootstraps default buttons are rectangular and have a bunch of size options. They can have their color changed via CSS or with the modifier classes (Danger, Warning, Success,…). Another unique feature to Bootstrap is the split button which is half button, half dropdown.

MDL offers both rectangular and circular buttons. Google has a guide on how and in which situations to use the different types of buttons. All buttons in MDL support the ripple animation effect.

Buttons Example

Buttons (Click To View)

Docs: Bootstrap Buttons | MDL Buttons

6. Tables

Tables are generally hard to make responsive. Bootstrap has overcome this problem by making a scrollbar appear when the table doesn’t fit. MDL’s developers haven’t added responsiveness to tables yet, but what they’ve done is add amazing styles making tables look super cool.

In bootstrap you can also make tables striped, bordered and condensed. MDL offers a default style (which again, looks very neat) and a design with selectable rows.

Table Example

Tables (Click To View)

Another cool feature that MDL brings to table is the option to align content according to it’s type by using classes. This works similar to Excel sheets, text in the middle, numbers to the right.

Docs: Bootstrap Tables | MDL Tables

7. Forms

Bootstrap’s forms support more types of input elements and have classes for making different alignments to the labels and inputs. It doesn’t come with validation out of the box, you will need to use a library like Parsley for that.

MDL has few supported input elements, but the ones that are supported have the material animations added to them making them pleasing to interact with. They also have integrated verification and pattern matching. This allows them to show an error message and turn red when the data isn’t valid.

Form Example

Forms (Click To View)

Docs: Bootstrap Forms | MDL Text Fields

8. Dropdown Menu

Here the approach of the two frameworks is the same. A button or anchor element to toggle the content, and an unordered list of items for the drawer.

The bonus of Bootstrap is you can add a separator line or a heading and do split buttons.

The plus of MDL is again a smooth animation compared to Bootstrap’s “display: none/block” technique.

Dropdown Example

Dropdowns (Click To View)

JavaScript required in both cases.

Docs: Bootstrap Dropdowns | MDL Menus

9. Tooltips

Bootstrap’s approach to tooltips is to add data-attributes to a button element, which then shows the tooltip on hover and click. The framework also presents two separate components: a simplified tooltip and a more advanced popover with a title.

MDL have achieved this with a different model. A button for toggling and a span element for the tooltip’s content. Two alternatives are given, a small and a large design. A negative here is that these only go downwards.

Popover

Tooltips (Click To View)

JavaScript is required in both frameworks.

Docs: Bootstrap Tooltips | Bootstrap Popovers | MDL Tooltips

10. Icons

Bootstrap comes with the Glyphicons icon font, which gives you over 250 pretty icons to choose from. They come bundled with the bootstrap CSS file and no special setup is needed.

MDL uses a set of icons that Google released some time ago called Material Icons. This is a huge set of nearly 800 icons. They are not bundled with MDL so you need to link it in the HEAD section of your page:

<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
Material Icons

Icons (Click To View)

Conclusion

Overall Material Design Lite is shaping up as a good frontend framework. Go with it if you want your web application to follow the Material Design guidelines, but you find Google’s other framework, Polymer, too complex. It is still the early days, but the fact that it is made by Google gives you confidence that it will always conform to the latest material design spec.

And if you don’t find Material Design appealing, there is Bootstrap with its large community. You can even get the best of both worlds by using one of the material themes that are available for it.

Source:: Tutorialzine.com

Freebie: 7 Clean and Responsive Form Templates

By Danny Markov

7-clean-responsive-forms

More freebies! This week, we have 7 form layouts for you that you can use in your projects for free. They don’t require any frameworks as they’re made with plain HTML 5 and CSS 3.

The Forms

To integrate any of these forms in your pages simply copy the HTML of the form and paste it in your project. You can get the CSS from the corresponding stylesheet in the assets folder. The CSS is self contained and won’t break the styling of the rest of your page.

You get forms for registration and sign up, search, data entry and a form with built-in validation. They are optimized, responsive and ready to go!

Registration Form

Free for Commercial Use

You can download these templates from the button above. Everything is free to use in both your personal and commercial projects. You can check our license page for more info. We hope that you like them!

Source:: Tutorialzine.com

Quick Tip: Style Form Elements With Pseudo Selectors

By Danny Markov

quick-tip-style-form-elements

Ever since CSS was invented, web developers everywhere have wished for a way to style the built-in browser controls. This is straightforward for simple elements like buttons and text inputs, but difficult for some of the more complex elements like select and range. In this quick tip, we will show you how to do it.

Why pseudo selectors?

There is no standard way for customizing the appearance of the built-in browser elements yet. For example, the search input shows a small “x” with you can press to cancel your search. This is implemented as a separate element internally, but you can’t reach it with regular CSS. Browser makers have taken notice, and they’ve added vendor specific selectors that you can use. For that “x”, the selector to use is input[type=search]::-webkit-search-cancel-button.

There is a huge list of the known selectors here. All browsers provide some selectors for customizing built in elements, but the bad news is that support is all over the place. Hopefully in the future there will be a standard that brings consistency to this mess. For now though, we have to target each browser individually.

If you use Google Chrome, there is an easy way to find out which selector you’re supposed to be using. After you enable Shadow DOM support, you can see the internal structure of the built in browser elements. Here is how to do it, as taken from our Chrome DevTools Tips and Tricks article:

Shadow DOM

Open up the developer tools and go to Settings. There, in General, under Elements check Show user agent shadow DOM. Now when you inspect elements you will see their #shadow-root. When you select an element in the #shadow-root, in the Styles tab you will see which selectors are used by the user agent stylesheet to style them. Most of the time this is the selector you are looking for.

Keep in mind that most of the following experiments only work in Chrome and Safari. Firefox and IE don’t support many of the pseudo selectors that are necessary to customize built-in elements, so they show the regular versions. Someday when we have standards in place, customizations like these will work everywhere.

1. Checkboxes

There is not a lot you can do with checkboxes in CSS, apart from giving them a width and height. But Chrome and Safari support :before and :after pseudo elements on inputs, so you can have some fun. Notice that the check mark is made entirely with CSS and is even animated with a fade in transition.

By setting -webkit-appearance to none, we prevent the default browser style from being applied, which leaves the doors open to our custom CSS. Also thanks to the em units, we made the checkbox scale with the font size of its parent. Try increasing it.

(Play with our code editor on Tutorialzine.com)

2. Radio Buttons

We can use the same technique on radio buttons. Here it is simpler, as we don’t need to make a check mark out of CSS. This still only works in Chrome and Safari. Other browsers display the regular radio button.

(Play with our code editor on Tutorialzine.com)

3. Select Elements

The select element is notoriously difficult to style with CSS. Even today we are limited to what we can change. To customize the downward arrow, we can use a background image and a bit of padding. For the dropdown list you can specify a font size and a background on the option elements, but not much more.

(Play with our code editor on Tutorialzine.com)

4. Range elements

Range is one of the newer form elements supported by browsers. It also is one of the most customizable. Chrome, Safari and Firefox all give us a large number of CSS pseudo selectors that we can use to style specific parts of the element. Even IE has support for some, although we haven’t implemented them in our example. See this list to learn what is available.

(Play with our code editor on Tutorialzine.com)

5. Progress Bars

The progress element also gives us a good deal of customizability. Although for a simple element like this, you could just as easily nest two divs and make your own version.

(Play with our code editor on Tutorialzine.com)

Conclusion

It is great that we can finally modify the built-in browser controls, but there is still a long way to go in terms of standardization. Google Chrome is a clear leader here, and if you write Chrome apps or extensions you can go ahead and use everything that we showed here. But if you want consistent cross-browser support, the best solution is still relying on JavaScript libraries and jQuery plugins like Chosen.

Source:: Tutorialzine.com