Archive

Archive for December, 2018

10 Typography Trends for 2019

December 10th, 2018 No comments
Typography Trends

Can you hear that? That’s the sweet sound of jingle bells followed by the explosion of fireworks. The combination of these two sounds can only mean one thing: 2019 is right around the corner. That might sound a little scary, but I can assure you that this article contains nothing but good vibes and happy thoughts.

As a designer, you’re probably pretty aware that you should be keeping up with trends, right? I certainly hope so. But, that doesn’t mean that you can’t put a little personal flare on those trends. For the purpose of this article, and because the title already says typography trends for 2019, we’re going to discuss… you guessed it: typography trends for 2019. This list is in no particular order. It will contain new trends and a few classics that you totally need to stick with. Fasten your seatbelts, explorers, we’re diving straight in.

Handwritten fonts

We’re going to start this list off with a style of font that will most likely be a trend for many years to come. Handwritten fonts are great because they allow you to put your own touch on your brand, and they bring with them a sense of detail that other fonts can’t. Granted, a handwritten font may not look so great on the side of a corporate office building, but they certainly are a great way to reach out to your audience on a more personal level.

Typography Trends

Vintage fonts

Vintage fonts are also a timeless classic that deserves a spot of any typography trends lists ever. The reason people are so drawn to vintage fonts is very similar to the reason they’re so drawn to handwritten fonts. The difference here is that the audience is most likely already familiar with the font, as it is vintage. Instead of making new connections using a handwritten touch, you renew old connections by going vintage.

Typography Trends

Watercolor fonts

Watercolor fonts have risen in popularity almost side-by-side with handwritten fonts because they go so well together. Watercolors have recently existed mainly in the background of a few web pages. But now, people are starting to use them in the spotlight. Watercolor fonts are a great way to portray calm, cool, and collected vibes. They take away from the seriousness of business and add to the homely feel.

Typography Trends

Serif fonts

Serifs again are nothing new. In fact, they’re probably one of the oldest typography trends we can dig up. They are, however, a trend that’s making a comeback. Serifs can vary depending on how extra you want to be, but they’re another great way to put a little more flare on your work.

Typography Trends

Big and small font types… together?

Yes, it’s true. A lot of people are instantly attracted to things that match or at least are the same size. The idea behind using both big and small fonts together isn’t exactly a new thing, but it has made great headway over the years. Because the letters in the font don’t match up, it can grab someone’s attention quicker than a buy-one-get-one sale at Old Navy. plus, it’s a creative way to put emphasis on a particular part of your brand or logo.

Typography Trends

Variable fonts

In addition to the variation in size, the mix-match of different font types has become a design phenomenon. I mean, why stick to just one font if you’ve found a few that you like? If done correctly, you’ll be able to mix a number of different fonts together and create your own personal masterpiece. Just try not to be too overwhelming.

Typography Trends

Color fonts

For too long black and white fonts have haunted our screens! Okay, maybe that’s a little dramatic, but sometimes we just need a little color. Color fonts have been popular on and off for forever, and they’re starting to make a massive comeback. Color fonts allow us to be that much more creative with our projects. They can say as little or as much as you want them to about the letters that they’re highlighting. They’re the perfect way to snag someone’s attention in a crowd full of black and white.

Typography Trends

Cutouts and overlays

Everyone wants to add layers to their designs, and it’s for good reason. People don’t want to sit and stare at a flat-looking, boring, underwhelming webpage. They want to be wowed and wanting more. Cutouts and overlays are a great way to give that 3-dimensional effect without having to wear the glasses that hurt your eyes after 30 minutes. They give you yet another layer to be creative with, and thus attracting more attention.

Typography Trends

Geometric fonts

While handwritten fonts and different sized lettering are cool, perfectly straight lines and rounded corners will always be one of the typography trends, too. Don’t get me wrong, though, geometric fonts leave plenty of room to be creative. Geometric fonts have grown exponentially over the past year or two, and I don’t see them slowing down anytime soon.

Typography Trends

Customize everything

If you have the extra cash to shell out, customizing your brand is a great way to set your own trends. I’m not talking about just logotypes here, I literally mean customize everything. What better way to give people a new experience than to create one custom for your brand? You’re a designer, challenge yourself!

Bring in the New Year right

Again, these typography trends aren’t in any particular order, but they are all super duper sweet. Trends are made every day. While some of us choose to follow those trends, others create their own path for us to follow in the future. The #1 rule of design is to be yourself and create your best work. Design something that you’re proud of, and show it off to the word.

Read More at 10 Typography Trends for 2019

Categories: Designing, Others Tags:

An Introduction and Guide to the CSS Object Model (CSSOM)

December 10th, 2018 No comments
The CSSStyleDeclaration API in the DevTools console

If you’ve been writing JavaScript for some time now, it’s almost certain you’ve written some scripts dealing with the Document Object Model (DOM). DOM scripting takes advantage of the fact that a web page opens up a set of APIs (or interfaces) so you can manipulate and otherwise deal with elements on a page.

But there’s another object model you might want to become more familiar with: The CSS Object Model (CSSOM). Likely you’ve already used it but didn’t necessarily realize it.

In this guide, I’m going to go through many of the most important features of the CSSOM, starting with stuff that’s more commonly known, then moving on to some more obscure, but practical, features.

What is the CSSOM?

According to MDN:

The CSS Object Model is a set of APIs allowing the manipulation of CSS from JavaScript. It is much like the DOM, but for the CSS rather than the HTML. It allows users to read and modify CSS style dynamically.

MDN’s info is based on the official W3C CSSOM specification. That W3C document is a somewhat decent way to get familiar with what’s possible with the CSSOM, but it’s a complete disaster for anyone looking for some practical coding examples that put the CSSOM APIs into action.

MDN is much better, but still largely lacking in certain areas. So for this post, I’ve tried to do my best to create useful code examples and demos of these interfaces in use, so you can see the possibilities and mess around with the live code.

As mentioned, the post starts with stuff that’s already familiar to most front-end developers. These common features are usually lumped in with DOM scripting, but they are technically part of the larger group of interfaces available via the CSSOM (though they do cross over into the DOM as well).

Inline Styles via element.style

The most basic way you can manipulate or access CSS properties and values using JavaScript is via the style object, or property, which is available on all HTML elements. Here’s an example:

document.body.style.background = 'lightblue';

Most of you have probably seen or used that syntax before. I can add to or change the CSS for any object on the page using that same format: element.style.propertyName.

In that example, I’m changing the value of the background property to lightblue. Of course, background is shorthand. What if I want to change the background-color property? For any hyphenated property, just convert the property name to camel case:

document.body.style.backgroundColor = 'lightblue';

In most cases, a single-word property would be accessed in this way by the single equivalent word in lowercase, while hyphenated properties are represented in camel case. The one exception to this is when using the float property. Because float is a reserved word in JavaScript, you need to use cssFloat (or styleFloat if you’re supporting IE8 and earlier). This is similar to the HTML for attribute being referenced as htmlFor when using something like getAttribute().

Here’s a demo that uses the style property to allow the user to change the background color of the current page:

See the Pen Using the style Object to Change the Background Color by Louis Lazaris (@impressivewebs) on CodePen.

So that’s an easy way to define a CSS property and value using JavaScript. But there’s one huge caveat to using the style property in this way: This will only apply to inline styles on the element.

This becomes clear when you use the style property to read CSS:

document.body.style.backgroundColor = 'lightblue';
console.log(document.body.style.backgroundColor);
// "lightblue"

In the example above, I’m defining an inline style on the element, then I’m logging that same style to the console. That’s fine. But if I try to read another property on that element, it will return nothing — unless I’ve previously defined an inline style for that element in my CSS or elsewhere in my JavaScript. For example:

console.log(document.body.style.color);
// Returns nothing if inline style doesn't exist

This would return nothing even if there was an external stylesheet that defined the color property on the element, as in the following CodePen:

See the Pen element.style Reads Only Inline Styles by Louis Lazaris (@impressivewebs) on CodePen.

Using element.style is the simplest and most common way to add styles to elements via JavaScript. But as you can see, this clearly has some significant limitations, so let’s look at some more useful techniques for reading and manipulating styles with JavaScript.

Getting Computed Styles

You can read the computed CSS value for any CSS property on an element by using the window.getComputedStyle() method:

window.getComputedStyle(document.body).background;
// "rgba(0, 0, 0, 0) none repeat scroll 0% 0% / auto padding-box border-box"

Well, that’s an interesting result. In a way, window.getComputedStyle() is the style property’s overly-benevolent twin. While the style property gives you far too little information about the actual styles on an element, window.getComputedStyle() can sometimes give you too much.

See the Pen The getComputedStyle() Method Can Read any CSS Property by Louis Lazaris (@impressivewebs) on CodePen.

In the example above, the background property of the element was defined using a single value. But the getComputedStyle() method returns all values contained in background shorthand. The ones not explicitly defined in the CSS will return the initial (or default) values for those properties.

This means, for any shorthand property, window.getComputedStyle() will return all the initial values, even if none of them is defined in the CSS:

See the Pen window.getComputedStyle() Returns All Longhand Values for a Shorthand Property by Louis Lazaris (@impressivewebs) on CodePen.

