Saturday, June 30, 2018

Why you should never code for new browsers

A quick, very short post today.

First, I should preface this by saying that I've been writing human/computer interfaces for a very long time...and for a good part of that time - it's been more than two decades now, I've been writing for these crazy user-agents we call browsers. The Mosaic Wars are a little fuzzy, but I remember the First Browser War vividly.

Every great once in a while, I see a question along the lines of "is x compatible with some-really-old-browser" and there's always a response along the lines of "no one uses that browser anymore, if you're coding for anything older than n - 1, then you're wasting money".

I can say with 100 percent certainty, that if you're coding for specific browsers - be they old or new - then you're wasting money.

Browsers are released very frequently - for Chrome and Firefox, it's typically about every 6 weeks. The specs they claim to support are release much less frequently...for example, a new HTML spec was release every 1 or 2 years between 1995 and 1999 when HTML 4.01 came out, but the next spec - HTML5 - didn't come out for 14 years. CSS first came out in 1996 and was updated about every 2 years until CSS 3 came out (in 1999). 

What's that I hear? A host of voices singing the popular refrain "but we use JavaScript"? JavaScript is finally to the point where it is currently being updated annually - which makes it the fastest changing language of front-end development and still much slower than 6 to 8 times a year.

Add into this mix of rapidly updating browsers the mix of assistive technology (with its own specifications), and we begin to get a picture of extremely volatile user-agents and very stable specifications.

If there was one thing we should have learned from the First Browser War, it's that we should be not be coding according features that are available in one browser that we then try to port to another browser with extra work. Determine what your needs (and wants) are, code to the specification, and let the browsers catch up. Browsers update much faster and are very likely to render your code as you want it to look within the year without additional work from you. Also, this approach is as backwardly-compatible as possible (what in the accessibility world we call being robust)...and if you're not attempting to deliver a product to every end user, regardless of the user-agent they use, then you really are wasting money.

Happy coding.

Saturday, May 26, 2018

Finding Your Way

One of the common challenges when writing interfaces is describing processes that have multiple steps in a way that is both understandable and accessible. Adding different functionality and different devices further complicates this. If we were Hänsel or Grethel, we would just leave a trail of pebbles or breadcrumbs.

Alas, we often find that even though we are not Hänsel or Grethel, navigation within a process is still often a problem and poorly written HTML or CSS can significantly contribute to the several common accessibility concerns and usability concerns surrounding the progress/breadcrumbs component as well. This post offers a pattern that is accessible and mobile friendly without being a burden.

Again, the HTML and CSS needed to provide a usable breadcrumbs component is relatively simple, but it can pose an even greater problem if it is not written correctly. It should also be noted that in addition to the pattern described here, it is very important that the page title and the primary heading should be modified to indicate the update progress.

When first building our progress bar or breadcrumbs, we must make the determination if our it represents unidirectional progress or if we might be able to restart the process. If the flow is unidirectional, you might consider using the progress element to demonstrate progress; however, be aware that the progress element is dependent on the OS in use, and the ability to modify the display is limited.

If we are providing the ability to move backward in the process - i.e., the process is not unidirectional - that means the breadcrumbs or progress bar has a navigational element, and it should be identified as such. The good news is that much of the code is unchanged. To demonstrate the difference in the code, both versions are provided below.

Image showing breadcrumbs with the current step highlighted, in both mobile and desktop.
Breadcrumbs Snapshot
The code below, is complete, with the exception that in the demonstration there is a style rule to center the content, and it produces the breadcrumbs show in the Breadcrumbs Snapshot.



HTML (without navigation)

<div class="breadcrumbs">   <ol >     <li>       <span data-step="#1" role="text">         <span class="description">Personal Information</span>       </span>     </li>     <li aria-current="step">       <span data-step="#2" role="text">         <span class="description">Financial Information</span>       </span>     </li>     <li>       <span data-step="#3" role="text">         <span class="description">Review Information</span>       </span>     </li>     <li>       <span data-step="#4" role="text">         <span class="description">Thank You</span>       </span>     </li>   </ol> </div>



HTML (with navigation)

<nav aria-label="Breadcrumb" class="breadcrumb">   <ol>     <li>       <a href="signup/1">       <span data-step="#1" role="text">         <span class="description">Personal Information</span>       </span>       </a>     </li>     <li aria-current="step">       <a href="signup/2">       <span data-step="#2" role="text">         <span class="description">Financial Information</span>       </span>       </a>     </li>     <li>       <a href="signup/3">       <span data-step="#3" role="text">         <span class="description">Review Information</span>       </span>       </a>     </li>     <li>       <a href="thankyou">       <span data-step="#4" role="text">         <span class="description">Thank You</span>       </span>       </a>     </li>   </ol> </nav>

A few items to note - one is the inclusion of the aria-current attribute, which lets users of assistive technology know which step is current, and another is the inclusion of the role attribute, which fixes a 'feature' in some assistive technologies that sees child elements as distinct from their wrapping elements, resulting in a different value for the accessible name than what would commonly be expected. Otherwise, the code should be self-explanatory.

Next, we add some CSS



CSS

