How To Create A Flat Vector Illustration In Affinity Designer

How To Create A Flat Vector Illustration In Affinity Designer

How To Create A Flat Vector Illustration In Affinity Designer

Isabel Aracama

2018-07-11T20:00:02+02:00
2018-07-11T18:05:32+00:00

(This is a sponsored post.) If you are in the design world, chances are that you’ve already heard about Affinity Designer, a vector graphics editor for Apple’s macOS and Microsoft Windows.

It was July 2015 when Serif Europe launched the amazing software that many designers and illustrators like me are using now as their main tool for professional work. Unlike some other packages, its price is really affordable, there’s no subscription model and, as mentioned already, it’s available for both Macs and PCs.

In this article, I would like to walk you through just some of its very user-friendly main tools and features as an introduction to the software and to show you how we can create a nice flat vector illustration of a Volkswagen Beetle. The illustration will scale up to whatever resolution and size needed because no bitmaps will be used.

Note: As of today, July 11, Affinity Designer is also available for the iPad. Although the iPad app’s features and functionality almost completely match the desktop version of Affinity Designer, it relies much more on using the touch screen (and the Apple Pencil) and because of that, you may expect to find some differences in the workflows.


Final image that we’ll be creating in this tutorial.
Final image that we’ll be creating in this tutorial. (View large version)

I will also explain some of the decisions I take and methods I follow as I work. You know the old saying, “All roads lead to Rome”? In this case, many roads will take us where we’d like to get to, but some are better than others.

We will see how to work with the Pen tool to trace the main car outline, how to break curves and segments, how to convert objects into curves, and how to use the wonderful Corner tool. We will also, among other things, learn how to use the Gradient tool, what is a “Smart copy”, how to import a color palette from an image that we can use as a reference for our artwork, how to use masks, and how to create a halftone pattern. Of course, along the way, you will also learn some helpful keyboard shortcuts and commands.

Note: Affinity Designer has three work environments, referred to as “personas”. By default, Affinity Designer is set to the draw persona. To switch from the draw persona to the pixel persona or to the export persona, you have to click on one of the three icons located in the top-left corner of the main window. You can start working in the draw persona and switch to the pixel persona at any time, when you need to combine vectors and bitmaps.

The three work environments: draw persona (leftmost icon), bitmap persona (middle icon) and export persona (rightmost icon).
The three work environments: draw persona (leftmost icon), bitmap persona (middle icon) and export persona (rightmost icon). (View large version)

Introduction: The Flat Design Era

In recent years, we’ve seen the rise of “flat design”, in contrast to what is known as skeuomorphic representation in design.

To put it simply, flat design gets rid of the metaphors that skeuomorphic design uses to communicate with users, and we’ve seen these metaphors in design, especially in user interface design, for years. Apple had some of the best examples of skeuomorphism in its early iOS and app designs, and today it is widely used in many industries, such as music software and video games. With Microsoft’s (with Metro) and later Google’s material design and Apple’s iOS 7, mobile apps, user interfaces and most systems and OS’ have moved away from skeuomorphism, using it or elements of it as mere enhancements to a new design language (including gradients and shadows). As you can imagine, illustrations on these systems were also affected by the new design currents, and illustrators and designers started creating artwork that would be consistent with the new times and needs. A whole new world of flat icons, flat infographics and flat illustrations opened in front of our eyes.


iPhone’s home screen (iOS 6 versus iOS 7).
iPhone’s home screen (iOS 6 versus iOS 7). (View large version)


(Image source) (View large version)


(Image source) (View large version)


(Image source) (View large version)


(Image source) (View large version)

Let’s Draw A Flat Illustration!

I am providing here the source file for this work, so you can use it to explore it and to better follow along as we design it. If you do not yet have a copy of Affinity Designer, you can download a trial.

1. Canvas Settings

Open Affinity Designer, and create a new document by clicking Cmd + N (Mac) or Ctrl + N (Windows). Alternatively, you can go to “Menu” → “File” → “New”. Be sure not to check the “Create Artboard” box.

Set the type to “Web”, which will automatically set the field DPI to 72. It should be understood now as PPI, but we won’t dive into the details here. If you want to learn more on the topic, check the following two resources:

Also, remember that you can change this setting at any time. The vectors’ quality won’t be affected by scaling them.

Set the size to 2000 × 1300 pixels, and click “OK”.

Our white canvas is now set, but before we start, I’d suggest you first save this file and give it a name. So, go to “File” → “Save”, and name it “Beetle”.

2. Importing A Color Palette From An Image

One of the things I use a lot in Affinity Designer is its ability to import the colors contained in an image and creating a palette from them.

Let’s see how this is done.

For the illustration I want to draw, I thought of warm colors, like in a sunset, so I searched Google with this query: “warm colors yellows oranges reds palette”. From all the images it found, I chose one that I liked and copied it into Affinity Designer in my recently created canvas. (You can copy and paste the image to the canvas directly from the browser.)

If the Swatches panel isn’t open yet, use menu “View” → “Studio” → “Swatches”. Click the menu in the top-right corner of the panel, and select the option “Create Palette From Document”, and then click on “As Document Palette”. Click “OK” and you’ll see the colors contained in the image form a new palette in the Swatches panel. The default name for it will be “Palette” if you still haven’t saved your file with a name. In case you have, the name of this palette will be the same as your document, but if you want to rename it, simply go to the menu on the right in the Swatches panel again and select the option “Rename Palette”.

I will call it “Beetle Palette”.


Creating a palette from an image.
Creating a palette from an image. (View large version)

We can now get rid of that reference image, or simply hide it in the Layers panel. We will be using this palette as a guide to create our artwork with harmonious colors.

Interface: Before we continue, I will present a quick overview of the main sections of the user interface in Affinity Designer, and the names of some of the most used tools.


Main areas of the UI in Affinity Designer when using the draw persona.
Main areas of the UI in Affinity Designer when using the draw persona. (View large version)

Tools for the (default) draw persona in Affinity Designer.
Tools for the (default) draw persona in Affinity Designer. (View large version)

3. Creating The Background With The Gradient Tool

The next thing is to create a background. For this, go to the tools displayed on the left side, and select the Rectangle tool. Drag it along the canvas, making sure to give it an initial random fill color so that you can see it. The fill color chip is located in the top toolbar.


Click the Rectangle tool and drag it along the canvas. Fill it with a random color.
Click the Rectangle tool and drag it along the canvas. Fill it with a random color. (View large version)

Next, select the Fill tool (the color wheel icon, or press G on the keyboard), and in the top Context toolbar, select the type: “Linear”.


Select “Linear” from the Fill tool’s contextual menu.
Select “Linear” from the Fill tool’s contextual menu. (View large version)

We have several options here: “None” removes the fill color, “Solid” applies one solid color, and all of the rest are different types of gradients.

To straighten the gradient and make it vertical, place your cursor over one of the ends and pull. When you are near the vertical line, press Shift: This will make it perfectly vertical and perpendicular to the base of the canvas.

To straighten a linear gradient, pull from one end, and then press the Shift key to make it perfectly vertical.
To straighten a linear gradient, pull from one end, and then press the Shift key to make it perfectly vertical. (View large version)

Next, in the Context toolbar, click on the color chip, and you’ll see a dialog that corresponds exactly with the gradient we just applied. Click now on the color chip, and an additional dialog will open.

In the combo, click on the “Color” tab, and then select “RGB Hex Sliders”; in the field marked with a #, input the value: FE8876. Press “OK”. You’ll see now how the gradient has been updated to the new color. Repeat this action with the other color stop in the gradient dialog, and input this value: E1C372.

You should now have something like this:


Setting gradient colors.
Setting gradient colors (View large version)

Let’s go to the Layers panel and rename the layer to “Background”. Double-click on it to rename it, and then lock it (by clicking on the little lock icon in the top-right corner).

4. Drawing The Car Outline With The Pen Tool

The next thing we need to do is look for an image that will serve as our reference to draw the outline of the car. I searched Google for “Volkswagen Beetle side view”. From the images I found, I selected one of a green Beetle and copied and pasted it into my document. (Remember to lock the layer with the reference image, so that it doesn’t move accidentally.)

Next, in the side toolbar, select the Pen tool (or press P), zoom in a bit so that you can work more comfortably, and start tracing a segment, following the outline of the car in the picture. Give the stroke an 8-pixel width in the Stroke panel.

Note: You won’t need to create a layer, because the segments you trace will be automatically placed on top of the image.

The Pen tool is one of the most daunting tools for beginners, and it is obviously one of the most important tools to learn in vector graphics. While practice is needed to reach perfection, it is also a matter of understanding some simple actions that will help you use the tool better. Let’s dive into the details!

As you trace with the Pen tool in Affinity Designer, you will see two types of nodes: squared nodes appear first, and as you pull the handles, they will turn into rounded nodes.


Sharp, smooth nodes and handles on a path segment
Sharp, smooth nodes and handles on a path segment (View large version)

Affinity Designer comes with several pen modes, but we will only be using the default one, called “Pen Mode”, and as we trace the car, we will get rid of one of the handles by clicking Alt in such a way that the next section of the segment to be traced will be independent of the previous one, even if connected to it.

Here’s how to proceed. Select the Pen tool, click once, move some distance away, click a second time (a straight line will be created between nodes 1 and 2), drag the second node (this will create a curve), Alt-click the node to remove the second control handle, then proceed with node 3, and so on.

An alternative way would be to select the Pen tool, click once, move some distance away, click a second time (a straight line will be created between nodes 1 and 2), drag the second node (this will create a curve), then, without moving the mouse, Alt-click the second handle’s point to remove this handle, then proceed with node 3, and so on.

Trace the outline of the car and get rid of the handles we don’t need by Alt-clicking.
Trace the outline of the car and get rid of the handles we don’t need by Alt-clicking. (View large version)

Note: Don’ be afraid to trace segments that are not perfect. With time, you’ll get a better grip of the Pen tool. For now, it’s not very important that each node and line looks as we want it to look in the end. In fact, Affinity Designer makes it really easy to amend segments and nodes, so tracing a rough line to start is just fine. For more insight on how to easily use the Pen tool (for beginners), check out Isabel Aracama’s video tutorial.

5. Resculpting Segments And Using The Corner Tool

What we need now is to make all of those rough lines look smooth and curvy. First, we will pull the straight segments to smoothen them, and then we will improve them using the Corner tool.

Click the Node tool in the side toolbar, or select it by pressing A on your keyboard. Now, start pulling segments to follow the lines of your reference picture. You can also use the handles to help make the line take the shape you need by moving and pulling them accordingly. Just do it in such a way that it all fits the reference image, but don’t bother much if it’s not yet perfect. With the Node tool (A), you can both select and move nodes, but you can also click and drag the curves themselves to change them.

Resculpt and correct segments with the Node tool A.
Resculpt and correct segments with the Node tool (A). (View large version)

Once all of the segments are where we need them, we are going to smoothen their corners using the Corner tool (shortcut: C). This is one of my favorite tools in Affinity Designer. The live Corner tool allows you to adjust your nodes and segments to perfection. Select it by pressing C, or select it from the Tools sidebar. The method is pretty simple: Pass the corner tool over the sharp nodes (squared nodes) that you want to smoothen. If you need to, switch back to the Node tool (A) to adjust a section of a segment by pulling it or its handles. (Smooth nodes (rounded nodes) don’t allow for more softening, and they will display a smaller circle the moment you select the Corner tool.)



View large version


View large version
Use the Corner tool on sharp nodes to smoothen the lines.
Use the Corner tool on sharp nodes to smoothen the lines. (View large version)

Once our corners and segments look good, we’ll want to fill the shape and change the color of the stroke. Select the closed curve line that we just created for the car, click on the fill color chip, and in the HEX color field input FFCF23. Click on the stroke color chip beside it and input 131000.


This is what you should have after applying the fill color and stroke color.
This is what you should have after applying the fill color and stroke color. (View large version)

Create now a shape with the Pen tool, and fill it with black (000000). Place it behind the car’s bodywork (the yellow shape). The exact shape of the new object that you will create does not really matter, except that its bottom side needs to be straight, as in the image below. Place it behind the main bodywork (the yellow shape) via either the Layers panel or through the menu “Arrange” → “Back One”.


Black shape behind the car bodywork.
Black shape behind the car bodywork (View large version)

6. Creating The Wheels Using Smart Copy

We need to put the wheels in place next. In the Tools, pick the Ellipse tool, and drag over the canvas, creating a circle the same size as the wheel in the reference picture. Click Shift as you drag to make the circle proportionate. Additionally, holding Ctrl (Windows) or Cmd (Mac), you can create a perfect circle from the center out.

Note: If you need to, hide the layers created thus far to see better, or simply reduce their opacity temporarily. You can change the opacity by selecting any shape and pressing a number on the keyboard, from 1 to 9, where 1 will apply a 10% opacity and 9 a 90% opacity value. To reset the opacity to 100%, press 0 (zero).

Choose a random color that contrasts with the rest. I like to do so initially just so that I can see the shapes well contrasted and differentiated. When I am happy with them, I apply the final color. Set the opacity to 50% (click 5 on the keyboard) to be able to see through as you draw it.

Zoom into your wheel shape. Press Z to select the Zoom tool, and drag over the shape while holding Alt key, or double-click on the thumbnail corresponding to it in the Layers panel. (It doesn’t need to be previously selected, although this will help you to visually locate it in the Layers panel.)

We will now learn how to use Smart copy, and we will paste some concentric circles.

Select the circle and press Cmd + J (Mac) or Ctrl + J (Windows). A new circle will be placed on top of the original one. Select it. This command is found under “Edit” → “Duplicate”, and it’s also known as Smart copy or Smart duplicate.

Click Shift + Cmd (Mac) or Shift + Ctrl (Windows), and drag in to transform it into a smaller concentrical circle. Repeat three times, reducing a bit more in size each time, to fit your reference. Smart duplicating a shape by pressing Shift + Cmd (Mac) or Shift + Ctrl (Windows) will make the shape transform in a relative way. This will happen from your third smart-duplicated shape onwards.

smart copy via keyboard shortcuts
Smart copy via Cmd + J or Ctrl + J. (View large version)

So, we have our concentric circles for the wheel, and now we have to change the colors. Go to the Swatches panel, and in the previously created palette, choose colors that work well with the yellow that we have applied to the car’s bodywork. You can select a color and modify it slightly to adapt to what you think works best. We need to apply fill and stroke colors. Remember to give the stroke the same width as the rest of the car (8 pixels) except for the innermost circle, where we will apply a stroke of 11.5 pixels. Also, remember to put back to 100% the opacity of each concentric circle.

I chose these colors, from the outer to inner circles: 5D5100, 918A00, CFA204, E5DEAB.

Now we want to select and group all of them together. Select them all and press Cmd + G (Mac) or Ctrl + G (Windows). Name the new group “Front Wheel” in the Layers panel. Duplicate this group and, while pressing Shift, select it and drag along the canvas until it overlaps with the back wheel. Name the layer accordingly.


