Archive

Archive for January, 2020

Thinking Through Styling Options for Web Components

January 16th, 2020 No comments

Where do you put styles in web components?

I’m assuming that we’re using the Shadow DOM here as, to me, that’s one of the big draws of a web component: a platform thing that is a uniquely powerful thing the platform can do. So this is about defining styles for a web component in a don’t-leak-out way, and less so a way to get global styles to leak in (although that’s very interesting as well, which can be done via custom properties which we’ll look at later in the article).

If you’re building the template inside the JavaScript — which is nice because of template literals and how we can sprinkle our data into the template nicely — you need access to those styles in JavaScript.

const template = `
  <style>${styles}</style>
  <div class="${class}">
    <h2>${title}</h2>
    ${content}
  </div>
`;

Where does that style variable come from? Maybe also a template literal?

const style = `
  :host {
    background: white;
  }
  h2 {
    font: 900 1.5rem/1.1 -system-ui, sans-serif;
  }
`;

I guess that’s fine, but it makes for a big messy block of code just dunked somewhere in the class where you’re trying to build this web component.

Another way is to the template and make a block part of it.

<template id="card-template">
  <style>
    :host {
      background: white;
    }
    h2 {
      font: 900 1.5rem/1.1 -system-ui, sans-serif;
    }
  </style>

  <div id="card-hook">
    <h2 id="title-hook"></h2>
    <p id="desc-hook"></p>
  </div>
</template>

I can see the appeal with this because it keeps HTML in HTML. What I don’t love about it is that you have to do a bunch of manual shadowRoot.querySelector("#title-hook").innerHTML = myData.title; work in order to flesh out that template. That doesn’t feel like a convenient template. I also don’t love that you need to just chuck this template somewhere in your HTML. Where? I dunno. Just chuck it in there. Chuck it.

The CSS is moved out of the JavaScript too, but it just moved from one awkward location to another.

If we wanted to keep the CSS in a CSS file, we can sorta do that like this:

<template id="card-template">
  <style>
    @import "/css/components/card.css";
  </style>

  <div id="card-hook">
    <h2 id="title-hook"></h2>
    <p id="desc-hook"></p>
  </div>
</template>

(The use of is deprecated, apparently.)

Now we have @import which is an extra HTTP Request, and notorious for being a performance hit. An article by Steven Lambert says it clocked in at half a second slower. Not ideal. I don’t suppose it would be much better to do this instead:

class MyComponent extends HTMLElement {
    
  constructor() {
    super();
    this.attachShadow({ mode: "open" });

    fetch('/css/components/card.css')
      .then(response => response.text())
      .then(data => {
        let node = document.createElement('style');
        node.innerHTML = data;
        document.body.appendChild(node);
      });
  }

  // ...
}

Seems like that would potentially be a Flash-of-Unstyled-Web-Component? I guess I should get off my butt and test it.

Now that I’m digging into this again, it seems like ::part has gotten some steam (explainer). So I can do…

const template = `
  <div part="card">
    <h2>${title}</h2>
    ${content}
  </div>
`;

…then write styles in a global stylesheet that only apply inside that Shadow DOM, like:

my-card::part(card) {
  background: black;
  color: white;
}

…which has a smidge of browser support, but maybe not enough?

These “part” selectors can only touch the exact element it’s connected to. You’d have to do all your styling by applying a part name to every single DOM node and then styling each entirely on its own. That’s no fun, particularly because the appeal of the Shadow DOM is this isolated styling environment in which we’re supposed to be able to write looser CSS selectors and not be worried our h2 { } style is going to leak all over the place.

Looks like if native CSS modules becomes a thing, that will be the most helpful thing that could happen.

import styles from './styles.css';

class MyElement extends HTMLElement {
  constructor() {
    this.attachShadow({mode: open});
    this.shadowRoot.adoptedStyleSheets = [styles];
  }
}

I’m not sure, however, if this is any sort of performance boost. Seems like it would be a wash between this and @import. I have to say I prefer the clarity and syntax with native CSS modules. It’s nice to be writing JavaScript when working with JavaScript.

Constructable Stylesheets also look helpful for sharing a stylesheet across multiple components. But the CSS modules approach looks like it could also do that since the stylesheet has already become a variable at that point.

The post Thinking Through Styling Options for Web Components appeared first on CSS-Tricks.

Categories: Designing, Others Tags:

The Design Squiggle

January 16th, 2020 No comments

I think we all have an intuitive understanding that, at the beginning of projects that require our creativity (be it design or code), things feel uncertain and messy. Then, as we go, things tend to straighten out. There is still some wiggling and setbacks, but by the end, we find a single solution and ship it.

Apparently this feeling has a logo: The Design Squiggle

The Process of Design Squiggle by Damien Newman, thedesignsquiggle.com

