Identifying stuff in React: keys and refs

Use links below to save image.

One of the defining features of React is that it has the ability to avoid re-rendering the entire DOM whenever an individual component has been changed. To accomplish this, React needs to be able to reliably and consistently identify each individual component so that when a component changes, React is then able to isolate and re-render only that specific component. It also needs to be able to identify exactly which components are firing handlers or onChange methods, and see them as unique from the others around them, even if they were all generated dynamically from some ever-changing array in the back end. The ‘id’ and ‘class’ attributes won’t get the job done here. Let’s talk about ‘key’ and ‘ref’.

key

Image result for matrix key maker

Many of us just know the key attribute as “that thing you’re supposed to give to components when you generate those components from an array of objects.” But what is that attribute actually, and why is it important to set it when we generate components from iteration?

So as we know, React always needs to be able to uniquely identify every component on the page. And, as it turns out, it uses the ‘key’ attribute to do exactly that. No key attribute, no identification of individual components. No identification of individual components, no Virtual DOM. No Virtual DOM, no React.

“But David” you say. “I write components without the key attribute all the time. Surely React still works without every single component in the app having a key attribute.”

Nope. Thing is, whether you define a value for the key attribute or not, React gives a key attribute to every single component in the app. And the way it does it is by index – i.e., it’s place in position among its siblings that are nested at the same level in the HTML. Now, though that works enough to get the app running, it’s far from ideal. Let’s say you generate a list of components from an array. You work hard to carefully configure and style everything so that it’s just perfect. Then someone unshifts an object onto the beginning of your array on the backend, and the index of every generated component goes up by one. That’s why, when you generate a bunch of components without key values, React throws a warning. It’s not because the components have no key attributes – it’s because they have those attributes, and they’re set equal to their indexes, which is fragile and code smelly.

Some people don’t know this and get rid of the warning by iterating through their collection of objects and generating components where they manually set the key equal to ‘index.’ As we now know, that does nothing but repeat what React already does by default. It’ll get rid of the warning, but the problem React is telling us about is still there, so setting keys equal to indexes like this is a recognized anti-pattern.  It’s recommended that you use an id or some other unique property of your objects to reliably distinguish your components from each other.

ref

Use links below to save image.

Refs are a way to store a reference to a React element or component returned by the render( ) function, and make them accessible elsewhere in the component.

First. a warning – if you run into any tutorials that set the ref attribute to a string value and access the DOM node later from this.refs, you’re running into an old version of refs, which has been deprecated in favor of what we’ll be discussing today.

Second, another warning – the recommended use cases for refs are narrow. If you find that you’re using refs to handle all of your events and make a lot of things happen in your code, there’s a problem and you’re no longer doing declarative programming. Overuse of ref kind of flies in the face of Reactive programming, but it’s a good option to have on the table, and is often referred to as an ‘escape hatch.’ The only uses of ref that are recommended by the official React docs are 1) accessing the DOM API, 2) integrating 3rd-party libraries that are designed to hook into the DOM, and 3) imperatively triggering animations.

Alright, enough moping about what refs can’t do. We’re not defined by our limitations and neither are refs!

Image result for tony robbins

Tony Robbins is refs.

Seeing how refs are great for accessing DOM nodes, here’s a good example of a use case for refs: Say a user makes a mistake filling out a form, and we need her to re-enter some of the fields. We don’t want her to have to hunt all around the page looking for said field, so we decide that after she hits submit we want to immediately focus on the field where the problem is, saving the user some stress.

To accomplish this, we’ll need to access an input element using ref. Now again, once we do that, we could easily start abusing that reference by making use of it all over our code. Instead we’ll just call the focus( ) method on it. Let’s get started with an input tag and give it a ref attribute:

Use links below to save image.

As we can see, ref gets set equal to a callback function. The callback takes, as it’s input the tag (i.e. the DOM node) itself. It then creates a property on the component class called myInput and sets it equal to the node with the ref attribute. this.myInput can now be used anywhere in the component to  access that input element, and this.myInput.value could be used to get it’s value. Again, we do not want to use this reference to power the basic functionality of our app – that’s better left to state. But for our little use case, calling this.myInput.focus() is an awesome idea, and a perfect use of ref. Alright refs!

So hey, we’ll get back into our CSS discussion next week, but I think I might start writing more about React in the future – keep an eye out for more posts like this down the line!

 

Contextualizing CSS. Pt 1.

Sometimes we get so caught up in the syntax and minutiae of a language that we start missing the forest for the trees.

Image result for trees header

I mean, don’t get me wrong, you’ve definitely got to understand the trees. But if you never take a breath and step back for a bit, you’re inevitably gonna end up in a quagmire of confusion, superstition and fear. So that’s what we’re gonna be fighting, starting today – we’re going to be getting some perspective about CSS. This post is geared towards newbie/mid-level devs, and assumes that you’ve been learning CSS for at least a month or two.