The car should look similar to this now.
The car should look similar to this now. (View large version)

7. Breaking Curves And Clipping Masks To Draw The Inner Lines Of The Car’s Bodywork

To keep working, either hide all layers or bring down the opacity so that they don’t get in your way. We need to trace the front and back fenders. We have to do the same as what we did for the main bodywork. Pick the Pen tool and trace an outline over it.

Once it is traced, modify it by using the handles, nodes and Corner tool. I also modified the black shape behind the car a bit, so that it shows a bit more in the lower part of the body work.


Fenders added to the car.
Fenders added to the car. (View large version)

Now we want to trace some of the inner lines that define the car. For this, we will duplicate the main yellow shape, remove its fill color and place it onto our illustration in the canvas.

Press A on the keyboard, and click on any of the bottom nodes of the segment. In the top Context toolbar, click on “Action” → “Break Curve”. You will see now that the selected node has turned into a red-outlined squared node. Click on it and pull anywhere. As you can see, the segment is now open. Click the Delete or Backspace key (Windows) or the Delete key (Mac), and do the same with all of the bottom nodes, leaving just the leftmost and rightmost ones, and also being very careful that what is left of the top section of the segment is not deformed at all.

(View large version)

I use this method for one main reason: Duplicating an existing line allows for a more consistent look and for more harmonious lines.

Select now the newly opened curve, and make it smaller in such a way that it fits into the main yellow shape when you place them on top of one another. In the Layers panel, drag this curve into the yellow shape layer to create a clipping mask. The reason for creating a clipping mask is simple: We want an object inside another object so that they do not overlap (i.e. both objects are visible), but one nested inside the other. Not doing so would result in some bits of the nested object being visible, which is not what we want; we need perfect, clean-cut lines.

Note: Clipping masks are not to be mistaken for masks. You will know you’re clipping and not masking because of the thumbnail (masks show a crop-like icon when applied) and because when you are about to clip, a blue stripe is displayed horizontally, a bit more than halfway across the layer. Masks, on the other hand, display a small vertical blue stripe beside the thumbnail.


Clipping versus masking in Affinity Designer
Clipping versus masking in Affinity Designer (View large version)
Clipping mask once it is applied
Clipping mask once it is applied (View large version)

Now that we have applied our clipping mask to insert the newly created segment inside the main shape of the car, I’ve broken some nodes and moved some others around a bit in order to place them exactly how I want. I’ve stretched the width a bit, and separated the front from the rest of the segment using exactly the same methods we’ve already seen. Then, I applied a bit more Corner tool to soften whatever I felt needed to be softened. Finally, with the Pen tool, I added some extra nodes and segments to create the rest of the inner lines that define the car.

Note: In order to select an object in a mask, a clipping mask or a group when not selecting the object directly in the Layers panel, you have to double-click until you select the object, or hold Ctrl (Windows) or Cmd (Mac) and click.

Adding extra lines to a segment.
Adding extra lines to a segment (View large version)

After some amendments and tweaking using the mentioned methods, our car looks like this:


How the car looks after a little tweaking of the segments and nodes
How the car looks after a little tweaking of the segments and nodes (View large version)

8. Drawing The Windows Using Some Primitive Shapes

In the side Toolbar, select the Rounded Rectangle tool. Drag on the canvas to create a shape. The size of the shape should fit in the car’s bodywork and look proportionate. No matter how you create it, you will be able to resize it later, so don’t worry much.

Note: When you create a shape with strokes and resize it, be sure to check “Scale with object” in the Stroke panel if you want the stroke to scale in proportion with the object. I recommend that you visually compare the difference between having this option checked and unchecked when you need to resize an object with a stroke.


Make sure this is checked if you plan to resize your artwork, so that it scales the strokes accordingly.
Make sure this is checked if you plan to resize your artwork, so that it scales the strokes accordingly. (View large version)

Once you have placed your rounded rectangle on the canvas, fill it with a blue-ish colour. I’ve used #93BBC1. Next, select it with the Node tool (press A). You will now see a little orange circle in the top-left corner. If you pull outwards or inwards, you’ll see how the angle in that corner changes. In the top Context toolbar, you can uncheck “Single radius”, and apply the angle you want to each corner of the rectangle individually. Uncheck it, and pull inwards on the tiny orange circle in the top-left corner. If you pull, you will be able to round it to a certain percentage, but you can also input the desired value in the input field for it, or even use the slider it comes with (it will show whether you’ve clicked on the little chevron). Let’s apply a value of 100%.



View large version

How the rounded rectangle primitive shape looks in default mode and how it changes when we uncheck the single radius box. Now we can manipulate the corners individually.
How the rounded rectangle primitive shape looks in default mode and how it changes when we uncheck the single radius box. Now we can manipulate the corners individually. (View large version)

Primitive shapes are not so flexible in terms of vector manipulation (compared to curves and lines), so, in order to apply further changes to such a shape (beyond fill, stroke, corners, width and height), we will need to convert it to curves.

Note: Once you convert a primitive shape into curves, there is no way to go back, and there will be no option to manipulate the shape through the little orange stops. If you need further tweaking, you will need to do it with the Corner tool.

Select the rectangle with the Node tool (A), and in the top Context toolbar, click the button “Convert to Curves”. The bounding box will disappear, and all of the nodes forming the shape will be shown. Also, note how in the Layers panel, the name of the object changes from “Rounded Rectangle” to “Curve”.

Now you need to manipulate the shape in order to create an object that looks like a car window. Look at the reference picture to get a better idea of how it should look. Also, tweak the rest of the drawn lines in the car, so that it all fits together nicely. Don’t worry if the shapes don’t look perfect (yet). Getting them right is a matter of practice! Using the Pen tool, help yourself with the Alt and Shift keys and observe how differently the segment nodes behave. After you have created the front window, go ahead and create the back one, following the same method.

We also need to create the reflections of the window, which we’ll do by drawing three rectangles, filling them with white color, overlapping them with a bit of offset from one another, and setting the opacity to 50%.

Place the cursor over the top bounding-box white circle, and when it turns into a curved arrow with two ends, move it to give the rectangles an angle. Create a clipping mask, dragging it over the window shape in the Layers panel as we saw before. You can also do this by following the following alternative methods:

  • Under the menu “Layer” → “Insertion” → “Insert Inside” the selected window object.
  • With the keyboard shortcut Ctrl + X (Windows) and Cmd + X (Mac), select your window object → “Edit” → “Paste Inside” (Ctrl/Cmd + Alt + V).

Repeat this for the back window. To add visual interest, you can duplicate the reflections and slightly change the rectangles’ opacities and widths.

Create the reflections on the windows, and clip them inside.
Create the reflections on the windows, and clip them inside. (View large version)

9. Adding Visual Interest: Halftone Pattern, Shadows And Reflections

Before we start with the shadows and reflections, we need to add an extra piece onto the car so that all of the elements look well integrated. Let’s create the piece that sits below the doors. It is a simple rectangle. Place it on the corresponding layer order, so that it looks like the picture below, and keep inserting all of the pieces together so that it looks compact. I will also move a bit the front fender to make the front shorter.


The car, once the final bodywork pieces have been placed and tweaks made. We’re getting there!
The car, once the final bodywork pieces have been placed and tweaks made. We’re getting there! (View large version)

Now let’s create the halftone pattern.

Grab the Pen tool (P) and trace a line on your canvas. In the Stroke panel (you can also do this in the Pen tool’s Context toolbar section for the stroke, at the top), set the size to something like 7 pixels. We can easily change this value later if needed. Select the “Dash” line style, and the rest of the dialog settings should be as follows:


Settings for the first part of creating the halftone pattern.
Settings for the first part of creating the halftone pattern. (View large version)

Now, duplicate this line, and place the new one below with a bit of an offset to the left.



View large version

Group both lines, duplicate this group with a Smart copy, and create something like this:


Smart copy the first two lines, and create the whole pattern.
Smart copy the first two lines, and create the whole pattern. (View large version)

When you drag a selection in Affinity Designer, only objects that are completely within the selection area will be selected. If you want to select all objects without having to drag over all of them completely, you have the following options:

  • Mac: Holding the (Ctrl) key will allow you to select all objects touching the selection marquee as you draw it.
  • Windows: Click and hold the left mouse button, start dragging a selection, and then click and hold the right mouse button as well. As you are holding both buttons, all objects touching the selection marquee will be selected.
  • Alternatively, you can make this behavior a global preference. On Mac, go to “Affinity Designer” → “Preferences” → “Tools”, and check “Select object when intersects with selection marquee”. On Windows, go to “Edit” → “Preferences” → “Tools”, and check “Select object when intersects with selection marquee”.

To make the illustration more interesting, we are going to vary the beginning and end of some of the lines a bit. To do this, we select the Node tool (A), and move the nodes a bit inwards.

It should now look like this:



View large version

To apply the pattern to our design, make sure everything is grouped, copy and paste it into our car artwork, reduce its opacity to 30%, and also reduce the size (making sure “Scale with object” is checked in the Stroke panel). We will then create a clipping mask. It is important to keep consistency in the angle, color and size of this pattern throughout the illustration.

Applying the halftone mask.
Applying the halftone mask (View large version)

Now, apply the halftone pattern to the back fender and to the car’s side; make sure to create a placeholder for it first, be it the fender itself or a new shape. Make some tweaks if you need to adapt the pattern to your drawing in a harmonious way. You can change the overall size, the dots’ size, the transparency, the angle and so on, but try to be consistent when applying these changes to the pattern bits.

For the shadow below the windows, I drew a curve to be the placeholder, and applied the color #CFA204 so that it looks darker.

10. Creating The Remaining Elements Of The Car

Now, it’s all about creating the rest of the elements that make up the car: the bumpers, the back wheel and the surf board, plus the design stickers.

  • The front and back lights
    For the front light, switch to the Segment tool and draw the shape. Then we need to rotate it a bit and place it somewhere below the car’s main bodywork. The same can be done for the back light but using the Rectangle tool. The colors are #FFDA9D for the front light and #FF0031 for the back light.
Creating the front light
Creating the front light (View large version)
  • Surfboard
    To create the surfboard, we will use the Ellipse tool and draw a long ellipse. Convert it to curves and pull up the lower segment, adjusting a bit the handles to give it the ideal shape.
Creating the surf board
Creating the surf board (View large version)

Now, just create two small rounded rectangles, with a little extra line on top for the board’s rack. Place them in a layer behind the car’s main body shape.


Board rack pieces
Board rack pieces (View large version)

With the Pen tool, add the rudder. Its color is #B2E3EF. And for the stroke, use a 6-pixel width and set the color to #131000.

  • Spare wheel
    Now let’s create the the spare wheel! Switch to the Rounded Rectangle tool. Drag over the canvas to draw a shape. Color it #34646C, and make the stroke #131000 and 8 pixels in size. The size of the spare wheel should fit the proportions of your car and should have the same diameter as the other wheels, or perhaps just a bit smaller. Pull the orange dots totally inwards, and give it a 45-degree angle. For the rack that holds the wheel, create a small piece with the Rectangle tool, and give it the same 45-degree angle, color it #4A8F99, and make the stroke #131000 and 4.5 pixels in size. Create the last piece that rests over the car in the same way, with a color of #34646C, and a stroke that is #131000 and 4.5 pixels in size.

Lastly, let’s create a shadow inside the wheel to add some more interest. For this, we’ll create a clipping mask and insert an ellipse shape with a color of #194147, without a stroke.

Note: We may want to create the same shadow effect for the car wheels. Use the Rectangle tool and a color of #312A00, create a clipping mask, and insert it in the wheel shape, placing it halfway.


Three simple shapes to draw the spare wheel and its rack
Three simple shapes to draw the spare wheel and its rack (View large version)
  • Bumpers
    For the bumpers, we will apply the boolean operation “add” to two basic shapes and then clip-mask a shadow, just as we did for the wheels.

Boolean operations are displayed in the section of icons labeled “Geometry” (Mac) and “Operations” (Windows). (Yes, the label names are inconsistent, but the Affinity team will likely update them in the near future, and one of the labels will become the default for both operating systems.) If you don’t see them in the upper toolbar, go to “View” → “Customize Toolbar”, and drag and drop them into the toolbar.

Important: If you want the operation to be non-destructive, hold the Alt key while clicking on the “Add” icon (to combine the two basic shapes).


Boolean operations: Add, Subtract, Intersect, Divide, Combine.
Boolean operations: Add, Subtract, Intersect, Divide, Combine. (View large version)

Applying the (destructive) Add operation to create a single shape from two shapes.
Applying the (destructive) Add operation to create a single shape from two shapes. (View large version)

Note: If you try to paste the “shadow” object inside the bumper, it will only work if the bumper is one whole object (a destructive operation). So, if you used Alt + “Add”, this will not work now. However, you can still work around this by converting the Compound shape (the result of a non-destructive operation that is a group of two objects) to one Curve (one whole vector object). You just need to click on the Compound shape, then in the menu go to “Layer” → “Convert to Curves” (or use the key combination Ctrl + Enter).

  • Back window
    We are still missing the back window, which we will create with the Pen tool, and the decoration for the car. For the two colored stripes, we need the Square tool and then clip-mask these two rectangles into the main bodywork. The size is 30 × 380 pixels, and the colors are #0AC8CE and #FF6500. Clip them by making sure you’ve put them on the right layer, so that the dark lines we drew before are above them.

  • Number 56
    For the number “56” decoration, use the Artistic Text tool (“T”), and type in “56”. Choose a nice font that matches the style of the illustration, or try the one I’ve used.

The color for the text object is #FFF3AD.

(I added an extra squared shape behind the back fender, which will look like the end of the exhaust pipe. The color is #000000.)

  • Color strips
    Now that we’ve done this, check the color stripes and the window they overlap with. As you can see (and because we put some transparency in the window glass), the orange stripe is visible through it. Let’s use some Boolean power again to fix this.

Bumpers and exhauster added. Check out the overlapped window and the orange stripe!
Bumpers and exhauster added. Check out the overlapped window and the orange stripe! (View large version)

Duplicate the window object. Select both the window object (the one you just duplicated) and the orange stripe in the Layers panel. Apply a “subtract” operation.


Stage 1, before the subtract operation.
Stage 1, before the subtract operation. (View large version)

tage 2, once the subtract operation is applied.
Stage 2, once the subtract operation is applied. (View large version)

Now, the orange stripe has the perfect shape, fitting the window in such a way that they don’t overlap.


Stripe and window with subtraction operation applied.
Stripe and window with subtraction operation applied. (View large version)
  • Smoke
    To create the smoke from the exhaust, draw a circle with a white stroke, 5.5 pixels in size and no fill. Transform it to curves and break one of its points. From the bottom node, trace a straight line with the Pen tool.

Duplicate this “broken” circle, and resize to smaller circles, and flip and place them so that they look like this:


Creating the exhaust smoke
Creating the exhaust smoke (View large version)

Note: Now that the car is finished, group all of its layers together. It will be much easier to keep working if you do so!

11. Creating The Ground And The Background Elements.

  • Ground
    Let’s trace a simple line for the ground, and add two bits breaking it in order to create visual interest and suggest a bit of movement. We also want to add an extra piece to create the ground. For this, we will use the Rectangle tool and draw a rectangle with a gradient color of #008799 for the left stop and #81BEC7 for the right stop. Give it 30% opacity.

Gradient for the ground piece and the grouped car layers for a clean view in the Layers panel.
Gradient for the ground piece and the grouped car layers for a clean view in the Layers panel. (View large version)
  • Clouds
    For the clouds, select the Cloud tool from the list of (primitive) vector shapes. Draw a cloud by holding Shift to keep the proportions. Make it white. Transform it into curves, and with the Node tool (A) select the bottom nodes and delete them. Sub-select the bottom-left and bottom-right nodes (after deleting all of the others), and then in the Context toolbar, select “Convert to Sharp” in the Convert section. This will make your bottom segment straight. Apply some transparency with the Transparency tool (Y), and duplicate this cloud. Place the clouds in your drawing, spread apart as you wish and in different sizes.

My clouds have 12 bubbles and an inner radius of 82%. You can do the same or change these values to your liking.

Creating the clouds with the Cloud tool and the Transparency tool
Creating the clouds with the Cloud tool and the Transparency tool (View large version)
  • Palm trees
    To create the palm trees, use the Crescent tool from the list of primitive shapes on the left. Give it a gradient color, with a left stop of #F05942 and a right stop of #D15846.

Drag to draw the crescent shape. Move its center of rotation to the bottom of the bounding box, and give it a -60-degree angle.

The center of rotation can be made visible in the Contextual toolbar section for the Move (and Node) tool. It looks like a little crosshair icon. When you click on it, the crosshair for moving the rotation center of an object will show. Duplicate it, either via Cmd + C and Cmd + V (Mac) or Ctrl + C and Ctrl + V (Windows), or by clicking and then Alt + dragging on the object, and move the angle of the new crescent to -96 degrees. Make it a bit smaller. Copy the two shapes and flip them horizontally.

I also created and extra crescent.

Creating the palm leaves
Create the palm leaves (View large version)

To create the indentations on the leaves, transform the object to curves, add a node with the Node tool, and pull inwards. To make the vortex sharp, use “Convert” → “Sharp”.

Creating the leaves’ indentations
Creating the leaves’ indentations (View large version)

Create the trunk of the palm tree with the Pen tool, group all of the shapes together, and apply an “add” boolean. This way, all of the shapes will transform into just one. Apply a 60% opacity to it.


The palm tree once the Add boolean operation has been applied.
The palm tree once the Add boolean operation has been applied (View large version)

Duplicate the tree shape several times, changing the sizes and tweaking to make the trees slightly different from one another. (Making them exactly the same would result in a less interesting image.)

The last thing we need to make is the sun.

  • The sun
    For this, simply draw an ellipse and apply a color of #FFFFBA to it. Apply a transparency with the Transparency tool (Y), where the bottom is transparent and gets opaque at the top.

Transparency applied to the sun shape
Transparency applied to the sun shape (View large version)

Now we will add some detail by overlapping several rounded rectangles over the sun circle and subtracting them (click Alt for a non-destructive action, if you prefer).

Applying a subtract operation
Applying a subtract operation (View large version)

Place your sun in the scene, and we are done!

12. A Note On The Stacking Order (And Naming Of Layers)

While you work, and as the number of objects (layers) grows, which will also make your illustration more and more complex, keep in mind the stacking order of your layers. The sooner you start naming the layers and placing them in the right order, the better. Also, lock those layers that you’re done with (especially for things such as the background), so that they don’t get in the way as you work.

In this illustration, the order of elements from bottom to top is:

  • background,
  • ground,
  • sun,
  • clouds,
  • palm trees,
  • car.

Conclusion

I hope you could follow all of the steps with no major problems and now better understand some of Affinity Designer’s main tools and actions. (Of course, if you have some questions or need help, leave a comment below!)

These tools will allow you to create not only flat illustrations, but many other kinds of artwork as well. The tools, actions and procedures we’ve used here are some of the most useful and common that designers and illustrators use daily (including me), be it for simple illustration projects or much more complex ones.

However, even my most complex illustrations usually need the same tools that we’ve seen in action in this tutorial! It’s mainly a matter of understanding how much you can get out of each tool.

Remember the few important tips, such as locking the layers that could get in your way (or using half-transparency), stacking the layers in the right order, and naming them, so that even the most complex of illustrations are easy to organize and work with. Practice often, and try to organize things so that your workflow improves — this will lead to better artwork and better time management as well.

Also, to learn more about how to create this type of illustration, check out the video tutorial that I posted on my YouTube channel.


The completed Volkswagen Beetle illustration.
The completed Volkswagen Beetle illustration. (View large version)
Smashing Editorial
(mb, ms, ra, yk, al, il)


Source: Smashing Magazine

Best Market for WordPress Themes: TemplateMonster or ThemeForest?

This article was created in partnership with TemplateMonster. Thank you for supporting the partners who make SitePoint possible.

Most users feel overwhelmed when they need to select the best ready-made design for their website. There are plenty of agencies and web design studios offering unique designs to help users get started with websites for multiple purposes.

The number of web platforms selling themes crafted by vendors worldwide grows quickly all the time. If you want to select the best ready-made design for your site and feel confident that you’ve made the right choice, then it’s always a great idea to choose the industry leaders.

TemplateMonster and ThemeForest have proven to be the two leading digital marketplaces selling WordPress templates of top quality. Comparing these two options, which one is a better place to buy themes for your websites? That’s the question that we are going to answer in this post.

Why You Should Select WordPress Themes with Caution

WordPress has become one of the leading content management systems in the world. With its help, you will find no difficulty launching any kind of website, representing any business niche in an effective style.

Selecting the most optimal starting point for your site, you need to make sure that your WordPress theme complements the content that you are going to share on your site. Using WordPress, you can create stunning blogs, portfolios, business and corporate web projects, landing pages, and even eCommerce sites. Depending on the goal and the type of the online project that you need to launch, you need to select WordPress themes that meet your specific requirements. For example, launching a blog, you need to select a template that improves the readability of your content. If you want to launch a portfolio site, then the template of your choice should be optimized for handling image-rich web projects perfectly well.

Many WordPress templates available today are pre-installed with plugins and extensions intended to enhance the performance of niche-specific web projects. Just in case the selected WordPress theme isn’t loaded with the necessary tools, make sure that it’s compatible with the respective functionality.

Security is one of the top priorities that you need to take into consideration while selecting the best WordPress theme for your site. Although WordPress is known as one of the safest CMSs on the web, featuring regular updates, you need to make sure that you download a template that features regular updates so it won’t become outdated a few months after the launch of your site.

Let’s compare the functionality included in two of the top-selling business WordPress themes from both marketplaces. There are some features they have in common and certain peculiarities that make each of them unique. So, let’s compare and choose the best theme of the two reviewed.

EasyJet vs Argenta Multipurpose WordPress Themes

EasyJet is a functional multipurpose template sold by ZEMEZ in the TemplateMonster digital marketplace. This is a usable ready-made solution that is easy-to-handle by both beginners and expert webmasters. This is a feature-rich WordPress template that comes loaded with everything that you need for the launch of personal, business or eCommerce sites. There is no need to be an expert web designer or a programming specialist in order to handle the theme on your own. The theme’s download pack includes a wide range of features that will appeal to users of all skill levels.

Argenta is a creative multipurpose WordPress template sold by Colabrio on the ThemeForest marketplace. This is one of those feature-rich WordPress templates suited to be used for content-heavy web projects. Collections of the fully editable layouts that are included in the theme’s download pack are ready to be customized by means of the usable modification features that can be accessed via the dashboard.

Both of the reviewed WordPress templates are multipurpose solutions that include a handful of tools and features that provide for specific needs. Both templates include similar options and different sets of tools, which make one of them stronger than the other. Well, enough said. Let’s get straight to the comparison.

Installation

In order to start working with any WordPress template, you need to have WordPress installed. If you haven’t done this yet, make sure you install the latest WordPress version on your web host.

In order to start working with the EasyJet WordPress template, you need to make all the necessary preparations and run the plugin installations. This guarantees that the chosen template will work correctly after the installation of all its components.

The post Best Market for WordPress Themes: TemplateMonster or ThemeForest? appeared first on SitePoint.


Source: Sitepoint

Learning To Code By Writing Code Poems

Learning To Code By Writing Code Poems

Learning To Code By Writing Code Poems

Murat Kemaldar

2018-07-11T14:00:32+02:00
2018-07-11T13:57:24+00:00

Back in 2008, I started studying design and clearly remember how the sheer sight of code just intimidated me. I had some coding classes, and without any prior coding experience, I had a tough time understanding the code I first got in touch with. Suddenly, the words that I was used to in the English language (such as “new,” “return” and “throw/catch”) took on a whole new meaning; the cryptic syntax, semicolons, brackets and completely new rules didn’t make things any easier for me.

If you are new to JavaScript and/or have struggles adding it to your skillset, I may have an approach for you to overcome those barriers. You are definitely not alone, and you have every right to think that learning to code is a tough nut to crack.

Why Is Learning To Code So Tough?

Here are some of the misconceptions about why I think people are having a hard time learning or getting interested in JavaScript (or any coding language):

  • Code is cryptic, purely functional and scary;
  • Code is meant for machines only, so people do not feel addressed or engaged;
  • Code is not treated as a language because it has a completely different use case and looks very different from anything they have seen before;
  • People think of stereotypes (evil hackers, maybe some Matrix dudes), and thus do not identify themselves with it.

A young and unexperienced student with a pacifier and pillow
Me, before any contact with code (Large preview)

As a developer, you are expected to treat code in a very specific way — even to think in a quite different (and highly logical) way. Coding languages are quite strict and intolerant; a single character can make the machine fail to understand what you mean and make applications crash. You are expected to ignore and override certain things you know from speaking and writing a human language (which is, by the way, also the case when learning a new human language).

But not all programming languages, documentations or tutorials on the web are made with this “human to programming language transition” in mind. Of course, they don’t have to. After all, the main purpose of code is to tell machines what to do.

Still, due to that purpose, a chance for comparison is simply missing and the languages you speak (vocabulary and rules) seem to be rendered useless for learning a programming language. There is no word for “love” in the JavaScript language, nor does it make sense to say “I love you.” A machine (or browser) simply does not know or care about love (yet?). This “completely new” and “don’t know where to start” feeling can be scary as hell.


 A student who is intimidated by coding languages
Me, after my first contact with code. (Large preview)

This is why I am here. I think that you can learn JavaScript in a much easier and artistic fashion, by holding on to your human language knowledge, and by treating JavaScript like any other human language. Let me demonstrate with a small example.

Fun fact: Some programming languages actually have the transition from one programming language to another in mind. This is why it is so much easier to learn a lot of programming languages — just by learning a single one.

A Small Example

In a lot of cases, when you want to execute JavaScript code, you want the “document” (basically the website, a user is downloading on each visit) to be ready so that you can interact with HTML elements, for example. In pure JavaScript, you may stumble over something this:

(function() {
   // Your code goes here
})();

(Yuck! 😖 In this case, a function is defined in brackets, and then immediately called with another pair of brackets at the end. This is referred to as an IIFE.)

Or sometimes like this:

if (document.readyState === ‘complete’) {
  // Your code goes here
}

The first snippet definitely requires an explanation, while with the second (and maybe some fantasy), one could comprehend that there is a condition which needs to be fulfilled so that something else happens just by just looking at it.

Imagine something like this, though:

onceUponATime(function () {
  // Your code (story) goes here
})

“Once upon a time” is something (dare I say) even a child might understand. It addresses the developer (by referring to childhood memories), while theoretically doing the same thing. This is what I consider “having the human to coding language transition” in mind.

Quick note on “functions“: A function is basically a skill, which is dormant until you call upon it. “To read” is a skill function read() { … }, which is called upon when you are want to read something like this: read(). There is also something called “anonymous functions”, i.e. "function() { … } (has no name, like in the snippets above) which are basically “one-time / casual actions” that you wouldn’t consider to be a skill, such as “to push a button.”

Turning The Tables: From Message To Basics

So let’s take this idea a bit further. Let’s take the reasons and misconceptions above, and turn them upside-down:

A small poem.

Written in JavaScript.

Made for human beings.

About the love between two individuals.

// Love at first sight
if (me.getDistanceTo(you.position) < 200) {
  me.setFeelings({
    inLove: true,
  });
}

It is not functional. It is currently not meant for machines. It is meant for you to read and understand.

If you got the message of the poem, you actually understood a piece of JavaScript code, which you might have compared to the English language.

Now you might ask yourself: I understand this, but why is it written like this? What are the rules (grammar) of this language? What is the meaning of “me” (in a technical sense), and why does this code look so similar to English?

Rules, Vocabulary, And Variables

One of the most important things to understand when learning a programming language is the concept of variables.

Every human language has its rules (grammar) and a lot of vocabulary (pre-defined). Obviously, both of these first need to be learned in order to be able to speak the language.

JavaScript, like many other programming languages, also comes with its own set of rules (e.g. the . between the words or how if statements are written) and its own vocabulary (if, document, window, Event, and so on). These keywords are reserved (or ‘pre-defined’) by JavaScript (and the browser), and each one of them has its specific purpose.

But like I mentioned earlier, a chance to compare the words and sentences you know from the English language is seemingly missing because there are no equivalents.

This is where variables come in; you (the developer) can (or even have to) define the variables in order to make machines and developers understand what something stands for. Variables can take a lot of forms (hence the name): They can be a chain of words and letters (strings), a number, an action (function), or even a collection (array). You name it.

In all languages, there is probably a word for love. You kinda know what it means, but not really, because it is so subjective. But still, there is a word for it.

But in JavaScript, there is no “love,” until you say there is. It can be whatever you want it to be.

var love = {
  color: ‘red’,
  duration: 365,
  loveTarget:  ‘cats’,
};
// a simple variable expression,
// where love is an object “{ … }”, a thing
// with some properties (color, duration, loveTarget).

const love2 = { color: ‘purple’, duration: ‘forever’, loveTarget: ‘dogs’, };

// also a variable expression, where love2 (a constant), // cannot be redefined / overwritten completely: // love2 = undefined; // => will not work

// (“undefined” is a pre-defined javascript keyword, // basically saying “has no value”)

It is crucial to be able to distinguish between what is pre-defined in JavaScript (JavaScript rules and vocabulary), and what is actually custom defined by the developer (also known as ‘application logic’ or ‘business logic’).

Returning to the poem written above:

// Love at first sight
if (me.getDistanceTo(you.position) < 200) {
  me.setFeelings({
    inLove: true,
  });
}

These expressions come from the following JavaScript vocabulary/ruleset:

if (…) { … }
// if statement: when … is met, do things in { … }

{ inLove: true, } // an “object” with some info, some thing in the world. // can contain other info, and “skills” (functions). // “inLove” is a custom property, // “true” is pre-defined in javascript, (meaning: “yes”) // and the value of “inLove”.

. // needed to access an objects property “my name: me.name”

getDistanceTo() // an expression to “call” a function (a “skill”). // getDistanceTo is custom (not JavaScript), and a function, // so it can be executed / called upon with the “()” after. // sometimes you can pass arguments in those brackets (like “position”) // to change the outcome of a function.

And these are the variables (where you have free reign over defining their names and behavior):

me // an object, some thing in the world
you // an object, some thing in the world
position // an info about “you”, accessed by the “.”
getDistanceTo // a skill of me, accessed by the “.”
getDistanceTo() // the skill, with javascript grammar telling: do it.
getDistanceTo(position) // same, but do it with “position”.
setFeelings // another skill of me, accessed by the “.”
setFeelings({ inLove: true }); // the skill, with some instructions (an object).

Let’s assume the poem is now human-readable. You might have understood the message, you also might see the difference between JavaScript language rules you need to follow, and the things you actually have to come up with yourself (the variables).

But what about the machine?

If the machine (the browser) were to read this poem, it would throw an error. The machine needs a definition of “me” and “you” because it tries to access its properties (via the . in me.getDistanceTo()). With the distinction ability mentioned above, you can actually engineer “me” and “you” to make the poem executeable/machine-readable, like this:

// This is how the definition of a being (me/you) could look like

var me = { position: {x: 0, y: 0} // some coordinates, maybe getDistanceTo: function(position) { // calculate the distance, relative to own position }, setFeelings: function(feelings) { // handle those feelings… } }

var you = { position: {x: 0, y: 0} // some coordinates, maybe }

// the poem itself if (me.getDistanceTo(you.position) < 200) { me.setFeelings({ inLove: true, }); }

So what happened here?

  • We read a JavaScript poem, written with JavaScript “grammar” with the only goal to be understood by human beings.
  • After understanding the message, we distinguished between rules, vocabulary, and variables, to understand the structure of the poem (grammar and basics of JavaScript).
  • With that distinction, we engineered the rest of the poems variables, with JavaScript rules in order to make it runnable by a machine (in the browser).

This was possible, because we treated JavaScript just like the English language.

A Bigger Example: Interactive Code Poetry

This is how my personal project LoveBits came to be. LoveBits is a code learning/storytelling experience.

Animated demonstration of the LoveBits project
LoveBits: Code poetry project in JavaScript (Large preview)

It tries to get people interested in JavaScript/coding by:

  • Putting readability and human language first;
  • Combining code with an art the reader might already be familiar with.

Storywise, it is about two Bits (rectangular beings); one of the Bits (blueBit) is the romantic one and writes JavaScript love poems to the other Bit (purpleBit).

When you start LoveBits, you can select one of the multiple love poems (written in JavaScript). Each poem has a code snippet which is written in a way that it is supposed to be understood by people who are not even familiar with programming. The only requirement is the English language.

“Love at first sight” (actually one of the LoveBits poems), for example, is about these two Bits in which the blueBit basically says, “If I get close enough to your position, I will ‘set my feelings’ to inLove: true.”

The special thing about these poems though is that you can “run” or “play” them simply by pressing the “play” button below. In the case of “Love at first sight,” you would see a blue and purple rectangle along with a number. As you might’ve already guessed, those are the two Bits mentioned in the poem, and the number below the blueBit is actually the distance between the blueBit and the purpleBit.

As the poem suggests, you may want to make the blueBit fall in love with the purpleBit by reducing the distance between them, right? So what can you do? You can interact and drag the blueBit around, and make it fall in love. But be careful, sometimes there is more than just one outcome.

One might actually say that you are the machine here. You’re the one who needs to interpret JavaScript code to be able to act and help two digital beings fall in love.

Where To Go From Here?

If you are a struggling developer, try treating JavaScript like a human language, and just understand what code snippets are supposed to do first instead of what they actually end up doing.

This is what I would recommend you to do next:

  • Always prefer going straight for examples and code for entire applications that combine rules, vocabulary, and variables together to form an application logic;
  • Application logic will tell the stories that will help you fill the gaps like in the code examples above. Code libraries and utilities such as lodash will only provide you with new vocabulary which will become helpful after being able to read and understand JavaScript code;
  • Review existing code, and try to break it down into small functions with names that reflect what they do. Write code which addresses humans and machines alike. Write code in such a way that it can be read like a sentence. Use comments wherever needed. Think about: How would I express this in a human language (to another developer)?

Conclusion

Learning to code can become easier once you start treating code as a human language and not as something aliens may have invented. Learning to distinguish between language features (built-ins) and variables/custom code for application logic is crucial. Being able to understand the application logic will put you in a powerful position to improve and change things, without even knowing language features.

Message before basics: Understand the message of any code snippet, and the basics of JavaScript will naturally follow. How many times have you heard someone say, “I understand the language, but I do not speak it yet”? It is a natural process, which can and maybe should be applied for learning both human and coding languages.

Also, always keep in mind that code has a clear functional purpose, but it does not always have to be like that. Even human languages were purely functional once, but then there came poems and even songs (JavaScript songs, anyone?), which connected people in entirely different ways. I think, or hope, that the same can apply here.

Always explore code projects, and perhaps even try writing a poem yourself (maybe even in another programming language you are familiar with)? I enjoyed creating the LoveBits project and would love to see some of your ideas in the comments below!

Further Reading

  • If Hemingway wrote JavaScript,” Angus Croll
    This is one of my favorite books which I actually stumbled upon after LoveBits. It’s about several famous poets and artists, and how they would have written JavaScript code snippets. It’s hilarious!
Smashing Editorial
(rb, ra, il)


Source: Smashing Magazine

How to Add Auth to Your PWA with Okta and Stencil

This article was originally published on OKTA Blog. Thank you for supporting the partners who make SitePoint possible.

Progressive Web Applications (PWAs) are the newest technology on the web dev block, and they’ve arrived just in time to solve a growing problem. Many companies are struggling to keep isolated development teams across their organization up-to-date when new features are released. Some companies are even trying to decide if it’s worth the cost to develop both a web app and a mobile application. Not surprisingly, it’s a headache most companies are looking to avoid. PWAs can give companies a lot of the features they need from a mobile app without the need to manage multiple teams and codebases.

A PWA performs spectacularly when on a fast connection, and still performs well when offline or on Wi-Fi that’s not really fast enough to be called Wi-Fi (sometimes called “Lie-Fi”). It does so via caching and a JavaScript “Service Worker” that intercepts server calls and tries to serve the data from cache first, then when the server finally responds, it will replace the cached data with possibly “fresher” data from the server.

Recently, the Ionic team released a new project called Stencil. Stencil is a compiler that generates standards-compliant web components. Unlike most JavaScript frameworks, it doesn’t deliver a “framework” of code to the browser. It simply takes the code you write and uses its compiler to create vanilla components. You can also use Stencil’s compiler with your favorite framework. The Stencil starter project is the easiest way to get started with Stencil and produces a base application that scores nearly a 100% score on Lighthouse’s progressive web app scorecard.

To get started building a PWA using Stencil, clone the starter application and detach it from the GitHub remote.

WARNING: Stencil is not at a 1.0 release yet (as of this writing). So be aware that if you continue, you’re in early-adopter territory. If you find bugs, submit an issue.

Set Up the Starter Application

git clone https://github.com/ionic-team/stencil-starter.git first-stencil
cd first-stencil
git remote rm origin

Then, install all the dependencies that your new Stencil app will need.

npm install

You may see a couple of warnings from node-pre-gyp around fsevents. There’s nothing to see here. This is just to get around a nasty little npm bug.

Next, add the Okta Auth SDK (via CDN) to the bottom of the index.html page, right before the closing </body> tag.

<script src="https://ok1static.oktacdn.com/assets/js/sdk/okta-auth-js/1.8.0/okta-auth-js.min.js" type="text/javascript"></script>

While there is an npm package for Okta’s Auth SDK, Stencil has a hard time compiling it. Overall it works better for now if you just use the CDN to include it.

If you’re like me, the next thing you’ll want to do is run npm start and check the site with Lighthouse. If you do, you’ll notice that the score is kind of low. In particular, it doesn’t register a service worker or return a 200 when offline. That’s because it’s a development build, and generally, you don’t want the service worker intercepting server calls and returning cached data in development.

To ensure an accurate depiction of the kind of PWA you get out of the box with Stencil, make sure to run a production build using npm run build. Once you do, you’ll see a www folder and inside that folder, you’ll see a sw.js file. That’s your service worker!

Set Up Your Okta Application

If you haven’t already done so, create a free-forever developer account.

Once you’ve registered, click on Applications in the top menu. Then click Add Application.

Application Listing Screen

You will then be taken to the application creation wizard. Choose Single-Page App and click Next at the bottom.

Create Application Screen SPA

On the next screen, you’ll see the default settings provided by the single-page application template. Change the name of the application to something more descriptive, like “Stencil SPA”. Also, change the base URIs and the login redirect URIs settings to use port 3333 because that’s where your application will be running. The rest of the default settings are fine.

Application Settings Screen

Click Done at the bottom.

Select your newly created application from the listing, and click on the General tab to view the general settings.

General Settings Client Id

At the bottom, you’ll see a Client ID setting (yours won’t be blurred out, obviously). Copy this to use in your Stencil application. You will also need your Okta organization URL, which you can find at the top right of the dashboard page. It will probably look something like “https://dev-XXXXXX.oktapreview.com”.

Add the Authentication Component

In the components folder, add a new folder called app-auth. This is where your login page component will go. You can call it whatever you want, I’m just following the naming conventions set out by the starter app here. I’d definitely recommend deciding on a naming convention early and sticking with it.

Inside the newly created app-auth folder create two files: app-auth.css and app-auth.tsx. Start by creating the shell of the app-auth.tsx file.

import { Component } from '@stencil/core';

@Component({
  tag: 'app-auth',
  styleUrl: 'app-auth.css'
})
export class AppAuth {
  render() {
    return <div>Hello</div>;
  }
}

If you are like I was, you might be thinking, “What kind of Frankenstein framework is this?”

You’ll notice the @Component decorator over the AppAuth class declaration like Angular, and then a render() method at the bottom like React. To me, that’s the beauty of Stencil. It takes some of the best parts of both popular frameworks and uses them to compile reusable components!

Add a Login Form

Next, you’ll add the JSX (that’s right, I said it) to the new component. Change the render() method to:

render() {
  return (
    <form class="app-auth">
      <div class="form-item">
        <label>
          Username:
          <input type="text" name="username" autocomplete="username" />
        </label>
      </div>
      <div class="form-item">
        <label>
          Password:
          <input
            type="password"
            name="password"
            autocomplete="current-password"
          />
        </label>
      </div>
      <div class="form-actions">
        <button type="button" onClick={() => this.login()}>
          Login
        </button>
      </div>
    </form>
  );
}

This is just a regular JSX form, but the login button’s onClick event is currently wired to function that doesn’t exist.

Add the Login Method’s Dependencies

Before you create that function, you’ll need to set up the OktaAuth JavaScript object to call the Okta API for authentication. You’ll add the object to the component’s state, so right below the class declaration, add the following line:

@State() authClient: any;

You will also have to import the @State() decorator. This is is used for values related to the internal state of the component. In the first import statement add State to the deconstruction list.

import { Component, State } from '@stencil/core'

You’ll also need to get the username and password values from the form itself, so add an @Element() to the code right below that @State() like you just created, so it read like this:

@State() authClient: any;
@Element() host: HTMLElement;

Then also add the @Element() decorator to the import so it reads:

import { Component, State, Element } from '@stencil/core';

One last thing that the login() function will need is access to the router, so you can redirect the user to their profile page if their authentication is successful. You’ll need a class property, so add it right below the @Element.

@State() authClient: any;
@Element() host: HTMLElement;
@Prop() history: RouterHistory;

To import it, add the @Prop() decorator to the main import and then import the RouterHistory from @stencil/router right below the core import statement. The @Prop decorator is used to define properties that can be passed in to your component. In this case, it’s not a passed in value, but it could be if need be. Your final import section should read:

import { Component, Prop, State, Element, Listen } from '@stencil/core';
import { RouterHistory } from '@stencil/router';

Finally, to use the OktaAuth JavaScript library you brought in from the CDN, add a declaration for it right below the import statements.

declare const OktaAuth: any;

Add the Login Method

Now you included everything you’ll need to get the login function to authenticate users with your Okta organization. First, set up the OktaAuth object in the constructor of the AppAuth class. Right below the property for the RouterHistory object, add:

constructor() {
  this.authClient = new OktaAuth({
    clientId: '{yourClientId}',
    url: 'https://{yourOktaDomain}.com',
    issuer: 'default'
  });
}

You can get your Client ID from that general settings page of your Okta application.

The post How to Add Auth to Your PWA with Okta and Stencil appeared first on SitePoint.


Source: Sitepoint

Building DApps with Ethereum: Creating, Deploying TNS Tokens

In part 1 of this tutorial series on building DApps with Ethereum, we bootstrapped two versions of a local blockchain for development: a Ganache version, and a full private PoA version.

In this part, we’ll dive right into it and build and deploy our TNS token — the token users will use to vote on proposals in the Story DAO.

Prerequisites

Have a Ganache version up and running, as per the previous part. Alternatively, have any local version of a blockchain running if you’re not following along from the first part, but make sure you can connect to it with tools we’ll need.

We’ll assume you have a working private blockchain and the ability to type commands into its console and the operating system’s terminal via the Terminal app or, on Windows, an app like Git Bash, Console, CMD Prompt, Powershell, etc.

The Basic Dependencies

To develop our application, we can use one of several frameworks and starter kits at our disposal: Dapp, eth-utils, Populus, Embark … and so on. But we’ll go with the current king of the ecosystem, Truffle.

Install it with the following:

npm install -g truffle

This will make the truffle command available everywhere. Now we can start the project with truffle init.

Starting the Token

Let’s get right into it and build our token. It’ll be a somewhat standard cookie-cutter ERC20 token with a twist. (You’ll see which twist lower in this post.) First, we’ll pull in some dependencies. The OpenZeppelin libraries are battle-tested high quality solidity contracts usable for extending and building contracts from.

npm install openzeppelin-solidity

Next, let’s create a new token file:

truffle create contract TNSToken

The default template that truffle generates here is a little out of date, so let’s get it updated:

pragma solidity ^0.4.24;

contract TNStoken {
    constructor() public {

    }
}

Up until now, the constructor of the token contract was supposed to be called the same as the contract itself, but for clarity it was changed to constructor. It should also always have a modifier telling the compiler who is allowed to deploy and interact with this contract (public meaning everyone).

SafeMath

The only Zeppelin contract we’ll be using in this case is their SafeMath contract. In Solidity, we import contracts with the import keyword, while the compiler will generally not require a full path, only a relative one, like so:

pragma solidity ^0.4.24;

import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";

contract TNStoken {
    using SafeMath for uint256;
    constructor() public {

    }
}

So, what is SafeMath? Long ago, there was an issue of 184 billion bitcoins being created because of a math problem in code. To prevent issues even remotely similar to these (not that this one in particular is possible in Ethereum), the SafeMath library exists. When two numbers are of the MAX_INT size (i.e. the maximum possible number in an operating system), summing them up would make the value “wrap around” to zero, like a car’s odometer being reset to 0 after reaching 999999 kilometers. So the SafeMath library has functions like these:

/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
  c = a + b;
  assert(c >= a);
  return c;
}

This function prevents this issue: it checks whether the sum of two numbers is still bigger than each of the two operands.

While it’s not too easy to make such silly mistakes when writing Solidity contracts, it’s still better to be safe than sorry.

By using SafeMath for uint256, we replace the standard uint256 numbers in Solidity (256bit unsigned — a.k.a. positive-only — whole numbers) with these “safe” versions. Instead of summing numbers like this: sum = someBigNumber + someBiggerNumber, we’ll be summing them like this: sum = someBigNumber.add(someBiggerNumber), thereby being safe in our calculations.

ERC20 from Scratch

With our math made safe, we can create our token.

ERC20 is a standard with a well-defined interface, so for reference, let’s add it into the contract. Read about the token standards here.

So the functions that an ERC20 token should have are:

pragma solidity ^0.4.24;

import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";

contract ERC20 {
    function totalSupply() public view returns (uint256);
    function balanceOf(address who) public view returns (uint256);
    function transfer(address to, uint256 value) public returns (bool);
    event Transfer(address indexed from, address indexed to, uint256 value);
    function allowance(address owner, address spender) public view returns (uint256);
    function transferFrom(address from, address to, uint256 value) public returns (bool);
    function approve(address spender, uint256 value) public returns (bool);
    event Approval(address indexed owner, address indexed spender, uint256 value);
}

contract TNStoken {

    using SafeMath for uint256;

    constructor() public {

    }
}

This might seem complex, but it’s actually very simple. This is a “directory” of functions our token needs to have, and we’ll build them one by one, explaining what each of them means. Consider the above an interface for our token. We’ll see how and why this is useful when we create the Story DAO application.

Basic balances

Let’s start. A token is actually just a “spreadsheet” in the Ethereum blockchain, like this:

| Name | Amount |
|:--|:--|
| Bruno | 4000 |
| Joe | 5000 |
| Anne | 0 |
| Mike | 300 |

So let’s create a mapping, which is essentially exactly like a spreadsheet in the contract:

mapping(address => uint256) balances;

According to the interface above, this needs to be accompanied by a balanceOf function, which can read this table:

function balanceOf(address _owner) public view returns (uint256) {
    return balances[_owner];
}

The function balanceOf accepts one argument: _owner is public (can be used by anyone), is a view function (meaning it’s free to use — does not require a transaction), and returns a uint256 number, the balance of the owner of the address sent in. Everyone’s balance of tokens is publicly readable.

Total supply

Knowing the total supply of the token is important for its users and for coin tracking applications, so let’s define a contract property (variable) to track this and another free function through which to read this:

uint256 totalSupply_;
function totalSupply() public view returns (uint256) {
    return totalSupply_;
}

The post Building DApps with Ethereum: Creating, Deploying TNS Tokens appeared first on SitePoint.


Source: Sitepoint

Better Collaboration By Bringing Designers Into The Code Review Process

Better Collaboration By Bringing Designers Into The Code Review Process

Better Collaboration By Bringing Designers Into The Code Review Process

Ida Aalen

2018-07-10T13:50:26+02:00
2018-07-10T14:35:58+00:00

Smooth collaboration between developers and designers is something everyone aspires to, but it’s notoriously difficult. But with today’s advanced web, it’s difficult — if not impossible — to build a truly great product without collaborating across disciplines. Because of the range of technologies required to build a product, the product can only truly succeed when all disciplines — developers and designers, content creators, and user experience strategists — are deeply involved from the early stages of the project. When this happens, all ends of what it takes to build a product come naturally together into a unified whole, and a thus great product.

Because of this, no one is really promoting waterfall processes anymore. Nevertheless, involving other people early on, especially people from other disciplines, can feel scary. In the worst case scenario, it leads to “design by committee.”

Moreover, both designers and content strategists often have backgrounds in fields in which a sole creative genius is still the ideal. Having someone else proof your work can feel like a threat to your creativity.

So how can you involve people early on so that you’re avoiding the waterfall, but also making sure that you’re not setting yourself up for design by committee? I found my answer when learning about code reviews.

The Aha! Moment

In July 2017, I founded Confrere together with two developers, and we quickly hired our first engineer (I’m not a developer myself, I’m more of a UX or content designer). Our collaboration was running surprisingly smoothly, so much so that at our retrospectives, the recurring theme was that we all felt that we were “doing it right.”


Three people are smiling and sitting next to each other around a computer. From left to right, they are Dag-Inge (CTO), Ida (CPO) and Ingvild (Sr. Engineer).
Dag-Inge (CTO), myself (CPO) and Ingvild (Sr. Engineer). (Large preview)

I sat down with my colleagues to try to pinpoint what exactly it was that we were “doing right” so that we could try to preserve that feeling even as our company grew and our team expanded. We came to the realization that we all appreciated that the whole team was involved early on and that we were being honest and clear in our feedback to each other. Our CTO Dag-Inge added: “It works because we’re doing it as peers. You’re not being berated and just getting a list of faults”.

The word “peer” is what gave me the aha moment. I realized that those of us working within UX, design, and content have a lot to learn from developers when it comes to collaboration.

Peer reviewing in the form of code reviews is essential to how software gets built. To me, code reviews offer inspiration for improving collaboration within our own fields, but also a model for collaborating across fields and disciplines.

If you’re already familiar with code reviews, feel free to skip the next section.

What Is A Code Review?

A code review can be done in various ways. Today, the most typical form of code review happens in the way of so-called pull requests (using a technology called git). As illustrated below, the pull requests let other people on the team know that a developer has completed code that they wish to merge with the main code base. It also allows the team to review the code: they give feedback on the code before it gets merged, in case it needs improvement.

Pull requests have clearly defined roles: there is an author and a reviewer(s).


Ingvild and Dag-Inge is setting next to each other and smiling. An arrow indicated that Ingvild has sent code to Dag-Inge.
Ingvild (the author) requests a review from Dag-Inge (the reviewer). (Large preview)

As an example, let’s say our senior engineer Ingvild has made a change to Confrere’s sign-up flow. Before it is merged into the main code base and gets shipped, she (the author) creates a pull request to request a review from our CTO Dag-Inge (the reviewer). He won’t make any changes to her code, only add his comments.


Ingvild and Dag-Inge is setting next to each other. An arrow indicates that Dag-Inge has sent comments on code back to Ingvild.
Dag-Inge comments on Ingvild’s code. (Large preview)

It’s up to Ingvild how she wants to act on the feedback she received in the review. She’ll update her pull request with the changes she sees fit.


Ingvild and Dag-Inge are sitting next to each other. An arrow indicates that Ingvild is sending back her code to Dag-Inge, having looked through the code he commented on.
Ingvild updates her code with the changes she sees fit in light of Dag-Inge’s comments. (Large preview)

When the reviewer(s) approve the pull request, Ingvild can then merge her changes with the main code base.


Ingvild and Dag-Inge are sitting next to each other. A thumbs-up is displayed on the code review Dag-Inge has sent to Ingvild. And arrow indicates she pushes this code to the main repository.
After Dag-Inge gives the thumbs up, Ingvild can push the fix to production. (Large preview)

Why Bother Doing Code Review?

If you’ve never done code review, the process above might sound bureaucratic. If you have doubts, here’s a ton of blog posts and academic research about the advantages of code review.

Code reviews set the tone for the entire company that everything we do should be open to scrutiny from others, and that such scrutiny should be a welcome part of your workflow rather than viewed as threatening.

Bruce Johnson, co-founder of Full Story

Code review reduces risk. Having someone proof your work, and also knowing someone will proof your work, helps weed out
 errors and
 heightens quality. In addition, it ensures consistency and helps every team member familiarize with more of the code base.

When done right, code review also builds a culture for collaboration and openness. Trying to understand and critique other people’s work is an excellent way to learn, and so is getting honest feedback on your work.

Always having at least two people look over the code also curtails ideas of “my” code 
and “your” code.
 It’s our code.

Considering these advantages, a review shouldn’t just be for code.

Review Principles For All Disciplines, Not Just Code

With reviews, there is always one author and one or more reviewers. That means you can involve people early on without falling into design by committee.

First, I have to mention two important factors which will affect your team’s ability to do beneficial reviews. You don’t necessarily have to have mastered them, but as a minimum, you should aspire to the following:

  • You and your colleagues respect each other and each other’s disciplines.
  • You’re sufficiently self-assured in your own role so that you feel like you can both give and receive criticism (this is also connected to the team’s psychological safety).

Even if we’re not reviewing code, there’s a lot to learn from existing best practices for code reviews.

Within our team, we try to adhere to the following principles when doing reviews:

  1. Critique the work, 
not the author.
  2. Be critical, but remain 
affable and curious.
  3. Differentiate between a) Suggestions b) Requirements, c) Points that need discussion or clarification.
  4. Move discussions from
 text to face-to-face. (Video counts)
  5. Don’t forget to 