.breadcrumbs {   display: inline-block;   width: auto; } .breadcrumbs ol {   list-style-type: none;   margin: 0 auto;   overflow: visible;   padding: 0; } .breadcrumbs ol li {   float: left;   background: darkgray;   border: 0.1em solid darkgray;   color: white;   padding: 0.5rem;   position: relative;   margin-right: 1rem; } .breadcrumbs ol li::after {   background: darkgray;   content: '';   display: inline-block;   height: 0.5rem;   left: 100%;   margin: 0;   padding: 0;   position: absolute;   top: 0.7rem;   /* width = margin-right + (border-width * 2) */   width: 1.2em;   z-index: -1; } .breadcrumbs ol li:last-of-type {   margin-right: 0; } .breadcrumbs ol li:last-of-type::after {   display: none; } .breadcrumbs ol li a {   background: inherit;   color: inherit;   text-decoration: none; } .breadcrumbs ol li[aria-current] {   background: green;   border-color: green;   color: white; } .breadcrumbs ol li[aria-current] ~ li {   background: lightgray;   color: black; } @media (max-width: 20rem) {   .breadcrumbs ol li {     border-radius: 100%;   }   .breadcrumbs ol li [data-step]::before {     content: attr(data-step);   }   .breadcrumbs ol li a .description {     clip: rect(0, 0, 0, 0);     clip-path: polygon(50% 0%, 100% 50%, 50% 100%, 0% 50%);   position: absolute;   } }

Here again, we need to comment about the code. First, the .breadcrumbs ol li rule is for past steps. This allows us to use the aria-current attribute as the selector for current steps and siblings of aria-current after the aria-current item - .breadcrumbs ol li[aria-current] ~ li - are those steps not yet completed. Another issue to note is that we are using the float property on list items. We might have used the display property to modify where items display, but in many assistive technologies, modification of the display property modifies the accessibility tree, rendering all our effort to construct an accurate tree moot.


Admittedly, this is a simple example; however, it should suffice to demonstrate how a progress bar or breadcrumbs might be built.

Happy coding.

Thursday, May 17, 2018

Hiding in Plain Sight: How to affect what you can't see in your analytics

What if I told you there is a way to improve your Google rank (placement) and significantly increase conversion and that you would not be able to discover how to do it by looking at your analytics? Would you do it? Would it matter what the delta was or would it matter what work was involved?

Several years ago, I worked on a project at PayPal with the sole purpose of improving conversion during checkout. A few "features" were added, but the majority of the project was running A/B tests for (minor) design and content changes for the existing product, so the amount of actual development work was minimal aside from refactoring existing code.

One might think such a project would yield as much as one hundred basis points, but realistically, since these were "minor" changes it should have yielded about half that...but the thing is, it was twice that amount. The most reasonable explanation we might have for this remarkable difference is that we were affecting users that were not even on our radar.

Years before that project, as a side project I took over the website for a non-profit. Before running any A/B tests or modifying design or content in any way, I refactored the code to use semantic HTML and CSS and their rank went from fifth to first overnight. Nearly all the research up to that point indicated that selection of keywords and inbound and outbound links were the primary source for SEO, but here again, something hidden had a significant impact.

In both of these projects, it was the use of solid, time-tested best practices of web development that yielded these results, in particular, Semantic HTML and CSS, unobtrusive JavaScript, and Progressive Enhancement. It was what is ordinarily hidden from users and even those in decision-making roles in technology that had the greatest impact.

Frankly, it seems like an outlandish claim, and had I not seen them firsthand, I would suspect such claims were the usual puffery in which engineers engage - sort of like boosting performance by switching turbochargers. After all, we're often told that the best tools are the newest tools and that time-to-market is the most important factor. Abundant anecdotal evidence demonstrates that neither of those beliefs are based in reality.

Again, here are the four principles behind these transformations.
  1. All HTML was Semantic HTML.
  2. All CSS was Semantic CSS.
  3. All JavaScript was unobtrusive.
  4. Sites were built using Progressive Enhancement.
I should point out that it's possible to use any of these principles alone, and using any of them will give you some of the benefits. The goal when using these practices were to create pages that are
  • fast,
  • flexible, enabling a user to complete the task in any user agent,
  • easily maintained
The primary goal in these projects was to get a page loaded in less than 4 seconds anywhere in the world. Because network reliability and speed are always unknowns outside the US, and even some places within the US, that benchmark meant the page had to load on an internal network in considerably less time. (It also meant I spent time writing a module that would allow me to simulate network rates and reliability that exist in the real world outside the US to more accurately gauge speed...but that's another story.)

The secondary goal was to build pages that would run in any user agent well enough to allow the user to accomplish the task in the shortest amount of time, in part because we know that the amount of time a process takes is inversely proportional to the likelihood of the user completing that process.

The simple truths that govern this secondary goal are that semantic HTML is easier for user agents other than browsers, like the bot(s) that rank your site, to understand; semantic CSS enables you to write fewer, better-performing rules; and unobtrusive JavaScript and Progressive Enhancement expand your audience into non-traditional user agents with the same codebase.

The Problem with Analytics

Examining the effect of these four principles is difficult, in part because of the way data collection for web analytics changed in the first decade of the 21st century. To simplify it, I'll use a mostly hypothetical example.

Let's say you're tracking user agents and see that seventy-three percent of your traffic is coming from Chrome, twenty-one percent is coming from Safari, and five percent is coming from Firefox - like the stats for this site report. Already, one percent is not reported, and if, as is the case for most analytics, your analytics package is using JavaScript to track that rather than the actual web server logs, there are even more users not tracked at all. It's unlikely that you will ever get insight into these users, which is why it has become so easy to dismiss the effect of certain principles, Progressive Enhancement being principle among them.

Progressive Enhancement

One percent is a small number, is it really enough to justify the amount of work Progressive Enhancement requires? On one hand, one percent likely is a small number - unless you're a company like PayPal, with more than 110 million active users - and on the other hand, that one percent represents a much larger number because it's the one percent we know exists. How many users fall into that not-the-popular-browsers group that typically hovers around "one percent", but aren't even measured because their browser isn't identified?

A government agency in the UK tracked visitors to government websites using actual web server logs to determine what percentage of visitors weren't being tracked by their JS analytics package and it was about two percent. Two percent. On government websites. Within a first-world country. For those government websites, that "one percent" is really three percent.

Retail websites are categorically different than government websites, so attempting to extrapolate user behavior in a government-assisted activity to private activity is a little like comparing apples and oranges. The user population in each group has different needs, desires, and expectations, and as a result, have different behavior. All we need consider is the desires and expectations around privacy between the two different categories to see there is a very clear difference in behavior. We can, however, easily support the case that the percentage of tracked users interacting with a government website is likely higher than those interacting with non-government websites. As a result, there is no way to determine what percentage of your actual traffic is untracked unless you are analyzing server logs rather than relying directly on analytics served by JavaScript. The principle of Progressive Enhancement, however, means even these untracked users are served, regardless of the user agent or its features.

Performance Matters

Since we are unlikely to gain insight into the untracked users, what does the data we collect about the tracked group tell us? The primary message we get from the data is that, performance is the most significant issue in web development - it's typically even more important than content. This is not something we've just learned - we've known it for decades. It's also not something that's unmeasured. Organizations frequently calculate the cost of each page or step in a process by calculating the abandonment rate and the drop off rate based on page load time or time-to-interactive, what Twitter used to call "time to first tweet". In a recent, rather finely-tuned test by etsy.com, we see a high correlation between the addition of a mere 160 kilobytes of page weight and a twelve percent drop off.

Semantic Code

Semantic CSS, writing CSS in a way that actually describes something about the code, and semantic HTML, writing HTML in a way that describes the content it contains, expands the robustness of the code (one of the measures of accessibility), is more maintainable, and reduces the amount of code delivered. Semantic code also performs better - there are fewer class and ID selectors to process and a cleaner, more compact Accessibility Tree is built.

Also, lighter pages load faster, and that's important because one of the lessons we've learned from gathering data about tracked users shows that nearly forty percent of users will abandon your site if it takes your page longer than three seconds to "load". If your HTML suffers from divitis and other non-semantic features, or if your CSS is bloated with non-semantic rules, it will take longer to load and parse, pushing the load time further out.

Even worse is the effect non-semantic HTML has on the Accessibility Tree. If your HTML is not semantic, you will have to add code to "fix" the Accessibility Tree, to make your code accessible. Unfortunately, as you add code the risk of harming accessibility even further raises more than the chance you will resolve issues. Here the problems become even more pronounced, because we run into a sub-group of "untracked" users within the tracked users - users who combine accessibility tools with their user agent.

Generally, we only identify site visitors using accessibility tools when they report an issue. There is no method available to determine if a user has engaged an accessibility tool. Conservative estimates generalize that for every accessibility issue registered, at least ten users have been blocked and are unable to complete their task. All industry experts agree about this premise - use of semantic HTML is the best way to minimize the accessibility risks.

A Hypothetical Example

Let's assume that you've looked at your target market and found that seventy-three percent use Chrome, twenty-one percent use Safari, and five percent use Firefox. Almost all - ninety-nine percent - of your users are using agents that have JavaScript enabled by default and you're not aware of "untracked" users. Based on this fantastic news, you've developed your site using ReactJs or Angular and you've tested it locally and the render time is pretty good - it only takes one or two seconds from the request until it's interactive from your development server.

Here's how that plays out in the real world. Your (average) page is really about eighty kilobytes of HTML, about ninety kilobytes of CSS, and almost two megabytes (or more) of JavaScript. If you've not used React's styled elements, your CSS is entirely separate, but nearly all of your eighty kilobytes of HTML is still embedded in the JavaScript. That JavaScript, which has to be entirely loaded before it can be parsed (to make sure there are no syntax errors) and rendered (or hydrated if you've used React's "server-side rendering") is on a CDN, so there's very little latency in the network, but on a 4G connection, mobile devices have a peak of about one-tenth the speed of your local network connection, which means at 100 percent reliability and speed, it's going to take about ten times as long to download the file(s) on a mobile device.

If we assume that you've really optimized and compressed and tweaked your code in production all the ways it's not optimized, compressed, and tweaked in development and your development network is not really that great, the difference between time to interactive on your development site for the more than two megabytes of code is about half of what it will be in production.

So your development version loads in about two seconds, which is pretty fast, and you're pretty confident. In production, your JavaScript resources load HTML into your page in four seconds (versus the two seconds in development) instead of two, but you decide that's still good. Of course, we know you've still lost forty percent of users. Unfortunately, what we now know is that's forty percent of tracked users.

Your beautifully designed site, which only renders for user agents with JavaScript enabled (rendering a "white screen of death" for at least three percent of visitors) unfortunately hasn't undergone an accessibility or usability review and was not written using semantic code. As a result of this oversight, your site has several color contrast issues, navigation is not identified, and your data collection form is not properly labeled - and some unknown portion of the roughly fifty percent of visitors who have made it to your page unscathed cannot complete the task. Here is where we see the final indignity - our analytics cannot tell us why that percentage does not convert, even if it tells us that they do not convert.

An Alternative Example

As an alternative, if your site were written with semantic code using Progressive Enhancement, the code would be lighter, loading in less than four seconds. Your analytics may not have changed, but by using Progressive Enhancement, no one gets a white screen of death, even those in the untracked category, which simply become a hidden bonus rather than a missed opportunity, because the technology fails gracefully.

The semantic code is, by its nature, accessible, and eliminating accessibility issues and offering an estimated ten-fold benefit that taps into an otherwise untracked market - a market that Barclays estimated in 2017 as worth twelve billion pounds, which is not a small number for any organization.

Conclusion

We know sites written with semantic code and unobtrusive JavaScript using Progressive Enhancement
  • perform faster
  • have greater accessibility
  • have greater stability
  • have greater durability
  • are more maintainable
The question is what are these qualities worth to you - do you continue on as usual or do you try to tap into what is hidden in your analytics. We tend to know a lot of information about what we know - it's what we don't know where the greatest promise rests.

Happy coding.

Saturday, March 24, 2018

Creation, Attribution, and Misogyny

One of the hidden, insidious, morally bankrupt things that repeatedly peeks its head above the slime in open source development is plagiarism - specifically, the lack of attribution.

We can have all the arguments you want about 'pirating' code and the like - this is not about patent trolls - and pirating code is stealing, but it's also not really the subject of this post. This post, instead, is about intentionally writing creators out of history - whether it's through intentionally omitting an author or reference link or by actively deleting it. Of course, it happens all the time and it's dishonest...and not in a cute "I'm a smuggler for the Rebel Alliance" kind of way, but in a .

Oooh, what's that? Open source is different - it shouldn't recognize any individual authors/creators/innovators? No, that is absolutely not the case, and writing them out of history is not only dishonest, it's misogynistic as well. That's right, I went there. If you are writing authors, creators, or innovators out of history, you're a sexist pig - and frankly, there's no other way to see it.

We must take sides. Neutrality helps the oppressor, never the victim. Silence encourages the tormentor, never the tormented.
Elie Wiesel
I hear people all over the world crying out in terror "I'm not a sexist pig, I delete (or omit) all creators, not just women". Here's the thing, though, in removing creators you are, at the least, maintaining the illusion and bias that many people have that women are not creators, and at the worst, actively promoting a hostile environment that dismisses and negates the contribution of women. Neither option is something which should invoke pride in our work.

Women are profoundly underrepresented in STEM. That's a simple fact. We can debate whether it's a pipeline problem (it both is and isn't) or whether STEM fields are hostile environments for women (they are), but ultimately none of those causes affects the outcome that women are underrepresented in STEM, and it isn't getting much better, folks.

Tweet by @stubbornella: It's pretty shocking how often this mixup happens given that OOCSS (my work) predates SMACSS (@snookca's work) by nearly 5 years.
Read this Twitter thread
Let's take a case in point, Nicole Sullivan started something nine years ago that is used almost universally today in user-interface engineering today, and not only is she not "Twitter Verified", many people don't even know her name, and Wikipedia even deletes entries about OOCSS.

I appreciate Nicole's contributions to the industry I have made my career. When I use her work - whether it's CSSLint or OOCSS - I point out that it doesn't come from me, and given my experience working directly with her while she was consulting for PayPal, I know she would act in a similarly ethical manner.

Attribution is important, and as my career has progressed, I've seen it growing in importance. As anyone who suffers from Imposter Syndrome can tell you, love/hate relationships with ownership and attribution of accomplishments is a very real thing, but it's something the entire tech industry needs to get a grip on...and it's something that very definitely eludes us.

One final thought - as someone who has led teams of engineers, including those working on projects that resemble Frodo and Sam's journey through the Dead Marshes, morale is something rather fragile. One of the easiest ways to boost morale is to give everyone on the team the sense that their contribution matters - to, as we used to say at PayPal (and eBay), keep it human. One of the easiest ways to keep it human is to afford each other the dignity of recognizing the creator in them. Of course, the opposite is also true - take that dignity away and morale will soon follow.

Related posts: Visibility and Obscurity, My Pen Is My Tongue

Wednesday, February 28, 2018

My Pen Is My Tongue

A series of tweets about self-documenting code
A few days back I sent out a series of tweets about "self-documenting code". Self-documenting code is an idea that's been around for many years, like stories about the wee folk...and like the wee folk, no one has seen self-documenting code.

The short version of the tweet series is that if you're writing code, you should be writing documentation as well - it's really too important to skip. This post, however, is not really about self-documenting code, but rather about how to write documentation, and more specifically a certain piece of documentation that you should never neglect.



I entered the whole techno-geek world at a time when computer labs were a real thing. Punchcards and shelves full of binders stuffed with documentation were commonplace. Documentation isn't like that anymore. When Java came along, I was almost enthused to use JavaDoc because of the level of clarity it added when writing the documentation. Now that nearly all code written by large, technologically advanced firms is either in Java or JavaScript (or ECMAScript), JavaDoc and JsDoc are - or should be - the de facto standard.

There is seldom serious argument against using one of these two tools anymore. There is disagreement about how the tools should be used, however. In the JsDoc community, one of the points of contention is the @author tag. To be clear, the JsDoc tool authors have stopped using the author tag and no 'contributor' tag has been added. It might seem, from their use (or non-use) that these tags are unimportant, and in fact, that is a common perception, especially in light of the advances in source code management, or what we used to call "version control".

However, not only should you use the authorship tag(s), you should be encouraging everyone else to use them as well.

It would come as a surprise to no one if I reminded you that we write code to solve problems. Not only are we writing code to solve problems, we're writing code to solve complex problems. For example, no one would write code to add two numbers...doing simple calculations on large data sets, perhaps, but there is a "complexity bar", below which we wouldn't dream of using code to address a problem. The first step of writing code is understanding the problem you're trying to solve.

As a hypothetical example, let's assume you've inherited a project. You've read the documentation that describes the solution to the problem the code offers, but after getting a small understanding of the problem combined with the solution being used, you have a list of questions. Why was this particular solution chosen over other solutions, for example. You can make some assumptions, but wouldn't it be nice to be able to contact the author to ask for their insight? Code, even well-documented code, is only a partial story. Just like every fan of a book turned into a motion picture knows, even faithful adaptations leave out bits that someone thought important. The first reason to include authorship information in your documentation, then, is the abundance of information it can point you to.

The common response to this concept is that the authorship information is not needed in the documentation because source control software, like git (my personal favorite), can track that information and expose it through tools like blame.

This response, however, misses the purpose of such tools. Version control is tied to a specific change...in git parlance, a commit. Yes, you can look at a particular line and see the last change of that line - the author of that change - but that is qualitatively different information than the author of a solution...and that information is generally only the last change. In order to get authorship information you must follow changes to a specific line back through history, and if at any point history was squashed or rewritten, that information is gone. Version control tools are excellent at solving the problem the author intended them to solve, as the author understood the problem; do not expect another author's code to solve a problem as you understand it.

Another reason authorship is important is we, as an industry...and really we as the human race...have difficult acknowledging the contributions of women and persons of color. The list of women who have significantly contributed in STEM fields without attribution is long...far too long. Not including attribution participates in that system of oppression by reinforcing the status quo. If we want to have any hope of disrupting patterns of discrimination, patterns that have existed for millennia, we must combat it at every turn.

A while ago I wrote a post called Visibility and Obscurity that described a situation in which attribution was changed on work I had done. In academia this is typically called plagiarism, and in most instances it's a punishable offense. Even outside academia, claiming to have done something you have not done can have serious consequences - Scott Thompson's resume scandal is evidence of that.

We should be writing code we can release with pride. Build things you're proud of and put your name on it...and give that same consideration to others. Amplify voices that are too often silenced or ignored - it does not diminish your contribution and it makes a difference. If it only makes a difference to the woman or person of color who finally has their contribution recognized - that's enough. If the only people who see an authorship reference are your employees, your colleagues, that's enough - they are important too.

Happy coding.

Wednesday, February 14, 2018

Git 'r Done

Wow, it's already far into the new year, and I've not written anything since before the winter (at least in my hemisphere) holidays. Time marches on, though, so this is a short post that maybe will make things a little easier.

One of the things I've come to rely on is the ubiquity of git. Seems like nearly every company is using it, whether it's github, or some internally hosted version...or even something, like Bitbucket, that uses git as its engine.

There are a lot of arguments about how best to use git - some people (*cough* wrongly *cough*) suggest that all development ought to be done in a fork and merged back into the communal repo and some use a clone/branch model. One argument against the clone/branch model is the number of branches that become stale - and frankly, it can become a mess.

One thing you, as a maintainer, will need to do if you're using a clone/branch model is establish, fairly early, a process for pruning those stale or dead branches. Once you have a process in place, though, what do you do? How do you list the branches and their detail in a convenient way?

One way is the following...

git for-each-ref --sort=authordate --format='%(authordate:iso8601) %(refname) by %(authoremail)' refs/remotes

This will give a list that can be used to either manually delete branches, or you could use this within a script that takes some action, like emailing or deleting, when the ref matches some criteria. Here's some sample data in case you want to build such a tool.

2017-07-27 22:29:31 -0400 refs/remotes/origin/master by <hrobertking@mailinator.com>
2017-10-03 11:31:58 -0700 refs/remotes/origin/lint-config by <hrobertking@mailinator.com>
2017-11-01 11:15:33 -0700 refs/remotes/origin/feature/US123456789 by <james.howlett@mailinator.com>
2018-01-10 14:26:58 -0700 refs/remotes/origin/feature/US234567890 by <james.howlett@mailinator.com>
2018-01-23 15:51:15 -0700 refs/remotes/origin/bugfix/DE123456 by <ororo.munroe@mailinator.com>
2018-01-25 16:51:50 -0700 refs/remotes/origin/bugfix/DE234567 by <remy.lebeau@mailinator.com>
2018-01-30 12:00:58 -0500 refs/remotes/origin/bugfix/DE345678 by <ororo.munroe@mailinator.com>
2018-01-31 17:47:52 -0500 refs/remotes/origin/feature/US345678901 by <hrobertking@mailinator.com>
2018-02-02 14:36:42 -0700 refs/remotes/origin/bugfix/DE456789 by <hrobertkinging@mailinator.com>

If you're looking for other git things to do, feel free to check out my github git repo, where you'll find a sample .gitconfig with aliases that have been tested in the bash terminal on a Mac. Most also run on PuTTY or other clients that can run a bash session, but a few will need to be modified.

Hopefully, this will help you "git 'r done" (after thinking about what you need to do, of course).

Happy coding.

Saturday, January 20, 2018

Getting the light show started

Anyone who's followed me for very long knows that one of my big concerns is accessibility. Today I'm going to tell you exactly how you can violate accessibility rules and possibly trigger epileptic seizures in a portion of the population at the same time. I'm sharing this information because this should NEVER happen, and yet it does (this means I've seen it in the wild).

Let's take, as a hypothetical case, a design where when you hover over something you want to show a callout - a very common design. In browser-based terms, there are two ways you can handle hovering interactions - using the CSS pseudoclass (which you should only use with focus and active, by the way) and with JavaScript using the mouse events.

Using CSS it's relatively straightforward - add the two elements (we'll call them the target and callout) to the DOM as siblings, placing the callout after the target, and hide the callout by default and use a sibling selector with the hover pseudoclass to show the callout. By the way, this shifts the show/hide functionality to the GPU and keeps it out of the script stack - which means it'll provide better performance. This is the best way to implement this little trick.

Unfortunately, more than a few engineers in our industry don't like CSS and prefer to do everything in JavaScript. In this case, we would still have the two DOM nodes and we would add event listeners to show the callout when we mouseover the target and hide the callout when we mouseover it. This method keeps the show/hide in the script stack, meaning it'll likely get janky at some point.

Here's where the bad stuff comes into play.

If the target and callout overlap (they way they sometimes will - especially in a responsive design), they will 'flash' as the 'hover' events fire on each element. This will be bad, very bad, especially if there is significant contrast between the colors, unless you're trying to simulate a nightclub or light show and don't really care about the likelihood of triggering photosensitive epilepsy.

If you want to see how this works, run the code samples below in a browser, but be warned, the target/callout flashes more than three times per second.

CSS
<!DOCTYPE html> <html> <body> <style type="text/css"> #callout, #target {   border: 1px solid black;   height: 10rem;   left: 20px;   position: absolute;   top: 100px;   width: 90%; } #callout {   z-index: -1; } #target:hover + #callout {   z-index: 10; } </style> <div id="parent">   <p id="target" style="background-color: #0f0;">target</p>   <p id="callout" style="background-color: #f00;">callout</p> </div> </body> </html>


JavaScript
<!DOCTYPE html> <html> <body> <style type="text/css"> #callout, #target {   border: 1px solid black;   height: 10rem;   left: 20px;   position: absolute;   top: 100px;   width: 90%; } #callout {   z-index: -1; } </style>
<div id="parent"> <p id="target" style="background-color: #0f0;">target</p> <p id="callout" style="background-color: #f00;">callout</p> </div>
<script> var callout = document.getElementById('callout'); var target = document.getElementById('target'); target.addEventListener('mouseover', function() {     callout.style.zIndex = '10'; }); callout.addEventListener('mouseover', function() {     callout.style.zIndex = '-1'; }); </script> </body> </html>


Notes

  1. A callout is those little bubbles that have a triangular-ish thing connecting the bubble to an item as a visual context clue.
  2. The events mouseenter, mouseleave, mousemove, mouseout,  and mouseover are the events applicable to a 'hover'

Tuesday, December 5, 2017

Print It!

Several years ago, Smashing Magazine did an article called 5 Powerful Tips and Tricks for Print Style Sheets, but we don't often remember print stylesheets today because, let's be honest, people don't generally print things anymore - at most, we save them to PDF on our device - but it is still an important part of the design of the interface.

Print stylesheets, however, can be pretty powerful, and there are a lot of times we still want a hardcopy of something we've worked on. In the financial services sector, we see this fairly often. People want a record of what they've signed up for - especially when it comes to paying interest. It doesn't really matter if the "hardcopy" is a PDF or a tree-killing version you can hold in your hands, we want it to look official.

There are a few things you'll want to keep in mind when printing, but generally, read the Smashing Magazine article I've linked above. One issue the Smashing Magazine article doesn't go into detail about is font size. Don't mess about with the font size. There are loads of posts about accessibility and font size and how to use rem or em rather than px on a web page - the same holds true for printed versions. You don't want someone getting the small print version when what they see on the screen is large print.

One thing that deserves a special callout - the Smashing Magazine article talks about expanding links and this is very important. In printed versions the user will not (generally) have the ability to hover over or follow a link, so make sure the appropriate links are followed by the URL in plain text. I'd suggest making certain the following is in your print stylesheet.



CSS

a:not([href^=javascript]):after {   content: " <" attr(href) "> "; } a[href="#"]:after {   content: "" !important; }


I'm going to go a little further here, because if you wish to exclude other links, let's say anything linked to "foo.com", for example, simply add those to the first rule, and use the in-string regular expression operator, like so...


CSS

a:not([href*=foo\.com]):not([href^=javascript]):after {   content: " <" attr(href) "> "; } a[href="#"]:after {   content: "" !imporant; }


...and you've included the link, enclosed in < and >, in your printed versions.

You'll notice, that on line one there are two differences in the attribute selector. First, I'm using a different regular expression selector, *= and second, I have a \ before the "." in "foo.com".

The selector *= matches a partial value in an attribute (you can learn more about regular expressions in attribute selectors at https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors), so take care that you have the most complete partial possible - in my example, links to barfoo.com would also be excluded.

Additionally, the . is a special character in CSS syntax (as are ":" and "/"), which means it will need to be escaped in order to be seen as part of the value, just as "http://www.foo.com" would need to be escaped as "http\:\/\/www\.foo\.com".

That's all there is to it - powerful selectors and the function that returns an attribute can make your printed (and saved-to-PDF) documents better for your users.

Happy coding.

Wednesday, October 18, 2017

Single use one-way binding

One of the things UI engineers are likely to be asked to do is some sort of one-way binding. The argument typically goes something like this...

Product Owner
We want this to be dynamic.
Engineer 1
All the browser is doing is showing what the server gives it, so the server needs to deliver the information to the browser.
Engineer 2
The server can't send <that information> to the browser because <reasons>, but the browser already has it, so just send back a template that's populated with the data.
Engineer 1
Data bindings are expensive, I don't think that's a good idea.
Engineer 2
<insert your favorite JS framework> does it, so it's OK.
Product Owner
I don't care how it's done, it just needs to be done.

Having had this conversation in nearly every role I've been engaged in over the last decade (more really), I can tell you there are good arguments on both sides because I've made those arguments (on both sides) depending on the specifics of the case.

While I won't reveal what I believe the deciding factors to be - there are just too many variables to make such a generalization - I can reveal a relatively easy way of getting at least some of the functionality...and I'll do it using a real-life case from my experience from nearly a decade ago.

The Case

In order to reduce the number of pages in a process, it was decided that we would do an AJAX call when the user clicked the submit button on page one. The response to that request would be the next page, minus all the extraneous stuff like headers and footers - it would be just the next page in the form. Because of the nature of the application - it involved sensitive information - there were significant restrictions on what information could be stored, and how it could be stored, on the server. There were also performance concerns that limited the amount of information going back and forth in requests and responses.

The Solution

In our case, we simply had to perform some sort of data binding. We agreed, however, that it would be a simple replacement of identified variables - no complex rules governing how variables might be combined, in fact, no business logic at all. This single use, one-way binding - something like the :: in Angular - allowed us to meet the security requirements while also maintaining our payload and performance budgets.

The challenge in this was making something general enough that it could handle any variable efficiently rather than be a string of replace commands. We were able to overcome this by using a feature of the JavaScript replace method that gets little attention - the ability to pass in a function in place of the substitution string.

When a function is passed to the replace method, the match of the regular expression (passed as the first argument in the call) is passed into the function. This allows the engineer to write a regular expression in which a key is wrapped in delimiters, passing the key into the substitution function. Once the substitution function has the key, it's a fairly simple matter of retrieving the variable from the dataset and returning it to the replace function where it's substituted for the original match.

This, of course, was all codified into a small library that looked something like this...
JavaScript
/** * @author H Robert King * @returns {object} * @param {object} config */ function PreProcessor(config) {   /**    * @property delimiters    * @description The start and stop delimiters identifying data elements. Strings are in    * Regular Expression format. Defaults to '<data>' and '<\\/data>'.    * @type {string[]}    */   this.delimiters = {    start: '<data>',    stop: '<\\/data>',   };   /**    * @method setData    * @description Sets the datastore    * @returns {undefined}    * @param {object} data    */   this.setData = function(data) {    dataset = data;   };   /**    * @method parse    * @description Parses a string, replacing data elements with values from the datastore    * @returns {string}    * @param {string} toParse    */   this.parse = function(toParse) {    var keys = Object.keys(dataset);    var parsed = toParse;    var property = '[."\'\\w\\s-_[\\]]+';    var match = new RegExp('(' + this.delimiters.start +    property +    this.delimiters.stop + ')', 'g');    var keyExp = new RegExp(this.delimiters.start +    '(' + property + ')' +    this.delimiters.stop);    if (keys.length) {    /* do the replace */    parsed = parsed.replace(match, function(element) {    var key = keyExp.exec(element)[1];    var path = key.split('.');    var val = dataset;    for (var i = 0; i < path.length; i += 1) {    var isElement = /([^[]+)\[["']?([\w\s-_]+)["']?\]/.exec(path[i]);    if (isElement) {    val = val[isElement[1]][isElement[2]];    } else {    val = val[path[i]];    }    }    return val;    });    }    return parsed;   };   var dataset = config.data;   this.delimiters = config.delimiters || this.delimiters;   return this; }


...and was called like this...
JavaScript
/* Set up the dataset */ var data = {   arr: {     values: [       { text: 'zero' },       { text: 'one' },       { text: 'two' },     ],   },   foo: {     value: 'the foo string',   },   bar: {     str: {       label: 'the bar string',     },   },   situation: 'snafu', }; data.hash = []; data.hash['one'] = { text: 'one' }; data.hash['two'] = { text: 'two' }; /* Create the preprocessor */ var preprocess = new PreProcessor({ data }); /* call the preprocessor */ var show = preprocess.parse('the value of array[1].text is   <data>arr.values[1].text</data>\n   the value of hash["one"].text is <data>hash["one"].text</data>\n   the value of foo is <data>foo.value</data>\n   the value of bar is <data>bar.str.label</data>\n   the value of situation is <data>situation</data>');


While I won't say that this comes up often - it's only come up once or twice at each of my gigs over the last 10 or 15 years - it does reappear with some regularity, so hopefully this is of some help to you when you're asked to do this sort of templating. As always, feel free to take the code and reuse or rework it - the same license is offered here as on my github account - which is basically do what you want with it. As always, I'd appreciate a shout out if you reuse it, but that's not a license requirement.

Happy coding.

Wednesday, September 27, 2017

A Simpler Slider Toggle

A few years ago I wrote an article about what I called a "slider toggle". Because it was written so long ago, and user-agents change pretty frequently, I wanted to revisit it to see if I could make it easier. In the original post, I gave two different orientations - one horizontal and the other vertical - but both using a single "round button" style. I won't be doing that in this post. In this post all versions are horizontally oriented; however, there are two styles - one a round button and one a rectangular version (with rounded corners).

Again, in HTML terms, these are stylized checkboxes, and the overall approach has not changed. The primary changes are in the CSS used to generate the different looks. I've also included, in this post, an approach that has the button labels inside the button as part of the background. To make this post as easy to understand as possible, I've grouped the markup, images of rendered code, and a demo together, and placed the CSS at the end. The CSS handles all the different styles - both round button (which is the default style) and rectangular button and with external labels, internal labels, and no labels.

☝ Note that the label tag wraps the entire element. This is to increase the size of the target and make the toggle button behave in keeping with the skeuomorphic design. To compensate for the fragmentation possible on some platforms (with regard to accessibility), the label tags have been given a role of text.

It's also important to note that the code provided uses an HTML checkbox rather than a different element and the checkbox or switch role. The ARIA checkbox and switch roles are widget roles, which will likely be treated differently than native HTML. It is likely an interface using a widget role will be less discoverable than a native element with no ARIA role specified.


External labels

This example uses labels outside the switch and is the pattern used in my original post. As mentioned in the earlier post, because the non-visual interface is a checkbox, the visual-only labels whose meaning is only proximity-based are hidden from accessibility devices.

HTML

<label for="push-mode" role="text">   Push Notifications   <span class="switch-label" aria-hidden="true">Off</span>   <span class="switch">     <input id="push-mode" type="checkbox" value="on">     <span></span>   </span>   <span class="switch-label" aria-hidden="true">On</span> </label> <label for="airplane-mode" role="text">   Airplane Mode   <span class="switch-label" aria-hidden="true">Off</span>   <span class="switch slider">     <input id="airplane-mode" type="checkbox" value="on">     <span></span>   </span>   <span class="switch-label" aria-hidden="true">On</span> </label>


Internal labels

This example uses labels inside the switch. It is not recommended due to the variance in text length.

HTML

<label for="location-mode" role="text">   Location Services   <span class="switch">     <span class="switch-label" aria-hidden="true">on</span>     <input id="location-mode" type="checkbox" value="on">     <span class="switch-label" aria-hidden="true">off</span>     <span></span>   </span> </label> <label for="email-mode" role="text">   Electronic communication   <span class="switch slider">     <span class="switch-label" aria-hidden="true">ON</span>     <input id="email-mode" type="checkbox" value="on">     <span class="switch-label" aria-hidden="true">OFF</span>     <span class="slider"></span>   </span> </label>


Longer text length makes buttons appear less like buttons as can be seen in the 'other alerts' and 'bluetooth' examples.

HTML

<label for="alert-mode" role="text">          Other Alerts   <span class="switch">     <span class="switch-label" aria-hidden="true">apagado</span>     <input id="alert-mode" type="checkbox" value="on">     <span class="switch-label" aria-hidden="true">encendido</span>     <span></span>   </span> </label> <label for="bluetooth-mode" role="text">   Bluetooth   <span class="switch slider">     <span class="switch-label" aria-hidden="true">apagado</span>     <input id="bluetooth-mode" type="checkbox" value="on">     <span class="switch-label" aria-hidden="true">encendido</span>     <span class="slider"></span>   </span> </label>


Unlabeled

This example does not use interior or exterior labels. It is not recommended due to the increase in cognitive load caused by the lack of those labels.

HTML

<label for="busy-mode" role="text">   Busy   <span class="switch">     <input id="busy-mode" type="checkbox" value="on">     <span></span>   </span> </label> <label for="dnd-mode" role="text">   Do Not Disturb   <span class="switch slider">     <input id="dnd-mode" type="checkbox" value="on">     <span></span>   </span> </label>


CSS

The CSS for these items is relatively simple. The rule for the label element is left out as it does not affect the switch.

CSS

.switch-label {   font-size: 0.5em; } .switch:before {   content: '';   display: inline-block; } .switch .switch-label {   display: table-cell;   padding: 0 0.5em;   text-align: center;   vertical-align: middle;   width: 50%; } .swtich .switch-label:after {   content: '';   display: block;   margin-top: 100%; } .switch {   background-color: rgb(255, 255, 255);   border: 1px solid rgb(0, 0, 0);   border-radius: 0.7rem 0.7rem 0.7rem 0.7rem;   box-shadow: 0 0 0.1rem 0.1rem rgb(187, 187, 187) inset;   cursor: pointer;   display: inline-table;   min-height: 1.2em;   min-width: 2.3em;   position: relative; } .switch * {   -webkit-touch-callout: none;   -webkit-user-select: none;   -moz-user-select: none;   -ms-user-select: none;   user-select: none; } .switch input[type="checkbox"] {   position: absolute;   z-index: -1; } .switch > span:last-of-type, .switch.slider > span:last-of-type {   background-image: linear-gradient(to bottom, rgb(255, 255, 255) 0%, rgb(153, 153, 153) 100%);   border: 1px solid rgb(0, 0, 0);   border-radius: 0.7rem 0.7rem 0.7rem 0.7rem;   display: table-cell; /*inline-block*/;   min-height: 90%;   position: absolute;   top: 0;   width: 50%;   z-index: 2; } .switch > input[type="checkbox"]:not(:checked) ~ span:last-of-type {   left: 0; } .switch > input[type="checkbox"]:checked ~ span:last-of-type {   right: 0; } .switch > input[type="checkbox"]:focus ~ span:last-of-type {   border: 1px solid rgba(204, 204, 204, 0.8);   box-shadow: 0 0 5px rgb(102, 102, 102); } .switch.slider {   border-radius: 0.2rem;   box-shadow: 0 0 0.1rem 0.1rem rgb(187, 187, 187) inset; } .switch.slider > span:last-of-type {   background-image: linear-gradient(to bottom, rgb(255, 255, 255) 0%, rgb(153, 153, 153) 100%);   border: 1px solid rgb(0, 0, 0);   border-radius: 0.2rem; } .switch.slider > input[type="checkbox"]:focus ~ span:last-of-type, .switch.slider:hover > span:last-of-type {   border: 1px solid rgba(204, 204, 204, 0.8);   box-shadow: 0 0 5px rgb(102, 102, 102); }


Although this may require a few tweaks, such as changing the colors to match your design, this should be ready for you to test in your page.

Happy coding