First thing:

CSS is big.

This is important to understand. It’s easy to underestimate the size, scope and difficulty of CSS when you first get started in development. I mean, it’s just presentation, right? It’s surface stuff! Though it’s easy to get this impression from CSS off the bat, you only have to scratch the surface a teeny bit to learn otherwise. You know those O’Reilly programming books? The ones with pencil drawings of animals on the front? The CSS one is over a thousand pages:

Image result for definitive guide to css thick

The thing is, there’s always new stuff being added to CSS – it changes and grows every year, and it goes deep.

So what are all these changes? A  lot of it is imitating the stuff that the most popular CSS preprocessors and frameworks do. For examples, variables and grid systems were developed outside of vanilla CSS, but are now a part of it. If a tool becomes super popular and enough people ask for it, it might get added into CSS native, and could even end up  spelling the death of the tool that was the inspiration for it. Many people think that with the proliferation of CSS Grid and Flexbox, Bootstrap’s days are numbered. Of course, not everything from preprocessors and frameworks will find a home in native CSS – picturing functions and loops in standard CSS is a stretch. But nesting? Hey, who knows?

Who decides all this stuff, anyway?

The CSS specification is maintained by the Wordwide Web Consortium – basically the council of elders who decide everything about the standards for the core technologies that are used on the web.

Image result for world wide web consortium logo

Also, 4-time winner of the “Most Crushingly Dull Logo” Webby Award

So the W3C defines a bunch of standard related to the web, f.x. what is and is not official HTML and CSS. The CSS part is done by a subsection on the W3C called the CSS Working Group.

Image result for css working group

Neeeeeeerds.

 These fine folks are the ones who actually decided what CSS is. There are representatives from all the big web companies – Apple, Google, Mozilla, etc. They pay around 50 grand a year to have a seat at the table. There are also folks who are part of the group due to their stature in the CSS world and their contributions to the language. People like Bert Bos, who worked on the language in its infancy, are part of the group. I don’t know if he has to pay the 50 grand. Probably not.

So we know now that CSS is being changed all the time. How exactly does that happen? Well, the first thing we have to talk about is this:

Image result for css3

CSS3. As you might know, this is the current version of CSS – it’s what all the major browsers are running. What you are less likely to know is that this is the last version of CSS that we’re ever going to see. The change was made in 1999, and there has been no discussion of a new version. The reason why is that CSS is being broken up into modules, which are being improved independently of each other. And the different versions of these modules are not called versions, they are called levels. To get a look at the current state of affairs for all of these modules, take a look at the CSS Working Group ‘current work’ page.

Once the CSS Working Group makes a decision about something, the browsers have the responsibility to start adopting the new rules and conforming to the specification. They generally all do this pretty quickly, except for Internet Explorer. Everyone makes fun of them and you should feel free too, as well. You can see how a given CSS property is supported by different browsers at caniuse.com. Here’s an example of a support table for CSS Grid. This is very out of date, by the way – it’s way more supported by now:

Image result for caniuse grid

Wow, IE actually did pretty well this time around. How about that. 

Browser Schenanigans

One thing we need to touch on is the fact that browsers aren’t simply neutral middlemen that just render our code exactly the way the W3C says to in the spec. A bunch of the default CSS you are used to seeing when you write code is not part of the official CSS spec at all, but is rather defined by the browsers. By the way, browsers in this context are referred to as ‘user agents,’ and every user agent has a ‘User Agent Stylesheet.’ This refers to all the styles that the browser throws into our CSS on top of the definitions that the CSS Working Group lays out. These rules are things like making h1s bigger than h2s and putting confusing default margins on stuff. Here’s a piece of the Chrome User Agent Stylesheet:

chrome_uas

That screenshot comes via John Meiert’s awesome collection of User Agent Stylesheets. By and large, the styles the browser adds into our CSS at the very least kind of makes sense, and are useful for getting us thinking in terms of proper semantic HTML. But they can also kind of get in the way, and confuse us about where certain styles are coming from. As such, you may want to reach for a CSS reset. This is a big chunk of CSS that basically just resets everything to zero – turns off default margins, makes everything the same size, stops links from turning all blue and underlined and whatnot. You can write your own, of course, but grabbing one from someone’s blog is pretty darn convenient. Some resets are more drastic than others, google around until you find whatever you’re looking for. Here’s an example of what a piece of one might look like:

Image result for css reset

And that’s it for today! Next week we’ll talk about the wonderful world of CSS tools and extensions – preprocessors, frameworks, grid systems, you name it! Thanks for reading!

The Wild and Wonderful World of Static HTML Site Generators

Image result for generator

It’s a generator. You get it.

 

You ever hear a song at a party for the first time and you’re like “Man, I kinda like this song” and then you hear someone else go “Woah, retrooooo! I feel like I’m back in middle school!” and you’re like what this song is new to me.

That’s how I feel about Static HTML Site Generators. Or, to be, more accurate, that’s how I feel about the

(TM)

That’s the sort of language I’ve been hearing around HTML generators and static pages for a while now, so hey, there’s probably something to it. What are HTML generators, what are the use cases for them, and why are they becoming so popular? Let’s find out!

Review –  What Defines a Static Webpage?

If  you started programming within the last five years, odds are that you remember static webpages as something you did for the first five minutes of your bootcamp before moving onto dynamic pages and writing static off forever as something archaic to laugh at from the comfort of the future, like we do at Michael Douglas’ cellphone in Wall Street.

‘Static’ has a meaning in development besides just ‘old.’ There are 50 different definitions to distinguish between static and dynamic, but by and large the difference is that dynamic pages actually generate new HTML all on their own based on changes to their database, while static sites serve up the same HTML each time, and don’t even have a database. In short, static sites don’t have a backend. Keep this in mind – it does NOT have anything to do with animation, movement on the page, Javascript, or the lack thereof. Again, static sites can include Javascript. That’s important.

So why use static?

The thing is, dynamic web pages are super cool – they give us online shopping and user accounts and personalized content and all sorts of nifty stuff. The most magical things on the internet are done through dynamic websites and apps. BUT. Static sites are faster than dynamic sites. Much faster. You ever load a plain html file in your browser? It feels like lifting a box that you thought was pull of old kettlebells but turned out to be empty – it’s disorienting how easy it is, how quickly the page loads. And it’s way more secure. Dynamic apps, with all their forms and whatnot, have a much larger attack surface for anyone trying to hack your site.

When to use static

“But David” I hear you say. “Static web sites sound so boring. I didn’t get into development to make GeoCities sites. I want to make beautiful, exciting websites, and thinking about sticking to static makes me want to commit seppuku.” I totally understand. The interaction between users and data is a beautiful thing . But you know what else is beautiful? Single-page marketing sites with pictures, text, a ‘contact’ box and that’s it.

http://vibrant.pratheev.com/

If you’re coming from a very backend-y development education, this might not be something you focused on a lot in your education; it’s easy to hear ‘static site’ and think ‘mid-90s’, but the truth is that the people making static pages are also the people at the very forefront of pushing CSS and aesthetics in web pages to their limits.

http://portalplus.omnifi.co.uk/

Another place that devs have gotten a lot of use out of static HTML sites is as blogs, portfolios, and personal sites for themselves and for clients. Let’s be honest, do you really need a comments section on your blog? Why? So strangers can tell you that you need to learn Haskell? Come on.

Static Site Generators

Okay, so we’ve established that static web pages have the potential to be jaw-droppingly gorgeous, faster and more secure than their dynamic cousins. So what’s the problem? Just write some HTML and some CSS, throw in a bit of JS, and let’s party!

Except, as it turns out, that sucks. You write a page, you finish it, then you realize that you want to use a similar page somewhere else in your app, and that you have to copy-paste it. You do this a couple more times and before you know what happened, your code has exploded. You realize that you don’t like static sites anymore. You miss React. You start crying and ripping up your “I Heart Static Websites” t-shirt.

There, there. It’ll be okay! Know why? Because we have static site generators! Basically, what these generators do is make creating a bunch of static HTML easier without giving us an entire programming language. And boy are there lots of these things. We’ll look at a few today, but there are a bajillion of them, so feel free to explore to your heart’s delight!

Jekyll

Probably the most well known option, Jekyll is built on Ruby and geared towards blogging. Many Rails devs love it as a nice lightweight way to write a blog with all the customization that CMSes deny them, but with a nifty Templating Engine called Liquid that lets them do stuff like loop through all of their blog post files and add the files’ markup to the blog index file.

Gatsby

Gastby

Gatsby is the generator that sucked me into this rabbit hole to start with. Gatsby is a static site generator for React. What this means is that it takes Javascript files that contain React components and generates totally static HTML, CSS and JS from them. The reason this is such a big deal is that we can now make use of reusable React components on our site and move past the problem that made us cry earlier. Every ability that React gives us is now available to us, without having to pay the price of a bulky front end – everything’s static.

Conclusion

Static site generators are available for nearly every major language –  Node has Hexo, Google Go has Hugo, Python has Pelican. They generally give you a file system of some sort to start with, a place to add content (HTML), a place to specify styles(CSS), a place to create the rules of how your site gets generated(language depends on the generator), and a build tool (usually some specific command in terminal). When you run the build tool, it spits out a directory of HTML, CSS, JS and images, ready for hosting, no database or anything needed.

Particularly if you’re planning to work at an agency, there’s a high likelihood that you’re going to be doing these sorts of stylish, lightweight builds, and that you’re going to be doing them often. Invest some time in learning a static generator or two. Rebuild your personal site using it! And have fun!

Adventures in the JS Concurrency Model

Once in a while, you’ll hear a word or phrase that, if you look it up, reveals a whole new world to you. Examples include Bo-Taoshi, Flat Earth, and Battlebots. The most recent example for me was “Javascript Event Loop.” The event loop itself isn’t terribly complicated, but understanding it requires understanding basically the entire context within which Javascript gets run. So that’s what we’re learning about today! Let’s go!

Javascript differs from complied languages in that it needs a container within which to run. The container can be a browser like Chrome, or a server-side runtime like Node.js. This container splits into two parts – the engine and the runtime.

Engines

Image result for rusty engine

The job of a Javascript Engine is to compile our JS code down into a lower-level language, usually C or C++. Each of the most popular browsers in the world has its own engine which competes with the others. Chrome uses V8, Firefox uses Spidermonkey, IE uses Chakra and Safari uses JavaScriptCore. Incidentally, Spidermonkey was the first JS engine ever built, and I have to say, I think it’s pretty cool that 12 updates later it’s still in use. These engines all compile to C++, except for JavaScriptCore, which compiles to Objective-C.

Runtime Environments

Image result for web apis

The other part of the container for our JS is our runtime environment. Essentially, the job of the runtime is to provide us with JS objects and APIs that are useful and relevant to the work we might want to do in that particular context. People are often surprised by how much of the Javascript they write is not provided by the language itself, but by the runtime of the container they are using, be it a browser, Node or something else entirely. Here are some examples of functions that are provided by browsers and not the core JS language: document, XMLHttpRequest and setTimout. Again, these functions are not provided by the core Javascript language itself, but rather the runtime of whatever container wraps it.

Moving on…

As you probably know, JS is single-threaded, meaning it can only do one thing at a time. I think most of us have experienced the cognitive dissonance of holding that in mind while we somehow go ahead and do asynchronous programming anyway. The reason it’s possible is that our JS code doesn’t do all of that async stuff – our container does, which in most cases means our browser. Runtimes and the tools they provide are very context-dependent. For example, Chrome and Node.js both use the V8 engine, but while the Chrome runtime gives us access to the DOM and the window object, the Node runtime gives us require and Process. This is because Chrome, a browser, has different needs from Node, a server-side environment. So though the core language and engines are the same, the runtime environment is different, and provides different APIs.

The CallStack

You’ve probably seen the callstack in your browser’s debugger, but the details of how it works may yet elude you. In the broadest terms, the callstack shows us where we are in the execution of our program. It displays a list of callbacks, but when we look at them in the callstack, we refer to them as frames. The earlier a frame was called, the closer to the bottom of the stack it is. Every frame was  called by the one below it, except of course for the one at the very bottom. When a function on the top of the stack returns (i.e. completes), it pops off the top of the stack, leaving the one underneath is to either finish as and pop off as well or make another function call, adding a frame to the top of the stack. This goes on until the bottom frame completes and the stack clears.

Now. With async functions, it gets a little trickier. Let’s say we have an AJAX get request in our code. If it just ran in our normal code, it would block up our callstack while everything else waited for it to complete. Even mouse clicks and scroll actions would be blocked, added to a que of actions that would only affect the page once the AJAX request was complete. So these kinds of callbacks aren’t going to be part of the normal callstack. Instead, they get sent to the container’s runtime, and its web APIs assume responsibility for those async actions while the main JS code just continues on its merry way. Woohoo! Unblocked!

Okay, we sent our AJAX request through and now it’s finished! Huzzah! Okay so now what happens to the remainder of our function? Our call stack is busy with stuff, we can’t just cram it back in there all haphazard-like. No, the remainder of our async function goes to the message que.

The message que is like the waiting list to get into the callstack area. I’m calling it ‘the callstack area’ and not just ‘the callstack’ because it’s important to remember that a function can’t get into the middle or top of a callstack without being called by another function. Every frame in the callstack is being called by the frame below it, except of course the bottom frame. None of the functions in our message que will be added to an existing callstack – they’re going to start new ones. The message que is just a bunch of callbacks waiting to be the new bottom frame of the callstack.

The process that powers the movement of functions from the message cue into the callstack is called the Event Loop. The Event Loop is simply a while loop that says “While the callstack is empty, add the oldest function in the message que to the callstack as the bottom-most frame.” And thus async JS can work without blocking, and we come full circle.

Let’s take a look at a visual, courtesy of Assem Raj Baranwal to tie this all together. One part of this chart we did not discuss is called the ‘heap’ – this basically just refers to the place in our engine’s memory where our JS objects get stored. Don’t worry your little noggins too much about it this time around, we’re really just focusing on the Callstack/Message Que flow today.

Image result for js concurrency model

One thing that’s a little hard to see here is what happens when your program runs callbacks that are not Web APIs provided by the container. Do they go straight to the callstack? Nope, they just get in line at the Message Que. Any callback that fires from a click, scroll or mouse move event goes into the message que, right next to the async stuff.

So that’s the JS Concurrency Model! Fun, right? I highly suggest taking a look at Phillip Roberts’ talk about it as well. My favorite part was when we learned that XHR was just a Web API provided by browsers! This whole time! Let’s use this knowledge as a springboard to talk about more complex backend JS stuff in the future. See you next week!

Code Challenge Retrospectives: React on Rails Chatroom

Recently, I’ve started doing personal projects a little differently. I’ve realized that I learn much quicker and get more done when my time to complete a project is limited. As such, I’ve started putting limits on the number of hours I can spend working on any given personal project. This approach pushes me to work faster, forces me to make decisions on how to fail gracefully,  and gives me practice with timeline estimation, a vital skill in the industry. Note that the hours do not have to be consecutive, but they are carefully logged on Github to make sure I don’t exceed them. I generally work three hours at a time.

The week before last, I gave myself the job of creating, in six hours, a sliding-tile puzzle that uses open access hi-res photos of art from the Met. It was tough, but a success. This last week I tried to push myself further, by attempting to create a React on Rails chatroom for the first time within nine hours. (Don’t expect too much from that link.) Most of what I did get done followed this tutorial. I wish I could have failed gracefully and created a blogging platform or something when it became clear that I couldn’t pull off the chat room in nine hours, but I couldn’t change direction in time and it was essentially a flop. However, I learned an absolutely insane amount about Rails technologies that I had zero exposure to before, including Decorators, Action Cable, Active Job and the react-rails gem (I had just used Rails APIs that talk to separate React front-ends up until now). It was also a great example of when to use serializers, and a very solid review of how to do so. In this post, I’ll be documenting the things I learned, the new subject matters I broached, and how I understand them at this point.

Decorators

I’d heard the term ‘Decorator’ thrown around before this week, but it was a very vague concept in my head. I think it’s pretty understandable that I thought that decorators had something to do with styling and CSS. As it turns out, decorators are a design pattern.

The Decorator design pattern lets you give an object a behavior without changing the class that it’s an instance of. Usually, something like this would be done by creating a subclass, but if you keep doing this you can end up with way more subclasses than you want, and on top of that you may need to create even more subclasses that are combinations of the previous subclasses to give a particular object all the behaviors you want. Ex: Bike, BikeWithBell, BikeWithLights, BikeWithBellAndLights, BikeWithBasket, BikeWithBellAndBasket, BikeWithBellLightsAndBasket, etc…. Any small amount of complexity in terms of custom object abilities can result in an explosion of subclasses, generating lots of code, and leading to confusion.

Decorators are an alternative. Think of them as as a wrapper for our objects that temporarily give them extra methods. There are a few different ways to implement decorators in Rails, but this time around I used the ‘draper’ gem.

Image result for don draper

I suspect that the name comes from the visual of ‘draping’ the decorator around an object. Once you install the gem, you can generate decorators from the command line, and they appear in a new directory: ‘app > decorators’.

Here is an example of a decorator:

class ArticleDecorator < Draper::Decorator
delegate_all

def published_at
object.published_at.strftime(“%A, %B %e”)
end
end

There are many ways you can now use this decorator. You can fetch an object from the database, enhanced with the published_at method:

@article = ArticleDecorator.decorate(Article.first)

…or you can create a new object with said enhancements, or you can fetch the full collections of all Article objects, with the published_at method now available for each. Decorators are super flexible and the sky’s the limit!

Action Cable

Action Cable was released with Rails 5 in July 2016. It’s the push by the Rails to integrate Websockets with the rest of the framework. Websocket is a protocol, standardized in 2011 and built on top of TCP/IP. It’s purpose is to facilitate real-time data transfer (streaming) between a server and client. This is made possible in part by the client not being required to send a request to the server in order to receive content. Information can be sent continuously between server and client while keeping communication constantly open. Action Cable is the integration of this protocol into Rails.

Action Cable comes in two parts: server-side and client-side. It exposes an API on the back end, written in Ruby, and one on the front-end, written in Javascript. Pretty wild, I don’t know of any other place where Rails exposes a JS API. Please let me know if you’re  aware of another example of that! Action Cable is a huge topic in its own right, and I’ll go further into detail about it another week.

Active Job

Active Job is a framework for declaring jobs. What we mean by ‘jobs’ is asynchronous background tasks. What callbacks and promises handle in Javascript, jobs handle in Rails. They are defined in the Jobs directory as classes that inherit from ApplicationJob. Their primary method is ‘perform’, which details what they ought to do when they are run. Once they are defined, they can be added to the queue of background processes from the controller.

The react-rails gem

Up to this point in my React on Rails adventures, I’d been keeping the two Rs largely separate from each other. I would fire up a rails API that would provide JSON endpoints for a React frontend generated with create-react-app. Though I might keep them in the same directory, I really just had two apps that didn’t know anything about the other’s existence. The react-rails gem is very different, and brings a much closer coupling to the two technologies. Once the gem is installed, we can generate new React components from terminal, and we can give Rails views access to them with the react_component method. It’s a lot of fun to work with, and I’ll probably use it much more in the future!

Conclusion

I learned a ton from this project. I’m going to try to start working more with all of these technologies, Action Cable in particular. The possibilities are crazy, my dream is to get a video chat up and running. It’ll be a little while before I start messing with that, but it’s fun to think about. Woo Rails!

Don’t Forget Design! (Pt. 3)

Time for more design features! Woot!

Photo Realism 

The simplest implementation of this is the practice of giving the site a high-res photograph as a background, and mapping links to different coordinates on the page.

More advanced examples of photorealism include visually impressive bits of UI that are made up to look like objects.

Image result for cupcuff website

Icons

Though icons seem like an afterthought, they have become a major part of every site on the web now, and are often used as a central design feature.

The following are the standard social media icons. These are the standard versions, but they show up in several different flavors and colors. Take a look at the social media icons up in the CupCuff website for an example.

Image result for social media icons

There are plenty of places for more generic icons, however, which can serve as a much better version of bullet points. Several icons have animations that can be set to play on mouse-rollover or scroll-down. The effect can look great, in a way that doesn’t even hint to the average user that you are using generic icons.

Image result for icon gifs

Guided Navigation

This is the term that I give to designing your site so that the user is guided in a certain direction, especially if that user is visiting for the first time. If you know what the majority of your users will be coming to your site to do, this is a good way to design your landing page. For example, the designers of the Bootstrap page know that most of the people coming to the page will be coming to download Bootstrap:

Image result for bootstrap website

This approach can also be useful if you want to elicit a certain response from visitors. Putting a giant login button front and center isn’t going to bring Netflix any extra revenue, but putting such a button aimed at first-time visitors might do just that:

Image result for netflix landing page

Tiles

Basically, make your website look like Windows 8. Or Pinterest. It can be accomplished through pure CSS, or a framework like bootstrap. It can be kind of jumbled together is a sort of on-purpose random way, or much more consistent.

Image result for tiles web design

Image result for tiles web design

And we’re done! Yay, design features!

Don’t Forget Design! (pt. 2)

In the last post we talked about a few different styles we can use to anchor our website, and ground it in a visual philosophy that makes the page as a whole make sense. Today we’re going to get a bit more specific about what sort of elements and design patterns we can use on our web page, not just the general feel and style we want them to have. These will be the things on out page that make it functional, and give the user an interface to change navigate the page and change the information she’s looking at.

Explicit Nav Menus

Here we see possibly the most traditional tool for users to move around a webpage – the navbar. In the above example, notice that we also have a sidebar. What a developer decides to put in these types of nav elements is up to him. Some devs like to have single link that the user is allowed to visit in one nav, and others like to spread them between a navbar and siderbar, and maybe throw a few others down in the footer for good measure. If or how you use it is up to you. Users are generally comfortable with this kind of navigation and know how to use it, but it has the side effect of making your site look busier and more cluttered.

Hidden Nav Menus

That last problem can be addressed by hidden, expandable, ‘hamburger’ menus. Especially since the rise of bootstrap, these types of menus have become extremely popular for their ability to provide the best of both worlds: an uncluttered page upon the user’s arrival, with the option to see much more if desired. For the most part, these menus have just opened into drop-down lists, but devs are quickly realizing that they can use those little hamburgers to prompt the appearance of any kind of menu they like.

Image result for hamburger menu gif

I found the preceding bit of CSS and many others like it at this website.

Headers and Footers

Headers are pretty simple. You can throw a brand name in there, maybe something about the status of the user (logged in status, shopping cart status, etc) and a navbar. The footer can help to reduce clutter by providing a place to hide away all the stuff the average user doesn’t really need to be bothered with – copyright information, careers, about page, social media links, etc. The size of the footer will depend on the website, and the degree to which you want the page above the fold to be free of excess links.

Single page scroll

One way to make building a website much easier and still make it beautiful is to make is a Single Page Scroll site. Just by continuously scrolling down, users experience all of the content you want them to, in the order you want them to. This also opens the door for lots of nifty features, like navbars that stick to the top of the screen while you scroll, populated with links that auto-scroll you to the right place on the page. Scroll-sensitive animations can be included in the page that fire as you slide further down the page. Backgrounds can change as you scroll with the use of CSS sprites, and some of the most beautiful sites built today are built around this feature.

Transparency

A variation on Single Page Scroll, a Transparency results in text on a translucent background sliding over a stationary background as the user scrolls down. The effect can be striking as demonstrated if done correctly, and it can be employed in several different ways. Sometimes just a touch of a stationary background in an otherwise normal Single Page Scroll app can make the whole thing seem more professional. A touch of the technique can be seen here.

Conclusion

I’m having a great time, aren’t you!?! There are so many wonderful features to use in web design! Let’s take a break and we’ll come back for a few more to wrap up our design series in part 3!

 

Don’t forget design! (Pt. 1)

beAs a developer, it’s easy to get a little bit too sucked into backend stuff sometimes, to the point that when you have to build an interface, the result looks like a geocities site with random bootstrap buttons thrown in among a hodgepodge of weird colors and goofy-looking navigation. You know CSS really well, you know how to use a grid system… why does this look so terrible?

Oh yeah. You’ve forgotten design.

It’s easy to forget how hard design can without templates, and sometimes it’s hard for engineers to get started figuring out the ‘feel’ or ‘theme’ of something they would really just like to be functional.

Silicon_Valley_design_concept_meeting

But neglecting those aspects is really not an option. Even quite sparse sites like Reddit and Wikipedia make an effort to create consistent, cohesive interfaces with very deliberately chosen fonts and layouts that feel natural and professional. Even a site with important content and impressive back-end tech will fail if it looks like it was designed by a fourth-grader learning HTML for the first time.

So. Where do we start? In my opinion, the best way to divide up the huge topic of web design is into two subtopics – ‘Styles’ and ‘Features.’ When we talk about styles, we’re playing with very broad, high-level, design-y concepts, trends and movements that bleed out of web design into fields like print, graphic design, art and architecture. When we talk about Features, we’re talking about specific components used in web design. This week, let’s just take a look at three Styles and then next week we’ll check out three Features to get us started thinking in a more design-oriented way.

Styles

The Style of your website should be clear in your head before you touch a single CSS file or build anything stylistic at all. The thing that makes a website look professional is consistency of theme, and that will be determined by the style. Let’s take a look at a few styles:

International Typographic Style / Swiss Modern

Image result for international typographic style

By the way, this post will have a lot of pictures. Also, I recommend google imaging these style names to get an even better idea of them.

If you’ve ever spent a lot of time in Europe, this look will be familiar to you. Legibility, negative space, clean lines and lots of Helvetica. If you look at a signpost somewhere and see nothing but information, that’s Swiss Modern. Websites using this style will tend to use ‘hamburger’ menus to free up the page of any little bit of clutter, as in the following example.

burnkit

In International Typographic, leaving things out is just as important as putting them in. Limited options and and the use of a single bold color (often red) are common in this style.

Genelab

Retro

Let’s face it. We live in the future. And as cool as that is, it comes along with a nice dose of existential dread. I mean that site up there in the Swiss style has me thinking about my insignificance AND my clone-ability.

Oof. You know what I need? A nice, solid dose of nostalgia.

Image result for retro ad

To be clear, the above isn’t technically a retro style, since it’s not trying to be old-fashioned on purpose, it’s ACTUALLY from the past. Nonetheless, it’s a good example of a design aesthetic that’s fun and pretty easy to implement in a page. You can find tons of components in photoshop or any other piece of graphic design software that will fit right into such a theme:

Image result for retro graphic

I should point out that this style is not appropriate for every situation – you don’t want the launch site for a new phone to be surrounded by imagery from the 50s, you would rather have such a product associated with the future. Where it does work well is when you’re selling a simple product, a link to the past is okay, and you’re able to have a bit of a sense of humor about yourself.

Grunge

The term ‘Grunge’ has its origins in the music of the 90s, but as a style it’s grown to refer to anything grimy and hardcore. It’s pretty straightforward, really – rebellion, chaos, dirt.

Image result for grunge graphic design

Websites in this style clearly identify as at least somewhat counter-cultural and may willingly sacrifice ease of use to achieve it.

Matt Mullenweg

The style can end up being much more difficult to work with than others, as there is often an attempt to get from the grid system. For example, slanted menus are common in the grunge style, an impossibility for normal HTML. This means that image mapping must be used for links, which breaks between different browsers. In short, it’s a risky style. But hey, isn’t that always the case with being on the fringe? Nonetheless, if you can pull it off, I think the results can be pretty cool.

iSpoil

So that’s it for styles. The vocabulary for talking about design varies a lot from person to person, so find a way to break it down that works for you. Next week we’ll talk about some of the actual features we can use in our website after we’ve chosen a style to go with.

Customized Styling for Devise Authentication Elements

As we all know, authentication can be tricky. Session persistence, encryption, third-party authentication, password resets…. there’s a lot to handle, and the stakes for screwing it up are high. Unless you consider yourself a specialist in authentication, it’s often best to eat a slice of humble pie and look at what the pros have made available to us.

When it comes to authenticating Ruby apps, that means using our old friend Devise. Devise gives options for nearly anything we could imagine having in a login/signup form.

Okay. We’ve installed the Devise gem and used rails g devise user to generate, behind the scenes, a database migration, model and series of views for users. We’ve migrated and we’ve thrown our Devise authenticate_user! method into a few places in our controller so that our users are asked to login if they haven’t yet. Cool! So for all intents and purposes now, we have authentication.

One problem, though : it looks all janky. The login form doesn’t fit into the style of the rest of the app.

So how do we style this thing? We can’t seem to find the file anywhere. Where are the view files for Devise elements?

They’re hidden. O.O

Devise keeps all of its generated files invisible by default. But we can expose them! Or, technically, we can copy them and make the copies the official one that gets used. It’s easy as pie.

rails g devise:views users

Boop! If we look in our views directory we’ll notice that Santa came early this year and he brought us a box full of CONTROL!

Over our Devise elements, I mean. If we open up the devise directory, we’ll see seven different directories. We’ll focus on three. sessions contains our login form, and registrations contains our new user form. Both of these forms are style-able with classes or ids just like anything we made ourselves. One thing that may bug you once you start playing with them is that changing the background of a form doesn’t change the form of everything that’s generated. First, move the heading inside the form element. Then take a look at the links that we pull in from the shared subfolder in the devise directory. This nifty file contains all the links to reset passwords, login with social media, etc. Just move the render up into the form element.

Boom! Everything’s contained in one unit now. Add a class or id to the form element and edit the main css file for your app to make them look how you like. I recommend giving the form width: 200px so that if you want to give it a custom background, it doesn’t look like it’s stretching across the page. If you’re feeling less custom-y and more boostrap-y, use the grid system to achieve the same effect!

 

Asynchronous Javascript for Beginners (pt. 3)

In this post we’ll discuss how asynchronous code has been dealt with up until the last few years. Namely, callbacks. Let’s start with the most basic example we have, a setTimeout call:

setTimeout(function(){ console.log(“Hello”); }, 3000);

As we’ve discussed, setTimeout is asynchronous. And so here it takes a callback function. What setTimeout does is calculate where in the process que it can slide that callback in that will occur AT LEAST three seconds later.

Now we have to take a quick break here because something is rearing its head already which, if we don’t take care of it, will lead to confusion. You might have heard that javascript is single-threaded. That only one process can be happening at any one time. Well if that’s the case, how can we have async at all? Isn’t that what asyc is, things happening at the same time? The answer is…well….. almost. But not quite! Your computer that you’re running right now is capable of truly running multiple processes at the same time, what we refer to as things running in parallel (as opposed to async). That’s how your machines can handle dozens of apps being open at the same time, all while handling tons of other processes behind the scenes that you never even see. Your computer is capable of running thousands of threads all at once! Pretty amazing, huh?

Well, don’t get too excited, because we don’t get to have those threads in our JS app. We get one. Javascript engines are single-threaded, meaning that we can only do one thing. At a time. So with this information on board, what is async in this new context?

It’s a trick. It’s a way of making your application SEEM likes it’s multi-threaded, even though it’s not. The reason we do this is for user experience.  If users see that SOMETHING is happening, it’s a lot easier to wait than if their screen just freezes for ten seconds, the result of allowing blocking processes in your app. So let’s get back to the main topic: callbacks and the problems they created. Let’s look at a simple AJAX request made with jQuery:

$.get( "ajax/test.html", function( data ) {
alert( "Load was performed." );
});
Pretty simple. Readable, easy to reason about. The problem is, what you wanted to do with a request usually wasn’t this easy. And when things got more complicated, you ended up with callback after callback, in a tangled maze that has come to be known as callback hell. Here is an example, taken from callbackhell.com :

fs.readdir(source, function (err, files) {
  if (err) {
    console.log('Error finding files: ' + err)
  } else {
    files.forEach(function (filename, fileIndex) {
      console.log(filename)
      gm(source + filename).size(function (err, values) {
        if (err) {
          console.log('Error identifying file size: ' + err)
        } else {
          console.log(filename + ' : ' + values)
          aspect = (values.width / values.height)
          widths.forEach(function (width, widthIndex) {
            height = Math.round(width / aspect)
            console.log('resizing ' + filename + 'to ' + height + 'x' + height)
            this.resize(width, height).write(dest + 'w' + width + '_' + filename, function(err) {
              if (err) console.log('Error writing file: ' + err)
            })
          }.bind(this))
        }
      })
    })
  }
})
The characteristic shape of this type of code came to be known as the pyramid of doom. However, even if the callbacks were extracted out into separate, external functions, we would find that it is still hard to reason about and that callback hell goes deeper than nesting and indentation. In the next post, we will explore those problems, and the solutions that were devised.