css

My first few hours with Visual Studio Code

Microsoft have released a new editor. This is Microsoft’s take on Sublime/Atom. It looks nice, it feels fast, and it can run on OSX or Linux (as well as Windows). I’ve been using it for work this morning - here are my impressions.

Visual Studio Code

You can download it here: Visual Studio Code Preview.

The big news is that Code is cross platform. It can run natively under OSX and Ubuntu, showing just how much Microsoft has changed direction. It will also excite my OSX-using co-worker - Jason - who constantly moans about having to start his Windows vm to run Visual Studio.

First Impressions

This is what you see when Code starts:

code main

My first thought is that it looks very much like Atom - which looks very much like Sublime.

When I jump in to update settings, Code takes me to a JSON file:

code settings

Settings are updated by overriding prperties in either user or workspace based settings files. Very sublime-like, and very nice.

To the left, we have a sidebar with our file explorer, search box, git integration, and debugger. Interestingly I didn’t see any options for TFS source control.

sidebar

The explorer is split into your working files and project view. Double clicking a file will open it and place it in your working files. Code has done away with tabs and is a much better editor because of it.

The Editor

The editor has syntax highlighting (as expected). It also has fantastic intellisense support. My last few projects have been javascript based, and I’ve found that in Sublime/Atom getitng intellisense style completion going is very hit and miss. When it does work, it has always felt like a hand-me-down half hearted effort compared to the joy of Visual Studio Intellisense.

Code’s intellisense is brilliant. It can negotiate require.js dependency trees. “Go to Definition” works. Peek works. “Go to symbol” works.

intellisense

I did find one annoyance. Code wasn’t quite sure about ES6, and gave some warnings about TypeScript (which I’m not using).

es6 intellisense

Given how fast the Javascript community moves, this should be fixed fairly quickly.

Looking to the top right of the editor, we see this row of buttons:

editor buttons

The buttons are:

  • split editor
  • Changes view
  • open preview

Splitting the editor gives you 2 panes (side by side). Change view displays differences compared to the checked in version in source control - a built in diff tool - awesome!

Preview is enabled if you are in a html or markdown file. It splits the view, and gives you a preview pane on the right which updates as you make code changes.

split view

What about column editing?

It’s in there! If you hold alt and click, you get a second cursor… and a third… and a forth… etc:

multi-cursor

This is the main feature that pulled me into Sublime editor. Code has a decent implementation (but I do miss being able to middle-click and drag - Sublime style).

Other nifty things

Here are a few other items I noticed:

  • there is a debugger, but only for node and mono. ASP5 support is coming soon. The debugger seemed to work ok when I gave it a test with a node.js app.
  • the search pane is great - better than any other editor I have tried. I can use regex, I can exclude and include files or folders and apply a filter - and I can do all of those things at the same time, easily.
  • it is built on Github Electron Shell, the same base Atom uses.
  • themes are supported

Overall

How is Code in general use? If you use Atom or Sublime, you’re going to be right at home. I haven’t found anything that has pissed me off. Code looks nice, and the defaults are sane.

The only thing I can really fault it for is the name. Try searching “Microsoft Code” in a search engine. Go on. Just try.

I like that I can take Code with me if I move to a different OS.

Code uses the same base as Atom (Electron), but unlike Atom - it doesn’t have issues of random lock ups or slow down. Code feels like a native editor. It feels fast.

In summary - I love Code! I wrote this blog post in Code, I previewed it in Code, and I checked it in in Code. If you’re a front-end developer, go get Code. Go!

/eof

Accidental NPM Packaging (and JSPM!)

Last week I created a package - an NPM. I didn’t intend to. I just wanted to use the Microsoft Signal-R javascript client, and I was surprised to see it wasn’t listed in the Node package repository.

How hard can it be to create a package anyway?

There are two great motivators for developers. Laziness and annoyance.

  • Laziness: “I bet I can automate this, so I can spend more time doing interesting things”.
  • Annoyance:“Why isn’t there an NPM package for this? what is this, the dark ages?!”.

I found myself annoyed when I decided to use Microsoft’s SignalR Javascript client. There was no JSPM or NPM package.

The package manager I was using is JSPM - a wonderful bundle of joy that can use either NPMs or git repos as a package source. Lets make packages!

Pre Conditions

You need:

  • npm (node package manager)
  • jspm (javascript package manager)
  • a git client
  • github & npm accounts

Make a JSPM github package


c:\\github> mkdir mypackage
c:\\github> cd mypackage
c:\\github\\mypackage> git init

Add a .gitignore file, and setup your github remote repo as your origin.

Now you need a package.json file. This file defines what your package is, what it depends on, who maintains it, and where it lives. It can define a lot of other things too, as defined by the package.json spec. We can create one with npm.


c:\\github\\mypackage> npm init

name: (mypackage)
version: (1.0.0)
description:
entry point: (index.js)
test command:
git repository:
keywords:
author:
license: (ISC)
About to write to C:\github\mypackage\package.json:

{
  "name": "mypackage",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}


Is this ok? (yes)

Edit your package.json to suit your project. Run it through a json validator. Once you’re happy with it, commit and push it to github:


c:\\github\\mypackage> git commit -a
c:\\github\\mypackage> git push origin master

Now you can test it. Add trying adding it to another project, directly from your github repo:


c:\\github\\mypackage> jspm install github:[youraccount]/[your repo]

Ok, hopefully that went well.

Create NPM package & add to NPM repo


c:\\github\\mypackage> npm publish

Update NPM package

/eof

Animating Aurelia

Have you heard of Aurelia? It’s Rob Eisenberg’s new framework. If you travelled forward in time two years and wrote a framework based on cutting edge tech, Aurelia would be the result. Aurelia is built on technology so new that the standards haven’t been ratified yet. I’m talking ES6, ES7, transpiling, a proper module loader, lambda expressions (arrow functions), computed properties, and more.

Aurelia

Now let’s use this massively powerful framework to animate a few boxes.

{% raw %}

2015-04-28 Article Updated

This article had some incorrect code listed, and was not making proper use of the Aurelia-Animator. I have corrected the text and updated the code samples. Thanks to commenter “firens” for giving me a heads up.

{% endraw %}

Applying CSS Animations in Aurelia

What we are going to do is this:

Have new databound elements fade in as they are added to the DOM, using CSS transitions. Then, we will update a counter and animate it.

To achieve our goal, we start by installing Aurelia’s animation library. Open a command prompt and add it to your project as follows:


$ jspm install aurelia-animator-css

If you haven’t seen jspm before, check it out. It isn’t limited to jspm packages. Jspm can also install and manage npm packages, as well as pulling modules down from github repositories.

CSS Animations

If you’re unfamiliar with CSS animations - don’t worry. They are straight forward. You define the key points in the animation - the starting state (0%) and the end state (100%). Apply CSS styles for those key points. The browser will extrapolate the rest. Here are the definitions for our “fade-in” and “flash” animations:


@keyframes fade-in {
  0%   { opacity: 0; }
  100% { opacity: 1; }
}
/* for compatibility with older browsers */
@-webkit-keyframes fade-in{
  0%   { opacity: 0; }
  100% { opacity: 1; }
}

@-webkit-keyframes flash {
  0%, 50%, 100% {
    opacity: 1;
  }

  25%, 75% {
    opacity: 0;
  }
}

/* Credit goes to http://daneden.github.io/animate.css/ */
@keyframes flash {
  0%, 50%, 100% {
    opacity: 1;
  }

  25%, 75% {
    opacity: 0;
  }
}

To use our new animations we need to create a CSS class to apply to our new DOM elements, and we need to define a class to animate our counter.


.fade-in-box {
  -webkit-animation: 0.5s fade-in;
  animation: 0.5s fade-in;

  border: 1px solid black;
  background: yellow;
}

.au-attention {
  -webkit-animation: 0.5s flash;
  animation:  0.5s flash;
}

Aurelia .js class

This is our view model.


import {inject} from 'aurelia-framework';
import {CssAnimator} from 'aurelia-animator-css';

// Use this decorator to inject the animator
@inject(CssAnimator)
export class ListExample{

  heading = 'List Example';

  listItems = [
    { listItem: 'pencils', qty: 2 },
    { listItem: 'glue', qty: 1 },
  ];

  // The inject decorator needs an appropriate constructor
  // to inject the animator.
  constructor(animator) {
    this.animator = animator;
  }

  addListItem() {
     this.listItems.push({listItem: 'packing tape',  qty: 1 });

     // then removeClass method returns a promise. We can use "then"
     // to chain it to addClass. This allows us to 'toggle' the class on the
     // element - and fire the animation
     this.animator.removeClass(this.elGridCount, 'au-attention')
        .then(this.animator.addClass(this.elGridCount, 'au-attention'));
  }

}

The code above creates a list of items and a button - which we bind our view to. Notice the nice ES6 syntax?

Aurelia .html view

This is our view.


<template>
  <section>
    <h2>${heading}</h2>

    <div><button click.trigger="addListItem()">Add List Item</button></div>

    <div role="grid">
      <div repeat.for="row of listItems" style="display: flex;">
        <div style="flex: 1 auto;" class="fade-in-box" >${row.listItem}</div>
        <div style="flex: 1 100px;" class="fade-in-box" >${row.qty}</div>
      </div>
    </div>

    Count: <div ref="elGridCount">${listItems.length}</div>

  </section>
</template>

In the view, we’ve defined a list, and used “repeat.for” to bind it to our view model list items. The button is bound to addListItem().

We’ve also added a count of our list items. Note the “ref” attribute on the counter. This attribute is used in the model to reference the element in the view.

Click!

When the user clicks the button, the following events occur:

Events related to new item addition

  1. The view model method addListItem() adds a new item to the list.
  2. Aurelia observes the new item being added, and triggers a DOM insert to add it to the grid.
  3. The browser begins the fade in animation for the new element

Events related to the counter

  1. The view model method addListItem() calls the aurelia animator with the removeClass method, and passes in addClass via a promise..
  2. The Aurelia-Animator removes the “au-attention” class (if it exists), then follows the next function in the promise chain (addClass).
  3. The Aurelia-animator adds the “au-attention” class to the “elGridCount” element in the view.
  4. The browser renders the “flash” animation referenced in the “au-attention” css class.

Pretty cool, huh? Some subtle, unobtrusive animations can really make a page seem slick. Just don’t go overboard, or you’ll take us back to the hellish days of animated gif wall papers.

You may be thinking “all the animator has done is add a css class to an element - the browser handled the animation part. What is the point of the animator?”.

Good question. The animator:

  • gives us events (such as animation start/end)
  • allows us to chain multiple animations together using promises
  • can also set/change the speed of animations
  • can stagger animations - one after the other

The animator uses Aurelia’s animator service - which provides an animation interface. The interface allows the animator service to have alternative implementations swapped in. For example, an implementation of the famo.us animation library) could be integrated. Exciting times ahead!

Aurelia-animator Supported Events

The DOM events supported by Aurelia’s animator are:

  • enter - Element enters view
  • leave - Element leaves view
  • removeClass - Class removed from DOM
  • addClass - Class added to DOM

The “move” event is defined, but not currently supported. It will return a failed result if you try.

/eof

Yes, the doc-type is still important

or… “why don’t my before/after pseudo elements work in IE8?”. It may be 2014, but doc types still matter.

If you have been a web developer longer than 3 minutes, you may remember the HTML doc type tag at the top of all your HTML markup. You probably just set it to <!DOCTYPE html> - and moved on with your life. That’s usually fine, but not always.

How I got burned today

For the last couple fo weeks, I’ve been rectifying some HTML written under Dot Net 1.0 (Yes, you did read that correctly). This code gets used by thousands of people every day. It is mostly reliable, but it is not accessible, and due to a change in government policy - my team needs to make it accessible (WCAG2 AA compliant).

Have you seen the movie Inception? This app is like thats that, but with never ending levels of nested tables. One of my co-workers replaced most of the tables with DIVs, but jury is out on whether that made things better or worse.

While bringing the CSS to modern standards, I used the CSS “before” attribute, as follows:

The style was quite simple:

.spiffy-form input.required-field:before {
    content: "*";
    font-weight: bold;
}

In Firefox, I had a nice star displayed.

Strangely, IE8 had no star.

IE8 does support the :before and :after pseudo-elements, what was going on?

It turns out that IE8 doesn’t support :before and :after if it’s rendering engine is in quirks mode.

Feeling Quirky

In the dark days of the web IE and Netscape Navigator rendered things a little differently to each other. Each browser had a partial implementation of the HTML (and later, CSS) specification - as well as custom extensions to it. This continued well into the time Netscape died and FireFox emerged.

The IE team had to move closer to standards compliance, but couldn’t risk breaking thousands (millions?) of sites to do so. The solution from the IE team (and later, other browsers) - was to implement “Quirks mode”. For IE, this means loading an earlier version of the rendering engine - one that has a bad/old/loose HTML compliance. You essentially get IE 5.5 with support for a few later features jammed in.

I’m going to emphasise that:

Quirks Mode == Internet Explorer 5

Obviously we don’t want to be using IE5.5 - because IE5.5 is crap.

Moving Forward

If it is a new(ish) site/app, go for the HTML5 doctype:

<!DOCTYPE html>

If you are updating some godawful mess from 2003, you are going to want the HTML4 doctype with loose standards compliance:

<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” “http://www.w3.org/TR/html4/loose.dtd">

If you want to stick with HTML4, but you care about accessibility, this doctype will let you use ARIA attributes:

<!DOCTYPE html PUBLIC “-//W3C//DTD HTML+ARIA 1.0//EN” “http://www.w3.org/WAI/ARIA/schemata/html4-aria-1.dtd">

Apply any of those doc types, and your before/after pseudo elements will start working. You will also have a more maintainable site and more consistent rendering.

Happy coding!

Further Reading

This great site goes into various DocTypes and their effects in a good level of detail.

/eof

Quick mobile optimisation for your blog

Here are some quick changes to make your blog (or other site) more readable on mobile devices. TLDR: viewport and mediaqueries.

Where to begin?

Here is my starting point:

Ugly mobile site

Straight away, we can identify the following issues:

  • The title is too small and hard to read
  • There are excessive side margins
  • The columns are too small to be readable

Not a good impression for a first time visitor.

Fix the Viewport

The viewport meta tag was originally introduced in Safari, by Apple. It is not part of any standards, but all major browsers now support it.

In a nutshell, the viewport meta tag allows developers to control the size and the scale of the web site display area. Mobile browsers have long used a “view port” to render the visible portion of a page. On larger websites, this allowed the viewport to be larger than the actual device - enabling the user to pan and zoom. This was browser controlled, and was usually a good thing. As most websites (at the time) were designed with 1024px wide screens as a minimum - the viewport enabled the user to have a good web experience.

Things were fine - until Apple introduced the Retina display. This upped the pixel density and other manufacturers soon followed. Websites that looked fine on mobile were suddenly one third smaller.

To deal with this, the CSS 2.1 spec included this line…

If the pixel density of the output device is very different from that of a typical computer display, the user agent should rescale pixel values

In other words, if a device has a display with a high pixel density, the browser should scale the page to allow it to display correctly.

Add this line to the HEAD section of your page:


<meta name="viewport" content="width=device-width, initial-scale=1.0">

The line above enables caling to occur. Once we provide an initial scale, the device can scale - determined by device resolution and size (a high res phone for exampke, may have a scale of 1.75 device pixels = one “CSS” pixel).

Additionally, we have given the viewport a starting width based on the device screen width.

Please note that you should only use viewport if your site is responsive.

Now that our view port is properly set up, we can use Media Queries…

Media Queries are great

Media queries are very very awesome. They allow use to target our CSS according to screen size. To see how useful this is, check this out. Say we have some CSS in our main content area that adds a 50px margin to each side:


.padSides {
  padding-left: 50px;
  padding-right: 50px;
}

Well crap, now our mobile viewers have margins that are too big. Lets fix our margins by adding a media query:


@media (min-width: 800px)
{
  .padSides {
    padding-left: 50px;
    padding-right: 50px;
  }
}

The @media part indicates a media query. It is followed by a condition. In this case, the style(s) will be overridden when the viewport is 800px wide or greater. Remember that order is important in CSS. You need to put your media-query rules after your default rules - otherwise the media query rules will never be applied!

Media queries can have rules for:

  • width/height
  • device type (TV or Handheld for example)
  • device orientation
  • and more…!

The Result

What does my blog look like now?

Nice looking mobile site

Much better, eh?

Note: To get the final result I fixed a few other items in my media query CSS (title sizes, columns). I have excluded the details to keep it simple.

References

/eof