praise the good parts! What’s clever, creative, solid, original, funny, nice, and so on?

These principles weren’t actually written down until after we discussed why our collaboration was working so well. We all felt we were allowed to and expected to ask questions and suggest improvements already, and that our motivations were always about building something great together, and not about criticising another person.

Because we were being clear about what kind of feedback we were giving, and also remembered to praise each other’s good work, doing reviews was a positive force rather than a demotivating one.

An Example

To give you an idea of how our team uses review across disciplines and throughout a process, let’s look at how the different members of our team switched between the roles of author and reviewer when we created our sign-up flow.

Step 1: Requirements gathering

Author: Ida (UX)

Reviewers: Svein (strategy), Dag-Inge (engineering), Ingvild (engineering).


A whiteboard is showing rough sketches of a sign-up form. A man (Svein) and a woman (Ingvild) are smiling and discussing.
The team gathered around the whiteboard. Svein (CEO) to the left, Ingvild (Sr. Eng), to the right. (Large preview)

Whiteboard sessions can be exhausting if there’s no structure to them. To maintain productivity and creativity, we use the author/reviewer structure, even for something as seemingly basic as brainstorming on a whiteboard. In this case, in which we were coming up with the requirements for our sign-up flow, I got to be the author, and the rest of the team gave their feedback and acted as reviewers. Because they also knew they’d be able to review what I came up with in step 2 (plenty more opportunity for adjustments, suggestions, and improvements), we worked swiftly and were able to agree upon the requirements in under 2 hours.

Step 2: Mockup with microcopy

Author: Ida (UX)

Reviewers: Ingvild (engineering), Eivind (design), Svein (strategy).


A screenshot of a Google Doc mocking up a sign-up form with comments from team members Ingvild and Ida.
By mocking up in Google docs, it’s easy for people from all disciplines to provide feedback early on. (Large preview)

As an author, I created a mockup of the sign-up flow with microcopy. Did the sign-up flow make sense, from both the user and engineering perspective? And how could we improve the flow from a design and frontend perspective? At this stage, it was essential to work in a format in which it would be easy for all disciplines to give feedback (we opted for Google Docs, but it could also have been done with a tool like InvisionApp).

Step 3: Implementing the sign-up flow

Author: Ingvild (engineering)

Reviewer: Ida (UX) and Dag-Inge (engineering).

We had agreed upon the flow, the input fields, and the microcopy, and so it was up to Ingvild to implement it. Thanks to Surge, we can automatically create preview URLs of the changes so that people who can’t read code are able to give feedback at this stage as well.

Step 4: User testing

Author: Ida (UX)

Reviewer: The users.


Two women (Ida and a user) sitting next to eachother in front of a laptop.
Ida doing user testing on a small budget. (Large preview)

Yes, we consider user testing a form of review. We brought our newly built sign-up flow face-to-face with actual users. This step gave us a ton of insight, and the most significant changes in our sign-up flow came as a result.

Step 5: Design

Author: Eivind (design)

Reviewers: Ingvild (engineering) and Ida (UX).


A screenshot from Slack. Eivind, the designer, has posted a screenshot, and Ida replies with enthusiasm.
The first version of the sign-up flow was based on existing design components. In this stage, Eivind developed some new components to help improve the design. (Large preview)

When design suddenly shows up here in step 5, it might look a lot like a waterfall process. However, our designer Eivind had already been involved as a reviewer since step 2. He gave a bunch of useful feedback at that stage and was also able to start thinking about how we could improve the design of the sign-up flow beyond the existing modules in our design system. At this step, Eivind could also help solve some of the issues that we identified in the user testing.

Step 6: Implementation

Author: Ingvild (engineering)

Reviewer: Eivind (design), Ida (UX) and Dag-Inge (engineering).

And then we’re back to implementing.

Why review works

In summary, there’s always just one author, thus avoiding design by committee. By involving a range of disciplines as reviewers early on, we avoid having a waterfall process.

People can flag their concerns early and also start thinking about how they can contribute later on. The clearly defined roles keep the process on track.

Regular Review Walkthroughs

Taking inspiration from code walkthroughs, we also do regular review walkthroughs with different foci, guided by the following principles:

  • The walkthrough is done together.
  • One person is in charge of reviewing and documenting.
  • The idea is to identify issues, not necessarily to solve them.
  • Choose a format that gives as much context as possible, so that it’s easy to act upon the findings later (e.g. InvisionApp for visual reviews, Google Docs for text, and so on).

We’ve done review walkthroughs for things such as accessibility audits, reviewing feature requests, auditing the implementation of the design, and doing heuristic usability evaluations.

When we do our quarterly accessibility reviews, our accessibility consultant Joakim first goes through the interface and documents and prioritizes the issues he’s found in a shared Google Sheet. Joakim then walks us through the most important issues he’s identified.

Meeting face-to-face (or at least on video) to go through the issues helps create an environment for learning rather than a feeling of being supervised or micromanaged.


Three people in a sofa gathered around a laptop. They’re discussing and smiling.
Accessibility review: Joakim (right) walks Ingvild and Dag-Inge through the accessibility issues he found in his audit. (Large preview)

If you find yourself always being tied up with something that’s due for release, or fixing whatever is at the top of your inbox, reviews can help remedy that. If you set aside regular half days for reviewing work you’ve already done, you can identify issues before they become urgent. It can also help you refocus and make sure you’re priorities are keeping along the right lines. Your team should maybe not begin building that new feature before you’re confident that the existing features are living up to your standards.

User Testing Is A Form Of Review

An important motivation for code reviews is to reduce risk. By doing it every single time you introduce a change or add something new to your product, and not just when you suspect something is maybe not up to par, you diminish the chance of shipping bugs or subpar features. I believe we should look at user testing from the same perspective.

You see, if you want to reduce the risk of shipping with major usability issues, user testing has to be part of your process. Just having your UX designers review the interface isn’t enough. Several studies have found that even usability experts fail in identifying every actual usability problems. On average, 1 in 3 issues identified by experts were false alarms — they weren’t issues for users in practice. But worse, 1 in 2 issues that users did in fact have, were overlooked by the experts.

Skipping user testing is just as big a risk as skipping code review.

Does Review Mean Death To Creativity?

People working within design, user experience, and content often have educational backgrounds from art schools or maybe literature, in which the sole creator or creative artistic genius is hailed as the ideal. If you go back in history, this used to be the case for developers as well. Over time, this has changed by necessity as web development has grown more complex.

If you cling to the idea of creativity coming from somewhere deep within yourself, the idea of review might feel threatening or scary. Someone meddling in your half-finished work? Ouch. But if you think about creativity as something that can spring from many sources, including dialogue, collaboration, or any form of inspiration (whether from the outside or from someplace within you), then a review is only an asset and an opportunity.

As long as we’re building something for the web, there’s no way around collaborating with other people, be it within our own field or others. And a good idea will survive review.

Let’s create something great together.

Smashing Editorial
(rb, ra, yk, il)


Source: Smashing Magazine

29 Awesome Tools for Web Designers & Developers

This article was created in partnership with Mekanism. Thank you for supporting the partners who make SitePoint possible.

We’re always on the lookout for the best web tools and services available for designers and developers. Which resources should we be using? Most customers don’t need a website built from scratch — only customizations are necessary for many to find a perfect fit for their projects. That’s why you can easily use the ListingPro WordPress directory theme to build business directory websites or Brizy, or other website builders we have included in the showcase. Using these resources will help you stay competitive in terms of pricing and project delivery dates.

Web designers and developers told us what they are using in their projects to get things done faster and better. Here are 29 solutions that work.

1. ListingPro: The #1 WordPress Directory Theme

ListingPro: The #1 WordPress Directory Theme

ListingPro is the world’s #1 best-selling end-to-end WordPress directory solution. It’s the only theme that includes all the core directory features, and no paid plugins are required. This makes it super easy to build an online directory and start monetizing from day one. All for a fraction of the cost, with no coding knowledge required.

Whether you want to build a directory like Yelp, the Yellow Pages, Zomato, Foursquare or even Justdial, ListingPro is the best directory listing software for all kinds of business directory use-cases, including:

  • Restaurants directories, like Yelp, Zomato or Foursquare
  • Local search business directories, like Yellow Pages and Justdial
  • Medical directories, like ZocDoc
  • Tour & travel review directories, like TripAdvisor
  • Hotel directories, like Airbnb
  • Software review sites, like Capterra

The core value proposition for ListingPro is simple: no paid plugins needed for all the core directory features. For more info on all the features, visit ListingPro’s official website.

2. Userfeel.com: Test Any Website or Mobile App‎

Userfeel

Userfeel is the usability testing tool that gives you videos of real users speaking their thoughts as they use your website or app. It is designed and developed by usability researchers, for usability researchers, but also for newcomers to UX research and anyone who wants to optimize their website or app.

Something that traditionally was difficult, costly and time-consuming, now is put at your disposal for an affordable cost. Every web designer, after they build their website with WordPress, should run a usability test to see whether the website is sending the right message and whether it’s easy to use.

Userfeel is offering the option to become a tester for the service, and earn $10 per test. Each test lasts 10-20 minutes, and you can do it from your home computer or smartphone.

Start testing your website for yourself or for your customers.

3. DealJumbo – Discounted Design Bundles

DealJumbo - Discounted Design Bundles

Dealjumbo brings you exclusive deals from the best web and graphic designers, writers, and artists from all over the world. The website was launched in 2013 and it was one of the first graphic design deal websites on the market, with excellent reviews in the industry.

You can download 1580+ free fonts and graphics. All come with a standard commercial license.

Check the website — it is packed with tons of items and design bundles with huge discounts.

4. Brizy – Create WordPress Pages Quickly

Brizy - Create WordPress Pages Quickly

Brizy is the friendliest and most complete WordPress page builder on the market, allowing users to build pages visually. Designers will find a huge collection of more than 4,000 icons at their disposal. There’s no need to have any coding skills.

As for developers, it comes with 150 pre-made design blocks. You can start from scratch and build anything you want, but if that is a little intimidating you can use the pre-made blocks to start your design. Developers can create a page on Brizy’s website and save the HTML for free, and use it anywhere they like in personal or commercial projects.

Brizy is a WordPress plugin and free to use. A Pro version is in the works with a presale lifetime deal available on its website.

5. Deeezy.com – Freebies for Web Designers

Deeezy

Deeezy is a brand new website offering awesome free and premium fonts and graphic design items. You will find 237 exclusive freebies and premium items offered with an extended license – for an unlimited number of commercial projects, or for your digital or physical items for sale.

You can subscribe for free and the premium plans start from $9 per month.

6. actiTIME

actiTIME

actiTIME is a powerful and popular time tracking app used by thousands of companies around the world. With its flexible configuration, actiTIME fits companies from many industries: IT, design, architecture, engineering and others.

Using actiTIME, you can easily manage project scope, assign tasks, track time and analyze your project performance based on the collected data. Everybody can benefit from using it day-to-day: employees, team managers and business owners.

7. Notism — Design & Video Collaboration for Teams

Notism — Design & Video Collaboration for Teams

Notism is an excellent design and video collaboration tool for creative teams making creative content review more effective. Yes, Notism also supports video collaboration. Finally, you can review and collaborate on your motion design work by adding notes, sketches or selections to the video timeline.

Sometimes it makes more sense to sketch directly on the work rather than adding notes. Notism offers several tools to draw on your uploaded content: a pencil, rectangle, and circle. You can also choose a line type, width or add a splashing color.

8. Goodie Website

Goodie Website

Goodie is a powerful web development service that allows you to have your website designed and coded by professionals from only $999. Everybody is looking to receive top quality for a reasonable price and this is what you will receive from this team of professionals. Goodie’s approach to help you is different: it hires only experienced web developers and lets them cooperate directly with you.

The post 29 Awesome Tools for Web Designers & Developers appeared first on SitePoint.


Source: Sitepoint

Pattern Library First: An Approach For Managing CSS

Pattern Library First: An Approach For Managing CSS

Pattern Library First: An Approach For Managing CSS

Rachel Andrew

2018-07-09T14:00:35+02:00
2018-07-10T14:35:58+00:00

In this article, based on the talk that I gave at Smashing Conference in Toronto, I’m going to describe a method of working that I’ve adopted over the past two years that helps me to manage CSS across my projects.

I’ll be showing you how to use the pattern library tool Fractal, to manage your CSS on a component by component basis, while allowing you to use the tools you are already familiar with. While this serves as an introduction to Fractal, and why we have selected this particular pattern library, it is likely this way of working would transfer to other solutions.

Our Projects

My company has a couple of products — Perch and Perch Runway CMS and Notist, a software as a service application for public speakers. These products are quite different, especially given that Perch is a self-hosted system and Notist is SaaS, however, they both have a lot of user interface to develop. We also have all of the associated websites and documentation for these products, plus other things that we work on such as the 24 Ways website. After discovering Fractal two years ago, we have moved every new project — large and small — into Fractal.

Problems we wanted to solve

I began investigating pattern library solutions two years ago when I started work rebuilding the Perch UI for version 3. A feature of Perch is that the templates you create for the output of content on your website become the schema of the admin UI. This means that any fieldtype used in a template needs to be able to exist alongside any other fieldtype. We don’t know how our customers might combine these, and there are a huge number of possible combinations. It’s also not a “website”, and I didn’t want to try and force the pattern library into something designed for organizing website patterns.

As Perch is self-hosted — people download it and host it on their own servers — we need to use the simplest tech stack possible in order to not place any additional barriers to entry in front of people, many of who are new to using a CMS. To add an extra level of fun, we support back to Internet Explorer 9, yet I intended to use a lot of Flexbox — as this was before Grid Layout shipped.

I was also keen to avoid using tools which came with a lot of relearning how we worked, and completely changing our process. Any additional tool or change to the way that you work on your projects brings with it new friction. You can solve one problem, but bring in a whole new set of problems if you make large changes to the way that you work. In our case, we were using Sass in a fairly limited way, and processing that using Gulp. None of our projects use a Javascript framework, we’re just writing HTML, CSS and JavaScript.

Fractal fit our needs perfectly. It is agnostic as to the way you develop or the tools you want to use. Importantly for our purposes, it didn’t assume we were building a website. The experiment was so successful that we found ourselves using Fractal for every project large or small, as it makes the process of working on CSS far more straightforward. Even small sites I create on my own often start life in Fractal, because there are more benefits than you might think in terms of working with a pattern library, and many of those benefits make as much sense for a team of one as a large team.

Before we think about how to develop using Fractal and why I think it makes sense for small projects as well as large ones, let’s take a look at how to get the environment set up.

Getting Started With Fractal

The most straightforward approach for working with Fractal is to go to the Fractal website and take a look at the Getting Started Guide. You will first need to install Fractal globally, you can then follow the steps listed here to create a new Fractal project.

With your new project installed, at the command line change into the folder you have just created and run the command:

fractal start --sync

This will start up a little server at port 3000, so you should be able to go to http://localhost:3000 in a web browser and see your project.

Now that your project is up and running, open up the project folder in your favorite text editor and find the example component under components/example. You will find a config file and a file named example.hbs. The example.hbs template is the HTML of your component, you can add some more HTML to that and Fractal will automatically reload and display it. Change the file to:

<h1>This is my heading</h1>
<p>{{ text }}</p>

You should see the heading appear in the browser. The config file can be used to add content and otherwise configure your component. If you want to read your heading text out of that file then edit that file to look like the following example:

title: Example component
context:
    text: This is an example component!
    heading: My heading

Now change your example.hbs file to read in that text.

<h1>{{ heading }}</h1>
<p>{{ text }}</p>
Adding Additional Components

You can follow the pattern of the example component to add your own. At a minimum, you need a folder (the name of the component) and a .hbs file using the same name. You can add the config file if you want to set configuration options.

Components can be nested into folders to make it easier to locate particular components, and how you structure the folders is completely up to you.

Note: It is really easy to find yourself spending a lot of time worrying about how to name your components. In Fractal at least, renaming and also reorganizing components into folders is straightforward. You can rename or move them and Fractal will update to show the new structure. I find that often the ideal structure only becomes apparent as I’m developing so I don’t worry too much at the outset and then firm it up later.

Adding a CSS Workflow

So far, we are able to create HTML components as handlebars templates, and a config file to insert data, however, we haven’t added any CSS. Ideally, we want to add the CSS for each component into the same folder as the rest of the component files and then combine it all together.

I mentioned that Fractal makes very few assumptions about your workflow; due to this, it does far less out of the box than it might if it were forcing you down a particular way of working. However, we can fairly easily get Fractal working with a Gulp setup.

Combining Fractal, Sass, And Gulp

The following describes a minimal setup using Gulp and Sass to create a single output CSS file. Hopefully, you can follow this process to do anything else that you would normally do in Gulp. The key thing to note is that most of this is not Fractal specific, so once you get the Fractal part working you can add in anything else following the same patterns. If you are familiar with another build tool then it is likely that you could create a similar process; if you do, and are happy to share, let us know in the comments.

First some setup, the following will enable you to follow along with the code listed in this tutorial, the locations of your Sass files and output CSS might ultimately be different to mine. The key thing is that the output CSS file needs to be somewhere in the public folder.

  1. Inside the public folder in your Fractal install, add a folder named css.
  2. In the root folder of your Fractal, install add a folder assets inside which is a folder scss. Create a Sass file named global.scss inside that folder. Inside that file add the following line:
    @import "../../components/**/*.scss";
  3. Create a file named example.scss in your example component directory.
  4. Create gulpfile.js in the root of your Fractal project and add the below code.
'use strict';

const gulp         = require('gulp');
const fractal      = require('./fractal.js');
const logger       = fractal.cli.console;
const sass         = require('gulp-sass');
const sassGlob     = require('gulp-sass-glob');
const plumber      = require('gulp-plumber');
const notify       = require('gulp-notify');
const path         = require('path');

gulp.task('sass',function() {
    return gulp.src('assets/scss/**/*.scss')
    .pipe(customPlumber('Error running Sass'))
    .pipe(sassGlob())
    .pipe(sass())
    .pipe(gulp.dest('public/css'))
});

gulp.task('watch', ['sass'], function() {
   gulp.watch([
        'components/**/*.scss',
        'assets/scss/**/*.scss'
        ], ['sass']);
});

function customPlumber(errTitle) {
    return plumber({
        errorHandler: notify.onError({
            title: errTitle || "Error running Gulp",
            message: "Error: ",
        })
    });
}

gulp.task('fractal:start', function(){
    const server = fractal.web.server({
        sync: true
    });
    server.on('error', err => logger.error(err.message));
    return server.start().then(() => {
        logger.success(`Fractal server is now running at ${server.url}`);
    });
});

gulp.task('default', ['fractal:start', 'sass', 'watch']);

I then install the dependencies listed at the top of the file. If you were to install those at the command line you would run:

npm install gulp gulp-sass gulp-sass-glob gulp-plumber gulp-notify

The sass function compiles the Sass from assets into a single file, and outputs it into the folder in public.

gulp.task('sass',function() {
return gulp.src('src/assets/scss/**/*.scss')
.pipe(customPlumber('Error running Sass'))
.pipe(sassGlob())
.pipe(sass())
.pipe(gulp.dest('public/css'))
});

I then create a watch function that will watch my Sass in assets and also that in individual components and compile it into the folder in public.

gulp.task('watch', ['sass'], function() {
   gulp.watch([
'components/**/*.scss',
'assets/scss/**/*.scss'
], ['sass']);
});

That’s my CSS building. I now want to make it so that I can run gulp and it will kick off the watching of the CSS file as well as starting fractal. I do this by creating a gulp task to run the fractal start command.

gulp.task('fractal:start', function(){
const server = fractal.web.server({
sync: true
});
server.on('error', err => logger.error(err.message));
return server.start().then(() => {
logger.success(Fractal server is now running at ${server.url});
});
});

Finally, I need to ensure that the Sass building and Fractal start run when I run gulp and the command line:

gulp.task('default', 'fractal:start', 'sass', 'watch');

That’s my completed gulpfile.js. If you add this into your default Fractal project, make sure the folders are in place for the paths mentioned. You should be able to go to the command line, run gulp, and Fractal will start.

Commandline output

Starting Fractal with gulp (View large version)

We can test out our Sass by adding a variable in the global.scss file; you will need to add this above the line that includes the components so that the variable is available for those components.

$color1: rebeccapurple;

Then in example.scss add a rule for the level 1 heading we added earlier:

h1 {
  color: $color1;
}

If everything is set up correctly, you should find you have a .css file in public/css which contains the rule:

h1 {
  color: rebeccapurple;
}

We need to do one more thing so that we can preview our components using the CSS we are building. We need to create a preview file, which will link in the stylesheet from the public folder.

Inside your components folder, create a file named _preview.hbs.

The preview file is essentially an HTML document, linking in our CSS and anything else you need to include. In the body is a tag {{ yield }}, and this is where a component will be placed.

<!doctype html>
<html lang="en">
<head>
	<meta charset="utf-8" />
	<title>Preview Layout</title>
	<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
	<link rel="stylesheet" href="{{ path '/css/global.css' }}">
</head>
<body>
	{{{ yield }}}
</body>
</html>

Note: The public folder can also house any other assets that you need to display in components such as images, fonts and so on.

The Pattern Library As Source Of Truth

As we have seen, Fractal can build our CSS. In our projects, we make it so that Fractal is the only place we build and process CSS and other assets for the site. What this means is that our pattern library and site or application do not drift. Drift happens after you deploy the site if people start editing the CSS of the site and not bringing those changes back to the pattern library. If you can make the pattern library the place where CSS is processed then changes have to start there — which prevents drift between the live site and library.

We build everything in Fractal and then copy those public assets over to the live sites to be deployed. In addition to preventing drift between the systems, it also makes managing CSS in source control much easier. When multiple people work on one CSS file, merge conflicts can be reasonably hard to deal with. With people working on individual components in the pattern library, you can usually avoid two people committing changes to the same file at once, and if they do it is only a small file to sort out and not all of your CSS.

Using A Pattern Library First Approach For Managing Fallbacks

I have found that working pattern library first makes dealing with fallbacks in your code far more straightforward and less overwhelming than attempting to fix up a complete site or application at once. It also allows us to concentrate on the best possible case, and be creative with new techniques, rather than limit what we do due to being worried about how we will get it to work well in non-supporting browsers.

We can look at a simple case of a media object component to see how that might work. To follow along, create a media folder inside components in Fractal, and add the files media.hbs and media.scss.

Start With Good Markup

Your starting point should always be well-structured markup. In the pattern library, it may be that you will use this component with a range of markup, for example, you could use a component with content marked up as a figure in one place and just with divs in another. Your content should, however, be structured in a way that makes sense and can be read from top to bottom.

This ensures that your content is accessible at a very basic level, but it also means you can take advantage of normal flow. Normal Flow is how browsers display your content by default, with block elements progressing one after the other in the block dimension and inline elements — such as words in a sentence — running along the inline axis. For a lot of content that is exactly what you want, and by taking advantage of normal flow rather than fighting against it you make your job far easier as you create your layout.

Therefore, my component has the following markup which I add to media.hbs.

<div class="media">

  <div class="img">
    <img src="/img/placeholder.jpg" alt="Placeholder">
  </div>
  <h2 class="title">This is my title</h2>
  <div class="content">
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis vehicula vitae ligula sit amet maximus. Nunc auctor neque ipsum, ac porttitor elit lobortis ac. Vivamus ultrices sodales tellus et aliquam. Pellentesque porta sit amet nulla vitae luctus. Praesent quis risus id dolor venenatis condimentum.</p>
  </div>
  <div class="footer">
    An optional footer goes here.
  </div>
</div>

You can see how this then displays inside Fractal.

The fractal UI with the added component

My component after adding the markup. (View large version)

Once I’ve got the markup that I want, I am going to work on the desktop display that I have in mind. I’m going to use CSS Grid Layout and the grid-template-areas method of doing so. Add the following to media.scss.

img { max-width: 100%; }

.media > .title { 
  grid-area: title; 
}

.media > .img { 
  grid-area: img; 
}

.media > .content { 
  grid-area: bd; 
}

.media > .footer { 
  grid-area: ft; 
}

.media {
  margin-bottom: 2em;
  display: grid;
  grid-column-gap: 20px;
  grid-template-columns: 200px 3fr;
  grid-template-areas:
    "img title"
    "img bd"
    "img ft";
  }

We now have a simple media object layout:

A two column layout, image on the left text on the right

The Media Object layout. (View large version)

Something you can do in Fractal is to add variations of a component. You might want to flip the media object so that the image is on the right.

Now add the CSS to media.scss in order to flip the layout:

.media.media-flip {
grid-template-columns: 3fr 200px ;
grid-template-areas:
  "title img"
  "bd img"
  "ft img";
  }

There are two ways to create variants: file-based and configuration based. File-based is simplest and is also useful if your variant has different markup. To create a file-based variant, make a copy of your component in the media folder with the name media –flip.hbs (that’s two dashes in the filename).

This component should have identical markup with the class media-flip added to the first line, and you will then be able to see both versions.

<div class="media media-flip">

A two column layout, image on the right text on the left

The flipped version. (View large version)

Alternately, as in this case all we need to do is add a class, you can create a variant using a config file.

If you want to do this, remove your variant file, and instead add a config file named media.config.json containing the following code:

{
    "title": "Media Object",
    "context": {
        "modifier": "default"
    },
    "variants": [
        {
            "name": "Flipped",
            "context": {
                "modifier": "flip"
            }
        }
    ]
}

Then modify the first line of media.hbs as follows:

<div class="media media-{{ modifier }}">

Note: You can add as many variants as you like (take a look at the documentation for variants to read more).

We might now think about adding some CSS to change the layout based on screen size. Wrapping the layout we have created in a media query and above that creating a single column layout for smaller devices.

img {
  max-width: 100%;
}

.media > .title { 
  grid-area: title; 
}

.media > .img { 
  grid-area: img; 
}

.media > .content { 
  grid-area: bd; 
}

.media > .footer { 
  grid-area: ft; 
}

.media {
  display: grid;
  grid-column-gap: 20px;
  grid-template-areas:
    "title"
    "img"
    "bd"
    "ft";
  }
  
  @media (min-width: 600px) {
    .media {
      margin-bottom: 2em;
      display: grid;
      grid-column-gap: 20px;
      grid-template-columns: 200px 3fr;
      grid-template-areas:
        "img title"
        "img bd"
        "img ft";
    }

    .media.media-flip {
      grid-template-columns: 3fr 200px ;
      grid-template-areas:
        "title img"
        "bd img"
        "ft img";
    }
}

A single column layout

The object for mobile devices. (View large version)

Then, just as we manage the view for smaller devices within our component, we can manage the layout for older browsers which do not support grid.

In this case, I’m going to build a float-based fallback (this will work for pretty much any legacy browser). I’m only going to worry about it for wider screen sizes and leave the component displaying in normal flow for older mobile devices.

Just inside the media query, add the following CSS:

.media:after {
  content: "";
  display: table;
  clear: both;
}

.media > .media {
  margin-left: 160px;
  clear: both;
}

.media .img {
  float: left;
  margin: 0 10px 0 0;
  width: 150px;
}

.media.media-flip .img {
  float: right;
  margin: 0 0 0 10px;
}

.media > * {
  margin: 0 0 0 160px;
}

.media.media-flip > * {
  margin: 0 160px 0 0;
}

This should sort out the display in non-grid browsers. For browsers that do support grid, you don’t need to worry about floats, i.e. when the floated item becomes a grid item, the float is removed. What will be a problem are any margins. The layout in grid supporting browsers will now be all spaced out due to the extra margins.

Two column layout with big gaps

The layout is spaced out due to the extra margins. (View large version)

This is where we can add a feature query, removing the margins if we know that our browser supports grid.

@supports(display: grid) {
  .media > *,
  .media.media-flip > * {
    margin: 0;
  }

  .media .img,
  .media.media-flip .img {
    width: auto;
    margin: 0;
  }
  
  .media:after {
    content: none;
  }
}

That’s our small component finished. While a simple example — and it might be argued that it’s one which doesn’t really need grid at all if you need to have a fallback — it demonstrates the approach I’m taking across all of my projects, large and small.

To get my CSS file into production, we can take the CSS file from the public folder and add that to our production site. You could even script this process to copy it over to your site folder as it builds.

Reduced Test Case First Development

Something I have discovered as a key benefit in working this way, is that it really does make the browser support piece of the puzzle easier. Not only is it easier to see what fallback CSS is being included with this component, but also if we are having problems with a browser, it makes it far easier to debug them.

When you are battling with a browser issue then the thing you will generally be told to do is create a reduced test case. Reduce the problem down to the smallest thing that exhibits the issue. A component in a pattern library is often very close to that reduced test case already. Certainly far closer than if you are trying to debug a problem while looking at your entire website.

In addition to making browser debugging easier, having your fallbacks included alongside the rest of the CSS makes it easier to remove the fallback code once it is no longer needed, it’s obvious this fallback code is for this component. I know that removing it won’t change the way anything else displays.

This ease of organizing our code is really why Fractal makes sense even in small projects. Given that we tend to use Gulp and Sass anyway (even on smaller projects), adding Fractal to the mix isn’t a big overhead. We don’t need to see it as only for our bigger projects, as even a small site might have a reasonable amount of CSS.

See The Code

I’ve created a GitHub Project which has all of the code mentioned in the article. I would suggest setting up Fractal as described in the article and then grabbing any bits – such as the gulpfile or preview layout, from my repository.

As an additional reference and to see some published Fractal projects, we have the published version of the Perch Pattern Library, and also the Pattern Library for 24 Ways (built by Paul Robert Lloyd), which you can take a look at. These are good examples of a non-website pattern library, and a more traditional one used for a site.

How Do You Manage CSS?

I really like this way of working; it allows me to write CSS in a straightforward, progressively enhanced way. Depending on the project, we may include far more tooling and processing of files. Or, I may be building a simple site in which case the setup will be pretty much as we have seen in this article — with some light processing of Sass. The fact that Fractal means we can have the same process for sites big and small, for web applications or websites. It means we can always work in a familiar way.

This works for us, and I hope this article might give you some things to experiment with. However, I would love to know the ways in which you and your team have approached managing CSS in your projects and the strengths and weaknesses of the approaches you have tried. I’d be especially interested in hearing from anyone who has developed a similar process using another pattern library solution. Add your experiences in the comments.

Smashing Editorial
(il)


Source: Smashing Magazine

Build Custom Dashboards with MongoDB, Azure & Serverless Functions

This article was originally published on Ahmad Awais. Thank you for supporting the partners who make SitePoint possible.

TL;DR: I’m building a custom WordPress dashboard for an enterprise client which is powered by React.js on top of Node.js, with MongoDB Atlas as the database.

This dashboard uses several Microsoft Azure services, e.g., Cognitive Services, Azure App Services, and especially serverless Azure Functions. In this post, you’ll learn how to build a small module from it and the reason behind my choice of stack, apps, and products.


One of my enterprise clients who owns a huge networking and media company has a large-scale WordPress site set up. He recently consulted me about the possibility of building a custom WordPress dashboard (based on the WordPress REST API) — to help him make intelligent business decisions via Machine Learning and Artificial Intelligence.

With JavaScript eating up the world and WordPress adapting to the move by creating the Gutenberg project, I thought of an architecture/stack where WordPress would be our content layer, a familiar battle-tested environment that does its job well with a custom dashboard that’s built with JavaScript.

When you’re tasked to build a modern JavaScript application, you find yourself in a mix of different frameworks, tools, and dev workflows. The JavaScript ecosystem has grown a lot over the last couple of years. We have many, many good options available today.

So, after researching my options for a bit, I opted to use React.js on top of Node.js to start building the custom WordPress dashboard. While the project is in its ideation phase at the moment, I think it’s important that I share some of our goals here to define context behind my choice of the stack.

Custom WordPress Dashboard Goals

Imagine you own a large networking company where over 500 hotels (in three different countries) use your services to power their conference halls, IT meetings, and online property management like the sites and blogs. That’s what my client does.

Most of this is powered by a huge multi-site WordPress instance that manages everything for the hotels, websites, online booking, registrations, events, tickets, reviews, and comments. There’re also other systems running different software which are able to produce content via REST API.

We’ve set out to create a custom WordPress dashboard with many goals in mind, but I’m listing a few of them which are related to this particular article. Take a look at what I have built so far, it’s all based on serverless Azure functions — which are pretty awesome.

A Custom WordPress Dashboard with MongoDB Atlas, Microsoft Azure, & Serverless Functions!

👀 High-level Data Reporting

The custom dashboard will report all the high-level data, e.g. things like live sales happening throughout my client’s portfolio (500+ hotels), entity/time-based and date-based breakdowns.

And how each of his franchise performing on a daily, weekly, monthly basis. All of this data is being fed to MongoDB Atlas. More on that later.

⚡ Serverless Automation

Most of the modules are built upon serverless architecture — which in this case provides huge benefits. All the automation is always running and the cost is paid as you go i.e. pay for what you use.

An initial rough estimate puts this solution 34% more economical than having a server VM running all the time. We are using Azure Functions for this serverless automation.

🔥 IoT (Internet of Things) Hub

There are about ~200 IT managers working for my client who have IoT enabled devices that feed data into several online projects. This custom dashboard also includes that data for making better decisions and connecting the whole registration, management, maintenance team’s hub into a single place.

As you might have already guessed, this project makes use of IoT Hub from Microsoft Azure to connect, monitor, and manage all of the IoT assets.

🤖 Machine Learning and Artificial Intelligence

We’re using a lot of different services from Microsoft Azure for the sake of making this dashboard artificially intelligent by Machine Learning.

There’s a huge dataset that is fed to the ML Studio which later helps us predict different decisions like space management, low registrations trends for IT events, and questions like why and when these things happen.

While the Machine Learning part is beyond the scope of this article, I still plan to touch base with some of the awesome Artificial Intelligence I’ve been able to cook in via Azure’s Cognitive Services.

🕰 Live & Real-time

One of the most important aspects of this custom dashboard is that it’s live and real-time. Which means I need a managed database that can cope with this amount of data and still stay highly available.

But at the same time, it’s for the management purposes and doesn’t need to have any impact on the WordPress sites. That is a crucial system design decision for this dashboard.

By that what I mean is we can do all sorts of experiments with this custom dashboard but it shouldn’t have any impact on the database/servers which are running the multi-site WordPress instance.

MongoDB & MongoDB Atlas

For this custom WordPress dashboard, I am using MongoDB Atlas as a DBaaS (Database as a Service). And I couldn’t be happier. When I first shared that I’d be using MongoDB, many developers had concerns.

Mongodb

Most of the questions asked why I’d add another layer of complexity by adding yet another database to the mix. Why not use the WordPress database as it is? To answer these questions and more I have prepared a list of reasons as to why I am using MongoDB Atlas.

♨ Dislike for RDBMS

I personally dislike relational databases. Most of the time, for me they get in the way of building applications. I have to completely get out of the app I am building, think about my database in the future and design a good schema which always ends up a bad exercise for my dev workflow. It’s counter-intuitive at best — at least for me, it is.

💸 HDD Is Cheap — CPU/RAM Is Not

Old databases were mostly designed to save disk space, among other things. This led to a plethora of problems like normalization, indexing, and made sharding, auto-scaling, and replication harder.

Nowadays, disk space is dirt cheap. On the other hand, CPU/RAM is not, and your sysadmin costs can skyrocket very quickly if you end up with a bad choice here.

Like you wanted to create a custom dashboard but your system design architect cost you two sysadmins with how they chose to design your system. Similarly, my client wanted a managed solution without having to hire a team of IT/DevOps folks — at least for an experimental custom dashboard.

🍀 MongoDB’s Pros

  • Schema-less. Flexible schema for the win. I don’t have to change anything, my regular app development workflow, creating a Node.js-based app that I am manipulating with JSON type data, I can just feed that into MongoDB and it just works.
  • Workflow-consistency. Creates documents the way my custom dashboard is represented. Sales, Videos, Talks, Comments, Reviews, Registrations, etc. all of that have similar data representation on the frontend and the backend — and even in the database. I manage 3rd party data via middleware. This consistency translates to clean code.
  • Ease of scale-out. It scales reads by using replica sets. Scales writes by using sharding (auto-balancing). Just fire up another machine and away you go. Most importantly, instead of vertical scaling via RDBMS, MongoDB lets you scale horizontally with different levels of consistency. That’s a big plus. ➕
  • Cost. Depends on which RDBMS of course, but MongoDB is free and can run on Linux, ideal for running on cheaper commodity kits.

🍃 Why MongoDB Atlas?

Well, now that I know MongoDB is the right database choice, there are so many different options to host your database. I can self-host on my Linux machine via DigitalOcean, use a cloud provider like AWS/Azure or a choose a DBaaS service specific to MongoDB.

Mongodb Atlas

But I want a fast, secure, and managed MongoDB solution that I can easily scale with the growth of the number of modules we attach in this custom WordPress dashboard. That’s MongoDB Atlas.

MongoDB Atlas is a cloud-hosted MongoDB service engineered and run by the same team that builds the database. And guess what, I trust that they follow the best operational practices since they are the ones who’re building MongoDB in the first place.

I want this custom dashboard to be self-managed, serverless, and using MongoDB Atlas saves me from worrying about software patching, backups, and reliable configuration setup for new DB updates. Again a big plus. ➕

Also, the fact that MongoDB Atlas is supported cross-platform as well as cross-region and across different cloud providers makes it a much better choice. I think each Cluster comes with two replica sets, ready to scale.

🔋 MongoDB Compass

Now that we are going to work with MongoDB, it’d be great to have a tool through which we can explore our database, view the changes, debug and so on. For this purpose, MongoDB again takes the lead with a product called MongoDB Compass. Take a look.

Mongodb Compass

I suggest that you go ahead and download MongoDB Compass. It’s literally the best tool to visualize your MongoDB database. Here’s a set of features:

  • Visualize and explore: Take a look at your database, find out how things are looking, and even visualize stuff like maps/coordinates.
  • Insert, modify, and delete: You can also perform CRUD operations for your DB right from MongoDB compass. Makes testing easier.
  • Debug and optimize: Finally, analyze your data, debug it and even find out about performance issues right inside a great GUI for your database. This tool is a must-have if you work with MongoDB.
  • Extensible: And the best part is you can build your own plugins to extend MongoDB Compass. Here’s the documentation on building your own Compass plugins.
  • Enterprise Flavor: MongoDB Compass comes in a few flavors: Community (Free), and Enterprise (Licensed) — the Enterprise version is the one that lets you visualize DB schema.

✅ Getting Started with MongoDB Atlas

Let’s get started and build a simple module that’s part of the custom WordPress dashboard I am building. For this module, we are collecting all the sales related data. For that, we need a MongoDB instance, and of course we’re using MongoDB Atlas here.

Step #1: Go to MongoDB Atlas →

Go to the MongoDB Atlas site and register a completely free MongoDB instance hosted on AWS, with shared RAM and 512 MB storage. Click the Get Started Free button.

Mongodb Atlas

Step #2: Sign up at MongoDB Atlas →

Now go ahead and sign up with your email ID and fill up the details. It’s amazing that you can sign up and use a free MongoDB Atlas hosted DB instance, and they don’t even require you to add a credit card for that.

Mongodb Atlas Signup

Step #3: Create the Cluster

Now you’ll be redirected to a page with a bunch of information about the new MongoDB Cluster you’re about to create. I suggest that you review this information, and move ahead by clicking the Create Cluster button at the bottom just like in the screenshot below.

Mongodb Atlas Create Cluster

Step #4: Create DB Username & Password

It’ll take a minute and your DB will be created. Once that happens, head over to the Security > MongoDB Users and click on the + ADD NEW USER button on the right, to create a new user for your database. Let’s keep all the other settings set to default for the sake of this intro-article.

I’m setting the user/pass as usermongo but you know better.

GIF for MongoDB Atlas, Microsoft Azure, & Serverless Functions

Step #5: Add IP to Whitelist for Access

To be able to access your MongoDB Atlas database, you need to setup the IP Whitelist with the IP of your server where your app is hosted. Authentication is beyond what I am discussing here so for the purpose of this demo let’s just allow everyone (obviously a bad practice in production).

So, again, head over to the Security > IP Whitelist and click on the + ADD IP ADDRESS button on the right, and finally ALLOW ACCESS FROM ANYWHERE button to allow the anonymous access.

GIF for MongoDB Atlas, Microsoft Azure, & Serverless Functions

Step #6: Connect via MongoDB Compass

Now that our DB’s IP access and a user has been created, we can pick up the connection string and use it to connect to our database with our MongoDB Compass application.

Go to Connect then choose Connect with MongoDB Compass and download Compass if you haven’t. Copy the URI Connection String. Finally, open Compass and it should be able to detect the connection string in your clipboard, allow it to connect to your database.

And you are set to visualize your database, analyze its performance, and even run complete CRUD operations. Awesome! 💯

GIF for MongoDB Atlas, Microsoft Azure, & Serverless Functions

Now that we have created a MongoDB Atlas and connected it with MongoDB Compass, we can move forward and start building our Node.js application.

WordPress REST API — FTW!

This WordPress based Node.js custom dashboard interacts with the WordPress instance via the WordPress REST API. Since this is a Node.js app, I am using an awesome library called wpapi written by K Adam White. He has also built a demo Express based WordPress app. That’s what I got inspired by while building this custom dashboard, so you’ll see a lot of it here.

🚀 WordPress Custom Router Based on Express

The router is set up with Express. Here’s a basic error handler and router template for using WordPress with express.

'use strict';

var express = require('express');
var router = express.Router();
var siteInfoMiddleware = require('../middleware/site-info');

// Set global site info on all routes
router.use(siteInfoMiddleware);

// Public Routes
// =============

router.get('/', require('./index'));
router.get('/page/:page', require('./index'));
router.get('/:slug', require('./single'));
router.use('/tags/:tag', require('./tag'));
router.use('/categories/:category', require('./category'));

// Catch 404 and forward to error handler.
router.use(function (req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// Error Handling
// ==============

// Development error handler will print stacktrace.
function developmentErrorRoute(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: err
    });
}

// Production error handler. No stacktraces leaked to user.
function friendlyErrorRoute(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
}

// Configure error-handling behavior
if (router.get('env') === 'development') {
    router.use(developmentErrorRoute);
} else {
    router.use(friendlyErrorRoute);
}

module.exports = router;

View the code on Gist.

🎚 Basic Express Based Implementation

I am not hosting this entire thing on WordPress, but the initial plan was to do just that. If you want to go do that, you’d wanna build the index by querying all the info using the RSVP.hash utility for convenience and parallelism. For that here’s what you should do.

'use strict';

var wp = require( '../services/wp' );
var contentService = require( '../services/content-service' );
var pageNumbers = require( '../services/page-numbers' );
var pageTitle = require( '../services/page-title' );
var RSVP = require( 'rsvp' );

function getHomepage( req, res, next ) {
  var pages = pageNumbers( req.params.page );

  RSVP.hash({
    archiveBase: '',
    pages: pages,
    title: pageTitle(),
    // Primary page content
    posts: wp.posts().page( pages.current ),
    sidebar: contentService.getSidebarContent()
  }).then(function( context ) {
    if ( req.params.page && ! context.posts.length ) {
      // Invalid pagination: 404
      return next();
    }

    res.render( 'index', context );
  }).catch( next );
}

module.exports = getHomepage;

View the code on Gist.

🦏 Authentication Cooked In

For this setup, you’ll also need to authenticate your Node.js app by giving it the authentication data, which along with wpapi can be processed like this. Beware this is not always a best practice if you don’t use correct permissions and environment variables settings.

var WP = require( 'wordpress-rest-api' );
var _ = require( 'lodash' );

var config = _.pick( require( './config' ).wordpress, [
  // Whitelist valid config keys
  'username',
  'password',
  'endpoint'
]);

var wp = new WP( config );

module.exports = wp;

View the code on Gist.

🦁 Site Content Accumulation

And finally, you are able to consume all the content by creating a content service which handles recursively fetching:

  • All the pages of a paged collection.
  • Your WordPress site’s info.
  • An alphabetized list of categories.
  • A specific category (specified by slug) from the content cache.
  • An alphabetized list of tags.
  • A specific tag (specified by slug) from the content cache
  • Other content required to have some feature parity with WP.

The code for this looks somewhat like this.

'use strict';

var wp = require( './wp' );
var cache = require( './content-cache' );
var _ = require( 'lodash' );
var RSVP = require( 'rsvp' );

/**
 * Recursively fetch all pages of a paged collection
 *
 * @param {Promise} request A promise to a WP API request's response
 * @returns {Array} A promise to an array of all matching records
 */
function all( request ) {
  return request.then(function( response ) {
    if ( ! response._paging || ! response._paging.next ) {
      return response;
    }
    // Request the next page and return both responses as one collection
    return RSVP.all([
      response,
      all( response._paging.next )
    ]).then(function( responses ) {
      return _.flatten( responses );
    });
  });
}

function siteInfo( prop ) {
  var siteInfoPromise = cache.get( 'site-info' );

  if ( ! siteInfoPromise ) {
    // Instantiate, request and cache the promise
    siteInfoPromise = wp.root( '/' ).then(function( info ) {
      return info;
    });
    cache.set( 'site-info', siteInfoPromise );
  }

  // Return the requested property
  return siteInfoPromise.then(function( info ) {
    return prop ? info[ prop ] : info;
  });
}

/**
 * Get an alphabetized list of categories
 *
 * All archive routes display a sorted list of categories in their sidebar.
 * We generate that list here to ensure the sorting logic isn't duplicated
 * across routes.
 *
 * @method sortedCategories
 * @return {Array} An array of category objects
 */
function sortedCategories() {
  return all( wp.categories() ).then(function( categories ) {
    return _.chain( categories )
      .sortBy( 'slug' )
      .value();
  });
}

function sortedCategoriesCached() {
  var categoriesPromise = cache.get( 'sorted-categories' );

  if ( ! categoriesPromise ) {
    categoriesPromise = sortedCategories();
    cache.set( 'sorted-categories', categoriesPromise );
  }

  return categoriesPromise;
}

/**
 * Get a specific category (specified by slug) from the content cache
 *
 * The WP API doesn't currently support filtering taxonomy term collections,
 * so we have to request all categories and filter them down if we want to get
 * an individual term.
 *
 * To make this request more efficient, it uses sortedCategoriesCached.
 *
 * @method categoryCached
 * @param {String} slug The slug of a category
 * @return {Promise} A promise to the category with the provided slug
 */
function categoryCached( slug ) {
  return sortedCategoriesCached().then(function( categories ) {
    return _.findWhere( categories, {
      slug: slug
    });
  });
}

/**
 * Get a specific tag (specified by slug) from the content cache
 *
 * The WP API doesn't currently support filtering taxonomy term collections,
 * so we have to request all tags and filter them down if we want to get an
 * individual term.
 *
 * To make this request more efficient, it uses the cached sortedTags promise.
 *
 * @method tagCached
 * @param {String} slug The slug of a tag
 * @return {Promise} A promise to the tag with the provided slug
 */
function tagCached( slug ) {
  return sortedTagsCached().then(function( tags ) {
    return _.findWhere( tags, {
      slug: slug
    });
  });
}

/**
 * Get an alphabetized list of tags
 *
 * @method sortedTags
 * @return {Array} An array of tag objects
 */
function sortedTags() {
  return all( wp.tags() ).then(function( tags ) {
    return _.chain( tags )
      .sortBy( 'slug' )
      .value();
  });
}

function sortedTagsCached() {
  var tagsPromise = cache.get( 'sorted-tags' );

  if ( ! tagsPromise ) {
    tagsPromise = sortedTags();
    cache.set( 'sorted-tags', tagsPromise );
  }

  return tagsPromise;
}

function getSidebarContent() {
  return RSVP.hash({
    categories: sortedCategoriesCached(),
    tags: sortedTagsCached()
  });
}

module.exports = {
  // Recursively page through a collection to retrieve all matching items
  all: all,
  // Get (and cache) the top-level information about a site, returning the
  // value corresponding to the provided key
  siteInfo: siteInfo,
  sortedCategories: sortedCategories,
  sortedCategoriesCached: sortedCategoriesCached,
  categoryCached: categoryCached,
  tagCached: tagCached,
  sortedTags: sortedTags,
  sortedTagsCached: sortedTagsCached,
  getSidebarContent: getSidebarContent
};

View the code on Gist.

🛠 Custom Routes & Sales Data

Finally, I have cooked in quite a few custom routes from where I can attain any kind of sales related data. For the particular architecture I have in place, I’m again using the RSVP.hash utility for convenience and parallelism. It works like a charm.

The post Build Custom Dashboards with MongoDB, Azure & Serverless Functions appeared first on SitePoint.


Source: Sitepoint

Building DApps with Ethereum: App Rules and Blockchain Setup

This is the first part of a series on building decentralized applications using the Ethereum blockchain. We’re going to build 3 things: a custom token a DAO which uses the tokens as votes a prototype web UI for interacting with the smart contracts After following the instructions in this course, you’ll be able to build […]

The post Building DApps with Ethereum: App Rules and Blockchain Setup appeared first on SitePoint.


Source: Sitepoint