Infocon: green

 ∗ SANS Internet Storm Center, InfoCON: green

XML: A New Vector For An Old Trick

XML: A New Vector For An Old Trick, (Thu, Mar 5th)

 ∗ SANS Internet Storm Center, InfoCON: green

October 2014 saw the beginning of an e-mail campaign spamming malicious Microsoft Office document ...(more)...

Cuckoo Sandbox 1.2 released http://cuckoosandbox.org/2015-03-04-cuckoo-sandbox-12.html, (Thu, Mar 5th)

 ∗ SANS Internet Storm Center, InfoCON: green

-- Rick Wanner MSISE - rwanner at isc dot sans dot edu - http://namedeplume.blogspot ...(more)...

Anybody Doing Anything About ANY Queries?, (Thu, Mar 5th)

 ∗ SANS Internet Storm Center, InfoCON: green

(in an earlier version of this story, I mixed up Firefox with Chrome. AFAIK, it was Firefox, not ...(more)...

ISC StormCast for Thursday, March 5th 2015 http://isc.sans.edu/podcastdetail.html?id=4383, (Thu, Mar 5th)

 ∗ SANS Internet Storm Center, InfoCON: green

...(more)...

Putty 0.64 released last week (sorry, we missed it) - private-key-not-wiped-2 and diffie-hellman-range-check security issues resolved. See http://www.chiark.greenend.org.uk/~sgtatham/putty/ and http://www.chiark.greenend.org.uk/~sgtatham/putty/changes.ht, (Wed, Mar 4th)

 ∗ SANS Internet Storm Center, InfoCON: green

...(more)...

Wireshark 1.10.13 (old stable) and 1.12.4 (stable) released - see https://www.wireshark.org/download.html and https://www.wireshark.org/docs/relnotes/, (Wed, Mar 4th)

 ∗ SANS Internet Storm Center, InfoCON: green

...(more)...

March OUCH! Newsletter: Gaming Online Safely & Securely http://www.securingthehuman.org/ouch, (Wed, Mar 4th)

 ∗ SANS Internet Storm Center, InfoCON: green

...(more)...

No Wireshark? No TCPDump? No Problem!, (Wed, Mar 4th)

 ∗ SANS Internet Storm Center, InfoCON: green

Have you ever been on a pentest, or troubleshooting a customer issue, and the next step was to ca ...(more)...

Insurance

 ∗ xkcd.com

LIFEHACKS: You can just take all the luggage off the airport conveyer belt and leave with it. They don't check that it's yours at the door!

Quantity Queries for CSS

 ∗ A List Apart: The Full Feed

Don’t you just hate documentaries that don’t deliver? They have enticing names like In Search of the Giant Squid, and tease you with shots of murky underwater shapes and excited scientists pointing far out to sea. You settle down to watch, eyes narrowed with suspicion, thinking, “I better see some squid or I’m writing an angry letter to the network.”

Sure enough, 90 minutes of interviews with bored-looking fishermen later, the presenter is forced to conclude, “No… no, we didn’t find any big squids. But maybe one day [majestic orchestral flourish].” Great. You wanted Finding Nemo and got Not Finding Nemo instead.

I wouldn’t do that to you, friends. This is your guide to creating style breakpoints for quantities of HTML elements, much as you already do with @media queries for viewport dimensions. I’m not pointing at some blurry specification in the distance or a twinkle in an implementer’s eye. We’re going to do this today, with CSS that’s already available.

Dynamic content

Responsive web design is primarily concerned with one variable: space. In testing responsive layouts, we take an amount of content and see which spaces it will successfully fit into. The content is deemed constant; the space, variable.

The @media query is the darling of responsive web design because it allows us to insert “breakpoints” wherever one layout strategy ceases to be viable and another should succeed it. However, it’s not just viewport dimensions, but the quantity of content that can put pressure on space.

Just as your end users are liable to operate devices with a multitude of different screen sizes, your content editors are liable to add and remove content. That’s what content management systems are for.  This makes Photoshop mockups of web pages doubly obsolete: they are snapshots of just one viewport, with content in just one state.

In this article, I will be outlining a technique to make CSS quantity-aware using specially formed selectors. I will be applying these selectors to one classic problem in particular: how to alter the display of items in a horizontal navigation menu when there are too many to suit the initial layout mode. That is, I will demonstrate how to switch from a display: table-cell to a display: inline-block layout when the number of items in the menu becomes “more than or equal to 6.”

I will not be relying on any JavaScript or template logic, and the menu’s list markup will remain devoid of class attribution. By using CSS only, the technique honors the separation of concerns principle, according to which content (HTML) and presentation (CSS) have clearly defined roles. Layout is CSS’s job and, where possible, CSS’s only.

Comparing the initial menu bar layout for fewer than six items with the layout for six or more items

The demonstration is available on CodePen and will be referred to throughout the article.

To help me illustrate this qualification of quantity, I’ll be employing diagrams of squids in the article to represent HTML elements. Green squids with ticks represent elements that match the CSS selector in question, red squids with crosses are unselected elements, and grayed-out squids denote elements that don’t exist.

A key for the three squid symbols to be used in following diagrams. A green squid (for selected elements), a red squid (for unselected elements) and a grey squid for elements that don't exist

Counting

The key to determining the quantity of elements in a given context is to count them. CSS doesn’t provide an explicit “counting API,” but we can solve the same problem with an inventive combination of selectors.

Counting to one

The :only-child selector provides a means to style elements if they appear in isolation. Essentially, it lets us “style all the child elements of a particular element, if counting those children returns 1 as the total.” Aside from its stablemate :only-of-type, it is the only simple selector that can be described as quantity-based.

In the following example, I use :only-of-type to add a special style to any buttons that are the only elements of their element type among sibling elements. I give these lone buttons an increased font-size because singularity suggests importance.


button { 
  font-size: 1.25em;
}

button:only-of-type {
  font-size: 2em;
}

Here’s the crucial part. If I were to start out with one button, replete with a larger font size, and add buttons before or after it, each button would then adopt a smaller font size. The style of all the elements in the set is dependent on a quantity threshold of two: if there are “fewer than two” elements, the larger font size is honored. Take a look at that code again with the “fewer than two” notion in mind:


button {
  font-size: 1.25em;
}

button:only-of-type {
  font-size: 2em;
}

The fewer than two logic means one selected element (green squid) becomes two unselected elements (red squids) when an element is added

If it feels more natural, you can turn the CSS logic on its head using negation and make the condition “more than one.”


/* "More than one" results in a smaller font size */
button {
  font-size: 2em;
}

button:not(:only-of-type) {
  font-size: 1.25em;
}

The more than one logic means one unselected element (red squid) becomes two selected elements (green squids) when an element is added

Quantity n

Styling elements based on the “more than one” and “fewer than two” thresholds is a neat trick, but a flexible “quantity query” interface would accept any quantity. That is, I should be able to style “more than or equal to n” for any value of n. Then I can style “more than or equal to 6” in our navigation menu.

With a view to achieving this final goal, what if I were able to style discrete quantities like “exactly 6 in total” or “exactly 745”? How would I go about that? I would need to use a selector that allowed me to traverse sets of elements of any quantity numerically.

Fortunately, the :nth-last-child(n) selector accepts the number “n”, enabling me to count sets of elements from the end of the set toward the beginning. For example, :nth-last-child(6) matches the element that is sixth from last among sibling elements.

Things get interesting when concatenating :nth-last-child(6) with :first-child, introducing a second condition. In this case, I am looking for any element that is both the sixth element from the end and the first element.


li:nth-last-child(6):first-child {
  /* green squid styling */
}

If this element exists, the set of elements must be exactly six in quantity. Somewhat radically, I have written CSS that tells me how many elements I am looking at.

Of six squids, the first is green and the rest red. The first is subject to the nth-last-child(6) selector as well as the first-child selector

All that remains is to leverage this key element to style the remaining elements in the set. For this, I employ the general sibling combinator.

Six green squids because the first green squid is combined with the general sibling combinator to make all the red squids that follow green

If you’re not familiar with the general sibling combinator, the ~ li in li:nth-last-child(6):first-child ~ li means “any li elements that occur after li:nth-last-child(6):first-child.” In the following example, the elements each adopt a green font color if there are precisely six of them in total.


li:nth-last-child(6):first-child, 
li:nth-last-child(6):first-child ~ li {
  color: green;
}

More than or equal to 6

Targeting a discrete quantity—whether it’s 6, 19, or 653—is not especially useful because it pertains to such a specific situation. Using discrete widths rather than min-width or max-width in our @media queries would be similarly unhelpful:


@media screen and (width: 500px) {
  /* styles for exactly 500px wide viewports */
}

In the navigation menu, I really want to switch layouts at a threshold: a quantity watershed. I want to switch at six or more items—not exactly six items. When I reach that threshold, I would like to change from a distributed table layout to a simpler, wrappable inline-block configuration. Importantly, I would like to retain that switched configuration as the number of items further increases.

The question is, how does one begin to construct such a selector? It’s a question of offsets.

The n+6 argument

Another arithmetical argument adoptable by the :nth-child() selector takes the form “n + [integer]”. For example, :nth-child(n+6) styles all the elements in a set starting from the sixth.

A set of red squids that become green at the sixth squid for the remainder of the set (which can be of any size), counting upwards.

Though this has conceivable applications all its own, it’s not a “quantity-aware” selection method as such: we’re not styling anything because there are six elements or more in total; we’re just styling the ones that happen to enumerate higher than five.

To begin solving the problem properly, what we really need is to create a set of elements that excludes the last five items. Using the opposite of :nth-child(n+6):nth-last-child(n+6)—I can apply the switched layout properties to all “last elements” starting from the sixth, counting back toward the beginning of the set.


li:nth-last-child(n+6) {
  /* properties here */
}

This omits the last five items from a set of any length, meaning that when you reduce the length of the set below six, you cease to see any selected items. It’s a sort of “sliding doors” effect.

A set of green squids (to the left) and red squids (to the right) become a set of just red squids when the set becomes fewer than six in number

If, indeed, the set is greater than or equal to six in total, then all that remains is to style those last five items as well. This is easy: where there are more than six items, one or more items that “return true” (in JavaScript-speak) for the nth-last-child(n+6) condition must exist. Any and all of these extant elements can be combined with “~” to affect all items (including the last five) that follow it.

When a set of red squids has squids added to it, the squids to the right of the set become green and can be used to make the rest of the red squids green too (with the general sibling combinator)

The surprisingly terse solution to our problem is this:


li:nth-last-child(n+6),
li:nth-last-child(n+6) ~ li {
  /* properties here */
}

Naturally, 6 can be replaced with any positive integer, even 653,279.

Fewer than or equal to n

As in the earlier :only-of-type example, you can turn the logic on its head, switching from “more than or equal to n” to “fewer than or equal to n.” Which brand of logic you use depends on which state you consider the more natural default state. “Fewer than or equal to n” is possible by negating n and reinstating the :first-child condition.


li:nth-last-child(-n+6):first-child,
li:nth-last-child(-n+6):first-child ~ li {
  /* properties here */
}

In effect, the use of “-” switches the direction of the selection: instead of pointing toward the start from the sixth, it points toward the end from the sixth. In each case, the selector is inclusive of the sixth item.

nth-child versus nth-of-type

Note that I am using :nth-child() and :nth-last-child() in the preceding examples, not :nth-of-type() and :nth-last-of-type(). Because I am dealing in <li> elements and <li>s are the only legitimate children of <ul>s, :last-child() and :last-of-type() would both work here.

The :nth-child() and :nth-of-type() families of selectors have different advantages depending on what you are trying to achieve. Because :nth-child() is element agnostic, you could apply the described technique across different element type siblings:


<div class="container">

  <p>...</p>

  <p>...</p>

  <blockquote>...</blockquote>

  <figure>...</figure>

  <p>...</p>

  <p>...</p>

</div>


.container > :nth-last-child(n+3),
.container > :nth-last-child(n+3) ~ * {
  /* properties here */
}

(Note how I am using the universal selector to maintain element agnosticism here. :last-child(n+3) ~ * means “any element of any type following :last-child(n+3).”)

The advantage of :nth-last-of-type(), on the other hand, is that you are able to target groups of like elements where other siblings of different types are present. For example, you could target the quantity of paragraphs in the following snippet, despite them being bookended by a <div> and a <blockquote>.


<div class="container">

  <div>...</div>

  <p>...</p>

  <p>...</p>

  <p>...</p>

  <p>...</p>

  <p>...</p>

  <p>...</p>

  <p>...</p>

  <blockquote>...</blockquote>

</div>


p:nth-last-of-type(n+6),
p:nth-last-of-type(n+6) ~ p {
  /* properties here */
}

Selector support

All of the CSS2.1 and CSS3 selectors used in this article are supported in Internet Explorer 9 and above, including all reasonably recent mobile/handheld stock browsers.

Internet Explorer 8 support is good for most selector types, but technically partial, so you might want to consider a JavaScript polyfill. Alternately, you could pair the selectors for the “safer” of the layout strategies with IE9-specific classes. In the case of the navigation menu, the safer option is the one catering to more items, using inline-block. The declaration block would look something like this:


nav li:nth-last-child(n+6),
nav li:nth-last-child(n+6) ~ li, 

.lt-ie9 nav li {
  display: inline-block;
  /* etc */
}

In the real world

Suppose our navigation menu belongs to a content-managed site. Depending on who is administering the theme, it will be populated with a greater or fewer number of options. Some authors will keep things simple with just “Home” and “About” links provided, while others will cram their menu full of custom page and category options.

By providing alternative layouts depending on the number of menu items present, we increase the elegance with which we tolerate different implementations of the theme: we address variable content as we might variable screen dimensions.

Comparing the initial menu bar layout for fewer than six items with the layout for six or more items

So, there you have it: squid ahoy! You can now add quantity as a styling condition to your repertoire.

Content-independent design

Responsive web design solves an important problem: it makes the same content comfortably digestible between different devices. For folks to receive different content just because they have different devices would be unacceptable. Similarly, it’s unacceptable for a design to dictate the nature of the content. We wouldn’t tell an editor, “Lose that, will you? It makes the design look wrong.”

But what form the content takes, and how much of it there is at any one time, is frequently indeterminate—another unknown. And we can’t always rely on text wrapping and truncation scripts. To get a real handle on content independence, we need to develop new tools and techniques. Quantity queries are just one idea.

Web design is about mutability, difference, uncertainty. It’s about not knowing. Uniquely, it is a mode of visual design not about manifesting a form, but about anticipating the different forms something might take. To some it is unbearably perplexing, but to you and me it is a challenge to relish. Like the elusive giant squid, it is a seriously slippery customer.

Stopping the Infighting About Digital Standards

 ∗ A List Apart: The Full Feed

I grew up in Columbia, Maryland, a planned community (see Figure 5.1). And as with the word “governance,” people tend to react to the phrase “planned community” in a not-so-positive way. “Planned” sounds dull and uncreative to people: cookie-cutter homes, on cookie-cutter lots, on cookie-cutter streets—“Little Houses Made of Ticky Tacky,” to invoke Malvina Reynolds’ well-known song. And Columbia was all about that: a city built quickly based on a template. There were street naming conventions, standard model homes, standardized lot sizes, and a standard “village” configuration complete with strategically placed shopping and swimming pools.

Map showing the neighborhoods of Columbia, Maryland.
Figure 5.1: Columbia, Maryland—a planned community that opened in 1967.

So what do you get when you build a city on a standards-based framework? Those who focus on the standards part like to say “boring,” “all the same,” “not diverse,” because they believe that any standardization leads to a lack of creativity or innovation. But that wasn’t all there was to it. Once you factor in the context and intent of Columbia, the picture becomes different. Columbia was one of the first planned communities intended to be racially and economically integrated. Its founder, James Rouse, had a vision about creating a place for people to live—a place that would make you feel good, a place where everyone would just get along. And there was the timing: Columbia was founded in the mid-sixties and started its initial growth spurt in the 1970s.

In standardized fashion, villages and neighborhoods were often named after literary figures with streets being named after lines in their works. That standard resulted in street names like Evening Wind Lane, Wood Elves Way, and Plaited Reed. No Main Street. No Church Street. No School Street. Sure, there are some boring people in Columbia, but Columbia has spawned some interesting people, too, including the following:

All this is to say that, contrary to popular belief from some of my clients, standardization does not have to give way to things boring or flat or uninteresting. It doesn’t mean that the standardized interface can’t be beautiful, or that your customer’s experience of your seamlessly integrated process that takes them from desktop to mobile to call center won’t be sublime. The belief that standardization necessarily leads to the boring and uninteresting is too simple. It’s what’s going on inside the structure that is important. You could have a beautiful, old, organically grown, charming town with nothing creative going on for it except that it looks good. Or you can have tract housing turning out really interesting people, music, and thought. It’s all about the substance and interactivity of the interior. What comes out of a community, planned or unplanned, is really contingent upon the intention and people within it.

So, if you’re going to take the time to establish and implement a standards framework, it had better be around the right intention. And that intention is expressed through your digital strategy. Your standards are the tactical manifestation of your strategy that will bring into existence the intent of your digital strategy. That’s why organizations that have no real digital strategy struggle so much with coming up with a quality online presence and why their digital team spends so much time arguing and debating about standards. In the absence of clear business intent, standards can be left up to a matter of taste and debate. So, if you are undertaking to develop standards without first having defined a digital strategy, you may develop a standards compliant website and have consistently moderated social channels. But your digital target will likely not resonate as well as it could with your customers. Only standards derived from clear vision have the capacity to create a high user experience and deliver on the mission of your organization.

I was lucky. I learned early that standards could enable rapid growth and provide a framework for coherent development, all the while creating a space for real creativity. Standardization can be, and often has been, the platform for creative and important work. But I’ll go further. Standards, in fact, might be an essential ingredient.

Standards frame and limit what you can do so that you can get across a certain message or get a particular piece of work done. And that’s the message you should carry to digital teams who are reluctant to adopt a standards-based framework. Likewise, you can have a World Wide Web operating within the open standards of the W3C with the whole of humanity trying to express itself freely and creatively, or you could have something else, like an Internet and Web controlled by a few businesses and political interests. It’s about clarity of intention and the quality and sustaining quality of your implementation. It’s about having a vision and figuring out how to make it happen and holding true to your aims and your standards.

Why Digital Standards Are Important

Practically speaking, having digital standards enables an organization to put into place details for execution so that digital work can be performed consistently and effectively. From a governance perspective, knowing who has the authority to define standards saves time by minimizing the time that resources spend making decisions about the same factors, over and over again. For instance, it’s good to know which Web browsers your organization’s digital presence supports, what fonts you use for mobile applications, and when and where it’s acceptable to use your organization’s mark. It might also be good to know that your organization operates on a .NET platform, or that when you refer to staff on a public website it’s always “Ms. Welchman” and not “Lisa.”

In an ecommerce environment, standards make sure that the right content gets to the right customer at the right point in the sales cycle. For example, it’s good for customers to know that whatever they are buying on a site, the sales checkout process will be the same. And it makes customers more comfortable knowing that whether they are purchasing a pair of trousers or a jacket, they will still have the same interface for toggling between garment color choices. In addition, it doesn’t just make the user’s task easier to accomplish, it also takes stress off internal digital workers.

Adopting a standards-based framework takes the stress out of development. When you have standards in place, more time can be spent having conversations about the substance and purpose of the work that is to be done instead of arguing about the details of execution or who has the authority to make decisions about application coding standards or a graphical user interface.

An organization’s digital standards steward’s job is to establish and maintain a standards-compliant environment within the organization (see Figure 5.5). Standards compliance exists in an environment where certain activities have occurred:

Illustration of the forces that influence the cycle of standards compliance.
Figure 5.5: Creating a standards-compliant environment.

The reason why most organizations have trouble with standards compliance is because they miss or incorrectly address these activities and then are only left with one alternative—to enforce (usually undocumented) standards after the non-compliant content and applications are already posted (or nearly posted) online. This reactive dynamic can lead to a stressful dynamic for digital teams. Too often, the core digital team is perceived as the last-minute bad guy, telling teams that the look and feel isn’t right or that the flow of the application screens is unusable.

The core digital team shouldn’t be in the position of having to ask their colleagues to remove content and applications that might represent weeks or months of effort. In the best of cases, the organizational standards steward is not an enforcer, but someone who is able to create an environment where bad things don’t get online in the first place. Let’s take a look at what the standards steward does to make that happen (see Table 5.1).

Table explaining the differences between policies, standards, and guidelines.

Standards Definition and Documentation

If you want your extended digital team to follow your standards, it’s important to write them down. This might seem self-evident, but many organizations, when asked, are unable to produce documentation of the standards that they claim their stakeholders will not comply with. This “I’m an expert, so do what I say” dynamic is hardly fair to digital stakeholders because these stakeholders often have some digital domain expertise and are heavily impacted by the business outcomes of their online efforts (so they are informed and they have a vested interest). Here are a few things to keep in mind when documenting standards.

Standards Dissemination

A common problem in digital teams is that they’ve often forgotten that their internal digital stakeholders are users as well. Typically, the experience of accessing and understanding digital standards for internal users in organizations is very low. For example, if you are a digital stakeholder trying to understand the rules of development for your organization, you are probably not interested in browsing through a beautifully designed PDF of a style guide. You just want to find the information quickly so you know, say, what font color to use for a visited link reference. The digital standards steward can help facilitate that information by being more strategic about standards dissemination.

Standards Implementation

Digital standards stewards usually feel that their job is complete when they have documented the standards and placed them online. In reality, their job has just begun. The real work lies in ensuring that the standards are implemented.

Standards Compliance Measurement

Hopefully, if you have defined, disseminated, and implemented your standards well, compliance will be high. Still, websites and intranets are large, complex environments. Even in the best of circumstances, standards will be misunderstood or ignored in haste. That is why it is import to measure standard compliance in a consistent and automated way. You can monitor standards through spot checks and prepublication reviews, but in a large production environment, this is often a daunting task. Implementing a website auditing tool is often helpful because it allows the core digital team to provide quantified reports on things such as broken links, terminology language use, usability, compliance, and SEO. Reporting back to stakeholders about which standards they are upholding and which they are not, and creating a plan to lead the team to higher rates of compliance, is a more positive method of standards enforcement than threats that content or applications will be removed from the server.

Even after you’ve implemented your standards lifecycle, there will still be exceptions to the rule. There will be times when digital workers will want to break with the standards. And then each organization will have to determine when it’s okay to break the rules and when it’s not. These types of situation can be touchy, particularly if the resources involved in the standards breach are fairly senior in the organization (like a CEO who insists on having the picture on a homepage or wants to write lengthy, dense blog posts). In the end, these types of situations will have to be negotiated by the standards steward, authors, and the “standards breaker.” During the discussion and negotiation, it is important to emphasize how the business is being put at risk due to a standards breach and how the business could benefit if the standards were complied with. At the end of the day, you’ll never have 100% compliance, but hopefully the vast majority of your digital presence will follow the rules as defined by digital standards authors.

Freak Attack - Surprised? No. Worried? A little. , (Wed, Mar 4th)

 ∗ SANS Internet Storm Center, InfoCON: green

There has been some press surrounding the SSL issue published recently dubbed Freak. ">1

Six Places

 ∗ BitWorking

One of the questions that comes up regularly when talking about zero frameworks is how can you expect to stitch together an application without a framework? The short answer is "the same way you stitch together native elements," but I think it's interesting and instructional to look at those ways of stitching elements together individually.

There are six surfaces, or points of contact, between elements, that you can use when stitching elements together, whether they are native or custom elements.

Before we go further a couple notes on terminology and scope. For scope, realize that we are only talking about DOM, we aren't talking about composing JS modules or strategies for composing CSS. For the terminology clarification, when talking about DOM I'm referring to the DOM Interface for an element, not the element markup. Note that there is a subtle difference between the markup element and the DOM Interface to such an element.

For example, <img data-foo="5" src="https://example.com/image.png"/> may be the markup for an image. The corresponding DOM Interface has an attribute of src with a value of "https://example.com/image.png", but the corresponding DOM Interface doesn't have a "data-foo" attribute, instead all data-* attributes are available via the dataset attribute on the DOM Interface. In the terminology of the WhatWG Living Standard, this is the distinction between content attributes vs IDL attributes, and I'll only be referring to IDL attributes. So with the preliminaries out of the way let's get into the six surfaces that can be used to stitch together an application.

Attributes and Methods

The first two surfaces, and probably the most obvious, are attributes and methods. If you are interacting with an element it's usually either reading and writing attribute values:

element.children

or calling element methods:

document.querySelector('#foo');

Technically these are the same thing, as they are both just properties with different types. Native elements have their set of defined attributes and methods, and depending on which element a custom element is derived from it will also have that base element's attributes and methods along with the custom ones it defines.

Events

The next two surface are events. Events are actually two surfaces because an element can listen for events,

ele.addEventListener(‘some-event’, function(e) { /* */ });

and an element can dispatch its own events:

var e = new CustomEvent(‘some-event’, {details: details});
this.dispatchEvent(e);

DOM Position

The final two surfaces are position in the DOM tree, and again I'm counting this as two surfaces because each element has a parent and can be a parent to another element. Yeah, an element has siblings too, but that would bring the total count of surfaces to seven and ruin my nice round even six.

<button>
  <img src="">
</button>

Combinations are powerful

Let's look at a relatively simple but powerful example, the 'sort-stuff' element. This is a custom element that allows the user to sort elements. All children of 'sort-stuff' with an attribute of 'data-key' are used for sorting the children of the element pointed to by the sort-stuff's 'target' attribute. See below for an example usage:

<sort-stuff target="#sortable">
   <button data-key=one>Sort on One</button>
   <button data-key=two>Sort on Two</button>
 </sort-stuff>
 <ul id=sortable>
   <li data-one=c data-two=x>Item 3</li>
   <li data-one=a data-two=z>Item 1</li>
   <li data-one=d data-two=w>Item 4</li>
   <li data-one=b data-two=y>Item 2</li>
   <li data-one=e data-two=v>Item 5</li>
 </ul>

If the user presses the "Sort on One" button then the children of #sortable are sorted in alphabetical order of their data-one attributes. If the user presses the "Sort on Two" button then the children of #sortable are sorted in alphabetical order of their data-two attributes.

Here is the definition of the 'sort-stuff' element:

    function Q(query) {
      return Array.prototype.map.call(
        document.querySelectorAll(query),
          function(e) { return e; });
    }

    var SortStuffProto = Object.create(HTMLElement.prototype);

    SortStuffProto.createdCallback = function() {
      Q('[data-key]').forEach(function(ele) {
        ele.addEventListener('click', this.clickHandler.bind(this));
      }.bind(this));
    };

    SortStuffProto.clickHandler = function(e) {
      var target = Q(this.getAttribute('target'))[0];
      var elements = [];
      var children = target.children;
      for (var i=0; i<children.length; i++) {
        var ele = children[i];
        var value = ele.dataset[e.target.dataset.key];
        elements.push({
          value: value,
          node: ele
        });
      }
      elements.sort(function(x, y) {
        return (x.value == y.value ? 0 : (x.value > y.value ? 1 : -1));
      });
      elements.forEach(function(i) {
        target.appendChild(i.node);
      });
    };

    document.registerElement('sort-stuff', {prototype: SortStuffProto});

And here is a running example of the code above:

  • Item 3
  • Item 1
  • Item 4
  • Item 2
  • Item 5

Note the surfaces that were used in constructing this functionality:

  1. sort-stuff has an attribute 'target' that selects the element to sort.
  2. The target children have data attributes that elements are sorted on.
  3. sort-stuff registers for 'click' events from its children.
  4. sort-stuff children have data attributes that determine how the target children will be sorted.

In addition you could imagine adding a custom event 'sorted' that 'sort-stuff' could generate each time it sorts.

So there's your six surfaces that you can use when composing elements into your application. And why the insistence on making the number of surfaces equal six? Because while history may not repeat itself, it does rhyme.

On Our Radar: Communication Builds Community

 ∗ A List Apart: The Full Feed

This week, we at ALA have been thinking about processes of inclusion—that is, how we communicate with our communities. Who (and what) gets to be included? How do we use vocabularies, fonts, even emojis, to make those choices? And how do those choices create our culture?

Here’s what’s on our radar:

Anna Debenham, technical editor:
The UX team at Salesforce have written about the difficulties they’ve had coming up with color schemes that look good and meet the WCAG2 guidelines on color contrast—so they’ve built a wonderful site called Color Safe that generates color palettes that meet these guidelines. It’s great to see companies release tools like this that help make everyone’s sites more accessible.

Marie Connelly, blog editor:
I really loved this piece over on Hopes & Fears on how the Deaf community is incorporating new terminology (think: selfie, photobomb) into American Sign Language. It touches on so many things I love: words, the subtle complexities of language, and the beautiful messiness of community collaboration. I think the examples of how the Deaf community works through this process offer great food for thought for any of us working on content and communication.

Caren Litherland, editor:
“I’m pretty content,” writes Indra Kupferschmid in a pragmatic survey of the current state of web typography. Almost anything we could ever do in print, we can now do on the web; the web “forces us to think about typography in terms of parameters and to get clear about content versus form.”

Ethan Marcotte, technical editor:
Kathy Sierra’s essay on skater culture is a fascinating, moving look at a once-inclusive industry that, over time, marginalized its female members. It’s also an urgent warning for the digital industry, which faces a similar crisis.

A gif about a music video we are into:

A gif of Tina from Bob's Burgers jumping up and down.
No outline will ever hold us.

What about you?
What stories are drawing your attention? Got any posts, pictures, tools, or code you want to share? (We love sharing!) Tweet us what’s on your radar—and what should be on ours.

Let's Encrypt!, (Fri, Feb 27th)

 ∗ SANS Internet Storm Center, InfoCON: green

As I have

Antoine Lefeuvre on The Web, Worldwide: Designing for Post-Connected Users — Part 1, the Diagnostic

 ∗ A List Apart: The Full Feed

I toured the world twice—first in 2009–10, then in 2013–14. Only four years between the two trips, but it felt like a century internet-wise. Where I had to go wifi-hunting in 2009, in 2014 the web was absolutely everywhere—even in places with no mobile coverage, such as remote El Chaltén in Argentine Patagonia. Yet, I had the feeling this advent of a truly connected world wasn’t much cause for celebration. Indeed, I met many who struggled with an increasing need to disconnect.

 

I’m so glad I’m taking a year off. Off from work, off from stress, off from modern life.

…Do you have WhatsApp?

Twenty-something European trekker in Northern Laos

I heard this line from fellow travelers numerous times, be it in Laos, Costa Rica, or New Zealand. I actually said it myself! As absurd as it sounds, it’s a perfect illustration of our ambiguous relationship with the internet.

Hyper-connected, hypo-social

Has the internet become repulsive? It certainly has in the eyes of Italian artist Francesco Sambo. His HyperConnection series depicts a dark and creepy humanity transformed—or tortured—by technology. Strikingly, Sambo is a savvy internet user, showcasing his work through Behance and SoundCloud.

HyperConnection, CC BY-NC-ND, Francesco Sambo.

Artists are often the first to capture the collective unconscious. Antisocial network I and II by Congolese artist Maurice Mbikayi are skulls made out of keyboards. “The […] sculptures ask questions such as to whom such technological resources are made available and at what or whose expense? What are the consequences impacting on our people and environment?” states Mbikayi. Less morbid but equally shocking is the alienation depicted in the Strangers in the Light series by French photographer Catherine Balet. In a very visual way, she questions us: are our babies born in a mad world?

Strangers in the Light by Catherine Balet
-->

Digital malaise

Not only does hyper-connection alter our social relationships, it also makes us dumber, as pointed out as early as 2005. It threatens our health too. Twenty-first-century afflictions include digital fatigue, social media burnout or compulsive internet use.

Cures for these rising internet-related disorders include such radical solutions as rehab centers, or disconnection.

“I was wrong”

Most of the experiments in living offline have begun with the same cause and led to the same conclusion: the internet drives us crazy, but it brings us much more than we realize.

“The internet isn’t an individual pursuit, it’s something we do with each other. The internet is where people are,” says journalist Paul Miller in his famous “I was wrong” piece on The Verge. When you disconnect, you’re not just cutting the link with a network of computers, you’re actually isolating yourself from the rest of society. Miller also emphasizes that there is no such thing as a divide between virtuality and reality. To me, the best example of this is the sharing economy of “virtual” communities such as AirBnb or Kickstarter that is all about changing the “real” world.

The cure is worse than the disease

A lot of people today feel torn between two extremes. They aren’t against modern ways of interaction per se, but they won’t close their eyes to the excesses. The concern becomes even greater when the developing minds of children and teenagers are at stake. Many parents believe their digital-native offspring aren’t capable of using the internet moderately. You can’t blame them when you come across stats such as 20 percent of French young people are addicted to their mobile.

Is disconnection the only alternative to unhealthy internet use? That cure is worse than the disease. There must be another way.
Internet users are ripe for a new era, for the next step. A “more asserted, more mature” use, in the words of Thierry Crouzet, another famous disconnectee. Neither hyper- nor dis-connected: post-connected.

I see the advent of post-connected users wary of addictive or invasive tools. Post-connected users are also well aware that a social network centered on the individual, rather than on the group, inevitably leads to narcissism. They see the internet as a means for more direct human relationships—not a thing that feeds on our continual attention.

The internet pictured as monstrous should sadden us all, for it is one of mankind’s greatest inventions, one which has done so much for knowledge, education and human rights. Besides, it isn’t addictive by nature, we have turned into a drug.

We are the drug dealers

We love it if other people listen to us. Why else would you tweet?

Psychologist James Pennebaker at the University of Texas at Austin interviewed by WSJ

We, the web makers, have designed interactions which encourage selfishness and competition. We created tools that cause fatigue and stress. We practically invented hyper-connection.

It is therefore our responsibility to design for post-connected users. If we’ve been powerful enough to create addiction, then we must surely have the resources to imagine post-connected user experiences. How? I’ll give you some leads in my next column.

In the meantime, I would very much like to discuss this topic with you. Have you ever felt the urge to disconnect? Do you agree there is such a thing as post-connected users? Would you say addiction is the sign of a successful design? Your comments, criticism, and true stories are most welcome.

gRPC

 ∗ BitWorking

Today Google launched gRPC, a new HTTP/2 and Protocol Buffer based system for building APIs. This is Google's third system for web APIs.

The first system was Google Data, which was based on the Atom Publishing Protocol [RFC 5023]. It was an XML protocol over HTTP. The serving system for that grew, but started to hit scalability issues at around 50 APIs. The scaling issues weren't in the realm of serving QPS, but more in the management of that many APIs, such as rolling out new features across all APIs and all clients.

Those growing pains and lessons learned led to the next generation of APIs that launched in 2010. In addition to writing a whole new serving infrastructure to make launching APIs easier, it was also a time to shed XML and build the protocol on JSON. This Google I/O video contains good overview of the system:

Now, five years later, a third generation API system has been developed, and the team took the opportunity to make another leap, moving to HTTP/2 and Protocol Buffers. This is the first web API system from Google that I haven't been involved in, but I'm glad to see them continuing to push the envelope on web APIs.

The Arc of a Design Career: Khoi Vinh on The Big Web Show № 128

 ∗ Jeffrey Zeldman Presents The Daily Report: Web Design News & Insights Since 1995

Khoi Vinh, photographed by Khoi Vinh

KHOI VINH IS my guest in Episode № 128 of The Big Web Show (“Everything Web That Matters”).

Khoi is a web and graphic designer, blogger, and former design director for The New York Times, where he worked from January 2006 until July 2010. Prior to that, Khoi co-founded and was design director for Behavior, a New York digital design studio. He is the author of  How They Got There: Interviews With Digital Designers About Their Careers (coming in 2015) and Ordering Disorder: Grid Principles for Web Design (New Riders, 2010), and was a leading proponent of bringing grid-based graphic design principles to web design in the mid-2000s. In 2011, Fast Company named him one of “The 50 Most Influential Designers in America.”

Listen to Episode № 128 of The Big Web Show.

URLs

http://www.subtraction.com
https://twitter.com/khoi
http://howtheygotthere.us
http://trywildcard.com
http://www.nytimes.com/2008/04/21/business/media/21askthetimes.html
http://www.creativebloq.com/khoi-vinh-using-sketch-instead-photoshop-6133901
http://www.behaviordesign.com
http://vllg.com/constellation/galaxie-polaris


Sponsored by DreamHost.

10 Years Ago in ALA: Attribute Anarchy

 ∗ A List Apart: The Full Feed

WARNING: there are experimental elements and deeply controversial syntaxes ahead! Proceed at your own peril! You have been warned, and the website you save…could be your own. Ten years ago, right here in ALA, a wild-eyed hell-raiser going by “PPK” made a radical proposal: custom attributes in markup.

In my opinion, using custom attributes to trigger the behavior layer … will help to separate behavior and structure and to write simple, efficient scripts.

Besides, triggers can grow to be more complicated than just a “deploy behavior here” command. Sometimes you’ll want to add a value to the trigger.

Well, okay. At the time it was radical. Here in the future, we have perfectly valid HTML5 data- attributes to contain all manner of information and act as behavioral triggers for our scripts.

The front end of a website consists of three layers. XHTML forms the structural layer, which contains structural, semantic markup and the content of the site. To this layer you can add a presentation layer (CSS) and a behavior layer (JavaScript) to make your website more beautiful and user-friendly. These three layers should remain strictly separate. For instance, it should be possible to rewrite the entire presentation layer without touching either the structural or the behavior layer.

All of this holds as true today as it did a decade ago. I know I’ve used data- attributes for both: to invoke custom behavior without touching the classes I use for styling—keeping my behavioral layers and presentation layers separate—and to pass relevant configuration information to said scripts. Picturefill 1’s data-srcset="1x source.jpg, 2x hd-source.jpg" comes to mind: we could define an attribute and write a script that dictates how the associated element should behave, all in one perfectly valid package.

The presence of the maxlength attribute alerts the script to check user input in this textarea, and it can find the maximum length of this specific textarea in the value of the attribute. As long as we’re at it we can port the “required” trigger to a custom attribute, too. required=“true”, for instance, though any value will do because this trigger just gives a general alert and doesn’t carry extra information.

maxlength? required? These custom attributes that once so daringly flew in the face of conventional web standards are now part of the HTML5 standard.

Maybe it’s best that the web didn’t linger too long on our warning at the top of the page.

 

Best Practices for Errors in Go

 ∗ Justinas Stankevičius

Error handling seems to be one of the more controversial areas of Go. Some are pleased with it, while others hate it with passion. Nevertheless, there is a handful of best practices that will make dealing with errors less painful if you're a sceptic and even better if you like it as it is.

Know when to panic

The idiomatic way of reporting errors in Go is having the error as the last return value of a funtion. However, Go also offers an alternative error mechanism called panic that is similar to what is known as exceptions in other programming languages.

Despite not being suitable everywhere, panics are useful in several specific scenarios.

When the user explicitly asks: Okay

In certain cases, the user might want to panic and thus abort the whole application if an important part of it can not be initialized. Go's standard library is ripe with examples of variants of functions that panic instead of returning an error, e.g. regexp.MustCompile. As long as there remains a function that does this in an idiomatic way (regexp.Compile), providing the user with a nifty shortcut is okay.

When setting up: Maybe

A scenario that, in a way, intersects with the previous one, is the setting up phase of an application. In most cases, if preparations fail, there is no point in continuing. One case of this might be a web application failing to bind the required port or being unable to connect to the database server. In that case, there's not much left to do, so panicking is acceptable, even if not explicitly requested by the user.

This behavior can also be observed in the standard library: the net/http muxer will panic if a pattern is invalid in any way.

func (mux *ServeMux) Handle(pattern string, handler Handler) {
    mux.mu.Lock()
    defer mux.mu.Unlock()

    if pattern == "" {
        panic("http: invalid pattern " + pattern)
    }
    if handler == nil {
        panic("http: nil handler")
    }
    if mux.m[pattern].explicit {
        panic("http: multiple registrations for " + pattern)
    }

    // ...

Otherwise: Not really

Although there might be other cases where panic is useful, returned errors remain preferable in most scenarios.

Predefine errors

It's not unusual to see code returning errors like this

func doStuff() error {
    if someCondition {
        return errors.New("no space left on the device")
    } else {
        return errors.New("permission denied")
    }
}

The wrongdoing here is that it's not convenient to check which error has been returned. Comparing strings is error prone: misspelling a string in comparison will result in an error that cannot be caught at compile time, while a cosmetic change of the returned error will break the checking just as much.

Given a small set of errors, the best way to handle this is to predefine each error publicly at the package level.

var ErrNoSpaceLeft = errors.New("no space left on the device")
var ErrPermissionDenied = errors.New("permission denied")

func doStuff() error {
    if someCondition {
        return ErrNoSpaceLeft
    } else {
        return ErrPermissionDenied 
    }
}

Now the previous problems aren't anymore.

if err == ErrNoSpaceLeft {
    // handle this particular error
}

Provide information

Sometimes, an error can happen because of a whole lot of different reasons. Wikipedia lists 41 different HTTP client errors. Let's say we want to treat them as errors in Go (net/http does not). What's more, we'd like to be able to look into the specifics of the error we received and find out whether the error was 404, 410 or 418.

In the last paragraph we developed a pattern for discerning errors from one another, but here it gets a bit messy. Predefining 41 separate errors like this:

var ErrBadRequest = errors.New("HTTP 400: Bad Request")
var ErrUnauthorized = errors.New("HTTP 401: Unauthorized")
// ...

will make our code and documentation messy and our fingers sore.

A custom error type is the best solution to this problem. Go's implicit interfaces make creating one easy: to conform to the error interface, we only need to have an Error() method that returns a string.

type HttpError struct {
    Code        int
    Description string
}

func (h HttpError) Error() string {
    return fmt.Sprintf("HTTP %d: %s", h.Code, h.Description)
}

Not only does this act like a regular error, it also contains the status code as an integer. We can then use it as follows:

func request() error {
    return HttpError{404, "Not Found"}
}

func main() {
    err := request()

    if err != nil {
        // an error occured
        if err.(HttpError).Code == 404 {
            // handle a "not found" error
        } else {
            // handle a different error
        }
    }

}

The only minor annoyance left here is the need to do a type assertion to a concrete error type. But it's a small price to pay compared to the fragility of parsing the error code from a string.

Provide stack traces

Errors as they exist in Go remain inferior to panics in one important way: they do not provide important information about where in the call stack the error happened.

A solution to this problem has recently been created by the Juju team at Canonical. Their package errgo provides the functionality of wrapping an error into another one that records where the error happened.

Building up on the HTTP error handling example, we'll now put this to use.

package main

import (
    "fmt"

    "github.com/juju/errgo"
)

type HttpError struct {
    Code        int
    Description string
}

func (h HttpError) Error() string {
    return fmt.Sprintf("HTTP %d: %s", h.Code, h.Description)
}

func request() error {
    return errgo.Mask(HttpError{404, "Not Found"})
}

func main() {
    err := request()

    fmt.Println(err.(errgo.Locationer).Location())

    realErr := err.(errgo.Wrapper).Underlying()

    if realErr.(HttpError).Code == 404 {
        // handle a "not found" error
    } else {
        // handle a different error
    }
}

Our code has changed in several ways. Firstly, we wrap an error into an errgo-provided type. This code now prints the information on where the error happened. On my machine it outputs

/private/tmp/example.go:19

referencing a line in request().

However, our code has become somewhat messier. To get to the real HttpError we need to do more unwrapping. Sadly, I'm not aware of a real way to make this nicer, so it's all about tradeoffs. If your codebase is small and you can always tell where the error came from, you might not need to use errgo at all.

What about concrete types?

Some might point out that a portion of the type assertions could have been avoided if we returned a concrete type from a function instead of an error interface.

However, doing that in conjunction with the := operator will bring trouble. As a result, the error variable will not be reusable.

func f1() HttpError { ... }
func f2() OsError { ... }

func main() {
    // err automatically declared as HttpError
    err := f1()

    // OsError is a completely different type
    // The compiler does not allow this
    err = f2()
}

To avoid this, errors are best returned using the error type. Standard library avoids returning concrete types as well, e.g. os package states:

Often, more information is available within the error. For example, if a call that takes a file name fails, such as Open or Stat, the error will include the failing file name when printed and will be of type *PathError, which may be unpacked for more information.

This concludes my list of best practices for errors in Go. As in other areas, a different mindset has to be adopted when coming into Go from elsewhere. "Different" does not imply "worse" though and deciding on a set of conventions is vital to making Go development even better.

Ghost of Threading Past

 ∗ One Big Fluke

I got an interesting link from Luciano Ramalho in reference to the asynchronous Python discussion: A paper called "Why Events Are A Bad Idea (for high-concurrency servers)" from Eric Brewer's lab in 2003. I hadn't seen this one before. The abstract says:

We examine the claimed strengths of events over threads and show that the weaknesses of threads are artifacts of specific threading implementations and not inherent to the threading paradigm. As evidence, we present a user-level thread package that scales to 100,000 threads and achieves excellent performance in a web server. We also refine the duality argument of Lauer and Needham, which implies that good implementations of thread systems and event systems will have similar performance. Finally, we argue that compiler support for thread systems is a fruitful area for future research. It is a mistake to attempt high concurrency without help from the compiler, and we discuss several enhancements that are enabled by relatively simple compiler changes.

Fixing threads must have been a popular subject back then. I remember that Linux got fast user-space mutexes in December 2003. Python's PEP 342 "Coroutines via Enhanced Generators" is from May 2005. But that design builds on rejected PEP 325 "Resource-Release Support for Generators" from August 2003, which outlined a way to make generators more cooperative. Jeremy Hylton also wrote about "Scaling [Python] to 100,000 Threads" in September 2003. Coroutines are clearly a big part of the paper's solution and Python had them early on.

Node.js brought back the popularity of an event loop in May 2009. Many programmers rejoiced, others lamented its implications. Node is bound to a single thread like Python. It can only take advantage of multiple CPUs using subprocesses, also like Python. It's funny that Python's asyncio now focuses on event loops, like Node, for better asynchronous programming. But Node and JavaScript won't get async coroutines until ECMAScript 7. At least it's got a good JIT and you can use ES6 features today.

Go, released in March 2011, addresses all of the issues from the paper with its goroutines and channels. The paper mentions the importance of dynamic stack growth, which Go addressed with segmented stacks (as of Go 1.4, it uses a stack reallocation model instead). The paper suggests compiler support for preventing race conditions, which Go has built-in. The paper says that threads are bad for dynamic fan-in and fan-out, but Go and Python's asyncio solve those use-cases, too. Seems to me that Go is winning the race these days.

If I could retitle the original paper, I'd call it: "Why Coroutines Are a Good Idea". What's old is new; what's new is old — always.

Reliably hosted by WebFaction.com