Similarly, for properties like width and height, it will reveal the computed dimensions of the element, regardless of whether those values were specifically defined anywhere in the CSS, as the following interactive demo shows:

See the Pen window.getComputedStyle() Returns Width and Height Values Even if Not Defined in the CSS by Louis Lazaris (@impressivewebs) on CodePen.

Try resizing the parent element in the above demo to see the results. This is somewhat comparable to reading the value of window.innerWidth, except this is the computed CSS for the specified property on the specified element and not just a general window or viewport measurement.

There are a few different ways to access properties using window.getComputedStyle(). I’ve already demonstrated one way, which uses dot-notation to add the camel-cased property name to the end of the method. You can see three different ways to do it in the following code:

// dot notation, same as above
window.getComputedStyle(el).backgroundColor;

// square bracket notation
window.getComputedStyle(el)['background-color'];

// using getPropertyValue()
window.getComputedStyle(el).getPropertyValue('background-color');

The first line uses the same format as in the previous demo. The second line is using square bracket notation, a common JavaScript alternative to dot notation. This format is not recommended and code linters will warn about it. The third example uses the getPropertyValue() method.

The first example requires the use of camel casing (although in this case both float and cssFloat would work) while the next two access the property via the same syntax as that used in CSS (with hyphens, often called “kebab case”).

Here’s the same demo as the previous, but this time using getPropertyValue() to access the widths of the two elements:

See the Pen Using window.getComputedStyle() along with getPropertyValue() by Louis Lazaris (@impressivewebs) on CodePen.

Getting Computed Styles of Pseudo-Elements

One little-known tidbit about window.getComputedStyle() is the fact that it allows you to retrieve style information on pseudo-elements. You’ll often see a window.getComputedStyle() declaration like this:

window.getComputedStyle(document.body, null).width;

Notice the second argument, null, passed into the method. Firefox prior to version 4 required a second argument, which is why you might see it used in legacy code or by those accustomed to including it. But it’s not required in any browser currently in use.

That second optional parameter is what allows me to specify that I’m accessing the computed CSS of a pseudo-element. Consider the following CSS:

.box::before {
  content: 'Example';
  display: block;
  width: 50px;
}

Here I’m adding a ::before pseudo-element inside the .box element. With the following JavaScript, I can access the computed styles for that pseudo-element:

let box = document.querySelector('.box');
window.getComputedStyle(box, '::before').width;
// "50px"

See the Pen Using getComputedStyle() to get styles from a pseudo-element by Louis Lazaris (@impressivewebs) on CodePen.

You can also do this for other pseudo-elements like ::first-line, as in the following code and demo:

let p = document.querySelector('.box p');
window.getComputedStyle(p, '::first-line').color;

See the Pen Using getComputedStyle() to get styles from a pseudo-element by Louis Lazaris (@impressivewebs) on CodePen.

And here’s another example using the ::placeholder pseudo-element, which apples to elements:

let input = document.querySelector('input');
window.getComputedStyle(input, '::placeholder').color

See the Pen Using getComputedStyle() to get styles from a ::placeholder pseudo-element by Louis Lazaris (@impressivewebs) on CodePen.

The above works in the latest Firefox, but not in Chrome or Edge (I’ve filed a bug report for Chrome).

It should also be noted that browsers have different results when trying to access styles for a non-existent (but valid) pseudo-element compared to a pseudo-element that the browser doesn’t support at all (like a made up ::banana pseudo-element). You can try this out in various browsers using the following demo:

See the Pen Testing getComputedStyle() on non-existent pseudo-elements by Louis Lazaris (@impressivewebs) on CodePen.

As a side point to this section, there is a Firefox-only method called getDefaultComputedStyle() that is not part of the spec and likely never will be.

The CSSStyleDeclaration API

Earlier when I showed you how to access properties via the style object or using getComputedStyle(), in both cases those techniques were exposing the CSSStyleDeclaration interface.

In other words, both of the following lines will return a CSSStyleDeclaration object on the document’s body element:

document.body.style;
window.getComputedStyle(document.body);

In the following screenshot you can see what the console produces for each of these lines:

The CSSStyleDeclaration API in the DevTools console

In the case of getComputedStyle(), the values are read-only. In the case of element.style, getting and setting the values is possible but, as mentioned earlier, these will only affect the document’s inline styles.

setProperty(), getPropertyValue(), and item()

Once you’ve exposed a CSSStyleDeclaration object in one of the above ways, you have access to a number of useful methods to read or manipulate the values. Again, the values are read-only in the case of getComputedStyle(), but when used via the style property, some methods are available for both getting and setting.

Consider the following code and demo:

let box = document.querySelector('.box');

box.style.setProperty('color', 'orange');
box.style.setProperty('font-family', 'Georgia, serif');
op.innerHTML = box.style.getPropertyValue('color');
op2.innerHTML = `${box.style.item(0)}, ${box.style.item(1)}`;

See the Pen Using Three Different Methods of the CSSStyleDeclaration API by Louis Lazaris (@impressivewebs) on CodePen.

In this example, I’m using three different methods of the style object:

  • The setProperty() method. This takes two arguments, each a string: The property (in regular CSS notation) and the value you wish to assign to the property.
  • The getPropertyValue() method. This takes a single argument: The property whose value you want to obtain. This method was used in a previous example using getComputedStyle(), which, as mentioned, likewise exposes a CSSStyleDeclaration object.
  • The item() method. This takes a single argument, which is a positive integer representing the index of the property you want to access. The return value is the property name at that index.

Keep in mind that in my simple example above, there are only two styles added to the element’s inline CSS. This means that if I were to access item(2), the return value would be an empty string. I’d get the same result if I used getPropertyValue() to access a property that isn’t set in that element’s inline styles.

Using removeProperty()

In addition to the three methods mentioned above, there are two others exposed on a CSSStyleDeclaration object. In the following code and demo, I’m using the removeProperty() method:

box.style.setProperty('font-size', '1.5em');
box.style.item(0) // "font-size"

document.body.style.removeProperty('font-size');
document.body.style.item(0); // ""

See the Pen Using the removeProperty() method of the CSSSTyleDeclaration API by Louis Lazaris (@impressivewebs) on CodePen.

In this case, after I set font-size using setProperty(), I log the property name to ensure it’s there. The demo then includes a button that, when clicked, will remove the property using removeProperty().

In the case of setProperty() and removeProperty(), the property name that you pass in is hyphenated (the same format as in your stylesheet), rather than camel-cased. This might seem confusing at first, but the value passed in is a string in this example, so it makes sense.

Getting and Setting a Property’s Priority

Finally, here’s an interesting feature that I discovered while researching this article: The getPropertyPriority() method, demonstrated with the code and CodePen below:

box.style.setProperty('font-family', 'Georgia, serif', 'important');
box.style.setProperty('font-size', '1.5em');

box.style.getPropertyPriority('font-family'); // important
op2.innerHTML = box.style.getPropertyPriority('font-size'); // ""

See the Pen Using getPropertyPriority() to get a property’s “importance” by Louis Lazaris (@impressivewebs) on CodePen.

In the first line of that code, you can see I’m using the setProperty() method, as I did before. However, notice I’ve included a third argument. The third argument is an optional string that defines whether you want the property to have the !important keyword attached to it.

After I set the property with !important, I use the getPropertyPriority() method to check that property’s priority. If you want the property to not have importance, you can omit the third argument, use the keyword undefined, or include the third argument as an empty string.

And I should emphasize here that these methods would work in conjunction with any inline styles already placed directly in the HTML on an element’s style attribute.

So if I had the following HTML:

<div class="box" style="border: solid 1px red !important;">

I could use any of the methods discussed in this section to read or otherwise manipulate that style. And it should be noted here that since I used a shorthand property for this inline style and set it to !important, all of the longhand properties that make up that shorthand will return a priority of important when using getPropertyPriority(). See the code and demo below:

// These all return "important"
box.style.getPropertyPriority('border'));
box.style.getPropertyPriority('border-top-width'));
box.style.getPropertyPriority('border-bottom-width'));
box.style.getPropertyPriority('border-color'));
box.style.getPropertyPriority('border-style'));

See the Pen Using getPropertyPriority() to check the priority of longhand properties by Louis Lazaris (@impressivewebs) on CodePen.

In the demo, even though I explicitly set only the border property in the style attribute, all the associated longhand properties that make up border will also return a value of important.

The CSSStyleSheet Interface

So far, much of what I’ve considered deals with inline styles (which often aren’t that useful) and computed styles (which are useful, but are often too specific).

A much more useful API that allows you to retrieve a stylesheet that has readable and writable values, and not just for inline styles, is the CSSStyleSheet API. The simplest way to access information from a document’s stylesheets is using the styleSheets property of the current document. This exposes the CSSStyleSheet interface.

For example, the line below uses the length property to see how many stylesheets the current document has:

document.styleSheets.length; // 1

I can reference any of the document’s stylesheets using zero-based indexing:

document.styleSheets[0];

If I log that stylesheet to my console, I can view the methods and properties available:

The CSSStyleSheet Interface in the DevTools Console

The one that will prove useful is the cssRules property. This property provides a list of all CSS rules (including declaration blocks, at-rules, media rules, etc.) contained in that stylesheet. In the following sections, I’ll detail how to utilize this API to manipulate and read styles from an external stylesheet.

Working with a Stylesheet Object

For the purpose of simplicity, let’s work with a sample stylesheet that has only a handful of rules in it. This will allow me to demonstrate how to use the CSSOM to access the different parts of a stylesheet in a similar way to accessing elements via DOM scripting.

Here is the stylesheet I’ll be working with:

* {
  box-sizing: border-box;
}

body {
  font-family: Helvetica, Arial, sans-serif;
  font-size: 2em;
  line-height: 1.4;
}

main {
  width: 1024px;
  margin: 0 auto !important;
}

.component {
  float: right;
  border-left: solid 1px #444;
  margin-left: 20px;
}

@media (max-width: 800px) {
  body {
    line-height: 1.2;
  }

  .component {
    float: none;
    margin: 0;
  }
}

a:hover {
  color: lightgreen;
}

@keyframes exampleAnimation {
  from {
    color: blue;
  }
  
  20% {
    color: orange;
  }
  
  to {
    color: green;
  }
}

code {
  color: firebrick;
}

There’s a number of different things I can attempt with this example stylesheet and I’ll demonstrate a few of those here. First, I’m going to loop through all the style rules in the stylesheet and log the selector text for each one:

let myRules = document.styleSheets[0].cssRules,
    p = document.querySelector('p');

for (i of myRules) {
  if (i.type === 1) {
    p.innerHTML += `<c​ode>${i.selectorText}</c​ode><br>`;
  }
}

See the Pen Working with CSSStyleSheet – Logging the Selector Text by Louis Lazaris (@impressivewebs) on CodePen.

A couple of things to take note of in the above code and demo. First, I cache a reference to the cssRules object for my stylesheet. Then I loop over all the rules in that object, checking to see what type each one is.

In this case, I want rules that are type 1, which represents the STYLE_RULE constant. Other constants include IMPORT_RULE (3), MEDIA_RULE (4), KEYFRAMES_RULE (7), etc. You can view a full table of these constants in this MDN article.

When I confirm that a rule is a style rule, I print the selectorText property for each of those style rules. This will produce the following lines for the specified stylesheet:

*
body
main
.component
a:hover
code

The selectorText property is a string representation of the selector used on that rule. This is a writable property, so if I want I can change the selector for a specific rule inside my original for loop with the following code:

if (i.selectorText === 'a:hover') {
  i.selectorText = 'a:hover, a:active';
}

See the Pen Working with the CSSStyleSheet API – Changing the Selector Text by Louis Lazaris (@impressivewebs) on CodePen.

In this example, I’m looking for a selector that defines :hover styles on my links and expanding the selector to apply the same styles to elements in the :active state. Alternatively, I could use some kind of string method or even a regular expression to look for all instances of :hover, and then do something from there. But this should be enough to demonstrate how it works.

Accessing @media Rules with the CSSOM

You’ll notice my stylesheet also includes a media query rule and a keyframes at-rule block. Both of those were skipped when I searched for style rules (type 1). Let’s now find all @media rules:

let myRules = document.styleSheets[0].cssRules,
    p = document.querySelector('.output');

for (i of myRules) {
  if (i.type === 4) {
    for (j of i.cssRules) {
      p.innerHTML += `<c​ode>${j.selectorText}</c​ode><br>`;
    }
  }
}

Based on the given stylesheet, the above will produce:

body
.component

See the Pen Working with the CSSStyleSheet API – Accessing @media Rules by Louis Lazaris (@impressivewebs) on CodePen.

As you can see, after I loop through all the rules to see if any @media rules exist (type 4), I then loop through the cssRules object for each media rule (in this case, there’s only one) and log the selector text for each rule inside that media rule.

So the interface that’s exposed on a @media rule is similar to the interface exposed on a stylesheet. The @media rule, however, also includes a conditionText property, as shown in the following snippet and demo:

let myRules = document.styleSheets[0].cssRules,
    p = document.querySelector('.output');

for (i of myRules) {
  if (i.type === 4) {
    p.innerHTML += `<c​ode>${i.conditionText}</c​ode><br>`;
    // (max-width: 800px) 
  }
}

See the Pen Working with the CSSStyleSheet API – Accessing @media Rules by Louis Lazaris (@impressivewebs) on CodePen.

This code loops through all media query rules and logs the text that determines when that rule is applicable (i.e. the condition). There’s also a mediaText property that returns the same value. According to the spec, you can get or set either of these.

Accessing @keyframes Rules with the CSSOM

Now that I’ve demonstrated how to read information from a @media rule, let’s consider how to access a @keyframes rule. Here’s some code to get started:

let myRules = document.styleSheets[0].cssRules,
    p = document.querySelector('.output');

for (i of myRules) {
  if (i.type === 7) {
    for (j of i.cssRules) {
     p.innerHTML += `<c​ode>${j.keyText}</c​ode><br>`;
    }
  }
}

See the Pen Working with the CSSStyleSheet API – Accessing @keyframes Rules by Louis Lazaris (@impressivewebs) on CodePen.

In this example, I’m looking for rules that have a type of 7 (i.e. @keyframes rules). When one is found, I loop through all of that rule’s cssRules and log the keyText property for each. The log in this case will be:

"0%"
"20%"
"100%"

You’ll notice my original CSS uses from and to as the first and last keyframes, but the keyText property computes these to 0% and 100%. The value of keyText can also be set. In my example stylesheet, I could hard code it like this:

// Read the current value (0%)
document.styleSheets[0].cssRules[6].cssRules[0].keyText;

// Change the value to 10%
document.styleSheets[0].cssRules[6].cssRules[0].keyText = '10%'

// Read the new value (10%)
document.styleSheets[0].cssRules[6].cssRules[0].keyText;

See the Pen Working with the CSSStyleSheet API – Setting @keyframes Rules by Louis Lazaris (@impressivewebs) on CodePen.

Using this, we can dynamically alter an animation’s keyframes in the flow of a web app or possibly in response to a user action.

Another property available when accessing a @keyframes rule is name:

let myRules = document.styleSheets[0].cssRules,
    p = document.querySelector('.output');

for (i of myRules) {
  if (i.type === 7) {
    p.innerHTML += `<c​ode>${i.name}</c​ode><br>`;
  }
}

See the Pen Working with the CSSStyleSheet API – Getting the name of a @keyframes rule by Louis Lazaris (@impressivewebs) on CodePen.

Recall that in the CSS, the @keyframes rule looks like this:

@keyframes exampleAnimation {
  from {
    color: blue;
  }
  
  20% {
    color: orange;
  }
  
  to {
    color: green;
  }
}

Thus, the name property allows me to read the custom name chosen for that @keyframes rule. This is the same name that would be used in the animation-name property when enabling the animation on a specific element.

One final thing I’ll mention here is the ability to grab specific styles that are inside a single keyframe. Here’s some example code with a demo:

let myRules = document.styleSheets[0].cssRules,
    p = document.querySelector('.output');

for (i of myRules) {
  if (i.type === 7) {
    for (j of i.cssRules) {
      p.innerHTML += `<c​ode>${j.style.color}</c​ode><br>`;
    }
  }
}

See the Pen Working with the CSSStyleSheet API – Accessing Property Values inside @keyframes Rules by Louis Lazaris (@impressivewebs) on CodePen.

In this example, after I find the @keyframes rule, I loop through each of the rules in the keyframe (e.g. the “from” rule, the “20%” rule, etc). Then, within each of those rules, I access an individual style property. In this case, since I know color is the only property defined for each, I’m merely logging out the color values.

The main takeaway in this instance is the use of the style property, or object. Earlier I showed how this property can be used to access inline styles. But in this case, I’m using it to access the individual properties inside of a single keyframe.

You can probably see how this opens up some possibilities. This allows you to modify an individual keyframe’s properties on the fly, which could happen as a result of some user action or something else taking place in an app or possibly a web-based game.

Adding and Removing CSS Declarations

The CSSStyleSheet interface has access to two methods that allow you to add or remove an entire rule from a stylesheet. The methods are: insertRule() and deleteRule(). Let’s see both of them in action manipulating our example stylesheet:

let myStylesheet = document.styleSheets[0];
console.log(myStylesheet.cssRules.length); // 8

document.styleSheets[0].insertRule('article { line-height: 1.5; font-size: 1.5em; }', myStylesheet.cssRules.length);
console.log(document.styleSheets[0].cssRules.length); // 9

See the Pen Working with the CSSStyleSheet API – Inserting Rules by Louis Lazaris (@impressivewebs) on CodePen.

In this case, I’m logging the length of the cssRules property (showing that the stylesheet originally has 8 rules in it), then I add the following CSS as an individual rule using the insertRule() method:

article {
  line-height: 1.5;
  font-size: 1.5em;
}

I log the length of the cssRules property again to confirm that the rule was added.

The insertRule() method takes a string as the first parameter (which is mandatory), comprising the full style rule that you want to insert (including selector, curly braces, etc). If you’re inserting an at-rule, then the full at-rule, including the individual rules nested inside the at-rule can be included in this string.

The second argument is optional. This is an integer that represents the position, or index, where you want the rule inserted. If this isn’t included, it defaults to 0 (meaning the rule will be inserted at the beginning of the rules collection). If the index happens to be larger than the length of the rules object, it will throw an error.

The deleteRule() method is much simpler to use:

let myStylesheet = document.styleSheets[0];
console.log(myStylesheet.cssRules.length); // 8

myStylesheet.deleteRule(3);
console.log(myStylesheet.cssRules.length); // 7

See the Pen Working with the CSSStyleSheet API – Deleting Rules by Louis Lazaris (@impressivewebs) on CodePen.

In this case, the method accepts a single argument that represents the index of the rule I want to remove.

With either method, because of zero-based indexing, the selected index passed in as an argument has to be less than the length of the cssRules object, otherwise it will throw an error.

Revisiting the CSSStyleDeclaration API

Earlier I explained how to access individual properties and values declared as inline styles. This was done via element.style, exposing the CSSStyleDeclaration interface.

The CSSStyleDeclaration API, however, can also be exposed on an individual style rule as a subset of the CSSStyleSheet API. I already alluded to this when I showed you how to access properties inside a @keyframes rule. To understand how this works, compare the following two code snippets:

<div style="color: lightblue; width: 100px; font-size: 1.3em !important;"></div>
.box {
  color: lightblue;
  width: 100px;
  font-size: 1.3em !important;
}

The first example is a set of inline styles that can be accessed as follows:

document.querySelector('div').style

This exposes the CSSStyleDeclaration API, which is what allows me to do stuff like element.style.color, element.style.width, etc.

But I can expose the exact same API on an individual style rule in an external stylesheet. This means I’m combining my use of the style property with the CSSStyleSheet interface.

So the CSS in the second example above, which uses the exact same styles as the inline version, can be accessed like this:

document.styleSheets[0].cssRules[0].style

This opens up a single CSSStyleDeclaration object on the one style rule in the stylesheet. If there were multiple style rules, each could be accessed using cssRules[1], cssRules[2], cssRules[3], and so on.

So within an external stylesheet, inside of a single style rule that is of type 1, I have access to all the methods and properties mentioned earlier. This includes setProperty(), getPropertyValue(), item(), removeProperty(), and getPropertyPriority(). In addition to this, those same features are available on an individual style rule inside of a @keyframes or @media rule.

Here’s a code snippet and demo that demonstrates how these methods would be used on an individual style rule in our sample stylesheet:

// Grab the style rules for the body and main elements
let myBodyRule = document.styleSheets[0].cssRules[1].style,
    myMainRule = document.styleSheets[0].cssRules[2].style;

// Set the bg color on the body
myBodyRule.setProperty('background-color', 'peachpuff');

// Get the font size of the body
myBodyRule.getPropertyValue('font-size');

// Get the 5th item in the body's style rule
myBodyRule.item(5);

// Log the current length of the body style rule (8)
myBodyRule.length;

// Remove the line height
myBodyRule.removeProperty('line-height');

// log the length again (7)
myBodyRule.length;

// Check priority of font-family (empty string)
myBodyRule.getPropertyPriority('font-family');

// Check priority of margin in the "main" style rule (!important)
myMainRule.getPropertyPriority('margin');

See the Pen Working with the style object of an individual style rule in an external Stylesheet by Louis Lazaris (@impressivewebs) on CodePen.

The CSS Typed Object Model… The Future?

After everything I’ve considered in this article, it would seem odd that I’d have to break the news that it’s possible that one day the CSSOM as we know it will be mostly obsolete.

That’s because of something called the CSS Typed OM which is part of the Houdini Project. Although some people have noted that the new Typed OM is more verbose compared to the current CSSOM, the benefits, as outlined in this article by Eric Bidelman, include:

  • Fewer bugs
  • Arithmetic operations and unit conversion
  • Better performance
  • Error handling
  • CSS property names are always strings

For full details on those features and a glimpse into the syntax, be sure to check out the full article.

As of this writing, CSS Typed OM is supported only in Chrome. You can see the progress of browser support in this document.

Final Words

Manipulating stylesheets via JavaScript certainly isn’t something you’re going to do in every project. And some of the complex interactions made possible with the methods and properties I’ve introduced here have some very specific use cases.

If you’ve built some kind of tool that uses any of these APIs I’d love to hear about it. My research has only scratched the surface of what’s possible, but I’d love to see how any of this can be used in real-world examples.

I’ve put all the demos from this article into a CodePen collection, so you can feel free to mess around with those as you like.

The post An Introduction and Guide to the CSS Object Model (CSSOM) appeared first on CSS-Tricks.

Categories: Designing, Others Tags:

Google Labs Web Components

December 10th, 2018 No comments

I think it’s kinda cool to see Google dropping repos of interesting web components. It demonstrates the possibilities of cool new web features and allows them to ship them in a way that’s compatible with entirely web standards.

Here’s one:

I wanted to give it a try, so I linked up their example two-up-min.js script in a Pen and used the element by itself to see how it works. They expose the component’s styling with custom properties, which I’d say is a darn nice use case for those.

<p data-height="455" data-theme-id="1" data-slug-hash="YRowgW" data-default-tab="html,result" data-user="chriscoyier" data-pen-title="”>See the Pen <two-up&rt; by Chris Coyier (@chriscoyier) on CodePen.

The post Google Labs Web Components appeared first on CSS-Tricks.

Categories: Designing, Others Tags:

How To Build A Real-Time App With GraphQL Subscriptions On Postgres

December 10th, 2018 No comments
A demonstration of the features in the polling app that is built in this tutorial

How To Build A Real-Time App With GraphQL Subscriptions On Postgres

How To Build A Real-Time App With GraphQL Subscriptions On Postgres

Sandip Devarkonda

2018-12-10T14:00:23+01:002018-12-10T14:33:33+00:00

In this article, we’ll take a look at the challenges involved in building real-time applications and how emerging tooling is addressing them with elegant solutions that are easy to reason about. To do this, we’ll build a real-time polling app (like a Twitter poll with real-time overall stats) just by using Postgres, GraphQL, React and no backend code!

The primary focus will be on setting up the backend (deploying the ready-to-use tools, schema modeling), and aspects of frontend integration with GraphQL and less on UI/UX of the frontend (some knowledge of ReactJS will help). The tutorial section will take a paint-by-numbers approach, so we’ll just clone a GitHub repo for the schema modeling, and the UI and tweak it, instead of building the entire app from scratch.

All Things GraphQL

Do you know everything you need to know about GraphQL? If you have your doubts, Eric Baer has you covered with a detailed guide on its origins, its drawbacks and the basics of how to work with it. Read article ?

Before you continue reading this article, I’d like to mention that a working knowledge of the following technologies (or substitutes) are beneficial:

  • ReactJS
    This can be replaced with any frontend framework, Android or IOS by following the client library documentation.
  • Postgres
    You can work with other databases but with different tools, the principles outlined in this post will still apply.

You can also adapt this tutorial context for other real-time apps very easily.

A demonstration of the features in the polling app that we’ll be building. (Large preview)

As illustrated by the accompanying GraphQL payload at the bottom, there are three major features that we need to implement:

  1. Fetch the poll question and a list of options (top left).
  2. Allow a user to vote for a given poll question (the “Vote” button).
  3. Fetch results of the poll in real-time and display them in a bar graph (top right; we can gloss over the feature to fetch a list of currently online users as it’s an exact replica of this use case).

Challenges With Building Real-Time Apps

Building real-time apps (especially as a frontend developer or someone who’s recently made a transition to becoming a fullstack developer), is a hard engineering problem to solve.

This is generally how contemporary real-time apps work (in the context of our example app):

  1. The frontend updates a database with some information; A user’s vote is sent to the backend, i.e. poll/option and user information (user_id, option_id).
  2. The first update triggers another service that aggregates the poll data to render an output that is relayed back to the app in real-time (every time a new vote is cast by anyone; if this done efficiently, only the updated poll’s data is processed and only those clients that have subscribed to this poll are updated):
    • Vote data is first processed by an register_vote service (assume that some validation happens here) that triggers a poll_results service.
    • Real-time aggregated poll data is relayed by the poll_results service to the frontend for displaying overall statistics.

Traditional design for a real-time poll app

A poll app designed traditionally

This model is derived from a traditional API-building approach, and consequently has similar problems:

  1. Any of the sequential steps could go wrong, leaving the UX hanging and affecting other independent operations.
  2. Requires a lot of effort on the API layer as it’s a single point of contact for the frontend app, that interacts with multiple services. It also needs to implement a websockets-based real-time API — there is no universal standard for this and therefore sees limited support for automation in tools.
  3. The frontend app is required to add the necessary plumbing to consume the real-time API and may also have to solve the data consistency problem typically seen in real-time apps (less important in our chosen example, but critical in ordering messages in a real-time chat app).
  4. Many implementations resort to using additional non-relational databases on the server-side (Firebase, etc.) for easy real-time API support.

Let’s take a look at how GraphQL and associated tooling address these challenges.

What Is GraphQL?

GraphQL is a specification for a query language for APIs, and a server-side runtime for executing queries. This specification was developed by Facebook to accelerate app development and provide a standardized, database-agnostic data access format. Any specification-compliant GraphQL server must support the following:

  1. Queries for reads
    A request type for requesting nested data from a data source (which can be either one or a combination of a database, a REST API or another GraphQL schema/server).
  2. Mutations for writes
    A request type for writing/relaying data into the aforementioned data sources.
  3. Subscriptions for live-queries
    A request type for clients to subscribe to real-time updates.

GraphQL also uses a typed schema. The ecosystem has plenty of tools that help you identify errors at dev/compile time which results in fewer runtime bugs.

Here’s why GraphQL is great for real-time apps:

  • Live-queries (subscriptions) are an implicit part of the GraphQL specification. Any GraphQL system has to have native real-time API capabilities.
  • A standard spec for real-time queries has consolidated community efforts around client-side tooling, resulting in a very intuitive way of integrating with GraphQL APIs.

GraphQL and a combination of open-source tooling for database events and serverless/cloud functions offer a great substrate for building cloud-native applications with asynchronous business logic and real-time features that are easy to build and manage. This new paradigm also results in great user and developer experience.

In the rest of this article, I will use open-source tools to build an app based on this architecture diagram:


GraphQL-based design for a real-time poll app

A poll app designed with GraphQL

Building A Real-Time Poll/Voting App

With that introduction to GraphQL, let’s get back to building the polling app as described in the first section.

The three features (or stories highlighted) have been chosen to demonstrate the different GraphQL requests types that our app will make:

  1. Query
    Fetch the poll question and its options.
  2. Mutation
    Let a user cast a vote.
  3. Subscription
    Display a real-time dashboard for poll results.

GraphQL elements in the poll app

GraphQL request types in the poll app (Large preview)

Prerequisites

  • A Heroku account (use the free tier, no credit card required)
    To deploy a GraphQL backend (see next point below) and a Postgres instance.
  • Hasura GraphQL Engine (free, open-source)/>A ready-to-use GraphQL server on Postgres.
  • Apollo Client (free, open-source SDK)
    For easily integrating clients apps with a GraphQL server.
  • npm (free, open-source package manager)
    To run our React app.

Deploying The Database And A GraphQL Backend

We will deploy an instance each of Postgres and GraphQL Engine on Heroku’s free tier. We can use a nifty Heroku button to do this with a single click.

Heroku button
Heroku button

Note: You can also follow this link or search for documentation Hasura GraphQL deployment for Heroku (or other platforms).


Deploying app backend to Heroku's free tier

Deploying Postgres and GraphQL Engine to Heroku’s free tier (Large preview)

You will not need any additional configuration, and you can just click on the “Deploy app” button. Once the deployment is complete, make a note of the app URL:

<app-name>.herokuapp.com

For example, in the screenshot above, it would be:

hge-realtime-app-tutorial.herokuapp.com

What we’ve done so far is deploy an instance of Postgres (as an add-on in Heroku parlance) and an instance of GraphQL Engine that is configured to use this Postgres instance. As a result of doing so, we now have a ready-to-use GraphQL API but, since we don’t have any tables or data in our database, this is not useful yet. So, let’s address this immediately.

Modeling the database schema

The following schema diagram captures a simple relational database schema for our poll app:


Schema design for the poll app

Schema design for the poll app. (Large preview)

As you can see, the schema is a simple, normalized one that leverages foreign-key constraints. It is these constraints that are interpreted by the GraphQL Engine as 1:1 or 1:many relationships (e.g. poll:options is a 1: many relationship since each poll will have more than 1 option that are linked by the foreign key constraint between the id column of the poll table and the poll_id column in the option table). Related data can be modelled as a graph and can thus power a GraphQL API. This is precisely what the GraphQL Engine does.

Based on the above, we’ll have to create the following tables and constraints to model our schema:

  1. Poll
    A table to capture the poll question.
  2. Option
    Options for each poll.
  3. Vote
    To record a user’s vote.
  4. Foreign-key constraint between the following fields (table : column):
    • option : poll_id ? poll : id
    • vote : poll_id ? poll : id
    • vote : created_by_user_id ? user : id

Now that we have our schema design, let’s implement it in our Postgres database. To instantly bring this schema up, here’s what we’ll do:

  1. Download the GraphQL Engine CLI.
  2. Clone this repo:
    $ git clone clone https://github.com/hasura/graphql-engine
    
    $ cd graphql-engine/community/examples/realtime-poll
  3. Go to hasura/ and edit config.yaml:
    endpoint: https://<app-name>.herokuapp.com
  4. Apply the migrations using the CLI, from inside the project directory (that you just downloaded by cloning):
    $ hasura migrate apply

That’s it for the backend. You can now open the GraphQL Engine console and check that all the tables are present (the console is available at https://.herokuapp.com/console).

Note: You could also have used the console to implement the schema by creating individual tables and then adding constraints using a UI. Using the built-in support for migrations in GraphQL Engine is just a convenient option that was available because our sample repo has migrations for bringing up the required tables and configuring relationships/constraints (this is also highly recommended regardless of whether you are building a hobby project or a production-ready app).

Integrating The Frontend React App With The GraphQL Backend

The frontend in this tutorial is a simple app that shows poll question, the option to vote and the aggregated poll results in one place. As I mentioned earlier, we’ll first focus on running this app so you get the instant gratification of using our recently deployed GraphQL API , see how the GraphQL concepts we looked at earlier in this article power the different use-cases of such an app, and then explore how the GraphQL integration works under the hood.

NOTE: If you are new to ReactJS, you may want to check out some of these articles. We won’t be getting into the details of the React part of the app, and instead, will focus more on the GraphQL aspects of the app. You can refer to the source code in the repo for any details of how the React app has been built.

Configuring The Frontend App
  1. In the repo cloned in the previous section, edit HASURA_GRAPHQL_ENGINE_HOSTNAME in the src/apollo.js file (inside the /community/examples/realtime-poll folder) and set it to the Heroku app URL from above:
    export const HASURA_GRAPHQL_ENGINE_HOSTNAME = 'random-string-123.herokuapp.com';
  2. Go to the root of the repository/app-folder (/realtime-poll/) and use npm to install the prequisite modules and then run the app:
    $ npm install
    
    $ npm start
    

Screenshot of the live poll app

Screenshot of the live poll app (Large preview)

You should be able to play around with the app now. Go ahead and vote as many times as you want, you’ll notice the results changing in real time. In fact, if you set up another instance of this UI and point it to the same backend, you’ll be able to see results aggregated across all the instances.

So, how does this app use GraphQL? Read on.

Behind The Scenes: GraphQL

In this section, we’ll explore the GraphQL features powering the app, followed by a demonstration of the ease of integration in the next one.

The Poll Component And The Aggregated Results Graph

The poll component on the top left that fetches a poll with all of its options and captures a user’s vote in the database. Both of these operations are done using the GraphQL API. For fetching a poll’s details, we make a query (remember this from the GraphQL introduction?):

query {
  poll {
    id
    question
    options {
      id
      text
    }
  }
}

Using the Mutation component from react-apollo, we can wire up the mutation to a HTML form such that the mutation is executed using variables optionId and userId when the form is submitted:

mutation vote($optionId: uuid!, $userId: uuid!) {
  insert_vote(objects: [{option_id: $optionId, created_by_user_id: $userId}]) {
    returning {
      id
    }
  }
}

To show the poll results, we need to derive the count of votes per option from the data in vote table. We can create a Postgres View and track it using GraphQL Engine to make this derived data available over GraphQL.

CREATE VIEW poll_results AS
 SELECT poll.id AS poll_id, o.option_id, count(*) AS votes
 FROM (( SELECT vote.option_id, option.poll_id, option.text
   FROM ( vote
          LEFT JOIN 
      public.option ON ((option.id = vote.option_id)))) o
 
           LEFT JOIN poll ON ((poll.id = o.poll_id)))
 GROUP BY poll.question, o.option_id, poll.id;

The poll_results view joins data from vote and poll tables to provide an aggregate count of number of votes per each option.

Using GraphQL Subscriptions over this view, react-google-charts and the subscription component from react-apollo, we can wire up a reactive chart which updates in realtime when a new vote happens from any client.

subscription getResult($pollId: uuid!) {
  poll_results(where: {poll_id: {_eq: $pollId}}) {
    option {
      id
      text
    }
    votes
  }
}

GraphQL API Integration

As I mentioned earlier, I used Apollo Client, an open-source SDK to integrate a ReactJS app with the GraphQL backend. Apollo Client is analogous to any HTTP client library like requests for python, the standard http module for JavaScript, and so on. It encapsulates the details of making an HTTP request (in this case POST requests). It uses the configuration (specified in src/apollo.js) to make query/mutation/subscription requests (specified in src/GraphQL.jsx with the option to use variables that can be dynamically substituted in the JavaScript code of your REACT app) to a GraphQL endpoint. It also leverages the typed schema behind the GraphQL endpoint to provide compile/dev time validation for the aforementioned requests. Let’s see just how easy it is for a client app to make a live-query (subscription) request to the GraphQL API.

Configuring The SDK

The Apollo Client SDK needs to be pointed at a GraphQL server, so it can automatically handle the boilerplate code typically needed for such an integration. So, this is exactly what we did when we modified src/apollo.js when setting up the frontend app.

Making A GraphQL Subscription Request (Live-Query)

Define the subscription we looked at in the previous section in the src/GraphQL.jsx file:

const SUBSCRIPTION_RESULT = `
subscription getResult($pollId: uuid!) {
  poll_results (
    order_by: option_id_desc,
    where: { poll_id: {_eq: $pollId} }
  ) {
    option_id
    option { id text }
    votes
  }
}`;

We’ll use this definition to wire up our React component:

export const Result = (pollId) => (
  <Subscription subscription={gql`${SUBSCRIPTION_RESULT}`} variables={pollId}>
    {({ loading, error, data }) => {
       if (loading) return 

Loading...</p>; if (error) return

Error :</p>; return ( <div> <div> {renderChart(data)} </div> </div> ); }} </Subscription> )

One thing to note here is that the above subscription could also have been a query. Merely replacing one keyword for another gives us a “live-query”, and that’s all it takes for the Apollo Client SDK to hook this real-time API with your app. Every time there’s a new dataset from our live-query, the SDK triggers a re-render of our chart with this updated data (using the renderChart(data) call). That’s it. It really is that simple!

Final Thoughts

In three simple steps (creating a GraphQL backend, modeling the app schema, and integrating the frontend with the GraphQL API), you can quickly wire-up a fully-functional real-time app, without getting mired in unnecessary details such as setting up a websocket connection. That right there is the power of community tooling backing an abstraction like GraphQL.

If you’ve found this interesting and want to explore GraphQL further for your next side project or production app, here are some factors you may want to use for building your GraphQL toolchain:

  • Performance & Scalability
    GraphQL is meant to be consumed directly by frontend apps (it’s no better than an ORM in the backend; real productivity benefits come from doing this). So your tooling needs to be smart about efficiently using database connections and should be able scale effortlessly.
  • Security
    It follows from above that a mature role-based access-control system is needed to authorize access to data.
  • Automation
    If you are new to the GraphQL ecosystem, handwriting a GraphQL schema and implementing a GraphQL server may seem like daunting tasks. Maximize the automation from your tooling so you can focus on the important stuff like building user-centric frontend features.
  • Architecture/>As trivial as the above efforts seem like, a production-grade app’s backend architecture may involve advanced GraphQL concepts like schema-stitching, etc. Moreover, the ability to easily generate/consume real-time APIs opens up the possibility of building asynchronous, reactive apps that are resilient and inherently scalable. Therefore, it’s critical to evaluate how GraphQL tooling can streamline your architecture.

Related Resources

  • You can check out a live version of the app over here.
  • The complete source code is available on GitHub.
  • If you’d like to explore the database schema and run test GraphQL queries, you can do so over here.
Smashing Editorial(rb, ra, yk, il)
Categories: Others Tags:

What do you name color variables?

December 7th, 2018 No comments

What naming scheme do you use for color variables?
Have you succeeded at writing CSS that uses color variables in a manner agnostic to the colors they represent?
I’ve tried all of the following, and I have yet to succeed at writing CSS that works well with any color scheme. ??

— Lea Verou (@LeaVerou) October 14, 2018

I remember the very first time I tried Sass on a project. The first thing I wanted to do was variablize my colors. From my naming-things-in-HTML skillz, I knew to avoid classes like .header-blue-left-bottom because the color and position of that element might change. It’s better for the to reflect it what it is than what it looks like.

So, I tried to make my colors semantic, in a sense — what they represent not what they literally are:

$mainBrandColor: #F060D6;
$secondaryFocus: #4C9FEB;
$fadedHighlight: #F1F3F4;

But I found that I absolutely never remembered them and had to constantly refer to where I defined them in order to use them. Later, in a “screw it” moment, I named colors more like…

$orange: #F060D6;
$red: #BB532E;
$blue: #4C9FEB;

$gray-1: #eee;
$gray-2: #ccc;
$gray-3: #555;

I found that to be much more intuitive with little if any negative side effects. After all, this isn’t crossing the HTML-CSS boundary here; this is all within CSS and developer-only-facing, which puts more of a narrow scope on the problem.

In a similar fashion, I’ve tried keeping colors within a Sass map, like:

$colors: (
  light: #ccc,
  dark: #333
);

But the only vague goal there was to clean up the global namespace, which probably isn’t worth the hassle of needing to map-get all the time. Namespacing like $-c-orange is probably an easier approach if you need to do anything at all.

I’ve largely stuck with that just-use-color-names approach today in Sass. As the shift toward CSS custom properties happens, I think having a --c-orange and --c-gray-5 is similarly appropriate.

:root {
  -c-orange: #F060D6;
  -c-red: #BB532E;
  -c-blue: #4C9FEB;

  -c-gray-1: #eee;
  -c-gray-2: #ccc;
  -c-gray-3: #555;
}

You could get a little more specific with those names with staying abstract, like Marcus Ortense says:

$color-primary:
$color-primary-dark:
$color-primary-light: 

And variations on each base like Mike Street says:

$primary:
$primaryLight: 
$primaryDark:

$secondary:
$secondaryLight:
$secondaryDark:

$neutralDarker:
$neutrayDark:
$neutral:
$neutralLight:
$neutralLighter: 
$neutralLightest: 

Silvestar Bistrovi? recently wrote about using abstract Greek numbering:

$color-alpha: #12e09f;
$color-beta: #e01258;
$color-gamma: #f5f5f5;
$color-psi: #1f1f1f;
$color-omega: #fff;

I’ve used that kind of thing for media query breakpoints before, as the numbering seems to make sense there (i.e. low numbers are smaller screens, big numbers are bigger screens). I could also see that being nice for tints or shades of the same color, but then why not regular numbers?

Another approach I’ve often seen is to combine named colors with abstracted names. Geoff does that and John Carroll lists that here:

$color-danube: #668DD1;
$color-cornflower: $6195ED;
$color-east-bay: $3A4D6E;

// theme1.scss
$color-alpha: $color-danube;
$color-bravo: $color-cornflower;
$color-charlie: $color-east-bay;

// theme2.scss
$color-alpha: $color-cornflower;
$color-bravo: $color-danube;
$color-charlie: $color-east-bay;

That can get as verbose as you need it to, even adding variations as you call from the palette.

$table-row-background: lighten($color-background, 10%);

Stuart Robson even gets a bit BEM-y with the names, including the namespace:

$ns-color__blue—dark: rgb(25,25,112); 
$ns-brand__color—primary: $ns-color__blue—dark;

// component.scss
$ns-component__color—text: $ns-brand__color—primary;

Material Design uses values that are similar to font-weight! That means you’d end up with something like a base range plus alternates:

$light-green-100:
$light-green-200:
$light-green-300:
// etc
$light-green-900:
$light-green-A200:
$light-green-A400:

$deep-purple-100:
$deep-purple-200:
$deep-purple-300:
// etc
$deep-purple-A900:

How might you pick names for colors? You might get a kick out of what to call a sunny yellow versus a sunflower yellow, or you might just want some help. Here’s one project for that, and here’s another:

See the Pen Color Namer by Maneesh (@maneeshc) on CodePen.

There is even a Sublime Text plugin for converting them (to whatever syntax you want):

And since we’re on the topic of naming:

The post What do you name color variables? appeared first on CSS-Tricks.

Categories: Designing, Others Tags:

Accessible SVG Icons With Inline Sprites

December 7th, 2018 No comments

This is a great look at accessible SVG markup patterns by Marco Hengstenberg. Here’s the ideal example:

<button type="button">
  Menu
  <svg class="svg-icon"
     role="img"
     height="10"
     width="10"
     viewBox="0 0 10 10"
     aria-hidden="true"
     focusable="false">
     <path d="m1 7h8v2h-8zm0-3h8v2h-8zm0-3h8v2h-8z"/>
    </svg>
</button>

Notes:

  • It’s not the itself that is interactive — it’s wrapped in a
  • The .svg-icon class has some nice trickery, like em-based sizing to match the size of the text it’s next to, and currentColor to match the color.
  • Since real text is next to it, the icon can be safely ignored via aria-hidden="true". If you need an icon-only button, you can wrap that text in an accessibily-friendly .visually-hidden class.
  • The focusable="false" attribute solves an IE 11 bug.

Plus a handy Pen to reference all the patterns.

Direct Link to ArticlePermalink

The post Accessible SVG Icons With Inline Sprites appeared first on CSS-Tricks.

Categories: Designing, Others Tags:

WordPress 5.0 Is Here (and Yes, So Is Gutenberg)

December 7th, 2018 No comments

WordPess 5.0 (codenamed “Bebo”) is officially out and prowling among the servers.

This, then, is when we find out how well Gutenberg works out. And make no mistake, whatever they’ve done under the hood, this release is about Gutenberg, both technically and in the public perception. It’s almost the only thing they talk about in their own blog post about this release.

?

Gutenberg

Automattic has set out to redefine the content editing experience in the CMS that powers at least a third of the Internet, and that is exactly what they’ve done. I think it’s for the better; others…not so much; still others think it’s a good idea that needs more development time.

Personally, I think a lot of that negative perception comes from earlier development builds. Those were builds that I didn’t use much because, well, they weren’t finished. I’d be surprised, honestly, if it was bug-free even now. That’s just not how software development seems to work these days. I’ve got my fingers crossed that it’s finished enough.

I’ve got my fingers crossed that it’s finished enough

I mean hey, I might be used to wrangling with unruly software, but someone who just wants to post on their blog already might not be as forgiving. The point is, whether any of us are ready or not, it’s here, and I personally quite like it.

One of the features that I find quite useful is the collection of default embedding blocks that allow you to easily embed content from a wide variety of sources. The classic editor had a bit of this functionality, but the current system gives you a proper idea of what you can and can’t embed by default, and I’m pretty sure some of the options were previously only available through third-party plugins. [Figure 1]

It might be a bit late for that Tumblr Embed Block, though. Ahem.

Another feature I like are contextual icons that appear on the upper-right of any new block, allowing you to select recently-used blocks quickly. That could come in handy when editing a longer document. [Figure 2]

For those of you who want to wait for Automattic to develop Gutenberg a little further, they have a Classic Editor plugin, as promised. The word is they’ll be supporting this plugin until 2021. Incidentally, it has a rating of 4.9 according to wordpress.org’s own rating system, and over 600,000 active installations at the time of this writing.

All plugins that previously made changes and additions to the classic editor should still work with this plugin, so it’s a viable option for those who want to play it safe.

Themes and Such

Twenty-Nineteen made it into the final release. Since that wasn’t always guaranteed, I’m glad it got finished up in time. They needed a way to properly showcase Gutenberg’s capabilities with this release, and now they have one. For a preview of said theme, as well as my thoughts on it, see Previewing the WordPress Twenty-Nineteen Theme. (Side note: all themes from Twenty-Ten to Twenty-Seventeen have been updated to support Gutenberg.)

For designers and developers, theme creation just got a bit easier and a bit more complicated at the same time. On the one hand, it is now possible to handle a lot of content-related layout within the CMS itself, which will save time when developing custom theme options. It gives users more control over the general flow of content, giving them more creative opportunities, and takes some work off your plate.

On the other hand, you need to make sure you have styles ready for all of the default content blocks available in every theme you make. This is not terribly difficult, and it shouldn’t take too long to develop a library of custom styles that can be adjusted to every theme, but it’s something to consider.

Additionally, most of the third-party block plugins I’ve seen are not style-agnostic, though most have multiple style options to choose from. I can see third-party blocks being something of a double-edged sword.

WordPress Support Changes

One last tidbit that was actually announced on December 3rd is a new support platform for WordPress. It’s called “HelpHub”, and it’s located at wordpress.org/support. They’re still migrating content from the old WordPress Codex, so that’s still there for now, but this is the new official help center.

It seems to be pretty heavily integrated with the support forums, so it seems like the general plan was to make help easier to find by putting it all (more or less) in one place. I’d call this an overall improvement.

My Opinion

On my own personal projects, the update installed flawlessly. I can’t report much on potential bugs, as yet, because this release just happened, but so far I like it quite a bit. I honestly like the new editor, and the new direction WordPress is heading in. There’s a lot of potential here. Whether or not you think Gutenberg is ready for release, as I do, the thing to realize is that Gutenberg is only the next step in a long journey.

Automattic has been working long and hard to transform WordPress from a pure-blog CMS into something like a framework or data platform, all without sacrificing usability, or too much in the way of backwards compatibility. The blog you could install in five minutes has more or less become the ecosystem you can install in five minutes, and then build any site you want.

It’s not perfect, and it’s not done yet, but this release is a giant step toward something we’ve never seen before. I’m genuinely excited to find out what it’ll be.

Add Realistic Chalk and Sketch Lettering Effects with Sketch’it – only $5!

Source

Categories: Designing, Others Tags:

What Can Be Learned From The Gutenberg Accessibility Situation?

December 7th, 2018 No comments
Form Design Patterns — a practical guide for anyone who needs to design and code web forms

What Can Be Learned From The Gutenberg Accessibility Situation?

What Can Be Learned From The Gutenberg Accessibility Situation?

Andy Bell

2018-12-07T11:30:08+01:002018-12-08T14:01:34+00:00

So far, Gutenberg has had a very mixed reception from the WordPress community and that reception has become increasingly negative since a hard deadline was set for the 5.0 release, even though many considered it to be incomplete. A hard release deadline in software is usually fine, but there is a glaring issue with this particular one: what will be the main editor for a platform that powers about 32% of the web isn’t fully accessible. This issue has been raised many times by the community, and it’s been effectively brushed under the carpet by Automattic’s leadership — at least it comes across that way.

Sounds like a messy situation, right? I’m going to dive into what’s happened and how this sort of situation might be avoided by others in the future.

Further Context

For those amongst us who haven’t been following along or don’t know much about WordPress, I’ll give you a bit of context. For those that know what’s gone on, you can skip straight to the main part of the article.

WordPress powers around 32% of the web with both the open-source, self-hosted CMS and the wordpress.com hosted blogs. Although WordPress, the CMS software is open-source, it is heavily contributed to by Automattic, who run wordpress.com, amongst other products. Automattic’s CEO, Matt Mullenweg is also the co-founder of the WordPress open source project.

It’s important to understand that WordPress, the CMS is not a commercial Automattic project — it is open source. Automattic do however make lots of decisions about the future of WordPress, including the brand new editor, Gutenberg. The editor has been available as a plugin while it’s been in development, so WordPress users can use it as their main editor and provide feedback — a lot of which has been negative. Gutenberg is shipping as the default editor in the 5.0 major release of WordPress, and it will be the forced default editor, with only the download of the Classic Editor preventing it. This forced change has had a mixed response from the community, to say the least.

I’ve personally been very positive about Gutenberg with my writing, teaching and speaking, as I genuinely think it’ll be a positive step for WordPress in the long run. As the launch of WordPress 5.0 has come ever closer, though, my concerns about accessibility have been growing. The accessibility issues are being “fixed” as I write this, but the handling of the situation has been incredibly poor, from Automattic.

I invite you to read this excellent, ever-updating Twitter thread by Adrian Roselli. He’s done a very good job of collecting information and providing expert commentary. He’s covered all of the events in a very straightforward manner.

Right, you’re up to speed, so let’s crack on.

What Happened?

For as long as the Gutenberg plugin has been available to install, there have been accessibility issues. Even when I very excitedly installed it and started hacking away at custom blocks back in March, I could see there was a tonne of issues with the basics, such as focus management. I kept telling myself, “This editor is very early doors, so it’ll all get fixed before WordPress 5.” The problem is: it didn’t. (Well, mostly, anyway.)

This situation was bad as it is, but two key things happened that made it worse. The accessibility lead, Rian Rietveld, resigned in October, citing political and codebase issues. The second thing is that Automattic set a hard deadline for WordPress 5’s release, regardless of whether accessibility issues were fixed or not.

Let me just illustrate how bad this is. As cited in Rian’s article: after an accessibility test round in March, the results indicated so many accessibility issues, most testers refused to look at Gutenberg again. We know that the situation has gotten a lot better since then, but there are still a tonne of open issues, even now.

I’ve got to say it how I see it, too. There’s clearly a cultural issue at Automattic in terms of their attitude towards accessibility and how they apparently compensate people who are willing to fix them, with a strange culture of free work, even from “outsiders”. Frankly, the company’s CEO, Matt Mullenweg’s attitude absolutely stinks — especially when he appears to be holding a potential professional engagement hostage over someone’s personal blog decision:

That’s too bad was about to reach out to work with Deque on the audits.

— Matt Mullenweg (@photomatt) November 13, 2018

Allow me to double-down on the attitude towards accessibility for a moment. When a big company like Automattic decides to prioritize a deadline they pluck out of thin air over enabling people with impairments to use the editor that they will be forced to use it is absolutely shocking. Even more shocking is the message that it sends out that accessibility compliance is not as important as flashy new features. Ironically, there’s clearly commercial undertones to this decision for a hard deadline, but as always, free work is expected to sort it out. You’d expect a company like Automattic to fix the situation that they created with their own resource, right?

You’ll probably find it shocking that a crowd funding campaign has been put together to get an accessibility audit done on Gutenberg. I know I certainly do. You heard me correctly, too. The Gutenberg editor, which is a product of Automattic’s influence on WordPress who (as a company) were valued at over $1 Billion in 2014 are not paying for a much-needed accessibility audit. They are instead sitting back and waiting for everyone else to pay for it. Well, at least they were, until Matt Mullenweg finally committed to funding an audit on 29 November.

How Could This Mess Be Avoided?

Enough dragging people over coals (for now) and let us instead think about how this could have been avoided. Apart from the cultural issues that seem to de-prioritize accessibility at Automattic, I think the design process is mostly at fault in the context of the Gutenberg editor.

A lot of the issues are based around complexity and cognitive load. Creating blocks, editing the content, and maneuvering between blocks is a nightmare for visually impaired and/or keyboard users. Perhaps if accessibility was considered at the very start of the project, the process of creating, editing and moving blocks would be a lot simpler and thus, not a cognitive overload. The problem now is that accessibility is a fix rather than a core feature. The cognitive issues will continue to exist, albeit improved.

Another very obvious thing that could have been done differently would be to provide help and training on the JS-heavy codebase that was introduced. A lot of the accessibility fixing work seems to have been very difficult because the accessibility team had no React developers within it. There was clearly a big decision to utilize modern JavaScript because Mullenweg told everyone to “Learn JavaScript Deeply”. At that point, it would have made a lot of sense to help people who contribute a lot to WordPress for free to also learn JavaScript deeply so that they could have been involved way earlier in the process. I even saw this as an issue and made learning modern JavaScript and React a core focus in a tutorial series I co-authored with Lara Schenck.

I’m convinced that some foresight and investment in processes, planning, and people would have prevented a tonne of the accessibility issues from existing at all. Again, this points at issues with attitude from Automattic’s leader, in my opinion. He’s had the attitude that ignoring accessibility is fine because Gutenberg is a fantastic, empowering new editor. While this is true, it can’t be labeled as truly empowering if it prevents a huge number of users from managing content — in some cases, even doing their jobs. A responsible CEO in this position would probably write an incredibly apologetic statement that addressed the massive oversights. They would probably also postpone the hard deadline set until every accessibility issue was fixed. At the very least, they wouldn’t force the new editor on every single WordPress user.

Wrapping Up

I’ve got to add to this article that I am a massive WordPress fan and can see some unbelievably good opportunities for managing content that Gutenberg provides. It’s not just a new editor — it is a movement. It’s going to shape WordPress for years to come, and it should allow more designers and front-end developers into the ecosystem. This should be welcomed with open arms. Well, if and when it is fully accessible, anyway.

There are also a lot of incredible people working at Automattic and on the WordPress core team, who I have heaps of respect and love for. I know these people will help this situation come good in the end and will and do welcome this sort of critique. I also know that lessons will be learned and I have faith that a mess like this won’t happen again.

Use this situation as a warning, though. You simply can’t ignore accessibility, and you should study up and integrate it into the entire process of your projects as a priority.

Smashing Editorial(dm, ra, il)
Categories: Others Tags:

Compound Components in React Using the Context API

December 7th, 2018 No comments
Form is the provider with state, Form Panel is the consumer receiving state, Panel displays the panel based on the state, and Signup and Login render the form views in the Panel.

Compound components in React allow you to create components with some form of connected state that’s managed amongst themselves. A good example is the Form component in Semantic UI React.

To see how we can implement compound components in a real-life React application, we’ll build a compound (multi-part) form for login and sign up. The state will be saved in the form component and we’ll put React’s Context AP to use to pass that state and the method from the Context Provider to the component that needs them. The component that needs them? It will become a subscriber to Context Consumers.

Here’s what we’re building:

See the Pen React Compound Component by Kingsley Silas Chijioke (@kinsomicrote) on CodePen.

Here’s a rough outline that shows how the following steps fit together:

Form is the provider with state, Form Panel is the consumer receiving state, Panel displays the panel based on the state, and Signup and Login render the form views in the Panel.

Before treading any further, you may want to brush up on the React Context API if you haven’t already. Neal Fennimore demonstrates the concept in this post and my primer on it is worth checking out as well.

Step 1: Creating context

First, let’s initialize a new context using the React Context API.

const FormContext = React.createContext({});
const FormProvider = FormContext.Provider;
const FormConsumer = FormContext.Consumer;

The provider, FormProvider, will hold the application state, making it available to components that subscribe to FormConsumer.

Step 2: Implement provider

One panel contains the form to log in and the other contains the form to sign up. In the provider, we want to declare the state, which determines the active panel, i.e. the form currently in display. We’ll also create a method to switch from one panel to another when a heading is clicked.

class Form extends React.Component {
  state = {
    activePanel: "login"
  };

  render() {
    return (
      <React.Fragment>
        <FormProvider
          value={{
            activePanel: this.state.activePanel,
            actions: {
              handlePanelSwitch: newPanel => {
                this.setState({
                  activePanel: newPanel
                });
              }
            }
          }}
        >
          {this.props.children}
        </FormProvider>
      </React.Fragment>
    );
  }
}

By default, the login panel will be shown to the user. When the signup panel is clicked, we want to make it the active panel by setting the state of activePanel to signup using the method handlePanelSwitch().

Step 3: Implement Consumers

We’ll use FormConsumer to make context available to the components that subscribe to it. That means the FormPanel component that handles displaying panels will look like this:

const FormPanel = props => {
  return (
    <FormConsumer>
      {({ activePanel }) =>
        activePanel === props.isActive ? props.children : null
      }
    </FormConsumer>
  );
};

And the Panel component will look like this:

const Panel = props => (
  <FormConsumer>
    {({ actions }) => {
      return (
        <div onClick={() => actions.switchPanel(props.id)}>
          {props.children}
        </div>
      );
    }}
  </FormConsumer>
);

To understand what is happening, let’s understand the approach here. The login and signup panels will have unique IDs that get passed via props to the Panel component. When a panel is selected, we get the ID and and use it to set activePanel to swap forms. The FormPanel component also receives the name of the panel via the isActive prop and we then check to see if the returned value is true. If it is, then the panel is rendered!

To get the full context, here is how the App component looks:

const App = () => {
  return (
    <div className="form-wrap">
      <Form>
        <div className="tabs">
          <Panel id="login">
            <h2 className="login-tab">Login</h2>
          </Panel>
          <Panel id="signup">
            <h2 className="signup-tab">Sign Up</h2>
          </Panel>
        </div>

        <FormPanel isActive="login">
          <Login />
        </FormPanel>

        <FormPanel isActive="signup">
          <SignUp />
        </FormPanel>
      </Form>
    </div>
  );
};

You can see how the components are composed when activePanel matches isActive (which is supposed to return true). The component is rendered under those conditions.

With that done, the Login component looks like this:

const Login = () => {
  return (
    <React.Fragment>
      <div id="login-tab-content">
        <form className="login-form" action="" method="post">
          <input
            type="text"
            className="input"
            id="user_login"
            placeholder="Email or Username"
          />
          <input
            type="password"
            className="input"
            id="user_pass"
            placeholder="Password"
          />
          <input type="checkbox" className="checkbox" id="remember_me" />
          <label htmlFor="remember_me">Remember me</label>

          <input type="submit" className="button" value="Login" />
        </form>
      </div>
    </React.Fragment>
  );
};

And the SignUp component:

const SignUp = () => {
  return (
    <React.Fragment>
      <div id="signup-tab-content" className="active tabs-content">
        <form className="signup-form" action="" method="post">
          <input
            type="email"
            className="input"
            id="user_email"
            placeholder="Email"
          />
          <input
            type="text"
            className="input"
            id="user_name"
            placeholder="Username"
          />
          <input
            type="password"
            className="input"
            id="user_pass"
            placeholder="Password"
          />
          <input type="submit" className="button" value="Sign Up" />
        </form>
      </div>
    </React.Fragment>
  );
};

Get it? Got it? Good!

You can use this pattern anytime you have components in your React application that need to share implicit state. You can also build compound components using React.cloneElement().

References

The post Compound Components in React Using the Context API appeared first on CSS-Tricks.

Categories: Designing, Others Tags:

Edge’s Announcements

December 6th, 2018 No comments

The public-consumption blog post:

Ultimately, we want to make the web experience better for many different audiences. People using Microsoft Edge (and potentially other browsers) will experience improved compatibility with all web sites, while getting the best-possible battery life and hardware integration on all kinds of Windows devices. Web developers will have a less-fragmented web platform to test their sites against, ensuring that there are fewer problems and increased satisfaction for users of their sites; and because we’ll continue to provide the Microsoft Edge service-driven understanding of legacy IE-only sites, Corporate IT will have improved compatibility for both old and new web apps in the browser that comes with Windows.

For us devs:

  1. We are making this decision for the long term. We expect our engineers to learn and over time become experts in the Chromium project and grow into active and responsible members of the community. We are eager to increase our contributions to the Chromium project and will continue to maintain any contributions we make.

  2. When seeking improvements in the web platform, our default position will be to contribute. We are focused on delivering a world class browser with Microsoft Edge through its differentiated user experience features and connected services, but where new platform capabilities are concerned, we will seek a ‘rising tide that floats all boats’. We will get started with bug fixes and meaningful contributions in such areas as ARM64 support, accessibility, security, touch input and power enhancements on Windows.

  3. We recognize and will respect the architecture requirements and engineering approach that are intrinsic in web open-source projects and have made Chromium successful. There are many aspects that have governed Chromium OSS and other projects: multi-device support, multi-OS support, rigorous real-time engineering, etc. Although our company has historically had a focus on Windows PCs and we believe we can make contributions that improve browsers on Windows, we also understand that web OSS projects embrace a wide range of device-types, including Android, and that contributions must accommodate this device diversity. We will contribute in a way that is consistent with the architectural design that meets Chromium’s cross-platform and cross-device needs.

  4. We believe the evolution of the open web is best served though the standards communities, and the open web benefits from open debate from a wide variety of perspectives. We will remain deeply and vigorously engaged in the standards discussions in the context of the W3C, ECMA and the WHATWG where the perspectives of vendors developing competing browsers and the larger web community can be heard and considered.

Nothing terribly surprising here. We’re doing this. We think it’ll be good for everybody. I’m slightly surprised they didn’t attempt to answer everyone’s main worry: is the web actually better off with less engine diversity? We’ll never know I guess.

The post Edge’s Announcements appeared first on CSS-Tricks.

Categories: Designing, Others Tags: