Collective #508

Front-end Developer Handbook 2019 Cody Lindley wrote this guide that outlines and discusses the practice of front-end engineering, how to learn it and what tools are used when practicing it in 2019. Check it out Our Sponsor Visual Composer founder had an AMA Read more

Biometrics And Neuro-Measurements For User Testing

dreamt up by webguru in Uncategorized | Comments Off on Biometrics And Neuro-Measurements For User Testing

Biometrics And Neuro-Measurements For User Testing

Biometrics And Neuro-Measurements For User Testing

Susan Weinschenk



(This article is sponsored by Adobe.) So it’s time to test the latest version of your app with users. You schedule your first user testing session. The participant enters the room; your lab partner puts velcro on the participant’s finger and fits a headband and head cap on before she sits down at a computer to start the user test session. What’s all this for? It’s biometrics and neuro-measurements.

In a “traditional” user test, you put a participant in front of your app, product, or software and give them tasks to do, ask them to “think aloud”, and observe and record what they say and what they do. You may ask them some questions before and after the session, too. I’ve done thousands of these sessions, and chances are that if you are a user researcher, you have to.


A traditional way or user testing in which a participant is seated in front of a screen and asked to say what they see and feel
The most common way of user testing: participants are seated in front of a screen and asked to say what they see and feel. (Image source: iMotions) (Large preview)

There’s nothing really wrong with user testing this way except that it relies on the participant telling you (either during or after the session) why they did what they did, and how they feel about the product or app. You can see that they clicked on a particular button or touched a link on the mobile app, but if they explain why, you are only getting the conscious reason why.


People filter their feelings, decisions and reasons consciously.

What if you could get their unconscious reactions? What if you could take a look inside your users’ brains and see what it is they aren’t saying, i.e. the things they themselves may not realize about their reactions to your product?

We know that most mental processing — including decision-making and emotional reactions — occurs unconsciously. So if people tell you how they feel and why they did something, it is possible that they believe what they are saying is the truth, but it’s also possible that they don’t know how they feel or why they did or did not take an action.

People filter their feelings, decisions and reasons consciously and by that time you aren’t necessarily getting real data. Add to that the fact that users aren’t always truthful during user tests. They may not want to offend you by telling you they think your product is hard to use or boring.

So that’s why user researchers are starting to use some other tools to get reactions and data directly from the body without the filtering of conscious thought. Hence, biometrics and neuro-measurements.

Some of these new tools are easy and inexpensive to use. Others may take more investment of your time and budget. Or you may want to bring in an outside firm that specializes in these tools. (Some suggestions for outside vendors are at the end of the article.)

Let’s take a look at what’s available.

Galvanic Skin Response (GSR)

GSR is also called “electrodermal activity” or EDA. A typical GSR measurement device is a relatively small, unobtrusive sensor that is connected to the skin of your finger or hand.

Sweat glands on the hands are very sensitive to changes in your emotional state. If you become emotionally aroused — either positively or negatively — then you will release more sweat in your hands. Sometimes, these are very small changes that you may not notice. This is what a GSR monitor is measuring.


An image of a GSR measurement device
You may not notice that there is a small amount of moisture, but even the tiniest amount of increase in moisture changes the amount of electrical conductance of your skin. (Image source: iMotions) (Large preview)

The GSR monitor can’t tell if you are happy, sad, scared, and so on, but it can tell if you are becoming more or less emotional. And since the amount of sweat you release is not under conscious control, a GSR monitor can measure what you may not be consciously aware of.

GSR monitoring has been around for over a hundred years. The monitors are relatively inexpensive and easy to learn how to use. The price for a GSR monitor ranges from about $150 to $600, depending on the brand and model you get. If you want to buy your own, check out Carolina Supply. iMotions also has a great downloadable guide to GSR monitors that you can get for free.

Recommended reading: How People Make Decisions

Respiration

It’s also relatively easy to measure respiration. When people are emotionally aroused they breathe faster. This can be detected in several ways — the easiest being to place a cloth band around the chest and/or stomach and measure the expansion of the chest or stomach as people breathe.


Belt from Biopac
A ‘respiration transducer’ helps measure any changes in the abdominal circumference that occur as a subject breathes. (Image source: iMotions) (Large preview)

If/when they are using your product and they start breathing faster, you can deduce that something has (either positively or negatively) affected them emotionally.

Heart Rate

You can also use the band around the chest or even a simpler measurement on a finger to measure heart rate/pulse. When you are emotionally aroused, your heart beats faster and your pulse increases.

How would you use GSR, respiration, or heart rate data in a user test or study? Let’s say you are testing an app for getting an insurance quote. You ask the user what they think of the insurance quote app, and they answer:

“It was OK, it wasn’t too hard to use.”

But looking at their GSR, respiration, and/or heart rate might tell you that they were stressed. The data will also show you when and where in the process they had the most stress.

Like GSR monitors, heart-rate and respiration monitors are relatively inexpensive (under $100). What you may really want, however, is a total package that includes, a universal monitor that you can plug more than one measurement into.

For example, you can use GSR, heart rate, respiration and even EEG (discussed below), plus software that lets you monitor the data and combine it with actions your users are taking at specific moments during your user study. These packages will cost you a lot, however. A whole system may run as much as $7,000.

To get started, you may want to bring in a vendor who has the equipment to get your feet wet before you decide to buy these tools for your lab.

Eye Tracking

I am probably unusual in my criticisms of eye-tracking. A lot of people like eye tracking, but I think it has some problems. I’ll explain why.

Eye tracking involves having people look at a special monitor while wearing eye-tracking headsets/glasses. The eye tracker measures what you look at and how long you look at it. If you were doing user testing on a web page, then you could see (either for an individual or through aggregated data) where people looked most, how long they looked at it, and what people did not look at, and so on.

Eye tracking works just fine in measuring what it is measuring. But here’s my criticism: Eye tracking only measures where people are looking with their central vision. It doesn’t measure peripheral vision.

Recent research on peripheral vision shows that peripheral vision is more important than once thought for information process. For example, images of danger and emotion are processed faster in peripheral vision than in central vision. We also know now that people use peripheral vision to decide if they are the right place, or in the case of software and website design, if they are at the right page or screen. It’s possible for people to “see” something in peripheral vision, but not be consciously aware that they have. And what they see can influence the action they take.

Since eye tracking doesn’t track any peripheral vision data, I am not a big fan of it. Monitors with eye tracking built in, plus the software to analyze and report on the data can cost around $7,000 to $10,000.


Eye tracking only measures where people are looking with their central and not with their peripheral vision.

Facial Coding

Cameras can capture someone’s face as they use a product or watch a video. Algorithms can then analyze the facial expressions and tell you whether the person is confused, happy, scared, and so on.


Facial coding used on a scene of a movie played on a screen
Facial coding uses algorithms to take a good guess at what the person is feeling. (Image source: iMotions) (Large preview)

Facial coding is also an “add-on” feature to eye tracking. You should assume similar pricing ($7,000 to $10,000) for facial coding as for eye tracking

fEMG

EMG stands for Electromyography, or muscle movement. Whenever a muscle contracts it generates a small amount of electricity which can be detected with some fairly simple electrodes. Muscle movement can be very small — you may not see the muscle move, but you can measure it.

This means that some of the most interesting EMG measurements come from the movement of muscles in the face or fEMG. Facial coding uses algorithms to take a good guess at what the person is feeling, but with fEMG you can actually measure the muscles in the face and thereby more accurately assess the emotion that the person is feeling. There is muscle activity in the face that a video won’t detect, but that the fEMG recordings will detect. This means that with fEMG you can pick up on emotions that are not being obviously displayed through just facial coding.


An image of a testing person using a fEMG measurement device placed to his forehead that records facial muscle movement
(Image source: iMotions) (Large preview)

When would you use facial coding or fEMG?

Well, let’s say you have created some new videos for the careers/employment page of your company’s website. The videos have real people who work at the company talking about how they came to be an employee, and what it is they like about working at the company. You want to know if people like and resonate with the videos. Facial coding and, even better, fEMG, would help you measure what people are feeling, and even tell you which parts of the video are eliciting which emotions.

fEMG equipment and software are expensive and not easy to learn how to use. For this reason, you will probably want to start by bringing in a vendor rather than using this on your own.

EEG (Electroencephalography)

You can directly measure the electrical activity of the brain by placing electrodes on the scalp. EEG devices measure the electrical activity generated by neurons.

EEG measures electrical changes on the surface of the brain — not deep within particular brain structures. This means that EEG can’t tell you that a particular part of the brain is active. It can only tell you when there is more or less brain activity. You would need to use more sophisticated methods, such as fMRI (functional Magnetic Resonance Imaging) to study more specific brain activity. fMRI equipment is very large and very expensive, which is why only research and medical institutions use them. In contrast, EEG is inexpensive.

EEG measures whether a person is engaged and paying attention. EEG measurements are particularly good at showing you activity by seconds or even parts of a second. Let’s go back to the example of the user test to measure the impact of the employee story videos at the careers/jobs page of the corporate website. Are the videos interesting? Do people pay attention while watching them? Exactly which parts of the videos are engaging? EEG can tell you this.

When I was in graduate school and doing EEG research, we had to use electrodes and gel to get EEG readings, but now there are easier ways. You can place a cap on someone’s head, kind of like a swim cap, and the electrodes are built in to the cap.


An EEG measurement device designed similar to a swim cap
(Image source: iMotions) (Large preview)

Some devices are like headsets rather than swim caps:


An EEG measurement device shaped like a headset
(Image source: Spark Neuro) (Large preview)

EEG devices range from the inexpensive to the expensive. For example, Emotiv makes a $299 EEG headset. You will probably, however, want to get a higher end version for $799, and then you will need a subscription for the software ($99 a month).

It can take a while to learn how to accurately read EEG data, so, again, it might be better to start by bringing in a vendor who has all the equipment and know-how until you learn.

Recommended reading: Grabbing Visual Attention With The Visual Cortex

Combining Measurements

It is common to combine multiple methods of biometrics together to help with the accuracy and interpretation of the results.

Although biometrics and neuro-measurements don’t tell the whole story, the data that we get from biometrics and neuro-measurements is more accurate than self-reporting. As the tools become easier to use and researchers get used to using them, they will become more common. We may even get to the point where we stop using the think-aloud technique altogether, although I don’t think we are there yet!

Takeaways

  • If you haven’t already researched biometrics for your user testing projects, now is a good time to check out these measurements as an addition to your current testing.
  • Pick a modality and/or a vendor and do a trial project.
  • If you are in charge of user-testing budgets, add in some biometrics to your budgeting process for the next year or two so you can get started.

Vendors

Vendors to consider for a biometric study:

This article is part of the UX design series sponsored by Adobe. Adobe XD tool is made for a fast and fluid UX design process, as it lets you go from idea to prototype faster. Design, prototype and share — all in one app. You can check out more inspiring projects created with Adobe XD on Behance, and also sign up for the Adobe experience design newsletter to stay updated and informed on the latest trends and insights for UX/UI design.

Smashing Editorial
(cm, ms, ra, il)

Source: Smashing Magazine, Biometrics And Neuro-Measurements For User Testing

Biometrics And Neuro-Measurements For User Testing

dreamt up by webguru in Uncategorized | Comments Off on Biometrics And Neuro-Measurements For User Testing

Biometrics And Neuro-Measurements For User Testing

Biometrics And Neuro-Measurements For User Testing

Susan Weinschenk



(This article is sponsored by Adobe.) So it’s time to test the latest version of your app with users. You schedule your first user testing session. The participant enters the room; your lab partner puts velcro on the participant’s finger and fits a headband and head cap on before she sits down at a computer to start the user test session. What’s all this for? It’s biometrics and neuro-measurements.

In a “traditional” user test, you put a participant in front of your app, product, or software and give them tasks to do, ask them to “think aloud”, and observe and record what they say and what they do. You may ask them some questions before and after the session, too. I’ve done thousands of these sessions, and chances are that if you are a user researcher, you have to.


A traditional way or user testing in which a participant is seated in front of a screen and asked to say what they see and feel
The most common way of user testing: participants are seated in front of a screen and asked to say what they see and feel. (Image source: iMotions) (Large preview)

There’s nothing really wrong with user testing this way except that it relies on the participant telling you (either during or after the session) why they did what they did, and how they feel about the product or app. You can see that they clicked on a particular button or touched a link on the mobile app, but if they explain why, you are only getting the conscious reason why.


People filter their feelings, decisions and reasons consciously.

What if you could get their unconscious reactions? What if you could take a look inside your users’ brains and see what it is they aren’t saying, i.e. the things they themselves may not realize about their reactions to your product?

We know that most mental processing — including decision-making and emotional reactions — occurs unconsciously. So if people tell you how they feel and why they did something, it is possible that they believe what they are saying is the truth, but it’s also possible that they don’t know how they feel or why they did or did not take an action.

People filter their feelings, decisions and reasons consciously and by that time you aren’t necessarily getting real data. Add to that the fact that users aren’t always truthful during user tests. They may not want to offend you by telling you they think your product is hard to use or boring.

So that’s why user researchers are starting to use some other tools to get reactions and data directly from the body without the filtering of conscious thought. Hence, biometrics and neuro-measurements.

Some of these new tools are easy and inexpensive to use. Others may take more investment of your time and budget. Or you may want to bring in an outside firm that specializes in these tools. (Some suggestions for outside vendors are at the end of the article.)

Let’s take a look at what’s available.

Galvanic Skin Response (GSR)

GSR is also called “electrodermal activity” or EDA. A typical GSR measurement device is a relatively small, unobtrusive sensor that is connected to the skin of your finger or hand.

Sweat glands on the hands are very sensitive to changes in your emotional state. If you become emotionally aroused — either positively or negatively — then you will release more sweat in your hands. Sometimes, these are very small changes that you may not notice. This is what a GSR monitor is measuring.


An image of a GSR measurement device
You may not notice that there is a small amount of moisture, but even the tiniest amount of increase in moisture changes the amount of electrical conductance of your skin. (Image source: iMotions) (Large preview)

The GSR monitor can’t tell if you are happy, sad, scared, and so on, but it can tell if you are becoming more or less emotional. And since the amount of sweat you release is not under conscious control, a GSR monitor can measure what you may not be consciously aware of.

GSR monitoring has been around for over a hundred years. The monitors are relatively inexpensive and easy to learn how to use. The price for a GSR monitor ranges from about $150 to $600, depending on the brand and model you get. If you want to buy your own, check out Carolina Supply. iMotions also has a great downloadable guide to GSR monitors that you can get for free.

Recommended reading: How People Make Decisions

Respiration

It’s also relatively easy to measure respiration. When people are emotionally aroused they breathe faster. This can be detected in several ways — the easiest being to place a cloth band around the chest and/or stomach and measure the expansion of the chest or stomach as people breathe.


Belt from Biopac
A ‘respiration transducer’ helps measure any changes in the abdominal circumference that occur as a subject breathes. (Image source: iMotions) (Large preview)

If/when they are using your product and they start breathing faster, you can deduce that something has (either positively or negatively) affected them emotionally.

Heart Rate

You can also use the band around the chest or even a simpler measurement on a finger to measure heart rate/pulse. When you are emotionally aroused, your heart beats faster and your pulse increases.

How would you use GSR, respiration, or heart rate data in a user test or study? Let’s say you are testing an app for getting an insurance quote. You ask the user what they think of the insurance quote app, and they answer:

“It was OK, it wasn’t too hard to use.”

But looking at their GSR, respiration, and/or heart rate might tell you that they were stressed. The data will also show you when and where in the process they had the most stress.

Like GSR monitors, heart-rate and respiration monitors are relatively inexpensive (under $100). What you may really want, however, is a total package that includes, a universal monitor that you can plug more than one measurement into.

For example, you can use GSR, heart rate, respiration and even EEG (discussed below), plus software that lets you monitor the data and combine it with actions your users are taking at specific moments during your user study. These packages will cost you a lot, however. A whole system may run as much as $7,000.

To get started, you may want to bring in a vendor who has the equipment to get your feet wet before you decide to buy these tools for your lab.

Eye Tracking

I am probably unusual in my criticisms of eye-tracking. A lot of people like eye tracking, but I think it has some problems. I’ll explain why.

Eye tracking involves having people look at a special monitor while wearing eye-tracking headsets/glasses. The eye tracker measures what you look at and how long you look at it. If you were doing user testing on a web page, then you could see (either for an individual or through aggregated data) where people looked most, how long they looked at it, and what people did not look at, and so on.

Eye tracking works just fine in measuring what it is measuring. But here’s my criticism: Eye tracking only measures where people are looking with their central vision. It doesn’t measure peripheral vision.

Recent research on peripheral vision shows that peripheral vision is more important than once thought for information process. For example, images of danger and emotion are processed faster in peripheral vision than in central vision. We also know now that people use peripheral vision to decide if they are the right place, or in the case of software and website design, if they are at the right page or screen. It’s possible for people to “see” something in peripheral vision, but not be consciously aware that they have. And what they see can influence the action they take.

Since eye tracking doesn’t track any peripheral vision data, I am not a big fan of it. Monitors with eye tracking built in, plus the software to analyze and report on the data can cost around $7,000 to $10,000.


Eye tracking only measures where people are looking with their central and not with their peripheral vision.

Facial Coding

Cameras can capture someone’s face as they use a product or watch a video. Algorithms can then analyze the facial expressions and tell you whether the person is confused, happy, scared, and so on.


Facial coding used on a scene of a movie played on a screen
Facial coding uses algorithms to take a good guess at what the person is feeling. (Image source: iMotions) (Large preview)

Facial coding is also an “add-on” feature to eye tracking. You should assume similar pricing ($7,000 to $10,000) for facial coding as for eye tracking

fEMG

EMG stands for Electromyography, or muscle movement. Whenever a muscle contracts it generates a small amount of electricity which can be detected with some fairly simple electrodes. Muscle movement can be very small — you may not see the muscle move, but you can measure it.

This means that some of the most interesting EMG measurements come from the movement of muscles in the face or fEMG. Facial coding uses algorithms to take a good guess at what the person is feeling, but with fEMG you can actually measure the muscles in the face and thereby more accurately assess the emotion that the person is feeling. There is muscle activity in the face that a video won’t detect, but that the fEMG recordings will detect. This means that with fEMG you can pick up on emotions that are not being obviously displayed through just facial coding.


An image of a testing person using a fEMG measurement device placed to his forehead that records facial muscle movement
(Image source: iMotions) (Large preview)

When would you use facial coding or fEMG?

Well, let’s say you have created some new videos for the careers/employment page of your company’s website. The videos have real people who work at the company talking about how they came to be an employee, and what it is they like about working at the company. You want to know if people like and resonate with the videos. Facial coding and, even better, fEMG, would help you measure what people are feeling, and even tell you which parts of the video are eliciting which emotions.

fEMG equipment and software are expensive and not easy to learn how to use. For this reason, you will probably want to start by bringing in a vendor rather than using this on your own.

EEG (Electroencephalography)

You can directly measure the electrical activity of the brain by placing electrodes on the scalp. EEG devices measure the electrical activity generated by neurons.

EEG measures electrical changes on the surface of the brain — not deep within particular brain structures. This means that EEG can’t tell you that a particular part of the brain is active. It can only tell you when there is more or less brain activity. You would need to use more sophisticated methods, such as fMRI (functional Magnetic Resonance Imaging) to study more specific brain activity. fMRI equipment is very large and very expensive, which is why only research and medical institutions use them. In contrast, EEG is inexpensive.

EEG measures whether a person is engaged and paying attention. EEG measurements are particularly good at showing you activity by seconds or even parts of a second. Let’s go back to the example of the user test to measure the impact of the employee story videos at the careers/jobs page of the corporate website. Are the videos interesting? Do people pay attention while watching them? Exactly which parts of the videos are engaging? EEG can tell you this.

When I was in graduate school and doing EEG research, we had to use electrodes and gel to get EEG readings, but now there are easier ways. You can place a cap on someone’s head, kind of like a swim cap, and the electrodes are built in to the cap.


An EEG measurement device designed similar to a swim cap
(Image source: iMotions) (Large preview)

Some devices are like headsets rather than swim caps:


An EEG measurement device shaped like a headset
(Image source: Spark Neuro) (Large preview)

EEG devices range from the inexpensive to the expensive. For example, Emotiv makes a $299 EEG headset. You will probably, however, want to get a higher end version for $799, and then you will need a subscription for the software ($99 a month).

It can take a while to learn how to accurately read EEG data, so, again, it might be better to start by bringing in a vendor who has all the equipment and know-how until you learn.

Recommended reading: Grabbing Visual Attention With The Visual Cortex

Combining Measurements

It is common to combine multiple methods of biometrics together to help with the accuracy and interpretation of the results.

Although biometrics and neuro-measurements don’t tell the whole story, the data that we get from biometrics and neuro-measurements is more accurate than self-reporting. As the tools become easier to use and researchers get used to using them, they will become more common. We may even get to the point where we stop using the think-aloud technique altogether, although I don’t think we are there yet!

Takeaways

  • If you haven’t already researched biometrics for your user testing projects, now is a good time to check out these measurements as an addition to your current testing.
  • Pick a modality and/or a vendor and do a trial project.
  • If you are in charge of user-testing budgets, add in some biometrics to your budgeting process for the next year or two so you can get started.

Vendors

Vendors to consider for a biometric study:

This article is part of the UX design series sponsored by Adobe. Adobe XD tool is made for a fast and fluid UX design process, as it lets you go from idea to prototype faster. Design, prototype and share — all in one app. You can check out more inspiring projects created with Adobe XD on Behance, and also sign up for the Adobe experience design newsletter to stay updated and informed on the latest trends and insights for UX/UI design.

Smashing Editorial
(cm, ms, ra, il)

Source: Smashing Magazine, Biometrics And Neuro-Measurements For User Testing

How To Build An Endless Runner Game In Virtual Reality (Part 1)

dreamt up by webguru in Uncategorized | Comments Off on How To Build An Endless Runner Game In Virtual Reality (Part 1)

How To Build An Endless Runner Game In Virtual Reality (Part 1)

How To Build An Endless Runner Game In Virtual Reality (Part 1)

Alvin Wan



Today, I’d like to invite you to build an endless runner VR game with webVR — a framework that gives a dual advantage: It can be played with or without a VR headset. I’ll explain the magic behind the gaze-based controls for our VR-headset players by removing the game control’s dependence on a keyboard.

In this tutorial, I’ll also show you how you can synchronize the game state between two devices which will move you one step closer to building a multiplayer game. I’ll specifically introduce more A-Frame VR concepts such as stylized low-poly entities, lights, and animation.

To get started, you will need the following:

  • Internet access (specifically to glitch.com);
  • A new Glitch project;
  • A virtual reality headset (optional, recommended). (I use Google Cardboard, which is offered at $15 a piece.)

Note: A demo of the final product can be viewed here.

Step 1: Setting Up A Basic Scene

In this step, we will set up the following scene for our game. It is composed of a few basic geometric shapes and includes custom lighting, which we will describe in more detail below. As you progress in the tutorial, you will add various animations and effects to transform these basic geometric entities into icebergs sitting in an ocean.


A preview of the game scene’s basic geometric objects
A preview of the game scene’s basic geometric objects (Large preview)

You will start by setting up a website with a single static HTML page. This allows you to code from your desktop and automatically deploy to the web. The deployed website can then be loaded on your mobile phone and placed inside a VR headset. Alternatively, the deployed website can be loaded by a standalone VR headset.

Get started by navigating to glitch.com. Then, do the following:

  1. Click on “New Project” in the top right.
  2. Click on “hello-webpage” in the drop down.

    Glitch.com’s homepage
    Glitch.com’s homepage (Large preview)
  3. Next, click on index.html in the left sidebar. We will refer to this as your “editor”.

Glitch project index.html file
Glitch project: the index.html file (Large preview)

Start by deleting all existing code in the current index.html file. Then, type in the following for a basic webVR project, using A-Frame VR. This creates an empty scene by using A-Frame’s default lighting and camera.

<!DOCTYPE html>
<html>
  <head>
    <title>Ergo | Endless Runner Game in Virtual Reality</title>
    https://aframe.io/releases/0.7.0/aframe.min.js
  </head>
  <body>
    <a-scene>
    </a-scene>
  </body>
</html>

Note: You can learn more about A-Frame VR at aframe.io.

To start, add a fog, which will obscure objects far away for us. Modify the a-scene tag on line 8.

<a-scene fog="type: linear; color: #a3d0ed; near:5; far:20">

Moving forward, all objects in the scene will be added between the <a-scene>...</a-scene> tags. The first item is the sky. Between your a-scene tags, add the a-sky entity.

<a-scene ...>
  <a-sky color="#a3d0ed"></a-sky>
</a-scene>

After your sky, add lighting to replace the default A-Frame lighting.

There are three types of lighting:

  • Ambient
    This is an ever-present light that appears to emanate from all objects in the scene. If you wanted a blue tint on all objects, resulting in blue-ish shadows, you would add a blue ambient light. For example, the objects in this Low Poly Island scene are all white. However, a blue ambient light results in a blue hue.
  • Directional
    This is analogous to a flashlight which, as the name suggests, points in a certain direction.
  • Point
    Again, as the name suggests, this emanates light from a point.

Just below your a-sky entity, add the following lights: one directional and one ambient. Both are light blue.

<!-- Lights -->
<a-light type="directional" castShadow="true" intensity="0.4" color="#D0EAF9;" position="5 3 1"></a-light>
<a-light intensity="0.8" type="ambient" color="#B4C5EC"></a-light>

Next, add a camera with a custom position to replace the default A-Frame camera. Just below your a-light entities, add the following:

<!-- Camera -->
<a-camera position="0 0 2.5"></a-camera>

Just below your a-camera entity, add several icebergs using low-poly cones.

<!-- Icebergs -->
<a-cone class="iceberg" segments-radial="5" segments-height="3" height="1" radius-top="0.15" radius-bottom="0.5" position="3 -0.1 -1.5"></a-cone>
<a-cone class="iceberg" segments-radial="7" segments-height="3" height="0.5" radius-top="0.25" radius-bottom="0.35" position="-3 -0.1 -0.5"></a-cone>
<a-cone class="iceberg" segments-radial="6" segments-height="2" height="0.5" radius-top="0.25" radius-bottom="0.25" position="-5 -0.2 -3.5"></a-cone>

Next, add an ocean, which we will temporarily represent with a box, among your icebergs. In your code, add the following after the cones from above.

<!-- Ocean -->
<a-box depth="50" width="50" height="1" color="#7AD2F7" position="0 -0.5 0"></a-box>

Next, add a platform for our endless runner game to take place on. We will represent this platform using the side of a large cone. After the box above, add the following:

<!-- Platform -->
<a-cone scale="2 2 2" shadow position="0 -3.5 -1.5" rotation="90 0 0" radius-top="1.9" radius-bottom="1.9" segments-radial="20" segments-height="20" height="20" emissive="#005DED" emissive-intensity="0.1">
  <a-entity id="tree-container" position="0 .5 -1.5" rotation="-90 0 0">
  </a-entity>
</a-cone>

Finally, add the player, which we will represent using a small glowing sphere, on the platform we just created. Between the <a-entity id="tree-container" ...></a-entity> tags, add the following:

<a-entity id="tree-container"...>
  <!-- Player -->
  <a-entity id="player" player>
    <a-sphere radius="0.05">
      <a-light type="point" intensity="0.35" color="#FF440C"></a-light>
    </a-sphere>
  </a-entity>
</a-entity>

Check that your code now matches the following, exactly. You can also view the full source code for step 1.

<!DOCTYPE html>
<html>
  <head>
    <title>Ergo | Endless Runner Game in Virtual Reality</title>
    https://aframe.io/releases/0.7.0/aframe.min.js
  </head>
  <body>
    <a-scene fog="type: linear; color: #a3d0ed; near:5; far:20">

      <a-sky color="#a3d0ed"></a-sky>

      <!-- Lights -->
      <a-light type="directional" castShadow="true" intensity="0.4" color="#D0EAF9;" position="5 3 1"></a-light>
      <a-light intensity="0.8" type="ambient" color="#B4C5EC"></a-light>

      <!-- Camera -->
      <a-camera position="0 0 2.5"></a-camera>

      <!-- Icebergs -->
      <a-cone class="iceberg" segments-radial="5" segments-height="3" height="1" radius-top="0.15" radius-bottom="0.5" position="3 -0.1 -1.5"></a-cone>
      <a-cone class="iceberg" segments-radial="7" segments-height="3" height="0.5" radius-top="0.25" radius-bottom="0.35" position="-3 -0.1 -0.5"></a-cone>
      <a-cone class="iceberg" segments-radial="6" segments-height="2" height="0.5" radius-top="0.25" radius-bottom="0.25" position="-5 -0.2 -3.5"></a-cone>

      <!-- Ocean -->
      <a-box depth="50" width="50" height="1" color="#7AD2F7" position="0 -0.5 0"></a-box>

      <!-- Platform -->
      <a-cone scale="2 2 2" shadow position="0 -3.5 -1.5" rotation="90 0 0" radius-top="1.9" radius-bottom="1.9" segments-radial="20" segments-height="20" height="20" emissive="#005DED" emissive-intensity="0.1">
        <a-entity id="tree-container" position="0 .5 -1.5" rotation="-90 0 0">
          <!-- Player -->
          <a-entity id="player" player>
            <a-sphere radius="0.05">
              <a-light type="point" intensity="0.35" color="#FF440C"></a-light>
            </a-sphere>
          </a-entity>
        </a-entity>
      </a-cone>
    </a-scene>
  </body>
</html>

To preview the webpage, click on “Preview” in the top left. We will refer to this as your preview. Note that any changes in your editor will be automatically reflected in this preview, barring bugs or unsupported browsers.


“Show Live” button in glitch project
“Show Live” button in glitch project (Large preview)

In your preview, you will see the following basic virtual reality scene. You can view this scene by using your favorite VR headset.

Animating Ocean and Fixed White Cursor
Animating Ocean and the fixed white cursor (Large preview)

This concludes the first step, setting up the game scene’s basic geometric objects. In the next step, you will add animations and use other A-Frame VR libraries for more visual effects.

Step 2: Improve Aesthetics for Virtual Reality Scene

In this step, you will add a number of aesthetic improvements to the scene:

  1. Low-poly objects
    You will substitute some of the basic geometric objects with their low-poly equivalents for more convincing, irregular geometric shapes.
  2. Animations
    You will have the player bob up and down, move the icebergs slightly, and make the ocean a moving body of water.

Your final product for this step will match the following:

Low-poly icebergs bobbing around
Low-poly icebergs bobbing around (Large preview)

To start, import A-Frame low-poly components. In <head>...</head>, add the following JavaScript import:

The A-Frame low-poly library implements a number primitives, such as lp-cone and lp-sphere, each of which is a low-poly version of an A-Frame primitive. You can learn more about A-Frame primitives over here.

Next, navigate to the <!-- Icebergs --> section of your code. Replace all <a-cone>s with <lp-cone>.

<!-- Icebergs -->
<lp-cone class="iceberg" ...></lp-cone>
<lp-cone class="iceberg" ...></lp-cone>
<lp-cone class="iceberg" ...></lp-cone>

We will now configure the low-poly primitives. All low-poly primitive supports two attributes, which control how exaggerated the low-poly stylization is:

  1. amplitude
    This is the degree of stylization. The greater this number, the more a low-poly shape can deviate from its original geometry.
  2. amplitude-variance
    This is how much stylization can vary, from vertex to vertex. The greater this number, the more variety there is in how much each vertex may deviate from its original geometry.

To get a better intuition for what these two variables mean, you can modify these two attributes in the A-Frame low-poly demo.

For the first iceberg, set amplitude-variance to 0.25. For the second iceberg, set amplitude to 0.12. For the last iceberg, set amplitude to 0.1.

<!-- Icebergs -->
<lp-cone class="iceberg" amplitude-variance="0.25" ...></lp-cone>
<lp-cone class="iceberg" amplitude="0.12" ... ></lp-cone>
<lp-cone class="iceberg" amplitude="0.1" ...></lp-cone>

To finish the icebergs, animate both position and rotation for all three icebergs. Feel free to configure these positions and rotations as desired.

The below features a sample setting:

<lp-cone class="iceberg" amplitude-variance="0.25" ...>
        <a-animation attribute="rotation" from="-5 0 0" to="5 0 0" repeat="indefinite" direction="alternate"></a-animation>
        <a-animation attribute="position" from="3 -0.2 -1.5" to="4 -0.2 -2.5" repeat="indefinite" direction="alternate" dur="12000" easing="linear"></a-animation>
      </lp-cone>
      <lp-cone class="iceberg" amplitude="0.12" ...>
        <a-animation attribute="rotation" from="0 0 -5" to="5 0 0" repeat="indefinite" direction="alternate" dur="1500"></a-animation>
        <a-animation attribute="position" from="-4 -0.2 -0.5" to="-2 -0.2 -0.5" repeat="indefinite" direction="alternate" dur="15000" easing="linear"></a-animation>
      </lp-cone>
      <lp-cone class="iceberg" amplitude="0.1" ...>
        <a-animation attribute="rotation" from="5 0 -5" to="5 0 0" repeat="indefinite" direction="alternate" dur="800"></a-animation>
        <a-animation attribute="position" from="-3 -0.2 -3.5" to="-5 -0.2 -5.5" repeat="indefinite" direction="alternate" dur="15000" easing="linear"></a-animation>
      </lp-cone>

Navigate to your preview, and you should see the low-poly icebergs bobbing around.

Bobbing player with fluctuating light
Bobbing player with fluctuating light (Large preview)

Next, update the platform and associated player. Here, upgrade the cone to a low-poly object, changing a-cone to lp-cone for <!-- Platform -->. Additionally, add configurations for amplitude.

<!-- Platform -->
<lp-cone amplitude="0.05" amplitude-variance="0.05" scale="2 2 2"...>
    ...
</lp-cone>

Next, still within the platform section, navigate to the <!-- Player --> subsection of your code. Add the following animations for position, size, and intensity.

<!-- Player -->
<a-entity id="player" ...>
  <a-sphere ...>
    <a-animation repeat="indefinite" direction="alternate" attribute="position" ease="ease-in-out" from="0 0.5 0.6" to="0 0.525 0.6"></a-animation>
    <a-animation repeat="indefinite" direction="alternate" attribute="radius" from="0.05" to="0.055" dur="1500"></a-animation>
    <a-light ...>
      <a-animation repeat="indefinite" direction="alternate-reverse" attribute="intensity" ease="ease-in-out" from="0.35" to="0.5"></a-animation>
    </a-light>
  </a-sphere>
</a-entity>

Navigate to your preview, and you will see your player bobbing up and down, with a fluctuating light on a low-poly platform.

Bobbing player with fluctuating light
Bobbing player with fluctuating light (Large preview)

Next, let’s animate the ocean. Here, you can use a lightly-modified version of Don McCurdy’s ocean. The modifications allow us to configure how large and fast the ocean’s waves move.

Create a new file via the Glitch interface, by clicking on “+ New File” on the left. Name this new file assets/ocean.js. Paste the following into your new ocean.js file:

/**
 * Flat-shaded ocean primitive.
 * https://github.com/donmccurdy/aframe-extras
 *
 * Based on a Codrops tutorial:
 * http://tympanus.net/codrops/2016/04/26/the-aviator-animating-basic-3d-scene-threejs/
 */
AFRAME.registerPrimitive('a-ocean', {
  defaultComponents: {
    ocean: {},
    rotation: {x: -90, y: 0, z: 0}
  },
  mappings: {
    width: 'ocean.width',
    depth: 'ocean.depth',
    density: 'ocean.density',
    amplitude: 'ocean.amplitude',
    'amplitude-variance': 'ocean.amplitudeVariance',
    speed: 'ocean.speed',
    'speed-variance': 'ocean.speedVariance',
    color: 'ocean.color',
    opacity: 'ocean.opacity'
  }
});

AFRAME.registerComponent('ocean', {
  schema: {
    // Dimensions of the ocean area.
    width: {default: 10, min: 0},
    depth: {default: 10, min: 0},

    // Density of waves.
    density: {default: 10},

    // Wave amplitude and variance.
    amplitude: {default: 0.1},
    amplitudeVariance: {default: 0.3},

    // Wave speed and variance.
    speed: {default: 1},
    speedVariance: {default: 2},

    // Material.
    color: {default: '#7AD2F7', type: 'color'},
    opacity: {default: 0.8}
  },

  /**
   * Use play() instead of init(), because component mappings – unavailable as dependencies – are
   * not guaranteed to have parsed when this component is initialized.
   * /
  play: function () {
    const el = this.el,
        data = this.data;
    let material = el.components.material;

    const geometry = new THREE.PlaneGeometry(data.width, data.depth, data.density, data.density);
    geometry.mergeVertices();
    this.waves = [];
    for (let v, i = 0, l = geometry.vertices.length; i < l; i++) {
      v = geometry.vertices[i];
      this.waves.push({
        z: v.z,
        ang: Math.random() * Math.PI * 2,
        amp: data.amplitude + Math.random() * data.amplitudeVariance,
        speed: (data.speed + Math.random() * data.speedVariance) / 1000 // radians / frame
      });
    }

    if (!material) {
      material = {};
      material.material = new THREE.MeshPhongMaterial({
        color: data.color,
        transparent: data.opacity < 1,
        opacity: data.opacity,
        shading: THREE.FlatShading,
      });
    }

    this.mesh = new THREE.Mesh(geometry, material.material);
    el.setObject3D('mesh', this.mesh);
  },

  remove: function () {
    this.el.removeObject3D('mesh');
  },

  tick: function (t, dt) {
    if (!dt) return;

    const verts = this.mesh.geometry.vertices;
    for (let v, vprops, i = 0; (v = verts[i]); i++){
      vprops = this.waves[i];
      v.z = vprops.z + Math.sin(vprops.ang) * vprops.amp;
      vprops.ang += vprops.speed * dt;
    }
    this.mesh.geometry.verticesNeedUpdate = true;
  }
});

Navigate back to your index.html file. In the <head> of your code, import the new JavaScript file:

 https://cdn.jsdelivr.net...
  http://./assets/ocean.js
</head>

Navigate to the <!-- Ocean --> section of your code. Replace the a-box to an a-ocean. Just as before, we set amplitude and amplitude-variance of our low-poly object.

<!-- Ocean -->
<a-ocean depth="50" width="50" amplitude="0" amplitude-variance="0.1" speed="1.5" speed-variance="1" opacity="1" density="50"></a-ocean>
<a-ocean depth="50" width="50" opacity="0.5" amplitude="0" amplitude-variance="0.15" speed="1.5" speed-variance="1" density="50"></a-ocean>

For your final aesthetic modification, add a white round cursor to indicate where the user is pointing. Navigate to the <!-- Camera -->.

<!-- Camera -->
<a-camera ...>
  <a-entity id="cursor-mobile" cursor="fuse: true; fuseTimeout: 250"
    position="0 0 -1"
    geometry="primitive: ring; radiusInner: 0.02; radiusOuter: 0.03"
    material="color: white; shader: flat"
    scale="0.5 0.5 0.5"
    raycaster="far: 50; interval: 1000; objects: .clickable">
  <a-animation begin="fusing" easing="ease-in" attribute="scale"
    fill="backwards" from="1 1 1" to="0.2 0.2 0.2" dur="250"></a-animation>
  </a-camera>

Ensure that your index.html code matches the Step 2 source code. Navigate to your preview, and you’ll find the updated ocean along with a white circle fixed to the center of your view.

Bobbing player with fluctuating light
Bobbing player with fluctuating light (Large preview)

This concludes your aesthetic improvements to the scene. In this section, you learned how to use and configure low-poly versions of A-Frame primitives, e.g. lp-cone. In addition, you added a number of animations for different object attributes, such as position, rotation, and light intensity. In the next step, you will add the ability for the user to control the player — just by looking at different lanes.

Step 3: Add Virtual Reality Gaze Controls

Recall that our audience is a user wearing a virtual reality headset. As a result, your game cannot depend on keyboard input for controls. To make this game accessible, our VR controls will rely only on the user’s head rotation. Simply look to the right to move the player to the right, look to the center to move to the middle, and look to the left to move to the left. Our final product will look like the following.

Note: The demo GIF below was recorded on a desktop, with user drag as a substitute for head rotation.

Controlling game character with head rotation
Controlling game character with head rotation (Large preview)

Start from your index.html file. In the <head>...</head> tag, import your new JavaScript file, assets/ergo.js. This new JavaScript file will contain the game’s logic.

 http://...
  http://./assets/ergo.js
</head>

Then, add a new lane-controls attribute to your a-camera object:

<!-- Camera -->
<a-camera lane-controls position...>
</a-camera>

Next, create your new JavaScript file using “+ New File” to the left. Use assets/ergo.js for the filename. For the remainder of this step, you will be working in this new JavaScript file. In this new file, define a new function to setup controls, and invoke it immediately. Make sure to include the comments below, as we will refer to sections of code by those names.

/************
 * CONTROLS *
 ************/

function setupControls() {
}

/********
 * GAME *
 ********/

setupControls();

Note: The setupControls function is invoked in the global scope, because A-Frame components must be registered before the <a-scene> tag. I will explain what a component is below.

In your setupControls function, register a new A-Frame component. A component modifies an entity in A-Frame, allowing you to add custom animations, change how an entity initializes, or respond to user input. There are many other use cases, but you will focus on the last one: responding to user input. Specifically, you will read user rotation and move the player accordingly.

In the setupControls function, register the A-Frame component we added to the camera earlier, lane-controls. We will add an event listener for the tick event. This event triggers at every animation frame. In this event listener, hlog output at every tick.

function setupControls() {
    AFRAME.registerComponent('lane-controls', {
        tick: function(time, timeDelta) {
            console.log(time);
        }
    });
}

Navigate to your preview. Open your browser developer console by right-clicking anywhere and selecting “Inspect”. This applies to Firefox, Chrome, and Safari. Then, select “Console” from the top navigation bar. Ensure that you see timestamps flowing into the console.


Timestamps in console
Timestamps in console (Large preview)

Navigate back to your editor. Still in assets/ergo.js, replace the body of setupControls with the following. Fetch the camera rotation using this.el.object3D.rotation, and log the lane to move the player to.

function setupControls() {
  AFRAME.registerComponent('lane-controls', {
    tick: function (time, timeDelta) {
      var rotation = this.el.object3D.rotation;

      if      (rotation.y > 0.1)  console.log("left");
      else if (rotation.y < -0.1) console.log("right");
      else                        console.log("middle");
    }
  })
}

Navigate back to your preview. Again, open your developer console. Try rotating the camera slightly, and observe console output update accordingly.

Lane log based on camera rotation
Lane log based on camera rotation (Large preview)

Before the controls section, add three constants representing the left, middle, and right lane x values.

const POSITION_X_LEFT = -0.5;
const POSITION_X_CENTER = 0;
const POSITION_X_RIGHT = 0.5;

/************
 * CONTROLS *
 ************/

...

At the start of the controls section, define a new global variable representing the player position.

/************
 * CONTROLS *
 ************/

// Position is one of 0 (left), 1 (center), or 2 (right)
var player_position_index = 1;

function setupControls() {
...

After the new global variable, define a new function that will move the player to each lane.

var player_position_index = 1;

/**
 * Move player to provided index
 * @param {int} Lane to move player to
 */
function movePlayerTo(position_index) {
}

function setupControls() {
...

Inside this new function, start by updating the global variable. Then, define a dummy position.

function movePlayerTo(position_index) {
  player_position_index = position_index;

  var position = {x: 0, y: 0, z: 0}
}

After defining the position, update it according to the function input.

function movePlayerTo(position_index) {
  ...
  if      (position_index == 0) position.x = POSITION_X_LEFT;
  else if (position_index == 1) position.x = POSITION_X_CENTER;
  else                          position.x = POSITION_X_RIGHT;
}

Finally, update the player position.

function movePlayerTo(position_index) {
    ...
document.getElementById('player').setAttribute('position', position);
}

Double-check that your function matches the following.

/**
 * Move player to provided index
 * @param {int} Lane to move player to
 */
function movePlayerTo(position_index) {
  player_position_index = position_index;
  
  var position = {x: 0, y: 0, z: 0}
  if      (position_index == 0) position.x = POSITION_X_LEFT;
  else if (position_index == 1) position.x = POSITION_X_CENTER;
  else                          position.x = POSITION_X_RIGHT;
  document.getElementById('player').setAttribute('position', position);
}

Navigate back to your preview. Open the developer console. Invoke your new movePlayerTo function from the console to ensure that it functions.

> movePlayerTo(2)  # should move to right

Navigate back to your editor. For the final step, update your setupControls to move the player depending on camera rotation. Here, we replace the console.log with movePlayerTo invocations.

function setupControls() {
  AFRAME.registerComponent('lane-controls', {
    tick: function (time, timeDelta) {
      var rotation = this.el.object3D.rotation;

      if      (rotation.y > 0.1)  movePlayerTo(0);
      else if (rotation.y < -0.1) movePlayerTo(2);
      else                        movePlayerTo(1);
    }
  })
}

Ensure that your assets/ergo.js matches the corresponding file in the Step 3 source code. Navigate back to your preview. Rotate the camera from side to side, and your player will now track the user’s rotation.

Controlling game character with head rotation
Controlling game character with head rotation (Large preview)

This concludes gaze controls for your virtual reality endless runner game.

In this section, we learned how to use A-Frame components and saw how to modify A-Frame entity properties. This also concludes part 1 of our endless runner game tutorial. You now have a virtual reality model equipped with aesthetic improvements like low-poly stylization and animations, in addition to a virtual-reality-headset-friendly gaze control for players to use.

Conclusion

We created a simple, interactive virtual reality model, as a start for our VR endless runner game. We covered a number of A-Frame concepts such as primitives, animations, and components — all of which are necessary for building a game on top of A-Frame VR.

Here are extra resources and next steps for working more with these technologies:

  • A-Frame VR
    Official documentation for A-Frame VR, covering the topics used above in more detail.
  • A-Frame Homepage
    Examples of A-Frame projects, exhibiting different A-Frame capabilities.
  • Low-Poly Island
    VR model using the same lighting, textures, and animations as the ones used for this endless runner game.

In the next part of this article series, I’ll show you how you can implement the game’s core logic and use more advanced A-Frame VR scene manipulations in JavaScript.

Stay tuned for next week!

Smashing Editorial
(rb, ra, il)

Source: Smashing Magazine, How To Build An Endless Runner Game In Virtual Reality (Part 1)

Building Robust Layouts With Container Units

dreamt up by webguru in Uncategorized | Comments Off on Building Robust Layouts With Container Units

Building Robust Layouts With Container Units

Building Robust Layouts With Container Units

Russell Bishop



Container units are a specialized set of CSS variables that allow you to build grids, layouts, and components using columns and gutters. They mirror the layout functionality found in UI design software where configuring just three values provides your document with a global set of columns and gutters to measure and calculate from.

They also provide consistent widths everywhere in your document — regardless of their nesting depth, their parent’s width, or their sibling elements. So instead of requiring a repeated set of .grid and .row parent elements, container units measure from the :root of your document — just like using a rem unit.

container units measure from the root of your document just like using a rem unit
(Large preview)

What Makes Container Units Different?

Grids from popular frameworks (such as Bootstrap or Bulma) share the same fundamental limitation: they rely on relative units such as ‘percentages’ to build columns and gutters.

This approach ties developers to using a specific HTML structure whenever they want to use those measurements and requires parent > child nesting for widths to calculate correctly.

Not convinced? Try for yourself:

  • Open any CSS framework’s grid demo;
  • Inspect a column and note the width;
  • Using DevTools, drag that element somewhere else in the document;
  • Note that the column’s width has changed in transit.

Freedom Of Movement (…Not Brexit)

Container units allow you more freedom to size elements using a set of global units. If you want to build a sidebar the width of three columns, all you need is the following:

.sidebar {
  width: calc(3 * var(--column-unit));
  /* or columns(3) */
}

Your ...class="sidebar">... element can live anywhere inside of your document — without specific parent elements or nesting.

Measuring three columns and using them for a sidebar.
Measuring three columns and using them for a sidebar (Large preview)

Sharing Tools With Designers

Designers and developers have an excellent middle-ground that helps translate from design software to frontend templates: numbers.

Modular scales are exceptional not just because they help designers bring harmony to their typography, but also because developers can replicate them as a simple system. The same goes for Baseline Grids: superb, self-documenting systems with tiny configuration (one root number) and massive consistency.

Container units are set up in the same way that designers use Sketch to configure Layout Settings:


Layout settings
Layout settings (Large preview)

Sketch gridlines
Sketch gridlines (Large preview)

Any opportunity for designers and developers to build with the same tools is a huge efficiency boost and fosters new thinking in both specialisms.

Start Building With Container Units

Define your grid proportions with three values:

:root {
  --grid-width: 960;
  --grid-column-width: 60;
  --grid-columns: 12;
}

These three values define how wide a column is in proportion to your grid. In the example above, a column’s width is 60 / 960. Gutters are calculated automatically from the remaining space.

Finally, set a width for your container:

:root {
  --container-width: 84vw;
}

Note: --container-width should be set as an absolute unit. I recommend using viewport units or rems.

You can update your --container-width at any breakpoint (all of your container units will update accordingly):

@media (min-width: 800px) {
  --container-width: 90vw;
}
    
@media (min-width: 1200px) {
  --container-width: 85vw;
}
    
/* what about max-width? */
@media (min-width: 1400px) {
  --container-width: 1200px;
}
breakpoints
Breakpoints (Large preview)

You’ve now unlocked two very robust units to build from:

  1. --column-unit
  2. --gutter-unit

Column Spans: The Third And Final Weapon

More common than building with either columns or gutters is to span across both of them:

6 column span = 6 columns + 5 gutters
6 column span = 6 columns + 5 gutters (Large preview)

Column spans are easy to calculate, but not very pretty to write. For spanning across columns, I would recommend using a pre-processor:

.panel {
  /* vanilla css */
  width: calc(6 * var(--column-and-gutter-unit) - var(--gutter-unit));
  
  /* pre-processor shortcut */
  width: column-spans(6);  
}

Of course, you can use pre-processor shortcuts for every container unit I’ve mentioned so far. Let’s put them to the test with a design example.

Building Components With Container Units

Let’s take a design example and break it down:


design example
(Large preview)

This example uses columns, gutters and column spans. Since we’re just storing a value, container units can be used for other CSS properties, like defining a height or providing padding:

.background-image {
  width: column-spans(9);
  padding-bottom: gutters(6);
  /* 6 gutters taller than the foreground banner */
}

.foreground-banner {
  width: column-spans(8);
  padding: gutters(2);
}

.button {
  height: gutters(3);
  padding: gutters(1);
}

Grab The Code

:root {
  /* Grid proportions */
  --grid-width: 960;
  --grid-column-width: 60;
  --grid-columns: 12;

  /* Grid logic */
  --grid-gutters: calc(var(--grid-columns) - 1);

  /* Grid proportion logic */
  --column-proportion: calc(var(--grid-column-width) / var(--grid-width));
  --gutter-proportion: calc((1 - (var(--grid-columns) * var(--column-proportion))) / var(--grid-gutters));

  /* Container Units */
  --column-unit: calc(var(--column-proportion) * var(--container-width));
  --gutter-unit: calc(var(--gutter-proportion) * var(--container-width));
  --column-and-gutter-unit: calc(var(--column-unit) + var(--gutter-unit));

  /* Container Width */
  --container-width: 80vw;
}

@media (min-width: 1000px) {
  :root {
    --container-width: 90vw;
  }
}

@media (min-width: 1400px) {
  :root {
    --container-width: 1300px;
  }
}

Why Use CSS Variables?

“Pre-processors have been able to do that for years with $variables — why do you need CSS variables?”

Not… quite. Although you can use variables to run calculations, you cannot avoid compiling unnecessary code when one of the variables updates it’s value.

Let’s take the following condensed example of a grid:

.grid {
  $columns: 2;
  $gutter: $columns * 1rem;
  display: grid;
  grid-template-columns: repeat($columns, 1fr);
  grid-gap: $gutter;

  @media (min-width: $medium) {
    $columns: 3;
    grid-template-columns: repeat($columns, 1fr);
    grid-gap: $gutter;
  }
  
  @media (min-width: $large) {
    $columns: 4;
    grid-template-columns: repeat($columns, 1fr);
    grid-gap: $gutter;
  }
}

This example shows how every reference to a SASS/LESS variable has to be re-compiled if the variable changes — duplicating code over and over for each instance.

But CSS Variables share their logic with the browser, so browsers can do the updating for you.

.grid {
  --columns: 2;
  --gutter: calc(var(--columns) * 1rem);
  display: grid;
  grid-template-columns: repeat(var(--columns), 1fr);
  grid-gap: var(--gutter);

  @media (min-width: $medium) {
    --columns: 3;
  }
  
  @media (min-width: $large) {
    --columns: 4;
  }
}

This concept helps form the logic of container units; by storing logic once at the root, every element in your document watches those values as they update, and responds accordingly.

Give it a try!

Recommended Reading

Smashing Editorial
(dm, ra, il)

Source: Smashing Magazine, Building Robust Layouts With Container Units

Using Composer With WordPress

dreamt up by webguru in Uncategorized | Comments Off on Using Composer With WordPress

Using Composer With WordPress

Using Composer With WordPress

Leonardo Losoviz



WordPress is getting modernized. The recent inclusion of JavaScript-based Gutenberg as part of the core has added modern capabilities for building sites on the frontend, and the upcoming bump of PHP’s minimum version, from the current 5.2.4 to 5.6 in April 2019 and 7.0 in December 2019, will make available a myriad of new features to build powerful sites.

In my previous article on Smashing in which I identified the PHP features newly available to WordPress, I argued that the time is ripe to make components the basic unit for building functionalities in WordPress. On one side, Gutenberg already makes the block (which is a high-level component) the basic unit to build the webpage on the frontend; on the other side, by bumping up the required minimum version of PHP, the WordPress backend has access to the whole collection of PHP’s Object-Oriented Programming features (such as classes and objects, interfaces, traits and namespaces), which are all part of the toolset to think/code in components.

So, why components? What’s so great about them? A “component” is not an implementation (such as a React component), but instead, it’s a concept: It represents the act of encapsulating properties inside objects, and grouping objects together into a package which solves a specific problem. Components can be implemented for both the frontend (like those coded through JavaScript libraries such as React or Vue, or CSS component libraries such as Bootstrap) and the backend.

We can use already-created components and customize them for our projects, so we will boost our productivity by not having to reinvent the wheel each single time, and because of their focus on solving a specific issue and being naturally decoupled from the application, they can be tested and bug-fixed very easily, thus making the application more maintainable in the long term.

The concept of components can be employed for different uses, so we need to make sure we are talking about the same use case. In a previous article, I described how to componentize a website; the goal was to transform the webpage into a series of components, wrapping each other from a single topmost component all the way down to the most basic components (to render the layout). In that case, the use case for the component is for rendering — similar to a React component but coded in the backend. In this article, though, the use case for components is importing and managing functionality into the application.

Introduction To Composer And Packagist

To import and manage own and third-party components into our PHP projects, we can rely on the PHP-dependency manager Composer which by default retrieves packages from the PHP package repository Packagist (where a package is essentially a directory containing PHP code). With their ease of use and exceptional features, Composer + Packagist have become key tools for establishing the foundations of PHP-based applications.

Composer allows to declare the libraries the project depends on and it will manage (install/update) them. It works recursively: libraries depended-upon by dependencies will be imported to the project and managed too. Composer has a mechanism to resolve conflicts: If two different libraries depend on a different version of a same library, Composer will try to find a version that is compatible with both requirements, or raise an error if not possible.

To use Composer, the project simply needs a composer.json file in its root folder. This file defines the dependencies of the project (each for a specific version constraint based on semantic versioning) and may contain other metadata as well. For instance, the following composer.json file makes a project require nesbot/carbon, a library providing an extension for DateTime, for the latest patch of its version 2.12:

{
    "require": {
        "nesbot/carbon": "2.12.*"
    }
}

We can edit this file manually, or it can be created/updated through commands. For the case above, we simply open a terminal window, head to the project’s root directory, and type:

composer require "nesbot/carbon"

This command will search for the required library in Packagist (which is found here) and add its latest version as a dependency on the existing composer.json file. (If this file doesn’t yet exist, it will first create it.) Then, we can import the dependencies into the project, which are by default added under the vendor/ folder, by simply executing:

composer install

Whenever a dependency is updated, for instance nesbot/carbon released version 2.12.1 and the currently installed one is 2.12.0, then Composer will take care of importing the corresponding library by executing:

composer update

If we are using Git, we only have to specify the vendor/ folder on the .gitignore file to not commit the project dependencies under version control, making it a breeze to keep our project’s code thoroughly decoupled from external libraries.

Composer offers plenty of additional features, which are properly described in the documentation. However, already in its most basic use, Composer gives developers unlimited power for managing the project’s dependencies.

Introduction To WPackagist

Similar to Packagist, WPackagist is a PHP package repository. However, it comes with one particularity: It contains all the themes and plugins hosted on the WordPress plugin and theme directories, making them available to be managed through Composer.

To use WPackagist, our composer.json file must include the following information:

{
    "repositories":[
        {
            "type":"composer",
            "url":"https://wpackagist.org"
        }
    ]
}

Then, any theme and plugin can be imported to the project by using "wpackagist-theme" and "wpackagist-plugin" respectively as the vendor name, and the slug of the theme or plugin under the WordPress directory (such as "akismet" in https://wordpress.org/plugins/akismet/) as the package name. Because themes do not have a trunk version, then the theme’s version constraint is recommended to be “*”:

{
    "require": {
        "wpackagist-plugin/akismet":"^4.1",
        "wpackagist-plugin/bbpress":">=2.5.12",
        "wpackagist-theme/twentynineteen":"*"
    }
}

Packages available in WPackagist have been given the type “wordpress-plugin” or “wordpress-theme”. As a consequence, after running composer update, instead of installing the corresponding themes and plugins under the default folder vendor/, these will be installed where WordPress expects them: under folders wp-content/themes/ and wp-content/plugins/ respectively.

Possibilities And Limitations Of Using WordPress And Composer Together

So far, so good: Composer makes it a breeze to manage a PHP project’s dependencies. However, WordPress’ core hasn’t adopted it as its dependency management tool of choice, primarily because WordPress is a legacy application that was never designed to be used with Composer, and the community can’t agree if WordPress should be considered the site or a site’s dependency, and integrating these approaches requires hacks.

In this concern, WordPress is outperformed by newer frameworks which could incorporate Composer as part of their architecture. For instance, Laravel underwent a major rewriting in 2013 to establish Composer as an application-level package manager. As a consequence, WordPress’ core still does not include the composer.json file required to manage WordPress as a Composer dependency.

Knowing that WordPress can’t be natively managed through Composer, let’s explore the ways such support can be added, and what roadblocks we encounter in each case.

There are three basic ways in which WordPress and Composer can work together:

  1. Manage dependencies when developing a theme or a plugin;
  2. Manage themes and plugins on a site;
  3. Manage the site completely (including its themes, plugins and WordPress’ core).

And there are two basic situations concerning who will have access to the software (a theme or plugin, or the site):

  1. The developer can have absolute control of how the software will be updated, e.g. by managing the site for the client, or providing training on how to do it;
  2. The developer doesn’t have absolute control of the admin user experience, e.g. by releasing themes or plugins through the WordPress directory, which will be used by an unknown party.

From the combination of these variables, we will have more or less freedom in how deep we can integrate WordPress and Composer together.

From a philosophical aspect concerning the objective and target group of each tool, while Composer empowers developers, WordPress focuses primarily on the needs of the end users first, and only then on the needs of the developers. This situation is not self-contradictory: For instance, a developer can create and launch the website using Composer, and then hand the site over to the end user who (from that moment on) will use the standard procedures for installing themes and plugins — bypassing Composer. However, then the site and its composer.json file fall out of sync, and the project can’t be managed reliably through Composer any longer: Manually deleting all plugins from the wp-content/plugins/ folder and executing composer update will not re-download those plugins added by the end user.

The alternative to keeping the project in sync would be to ask the user to install themes and plugins through Composer. However, this approach goes against WordPress’ philosophy: Asking the end user to execute a command such as composer install to install the dependencies from a theme or plugin adds friction, and WordPress can’t expect every user to be able to execute this task, as simple as it may be. So this approach can’t be the default; instead, it can be used only if we have absolute control of the user experience under wp-admin/, such as when building a site for our own client and providing training on how to update the site.

The default approach, which handles the case when the party using the software is unknown, is to release themes and plugins with all of their dependencies bundled in. This implies that the dependencies must also be uploaded to WordPress’ plugin and theme subversion repositories, defeating the purpose of Composer. Following this approach, developers are still able to use Composer for development, however, not for releasing the software.

This approach is not failsafe either: If two different plugins bundle different versions of a same library which are incompatible with each other, and these two plugins are installed on the same site, it could cause the site to malfunction. A solution to this issue is to modify the dependencies’ namespace to some custom namespace, which ensures that different versions of the same library, by having different namespaces, are treated as different libraries. This can be achieved through a custom script or through Mozart, a library which composes all dependencies as a package inside a WordPress plugin.

For managing the site completely, Composer must install WordPress under a subdirectory as to be able to install and update WordPress’ core without affecting other libraries, hence the setup must consider WordPress as a site’s dependency and not the site itself. (Composer doesn’t take a stance: This decision is for the practical purpose of being able to use the tool; from a theoretical perspective, we can still consider WordPress to be the site.) Because WordPress can be installed in a subdirectory, this doesn’t represent a technical issue. However, WordPress is by default installed on the root folder, and installing it in a subdirectory involves a conscious decision taken by the user.

To make it easier to completely manage WordPress with Composer, several projects have taken the stance of installing WordPress in a subfolder and providing an opinionated composer.json file with a setup that works well: core contributor John P. Bloch provides a mirror of WordPress’ core, and Roots provides a WordPress boilerplate called Bedrock. I will describe how to use each of these two projects in the sections below.

Managing The Whole WordPress Site Through John P. Bloch’s Mirror Of WordPress Core

I have followed Andrey “Rarst” Savchenko’s recipe for creating the whole site’s Composer package, which makes use of John P. Bloch’s mirror of WordPress’ core. Following, I will reproduce his method, adding some extra information and mentioning the gotchas I found along the way.

First, create a composer.json file with the following content in the root folder of your project:

{
    "type": "project",
    "config": {
        "vendor-dir": "content/vendor"
    },
    "extra": {
        "wordpress-install-dir": "wp"
    },
    "require": {
        "johnpbloch/wordpress": ">=5.1"
    }
}

Through this configuration, Composer will install WordPress 5.1 under folder "wp", and dependencies will be installed under folder "content/vendor". Then head to the project’s root folder in terminal and execute the following command for Composer to do its magic and install all dependencies, including WordPress:

composer install --prefer-dist

Let’s next add a couple of plugins and the theme, for which we must also add WPackagist as a repository, and let’s configure these to be installed under "content/plugins" and "content/themes" respectively. Because these are not the default locations expected by WordPress, we will later on need to tell WordPress where to find them through constant WP_CONTENT_DIR.

Note: WordPress’ core includes by default a few themes and plugins under folders "wp/wp-content/themes" and "wp/wp-content/plugins", however, these will not be accessed.

Add the following content to composer.json, in addition to the previous one:

{
    "repositories": [
        {
            "type": "composer",
            "url" : "https://wpackagist.org"
        }
    ],
    "require": {
        "wpackagist-plugin/wp-super-cache": "1.6.*",
        "wpackagist-plugin/bbpress": "2.5.*",
        "wpackagist-theme/twentynineteen": "*"
    },
    "extra": {
        "installer-paths": {
            "content/plugins/{$name}/": ["type:wordpress-plugin"],
            "content/themes/{$name}/": ["type:wordpress-theme"]
        }
    }
}

And then execute in terminal:

composer update --prefer-dist

Hallelujah! The theme and plugins have been installed! Since all dependencies are distributed across folders wp, content/vendors, content/plugins and content/themes, we can easily ignore these when committing our project under version control through Git. For this, create a .gitignore file with this content:

wp/
content/vendor/
content/themes/
content/plugins/

Note: We could also directly ignore folder content/, which will already ignore all media files under content/uploads/ and files generated by plugins, which most likely must not go under version control.

There are a few things left to do before we can access the site. First, duplicate the wp/wp-config-sample.php file into wp-config.php (and add a line with wp-config.php to the .gitignore file to avoid committing it, since this file contains environment information), and edit it with the usual information required by WordPress (database information and secret keys and salts). Then, add the following lines at the top of wp-config.php, which will load Composer’s autoloader and will set constant WP_CONTENT_DIR to folder content/:

// Load Composer’s autoloader
require_once (__DIR__.'/content/vendor/autoload.php');

// Move the location of the content dir
define('WP_CONTENT_DIR', dirname(__FILE__).'/content');

By default, WordPress sets constant WP_CONSTANT_URL with value get_option('siteurl').'/wp-content'. Because we have changed the content directory from the default "wp-content" to "content", we must also set the new value for WP_CONSTANT_URL. To do this, we can’t reference function get_option since it hasn’t been defined yet, so we must either hardcode the domain or, possibly better, we can retrieve it from $_SERVER like this:

$s = empty($_SERVER["HTTPS"]) ? '' : ($_SERVER["HTTPS"] == "on") ? "s" : "";
$sp = strtolower($_SERVER["SERVER_PROTOCOL"]);
$protocol = substr($sp, 0, strpos($sp, "/")) . $s;
$port = ($_SERVER["SERVER_PORT"] == "80") ? "" : (":".$_SERVER["SERVER_PORT"]);
define('WP_CONTENT_URL', $protocol."://".$_SERVER[’SERVER_NAME'].$port.'/content');

We can now access the site on the browser under domain.com/wp/, and proceed to install WordPress. Once the installation is complete, we log into the Dashboard and activate the theme and plugins.

Finally, because WordPress was installed under subdirectory wp, the URL will contain path “/wp” when accessing the site. Let’s remove that (not for the admin side though, which by being accessed under /wp/wp-admin/ adds an extra level of security to the site).

The documentation proposes two methods to do this: with or without URL change. I followed both of them, and found the without URL change a bit unsatisfying because it requires specifying the domain in the .htaccess file, thus mixing application code and configuration information together. Hence, I’ll describe the method with URL change.

First, head to “General Settings” which you’ll find under domain.com/wp/wp-admin/options-general.php and remove the “/wp” bit from the “Site Address (URL)” value and save. After doing so, the site will be momentarily broken: browsing the homepage will list the contents of the directory, and browsing a blog post will return a 404. However, don’t panic, this will be fixed in the next step.

Next, we copy the index.php file to the root folder, and edit this new file, adding “wp/” to the path of the required file, like this:

/** Loads the WordPress Environment and Template */
require( dirname( __FILE__ ) . '/wp/wp-blog-header.php' );

We are done! We can now access our site in the browser under domain.com:


WordPress site
WordPress site successfully installed through Composer (Large preview)

Even though it has downloaded the whole WordPress core codebase and several libraries, our project itself involves only six files from which only five need to be committed to Git:

  1. .gitignore
  2. composer.json
  3. composer.lock
    This file is generated automatically by Composer, containing the versions of all installed dependencies.
  4. index.php
    This file is created manually.
  5. .htaccess
    This file is automatically created by WordPress, so we could avoid committing it, however, we may soon customize it for the application, in which case it requires committing.

The remaining sixth file is wp-config.php which must not be committed since it contains environment information.

Not bad!

The process went pretty smoothly, however, it could be improved if the following issues are dealt better:

  1. Some application code is not committed under version control.
    Since it contains environment information, the wp-config.php file must not be committed to Git, instead requiring to maintain a different version of this file for each environment. However, we also added a line of code to load Composer’s autoloader in this file, which will need to be replicated for all versions of this file across all environments.
  2. The installation process is not fully automated.
    After installing the dependencies through Composer, we must still install WordPress through its standard procedure, log-in to the Dashboard and change the site URL to not contain “wp/”. Hence, the installation process is slightly fragmented, involving both a script and a human operator.

Let’s see next how Bedrock fares for the same task.

Managing The Whole WordPress Site Through Bedrock

Bedrock is a WordPress boilerplate with an improved folder structure, which looks like this:

├── composer.json
├── config
│   ├── application.php
│   └── environments
│       ├── development.php
│       ├── staging.php
│       └── production.php
├── vendor
└── web
    ├── app
    │   ├── mu-plugins
    │   ├── plugins
    │   ├── themes
    │   └── uploads
    ├── wp-config.php
    ├── index.php
    └── wp

The people behind Roots chose this folder structure in order to make WordPress embrace the Twelve Factor App, and they elaborate how this is accomplished through a series of blog posts. This folder structure can be considered an improvement over the standard WordPress one on the following accounts:

  • It adds support for Composer by moving WordPress’ core out of the root folder and into folder web/wp;
  • It enhances security, because the configuration files containing the database information are not stored within folder web, which is set as the web server’s document root (the security threat is that, if the web server goes down, there would be no protection to block access to the configuration files);
  • The folder wp-content has been renamed as “app”, which is a more standard name since it is used by other frameworks such as Symfony and Rails, and to better reflect the contents of this folder.

Bedrock also introduces different config files for different environments (development, staging, production), and it cleanly decouples the configuration information from code through library PHP dotenv, which loads environment variables from a .env file which looks like this:

DB_NAME=database_name
DB_USER=database_user
DB_PASSWORD=database_password

# Optionally, you can use a data source name (DSN)
# When using a DSN, you can remove the DB_NAME, DB_USER, DB_PASSWORD, and DB_HOST variables
# DATABASE_URL=mysql://database_user:database_password@database_host:database_port/database_name

# Optional variables
# DB_HOST=localhost
# DB_PREFIX=wp_

WP_ENV=development
WP_HOME=http://example.com
WP_SITEURL=${WP_HOME}/wp

# Generate your keys here: https://roots.io/salts.html
AUTH_KEY='generateme'
SECURE_AUTH_KEY='generateme'
LOGGED_IN_KEY='generateme'
NONCE_KEY='generateme'
AUTH_SALT='generateme'
SECURE_AUTH_SALT='generateme'
LOGGED_IN_SALT='generateme'
NONCE_SALT='generateme'

Let’s proceed to install Bedrock, following their instructions. First create a project like this:

composer create-project "roots/bedrock"

This command will bootstrap the Bedrock project into a new folder “bedrock”, setting up the folder structure, installing all the initial dependencies, and creating an .env file in the root folder which must contain the site’s configuration. We must then edit the .env file to add the database configuration and secret keys and salts, as would normally be required in wp-config.php file, and also to indicate which is the environment (development, staging, production) and the site’s domain.

Next, we can already add themes and plugins. Bedrock comes with themes twentyten to twentynineteen shipped by default under folder web/wp/wp-content/themes, but when adding more themes through Composer these are installed under web/app/themes. This is not a problem, because WordPress can register more than one directory to store themes through function register_theme_directory.

Bedrock includes the WPackagist information in the composer.json file, so we can already install themes and plugins from this repository. To do so, simply step on the root folder of the project and execute the composer require command for each theme and plugin to install (this command already installs the dependency, so there is no need to execute composer update):

cd bedroot
composer require "wpackagist-theme/zakra"
composer require "wpackagist-plugin/akismet":"^4.1"
composer require "wpackagist-plugin/bbpress":">=2.5.12"

The last step is to configure the web server, setting the document root to the full path for the web folder. After this is done, heading to domain.com in the browser we are happily greeted by WordPress installation screen. Once the installation is complete, we can access the WordPress admin under domain.com/wp/wp-admin and activate the installed theme and plugins, and the site is accessible under domain.com. Success!

Installing Bedrock was pretty smooth. In addition, Bedrock does a better job at not mixing the application code with environment information in the same file, so the issue concerning application code not being committed under version control that we got with the previous method doesn’t happen here.

Conclusion

With the launch of Gutenberg and the upcoming bumping up of PHP’s minimum required version, WordPress has entered an era of modernization which provides a wonderful opportunity to rethink how we build WordPress sites to make the most out of newer tools and technologies. Composer, Packagist, and WPackagist are such tools which can help us produce better WordPress code, with an emphasis on reusable components to produce modular applications which are easy to test and bugfix.

First released in 2012, Composer is not precisely what we would call “new” software, however, it has not been incorporated to WordPress’ core due to a few incompatibilities between WordPress’ architecture and Composer’s requirements. This issue has been an ongoing source of frustration for many members of the WordPress development community, who assert that the integration of Composer into WordPress will enhance creating and releasing software for WordPress. Fortunately, we don’t need to wait until this issue is resolved since several actors took the matter into their own hands to provide a solution.

In this article, we reviewed two projects which provide an integration between WordPress and Composer: manually setting our composer.json file depending on John P. Bloch’s mirror of WordPress’ core, and Bedrock by Roots. We saw how these two alternatives, which offer a different amount of freedom to shape the project’s folder structure, and which are more or less smooth during the installation process, can succeed at fulfilling our requirement of completely managing a WordPress site, including the installation of the core, themes, and plugins.

If you have any experience using WordPress and Composer together, either through any of the described two projects or any other one, I would love to see your opinion in the comments below.

I would like to thank Andrey “Rarst” Savchenko, who reviewed this article and provided invaluable feedback.

Further Reading on SmashingMag:

Smashing Editorial
(rb, ra, il)

Source: Smashing Magazine, Using Composer With WordPress

Organizing Brainstorming Workshops: A Designer’s Guide

dreamt up by webguru in Uncategorized | Comments Off on Organizing Brainstorming Workshops: A Designer’s Guide

Organizing Brainstorming Workshops: A Designer’s Guide

Organizing Brainstorming Workshops: A Designer’s Guide

Slava Shestopalov



When you think about the word “brainstorming”, what do you imagine? Maybe a crowd of people who you used to call colleagues, outshouting each other, assaulting the whiteboard, and nearly throwing punches to win control over the projector? Fortunately, brainstorming has a bright side: It’s a civilized process of generating ideas together. At least this is how it appears in the books on creativity. So, can we make it real?

I have already tried the three methodologies presented in this article with friends of mine, so there is no theorizing. After reaching the end of this article, I hope that you’ll be able to organize brainstorming sessions with your colleagues and clients, and co-create something valuable. For instance, ideas about a new mobile application or a design conference agenda.

Building Diverse Design Teams

What is diversity and what does it have to do with design? It’s important to understand that design is not only critical to solving problems on the product and experience level, but also relevant on a bigger scale to close social divides and to create inclusive communities. Learn more →

Universal Principles

Don’t be surprised to notice all brainstorming techniques have much in common. Although “rituals” vary, the essence is the same. Participants look at the subject from different sides and come up with ideas. They write their thoughts down and then make sorting or prioritizing. I know, sounds easy as pie, doesn’t it? But here’s the thing. Without the rules of the game, brainstorming won’t work. It all boils down to just three crucial principles:

  1. The more, the better.
    Brainstorming aims at the quantity, which later turns into quality. The more ideas a team generates the wider choice it gains. It’s normal when two or more participants say the same thing. It’s normal if some ideas are funny. A facilitator’s task is encouraging people to share what is hidden in their mind.
  2. No criticism.
    The goal of brainstorming is to generate a pool of ideas. All ideas are welcome. A boss has no right to silence a subordinate. An analyst shouldn’t make fun of a colleague’s “fantastic” vision. A designer shouldn’t challenge the usability of a teammates’ suggestion.
  3. Follow the steps.
    Only a goal-oriented and time-bound activity is productive, whereas uncontrolled bursts of creativity, as a rule, fail. To make a miracle happen, organize the best conditions for it.

Here are the universal slides you can use as an introduction to any brainstorming technique.


Examples of slides that describe the three core brainstorming rules
(Large preview)

Now when the principles are clear, you are to decide who’s going to participate. The quick answer is diversity. Invite as many different experts as possible including business owners, analysts, marketers, developers, salespeople, potential or real users. All participants should be related to the subject or be interested in it. Otherwise, they’ll fantasize about the topic they’ve never dealt with and don’t want to.

One more thing before we proceed with the three techniques (Six Thinking Hats, Walt Disney’s Creative Strategy, and SCAMPER). When can a designer or other specialist use brainstorming? Here are two typical cases:

  1. There is a niche for a new product, service or feature but the team doesn’t have a concept of what it might be.
  2. An existing product or service is not as successful as expected. The team generally understands the reasons but has no ideas on how to fix it.

1. Six Thinking Hats

The first technique I’d like to present is known as “Six Thinking Hats”. It was invented in 1985 by Edward de Bono, a Maltese physician, psychologist, and consultant. Here’s a quick overview:

Complexity Normal
Subject A process, a service, a product, a feature, anything. For example, one of the topics at our session was the improvement of the designers’ office infrastructure. Another team brainstormed about how to improve the functionality of the Sketch app.
Duration 1–1.5 hours
Facilitation One facilitator for a group of 5–8 members. If there are more people, better divide them into smaller groups and involve assistants. We split our design crew of over 20 people into three workgroups, which were working simultaneously on their topics.

A photo of the brainstorming session using the Six Thinking Hats technique
Brainstorming workshop for the ELEKS design team (Large preview)

Materials

  • Slides with step-by-step instructions.
  • A standalone timer or laptop with an online timer in the fullscreen mode.
  • 6 colored paper hats or any recognizable hat symbols for each participant. The colors are blue, yellow, green, white, red, and black. For example, we used crowns instead of hats, and it was fun.
  • Sticky notes of 6 colors: blue, yellow, green, white, red, and brown or any other dark tint for representing black. 1–2 packs of each color per team of 5–8 people would be enough.
  • A whiteboard or a flip-chart or a large sheet of paper on a table or wall.
  • Black marker pens for each participant (markers should be whiteboard-safe if you choose this kind of surface).

Process

Start a brainstorming session with a five-minute intro. What will participants do? Why is it important? What will the outcome be? What’s next? It’s time to explain the steps. In my case, we described the whole process beforehand to ensure people get the concept of “thinking hats.” De Bono’s “hat” represents a certain way of perceiving reality. Different people are used to “wearing” one favorite “hat” most of the time, which limits creativity and breeds stereotypes.

For example, risk analysts are used to finding weaknesses and threats. That’s why such a phenomenon as gut feeling usually doesn’t ring them a bell.


A set of slide samples for conducting a brainstorming session due to the method of Six Thinking Hats
(Large preview)

Trying on “hats” is a metaphor that helps people to start thinking differently with ease. Below is an example of the slides that explain what each “hat” means. Our goal was to make people feel prepared, relaxed, and not afraid of the procedure complexity.


A set of slide samples for conducting a brainstorming session due to the method of Six Thinking Hats
(Large preview)

The blue “hat” is an odd one out. It has an auxiliary role and embodies the process of brainstorming itself. It starts the session and finishes it. White, yellow, black, red, and green “hats” represent different ways to interpret reality.

For example, the red one symbolizes intuitive and emotional perception. When the black “hat” is on, participants wake up their inner “project manager” and look at the subject through the concepts of budgets, schedule, cost, and revenue.

There are various schemas of “hats” depending on the goal. We wanted to try all the “hats” and chose a universal, all-purpose order:

Blue Preparation
White Collecting available and missing data
Red Listening to emotions and unproven thoughts
Yellow Noticing what is good right now
Green Thinking about improvements and innovations
Black Analyzing risks and resources
Blue Summarizing

A set of slide samples for conducting a brainstorming session due to the method of Six Thinking Hats
(Large preview)

Now the exercise itself. Each slide is a cheat sheet with a task and prompts. When a new step starts and a proper slide appears on the screen, a facilitator starts the timer. Some steps have an extended duration; other steps require less time. For instance, it’s easy to agree on a topic formulation and draw a canvas but writing down ideas is a more time-consuming activity.

When participants see a “hat” slide (except the blue one), they are to generate ideas, write them on sticky notes and put the notes on the whiteboard, flip-chart or paper sheet. For example, the yellow “hat” is displayed on the screen. People put on yellow paper hats and think about the benefits and nice features the subject has now and why it may be useful or attractive. They concisely write these thoughts on the sticky notes of a corresponding color (for the black “hat” — any dark color can be used so that you don’t need to buy special white markers). All the sticky notes of the same color should be put in the corresponding column of the canvas.


A set of slide samples for conducting a brainstorming session due to the method of Six Thinking Hats
(Large preview)

The last step doesn’t follow the original technique. We thought it would be pointless to stick dozens of colored notes and call it a day. We added the Affinity sorting part aimed at summarizing ideas and making the moment of their implementation a bit closer. The teams had to find notes about similar things, group them into clusters and give a name to each cluster.

For example, in the topic “Improvement of the designers’ office infrastructure,” my colleagues created such clusters as “Chair ergonomics,” “Floor and walls,” “Hardware upgrade.”


A set of slide samples for conducting a brainstorming session due to the method of Six Thinking Hats
(Large preview)

We finished the session with the mini-presentations of findings. A representative from each team listed the clusters they came up with and shared the most exciting observation or impression.

Walt Disney’s Creative Strategy

Walt Disney’s creative method was discovered and modeled by Robert Dilts, a neuro-linguistic programming expert, in 1994. Here’s an overview:

Complexity Easy
Subject Anything, especially projects you’ve been postponing for a long time or dreams you cannot start fulfilling for unknown reasons. For example, one of the topics I dealt with was “Improvement of the designer-client communication process.”
Duration 1 hour
Facilitation One facilitator for a group of 5–8 members. When we conducted an educational workshop on brainstorming, my co-trainers and I had four teams of six members working simultaneously in the room.

A photo of the brainstorming session using Walt Disney's Creative Strategy
Educational session on brainstorming for the Projector Design School (Large preview)

Materials

  • Slides with step-by-step instructions.
  • A standalone timer or laptop with an online timer in the fullscreen mode.
  • Standard or large yellow sticky notes (1–2 packs per team of 5–8 people).
  • Small red sticky notes (1–2 packs per team).
  • The tiniest sticky stripes or sticky dots for voting (1 pack per team).
  • A whiteboard or a flip-chart or a large sheet of paper on a table or wall.
  • Black marker pens for each participant (markers should be whiteboard-safe if you choose this kind of surface).

Process

This technique is called after the original thinking manner of Walt Disney, a famous animator and film producer. Disney didn’t use any “technique”; his creative process was intuitive yet productive. Robert Dilts, a neuro-linguistic programming expert, discovered this creative knowhow much later based on the memories of Disney’s colleagues. Although original Dilts’s concept is designed for personal use, we managed to turn it into a group format.


Slide examples for conducting a rainstorming workshop according to Walt Disney's Strategy
(Large preview)

Disney’s strategy works owing to the strict separation of three roles — the dreamer, the realist, and the critic. People are used to mixing these roles while thinking about the future, and that’s why they often fail. “Let’s do X. But it’s so expensive. And risky… Maybe later,” this is how an average person dreams. As a result, innovative ideas get buried in doubts and fears.

In this kind of brainstorming, the facilitator’s goal is to prevent participants from mixing the roles and nipping creative ideas in the bud. We helped the team to get into the mood and extract pure roles through open questions on the slides and introductory explanations.


Slide examples for conducting a rainstorming workshop according to Walt Disney's Strategy
(Large preview)

For example, here is my intro to the first role:

“The dreamer is not restrained by limitations or rules of the real world. The dreamer generates as many ideas as possible and doesn’t think about the obstacles on the way of their implementation. S/he imagines the most fun, easy, simple, and pleasant ways of solving a problem. The dreamer is unaware of criticism, planning, and rationalism altogether.”

As a result, participants should have a bunch of encircled ideas.

When participants come up with the cloud of ideas, they proceed to the next step. It’s important to explain to them what the second role means. I started with the following words:

“The realist is the dreamer’s best friend. The realist is the manager who can convert a vague idea into a step-by-step plan and find necessary resources. The realist has no idea about criticism. He or she tries to find some real-world implementation for dreamer’s ideas, namely who, when, and how can make an idea true.”

Brainstormers write down possible solutions on sticky notes and put them on the corresponding idea circles. Of course, some of the ideas can have no solution, whereas others may be achieved in many ways.


Slide examples for conducting a rainstorming workshop according to Walt Disney's Strategy
(Large preview)

The third role is the trickiest one because people tend to think this is the guy who drags dreamer’s and realist’s work through the mud. Fortunately, this is not true.

I started my explanation:

“The critic is the dreamer’s and realist’s best friend. This person analyses risks and cares about the safety of proposed solutions. The critic doesn’t touch bare ideas but works with solutions only. The critic’s goal is to help and foresee potential issues in advance.”

The team defines risks and writes them down on smaller red notes. A solution can have no risks or several risks.

After that’s done, team members start voting for the ideas they consider worth further working on. They make a decision based on the value of an idea, the availability of solutions, and the severity of connected risks. Ideas without solutions couldn’t be voted for since they had no connection with reality.

During my workshops, each participant had three voting dots. They could distribute them in different ways, e.g. by sticking the dots to three different ideas or supporting one favorite idea with all of the dots they had.


Slide examples for conducting a rainstorming workshop according to Walt Disney's Strategy
(Large preview)

The final activity is roadmapping. The team takes the ideas that gained the most support (typically, 6–10) and arrange them on a timeline depending on the implementation effort. If an idea is easy to put into practice, it goes to the column “Now.” If an idea is complex and requires a lot of preparation or favorable conditions, it’s farther on the timeline.

Of course, there should be time for sharing the main findings. Teams present their timelines with shortlisted ideas and tell about the tendencies they have observed during the exercise.

SCAMPER

This technique was proposed in 1953 by Alex Osborn, best known for co-founding and leading BBDO, a worldwide advertising agency network. A quick overview:

Complexity Normal to difficult
Subject Ideally, technical or tangible things, although the author and evangelists of this method say it’s applicable for anything. From my experience, SCAMPER works less effective with abstract objects. For example, the team barely coped with the topic “Improve communication between a designer and client,” but it worked great for “Invent the best application for digital prototyping.”
Duration Up to 2 hours
Facilitation One facilitator for a group of 5–8 members

A photo of the brainstorming session using the SCAMPER technique
Brainstorming workshop for the ELEKS design team (Large preview)

Materials

  • Slides with step-by-step instructions.
  • A standalone timer or laptop with an online timer in the fullscreen mode.
  • Standard yellow sticky notes (7 packs per team of 5–8 people).
  • A whiteboard or a flip-chart or a large sheet of paper on a table or wall.
  • Black marker pens for each participant (markers should be whiteboard-safe if you choose this kind of surface).
  • Optionally: Thinkpak cards by Michael Michalko (1 pack per team).

Process

This brainstorming method employs various ways to modify an object. It’s aimed at activating the inventory thinking and helps to optimize an existing product or create a brand new thing.


Samples of slides for conducting a brainstorming workshop employing SCAMPER method
(Large preview)

Each letter in the acronym represents a certain transformation you can apply to the subject of brainstorming.

S  Substitute
C Combine
A Adapt
M Modify
P Put to other uses
E Eliminate
R Rearrange/Reverse

It’s necessary to illustrate each step with an example and ask participants to generate a couple of ideas themselves for the sake of training. As a result, you’ll be sure they won’t get stuck.

We explained the mechanism by giving sample ideas for improving such an ordinary object as a ballpoint pen.

  • Substitute the ink with something edible.
  • Combine the body and the grip so that they are one piece.
  • Adapt a knife for “writing” on wood like a pen.
  • Modify the body so that it becomes flexible — for wearing as a bracelet.
  • Use a pen as a hairpin or arrow for darts.
  • Eliminate the clip and use a magnet instead.
  • Reverse the clip. As a result, the nib will be oriented up, and the pen won’t spill in a pocket.

Samples of slides for conducting a brainstorming workshop employing SCAMPER method
(Large preview)

After the audience doesn’t have questions left, you can start. First of all, team members agree on the subject formulation. Then they draw a canvas on a whiteboard or large paper sheet.

Once a team sees one of the SCAMPER letters on the screen, they start generating ideas using the corresponding method: substitute, combine, adapt, modify, and so on. They write the ideas down and stick the notes into corresponding canvas columns.

The questions on the slides remind what each step means and help to get in a creative mood. Time limitation helps to concentrate and not to dive into discussions.


Samples of slides for conducting a brainstorming workshop employing SCAMPER method
(Large preview)

Affinity sorting — the last step — is our designers’ contribution to the original technique. It pushes the team to start implementation. Otherwise, people quickly forget all valuable findings and return to the usual state of things. Just imagine how discouraging it will be if the results of a two-hour ideation session are put on the back burner.


Samples of slides for conducting a brainstorming workshop employing SCAMPER method
(Large preview)

Thinkpak Cards

It’s a set of brainstorming cards created by Michael Michalko. Thinkpak makes a session more exciting through gamification. Each card represents a certain letter from SCAMPER. Participants shuffle the pack, take cards in turn and come up with corresponding ideas about an object. It’s fun to compete in the number of ideas each participant generates for a given card within a limited time, for instance, three or five minutes.

My friends and I have tried brainstorming both with and without a Thinkpak; it works both ways. Cards are great for training inventory thinking. If your team has never participated in brainstorming sessions, it’ll be great to play the cards first and then switch to a business subject.

Lessons Learned

  1. Dry run.
    People often become disappointed in brainstorming if the first session they participate in fails. Some people I worked with have a prejudice towards creativity and consider it the waste of time or something not proven scientifically. Fortunately, we tried all the techniques internally — in the design team. As a result, all the actual brainstorming sessions went well. Moreover, our confidence helped others to believe in the power of brainstorming exercises.
  2. Relevant topic and audience.
    Brainstorming can fail if you invite people who don’t have a relevant background or the power and willing to change anything. Once I asked a team of design juniors to ideate about improving the process of selling design services to clients. They lacked the experience and couldn’t generate plenty of ideas. Fortunately, it was a training session, and we easily changed the topic.
  3. Documenting outcomes.
    So, the session is over. Participants go home or return to their workplaces. Almost surely the next morning they will recall not a single thing. I recommend creating a wrap-up document with photos and digitized canvases. The quicker you write and share it, the higher the chances will be that the ideas are actually implemented.

Further Resources

Smashing Editorial
(dm, ra, il)

Source: Smashing Magazine, Organizing Brainstorming Workshops: A Designer’s Guide

Collective #496

dreamt up by webguru in Uncategorized | Comments Off on Collective #496



C496_zeroserver

Zero Server

A zero configuration web framework that abstracts the usual project configuration for routing, bundling, and transpiling to make it easier to get started.

Check it out






C496_chrome

We Need Chrome No More

A very interesting article on how we should foster browser diversity and step away from using the browser of the world’s largest advertising company.

Read it






C496_dribbble

The Dribbble Experiment

Robert Williams analyzes the performance of a job post on Dribbble and compares it to using the advanced search tool.

Read it




C496_codevember

Codevember 2018

A fantastic compilation of loops for Codevember 2018 including source codes and breakdown gifs. By Jaume Sanchez Elias.

Check it out








C496_subsync

Subsync

Language-agnostic automatic synchronization of subtitles to video, so that subtitles are aligned to the correct starting point within the video.

Check it out


Collective #496 was written by Pedro Botelho and published on Codrops.


Source: Codrops, Collective #496

Fresh Spring Vibes For Your Desktop (March 2019 Wallpapers Edition)

dreamt up by webguru in Uncategorized | Comments Off on Fresh Spring Vibes For Your Desktop (March 2019 Wallpapers Edition)

Fresh Spring Vibes For Your Desktop (March 2019 Wallpapers Edition)

Fresh Spring Vibes For Your Desktop (March 2019 Wallpapers Edition)

Cosima Mielke



Spring is coming! With March just around the corner, nature is slowly but surely awakening from its winter sleep. And, well, even if spring seems far away in your part of the world, this month’s wallpaper selection is bound to at least get your ideas springing.

Just like every month since more than nine years already, artists and designers from across the globe got out their favorite tools and designed unique wallpapers to cater for some fresh inspiration on your desktop and mobile screens. The wallpapers come in versions with and without a calendar for March 2019 and can be downloaded for free. A big thank-you to everyone who submitted their designs! As a little bonus goodie, we also added some favorites from past years’ March editions at the end of this post. Now which one will make it to your screen?

Please note that:

  • All images can be clicked on and lead to the preview of the wallpaper,
  • You can feature your work in our magazine by taking part in our Desktop Wallpaper Calendar series. We are regularly looking for creative designers and artists to be featured on Smashing Magazine. Are you one of them?

Further Reading on SmashingMag:

Time To Wake Up

“Rays of sunlight had cracked into the bear’s cave. He slowly opened one eye and caught a glimpse of nature in blossom. Is it spring already? Oh, but he is so sleepy. He doesn’t want to wake up, not just yet. So he continues dreaming about those sweet sluggish days while everything around him is blooming.” — Designed by PopArt Studio from Serbia.

Time To Wake Up

Queen Bee

“Spring is coming! Birds are singing, flowers are blooming, bees are flying… Enjoy this month!” — Designed by Melissa Bogemans from Belgium.

Queen Bee

Bunny O’Hare

“When I think of March I immediately think of St. Patrick’s Day and my Irish heritage… and then my head fills with pub music! I had fun putting a twist on this month’s calendar starring my pet rabbit. Erin go Braugh.” — Designed by Heather Ozee from the United States.

Bunny O’Hare

A Bite Of Spring

Designed by Ricardo Gimenes from Sweden.

A Bite Of Spring

Balance

“International Women’s Day on March 8th is the inspiration behind this artwork. Through this artwork, we wish a jovial, strong and successful year ahead for all women around the world.” — Designed by Sweans Technologies from London.

Balance

Stunning Beauty

“A recent vacation to the Philippines led me to Palawan, specifically El Nido, where I was in awe of the sunset. I wanted to emphasize the year in the typography as a reminder that, even though we are three months in, our resolutions are still fresh and new and waiting for us to exceed them! Photograph shot by @chrishernando, whose companionship and permission I am so grateful for.” — Designed by Mary Walker from the United States.

Stunning Beauty

Spring Time!

“Spring is here! Giraffes are starting to eat the green leaves.” — Designed by Veronica Valenzuela from Spain.

Spring Time!

Banished

“The legend of St. Patrick banishing snakes from Ireland.” — Designed by Caitey Kennedy from the United States.

Banished

Oldies But Goodies

In more than nine years running this community project, a lot of wallpaper gems have accumulated in our archives. Let’s take a look back and rediscover some March favorites from past years. Please note that these wallpapers don’t come with a calendar.

Let’s Get Outside

“Let’s get outside and seize the beginning of Spring. Who knows what adventures might await us there?” — Designed by Lívia Lénárt from Hungary.

Let’s Get Outside!

The Unknown

“I made a connection, between the dark side and the unknown lighted and catchy area.” — Designed by Valentin Keleti from Romania.

The Unknown

Imagine

Designed by Romana Águia Soares from Portugal.

Imagine

Spring Bird

Designed by Nathalie Ouederni from France.

Spring Bird

Ballet

“A day, even a whole month aren’t enough to show how much a woman should be appreciated. Dear ladies, any day or month are yours if you decide so.” — Designed by Ana Masnikosa from Belgrade, Serbia.

Ballet

Wake Up!

“Early spring in March is for me the time when the snow melts, everything isn’t very colorful. This is what I wanted to show. Everything comes to life slowly, as this bear. Flowers are banal, so instead of a purple crocus we have a purple bird-harbinger.” — Designed by Marek Kedzierski from Poland.

Wake Up!

Spring Is Coming!

“Spring is the best part of the year! Nature breaking free and spring awakening is symbolic of our awakening.” — Designed by Silvia Bukovac from Croatia.

Spring Is Coming!

Spring Is Inevitable!

“Spring is round the corner. And very soon plants will grow on some other planets too. Let’s be happy about a new cycle of life.” — Designed by Igor Izhik from Canada.

Spring Is Inevitable!

Tune In To Spring!

Designed by Iquadart from Belarus.

Tune in to spring!

Wake Up!

“I am the kind of person that prefers cold but I do love spring since it’s the magical time when flowers and trees come back to life and fill the landscape with beautiful colors.” — Designed by Maria Keller from Mexico.

Wake up!

Let’s Spring!

“After some freezing months, it’s time to enjoy the sun and flowers. It’s party time, colours are coming, so let’s spring!” — Designed by Colorsfera from Spain.

Let's spring!

MARCHing Forward!

“If all you want is a little orange dinosaur MARCHing (okay, I think you get the pun) across your monitor, this wallpaper was made just for you! This little guy is my design buddy at the office and sits by (and sometimes on top of) my monitor. This is what happens when you have designer’s block and a DSLR.” — Designed by Paul Bupe Jr from Statesboro, GA.

MARCHing forward!

Waiting For Spring

“As days are getting longer again and the first few flowers start to bloom, we are all waiting for Spring to finally arrive.” Designed by Naioo from Germany.

Smashing Wallpaper - march 12

March Fusion

Designed by Rio Creativo from Poland.

Smashing Wallpaper - march 12

Daydream

“A daydream is a visionary fantasy, especially one of happy, pleasant thoughts, hopes or ambitions, imagined as coming to pass, and experienced while awake.” Designed by Bruna Suligoj from Croatia.

Smashing Wallpaper - march 11

Sweet March

“Digital collage, based on past and coming spring. The idea is to make it eternal or at least make it eternal in our computers! Hope you like it.” Designed by Soledad Martelletti from Argentina.

Smashing Wallpaper - march 11

Knowledge

“Exploring new worlds is much like exploring your own mind, creativity and knowledge. The only way to learn what’s really inside you is by trying something new. The illustration is my very own vision of the knowledge. It’s placed in some mysterious habitat. It’s a space where people learn from each other, find new talents and study their own limits.” — Designed by Julia Wójcik from Poland.

Knowledge

Join In Next Month!

Please note that we respect and carefully consider the ideas and motivation behind each and every artist’s work. This is why we give all artists the full freedom to explore their creativity and express emotions and experience throughout their works. This is also why the themes of the wallpapers weren’t anyhow influenced by us but rather designed from scratch by the artists themselves.

Thank you to all designers for their participation. Join in next month!

Source: Smashing Magazine, Fresh Spring Vibes For Your Desktop (March 2019 Wallpapers Edition)

Breaking Boxes With CSS Fragmentation

dreamt up by webguru in Uncategorized | Comments Off on Breaking Boxes With CSS Fragmentation

Breaking Boxes With CSS Fragmentation

Breaking Boxes With CSS Fragmentation

Rachel Andrew



In this article, I’m going to introduce you to the CSS Fragmentation specification. You might never have heard of it, however, if you have ever created a print stylesheet and wanted to control where the content breaks between pages, or multi-column layout and wanted to stop a figure breaking between columns, you have encountered it.

I find that quite often problems people report with multicol are really problems with browser support of fragmentation. After a quick rundown of the properties contained in this specification, I’ll be explaining the current state of browser support and some of the things you can do to get it working as well as it can in your multicol and print projects.

What Is Fragmentation?

Fragmentation in CSS describes the process by which content becomes broken up into different boxes. Currently, we have two places in which we might run into fragmentation on the web: when we print a document, and if we use multi-column layout. These two things are essentially the same. When you print (or save to PDF) a webpage, the content is fragmented into as many pages as are required to print your content.

When you use multicol, the content is fragmented into columns. Each column box is like a page in the paged context. If you think of a set of columns as being much like a set of pages it can be a helpful way to think about multicol and how fragmentation works in it.

If you take a look at the CSS Fragmentation Specification you will see a third fragmented context mentioned — that context is Regions. As there are no current usable implementations of Regions, we won’t be dealing with that in this article, but instead looking at the two contexts that you might come across in your work.

Block And Inline Boxes

I am going to mention block boxes a lot in this article. Every element of your page has a box. Some of those boxes are laid out as blocks: paragraphs, list items, headings. These are said to be participating in a block formatting context. Others are inline such as the words in a paragraph, spans and anchor elements. These participate in an inline formatting context. Put simply, when I refer to a block box, I’m talking about boxes around things like paragraphs. When dealing with fragmentation, it is important to know which kind of box you are dealing with.

For more information on block and inline layout, see the MDN article “Block And Inline Layout In Normal Flow”. It is one of those things that we probably all understand on some level but might not have encountered the terminology of before.

Controlling Breaks

Whether you are creating a print stylesheet, using a specific print user agent to make a PDF,or using multicol, you will sometimes run into problems that look like this.

In the below multicol example, I have some content which I am displaying as three columns. In the middle of the content is a boxed out area, which is being broken across two columns. I don’t want this behavior — I would like the box to stay together.


Three columns with a boxed out area broken across two of them
The box breaks across two columns (Large preview)

To fix this, I add the property break-inside: avoid to the box. The break-inside property controls breaks inside elements when they are in a fragmented context. In a browser which supports this property, the box will now stay in one of the columns. The columns will look less well balanced, however, that is generally a better thing than ending up with the boxout split across columns.

The break-inside property is one of the properties detailed in the fragmentation spec. The full list of properties is as follows:

  • break-before
  • break-after
  • break-inside
  • orphans
  • widows
  • box-decoration-break

Let’s have a look at how these are supposed to work before we move onto what actually happens in browsers.

The break-before And break-after Properties

There are two properties that control breaks between block-level boxes: break-before and break-after. If you have an h2 followed by two paragraphs <p> you have three block boxes and you would use these properties to control the breaks between the heading and first paragraph, or between the two paragraphs.

The properties are used on selectors which target the element you want to break before or after.

For example, you might want your print stylesheet to break onto a new page every time there is a level 2 heading. In this case, you would use break-before: page on the h2 element. This controls the fragmentation and ensures there is always a break before the box of the h2 element.

h2 {
    break-before: page;
}

Another common requirement is to prevent headings ending up as the last thing on a page or column. In this case, you might use break-after with a value of avoid. This should prevent a break directly after the box of the element:

h1, h2, h3, h4 {
    break-after: avoid;
}
Fragments Within Fragments

It is possible that you might have an element that is fragmented nested inside another. For example, having a multicol inside something which is paged. In that case, you might want to control breaks for pages but not for columns, or the other way around. This is why we have values such as page which would always force a break before or after the element but only when the fragment is a page. Or avoid-page which would avoid a break before or after the element only for paged contexts.

The same applies to columns. If you use the value column, this would always force a break before or after that element, but only for multicol contexts. The value avoid-column would prevent a break in multicol contexts.

There is an always value in the Level 4 specification which indicates that you want to break through everything – page or column. However, as a recent addition to the spec it is not currently useful to us.

Additional Values For Paged Media

If you are creating a book or magazine, you have left and right pages. You might want to control breaking in order to force something onto the left or right page of a spread. Therefore, using the following would insert one or two-page breaks before the h2 to ensure it was formatted as a right page.

h2 {
    break-before: right;
}

There are also recto and verso values which relate to page progression as books written in a vertical or right to left language have a different page progression than books written in English. I’m not going to cover these values further in this article as I’m primarily concerned with what is possible from the browser this time.

break-inside

We have already seen an example of the break-inside property. This property controls breaking inside block boxes, e.g. inside a paragraph, heading or a div.

Things that you may not want to break can include a boxout as described above: figures where you do not want the caption detached from the image, tables, lists and so on. Add break-inside: avoid to any container you don’t wish to break in any fragmentation context. If you only wish to avoid breaks between columns use break-inside: avoid-column and between pages break-inside: avoid-page.

The orphans And widows Properties

The orphans and widows properties deal with how many lines should be left before or after a break (either caused by a column or a new page). For example, if I want to avoid a single line being left at the end of a column, I would use the orphans property, as in typography, an orphan is the first line of a paragraph that appears alone at the bottom of a page with the rest of the paragraph broken onto another page. The property should be added to the same element which is fragmenting (in our case, the multicol container).

.container {
    column-count: 3;
    orphans: 2;
}

To control how many lines should be at the top of a column or page after a break, use widows:

.container {
    column-count: 3;
    widows: 2;
}

These properties deal with breaks between inline boxes such as the lines of words inside a paragraph. Therefore, they don’t help in the situation where a heading or other block element is alone at the bottom of a column or page, you need the break properties discussed above for that.

Box Decoration

A final property that may be of interest is the box-decoration-break property. This controls the situation where you have a box with a border broken between two column boxes or pages. Do you want the border to essentially be sliced in half? Or do you want each of the two halves of the box to be wrapped fully in a border?

The first scenario is the default, and is as if you set the box-decoration-break property to slice on the box.

.box {
    box-decoration-break: slice;
}

A box with a border which is broken between columns
A value of slice means the border is effectively sliced in half (Large preview)

To get the second behavior, set box-decoration-break to clone.

.box {
    box-decoration-break: clone;
}

Boxes are completely wrapped in borders
A value of clone means the border is wrapped fully round each fragment of the box (Large preview)

Browser Support For Fragmentation

Now we come to the reason I don’t have a bunch of CodePen examples above to demo all of this to you, and the main reason for my writing this article. Browser support for these properties is not great.

If you are working in Paged Media with a specific user agent such as Prince, then you can enjoy really good support for fragmentation, and will probably find these properties very useful. If you are working with a web browser, either in multicol, creating print stylesheets, or using something like Headless Chrome to generate PDFs, support is somewhat patchy. You’ll find that the browser with the best support is Edge — until it moves to Chromium anyway!

Can I Use isn’t overly helpful with explaining support due to mixing the fragmentation properties in with multicol, then having some separate data for legacy properties. So, as part of the work I’ve been doing for MDN to document the properties and their support, I began testing the actual browser support. What follows is some advice based on that testing.

Legacy And Vendor Prefixed Properties

I can’t go much further without a history lesson. If you find you really need support for fragmentation then you may find some relief in the legacy properties which were originally part of CSS2 (or in some prefixed properties that exist).

In CSS2, there were properties to control page breaking. Multicol didn’t exist at that point, so the only fragmented context was a paged one. This meant that three specific page breaking properties were introduced:

  • page-break-before
  • page-break-after
  • page-break-inside

These work in a similar way to the more generic properties without the page- prefix, controlling breaks before, after and inside boxes. For print stylesheets, you will find that some older browsers which do not support the new break- properties, do support these page prefixed properties. The properties are being treated as aliases for the new properties.

In a 2005 Working Draft of the multicol specification are details of breaking properties for multicol — using properties prefixed with column- (i.e. column-break-before, column-break-after, and column-break-inside). By 2009, these had gone, and a draft was in the multicol specification for unprefixed break properties which eventually made their way into the CSS Fragmentation specification.

However, some vendor prefixed column-specific properties were implemented based on these properties. These are:

  • -webkit-column-break-before
  • -webkit-column-break-after
  • -webkit-column-break-inside

Support For Fragmentation In Multicol

The following is based on testing these features in multicol contexts. I’ve tried to explain what is possible, but do take a look at the CodePens in whichever browsers you have available.

Multicol And break-inside

Support in multicol is best for the break-inside property. Up to date versions of Chrome, Firefox, Edge, and Safari all support break-inside: avoid. So you should find that you can prevent boxes from breaking between columns when using multicol.

Several browsers, with the exception of Firefox, support the -webkit-column-break-inside property, this can be used with a value of avoid and may prevent boxes breaking between columns which do not have support for break-inside.

Firefox supports page-break-inside: avoid in multicol. Therefore, using this property will prevent breaks inside boxes in Firefox browsers prior to Firefox 65.

This means that if you want to prevent breaks between boxes in multicol, using the following CSS will cover as many browsers as possible, going back as far as possible.

.box {
    -webkit-column-break-inside: avoid;
    page-break-inside: avoid;
    break-inside: avoid;
}

As for the column value, explicitly stating that you only want to avoid breaks between columns, and not pages, works in all browsers except Firefox.

The below CodePen rounds up some of these tests in multicol so you can try them for yourself.

Multicol And break-before

In order to prevent breaks before an element, you should be able to use break-before: avoid or break-before: avoid-column. The avoid property has no browser support.

Edge supports break-before: column to always force a break before the box of the element.

Safari, Chrome and Edge also support -webkit-column-break-before: always which will force a break before the box of the element. Therefore, if you want to force a break before the box of an element, you should use:

.box {
    -webkit-column-break-before: always;
    break-before: column;
}

Preventing a break before the box is currently an impossible task. You can play around with some examples of these properties below:

Multicol And break-after

To prevent breaks after an element, to avoid it becoming the last thing at the bottom of a column, you should be able to use break-after: avoid and break-after: avoid-column. The only browser with support for these is Edge.

Edge also supports forcing breaks after an element by using break-after: column, Chrome supports break-after: column and also -webkit-column-break-after: always.

Firefox does not support break-after or any of the prefixed properties to force or allow breaks after a box.

Therefore, other than Edge, you cannot really avoid breaks after a box. If you want to force them, you will get results in some browsers by using the following CSS:

.box {
    -webkit-break-after: always;
    break-after: column;
}

Support When Printing From The Browser

Whether you print directly from your desktop browser or generate PDF files using headless Chrome or some other solution reliant on browser technology doesn’t make any difference. You are reliant on the browser support for the fragmentation properties.

If you create a print stylesheet you will find similar support for the break properties as for multicol, however, to support older browsers you should double up the properties to use the page- prefixed properties.

In modern browsers ,the break-inside property can be used to prevent breaks inside boxes, add the page-break-inside property to add support for older browsers.

.box {
    page-break-inside: avoid;
    break-inside: avoid;
}

To force breaks before a box use break-before:page along with page-break-before: always.

.box {
    page-break-before: always;
    break-before: page;
}

To avoid breaks before a box use break-before: avoid-page along with page-break-before: avoid.

.box {
    page-break-before: avoid;
    break-before: avoid-page;
}

There is better support for the page and avoid-page values than we see for the equivalent multicol values. The majority of modern browsers have support.

To force breaks after a box, use break-after: page along with page-break-after: always.

.box {
    page-break-after: always;
    break-after: page;
}

To prevent breaks after a box use break-after: avoid-page along with page-break-after: avoid.

.box {
    page-break-after: avoid;
    break-after: avoid-page;
}

Widows And Orphans

The widows and orphans properties enjoy good cross-browser support — the only browser without an implementation being Firefox. I would suggest using these when creating a multicol layout or print stylesheet. If they don’t work for some reason, you will get widows and orphans, which isn’t ideal but also isn’t a disaster. If they do work your typography will look all the better for it.

box-decoration-break

The final property of box-decoration-break has support for multicol and print in Firefox. Safari, Chrome and other Chromium-based browsers support -webkit-box-decoration-break, but only on inline elements. So you can clone borders round lines of a sentence for example; they do not have support in the context we are looking at.

In the CodePen below, you can see that testing for -webkit-box-decoration-break: clone with Feature Queries returns true, however, the property has no effect on the border of the box in the multicol context.

Using Fragmentation

As you can see, the current state of fragmentation in browsers is somewhat fragmented! That said, there is a reasonable amount you can achieve and where it fails, the result tends to be suboptimal but not a disaster. Which means it is worth trying.

It is worth noting that being too heavy handed with these properties could result in something other than what you hoped for. If you are working on the web rather than print and force column breaks after every paragraph, then end up with more paragraphs than space for columns, multicol will end up overflowing in the inline direction. It will run out of columns to place your additional paragraphs. Therefore, even where there is support, you still need to test carefully, and remember that less is more in a lot of cases.

More Resources

To read more about the properties head over to MDN, I’ve recently updated the pages there and am also trying to keep the browser compat data up to date. The main page for CSS Fragmentation links to the individual property pages which have further examples, browser compat data and other information about using these properties.

Smashing Editorial
(il)

Source: Smashing Magazine, Breaking Boxes With CSS Fragmentation

Sliding In And Out Of Vue.js

dreamt up by webguru in Uncategorized | Comments Off on Sliding In And Out Of Vue.js

Sliding In And Out Of Vue.js

Sliding In And Out Of Vue.js

Kevin Ball



Vue.js has achieved phenomenal adoption growth over the last few years. It has gone from a barely known open-source library to the second most popular front-end framework (behind only React.js).

One of the biggest reasons for its growth is that Vue is a progressive framework — it allows you to adopt bits and pieces at a time. Don’t need a full single page application? Just embed a component. Don’t want to use a build system? Just drop in a script tag, and you’re up and running.

This progressive nature has made it very easy to begin adopting Vue.js piecemeal, without having to do a big architecture rewrite. However, one thing that is often overlooked is that it’s not just easy to embed Vue.js into sites written with other frameworks, it’s also easy to embed other code inside of Vue.js. While Vue likes to control the DOM, it has lots of escape hatches available to allow for non-Vue JavaScript that also touches the DOM.

This article will explore the different types of third-party JavaScript that you might want to use, what situations you might want to use them inside of a Vue project, and then cover the tools and techniques that work best for embedding each type within Vue. We’ll close with some considerations of the drawbacks of these approaches, and what to consider when deciding if to use them.

This article assumes some familiarity with Vue.js, and the concepts of components and directives. If you are looking for an introduction to Vue and these concepts, you might check out Sarah Drasner’s excellent introduction to Vue.js series or the official Vue Guide.

Types Of Third-Party JavaScript

There are three major types of third-party JavaScript that we’ll look at in order of complexity:

  1. Non-DOM Touching Libraries
  2. Element Augmentation Libraries
  3. Components And Component Libraries

Non-DOM Libraries

The first category of third-party JavaScript is libraries that provide logic in the abstract and have no direct access to the DOM. Tools like moment.js for handling dates or lodash for adding functional programming utilities fall into this category.

These libraries are trivial to integrate into Vue applications, but can be wrapped up in a couple of ways for particularly ergonomic access. These are very commonly used to provide utility functionality, the same as they would in any other type of JavaScript project.

Element Augmentation Libraries

Element augmentation is a time-honored way to add just a bit of functionality to an element. Examples include tasks like lazy-loading images with lozad or adding input masking using Vanilla Masker.

These libraries typically impact a single element at a time, and expect a constrained amount of access to the DOM. They will likely be manipulating that single element, but not adding new elements to the DOM.

These tools typically are tightly scoped in purpose, and relatively straightforward to swap out with other solutions. They’ll often get pulled into a Vue project to avoid re-inventing the wheel.

Components And Component Libraries

These are the big, intensive frameworks and tools like Datatables.net or ZURB Foundation. They create a full-on interactive component, typically with multiple interacting elements.

They are either directly injecting these elements into the DOM or expect a high level of control over the DOM. They were often built with another framework or toolset (both of these examples build their JavaScript on top of jQuery).

These tools provide extensive functionality and can be challenging to replace with a different tool without extensive modifications, so a solution for embedding them within Vue can be key to migrating a large application.

How To Use In Vue

Non-DOM Libraries

Integrating a library that doesn’t touch the DOM into a Vue.js project is relatively trivial. If you’re using JavaScript modules, simply importor require the module as you would in another project. For example:

import moment from 'moment';

Vue.component('my-component', {
  //…
  methods: {
    formatWithMoment(time, formatString) {
      return moment(time).format(formatString);
    },
});

If using global JavaScript, include the script for the library before your Vue project:

One additional common way to layer on a bit more integration is to wrap up your library or functions from the library using a filter or method to make it easy to access from inside your templates.

Vue Filters

Vue Filters are a pattern that allows you to apply text formatting directly inline in a template. Drawing an example from the documentation, you could create a ‘capitalize’ filter and then apply it in your template as follows:

{{myString | capitalize}}

When importing libraries having to do with formatting, you may want to wrap them up as a filter for ease of use. For example, if we are using moment to format all or many of our dates to relative time, we might create a relativeTime filter.

const relativeTime = function(value) {
  if (!value) return '';
  return moment(value).fromNow();
}

We can then add it globally to all Vue instances and components with the Vue.filter method:

Vue.filter(’relativeTime', relativeTime);

Or add it to a particular component using the filters option:

const myComponent = {
  filters: {
    ’relativeTime': relativeTime,
  } 
}

You can play with this on CodePen here:

See the Pen Vue integrations: Moment Relative Value Filter by Kevin Ball.

Element Augmentation Libraries

Element augmentation libraries are slightly more complex to integrate than libraries that don’t touch the DOM — if you’re not careful, Vue and the library can end up at cross purposes, fighting each other for control.

To avoid this, you need to hook the library into Vue’s lifecycle, so it runs after Vue is done manipulating the DOM element, and properly handles updates that Vue instigates.

This could be done in a component, but since these libraries typically touch only a single element at a time, a more flexible approach is to wrap them in a custom directive.

Vue Directives

Vue directives are modifiers that can be used to add behavior to elements in your page. Vue ships with a number of built-in directives that you are likely already comfortable with — things like v-on, v-model, and v-bind. It is also possible to create custom directives that add any sort of behavior to an element — exactly what we’re trying to achieve.

Defining a custom directive is much like defining a component; you create an object with a set of methods corresponding to particular lifecycle hooks, and then add it to Vue either globally by running:

Vue.directive('custom-directive', customDirective);

Or locally in a component by adding it to the directives object in the component:

const myComponent = {
  directives: {
    'custom-directive': customDirective,
  } 
}
Vue Directive Hooks

Vue directives have the following hooks available to define behavior. While you can use all of them in a single directive, it is also not uncommon to only need one or two. They are all optional, so use only what you need.

  • bind(el, binding, vnode)
    Called once and only once, when the directive is first bound to an element. This is a good place for one-time setup work, but be cautious, i.e. the element exists, may not yet actually be in the document.
  • inserted(el, binding, vnode)
    Called when the bound element has been inserted into its parent node. This also does not guarantee presence in the document, but does mean if you need to reference the parent you can.
  • update(el, binding, vnode, oldVnode)
    Called whenever the containing component’s VNode has updated. There are no guarantees that other children of the component will have updated, and the value for the directive may or may not have changed. (You can compare binding.value to binding.oldValue to see and optimize away any unnecessary updates.)
  • componentUpdated(el, binding, vnode, oldVnode)
    Similar to update, but called after all children of the containing component have updated. If the behavior of your directive depends on its peers (e.g. v-else), you would use this hook instead of update.
  • unbind(el, binding, vnode)
    Similar to bind, this is called once and only once, when the directive is unbound from an element. This is a good location for any teardown code.

The arguments to these functions are:

  • el: The element the directive is bound to;
  • binding: An object containing information about the arguments and value of the directive;
  • vnode: The virtual node for this element produced by Vue’s compiler;
  • oldVNode: The previous virtual node, only passed to update and componentUpdated.

More information on these can be found in the Vue Guide on custom directives.

Wrapping The Lozad Library In A Custom Directive

Let’s look at an example of doing this type of wrapping using lozad, a lazy-loading library built using the Intersection Observer API. The API for using lozad is simple: use data-src instead of src on images, and then pass a selector or an element to lozad() and call observe on the object that is returned:

const el = document.querySelector('img');
const observer = lozad(el); 
observer.observe();

We can do this simply inside of a directive using the bind hook.

const lozadDirective = {
  bind(el, binding) {
    el.setAttribute('data-src', binding.value) ;
    let observer = lozad(el);
    observer.observe();
  }
}
Vue.directive('lozad', lozadDirective)

With this in place, we can change images to lazy load by simply passing the source as a string into the v-lozad directive:

<img v-lozad="'https://placekitten.com/100/100'" />

You can observe this at work in this CodePen:

See the Pen Vue integrations: Lozad Directive Just Bind by Kevin Ball).

We’re not quite done yet though! While this works for an initial load, what happens if the value of the source is dynamic, and Vue changes it? This can be triggered in the pen by clicking the “Swap Sources” button. If we only implement bind, the values for data-src and src are not changed when we want them to be!

To implement this, we need to add an updated hook:

const lozadDirective = {
  bind(el, binding) {
    el.setAttribute('data-src', binding.value) ;
    let observer = lozad(el);
    observer.observe();
  },
  update(el, binding) {
    if (binding.oldValue !== binding.value) {
      el.setAttribute('data-src', binding.value);
      if (el.getAttribute('data-loaded') === 'true') {
        el.setAttribute('src', binding.value);
      }
    }
  }
}

With this in place, we’re set! Our directive now updates everything lozad touches whenever Vue updates. The final version can be found in this pen:

See the Pen Vue integrations: Lozad Directive With Updates by Kevin Ball.

Components And Component Libraries

The most complex third-party JavaScript to integrate is that which controls entire regions of the DOM, full-on components and component libraries. These tools expect to be able to create and destroy elements, manipulate them, and more.

For these, the best way to pull them into Vue is to wrap them in a dedicated component, and make extensive use of Vue’s lifecycle hooks to manage initialization, passing data in, and handling events and callbacks.

Our goal is to completely abstract away the details of the third-party library, so that the rest of our Vue code can interact with our wrapping component like a native Vue component.

Component Lifecycle Hooks

To wrap around a more complex component, we’ll need to be familiar with the full complement of lifecycle hooks available to us in a component. Those hooks are:

  • beforeCreate()
    Called before the component is instantiated. Pretty rarely used, but useful if we’re integrating profiling or something similar.
  • created()
    Called after the component is instantiated, but before it is added to the DOM. Useful if we have any one-off setup that doesn’t require the DOM.
  • beforeMount()
    Called just before the component is mounted in the DOM. (Also pretty rarely used.)
  • mounted()
    Called once the component is placed into the DOM. For components and component libraries that assume DOM presence, this is one of our most commonly used hooks.
  • beforeUpdate()
    Called when Vue is about to update the rendered template. Pretty rarely used, but again useful if integrating profiling.
  • updated()
    Called when Vue has finished updating the template. Useful for any re-instantiation that is needed.
  • beforeDestroy()
    Called before Vue tears down a component. A perfect location to call any destruction or deallocation methods on our third-party component
  • destroyed()
    Called after Vue has torn down a component.
Wrapping A Component, One Hook At A Time

Let’s take a look at the popular jquery-multiselect library. There exist many fine multiselect components already written in Vue, but this example gives us a nice combination: complicated enough to be interesting, simple enough to be easy to understand.

The first place to start when implementing a third-party component wrapper is with the mounted hook. Since the third-party component likely expects the DOM to exist before it takes charge of it, this is where you will hook in to initialize it.

For example, to start wrapping jquery-multiselect, we could write:

mounted() { 
  $(this.$el).multiselect();
}

You can see this functioning in this CodePen:

This is looking pretty good for a start. If there were any teardown we needed to do, we could also add a beforeDestroy hook, but this library does not have any teardown methods that we need to invoke.

Translating Callbacks To Events

The next thing we want to do with this library is add the ability to notify our Vue application when the user selects items. The jquery-multiselect library enables this via callbacks called afterSelect and afterDeselect, but to make this more vue-like, we’ll have those callbacks emit events. We could wrap those callbacks naively as follows:

mounted() { 
  $(this.$el).multiSelect({
     afterSelect: (values) => this.$emit('select', values),
     afterDeselect: (values) => this.$emit('deselect', values)
   });
}

However, if we insert a logger in the event listeners, we’ll see that this does not provide us a very vue-like interface. After each select or deselect, we receive a list of the values that have changed, but to be more vue-like, we should probably emit a change event with the current list.

We also don’t have a very vue-like way to set values. Instead of this naive approach then, we should look at using these tools to implement something like the v-model approach that Vue provides for native select elements.

Implementing v-model

To implement v-model on a component, we need to enable two things: accepting a value prop that will accept an array and set the appropriate options as selected, and then emit an input event on change that passes the new complete array.

There are four pieces to handle here: initial setup for a particular value, propagate any changes made up to the parent, and handle any changes to value starting outside the component, and finally handle any changes to the content in the slot (the options list).

Let’s approach them one at a time.

  1. Setup With A Value Prop
    First, we need to teach our component to accept a value prop, and then when we instantiate the multiselect we will tell it which values to select.
    export default {
      props: {
        value: Array,
        default: [],
      },
      mounted() { 
        $(this.$el).multiSelect();
        $(this.$el).multiSelect('select', this.value);
      },
    }
    
  2. Handle Internal Changes
    To handle changes occurring due to the user interacting with the multiselect, we can go back to the callbacks we explored before — but ‘less naively’ this time. Instead of simply emitting what they send us, we want to turn a new array that takes into account our original value and the change made.
    mounted() { 
      $(this.$el).multiSelect({
        afterSelect: (values) => this.$emit('input', [...new Set(this.value.concat(values))]),
        afterDeselect: (values) => this.$emit('input', this.value.filter(x => !values.includes(x))),
      });
      $(this.$el).multiSelect('select', this.value);
    },
    

    Those callback functions might look a little dense, so let’s break them down a little.

    The afterSelect handler concatenates the newly selected value with our existing values, but then just to make sure there are no duplicates, it converts it to a Set (guarantees uniqueness) and then a destructuring to turn it back to an array.

    The afterDeselect handler simply filters out any deselected values from the current value list in order to emit a new list.

  3. Handling External Updates To Value
    The next thing we need to do is to update the selected values in the UI whenever the value prop changes. This involves translating from a declarative change to the props into an imperative change utilizing the functions available on multiselect. The simplest way to do this is to utilize a watcher on our value prop:
    watch:
      // don’t actually use this version. See why below
      value() {
        $(this.$el).multiselect('select', this.value);
      }
    }
    

    However, there’s a catch! Because triggering that select will actually result in our onSelect handler, and thus use updating values. If we do this naive watcher, we will end up in an infinite loop.

    Luckily,for us, Vue gives us the ability to see the old as well as the new values. We can compare them, and only trigger the select if the value has changed. Array comparisons can get tricky in JavaScript, but for this example, we’ll take advantage of the fact that our arrays are simple (not containing objects) and use JSON stringify to do the comparison. After taking into account that we need to also deselect any that options that have been removed, our final watcher looks like this:

    watch: {
        value(newValue, oldValue) {
          if (JSON.stringify(newValue) !== JSON.stringify(oldValue)) {
            $(this.$el).multiSelect('deselect_all');
            $(this.$el).multiSelect('select', this.value);
          }
        }
      },
    
  4. Handling External Updates To Slot
    We have one last thing that we need to handle: our multiselect is currently utilizing option elements passed in via a slot. If that set of options changes, we need to tell the multiselect to refresh itself, otherwise the new options don’t show up. Luckily, we have both an easy API for this in multiselect (the ’refresh’ function and an obvious Vue hook to hook into) updated. Handling this last case is as simple as:
    updated() {
      $(this.$el).multiSelect(’refresh');
    },
    

    You can see a working version of this component wrapper in this CodePen:

    See the Pen Vue integrations: Multiselect Wrapper with v-model by Kevin Ball.

Drawbacks And Other Considerations

Now that we’ve looked at how straightforward it is to utilize third-party JavaScript within Vue, it’s worth discussing drawback of these approaches, and when it appropriate to use them.

Performance Implications

One of the primary drawbacks of utilizing third-party JavaScript that is not written for Vue within Vue is performance — particularly when pulling in components and component libraries or things built using entire additional frameworks. Using this approach can result in a lot of additional JavaScript that needs to be downloaded and parsed by the browser before the user can interact with our application.

For example, by using the multiselect component, we developed above means pulling in not only that component’s code, but all of jQuery as well. That can double the amount of framework related JavaScript our users will have download, just for this one component! Clearly finding a component built natively with Vue.js would be better.

Additionally, when there are large mismatches between the APIs used by third-party libraries and the declarative approach that Vue takes, you may find yourself implementing patterns that result in a lot of extra execution time. Also using the multiselect example, we had to refresh the component (requiring looking at a whole bunch of the DOM) every time a slot changed, while a Vue-native component could utilize Vue’s virtual DOM to be much more efficient in its updates.

When To Use

Utilizing third-party libraries can save you a ton of development time, and often means you’re able to use well-maintained and tested software that you don’t have the expertise to build. The primary drawback is performance, particularly when bringing in large frameworks like jQuery.

For libraries that don’t have those large dependencies, and particularly those that don’t heavily manipulate the DOM, there’s no real reason to favor Vue-specific libraries over more generic ones. Because Vue makes it so easy to pull in other JavaScript, you should go based on your feature and performance needs, simply picking the best tool for the job, without worrying about something Vue-specific.

For more extensive component frameworks, there are three primary cases in which you’d want to pull them in.

  1. Prototyping
    In this case, speed of iteration matters far more than user performance; use whatever gets the job done fastest.
  2. Migrating an existing site.
    If you’re migrating from an existing site to Vue, being able to wrap whatever framework you’re already using within Vue will give you a graceful migration path so you can gradually pull out the old code piece by piece, without having to do a big bang rewrite.
  3. When the functionality simply isn’t available yet in a Vue component.
    If you have a specific and challenging requirement you need to meet, for which a third-party library exists but there isn’t a Vue specific component, by all means consider wrapping the library that does exist.


When there are large mismatches between the APIs used by third-party libraries and the declarative approach that Vue takes, you may find yourself implementing patterns that result in a lot of extra execution time.

Examples In The Wild

The first two of these patterns are used all over the open-source ecosystem, so there are a number of different examples you can investigate. Since wrapping an entire complex component or component library tends to be more of a stopgap/migration solution, I haven’t found as many examples of that in the wild, but there are a couple out there, and I’ve used this approach for clients occasionally as requirements have dictated. Here is a quick example of each:

  1. Vue-moment wraps the moment.js library and creates a set of handy Vue filters;
  2. Awesome-mask wraps the vanilla-masker library and creates a directive for masked inputs;
  3. Vue2-foundation wraps up the ZURB Foundation component library inside of Vue components.

Conclusion

The popularity of Vue.js shows no signs of slowing down, with a huge amount of credit being due to the framework’s progressive approach. By enabling incremental adoption, Vue’s progressive nature means that individuals can start using it here and there, a bit at a time, without having to do massive rewrites.

As we’ve looked at here, that progressive nature extends in the other direction as well. Just as you can embed Vue bit by bit in another application, you can embed other libraries bit by bit inside of Vue.

Need some piece of functionality that hasn’t been ported to a Vue component yet? Pull it in, wrap it up, and you’re good to go.

Further Reading on SmashingMag:

Smashing Editorial
(rb, ra, il)

Source: Smashing Magazine, Sliding In And Out Of Vue.js