It comes from Damien Newman who says that a client gave him 30 seconds to sell them on the value of design, and this did the trick.

I find it a little funny to take this little concept and give it such a grandiose presentation. A dedicated website! A story with a boatload of name dropping! Very specific attribution instructions! But hey, I don’t have any famous doodles, and I gotta admit, this does a great job of expressing a complex thing quite quickly.

Reminds me of a boss a buddy of mine had who claims to have invented the Curiously Strong motto for Altoids, and didn’t mind telling people about it.

Direct Link to ArticlePermalink

The post The Design Squiggle appeared first on CSS-Tricks.

Categories: Designing, Others Tags:

GoDaddy Goes All-In With New Logo Design And Identity

January 16th, 2020 No comments

Ah, GoDaddy.

The father of loads of website domains and the place of website hosting.

GoDaddy has been around for a long, long time. For 23 years to be exact.

And it was about time they got a little facelift.

GoDaddy Goes All-In With New Logo Design And Identity

go-daddy-logo-before-and-after

GoDaddy was established back in 1997 and is a website registrar and web hosting company.

The company hosts over 19 million users, and if that’s not impressive enough, let me hit you with this statistic.

78 Million website domains have been registered through them.

So, if that doesn’t prove credibility, then I don’t know what will.

I personally use GoDaddy and have been using it for many years now.

Just a few months back when I was using GoDaddy, I remember thinking, “Man, this website and logo needs some help.”

old go daddy logo and website

(before)

And I’m happy to announce that I checked back in recently and was shocked but what I saw!

I did a double-take and thought I might be on the wrong website.

So I double-checked the domain and to my delight, it was the right website domain that I had typed in. (All those years of typing classes in 2nd grade paid off)

Their site looks so good, so modern, and so sleek now. I love it.

(after)

Here’s what GoDaddy had to say about it all.

“We thoughtfully considered every detail of our brand design system and centered it around our Design Ethos.

Our design originates from a tasteful, considered aesthetic, with every creative piece distilled down to its essential form.

The GO is a clear statement of advocacy for entrepreneurs everywhere – a symbol of empowerment that encourages them to stand on their own two feet.

godaddy new logo

Always bright and dynamic, our brand colors speak to the creativity of our customers.

Our wide palette connects with people across the globe and promotes inclusivity for all cultures. We use color to bring joy to our brand.

new go daddy website design

Our bold, serif headline font is elegant and expressive projecting a fresh, modern voice.

It presents a hint of flair for professionalism, giving the brand a distinguished feel.

We use it to establish strong moments of brand for customers.”

I personally love all of the changes that GoDaddy underwent.

The colors, the new and understandable typeface they’re using, the new logo that’s got the word “Go” in it and it’s shaped like a heart.

I really think they took a huge step in the right direction when it comes to approachability.

When you change everything about your website and logo and design, well… that can be truly nerve-wracking.

Kudos to them for taking that huge leap of faith, because I really think it worked out in their favor.

No more weird animation dude sticking out of the side of the logo. Just a really cool, well-thought-out modern logo and great colors.

I personally like all of the changes made, although I know that’s an unpopular opinion.

What do you guys think?

Let us know in the comment section below what you think of GoDaddy’s new identity and design!

Until next time,

Stay creative, folks!

Read More at GoDaddy Goes All-In With New Logo Design And Identity

Categories: Designing, Others Tags:

Understanding the Mobility Adoption – [Infographic]

January 16th, 2020 No comments

A lot of businesses are digitally transforming, that’s because the world is transforming as well. If you don’t want to stay behind, you need to follow the latest trends and make the necessary changes.

Make sure to check out this infographic to learn about the current mobility adaption level, upcoming trends that drive businesses worldwide.

[Infographic] The Magnified Mobile Ecosystem by Scalefusion Kiosk Software

Categories: Others Tags:

Can Best Practice Replace Design Research?

January 16th, 2020 No comments

Heart-warming or not, co-creation with a client—the utopian ideal of shared vision—has its drawbacks. There are only so many times you can hear the words “brand strategy” before actually chewing your own face off. In the age of WordPress, Drupal and, dare I say it, Wix, it’s never been more tempting to pay lip-service to research and consultation. Instead of building a principles framework from scratch, why not roll out something from a template in a fraction of the time?

Well, in fact, there probably are situations where a simple WordPress-type approach will work really well. The trick is knowing when.

What Is “Best Practice” Anyway?

Well, exactly.

Even if you slept through design school, or didn’t go at all, you probably know the fundamentals already. And it’s true. If you stick to first principles, you won’t go far wrong. Here are some examples:

  • Color and Contrast: 2-3 colors maximum, use contrast to highlight important elements;
  • White Space: Use plenty of it, be consistent with proportions above and below;
  • Layout: Symmetric Grid. Err…Always. Work ‘above the fold’;
  • Typography: No more than 2-3 typefaces;
  • Logo: Long, top left, always;
  • Compexity vs Simplicity: Look for balance and visual interest;
  • Visual Hierarchy: Use color, contrast, size and complexity to highlight important elements;
  • Consistency: With all of the above, whatever you decide, be consistent;
  • And so on…

One size, though, doesn’t fit all. By bending and even breaking the rules sometimes, you’ll create designs that stand out and, more importantly, meet the real requirements of the brief.

The One Unbreakable Rule

It’s pretty hard to find a “Best Practice” that really works in every situation, but here’s one:

No matter what you’re doing, make sure you know why you’re doing it.

And, just in case you were wondering, “err…because it looks pretty?” and “because it’s easier than what I probably ought to do instead…” aren’t really reasons.

There are clearly situations where a client—whatever they may think—is best served by a simple off-the-shelf approach. Particularly if their budget is more Scrooge than Soros. The thing is, you probably still need to go through a research process to find out whether that’s the case or not.

When And How To Go Off Piste

Before or just after accepting the job, you’ll likely need to do some research with the client. This process should focus on (you guessed it) brand strategy.

Ideally, in the first instance, you’ll build a design principles framework. Whatever decisions you make after that (whether you’re going to stick to the rules or break them) should be justified with reference to the framework.

Here are some examples of situations where you might consider deviating from “best practice”:

You Want to Send a Particular Message

Take this site for a children’s fitness company, for example.

It clearly breaks all the rules about color and typeface, and a few more besides, but overall gives a sense of vibrance and playfulness, which of course is ideal for this market.

You Want to Draw Attention to Something

By ignoring the imperative to “work above the fold” and putting product and logo front and centre, candle manufacturer Waxxy draws the eye directly to their “product centred” philosophy and creates a sense of light and space:

Natale’s Clothing uses additional fonts and a broken grid layout to emphasise content and create a sense of being “out of the ordinary”.

You Want to Keep Things Clean

Legend has it, if you “put everything on the homepage” it’s good for SEO and easier for users. These days, though, there’s often a lot of information, and we prefer to have more space, even if it means a bit more browsing.

If you visit Toke’s site here, you’ll see that they break the animation taboo in a subtle and effective way as well.

These are just a few examples, there are many more. In each case the key questions to ask are:

  1. How does it meet the brief?
  2. How does it help brand strategy?

When To Stick To The Script

A big consideration here will likely be the client’s budget. With the best will in the world, you’re going to struggle to create a logo, design a custom typeface, and build a multi-page site from scratch on $800. If that’s what the client’s asking for, and can’t understand the limitations, maybe consider saying no!

If, on the other hand, there’s scope to negotiate, where budgets are small and, in situations where, for example, the client has a small number of products and/or services, a single page WordPress site will often be exactly what they need. Here it’s not a question of “doing the bare minimum” but rather “not doing too much”. Even so, there will probably be bespoke elements that you can change to better fit the strategy.

Another important moment to check yourself, is whenever you’re not sure if an idea works. If you can’t justify a decision with reference to your design principles framework—or at least with reference to the client’s brand strategy—then it’s probably best to err on the side of caution.

Research or Best Practice?

In a word, both.

There are definitely situations where a “first principles” approach will be exactly what the client needs. Particularly if their budget is small and their needs are simple. Even in this case, though, a great designer will take the time to understand (or help to develop) the brand strategy, and add whatever tweaks are necessary. Each client and each brand is unique, and a designer’s job, if you think about it, is to reflect just that.

When using a bespoke approach, breaking with convention can, as we’ve seen, produce interesting and stylish results. It’s important, though, that each decision makes sense, and can be linked back to the brand strategy. If it can’t, it probably shouldn’t be in the design.

And whatever you do, don’t chew your face off.

Featured image via Unsplash.

Source

Categories: Designing, Others Tags:

AMP – A Waste of Time, or Not?

January 16th, 2020 No comments

Nowadays, one of the key aspects of optimizing your website through responsive web design is optimizing for mobile.

Since over 51% of mobile users find new companies and products by searching online from their smartphones, making sure your company’s site is structured correctly for both desktops and smartphones is a must.

Google found a way to help with Accelerated Mobile Pages (AMPs), which create a faster user experience for those on mobile. But are AMPs really worth the effort in the long run when there are already so many options for optimization?

What is Accelerated Mobile Pages (AMP)?

Before we dive in, let’s take a look at what AMPs actually do. Basically, AMPs are specific webpages created to make mobile browsing faster with a reduced page load speed. This can be an important feature to consider when higher page loading times mean that less users will be willing to interact further with your site.

How Do AMPs Work?

AMPs are open source initiatives, created with streamlined HTML coding in order to render webpages faster. They are compatible through several browsers, and when implemented correctly, have the potential to increase user traffic and improve SEO rankings.

Google ad landing pages are also compatible with AMPs. They are able to be tracked and optimized with many of Google’s built-in protocols and tools. Google has placed a lot of emphasis on utilizing AMPs with landing pages, and for good reason.

Faster load speed on mobile devices can lower your bounce rate, or how long someone views an ad before navigating away from it. A more responsive user interface will make users more likely to click on your ad (otherwise known as the click through rate), which can increase your number of conversions.

And that’s really the goal of AMPs overall – optimizing the user experience in order to increase web traffic, and in the process, helping to generate mobile leads.

How Has AMP Changed Since its Release?

AMP by Google was first released on October 7, 2015. In February of 2016, Google announced that AMPs would be integrated into mobile search results, giving new challenges to SEO marketers optimizing for mobile.

However, December of 2018 marked an important moment, where WordPress partnered with AMP and Google to release an official AMP plugin. While this didn’t do much for everyone else, it certainly gave a leg-up for WordPress sites.

What You Gain with AMP

The basic premise of AMPs is simple: faster-loading speed for mobile web pages can exponentially increase your mobile web traffic. Since over half of users are both browsing and consuming from their smartphones, this can be crucial to your bottom line.

But here’s how:

Improvements in Responsive Web Design

The goal of responsive web design is to ensure that webpages are designed to maximize the user interface. In other words, responsive web design creates a clearly navigable sitemap that can be accessed from any kind of device: desktops, iPads and tablets, and of course, mobile devices.

It also ensures that webpages load quickly, are well organized, and are easy to read, so it goes to reason that AMPs can help improve responsive web design as a whole.

Enhanced User Experience

UX design, also called user experience design, focuses on improving the user experience. It incorporated structured and clear hierarchies of information within webpages and the sitemap to help people access and better understand the information on your site.

But again, this involves both mobile optimization and page loading speed, along with responsive web design to create an excellent user experience. AMPs can go a long way to expedite that process.

Potential Drawbacks of Implementing AMP

While the benefits of AMPs look extremely promising, there are a few essential tips to keep in mind when it comes to implementing AMPs into your mobile content strategy.

AMP Coding

AMP coding may utilize a stripped-down version of HTML, but in order for the pages to be rendered correctly, there are certain HTML tags that just won’t work with AMPs. Script, base, embed, and frame tags are all examples of these.

According to GitHub’s guide to AMP HTML coding, “XML-related attributes, such as xmlns, xml:lang, xml:base, and xml:space are disallowed in AMP HTML.”

Though of course, there are also tags that must be included for AMPs to work within your site, like AMP boilerplate code that helps form the basic structure of the page. Other common tags that have their own specifications in AMPs are:

  • Style tags
  • Video tags
  • Audio tags
  • Img tags

AMP Markup

While GitHub’s guide has some pretty helpful notes about attributes, stylesheets, and other properties, AMP itself has an extensive table of contents on page markup guidelines. It details information on:

  • Metadata
  • Classes
  • IDs
  • Links
  • Selectors
  • Runtime
  • Resources
  • Other AMP Components

Once the AMP is created, it must be validated using a built-in developer tool in Google Chrome. Any issues within the page will be highlighted for you to fix.

As you can see, there’s a lot to work with, and web developers have a heavy task ahead of them when it comes to creating functional AMPs that still retain the same design themes, style, and tone of your site.

What This Could Mean for Your Mobile Content Strategy

The question remains: jump on the AMP bandwagon, or not?

The Case for Mobile SEO

Even though the process of creating and integrating AMPs within the rest of your web content may have a learning curve, the fact of the matter is, loading speed is directly linked to developing good SEO—both for mobile and non-mobile platforms.

Your mobile search rankings could improve exponentially with an increase in mobile user traffic, and sites with higher rankings on search engine results pages (SERPs), ultimately, make more conversions.

The Case for Google Ads

AMPs are also easily made compatible with paid ads and landing pages. Google makes them simple to optimize, as well as to track clicks and conversions with specialized tags.

With so many tools at your disposal, measuring ROI on AMP data becomes that much more straightforward.

Categories: Others Tags:

How We Tagged Google Fonts and Created goofonts.com

January 15th, 2020 No comments

GooFonts is a side project signed by a developer-wife and a designer-husband, both of them big fans of typography. We’ve been tagging Google Fonts and built a website that makes searching through and finding the right font easier.

GooFonts uses WordPress in the back end and NuxtJS (a Vue.js framework) on the front end. I’d love to tell you the story behind goofonts.com and share a few technical details regarding the technologies we’ve chosen and how we adapted and used them for this project.

Why we built GooFonts

At the moment of writing this article, there are 977 typefaces offered by Google Fonts. You can check the exact number at any moment using the Google Fonts Developer API. You can retrieve the dynamic list of all fonts, including a list of the available styles and scripts for each family.

The Google Fonts website provides a beautiful interface where you can preview all fonts, sorting them by trending, popularity, date, or name.

But what about the search functionality?

You can include and exclude fonts by five categories: serif, sans-serif, display, handwriting, and monospace.

You can search within scripts (like Latin Extended, Cyrillic, or Devanagari (they are called subsets in Google Fonts). But you cannot search within multiple subsets at once.

You can search by four properties: thickness, slant, width, and “number of styles.” A style, also called variant, refers both to the style (italic or regular) and weights (100, 200, up to 900). Often, the body font requires three variants: regular, bold, and italic. The “number of styles” property sorts out fonts with many variants, but it does not allow to select fonts that come in the “regular, bold, italic” combo.

There is also a custom search field where you can type your query. Unfortunately, the search is performed exclusively over the names of the fonts. Thus, the results often include font families uniquely from services other than Google Fonts.

Let’s take the “cartoon” query as an example. It results in “Cartoon Script” from an external foundry Linotype.

I can remember working on a project that demanded two highly stylized typefaces — one evoking the old Wild West, the other mimicking a screenplay. That was the moment when I decided to tag Google Fonts. 🙂

GooFonts in action

Let me show you how GooFonts works. The dark sidebar on the right is your “search” area. You can type your keywords in the search field — this will perform an “AND” search. For example, you can look for fonts that are at once cartoon and slab.

We handpicked a bunch of keywords — click any of them! If your project requires some specific subsets, check them in the subsets sections. You can also check all the variants that you need for your font.

If you like a font, click its heart icon, and it will be stored in your browser’s localStorage. You can find your bookmarked fonts on the goofonts.com/bookmarks page. Together with the code, you might need to embed them.

How we built it: the WordPress part

To start, we needed some kind of interface where we could preview and tag each font. We also needed a database to store those tags.

I had some experience with WordPress. Moreover, WordPress comes with its REST API, which opens multiple possibilities for dealing with the data on the front end. That choice was made quickly.

I went for the most straightforward possible initial setup. Each font is a post, and we use post tags for keywords. A custom post type could have worked as well, but since we are using WordPress only for the data, the default content type works perfectly well.

Clearly, we needed to add all the fonts programmatically. We also needed to be able to programmatically update the fonts, including adding new ones or adding new available variants and subsets.

The approach described below can be useful with any other data available via an external API. In a custom WordPress plugin, we register a menu page from which we can check for updates from the API. For simplicity, the page will display a title, a button to activate the update and a progress bar for some visual feedback.

/**
 * Register a custom menu page. 
 */
function register_custom_menu_page() {
  add_menu_page( 
    'Google Fonts to WordPress', 
    'WP GooFonts', 
    'manage_options', 
    'wp-goofonts-menu', 
  function() { ?>        
    <h1>Google Fonts API</h1>
    <button type="button" id="wp-goofonts-button">Run</button>
    <p id="info"></p>        
    <progress id="progress" max="100" value="0"></progress>
  <?php }
  );
}
add_action( 'admin_menu', 'register_custom_menu_page' );

Let’s start by writing the JavaScript part. While most of the examples of using Ajax with WordPress implements jQuery and the jQuery.ajax method, the same can be obtained without jQuery, using axios and a small helper Qs.js for data serialization.

We want to load our custom script in the footer, after loading axios and qs:

add_action( 'admin_enqueue_scripts' function() {
  wp__script( 'axios', 'https://unpkg.com/axios/dist/axios.min.js' );
  wp_enqueue_script( 'qs', 'https://unpkg.com/qs/dist/qs.js' );
  wp_enqueue_script( 'wp-goofonts-admin-script', plugin_dir_url( __FILE__ ) . 'js/wp-goofonts.js', array( 'axios', 'qs' ), '1.0.0', true );
});

Let’s look how the JavaScript could look like:

const BUTTON = document.getElementById('wp-goofonts-button')
const INFO = document.getElementById('info')
const PROGRESS = document.getElementById('progress')
const updater = {
  totalCount: 0,
  totalChecked: 0,
  updated: [],
  init: async function() {
    try {
      const allFonts = await axios.get('https://www.googleapis.com/webfonts/v1/webfonts?key=API_KEY&sort=date')
      this.totalCount = allFonts.data.items.length
      INFO.textContent = `Fetched ${this.totalCount} fonts.`
      this.updatePost(allFonts.data.items, 0)
    } catch (e) {
      console.error(e)
    }
  },
  updatePost: async function(els, index) {
    if (index === this.totalCount) {
      return
    }                
    const data = {
      action: 'goofonts_update_post',
      font: els[index],
    }
    try {
       const apiRequest = await axios.post(ajaxurl, Qs.stringify(data))
       this.totalChecked++
       PROGRESS.setAttribute('value', Math.round(100*this.totalChecked/this.totalCount))
       this.updatePost(els, index+1)
    } catch (e) {
       console.error(e)
      }
   }
}

BUTTON.addEventListener('click', () => {
  updater.init()
})

The init method makes a request to the Google Fonts API. Once the data from the API is available, we call the recursive asynchronous updatePost method that sends an individual font in the POST request to the WordPress server.

Now, it’s important to remember that WordPress implements Ajax in its specific way. First of all, each request must be sent to wp-admin/admin-ajax.php. This URL is available in the administration area as a global JavaScript variable ajaxurl.

Second, all WordPress Ajax requests must include an action argument in the data. The value of the action determines which hook tag will be used on the server-side.

In our case, the action value is goofonts_update_post. That means what happens on the server-side is determined by the wp_ajax_goofonts_update_post hook.

add_action( 'wp_ajax_goofonts_update_post', function() {
  if ( isset( $_POST['font'] ) ) {
    /* the post tile is the name of the font */
    $title = wp_strip_all_tags( $_POST['font']['family'] );
    $variants = $_POST['font']['variants'];
    $subsets = $_POST['font']['subsets'];
    $category = $_POST['font']['category'];
    /* check if the post already exists */
    $object = get_page_by_title( $title, 'OBJECT', 'post' );
    if ( NULL === $object ) {
      /* create a new post and set category, variants and subsets as tags */
      goofonts_new_post( $title, $category, $variants, $subsets );
    } else {
      /* check if $variants or $subsets changed */
      goofonts_update_post( $object, $variants, $subsets );
    }
  }
});

function goofonts_new_post( $title, $category, $variants, $subsets ) {
  $post_id =  wp_insert_post( array(
    'post_author'  =>  1,
    'post_name'    =>  sanitize_title( $title ),
    'post_title'   =>  $title,
    'post_type'    =>  'post',
    'post_status'  => 'draft',
    )
  );
  if ( $post_id > 0 ) {
    /* the easy part of tagging ;) append the font category, variants and subsets (these three come from the Google Fonts API) as tags */
    wp_set_object_terms( $post_id, $category, 'post_tag', true );
    wp_set_object_terms( $post_id, $variants, 'post_tag', true );
    wp_set_object_terms( $post_id, $subsets, 'post_tag', true );
  }
}

This way, in less than a minute, we end up with almost one thousand post drafts in the dashboard — all of them with a few tags already in place. And that’s the moment when the crucial, most time-consuming part of the project begins. We need to start manually add tags for each font one by one.
The default WordPress editor does not make much sense in this case. What we needed is a preview of the font. A link to the font’s page on fonts.google.com also comes in handy.

A custom meta box does the job very well. In most cases, you will use meta boxes for custom form elements to save some custom data related to the post. In fact, the content of a meta box can be practically any HTML.

function display_font_preview( $post ) {
  /* font name, for example Abril Fatface */
  $font = $post->post_title;
  /* font as in url, for example Abril+Fatface */
  $font_url_part = implode( '+', explode( ' ', $font ));
  ?>
  <div class="font-preview"> 
    <link href="<?php echo 'https://fonts.googleapis.com/css?family=' . $font_url_part . '&display=swap'; ?>" rel="stylesheet">
    <header>
      <h2><?php echo $font; ?></h2>
      <a href="<?php echo 'https://fonts.google.com/specimen/' . $font_url_part; ?>" target="_blank" rel="noopener">Specimen on Google Fonts</a>
    </header>
    <div contenteditable="true" style="font-family: <?php echo $font; ?>">
      <p>The quick brown fox jumps over a lazy dog.</p>
      <p style="text-transform: uppercase;">The quick brown fox jumps over a lazy dog.</p>
      <p>1 2 3 4 5 6 7 8 9 0</p>
      <p>& ! ; ? {}[]</p>
    </div>
  </div>
<?php }

add_action( 'add_meta_boxes', function() {
  add_meta_box(
    'font_preview', /* metabox id */
    'Font Preview', /* metabox title */
    'display_font_preview', /* content callback */
    'post' /* where to display */
  );
});

Tagging fonts is a long-term task with a lot of repetition. It also requires a big dose of consistency. That’s why we started by defining a set of tag “presets.” That could be, for example:

{
  /* ... */
  comic: {
    tags: 'comic, casual, informal, cartoon'
  },
  cursive: {
    tags: 'cursive, calligraphy, script, manuscript, signature'
  },
  /* ... */
}

Next with some custom CSS and JavaScript, we “hacked” the WordPress editor and tags form by enriching it with the set of preset buttons.

How we built it: The front end part (using NuxtJS)

The goofonts.com interface was designed by Sylvain Guizard, a french graphic and web designer (who also happens to be my husband). We wanted something simple with a distinguished “search” area. Sylvain deliberately went for colors that are not too far from the Google Fonts identity. We were looking for a balance between building something unique and original while avoiding user confusion.

While I did not hesitate choosing WordPress for the back-end, I didn’t want to use it on front end. We were aiming for an app-like experience and I, personally, wanted to code in JavaScript, using Vue.js in particular.

I came across an example of a website using NuxtJS with WordPress and decided to give it a try. The choice was made immediately. NuxtJS is a very popular Vue.js framework, and I really enjoy its simplicity and flexibility.
I’ve been playing around with different NuxtJS settings to end up with a 100% static website. The fully static solution felt the most performant; the overall experience seemed the most fluid.That also means that my WordPress site is only used during the build process. Thus, it can run on my localhost. This is not negligible since it eliminates the hosting costs and most of all, lets me skip the security-related WordPress configuration and relieves me of the security-related stress. 😉

If you are familiar with NuxtJS, you probably know that the full static generation is not (yet) a part of NuxtJS. The prerendered pages try to fetch the data again when you are navigating.

That’s why we have to somehow “hack” the 100% static generation. In this case, we are saving the useful parts of the fetched data to a JSON file before each build process. This is possible, thanks to Nuxt hooks, in particular, its builder hooks.

Hooks are typically used in Nuxt modules:

/* modules/beforebuild.js */

const fs = require('fs')
const axios = require('axios')

const sourcePath = 'http://wpgoofonts.local/wp-json/wp/v2/'
const path = 'static/allfonts.json'

module.exports = () => {
  /* write data to the file, replacing the file if it already exists */
  const storeData = (data, path) => {
    try {
      fs.writeFileSync(path, JSON.stringify(data))
    } catch (err) {
      console.error(err)
    }
  }
  async function getData() {    
    const fetchedTags = await axios.get(`${sourcePath}tags?per_page=500`)
      .catch(e => { console.log(e); return false })
    
  /* build an object of tag_id: tag_slug */
    const tags = fetchedTags.data.reduce((acc, cur) => {
      acc[cur.id] = cur.slug
      return acc
    }, {})
    
  /* we want to know the total number or pages */
    const mhead = await axios.head(`${sourcePath}posts?per_page=100`)
      .catch(e => { console.log(e); return false })
    const totalPages = mhead.headers['x-wp-totalpages']

  /* let's fetch all fonts */
    let fonts = []
    let i = 0
    while (i < totalPages) {
      i++
      const response = await axios.get(`${sourcePath}posts?per_page=100&page=${i}`)
      fonts.push.apply(fonts, response.data)
    }
  
  /* and reduce them to an object with entries like: {roboto: {name: Roboto, tags: ["clean","contemporary", ...]}} */
    fonts = (fonts).reduce((acc, el) => {
      acc[el.slug] = {
        name: el.title.rendered,
        tags: el.tags.map(i => tags[i]),
      }
      return acc
    }, {})

  /* save the fonts object to a .json file */
    storeData(fonts, path)
  }

  /* make sure this happens before each build */
  this.nuxt.hook('build:before', getData)
}
/* nuxt.config.js */
module.exports = {
  // ...
  buildModules: [
    ['~modules/beforebuild']
  ],
// ...
}

As you can see, we only request a list of tags and a list posts. That means we only use default WordPress REST API endpoints, and no configuration is required.

Final thoughts

Working on GooFonts was a long-term adventure. It is also this kind of projects that needs to be actively maintained. We regularly keep checking Google Fonts for the new typefaces, subsets, or variants. We tag new items and update our database. Recently, I was genuinely excited to discover that Bebas Neue has joint the family. We also have our personal favs among the much lesser-known specimens.

As a trainer that gives regular workshops, I can observe real users playing with GooFonts. At this stage of the project, we want to get as much feedback as possible. We would love GooFonts to be a useful, handy and intuitive tool for web designers. One of the to-do features is searching a font by its name. We would also love to add a possibility to share the bookmarked sets and create multiple “collections” of fonts.

As a developer, I truly enjoyed the multi-disciplinary aspect of this project. It was the first time I worked with the WordPress REST API, it was my first big project in Vue.js, and I learned so much about typography.

Would we do anything differently if we could? Absolutely. It was a learning process. On the other hand, I don’t think we would change the main tools. The flexibility of both WordPress and Nuxt.js proved to be the right choice. Starting over today, I would definitely took time to explore GraphQL, and I will probably implement it in the future.

I hope that you find some of the discussed methods useful. As I said before, your feedback is very precious. If you have any questions or remarks, please let me know in the comments!

The post How We Tagged Google Fonts and Created goofonts.com appeared first on CSS-Tricks.

Categories: Designing, Others Tags:

A Web Component with Different HTML for Desktop and Mobile

January 15th, 2020 No comments

Christian Schaefer has a great big write-up about dealing with web advertisements. The whole thing is interesting, first documenting all the challenges that ads present, and then presenting modern solutions to each of them.

One code snippet that caught my eye was a simple way to design a component that renders different HTML depending on the screen size.

<div class="ad">
  <template class="ad__mobile">
    // Mobile ad HTML code with inline script
  </template>
  <template class="ad__desktop">
    // Desktop ad HTML code with inline script
  </template>
  <script>
    const isMobile = matchMedia('(max-device-width: 20em)').matches;
    const ad = document.currentScript.closest('.ad');
    const content = ad
      .querySelector(isMobile ? '.ad__mobile' : '.ad__desktop')
      .content;
    
    ad.appendChild(document.importNode(content, true));
  </script>
</div> 

Clever. Although note that Christian ends up going a totally different route in the article.

Here’s that same code where I use a custom element and move the JavaScript to JavaScript just ‘cuz.

See the Pen
A Web Component with Different HTML for Desktop and Mobile
by Chris Coyier (@chriscoyier)
on CodePen.

The post A Web Component with Different HTML for Desktop and Mobile appeared first on CSS-Tricks.

Categories: Designing, Others Tags:

The Deal with the Section Element

January 15th, 2020 No comments

Two articles published the exact same day:

  1. Bruce Lawson on Smashing Magazine: Why You Should Choose HTML5
  2. Adam Laki on Pine: The Difference Between
    and

They are comparing slightly different things, but they both involve the

element.

I find it pretty clear when you reach for a

: When you want that element to be essentially meaningless. You’re only using it for styling purposes.

I always think of RSS when I think of

: Would this little bit of stuff make sense as an entry (which doesn’t necessarily need to be the entire content of the article)? If yes, use

; if not, don’t.

Bruce has a go-to answer:

[…] think of

not just as a newspaper article, or a blog post, but as an article of clothing — a discrete entity that can be reused in another context. So your trousers are an article, and you can wear them with a different outfit; your shirt is an article, and can be worn with different trousers; your knee-length patent leather stiletto boots are an article.

More importantly, it has some actual functionality. Bruce mentions that Apple WatchOS specifically uses it to find content on pages.

But

is more nebulous. At one point, you were supposed to think of sections as places where your

headings would reset, but that never came to fruition because it required a thing called “HTML5 Outlining” which zero browsers support.

So should we use

it at all? According to Bruce, sometimes! Smashing Magazine’s design for articles has a summary at the beginning of the article. Visually, that’s fairly clear, but less-so for screen reader users. The solution was wrapping the summary in an element with an aria-label to make that clear. But you aren’t supposed to use aria-label unless that element also has a role. You could apply a role to a

, but

already has a good default role, so:

<section aria-label="quick summary">
  Summary text
</section>

Adam’s article (sorry, Adam) is very vague on the points.

The main difference comes from the semantic. If you have a part in your site or application which has its logic you need to use the

tag to declare it…

… use

when it is logically correct to make a part of your site or app readable to the assistive technology. It is an excellent approach if you keep in mind the screen readers.

So you get a role="region" automatically for sections, but I’m not sure that does anything for screen readers, sans the label. In a quick test (Chrome for desktop with VoiceOver enabled), a

without an aria-label just wasn’t there in the Landmarks section of the Web Rotor, but it showed up once it had an aria-label.

Point is: don’t just use

and assume you’re doing something good for accessibility. Its purpose is pretty limited and only useful for establishing landmarks. Even then, you aren’t helping that much. Leonie Watson in the comments:

When the choice is between a visually hidden heading and a section element with an accessible name there are a couple of things to consider before deciding which approach is the right one.

When a section element has an accessible name it becomes a navigable landmark element, so a screen reader user can use their screen reader’s shortcut key for navigating from one to the next – just like they can do with headings.

According to the most recent WebAIM screen reader user survey though, 68% of screen reader users prefer to navigate by headings compared to 2.9% who prefer landmarks.

So from a strict accessibility point of view, you could probably drop the heading, but from a usability point of view you really want to keep the heading – at least until more screen reader users express a preference for using landmarks to navigate content.

The post The Deal with the Section Element appeared first on CSS-Tricks.

Categories: Designing, Others Tags:

Debunking the Myth: Accessibility and React

January 15th, 2020 No comments

I find it notable when the blog of a major accessibility-focused company like Deque publishes an article called Debunking the Myth: Accessibility and React. Mark Steadman is essentially saying if a site has bad accessibility, it ain’t React… it’s you. The tools are there to achieve good accessibility.

React didn’t use a

for a
Categories: Designing, Others Tags: