Monthly Archives: October 2015

Learn the Bootstrap Grid in 15 Minutes

By Danny Markov

learn-bootstrap-grid

Bootstrap is the most widely used frontend framework right now. When it comes to building responsive websites and apps, it’s the first choice of both professionals and hobbyists because of how simple it is to work with. Anybody who knows HTML, CSS and a bit of JavaScript can learn Bootstrap in no time.

In this quick lesson we’re going to cover the grid system, one of the fundamental concepts every Bootstrap developer needs to master. It allows us to create responsive page layouts which can change and adapt depending on the screen size of the device the user is on.

1. Rows and Columns

The grid consists of rows and columns. This allows us to freely position elements vertically and horizontally.

Rows are block level. This means, that when we create a row, it takes up the entire width of the element it is in. You can think of rows as new lines in your layout.

The horizontal alignment in the grid is done via columns. Only columns can be the direct children of a row and all content should go inside them. Placing content directly within a row will break the layout.

<!-- Wrong -->
<div class="row">
    Some content
</div>

<!-- Correct -->
<div class="row">
    <div class="col-md-12">Content Goes Here</div>
</div>
<!DOCTYPE html>
<html>

<head>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Learn the bootstrap grid in 15 minutes</title>

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
    <style>

        body{ padding-top:50px;}

        .row div{
            background-color: #2196F3;
            border: 1px solid #fff;
            height: 125px;
            padding: 15px;
            color: #fff;
        }

    </style>

</head>

<body>

    <div class="container">
        <div class="row">
            <div class="col-md-6">First row, first column</div>
            <div class="col-md-6">First row, second column</div>
        </div>

        <div class="row">
            <div class="col-md-4">Second row, first column</div>
            <div class="col-md-4">Second row, second column</div>
            <div class="col-md-4">Second row, third column</div>
        </div>
    </div>

</body>
</html>

Note: Rows and columns have a special relationship. Columns have 15px left and right padding so that their content is properly spaced out. However, this pushes the first and last column’s content 15px away from the parent. To compensate, the row has negative left and right 15px margins. This is why you should always place columns within rows.

2. Rows are Divided in 12

Rows are divided horizontally into 12 equal parts. When we place a column inside a row, we have to specify the number of parts it is going to take up.

This is done by applying a specific class .col-md-NUMBER, where NUMBER can be an integer from 1 to 12. Depending on the number, a column will occupy a percentage of the full row width: 6 will be 50% (12/6), 3 will be 25% (12/3) and so on. The following example should make things clearer:

<div class="row">
    <div class="col-md-12">Full width</div>
</div>
<div class="row">
    <div class="col-md-3">25%</div>
    <div class="col-md-3">25%</div>
    <div class="col-md-6">50%</div>
</div>
<!DOCTYPE html>
<html>

<head>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Learn the bootstrap grid in 15 minutes</title>

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
    <style>

        body{ padding-top:50px;}

        .row div{
            background-color: #2196F3;
            border: 1px solid #fff;
            height: 125px;
            padding: 15px;
            color: #fff;
        }

    </style>

</head>

<body>

        <div class="container">
	    <div class="row">
	        <div class="col-md-12">Full width</div>
	    </div>
	    <div class="row">
	        <div class="col-md-3">25%</div>
	        <div class="col-md-3">25%</div>
	        <div class="col-md-6">50%</div>
	    </div>
	</div>

</body>
</html>

3. Column Wrapping

We always have to take into consideration, that there are only 12 available spaces in a line. If we sum up the space required by a couple of adjacent columns, and the result exceeds 12, the last columns in that group will have to move to the next line. Let’s take a look at a practical example:

The first two columns have sizes of respectively 8 and 4 (8+4=12), which makes the first line full. There isn’t enough space for the third cell there, so it will have to wrap to the next line.

<div class="row">
    <div class="col-xs-8"></div>
    <div class="col-xs-4"></div>
    <div class="col-xs-9">This column will move to the next line.</div>
</div>
<!DOCTYPE html>
<html>

<head>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Learn the bootstrap grid in 15 minutes</title>

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
    <style>

        body{ padding-top:50px;}


        .row div{
            background-color: #2196F3;
            border: 1px solid #fff;
            height: 125px;
            padding: 15px;
            color: #fff;
        }

    </style>

</head>

<body>

        <div class="container">
	    <div class="row">
	        <div class="col-xs-8"> 8 </div>
	        <div class="col-xs-4"> 4 </div>
	        <div class="col-xs-9"> 9 </div>
	    </div>
	</div>

</body>
</html>

4. Screen Size Classes

Remember when we wrote .col-md-NUMBER in step 2? That -md- stands for medium. Bootstrap has a number of these classes for different screen sizes:

  • xs – Extra small screens like smartphones. Use it as .col-xs-NUMBER
  • sm – Small screen devices like tablets. .col-sm-NUMBER
  • md – Medium sized screens such as low dpi desktops and laptops. .col-md-NUMBER
  • lg – Large, high resolution screens. .col-lg-NUMBER

Bootstrap takes the screen resolution and dpi into account when deciding which classes are active (learn more here). This is a powerful way how to control how layouts render on different devices.

When we define a rule for any device size, this rule will be inherited and applied to all bigger sizes, unless we overwrite it by supplying a new one. Hit the Run button on the following example and try resizing your browser to see the layout adapt.

<div class="row">
    <div class="col-xs-12 col-md-6"><p>Try resizing the browser to see this text and the image rearrange for optimal viewing. </p></div>
    <div class="col-xs-12 col-md-6"><img src="city.jpg" class="img-responsive"></div>
</div>
<!DOCTYPE html>
<html>

<head>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Learn the bootstrap grid in 15 minutes</title>

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
    <style>

        body{ padding-top:50px;}

    </style>

</head>

<body>

        <div class="container">
	    <div class="row">
	        <div class="col-xs-12 col-md-6">
	            <p>Try resizing the browser to see this text and the image rearrange for optimal viewing.</p>
	            <p> On extra small screens both the text and the image take up the whole width of the row. </p>
	            <p> When the browser size gets into the medium category, they can move in together and share a single row. They only need half of the row, since there is more space horizontally on the screen.</p>
	        </div>
	        <div class="col-xs-12 col-md-6"><img src="http://cdn.tutorialzine.com/wp-content/uploads/2015/10/city.jpg" class="img-responsive"></div>
	    </div>
	</div>

</body>
</html>

5. Clearfix

In some scenarios, when a column has much more content and a bigger height then the ones after it, the layout will break. The columns will all pile up under each other, instead of moving to the next line as they should.

To prevent this, we add a helper div with the clearfix class. It will force all columns after it move to a new line, solving the issue.

<div class="row">
    <div class="col-xs-6 tall-column">A column much taller than the rest.</div>
    <div class="col-xs-6"></div>
    <div class="clearfix"></div>
    <div class="col-xs-6"></div>
</div>
<!DOCTYPE html>
<html>

<head>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Learn the bootstrap grid in 15 minutes</title>

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
    <style>

        body{ padding-top:50px;}

        .row{
            margin-bottom: 50px;
        }

        .row .col-xs-6{
            background-color: #2196F3;
            border: 1px solid #fff;
            height: 125px;
            padding: 15px;
            color: #fff;
        }

        .row .tall-column{
            height: 300px;
        }

    </style>

</head>

<body>

         <div class="container">

	    <div class="row">
	        <div class="col-xs-6 tall-column">All columns are 6 units wide, but this one is too tall!</div>
	        <div class="col-xs-6"></div>
	        <div class="col-xs-6">This column shoudln't be here.</div>
	        <div class="col-xs-6">This column shoudln't be here.</div>
	    </div>

	    <div class="row">
	        <div class="col-xs-6 tall-column">By adding a clearfix between the second and third columns, everything will go where it should.</div>
	        <div class="col-xs-6"></div>
	        <div class="clearfix"></div>
	        <div class="col-xs-6">All better now.</div>
	        <div class="col-xs-6"></div>
	    </div>

	</div>

</body>
</html>

You can use Bootstrap’s responsive utility classes to control when clearfix is active.

6. Offsets Are Your Friend

By default, columns stick to each other without leaving any space, floating to the left. Any excess space remaining in that row stays empty on the right.

To create margins on the left of columns we can use the offset classes. Applying a .col-md-offset-2 class to any column will move it to the right, as if there is an invisible .col-md-2 cell there. You can have different offsets for the different screen sizes thanks to the xs, sm, md and lg prefixes.

You can use offsets to easily center columns:

<div class="row">
    <div class="col-md-6 col-md-offset-3"></div>
    <div class="col-md-10 col-md-offset-1"></div>
</div>
<div class="container">

    <div class="row">
        <div class="col-xs-5 col-xs-offset-4">col-xs-5 col-xs-offset-4</div>
        <div class="col-xs-9 col-xs-offset-2">col-xs-9 col-xs-offset-2</div>
        <div class="col-xs-6 col-xs-offset-1">col-xs-6 col-xs-offset-1</div>
        <div class="col-xs-4 col-xs-offset-1">col-xs-4 col-xs-offset-1</div>
        <div class="col-xs-11 col-xs-offset-1">col-xs-11 col-xs-offset-1</div>
        <div class="col-xs-10">col-xs-10</div>
        <div class="col-xs-7">col-xs-7</div>
    </div>
    <div class="row">
        <div class="col-xs-5">col-xs-5</div>
    </div>
    <div class="row">
        <div class="col-xs-7">col-xs-7</div>
        <div class="col-xs-10">col-xs-10</div>
        <div class="col-xs-11 col-xs-offset-1">col-xs-11 col-xs-offset-1</div>
        <div class="col-xs-11 col-xs-offset-1">col-xs-11 col-xs-offset-1</div>
        <div class="col-xs-9 col-xs-offset-2">col-xs-9 col-xs-offset-2</div>
        <div class="col-xs-5 col-xs-offset-4">col-xs-5 col-xs-offset-4</div>
    </div>

</div>
<!DOCTYPE html>
<html>

<head>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Learn the bootstrap grid in 15 minutes</title>

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
    <style>

        body{ padding-top:50px;}

        .row{
            padding: 0 250px;
        }

        .row div{
            background-color: #2196F3;
            height: 50px;
            padding: 15px;
            color: #fff;
        }

        @media(max-width: 992px){

            .row{
                padding: 0 100px;
            }

            .row div{
                height: 25px;
            }
        }

    </style>

</head>

<body>

        <div class="container">

	    <div class="row">
	        <div class="col-xs-5 col-xs-offset-4">col-xs-5 col-xs-offset-4</div>
	        <div class="col-xs-9 col-xs-offset-2">col-xs-9 col-xs-offset-2</div>
	        <div class="col-xs-6 col-xs-offset-1">col-xs-6 col-xs-offset-1</div>
	        <div class="col-xs-4 col-xs-offset-1">col-xs-4 col-xs-offset-1</div>
	        <div class="col-xs-11 col-xs-offset-1">col-xs-11 col-xs-offset-1</div>
	        <div class="col-xs-10">col-xs-10</div>
	        <div class="col-xs-7">col-xs-7</div>
	    </div>
	    <div class="row">
	        <div class="col-xs-5">col-xs-5</div>
	    </div>
	    <div class="row">
	        <div class="col-xs-7">col-xs-7</div>
	        <div class="col-xs-10">col-xs-10</div>
	        <div class="col-xs-11 col-xs-offset-1">col-xs-11 col-xs-offset-1</div>
	        <div class="col-xs-11 col-xs-offset-1">col-xs-11 col-xs-offset-1</div>
	        <div class="col-xs-9 col-xs-offset-2">col-xs-9 col-xs-offset-2</div>
	        <div class="col-xs-5 col-xs-offset-4">col-xs-5 col-xs-offset-4</div>
	    </div>

	</div>

</body>
</html>

7. Push and Pull

The push and pull classes allow us to reorder columns depending on screen size. Push moves a column to the right, and pull to the left. This is different from offset as push and pull use position: relative and don’t shift other columns.

Push and pull classes have the following format: .col-SIZE-push-NUMBER, and .col-SIZE-pull-NUMBER. Possible SIZE values are sm, xs, md and lg. This represents in which of the 4 screen size scenarios we want the swap to occur. NUMBER tells Bootstrap how many positions we want to move.

Hit Run on the code below and resize the pop-out to see how the two cells change places when the window becomes small.

<div class="row">
    <div class="col-xs-4 col-md-push-8">On laptop and desktop screens this text will go to the right and the image will go to the left, changing places.</div>
    <div class="col-xs-8 col-md-pull-4"><img src="city.jpg" class="img-responsive"></div>
</div>
<!DOCTYPE html>
<html>

<head>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Learn the bootstrap grid in 15 minutes</title>

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
    <style>

        body{ padding-top:50px;}

    </style>

</head>

<body>

       <div class="container">
	    <div class="row">
	        <div class="col-xs-4 col-md-push-8">On laptop and desktop screens this text will go to the right and the image will go to the left, changing places.</div>
	        <div class="col-xs-8 col-md-pull-4"><img src="http://cdn.tutorialzine.com/wp-content/uploads/2015/10/city.jpg" class="img-responsive"></div>
	    </div>
	</div>

</body>
</html>

Conclusion

Great job! You now know the most important part of the Bootstrap framework, and you’re ready to build your next stellar responsive design. But there is a bit more left to learn to achieve true mastery. Check out Bootstrap’s extensive documentation for more.

Source:: Tutorialzine.com

The traversal order of object properties in ES6

By Axel Rauschmayer

The ECMAScript 6 specification defines in which order the properties of an object should be traversed. This blog post explains the details.

Why specify the traversal order?

Traditionally, a JavaScript object is basically a map from strings to arbitrary values. The inherent nature of such a data structure is for entries to be unordered, which explains why, for a long time, the order in which properties are traversed was left unspecified in JavaScript (to be handled by engines as they saw fit).

However, most engines ended up having the same order and now code depends on it. Therefore, using a different order breaks web apps, which is why requiring an order makes sense.

In general, there are two possible approaches for preventing code from breaking in the manner that I’ve just described:

  1. Specify an order that code can depend on.
  2. Specify that engines must make it impossible for code to rely on an order, by choosing a different order each time.

The latter is hard, which is why the former approach was taken. An additional benefit is that it helps with programming tasks such as debugging and testing output, where a fixed order makes it easier to compare expected with actual results. For example, JSON.stringify(obj) will always produce the same result, as long as obj is created in the same manner.

Operations that traverse properties

The following operations in ECMAScript 6 traverse the keys of properties (the only way in which you can currently iterate over properties):

  • Own property keys:
    • Object.keys()
    • Object.getOwnPropertyNames()
    • Reflect.ownKeys()
  • All (own and inherited) keys:
    • Reflect.enumerate()
    • for-in loop

Traversing the own keys of an object

Property keys are traversed in the following order:

  • First, the keys that are integer indices (what these are is explained later), in ascending numeric order.
  • Then, all other string keys, in the order in which they were added to the object.
  • Lastly, all symbol keys, in the order in which they were added to the object.

Many engines treat integer indices specially (even though they are still strings, at least as far as the ES6 spec is concerned). Therefore, it makes sense to treat them as a separate category of keys.

Integer indices

Roughly, an integer index is a string that, if converted to a 53-bit non-negative integer and back is the same value. Therefore:

  • '10' and '2' are integer indices.
  • '02' is not an integer index. Coverting it to an integer and back results in the different string '2'.
  • '3.141' is not an integer index, because 3.141 is not an integer.

In ES6, instances of String and Typed Arrays have integer indices. The indices of normal Arrays are a subset of integer indices: they have a smaller range of 32 bits. For more information on Array indices, consult “Array Indices in Detail” in “Speaking JavaScript”.

Example

The following code demonstrates the order in which the own keys of an object are iterated over:

    let obj = {
        [Symbol('first')]: true,
        '02': true,
        '10': true,
        '01': true,
        '2': true,
        [Symbol('second')]: true,
    }
    Reflect.ownKeys(obj);
    [ '2', '10', '02', '01', Symbol('first'), Symbol('second') ]

Explanation:

  • '2' and '10' are integer indices, come first and are sorted numerically.
  • '02' and '01' are normal string keys, come next and appear in the order in which they were added to obj.
  • Symbol('first') and Symbol('second') are symbols and come last, in the order in which they were added to obj.

Enumerating the string keys of all enumerable properties

The for-in loop and its iterator-returning analog, Reflect.enumerate() traverse the keys of all properties, not just the own ones. But they only consider enumerable string keys.

Algorithm: In order to enumerate the property keys of an object obj, …

  • Visit the keys of all own enumerable string keys of obj, in the order described in the previous section. Ignore any keys that existed in previously processed objects (independently of whether those were keys of enumerable properties or not).

  • Perform the previous step for the prototype of obj, the prototype’s prototype, etc., until the end of the chain is reached.

The ES6 spec contains a recursive implementation that stays close to the ES6 meta object protocol. This is an iterative version of that implementation that is slightly easier to understand:

    function* enumerate(obj) {
        let visited = new Set();
        while (obj) {
            for (let key of Reflect.ownKeys(obj)) {
                if (typeof key === 'string') {
                    let desc = Reflect.getOwnPropertyDescriptor(obj, key);
                    if (desc && !visited.has(key)) {
                        visited.add(key);
                        if (desc.enumerable) {
                            yield key;
                        }
                    }
                }
            }
            obj = Reflect.getPrototypeOf(obj);
        }
    }

The following code demonstrates that for-in and Reflect.enumerate() ignore properties they encountered before, even if they weren’t enumerated.

    let proto = Object.defineProperty({},
        'foo', {
            // Ignored, because key was already encountered
            enumerable: true,
        });
    let object = Object.create(proto, {
        foo: {
            // Not enumerated
            enumerable: false,
        },
    });
    console.log([...Reflect.enumerate(object)]); // []

Conclusion

Being able to rely on the order in which properties are traversed in ES6 will help with several tasks (such as testing).

However, I expect that with ES6 Maps, one will traverse properties of objects less often. As an aside, the entries of Maps are ordered, too, by when they were added. The rationale for doing so is they same as the one for objects (as described earlier).

Sources

Two threads on es-discuss are instructive w.r.t. the traversal order of properties:

Source:: 2ality

Influences on ECMAScript 6

By Axel Rauschmayer

This is a list of a few ECMAScript 6 features and what their influences were:

Source:: 2ality

call-constructor-esprop

By Axel Rauschmayer

This blog post describes the proposed ECMAScript feature “call constructor” (stage 1).

Classes can’t be function-called in ES6

In ECMAScript 6, classes can’t be function-called:

    class Point {
        constructor(x, y) {
            this.x = x;
            this.y = y;
        }
    }
    let p1 = new Point(1, 2); // OK
    let p2 = Point(3, 4); // TypeError

For ES6, there was no categorical objection to classes being function-called. The error was only thrown so that handling function calls via classes could be added later.

Function-callable constructors in ES6

If you want to implement a constructor Point that can be both function-called and constructor-called, you have no choice but to use a constructor function in ES6:

    function Point(x, y) {
        if (!new.target) {
            // Point was function-called
            return new Point(x, y);
        }
        this.x = x;
        this.y = y;
    }
    let p1 = new Point(1, 2); // OK
    let p2 = Point(3, 4); // OK

Function-callable classes via the proposed call constructor

The proposal is about allowing classes to handle function calls via the pseudo-method call constructor():

    class Point {
        constructor(x, y) {
            this.x = x;
            this.y = y;
        }
        call constructor(x, y) {
            return new Point(x, y);
        }
    }
    let p1 = new Point(1, 2); // OK
    let p2 = Point(3, 4); // OK

Things of note:

  • A call constructor is not inherited by subclasses, you have to put it into each class you want to function-call.
  • A super() call is a compile-time error inside a call constructor (just like it is in normal methods). That is done to keep options open w.r.t. enabling super() in call constructors in the future.

Possible future additions to the proposal

New meta-properties

In a future version of the proposal, two meta-properties will probably be added:

  • class.current refers to the current class (a function).
  • class.extends refers to the super-class of the current class.

class.current will help with forwarding from the call constructor to the constructor:

    class Foo {
        constructor(···) {
            ···
        }
        call constructor(...args) {
            return new class.current(...args);
        }
    }

A decorator for making classes function-callable

Another possibility is a class decorator that enables function-calling by forwarding from the call constructor to the constructor. For example:

    @callConstructor
    class Foo {
        constructor(···) {
            ···
        }
    }

Internally, this class looks like the previous example.

Further reading

Source:: 2ality

Why is there a “temporal dead zone” in ES6?

By Axel Rauschmayer

In ECMAScript 6, accessing a let or const variable before its declaration (within its scope) causes a ReferenceError. The time span when that happens, between the creation of a variable’s binding and its declaration is called the temporal dead zone.

For more information, consult Sect. “The temporal dead zone” in “Exploring ES6”. Here, I’d like to answer two questions:

  • Why is there a temporal dead zone?
  • Why does typeof cause a ReferenceError for variables in the TDZ?

Why is there a temporal dead zone?

  • To catch programming errors: Being able to access a variable before its declaration is strange. If you do so, it is normally by accident and you should be warned about it.
  • For const: Making const work properly is difficult. Quoting Allen Wirfs-Brock: “TDZs … provide a rational semantics for const. There was significant technical discussion of that topic and TDZs emerged as the best solution.” let also has a temporal dead zone so that switching between let and const doesn’t change behavior in unexpected ways.
  • Future-proofing for guards: JavaScript may eventually have guards, a mechanism for enforcing at runtime that a variable has the correct value (think runtime type check). If the value of a variable is undefined before its declaration then that value may be in conflict with the guarantee given by its guard.

Why does typeof cause a ReferenceError for variables in the TDZ?

If you access a variable in the temporal dead zone via typeof, you get an error, too:

    {
        console.log(typeof foo); // ReferenceError
        console.log(typeof someVariableThatDoesntExist); // 'undefined'
        let foo;
    }

The rationale here is as follows: foo is not undeclared, it is uninitialized. You should be aware of its existencee, but aren’t. Therefore, being warned seems desirable.

Furthermore, this kind of check is only useful for conditionally creating global variables. That can only be done via var (not by let or const) and there are different ways of performing the check:

    // With `typeof`
    if (typeof someGlobal === 'undefined') {
        var someGlobal = { ··· };
    }
    
    // Without `typeof`
    if (!('someGlobal' in window)) {
        window.someGlobal = { ··· };
    }

The former way of creating a global variable only works in global scope (and therefore not inside an ES6 module).

Futher reading

Sources of this blog post:

Source:: 2ality

Running a simple web server from a shell

By Axel Rauschmayer

The classic command for running a simple web server from a shell is:

    python -m SimpleHTTPServer

This command has the advantage that it is built into Python and that Python is built into Mac OS X. However, this command always serves the current working directory (the directory that you are currently in), there is no way to provide a directory as an argument. That’s a problem if the directory you want to serve is constantly being deleted and recreated. You can’t specify the port where the files are served, either, it is always 8000.

Node.js doesn’t have a similar built-in mechanism, but there is an npm package that you can install: http-server.

    npm install -g http-server

A basic way of using the shell command that this package comes with is:

    http-server ["path»] [-p "port»]

Afterwards, files are served at http://localhost:"port».

  • If you omit the path, ./public is used, if it exists, and ./ otherwise.
  • If you omit the port, 8080 is used.

Why would you want to do this? Many styles of sites and web apps don’t run properly “over” the file: protocol (accessed directly via the local file system). Therefore, you often need to serve them from localhost during development.

Source:: 2ality

Modular HTML pages

By Axel Rauschmayer

Static generation: minimizing how much is re-generated

When statically generating HTML content, you face an interesting challenge: If the page frame (the “chrome” of a page) contains information that changes frequently, you need to re-generate all pages every time it does. One example of such information is a top 10 list of the pages that were most popular during the last 30 days.

A work-around is to save the information in a separate file and to load that information dynamically via JavaScript. You then have a choice: You can save a JSON file and transform that into HTML or you can save an HTML file and insert it without processing it. Apart from having to re-generate fewer files, you also save traffic, because the shared information only needs to be downloaded once and will be cached, afterwards.

Similar: HTTP/2 and JavaScript modules

This situation is similar to JavaScript modules. Currently, many modules are bundled (combined) into a single file, to avoid the cost of one connection per file, imposed by HTTP/1. That means you have to re-generate all of the code, even if only a small module changes. However, things change with HTTP/2: You don’t need a new connection for each module, you can send multiple files over the same connection (if the server is aware of what needs to be done). Therefore, having many small modules doesn’t cost you, connection-wise, anymore. This enables small incremental updates for web apps.

Modular HTML pages?

Coming back to HTML pages: What if there was a way to declaratively compose HTML pages? You’d get both small incremental updates and traffic savings, but without having to use JavaScript.

As far as I can tell, HTML Imports do not help with this use case.

Source:: 2ality

Comparing The Top Frameworks For Building Hybrid Mobile Apps

By Danny Markov

comparing-the-top-frameworks

Only a few years ago, developing mobile apps via JavaScript was nothing more then a quirky experiment. The idea that you could build iOS and Android apps, without having to operate with Java and Objective C, seemed appealing to many web devs. Now we have a plethora of frameworks bringing us closer than ever to creating a native mobile experience using only web technologies.

What are Hybrid Mobile Apps?

A hybrid app is just a regular mobile optimized website, written in CSS, HTML and JavaScript, that is displayed in a webview (this is a basically a stripped down web browser). The advantage is that you only need to write a single application, which in most cases runs unmodified on Android, iOS and Windows Phone. Most of the frameworks listed in this article do this using Cordova or PhoneGap, which give you a bridge to the device APIs in JavaScript.

In this article we’re going to compare the most popular JavaScript frameworks for building hybrid and native mobile apps. Scroll to the bottom of the article to see the scores.

1. Ionic

Ionic

Ionic is the most popular framework on our list and probably the first choice of many developers. You can use the CSS portion of the framework to create native looking designs, but to harness the full potential of Ionic, it’s best to pair it with AngularJS. A big bonus you get with Ionic is the command-line interface which is full of awesome features including integrated emulators and a Cordova based app packager.

Pros:

  • Works with predefined components
  • Great community
  • Command Line Interface with lots of useful features

Cons:

  • You need to know AngularJS to do anything complex

2. Onsen UI

Onsen UI

Onsen UI

This is an open source framework that allows developers to build apps by combining native-looking components. It’s fairly simple to use, can work with or without AngularJS, and has great documentation that includes lots of examples and layouts for the most common app structures. A disadvantage of Onsen UI is that it currently offers only an iOS theme, although the next version promises Material Design support.

Pros:

  • Works with predefined components
  • Excellent documentation with examples

Cons:

  • PhoneGap/Cordova builder not included, but supported
  • No support for Material Design (yet)

3. Framework 7

Framework 7

Framework 7

The cool thing about Framework 7 is that it is completely framework agnostic (doesn’t have external dependencies like Angular or React) and still manages to make apps look and feel native, with properly styled components and animations. Anyone who understands HTML, CSS and JavaScript can create an app without making the code convoluted. Framework 7 doesn’t include any tools for emulation or app packaging so you will need to combine it with Cordova or PhoneGap.

Pros:

  • Simple to use, relies only on HTML, CSS and JavaScript
  • Good performance
  • Can be combined with any JavaScript framework of choice

Cons:

  • PhoneGap/Cordova builder not included, but supported

4. React Native

React Native

React Native

As the name implies, React Native’s purpose is to build proper native apps, instead of creating hybrid ones that run in a Webview. Development, however, is still done completely via JavaScript and React. This frameworks isn’t tailored towards beginners in web development, but on the plus side, there is a huge community behind it that will help you in every part of the way. Recently the framework rolled support for Android, so you can have real cross-platform apps.

Pros:

  • Native-like performance
  • Huge community

Cons:

  • Steep learning curve
  • The development tools only work on OS X at the moment

5. jQuery Mobile

jQuery Mobile

jQuery Mobile

The grandpa of all mobile frameworks, jQuery Mobile doesn’t try to make apps that look like Android or iOS. Instead, it’s purpose is to help develop web apps that will work equally well on all mobile browsers (including oldies such as Windows Phone, Blackberry, and Symbian). As such, it is very lightweight, depends only on jQuery and is quite easy to learn, while still offering good touch recognition and PhoneGap/Cordova support.

Pros:

  • Support for wide range of mobile browsers
  • Simple to use

Cons:

  • Dated styles that don’t resemble either iOS or Android
  • PhoneGap/Cordova builder not included, but supported

6. Native Script

NativeScript

NativeScript

Native script’s biggest feature is that it allows you to write the functionality of your app in TypeScript once, which then will be transformed accordingly to Android, iOS and Windows Phone. Packaged, the compiled applications start in a native fashion, without opening and running in a browser. This frameworks does require some coding skills, but compensates for it with an extensive, in-depth documentation.

Pros:

  • Write once, use everywhere approach.
  • Great documentation

Cons:

  • Steep learning curve
  • Small community

7. Famous

Famous

Famous

Famous has a unique approach to web and mobile development. It combines the DOM tree (your HTML) with WebGL, displaying everything in a canvas, similar to what HTML game engines do. This novel technique allows the framework to run your apps in 60 fps, which is as smooth as most native apps. Sadly, this project is no longer being actively developed and doesn’t have good docs for reference.

Pros:

  • Native-like performance

Cons:

  • No longer actively developed
  • Documentation not full
  • Small community

The Rundown

Conclusion

There is no best framework – all of them have their pros and cons and it’s up to you to decide depending on what you plan on using them for.

We hope this quick comparison has been of great use to you! If you have experience with any of the listed frameworks or similar ones, please leave a comment and share your opinion on hybrid app development!

Source:: Tutorialzine.com

Using the Google Analytics Core Reporting API from Node.js

By Axel Rauschmayer

This blog post explains how to use the Analytics Core Reporting API by Google from Node.js.

Let’s use that API to create a Node.js script analytics.js that downloads the top 10 most visited pages of your website.

Unlocking the Google Analytics API

Go to the Google Developers Console:

  • Create a new project (e.g. myproject).
  • In section “APIs & auth → Credentials”, execute “Add credentials → Service account”.
    • Download the resulting JSON file (e.g. “myproject-3126e4caac6a.json”).
    • Put that file into a directory node_modules that is inside one of the parent directories of the script that we’ll create later. That means that you can keep it out of the repository with analytics.js. For example, the following path is perfectly fine:
          $HOME/node_modules/myproject-3126e4caac6a.json
      
  • The credentials that you created have an email address (which is displayed in the user interface and stored inside the JSON file). Copy that email address.

Go to the Admin panel in Google Analytics:

  • Analytics has three scopes:
    • Account
    • Property
    • View
  • Create a new user in scope “Property”, via “User Management”.
    • That user has the email address that you copied previously.
    • Its permissions are “Read & Analyze”.
  • In scope “View”, go to “View Settings” and write down the “View ID” (e.g. 97675673) for later.

Installing the Google API client library

  • Google provides many public APIs. You need the “Analytics Core Reporting API”.
  • All APIs are accessed via the Google API client library. You want the one for Node.js, which can be installed via npm:
        npm install --save googleapis
    

Writing the script

The first line of the script enables us to execute the script directly on Unix systems (if it is executable):

    #!/usr/bin/env babel-node

The code shown in this section is ECMAScript 6, which is why we run the script via babel-node. You can also omit this first line and run the script like this:

    babel-node analytics.js

Next, we import the Google API client library and prepare a helper function.

    import google from 'googleapis';
    const raw = String.raw;

Next, we import the key and define the view ID (prefixed with 'ga:'):

    import key from 'myproject-3126e4caac6a.json';
    const VIEW_ID = 'ga:97675673';

Next, we authenticate (consult “Authorizing and Authenticating” for more information):

    let jwtClient = new google.auth.JWT(
      key.client_email, null, key.private_key,
      ['https://www.googleapis.com/auth/analytics.readonly'], null);
    jwtClient.authorize(function (err, tokens) {
      if (err) {
        console.log(err);
        return;
      }
      let analytics = google.analytics('v3');
      queryData(analytics);
    });

Finally, we make the query (for consistency’s sake, all keys are quoted):

    function queryData(analytics) {
      analytics.data.ga.get({
        'auth': jwtClient,
        'ids': VIEW_ID,
        'metrics': 'ga:uniquePageviews',
        'dimensions': 'ga:pagePath',
        'start-date': '30daysAgo',
        'end-date': 'yesterday',
        'sort': '-ga:uniquePageviews',
        'max-results': 10,
        'filters': raw`ga:pagePath=~/ch_[-a-z0-9]+.html$`,
      }, function (err, response) {
        if (err) {
          console.log(err);
        }
        console.log(JSON.stringify(response, null, 4));
      });  
    }

We retrieve the top 10 most visited pages within the last 30 days:

  • metrics: what was measured?
  • dimensions: what meta-data are we interested in?
  • Dates: we must provide both a start and an end date. If we want the earliest possible start date (minus infinity, if you will), we can use '2005-01-01'.
  • sort: comma-separated keys of either metrics or dimensions.
  • filter: we filter the ga:pagePath via a regular expression, so that only files with specific names are shown in the results. The property value is an ES6 tagged template, which is why we can use the backslash directly, without escaping it.

More information on the Analytics Core Reporting API:

Source:: 2ality