Monthly Archives: September 2017

Mastering Advanced Sass & Workflow with Zurb Foundation (Part 2)

By Harry Manchanda

Welcome back! In the previous article, we covered all the advanced topics that Sass has in its arsenal, but the thing is you need to build a website, you need a grid for your layout, you need some excellent Components, Utility library, those neat JS plugins, succinctly put you need a web framework!

In this part, we will look to implement all of the learning that we had in the previous article into the workflow of Foundation framework.

We will learn about the Foundation’s Sass Variables, and it’s Settings file, then we will deep dive into those functions and mixins that foundation provides. We will also talk about on how to build both horizontal and vertical grid semantically through mixins by generating your own classes (and not default classes).

Why Zurb Foundation?

Foundation is the most advanced responsive front-end framework in the world. Foundation 6 has been designed to get your project from prototype to production efficiently! It includes a full range of modular and flexible components that get styled easily. It has a collection of HTML, CSS, and JavaScript that contains design patterns that you can build upon on yours next website design.

It also includes an optional prototype library that you can use to prototype layouts and UI quickly. These prototype library can be quickly thrown away thanks to the mixins which helps you to use your own custom classes or swap classes for mixins in production for cleaner markup.

Why not Bootstrap? Bootstrap is world’s most popular front-end component library then why Foundation? I heard Bootstrap 4 is in Sass? Bootstrap Styling makes me feel comfortable?

I think that Bootstrap is an excellent framework and especially with their default styling as it helps the developer’s who are not good in CSS to make their website designs with ease. But the problem arises when you need to customise the project with your own CSS classes and to write your very own advanced Sass code like functions, mixins, loops, directives, and maps that compile to CSS for the browser.

At another flip of the coin, Foundation has excellent support for Sass functions and mixins which as of yet Bootstrap doesn’t have in comparison. In layman terms, right now you can’t use Bootstrap for your own Advanced Sass code, and thus Foundation is a great bet if you are looking to code up a website layout in Sass/SCSS.

Foundation Sass Installation

There are many ways to install Foundation but for Sass Installation, you first need to get Node and then the process is quite like this:

You can install the Foundation CLI by this below command. Please note that you may need sudo to run this.

npm install --global foundation-cli

After that just run foundation new and you will be able to install foundation with their interactive interface.

Running Into Problems? You can manually set this up too, click here for more info.

Sass Variables (Settings file)

The _settings.scss is a file which contains all the default variables that exist in Foundation. You can make your changes in that one file as per your requirements. You can download the latest settings file from here.

Sass Functions

Behind the scenes, Foundation is powered by a set of utility Sass functions that help them work with colors, units, selectors, and more. But this is not all; you can use them to your advantage too just like Vanilla functions in Part 1. Here are some examples:

$color1: #0875bd;
$color2: #0EA29D;
$num: 40px;
$int1: 12;
$int2: 15;

$a: color-luminance($primary-color); // Checks the luminance of $color.
$b: color-contrast($color1, $color2); // Checks the contrast ratio of two colors.
$c: strip-unit($num); // Removes the unit (e.g. px, em, rem) from a value, returning the number only.
$d: rem-calc($num); // Converts one or more pixel values into matching rem values.
$e: gcd($int1, $int2); // Finds the greatest common divisor of two integers.

And the output,

.a { color: 0.17699; } /* color-luminance($primary-color); */
.b { content: 1.6; } /* color-contrast($color1, $color2); */
.c { content: 40; } /* strip-unit($num); */
.d { content: 2.5rem; } /* rem-calc($num); */
.e { content: 3; } /* gcd($int1, $int2); */

The whole list of functions provided by foundation can be found out here.

Sass Mixins

Foundation provides mixins for generating your own classes for all the components, utility library with ease. They also provide some generic but handy mixins like CSS triangle. So, you can use those mixins to generate your own classes to create own Semantic CSS.

Yup Semantic CSS, whether it’s SMACSS or BEM or ECSS or any other CSS methodology, just use it right away in your projects.

General Mixins

Foundation includes some handy Sass mixins to quickly create styles or to extend and truly customize an existing component.

Let’s look at some of these generic mixins in the toolset

CSS Triangle: You can create a CSS triangle, which can then be used for creating dropdown arrows, dropdown pips, and much more. You can use this mixin inside a &::before or &::after selector, for attaching the triangle to an existing element. It takes three parameters: $triangle-size, $triangle-color, and $triangle-direction respectively.

.triangle-up { @include css-triangle(5px, black, up); }
.triangle-down { @include css-triangle(20px, #f00, down); }
.triangle-right { @include css-triangle(60px, green, right); }
.triangle-left { @include css-triangle(10px, blue, left); }

Here is the output for the above code (yes Foundation’s Sass does all the heavy lifting for you).

Codepen:

Hamburger Icon Mixin: You can create a menu icon with a set width, height, number of bars, and colors. This mixin uses the height of the icon and the weight of the bars to determine the spacing in between the bars. By default, it takes three parameters: $color, $color-hover, $width, $height, $weight, and $bars respectively.

.hammenu { @include hamburger($black, $dark-gray, 20px, 16px, 2px, 3); }

And with that single line of code, you just got a hamburger menu in your project. But remember, this isn’t that simple as it looks. Check out the generated code below!

Codepen:

I hope by now, you would be understanding that why these mixins are far better then choosing to go with Vanilla CSS. But this is not all, there are many more generic mixins available for you which can be found here.

Prototyping Utility Mixins

Quickly prototype layouts and UI with Foundation’s Prototyping Utility mixins. These mixins are great realizing your sketches and mockups into hi-fi coded prototype’s ultra fast.

Margin Helper Mixin: You can use the margin helper utility as a mixin too; all the values are multiplied by $global-margin which by default is equal to 1rem. It takes 4 parameters: $top, $right, $bottom, and $left respectively.

.foo { @include margin(1, 0, 2, null); }

This above code will generate the below output. See how margin-left property wasn’t printed as this mixin also accept null as a value to reduce the CSS output.

.foo {
  margin-top: 1rem !important;
  margin-right: 0rem !important;
  margin-bottom: 2rem !important; }

Box Mixin: This mixin helps you to create a square, rectangle or a circle quickly. It takes three parameters: $width, $height, and $circle respectively.

.bar { @include box(1rem, 2rem); } // Rectangle
.baz { @include box(1rem); } // Square
.shaz { @include box(1rem, $circle: true); } // Circle

And this below is the Generated output,

Codepen:

See how these utilities are so much better and easy than those utility libraries. If you looking for more, then the whole list of Prototype specific mixins can be found here.

Flexbox Utility Mixins

Flexbox makes horizontal and vertical alignment painless, with the help of CSS properties like align-items, align-self, and justify-content. It includes a handful of classes for these properties, which will work with any flexbox-enabled component.

But hey, it’s not all about those classes, you can access all those helper classes as Sass mixins also. Please note that for building your very own flexbox component, you will need to use the flex() mixin to get started.

.my-flexbox-component {
  @include flex();

  // Horizontally or vertically aligns the items within a flex container.
  // => @include flex-align($x, $y);
  @include flex-align(center, middle);

  .sidebar {
    // Vertically align a single column within a flex row.
    // Apply this mixin to a flex column.
    // => @include flex-align-self($y);
    @include flex-align-self(bottom);
  }
}

Full list of Flexbox specific mixins can be found here.

Component Specific Mixins

Foundation provides mixins for every component out there. Unfortunately, I can’t cover all the components, so I am going to provide an example for mixins of button component but please note that all the components are being included like this only so it shouldn’t be a problem.

Button Mixin: This mixin helps you to add styles to your buttons as per your needs. Please note that for more granular control over styles, you should be using the individual button mixins. It takes 5 parameters: $expand, $background, $background-hover, $color, and $style respectively.

.my-button { @include button(false, $primary-color, auto, auto, hollow); }

As you can see, I have set $background-hover, and $color to auto respectively, as this automatically generate a color for me based on the background color.

For hover, it will darken by 15% on hover, whereas producing a white or black color for $color based on the contrast with the background. Check the output now within the codepen, yes yes all this below code is generated by the above single line Sass.

Codepen:

As I said before, I can’t cover all the components, but this process is same for all the components of foundation. Head out to docs, for more components.

Horizontal Grid (Build Semantically)

You can create a horizontal grid semantically with your own classes with ease. Here is a small example for the same, thing to be denoted is that .wrapper class is our grid container so that its center’s content in our device viewport.

The .row class will be our grid, whereas .content, and .sidebar will be our custom cells. The cells have been setup in such a way that the content will take up the remaining size not used by sidebar thanks to the handy utility provided by flexbox!

HTML Markup

<div class="wrapper">
    <div class="row">
        <div class="content"></div>
        <div class="sidebar"></div>
    </div>
</div>

SCSS Code

.wrapper {
  // Creates a max width container, designed to house up your grid content.
  // => @include xy-grid-container($width);
  @include xy-grid-container();
}

.row {
  // Creates a container for your flex cells.
  // => @include xy-grid($direction, $wrap);
  @include xy-grid();
}

.content {
  // Creates a cell for your grid.
  // => @include xy-cell($size, $gutter-output, $gutters, $gutter-type, $gutter-position, $breakpoint, $vertical);
  @include xy-cell(12);

  // Wraps a media query around the content you put inside the mixin. 
  // => @include breakpoint($value) { ... }
  @include breakpoint(medium) {
    @include xy-cell(auto);
  }
}

.sidebar {
  @include xy-cell(12);
  @include breakpoint(medium) {
      @include xy-cell(4);
  }
}

Codepen:

Vertical Grid (Build Semantically)

Inspired from CSS Grid, XY Grid was made and if there is one thing that XY Grid brought to the web framework community was the vertical grid. Vertical Grid is used for splitting up the screen vertically, lets you create a grid in a vertical direction and most commonly been used for app style layouts.

Here is a small example for this vertical grid, the thing to be denoted is that this .page will be our grid, whereas header, .content, and .footer will be our custom cells.

HTML Markup

<div class="page">
    <div class="header"></div>
    <div class="content"></div>
    <div class="footer"></div>
</div>

SCSS Code

.page {
  // Modifies a grid to give it "frame" behavior (no overflow, no wrap, stretch behavior)
  // => @include xy-grid-frame($vertical, $nested, $gutters, $breakpoint, $include-base);
  @include xy-grid-frame(true);

  // Creates a container for your flex cells.
  // => @include xy-grid($direction, $wrap);
  @include xy-grid(vertical, false);
}

.header {
  // Creates a cell for your grid.
  // => @include xy-cell($size, $gutter-output, $gutters, $gutter-type, $gutter-position, $breakpoint, $vertical);
  @include xy-cell(2, $gutter-position: top bottom, $vertical: true);
}

.content {
  @include xy-cell(7, $gutter-position: top bottom, $vertical: true);
}

.footer {
  @include xy-cell(3, $gutter-position: top bottom, $vertical: true);
}

Codepen:

I hope you loved it but hey there is a lot of more customization that you can do with XY Grid and it’s mixins. Wanna know more, head over to the docs.

Directives for Console Output

While working with the foundation framework, it’s entirely reasonable that you will face some console errors and warnings. So, for the sake of the same, you should know what all these console outputs mean. Here is a simple definition:

  1. Debug: @debug prints the value of the expression it contains (variable, math, etc.) to the console. This is ideal when you are in between of a complex bit of math, and you need to know what one of your variables contains the very right moment.

  2. Warn: @warn is a warning to the developer through which a message is sent that needs to be read, but please note that this doesn’t stop anything but instead allows the compiler to finish its job and write all the CSS. @warn is mostly suited for deprecation notices or even in the cases where you need to tell the developer to follow certain best practices.

  3. Error: @error is for stopping the Sass compiler altogether and sending the string of text as a fatal error within the compiler’s output. You should be using this when you need to send a message that stops all the process immediately. This is ideal for letting another developer know that they have messed up with something within the code and they need to correct it before moving further ahead.
// Print the output to the console.
@debug 'Red: #{$red} | Green: #{$green} | Blue: #{$blue}';

// Shows warning but doesn't break anything.
@warn 'Deprecation, $header-sizes has been replaced with $header-styles.';

// Show error and stops the whole process
@error 'No $prop specified.';

Thanks a lot…

  • If you liked my article and also my passion for teaching and want to say hello… my twitter handle is @harmanmanchanda for getting in touch! My DM’s are open to the public so just hit me up.
  • All the code discussed in the article can be found here.

Source:: scotch.io

Mastering Advanced Sass & Workflow with Zurb Foundation (Part 1)

By Harry Manchanda

You know CSS; you got into Sass as someone told you that it is that better CSS with wings. I get to tell you that you heard it right! Then you started learning it, explored through this Starter Guide and learned basic topics like variables, mixins, nesting, and imports.

After learning Sass basics, the question’s on your mind might be,

  • What are the advanced topics moving ahead?
  • How do I implement all of this in a web framework?
  • How do I create websites out of it?
  • How do I create WebApps out of it?
  • Does Sass have those conditional, loops, functions like other languages?

This is a two part article series where in the first half, we will look to cover advanced Sass topics like data types, maps, if directive, loops, and most importantly Vanilla functions such as colors, strings, lists and numbers. If you are just starting out in Sass, then also please follow along as I have some links in the below section which will help you get started

Take a look at our other Sass articles

Moving ahead, to the second half we will cover about on how to implement all of this learning within the workflow of the most advanced responsive front-end framework, Zurb Foundation.

Basics & Installation

Sass is a preprocessor that will produce clean and efficient CSS code and will cut your development time to half (if not more). Sass has more functionality than traditional CSS. Yes, it’s true that Vanilla CSS has its own fun, but you can’t reject the fact that stylesheets are getting larger, complex and harder to maintain day by day.

Please note that this article assumes you to have basic knowledge of Sass in general. If that’s not the case with you, then you should start here with this Basic Guide for starting out. For Sass Mixins, you can check out this tutorial here by Samuel Oloruntoba

If you are looking to Install Sass, then click here.

Sass Data Types

Sass is a Programming Language. Isn’t it? Data types exist in most of the programming languages, and Sass is no exception to that. A data type is a way to classify data into specific categories for different purposes.

Sass data types may not seem very useful to you right now, but their’s main strength is when they applied to other features that Sass offers. Let’s look into all the eight data types that exist in Sass.

/* Strings */
$a: harry; // Unquoted string
$b: 'harry'; // Single Quoted string
$c: "harry"; // Double Quoted string

/* Numbers */
$d: 1; // Integer
$e: 1.5; // Float
$f: 1rem; // rem Values (CSS units)
$g: 2em; // em Values (CSS units)
$h: 5px; // px Values (CSS units)

/* Booleans */
$i: true; // True
$j: false; // False

/* Null */
$k: null; // Null

/* Lists */
$l: 'Raleway','Open Sans','Lato'; // comma separated elements
$m: 3px 4px 8px; // space separated elements
$n: 'Roboto' 'Ubuntu', 15px 1.3em; // multi-list with two lists

/* Maps */
$o: (
'font-family': 'Open Sans',
'font-size': 2rem,
'color': blue
); // We will talk about maps later on. 

/* Colors */
$p: DarkBlue; // Color Name
$q: #00008B; // Hex
$r: rgba(255, 0, 0, 0.5); // RGB/RGBA
$s: hsl(10, 30%, 50%); // HSL/HSLA

/* Function References */
$t: darken($q); // We will talk about functions later on.

Sass Maps

Version 3.0 Sass brought a new data type called map. It may be confusing for some but merely think of it as key value pairs. There are a lot of functions by default (which we will discuss later on) that lets you manipulate maps.

Please note that the keys must be unique and values can include any of Sass data-type, including lists and other maps nested within it.

$map1 : (
  'Key': 'Value',
  'AnotherKey': 3rem
); // Key Value Pair

$map2 : (
  'key1' : 'value1',
  'key2' : 'value2',
  'key3' : 'value3'
); // Another Key value Pair

$map3 : (
  'KeyName': 'You can't escape me',
  'String':  string,
  'Number':  234,
  'List':  ( width 2s, height 2s, transform 2s ),
  'NestedMap':  (
    'NestedKey':  'I am deeply nested',
    'url':  './images/harry.svg',
    'Width':  300px
  ); // Nested Map
); // Key value pair with lists and map's nested in it

@If control directive

Ability to evaluate the boolean logic is an essential feature of every programming language, and Sass is no exception. The @if control directive takes a Sass expression to process it’s block of styles if the expression manages to return anything other than false or null.

Relational operators (<, >, <=, >=) are supported for numbers data types, whereas equality operators (==, !=) are supported for all data types. According to official docs,

The @if statement can be followed by several @else if statements and one @else statement. If the @if statement fails, the @else if statements are tried in order until one succeeds or the @else is reached.

@if ($prop == margin) {
  margin: $spacer * $global-margin;
} @else if ($prop == padding) {
  padding: $spacer * $global-padding;
} @else {
  @warn 'No Property Specified';
}

If() function

You can also use if else condition like a ternary operator also thanks to the Sass if function. According to official docs,

The built-in if() function allows you to branch on a condition and returns only one of two possible outcomes. It can be used in any script context. The if function only evaluates the argument corresponding to the one that it will return — this allows you to refer to variables that may not be defined or to have calculations that would otherwise cause an error (E.g. divide by zero).

Check out this below example in which we see whether the condition has met or not. If yes, then we will show green background color, or else it will be a purple background.

@mixin item-styles($condition) {
  // if true then green, else purple
  $color: if($condition, green, purple);
  .items li {
    background-color: $color;
  }
}

// Show for true condition aka green
@include item-styles(true);

@media screen and (min-width: 800px) {
  // Show for false condition aka purple
  @include item-styles(false);
}

And here is the Generated CSS output,

.items li {
  background-color: green;
}

@media screen and (min-width: 800px) {
  .items li {
    background-color: purple;
  }
}

Loops in Sass

A loop statement allows you to iterate a statement or group of statements multiple times, which allows the code to execute repeatedly. Again, Loops in Sass is not any exception from other languages. Sass provide us with three different kinds of loops to iterate over collections

  1. @for loop
  2. @each loop
  3. @while loop

If you know the iteration index, then you should be using a @for loop. But when you are iterating over a list or a map or a map with nested lists/map, the @each loop should be used.

According to developers (which includes me), @while has no exclusive use and should not be utilized so that you stay away from any confusions.

For Loop

This handy @for loop comes with two options. First is to use @for $var from $start through $end. Second is to use @for $var from $start to $end.

Please note that once the directive hits the $end, it just ends the looping process and stops there. Here is the simple example for the @for loop which makes a block grid with iteration.

// Maximum number of cells to display per direction
$max: 7; 

.grid {
  display: flex;
  flex-wrap: wrap;

  > div {
    height: 25px;
    background: #ccc;
    border: 1px solid #aaa;
  }
}

// Looping through the code
@for $i from 1 through $max {
 $equ: 100% / $i ;
 .grid.block-#{ $i } > div {
    flex: 0 0 $equ;
 }
}

And here below is the generated CSS output. As you can see we have looped through the maximum number of cells to display per direction to create a block grid. See how quickly Sass calculates everything by itself.

.grid {
  display: flex;
  flex-wrap: wrap; }
  .grid > div {
    height: 25px;
    background: #ccc;
    border: 1px solid #aaa; }

.grid.block-1 > div {
  flex: 0 0 100%; }

.grid.block-2 > div {
  flex: 0 0 50%; }

.grid.block-3 > div {
  flex: 0 0 33.33333%; }

.grid.block-4 > div {
  flex: 0 0 25%; }

.grid.block-5 > div {
  flex: 0 0 20%; }

.grid.block-6 > div {
  flex: 0 0 16.66667%; }

.grid.block-7 > div {
  flex: 0 0 14.28571%; }

Each Loop

The @each loop is commonly used for maps or lists so that you can loop through them, rather than addressing each key separately. Here is an example for a @each loop which makes buttons based on provided color palette map.

$button-palette: (
  primary: #1779ba,
  secondary: #767676,
  success: #3adb76,
  warning: #ffae00,
  alert: #cc4b37
);

@each $name, $color in $button-palette {
  .#{$name} {
    background-color: $color;
    &:hover, &:focus {
      background-color: darken($color, 20%);
    }
  }
}

See the output below where you can see how this looped through the given map and added the colors to specific classes as per the key and values provided to the tool.

.primary {
  background-color: #1779ba; }
  .primary:hover, .primary:focus {
    background-color: #0c3e5f; }

.secondary {
  background-color: #767676; }
  .secondary:hover, .secondary:focus {
    background-color: #434343; }

.success {
  background-color: #3adb76; }
  .success:hover, .success:focus {
    background-color: #1b9448; }

.warning {
  background-color: #ffae00; }
  .warning:hover, .warning:focus {
    background-color: #996800; }

.alert {
  background-color: #cc4b37; }
  .alert:hover, .alert:focus {
    background-color: #7d2c20; }

While Loop

As I said above that @while loops has no significant usage, but still, there is one thing about them that makes perfect sense about them. In our daily life, it’s common to use or hear such words like Do this while I do this or. Don’t open Computer until I clean the room, etc.

Precisely, this is what @while loop does. Check out this simple heading type scale that lets you iterate over different header sizes. Also, look how the program is adding 1 to the index after the code get executed every time.

$headerSizes: 48px 40px 31px 25px 20px 16px;
$index: 1;

@while $index <= 6 {
  h#{$index}, .h#{$index} {
    font-size: nth($headerSizes, $index);
  }
  $index: $index + 1;
}

Here below in the CSS, you can see how these header sizes get’s generated through the list thanks to @while loop.

h1, .h1 { font-size: 48px; }
h2, .h2 { font-size: 40px; }
h3, .h3 { font-size: 31px; }
h4, .h4 { font-size: 25px; }
h5, .h5 { font-size: 20px; }
h6, .h6 { font-size: 16px; }

Again will remind you that you should be using @for or @each as per the requirements. @while feels a bit useless, may this is just why Foundation Framework doesn’t use a single while in their codebase.

Vanilla Functions in Sass

This is my favorite of the lot. A Sass function, just like every other language is that so called “subprogram” that can be called from external code. Sass does include some Vanilla functions by default in which you can give Sass the arguments for a particular function and the function will return you the value. Apart from these below, there are some extra functions that are provided by Foundation which we discuss later on in Part 2.

This section below is on how to use vanilla functions provided by Sass that you can use. If you are looking for creating your own functions, this tutorial may help you.

Color Functions

Colors! When used correctly, can be incredibly powerful. This is where Sass comes in. Sass lets you control your colors with ease without needing you to choose and manipulate the colors. It does all that job for you.

$color: #0EA29D;

$a: darken($color, 10%); // Darken a color by 10%
$b: lighten($color, 15%); // Lighten a color by 15%
$c: saturate($color, 20%); // Saturate a color by 20%
$d: desaturate($color, 20%); // Desaturate a color by 20%
$e: adjust-hue($color, 15%); // Adjust hue of a color by 15%
$f: rgba($color, .7); // Adding Alpha Transparency
$g: grayscale($color); //  Converts a color to grayscale.
$h: complement($color); // Returns the complement of a color.

// Mix two colors, weight 50% by default.
// mix($color1, $color2, $weight:50%)
//
// 25% means that a quarter of the first color and three quarters of the second color should be used.
$mix: mix(#f00, #00f, 25%);

/* Just for demo */
.a { content: $a; }
.b { content: $b; }
.c { content: $c; }
.d { content: $d; }
.e { content: $e; }
.f { content: $f; }
.g { content: $g; }
.h { content: $h; }
.mix { content: $mix; }

The Generated CSS is here below, Sass just calculates all by itself.

.a { color: #0a7370; } /* Darken */
.b { color: #14e8e1; } /* Lighten */
.c { color: #00b0aa; } /* Saturate */
.d { color: #20908d; } /* Desaturate */
.e { color: #0e82a2; } /* Adjust hue */
.f { color: rgba(14, 162, 157, 0.7); } /* Alpha Transparency */
.g { color: #585858; } /* Grayscale */
.h { color: #a20e13; } /* Complement */
.mix { color: #4000bf; } /* Mixing two colors */

Alternatively, you can Debug the color too for different purposes. Stop! Big Word Alert, for now, think of @debug as console.log of javascript. We will talk about it later on in Part 2.
In this below example, we are debugging the red, green, and blue component of the variable $color.

$color: #0EA29D;

/* Debugging a color */
$red: red($color); // Gets the red component of a color.
$green: green($color); // Gets the green component of a color.
$blue: blue($color); // Gets the blue component of a color.

%debug {
  @debug 'Red: #{$red} | Green: #{$green} | Blue: #{$blue}';
}

And here is what I got in my console,

DEBUG: Red: 14 | Green: 162 | Blue: 157

String Functions

If you’ve done anything with strings in any language, you would be quite comfortable with these Sass string functions. But hey there is one exception: Please be careful that Sass strings are NOT zero-based arrays.

The first character in a Sass string is at index 1, not 0. If you are coming from a programming background, you will just hate this (includes me). Find the below examples which would help you in your upcoming Strings in Sass journey.

$a: unquote("hello world"); // Removes the quotes, if any, around a string
$b: quote(hello); // Adds quotes to an unquoted string
$c: quote("hello harry"); // Returns a quoted string unmodified
$d: str-length("hello world"); // Returns the number of characters in a string
$e: str-index("Hello", "H"); // Returns the index of the first occurrence of $substring in $string.
$f: str-index("hello", "H"); // If there is no such occurrence, returns null.
$g: to-upper-case("hello"); // Converts a string to upper case.
$h: to-lower-case("Hello"); // Converts a string to lower case.

// Inserts the string specified as $insert at the specified index position inside string
// str_insert($string, $insert, $index)
$insert: str-insert(" harry", "hello", 0);

// Extracts a substring from $string.
// The substring will begin at index $start-at and optionally ending at position $end-at.
// str_slice($string, $start-at, $end-at:-1)
$slice: str-slice("hello, world", 8);
$slice-end: str-slice("hello, world", 8, 9);

/* Just for demo */
.a { content: $a; }
.b { content: $b; }
.c { content: $c; }
.d { content: $d; }
.e { content: $e; }
.f { content: $f; }
.g { content: $g; }
.h { content: $h; }
.insert { content: $insert; }
.slice { content: $slice; }
.slice-end { content: $slice-end; }

The Generated CSS output looks like this below

.a { content: hello world; }
.b { content: "hello"; }
.c { content: "hello harry"; }
.d { content: 11; }
.e { content: 1; }
.g { content: "HELLO"; }
.h { content: "hello"; }
.insert { content: "hello harry"; }
.slice { content: "world"; }
.slice-end { content: "wo"; }

List Functions

Lists in Sass are immutable, and all list functions would return a new list rather than updating the existing list in-place. All the list functions will work for maps as well, treating them as lists of pairs. According to the one and only Hugo Giraudel,

Lists have to be the most complicated and vicious thing in the whole Sass language. The main problem with lists -if a problem it is- is that the syntax is way too permissive. You can do pretty much whatever you want. Here are some examples.

$list1 : 200px;
$list2 : 1px 2px 3px black,;
$list3 : Helvetica, Arial, sans-serif;

$zip1: 1px 2px 3px 4px;
$zip2: 4em 3em 2em 1em;
$zip3: black green blue red;

$nested-list: 1px 2px 3px green, 6px 7px 8px blue, 3px 2px 1px yellow;

html{
  // Returns the length of a list.
  // => length($list)
  width: length($list2);

  // Returns a specific item in a list.
  // => nth($list, $n)
  box-shadow: nth($nested-list , 2);

  // Replaces the nth item in a list.
  // => set-nth($list, $n, $value)
  text-shadow: set-nth($nested-list , 3 , 0em 1em .5em orange);

  // Returns the separator of a list.
  // => list-separator($list)
  height: list-separator($list3);

  // Joins together two lists into one.
  // => join($list1, $list2, $separator:auto, $bracketed:auto)
  line-height: join($nested-list , $list3,  comma);

  // Appends a single value onto the end of a list.
  // => append($list, $val, $separator:auto)
  font: append($zip3 , gray);

  // Returns the position of a value within a list.
  // => index($list, $value)
  font-size: index($nested-list , 3px 2px 1px yellow);

  // Combines several lists into a single multidimensional list.
  // => zip($lists...)
  background: zip($zip1 , $zip2 , $zip3);
}

And, here is the Generated CSS

html {
  width: 1;
  box-shadow: 6px 7px 8px blue;
  text-shadow: 1px 2px 3px green, 6px 7px 8px blue, 0em 1em 0.5em orange;
  height: comma;
  line-height: 1px 2px 3px green, 6px 7px 8px blue, 3px 2px 1px yellow, Helvetica, Arial, sans-serif;
  font: black green blue red gray;
  font-size: 3;
  background: 1px 4em black, 2px 3em green, 3px 2em blue, 4px 1em red; 
}

Number Functions

STOP! Let’s understand Math/Arithmetic operators: Before I move ahead, let’s have a little revisit to these math operators. SASS allows mathematical operations for addition, subtraction, multiplication, division, and remainder.

I hope you by now would be able to understand this below code. Let’s move ahead!

// Math Variables
$a : 16px; $b : 32px; $c : 4.5px; $d : -12px;

// Styling
.button { width: 5 + 10 + $a - ($b * 2) / $c % $d; } // 40.7777777778px;

Sass lets you add calculations in such a way that CSS would bow down and just write down the output. But would it mean that you should go around adding and dividing just anywhere? Here I will help you understand how to make calculations more useful and your Sass files more understandable.

$a : 16px;
$b : 32px;
$c : 4.5px;
$d : -12px;

// Rounds a number to the nearest whole number.
// => round($number)
.a { width: round( 5 + 10 + $a - $b * 2 / $c % $d ); }

// Rounds a number down to the previous whole number.
// => floor($number)
.b { width: floor( 5 + 10 + $a - $b * 2 / $c ); }

// Rounds a number up to the next whole number.
// => ceil($number)
.c { width: ceil( 5 + 10 + $a - $b * 2 / $c - .4 ); }

// Converts a unitless number to a percentage.
// => percentage($number)
.d { width: percentage( 4.5 ); }

// Returns the absolute value of a number.
// => abs($number)
.e { width: abs( $d ); }

// Finds the minimum of several numbers.
// This function takes any number of arguments.
// min($numbers...)
.f { width: min( 10, 20, 50, 50.1, $a ); }

// Finds the maximum of several numbers.
// This function takes any number of arguments.
// max($numbers...)
.g { width: max( 10, 20, 50, 50.1, $a ); }

// Return a decimal between 0 and 1, inclusive of 0 but not 1.
// or, if limit specified, then returns an integer between 1 and $limit
// => random | random($limit)
.h { width: random( 100 ); }

And, this below is the code which CSS has to say for all these Maths Calculations

.a { width: 41px; } /* round( 5 + 10 + $a - $b * 2 / $c % $d ); */
.b { width: 16px; } /* floor( 5 + 10 + $a - $b * 2 / $c ); */
.c { width: 17px; } /* ceil( 5 + 10 + $a - $b * 2 / $c - .4 ); */
.d { width: 450%; } /* percentage( 4.5 ); */
.e { width: 12px; } /* abs( $d ); */
.f { width: 10; } /* min( 10, 20, 50, 50.1, $a ); */
.g { width: 50.1; } /* max( 10, 20, 50, 50.1, $a ); */
.h { width: 95; } /* random( 100 ); */

For a full list of all the available functions, check out the official docs.

To be Continued: Foundation Workflow

We will wrap up this part and move into the second part, where we will look to apply our learnings within the Foundation’s Workflow. We will learn about some of the Sass Functions and Mixins (Generic, Prototype, Flexbox, Components, XY Grid) that foundation provides and how to use them so check them out at Part 2.

Thanks a lot…

  • If you liked my article and also my passion for teaching and want to say hello… my twitter handle is @harmanmanchanda for getting in touch! My DM’s are open to the public so just hit me up.
  • All the code discussed in the article can be found here.

Source:: scotch.io

Node.js Weekly Update - September 22

By Tamas Kadlecsik

Node.js Weekly Update - September 22

Below you can find RisingStack‘s collection of the most important Node.js updates, projects & tutorials from this week:

DIY Object Recognition with Raspberry Pi, Node.js, & Watson

A glorious thing nowadays is that you needn’t be an AI researcher to leverage machine learning.

In this posr you will learn how to roll your own custom object recognition solution with Raspberry Pi, Node.js, and Watson.

Mastering the Node.js Core Modules – The Process Module

In this article, you will take a look at the Node.js Process module, and what hidden gems it has to offer. After you’ve read this post, you’ll be able to write production-ready applications with much more confidence.

Topics include:

  • process.on('uncaughtException') vs process.on('unhandledRejection'),
  • Node.js signal events, like SIGTERM and SIGUSR1,
  • Node.js exit codes.

npm v5.4.2 released

This is a small bug fix release wrapping up most of the issues introduced with 5.4.0.

Node.js Performance Monitoring – Debugging the Event Loop

In this blog post, you will take a deep dive into the Node.js event loop and learn how to diagnose and debug issues that stem from unoptimized JavaScript.

Typically you’re going to want your Node.js application to perform with low lag and high idle time in the event loop—this is usually a sign of an efficient application.

Modern JavaScript cheatsheet

This document is a cheatsheet for JavaScript you will frequently encounter in modern projects and in most contemporary sample code.

This guide is not intended to teach you JavaScript from the ground up, but to help developers with basic knowledge who may struggle to get familiar with modern codebases because of the JavaScript concepts used.

Previously in the Node.js Weekly Update

In the previous Node.js Weekly Update we read that how the Node.js module ecosystem should be rethought with keeping the browser in mind as well, as well as what’s new in Node.js 8.5.

We help you to stay up-to-date with Node.js on a daily basis too. Check out our Node.js news page and its Twitter feed!

Source:: risingstack.com

Implementing GraphQL in React using Apollo

By John Kariuki

This is a second part of a set articles exploring GraphQL technology. Refer to Implementing GraphQL Using Apollo on an Express Server
for the server setup which is necessary for this client side article.

In this section, we focus on how to implement GraphQL on a React client using Apollo. We begin by setting up a simple React Component. First we will have an app component which will be the parent component and another component to render the list of channels and a third component for creating new channels.

Project Structure.

We begin by defining a simple directory structure for our react application.

app/
├── src/
    └── app/
              ├── components/
              ├── ChannelList/
                  └── ChannelList.jsx
              └──  CreateChannel/
                  └── CreateChannel.jsx
        ├── app.jsx
        ├── public/
            └── index.html
        ├── style/
            └── style.scss
        ├── .eslintrc.js
        ├── webpack.config.js
        └── package.json

Creating a ChannelList Component.

We create a simple functional component to show a list of channels from the server.

// src/app/components/ChannelList/ChannelList.jsx
import React from 'react';
const ChannelsList = () => {
  ...
 };

Wiring Our component with the GraphQL query.

To hook up our component with our query, we require the Apollo client and some other helper packages from react-apollo.

npm i -S react-apollo #yarn add react-apollo

react-apollo allows you decorate your components with a higher order component called graphql to get your GraphQL data into the component. React Apollo also comes with ApolloClient, which is the core of Apollo that handles all the data fetching, caching and optimistic updates. To setup the Apollo Client, we will need to import the required components.

// src/app/components/ChannelList/ChannelList.jsx
...
import {
  gql,
  graphql
} from 'react-apollo';
...

Next, we decorate our component with a GraphQL higher-order component that takes the query and passes the data to the component:

// src/app/components/ChannelList/ChannelList.jsx
...
const channelsListQuery = gql`
   query ChannelsListQuery {
     channels {
       id
       name
     }
   }
 `;
const ChannelsListWithData = graphql(channelsListQuery)(ChannelsList);
export default ChannelsListWithData;

The gql template tag is what you use to define GraphQL queries in your Apollo Client apps. It parses your GraphQL query which may then be consumed by Apollo Client methods. Whenever Apollo Client is asking for a GraphQL query you will always want to wrap it in a gql template tag.

When wrapped in the graphql HOC, our ChannelsList component will receive a prop called data, which will contain channels when it’s available, or error when there is an error. Data also contains a loading property, which is true when Apollo Client is still waiting for data to be fetched; this reduces the amount of code which we would otherwise write to monitor the state of the request.
We can utilize the data in out component to notify the user accordingly about the state of the API request. We can then render the channels if they are fetched successfully.

// src/app/components/ChannelList/ChannelList.jsx
...
const ChannelsList = ({ data: {loading, error, channels }}) => {
   if (loading) {
     return <p>Fetching Data...</p>;
   }
   if (error) {
     return <p>{error.message}</p>;
   }
   return <ul className="list-group">
     { channels.map( channel => <li class="list-group-item"key={channel.id}>{channel.name}</li> ) }
   </ul>;
 };
 ...

Setting up the Main App Component.

We then set up the main app component that will render the ChannelList component.

The app component is responsible for setting up the Apollo client and a network interface which defines the a http connection of our API.

// src/app/app.jsx
import {
 ApolloClient,
 ApolloProvider,
 createNetworkInterface
} from 'react-apollo';
import ChannelList from './components/ChannelList/ChannelList';

const networkInterface = createNetworkInterface({
  uri: 'http://localhost:7700/graphql',
});

const client = new ApolloClient({
   networkInterface,
});

let app = document.querySelector('#app');

render(
    <ApolloProvider client={client}>
      <div className="App">
        <h3 className="center">React , GraphQL , Apollo</h3>
        <div className="row">
            <div className="col-lg-4 col-lg-offset-4">
                <ChannelList />
            </div>
        </div>
      </div>
    </ApolloProvider>,
    app
)

The createNetworkInterface() function creates a simple HTTP network interface using the provided configuration object which includes the URI Apollo will use to fetch data from.
The ApolloProvider HOC provides a client instance to a React component tree, similar to react-redux Provider component. It provides an ApolloClient instance to all of your GraphQL components that use the graphql function. If you do not add this component to the root of your React tree then your components enhanced with Apollo capabilities will not be able to function.

A part from the client prop, ApolloProvider may also take an optional store which is an instance of Redux if we wish to include Redux in your project too. This ensures that we only use one HOC ApolloProvider and not react-redux Provider.

When we navigate to http://localhost:7700/graphiql and issue our query, we see the following results.

Subsequently when we open our application at http://localhost:7800/, we can confirm the expected results.

Performing GraphQL Mutations.

Mutations are aimed at creating, updating or deleting of records. They basically perform the write operations equivalents in CRUD operations. In this section, we will create a mutation that creates a new channel. We will create a new component CreateChannel that will be responsible for creating the new channels. It’s a simple component that provides an input field and an event handler for the input.

// src/app/components/CreateChannel/CreateChannel.jsx
...
const CreateChannel = ({mutate}) => {
    const handleKeyUp = (evt) => {
      if (evt.keyCode === 13) {
        evt.persist();
        mutate({
          variables: { name: evt.target.value }
        })
        .then( res => {
          evt.target.value = '';
        });
      }
  };

  return (
    <input
      type="text"
      className="form-control"
      placeholder="New channel"
      onKeyUp={handleKeyUp}
    />
  );
};

const CreateChannelMutation = gql`
  mutation addChannel($name: String!) {
    addChannel(name: $name) {
      id
      name
    }
  }
`;

const CreateChannelWithMutation = graphql(
  CreateChannelMutation
)(CreateChannel);

export default CreateChannelWithMutation;

Using graphql with mutations makes it easy to bind actions to your components. Unlike queries, which provide a complicated object with lots of metadata and methods, mutations provide only a simple function to the wrapped component, in a prop called mutate. Most mutations will require arguments in the form of query variables.

...
mutate({
   variables: { name: evt.target.value }
})
...

In the above snippet, we pass a name variable into mutate which will be passed to the actual query and will send to the server. The addChannel query below takes in the name variable passed in as part of the variables in mutate above.

...
const CreateChannelMutation = gql`
  mutation addChannel($name: String!) {
    addChannel(name: $name) {
      id
      name
    }
  }
`;
...

We then wire it up in the main app component.

// src/app/app.jsx
…
import CreateChannel from './components/CreateChannel/CreateChannel';
… 
render(
    <ApolloProvider client={client}>
      ...
        <div className="row">
            <div className="col-lg-4 col-lg-offset-4">
                <CreateChannel /><br/>
                <ChannelList />
            </div>
        </div>
      ...
    </ApolloProvider>,
    app
)

To make our input component call a GraphQL mutation, we have to wire it up with the GraphQL higher order component (HOC) from react-apollo. For mutations, the graphql HOC passes down a mutate prop, which we’ll call to execute the mutation. Inputting a new value and reloading the page shows the new channel.

Conclusion.

GraphQL is a pretty alternative to the conventional REST implementations. Looking at the above application and making a comparison with Redux, we can see that the amount of code used is reduced by a very large percentage. We can avoid the whole concept of writing actions and reducers and configuring stores.

In the next and final part of this series, we will focus on how to update the UI in realtime; how to perform operations and have the browser automatically update in three different ways; refetching queries, manually updating the client state based on the mutation result and using GraphQL subscriptions to notify the client about the updates. Unlike conventinal REST updates, GraphQL provides a more real-time view using subscriptions; updating data in one browser will automatically show changes in the next browser like push notifications.

Source:: scotch.io

Get to Know Bulma: My Current Favorite CSS Framework

By Chris Sevilleja

Bulma Home Page

While Bootstrap has always been a great framework and in many ways led the way for CSS frameworks to blossom, it’s good to switch it up a bit. While waiting on Bootstrap v4 to come out of beta, I went looking for other frameworks, especially flexbox based ones. Bulma to the rescue!

Bulma is built by Jeremy Thomas and is fully open source.

The modern design and features Bulma offers were the main reasons we chose to use it for Scotch.

Bulma provides many great features like:

  • Flexbox based: Makes creating grid items and vertically aligned things really easy.
  • Responsive: Mobile first framework similar to Bootstrap
  • Well documented: This sounds like a boring reason but is so very important
  • Solid looking foundation: All the typography, buttons, tables, forms, and basic CSS goodies you’d expect
  • Tons of components: Comes with layouts, a vertical alignment level, and media objects
  • Modular: Built with Sass. Only import the features that you’ll use for your project

I’ve found that building out sites/apps with Bulma (including Scotch.io!), there is less CSS that I have to write since there are so many features built in. We make heavy use of the layout features like hero sections and cards.

Here’s a quick look at the .hero class:

And the .card class:

Why Have a CSS Framework

Having a solid CSS framework as part for your project is an important foundational addition. While it’s fun to roll your own CSS foundation/framework, it is also a good option having a third-party framework like Bootstrap or Bulma. A third-party CSS framework allows for:

  • Uniformity across teams of developers
  • Documented features
  • New features are added by the package owner or community
  • A set of classes and components

Bulma Syntax

The Bulma syntax uses the is- keyword to identify modifiers on the base class. For buttons, button is the base class and there are modifiers like is-primary, is-small, and more.

Here’s a comparison of the Bootstrap vs Bulma classes. Pretty similar overall and Bulma uses the is- keyword that is pretty readable. We have a button that is-danger, is-large, is-inverse.

<!-- bootstrap button -->
<a class="btn btn-danger btn-large">Bootstrap Button</a>

<!-- bulma button -->
<a class="button is-danger is-large is-inverse">Bootstrap Button</a>

Bulma Docs and Favorite Features

Bulma’s main features are separated into a few main sections. We’ll look at some highlights of the Bulma framework. These are the features that convinced me to use Bulma when building Scotch.

Overview

Overview

The main place to get an overview of how Bulma works and what it offers. This is mostly talking on installation and how to use Bulma if you were to import the Sass variables/files/functions.

If you wanted to bring in the entire Bulma CSS file, you can use it with:

<link href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.5.3/css/bulma.min.css">

You can also install using npm:

npm install bulma

Modifiers

Modifiers

Shows off the main modifiers like responsive helpers to hide and show elements based on viewport size. There are also typography helpers to size, color, and align text.

Some examples:

<!-- sizing -->
<p class="is-size-1">3rem</p>
<p class="is-size-7">0.75rem</p>

<!-- responsive sizing based on viewport -->
<p class="is-size-1-mobile">large sizing < 768px</p>

<!-- change text color -->
<p class="has-text-white">White!</p>
<p class="has-text-black">Black!</p>
<p class="has-text-info">Blue!</p>
<p class="has-text-danger">Red!</p>

<!-- alignment -->
<p class="has-text-centered">In the middle!</p>
<p class="has-text-right">To the right!</p>

Columns

Columns

The grid system in Bulma is easy to use and customizable. We have the ability to control the sizes, grid layout based on viewport, nesting, and even sizing the gap.

Since the grid is flexbox based, we don’t have to set the sizing. The columns will just fill the space evenly.

You can also set sizes using the is- modifiers.

<!-- numbered sizing -->
is-1
is-6

<!-- readable sizing -->
is-one-third
is-one-quarter
is-half

<!-- responsive -->
is-one-third-desktop
is-one-half-tablet

Layout

Layout

This is my favorite section of Bulma. While other frameworks will give you a lot of the basics like styling, forms, and buttons, Bulma sets itself apart by providing layout components.

These are a big reason you won’t have to write much custom CSS when writing your own apps/sites. Section, hero, and level are crucial parts to any site.

Section and Container

This is a generic section class to provide a quick divider for your site. The container class will set the correct widths for your content based on viewport sizing.

<section class="section">
<div class="container">

  <h1 class="title">My New Section!</h1>

</div>
</section>

Hero

This is my favorite feature of Bulma. Browse around Scotch and you’ll see it’s heavily used. The hero class is all over the Scotch home page, at the top of article pages, and pretty much on every page! We added the icon background to our heroes and voila, you have quickly made a site topper.

<section class="hero is-info">
<div class="hero-body">
<div class="container">

  <h1 class="title">My New Hero!</h1>

</div>
</div>
</section>

The hero layout allows us to do the following modifier classes:

  • Sizing: is-small | is-medium | is-large | is-fullheight
  • Colors: is-primary | is-dark | is-info | is-danger

We can even add a navbar or tabs to the inside of the hero layout.

Level

The level is a feature that allows us to vertically center elements in a row. This is made easy thanks to flexbox.

<nav class="level">
  <div class="level-item has-text-centered">
    <div>
      <p class="heading">Tweets</p>
      <p class="title">3,456</p>
    </div>
  </div>
  <div class="level-item has-text-centered">
    <div>
      <p class="heading">Following</p>
      <p class="title">123</p>
    </div>
  </div>
  <div class="level-item has-text-centered">
    <div>
      <p class="heading">Followers</p>
      <p class="title">456K</p>
    </div>
  </div>
  <div class="level-item has-text-centered">
    <div>
      <p class="heading">Likes</p>
      <p class="title">789</p>
    </div>
  </div>
</nav>

Components

Components

Bulma comes with many important components that will be used in most sites:

All of these put together help you focus on what makes your site unique and not on writing CSS to create these often-used components.

Form and Elements

The form and elements sections aren’t as glamorous as the features mentioned above. Definitely look through them to see how the base classes of Bulma look. Here’s a few highlights out of the elements section of the docs.

Conclusion

Overall, Bulma is a great flexbox based CSS framework that has proven itself with the constant updates and new features being added at lightning pace. The modifier is- keyword is simple to use and also very readable. The use of flexbox and easy vertical centering is a solid feature.

On top of all these great features, the layout classes that come with Bulma allow us to make sites/apps quickly. Give Bulma a try and definitely read through the docs to see all the offerings.

Source:: scotch.io