book – CSS-Tricks https://css-tricks.com Tips, Tricks, and Techniques on using Cascading Style Sheets. Wed, 31 Jul 2024 21:25:41 +0000 en-US hourly 1 https://wordpress.org/?v=6.6.1 https://i0.wp.com/css-tricks.com/wp-content/uploads/2021/07/star.png?fit=32%2C32&ssl=1 book – CSS-Tricks https://css-tricks.com 32 32 45537868 Where You Can Still Get A Book Apart Titles https://css-tricks.com/where-you-can-still-get-a-book-apart-titles/ https://css-tricks.com/where-you-can-still-get-a-book-apart-titles/#comments Wed, 31 Jul 2024 14:52:44 +0000 https://css-tricks.com/?p=379392 It’s been a few months out since A Book Apart closed shop. I’m sad about it, of course. You probably are, too, if you have one of their many brightly-colored paperbacks sitting on a bookshelf strategically placed as a backdrop …


Where You Can Still Get A Book Apart Titles originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
It’s been a few months out since A Book Apart closed shop. I’m sad about it, of course. You probably are, too, if you have one of their many brightly-colored paperbacks sitting on a bookshelf strategically placed as a backdrop for your video calls.

It looked for a bit like the books would still be available for purchase through third-party distributors who could print them on demand or whatever. And then a redaction on A Book Apart’s original announcement:

UPDATE: Ownership and publishing rights for all books have been given back to their respective authors. Many authors are continuing to offer their work for free or in new editions. Our hope is that these books will continue to live on forever. A Book Apart no longer sells or distributes books, please reach out to authors for information about availability.

Oh, snap. The books are on the loose and several authors are making sure they’re still available. Eric Meyer, for example, says he and co-author Sara Wachter-Boettcher still figuring out what’s next for their Design for Real Life title:

One of the things Sara and I have decided to do is to eventually put the entire text online for free, as a booksite. That isn’t ready yet, but it should be coming somewhere down the road.

In the meantime, we’ve decided to cut the price of print and e-book copies available through Ingram. [Design for Real Life] was the eighteenth book [A Book Apart] put out, so we’ve decided to make the price of both the print and e-book $18, regardless of whether those dollars are American, Canadian, or Australian.

Ethan Marcotte has followed suit by listing his three titles on his personal website and linking up where they can be purchased at a generous discount off the original price tag, including his latest, You Deserve a Tech Union.

Others have quickly responded with free online versions of their books. Mat Marquis has offered JavaScript for Web Designers free online for a long time. He helped Chris Coyier do the same with Practical SVG this past week. Jeremy Keith put out one of my personal ABA faves (and the first ever ABA-published book) for free, HTML5 for Web Designers.

What about all the other titles? I dunno. A Book Apart simply doesn’t sell or distribute them anymore. Rachel McConnell sells Leading Content Design directly. Every other book I checked seems to be a link back to A Book Apart. We’ll have to see where the proverbial dust settles. The authors now hold all the rights to their works and may or may not decide to re-offer them. Meanwhile, many of the titles are listed in places like Goodreads, Amazon, Barnes & Noble, etc.

A couple of folks have even started tracking the books on their personal sites, like Ryan Trimble and Alan Dalton. (Thanks for the tip, Chris!)

Thanks for all the great reads and years, A Book Apart! You’ve helped man, many people become better web citizens, present company included.


Where You Can Still Get A Book Apart Titles originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
https://css-tricks.com/where-you-can-still-get-a-book-apart-titles/feed/ 3 379392
Great (and Free!) Web Development Books You Can Get Online https://css-tricks.com/web-development-books-you-can-get-for-free/ https://css-tricks.com/web-development-books-you-can-get-for-free/#comments Mon, 27 Jun 2022 13:27:49 +0000 https://css-tricks.com/?p=366468 Right after “Where is the best place to learn?” perhaps the most commonly asked question I hear from folks getting into code is “What web development books should I get to learn?” Well, consider this an answer to that question …


Great (and Free!) Web Development Books You Can Get Online originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
Right after “Where is the best place to learn?” perhaps the most commonly asked question I hear from folks getting into code is “What web development books should I get to learn?” Well, consider this an answer to that question as I’ve curated a list of books that are not only great for getting into front-end development but also freely available.

Books on CSS

This is the bulk of where we’re going to hang out because, well, this is a site mostly about CSS!

The Magic of CSS by Adam Schwartz

  • Perfect for: Next steps in your CSS journey
  • Learning level: Intermediate
  • Requires: Some basic understanding of CSS

Adam Schwartz covers six CSS concepts in this book, including the box model, layout, tables, color, typography, and transitions. These are things even stump some seasoned CSSers, some of these concepts might be confusing. Adam has gone to a great length to demystify each.

In addition to the book being a great primer on complex CSS concepts, I love how each of the CSS properties mentioned throughout the book is clickable so you can always click on them to see how each is applied. There are many illustrative examples and recommendations for further reading, should you desire to learn more about each chapter.

I found the chapter on colors very interesting not only because it gets into the best practices for using color accessibly, but also because there’s super practical applications, like when Adam gets into using CSS to support an organization’s branding.

Resilient Web Design by Jeremy Keith

  • Perfect for: Developing strategies for writing code
  • Learning level: Intermediate
  • Requires: Some basic understanding of CSS

Straight from the introduction:

You won’t find any code in here to help you build better websites. But you will find ideas and approaches. Ideas are more resilient than code. I’ve tried to combine the most resilient ideas from the history of web design into an approach for building the websites of the future.

What Jeremy does so well is describing soft skills, like planning, outlining, and approaches for writing code. So, rather than dropping in code snippets throughout the book, what you’ll find are details about code strategies, such as progressive enhancement, deciding on what tooling to use, and the challenges of writing future-friendly code.

And for those of you who have not had the pleasure of listening to Jeremy narrate content (like he does in the Web History series), there’s an audio file available to download.

Beginning CSS Web Development: From Novice to Professional by Simon Collison

  • Perfect for: The fundamentals of CSS
  • Learning level: Absolute beginners
  • Requires: Nothing but time and motivation

It may be written in 2006, but Simon’s coverage of web standards and accessibility is timeless and relevant today. He provides an understanding of interoperability as well as approaches for building web applications, including the early planning phases that often go overlooked.

The book has two broad parts which are further divided into 16 chapters. Part 1 covers CSS topics, like working with text, links, lists, backgrounds, images, tables, and forms. It really doesn’t skimp on the details either.

Part 2 is all about layout, shedding light on usability and layout manipulation, plus a handy case study. The chapters are arranged in such a way that one chapter naturally flows into the next. Each chapter also contains a concluding section that highlights all the important concepts covered in the chapter.

Indeed, the book provides novice developers a solid background in CSS and helps them gradually with more advanced concepts. It will make your CSS journey easier.

Books on HTML & CSS

CSS and HTML are often taught together, which can be especially helpful when you’re writing your first lines of code and want to know how the two languages interact with one another.

Learn to Code HTML & CSS by Shay Howe

  • Perfect for: Starting your front-end journey
  • Learning level: Beginners
  • Requires: No prior experience at all

Shay refers to this book as a simple and comprehensive guide dedicated to helping beginners learn HTML and CSS. He does this by focusing on common elements of front-end design and development. Some of the lessons covered are Box Model, Positioning, Typography, Background and Gradients, Lists, Media, Forms, and Tables. In the first chapter *Building Your First Web Page, Shay analyzed the contents of a typical website including elements, attributes and setting up the HTML document structure, code validation, selectors and CSS resets. I find the book very instructive especially as it went beyond the surface to address many key concepts with code samples, which you can follow along.

One profound thing about this great book is that, Shay built a complete project from scratch throughout the 12 lessons and at the end of each lesson, he provided a summary and links to the current state of that website (so you can compare with yours if you follow along) and the source code at every stage of the lessons.

If you’re a learner who learns by doing, you will find this material very useful and by the time you’re done, you will have developed a multi page functional website.

An advanced sequel of the course is also available free via the same link.

HTML & CSS: Learn the Fundamentals in 7 Days by Michael Knapp

  • Perfect for: Starting your front-end journey
  • Learning level: Beginners
  • Requires: No prior experience at all

Can you possibly learn everything there is to know about the HTML and CSS in seven days? Probably not, but that’s why this 2017 book by Michael Knapp is focused straight on the fundamentals. Michael delves into a brief history lesson before launching into HTML and CSS structure, logic, and presentation. You’re going to get all up to speed to the point where you should feel pretty confident about putting a basic webpage together, plus a few extras along the way as the book touches on SEO and analytics.

The book is comprised of simple programs that you can run on your computer if you wish to follow along.

The ebook version is available for free on Apple Books, but there is a Kindle version as well if you already have a subscription there.

The Greatest CSS Tricks Vol. 1 by Chris Coyier

  • Perfect for: Marveling at what CSS can do
  • Learning level: Intermediate
  • Requires: Some CSS experience

Did you know that CSS-Tricks has a book on CSS too? It would be silly to leave that off this list because what you get is a collection of classic CSS trickery that’s explained by none other than Chris Coyier. In fact, Chris handpicked all of the examples covered in the book from his many, many (many!) years running this here site from the plentitude of tricks that have crossed his desk.

Each trick solves a particular pain point. For instance, the first “Pin Scrolling to Bottom” trickdemonstrates how the overflow-anchor CSS property can be used to create the same chat-like interface of a tool like Slack, where the screen is anchored at the bottom in a way that feels as though the page is scrolling for you as new items are added.

Books on process

Code is just as much about how we write code and collaborate on projects with others as it is about the actual code we write. The following books are great starting points for everything from planning and project management to communicating and collaborating with others.

Collaborate: Bring People Together Around Digital Projects by Ellen De Vries

  • Perfect for: Being a better collaborator
  • Learning level: N/A
  • Requires: An open mind to working well with others!

Ellen addresses something in this book that we all have to deal with: collaborating with others. And it’s no small deal — the book is divided into four parts that go super deep into things we can go to work well with others:

  • Know how to prepare the ground and create the right conditions for collaboration.
  • Nurture the group culture in the early stages of collaboration.
  • Maintain a healthy collaborative process.
  • Reap the rewards of a collaboration.

As a content strategist, Ellen has the right kind of experience to help anyone be part of a collaborative project, or get the most from a collaboration.

The Modern Web Design Process by webflow

  • Perfect for: Senior designers, project managers
  • Learning level: N/A
  • Requires: Some basic understanding of CSS

This free ebook features a seven-step design process that’s meant to help define the workflow for today’s brand of web design.

That includes:

  • Setting goals
  • Defining scope
  • Sitemaps and wireframes
  • Working with content
  • Handling visual elements
  • Testing
  • Shipping

Anyone starting a new design project or in the middle of a design project will find the invaluable insights throughout the book. And what’s most remarkable is how this is written in a way that almost feels as though you are being hand-held through an entire project from concept to completion.

Designing for the Web by Mark Boulton

  • Perfect for: Learning to work with clients
  • Learning level: Beginners
  • Requires: A genuine interest in design

It seems many organizations tackle design differently. But author Mark Boulton documents a thorough design workflow in Designing for the Web that de-mystifies many challenges and covers everything you need to know.

What’s unique about this book is that it’s really about work. Sure, there’s a bunch of hugely valuable information on design best practices for things like typography, color, and layout, but what you’re really going to take away from this book is how these fit into a design workflow. It teaches you how to research, the technologies we have to implement ideas, and ultimately, how to work with others as well as clients — perfect fodder for folks including design leads, project managers, freelancers, or anyone who’s involved in the project delivery process.

Learn Version Control with Git by Tower

  • Perfect for: Mastering Git
  • Learning level: All levels welcome
  • Requires: No prior knowledge at all

In this book, the team behind the popular Tower client for Git introduce learners to the crux of version control system using Git. Developers who work in teams will particularly find this very useful, as it helps in effectively collaborating with team members building different features of a project even when you’re thousands of miles apart. That said, it’s still really great for anyone who might be shy of the command line and wants to build confidence there.

And since the book is by the maker of an application that interacts with Git, you’re going to get a nice dose of using Tower as a GUI in addition to working directly on the command line.

So, whether it’s committing, branching, merging, pull requests, forking work, or handling merge conflicts, you’re going to get a whole lot from this book.

Books on JavaScript

Learning JavaScript always seems to be en vogue. In fact, Jason Rodriguez wrote about the JavaScript learning landscape in 2018 and provided a nice list of free books. Not too much has cropped up since then, but here are my thoughts on the following books.

Eloquent JavaScript by Marijn Haverbeke

  • Perfect for: Getting better at writing JavaScript
  • Learning level: Intermediate to seasoned developers
  • Requires: Prior JavaScript experience

Eloquent JavaScript really lives up to its name. Personally, I consider this one of the best-written JavaScript books I have ever come across. Marjin’s writing style is engaging, especially with how he introduces programming concepts and carries the reader along. In his words, the book is simply about instructing computers and making them do what you want them to do.

The book is a deep dive into JavaScript spread across three parts and 21 chapters. You’re going to read a bunch about basic programming concepts, such as values, types, operators and functions, to advanced concepts like regular expressions, modules, the DOM, and asynchronous programming. He starts every chapter with a somewhat philosophical quote to prepare the reader for what lies ahead and then dives straight into the topic.

Plus, there’s three projects to help you practice your newfound skills.

Understanding JavaScript Promises by Nicholas C. Zakas

  • Perfect for: Those who want to learn all about asynchronous programming with promises in JavaScript.
  • Learning level: Intermediate
  • Requires: Basic JavaScript chops

JavaScript promises were introduced in 2015 as part of the ES6 specification to handle asynchronous functions in JavaScript. According to MDN:

A promise is an object representing the eventual completion or failure of an asynchronous operation

In this 51-page book, Nicholas explains the concept of Promises over three chapters: Basics, Chaining Promises, and Working with Multiple Promises. Although the link to the book we’re providing is the free community version, the full version (available on Amazon) has two more chapters on Async Functions and Unhandled Rejection Tracking. Nicholas simplified the concept of Promises with several illustrations and examples. You will learn how to use then(), catch(), and finally() and understand how to chain multiple promises together. Nicholas also covers the assignment of rejection and settlement handlers. You may want to give the book a read to solidify your understanding of the topic.

Nicholas is a veteran JavaScript book author who has been writing about JavaScript for over 15 years. He brings his wealth of experience to bear in this book (just as he has in his work here at CSS-Tricks).

Speaking JavaScript by Axel Rauschmayer

  • Perfect for: Leveling up from beginning JavaScript
  • Learning level: Intermediate
  • Requires: Knowledge of object oriented programming

This book is presented in four chapters covering more than 30 topics. Here’s how it breaks down:

  1. The first chapter is a nice refresher on syntax, variable types, functions and exception handling.
  2. The second chapter offers historical perspective into JavaScript as a prelude for the types of features covered throughout the rest of the book.
  3. Chapter 3 is presented as more or less a reference book with short, clean examples.
  4. The final chapter outlines tips, tools and libraries to help write better JavaScript and follow best practices.

Secrets of the JavaScript Ninja by John Resig and Bear Bibeault

  • Perfect for: Creating a cross-browser JavaScript library from the ground up
  • Learning level: Intermediate
  • Requires: Some prior programming experience

There’s actually a newer edition of this book, but the 2012 edition is the one that’s free. Either way, it’s a good opportunity to learn from John Resig; you know, the guy who created jQuery.

The techniques covered here include closures, functions, the DOM, object orientation with prototypes, and cross-browser strategies. One nice perk is that each chapter is followed by a brief recap that’s perfect for a reference once you’ve finished the book.

Learning JavaScript Design Patterns by Addy Osmani

  • Perfect for: Learning to write more efficient JavaScript
  • Learning level: Intermediate
  • Requires: A decent level of JavaScript experience

The concept of design pattern refers to a reusable solution to a commonly recurring problem in application development. In this book, Addy Osmani covers the implementation of common design patterns using ES6 and beyond, as well as React-specific design patterns, which can be super handy when working on complex React apps where maintainability is a primary goal.

Some of the patterns covered include Singleton, Proxy, Provider, Prototype and Observer patterns. In some cases, Addy includes pros and cons of using some of these patterns and how they may affect the performance of your application.

You Don’t Know JS by Kyle Simpson

  • Perfect for: Mastering JavaScript
  • Learning level: Beginner
  • Requires: Little or no prior programming experience

While the title might be a bit provocative, what Kyle is implying here is that he writes this book assuming you have no prior JavaScript experience whatsoever.

Kyle begins starts by going through the rudiments of programming as seen through the lens of JavaScript. He then proceeds, in subsequent chapters, to introduce more advanced concepts like scope and closure, the this keyword, object prototypes, async, and performance.

There’s a lot of excellent details and explanations in here, and Kyle makes it super easy to understand by avoiding super technical jargon. There is also many exercises designed to reinforce your learning. This book will definitely get you up to speed with JavaScript. There’s second edition of the book in the works that you can track in GitHub.

The JavaScript Beginner’s Handbook by Flavio Copes

  • Perfect for: A beginner’s reference
  • Learning level: Just getting started
  • Requires: Email sign-up, maybe some prior experience

Flavio has put together a very useful JavaScript reference for those just starting out. It’s more like a quick reference guide than a textbook, so those of you just starting out might want to consider this as something you keep on your desk rather than something you sit with for long periods of time.

JavaScript for Data Science by Gans, Hodges & Wilson

  • Perfect for: Getting into data visualizations
  • Learning level: Intermediate to advanced
  • Requires: A decent handle on JavaScript

The authors cover core features of modern JavScript, including callbacks, promises, inheritance, objects and classes. They also get into testing using Mocha, React, and data vizualization, all of which are great for anyone looking to level up their code and how its written. The book doesn’t get as deep into many the concepts as some of the other books, but it really shines when it gets into data science.

The book uses Data-Forge; a JavaScript library designed for working with tabular data. There are numerous exercises to help readers keep up to speed with the subject of discussion. The last chapter also includes a capstone project that pulls everything together.

Wrapping up

I sure hope this collection of books help you, whether you’re taking your first steps in front-end web development, have a dozen years under your belt, or you fall somewhere in between. I know how hard it is to get into something new for the first time and the feeling of not knowing where to look. I also know how it feels to hit a plateau and need something to level me up. There should be something for everyone here, regardless of where you are in your learning journey.

And, hey, if you have any other books that are available to snag for free online, please share them in the comments! I bet we can get an even bigger list going.


Great (and Free!) Web Development Books You Can Get Online originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
https://css-tricks.com/web-development-books-you-can-get-for-free/feed/ 2 366468
Responsible JavaScript https://css-tricks.com/responsible-javascript-2/ https://css-tricks.com/responsible-javascript-2/#comments Tue, 02 Nov 2021 14:17:55 +0000 https://css-tricks.com/?p=355395 High five to Jeremy on the big release of Responsible JavaScript on A Book Apart. There is a lot of talk about how the proliferation of JavaScript has had a negative impact on the web, but now we have …


Responsible JavaScript originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
High five to Jeremy on the big release of Responsible JavaScript on A Book Apart. There is a lot of talk about how the proliferation of JavaScript has had a negative impact on the web, but now we have the canonical reference tome.

The book is just chock-full of Jeremy framing some of the biggest arguments discussions about modern web development, dissecting them, and helping us learn from them. I say “modern web development” there on purpose, because JavaScript has gotten to be such a massive part of building websites these days that the two terms are almost synonymous, for better or worse. While the book title is Responsible JavaScript, it might as well be “Responsible Web Development” to make it go hand and hand with Scott’s book (and Mat’s book, if you need a more gentle introduction to JavaScript).

I like how Jeremy blends the old and new together. Readers are introduced and shown how techniques as old as the web (like progressive enhancement) are still useful today and perhaps even more useful than they have ever been. But this isn’t a history novel. New technology (like service workers) is handled with equal grace, and modern techniques for performance gains are given the credit they are due (like build tools and code splitting).


As an aside here — have you ever had an inkling to write a tech book? I have both heard and given this advice: Write a blog post first, or maybe a whole bunch of blog posts. That’ll prove you clearly have words to say about this. Plus it will get the energy of your idea into the world. You might get feedback and constructive insights on the idea as it is shared. Then, hopefully, you can turn that blog post into a talk. That’ll really get you thinking deeply about your idea while getting even more comfortable with the idea of sharing it clearly. And, if all goes well, turn all of that into a book!

Let’s see what happened here. Jeremy wrote a couple of blog posts (hey, nice title). They became a talk (hey, nice title). And that turned into a book (hey, nice title).


Responsible JavaScript originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
https://css-tricks.com/responsible-javascript-2/feed/ 2 355395
The Greatest CSS Tricks Vol. I eBook (PDF and EPUB) https://css-tricks.com/the-greatest-css-tricks-vol-i-ebook-pdf-and-epub/ https://css-tricks.com/the-greatest-css-tricks-vol-i-ebook-pdf-and-epub/#comments Mon, 25 Oct 2021 19:25:17 +0000 https://css-tricks.com/?p=353728 When I wrote the “book” The Greatest CSS Tricks Vol. I, I put “book” in quotes because there wasn’t anything terribly book-like about it. The only way you could read it was online, logged into this website, with an …


The Greatest CSS Tricks Vol. I eBook (PDF and EPUB) originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
When I wrote the “book” The Greatest CSS Tricks Vol. I, I put “book” in quotes because there wasn’t anything terribly book-like about it. The only way you could read it was online, logged into this website, with an MVP supporter membership (no longer required). No printed version, not even digital copies you might expect from a digital book.

I’ve changed that now and offer PDF and EPUB versions of the book. They are free downloads for members — just add them to your cart and check out.

All this book-writing stuff was and is an experiment. I like writing on this website in a blog-post-like format where all the content is at URLs and can have interactive content. Being digital, I can control the access and such. It means I can write in a way that is comfortable to me, and maybe-just-maybe, I can be more prolific about it. Maybe I can get a Vol. II done that I already have a ton of ideas for. Maybe I can write some other books I’ve been thinking about. Now I have a system! A place to write, multiple places to publish to, and a way to sell it.

Producing the digital versions

When I originally made the choice to write the book online, I figured PDF would be incredibly simple. I’d output the content on a “raw” template (just as a clean starting point that will last and is easy to preview), apply nice print-like CSS, then quite literally, just ⌘P (Print) and “Save as PDF.” Done.

Print dialog bog in Google Chrome, with the Save as PDF option chosen.

That actually kinda works. You can fiddle with the settings (e.g. “✔ Print Background Graphics” in order to have white text on a dark background on things like code blocks) and get it fairly nice. But there are issues — like you can’t control the header or footer of each page very well. Not to mention it’s not programmatic, but a very manual process.

Doing things programmatically is what I was shooting for. Then I happened across this blog post from Baldur Bjarnason in which he was looking for work:

• Do you need to make a site or sites that walks like a book, talks like a book, and reads like a book but everything you make looks like a blog?

• Are you having trouble dealing with file formats such as PDF, DOCX, or EPUB using web tech?

• Are you trying to produce PDFs or ebooks from your website or your CMS?

Yes, yes, yes!

Programatically creating an eBook

I reached out to Baldur and he was able to help me work on all this. He created an automated system for me that accepts a local .html file and automatically produces PDF, EPUB, and MOBI formats from that single file. Essentially, I can run make from the command line and it’ll do all the work, leveraging open source tools.

VS Code showing there terminal open running a Makefile script producing the eBooks.

I still needed near-perfect HTML ready for the machine, though, which took some work. Fortunately, I was already somewhat ready to produce this, as I have a special URL that outputs the raw content (you can still see this if you’re not a member, just with truncated content) with the light print styles I wanted.

The tools

With the raw HTML and a programmatic approach in hand, here are the tools that make up the stack:

  • For PDF creation, we tried both Paged.js and WeasyPrint. They both had their quirks and did things worse/better than each other. We ultimately landed on Paged.js.
  • For EPUB creation, we used pandoc.
  • For MOBI creation (which we did not focus on at all), we used Calibre. It’s a native Mac app, but it has an ebook-convert tool buried within it that can be called from the command line.

To get to the point where we could use these tools over the command line, all sorts of other software have to be installed and ready to use, like Python, pango, libffi, and more. Baldur’s script made managing this easy, which was awesome.

It looks like there is a new player on the block called Percollate) for this stuff, but we did not explore that.

An Public Repo Combining all this Tooling for HTML-to-eBook Creation

After we got through this process together, Baldur generously created an open-source trimmed down public repo (book-tricks) for all y’alls reference. There is a lot of useful magic in this Makefile that I’d be shocked if it wasn’t useful for someone in the same position I was in: needing to create eBooks from simple HTML.

Previewing builds

PDFs are easy to view, of course (you can even just use a web browser), but I generally popped it open in Preview.app.

EPUB is similarly easy on a Mac because you can just pop it into Books.app to view it.

Mac app Books.app with the EPUB version of the book open.

For MOBI, Calibre’s main function is viewing those, so that’s the trick there:

The most painful part is the feedback loop. There is a whole process of updating code (mostly CSS) and then running the whole build to see how it all looks. I’m sure I did it 100 or more times to get things right. There really should be a better story for this, with live previews.

Web-only vs. eBook-only content

Early in the book-writing process, I had given up on both paper and digital versions. I stopped leaning on images in the text as much and started using embedded CodePen demos to show off output and code. That’s the ideal experience for the web anyway. But I can’t use embedded Pens in eBooks. eBooks can do some interactive things (e.g. EPUB supports animated GIFs and links, of course), but running JavaScript and using <iframe>s are things I didn’t want to count on. If I had proper images for everything, then just maybe it’s more ready for paper someday anyway.

It’s easy enough to hide things from the eBook output with display: none, so that’s what I did for all embedded Pens. (They are a bit of HTML before they transform into the iframe.) Then to have “alternate” content that is only for the eBook version, I essentially just wrapped that stuff in <div class="print-only"> which is hidden online and shown in the print CSS. I made custom blocks in the WordPress block editor to make authoring those blocks easier. That way, I could really see what I was doing.

One interesting bit is that because I was shooting for eBook-only here, I didn’t have to do the sort of CSS trickery I’m used to for things like print stylesheets where the output is likely some computer paper. For example, in a print stylesheet, I’d probably normally do:

main a[href]::after {
  content: " (" attr(href) ") ";
}

That way, people can see the URLs of links in content. But with these digital eBooks, I just make sure the links are blue and they’ll be clickable in any of the digital formats.


This was a fun journey! I’m mostly excited to have climbed the ladder of understanding a bit on all this, especially because rendering things on digital canvases is kinda my wheelhouse. I’m only a couple of rungs up though, as this stuff has a pretty steep learning curve!


The Greatest CSS Tricks Vol. I eBook (PDF and EPUB) originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
https://css-tricks.com/the-greatest-css-tricks-vol-i-ebook-pdf-and-epub/feed/ 4 353728
Computer Science Unleashed, Chapter 1: Connections https://css-tricks.com/computer-science-unleashed-chapter-1-connections/ https://css-tricks.com/computer-science-unleashed-chapter-1-connections/#respond Fri, 17 Sep 2021 15:27:49 +0000 https://css-tricks.com/?p=350843 Humans crave connections, and the advent of the digital revolution has empowered us to be more connected than ever before. The Internet has unleashed upon billions of people unprecedented economic and political freedom, as well as powerful means of control and domination. Yet, the vast majority of us are oblivious to its inner workings.


Computer Science Unleashed, Chapter 1: Connections originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
This article is actually an excerpt from Wladston Ferreira Filho‘s new book Computer Science Unleashed. This book is about all the groundbreaking technologies behind the World Wide Web. We might even take them for granted these days, but there are important and learnable technologies behind how it all works. Read on and marvel at the engineering ingenuity that enables simple physical links between computers to become a global, near-instant communication medium that everyone can use almost for free.

Humans crave connections, and the advent of the digital revolution has empowered us to be more connected than ever before. The Internet has unleashed upon billions of people unprecedented economic and political freedom, as well as powerful means of control and domination. Yet, the vast majority of us are oblivious to its inner workings.

Skilled people who can program computers to use the Internet are at the vanguard of the digital revolution. This chapter will teach you how the Internet works, so you can join this select group. You’ll learn to:

  • Link computers to one another to make a network,
  • Combine networks using the Internet Protocol,
  • Locate a recipient from its Internet address,
  • Find a route through the Internet to that location,
  • Transport data between distant applications.

Before the Internet, telecommunication between two parties required a direct physical link. In the 1950s, each telephone had a wire leading directly to a central station. For a call to go through, an operator had to physically connect the wires of two telephones. For long distance calls, wires were laid out between distant stations, and several operators in different places had to physically connect the chain of wires linking the two phones.

The Internet did away with this. Wires aren’t physically reconfigured to create direct, exclusive links. Instead, the information is retransmitted step by step via a chain of linked devices until it reaches its destination. This eliminates the need for wire operators and central coordination. Also, wires are no longer constrained to serve a single connection–many concurrent connections can share the same wire. This allows global communications to be instant, cheap and accessible.

However, modern networking technology is more intricate than early telephony. It has many successive layers, each building on top of the previous. Let’s explore how connections are made at these different levels, starting with the most basic layer.

A direct connection between two computers is achieved through a transmission medium: a physical channel where signals flow. It can be a copper wire carrying electric currents, a fiber-optic cable directing light, or air hosting radio waves. Each connected computer has a network interface to send and receive signals in the transmission medium. For instance, cellphones have a radio chip and antenna to handle radio signals traveling through the air.

Figure 1.1 A link is established between two network interfaces if they share a transmission medium and agree on the rules of communication.

In order to communicate, network interfaces must agree on the rules to follow when sending and receiving signals. This set of rules is called the link layer.

When a medium exclusively connects two computers, we say they maintain a point-to-point connection, and their link layer relies on the most basic set of rules: the Point-to-Point-Protocol (PPP). It merely ensures the two computers can identify each other and exchange data accurately.

However, connected computers don’t always get to enjoy such an exclusive link. Often, they must share the transmission medium with several other computers.

One way to link computers in an office is to plug each of them into a hub with a wire. The hub physically connects all the wires that reach it, so a signal sent by one computer will be detected by all the others! This will also happen on your home WiFi, since the same radio frequency is used by all connected devices. Communications can become messy if all of them use the medium at the same time.

Figure 1.2 A message sent on a shared link will be detected by all.

The link layer contains a set of rules to define how computers should share their communication medium, fittingly called Medium Access Control (MAC). The rules resolve two main challenges:

COLLISIONS — If two computers send a signal through the same medium at the same time, the resulting interference garbles both transmissions. Such events are called Collisions. A similar problem occurs when your group of friends or family talk over each other hand no single voice can be clearly heard.

There are methods to avoid collisions. First, only start transmitting signals when no other computer is transmitting. Second, monitor your communications–if a collision occurs, wait for a brief but random amount of time before trying to transmit again.

Figure 1.3 Collision between Ada and Andrew.
Figure 1.4 Ada and Andrew both resend after a random duration.

These methods have some limitations. If there are too many transmission attempts through a medium, collisions will occur relentlessly. We say the link is saturated when excessive collisions break down communications. Have you ever been frustrated at a large venue because your phone wouldn’t send text messages or make calls? This may happen if too many phones are attempting to communicate concurrently and the cellular link becomes saturated.

PHYSICAL ADDRESSING — Ada and Charles have a direct link between their computers. Ada wants to talk with Charles, so she transmits a signal with her message through the medium. However, the medium is shared, so everyone linked to the medium gets the message. How can the other computers know that the signal they picked up was not destined for them?

Figure 1.5 Andrew’s network interface discards the message.

Each computer’s network interface has an identifier, known as its physical address or hardware address. A transmission in a shared medium must begin with two such addresses: that of the recipient and that of the sender. Upon receiving a transmission, a computer will know if it should be ignored or picked up and to which address it should reply.

This can only work if physical addresses are unique: if two computers use “my_netinterface”, we’re back to square one. For this reason, virtually all network interfaces follow a naming scheme defined in the rules of Medium Access Control. These standard physical addresses are called MAC addresses.

MAC Addressing

Computers, smartphones, smart watches, and smart televisions can each have WiFi, Bluetooth, and Ethernet network interfaces. Each network interface has its own, unique MAC address marked into the hardware during production. You should not worry about assigning a MAC address to your computer: you can always use the one that came with its network interface.

Since MAC addresses are simply large random-looking numbers, network interface manufacturers around the world must coordinate to avoid accidentally assigning the same number to two different devices. To this end, they rely on the Institute of Electrical and Electronics Engineers (IEEE), that assigns each of them a different range of MAC addresses.

A MAC address is expressed as six pairs of hexadecimals1 separated by colons. The first half of the address is an identifier assigned by the IEEE to a unique manufacturer. This manufacturer then chooses a unique second half for each network interface.

60:8B:0E:C0:62:DE

Here, 608B0E is the manufacturer number. This specific number was assigned by IEEE to Apple, so this MAC address should belong to an Apple device.2 A device’s MAC address is often written on a label stuck to the packaging or on the device itself, next to the serial number.

Figure 1.6 Each MAC address is unique.

There’s a special address reserved for transmissions to all computers in a medium. It’s called the broadcast address, and it reads FF:FF:FF:FF:FF. You use it when you try to connect to an unknown device. For instance, when your smartphone’s WiFi card isn’t deactivated, it persistently broadcasts to FF:FF:FF:FF:FF that it’s looking for an access point. Discoverable access points will respond with their own MAC address so you can establish a link.

Such discovery broadcasts, like all other transmissions, contain the sender’s MAC address. Walking around with a smartphone can therefore be like walking around with a loudspeaker shouting your name non-stop, only using radio waves instead of sound and the MAC address instead of your moniker. In 2013, Edward Snowden revealed that the NSA3 monitored the movements of people by sniffing WiFi transmissions in big cities, storing records of where each MAC address was seen.

You can also set your own network interface to promiscuous mode, and it will pick up all transmissions regardless of their intended recipient. Doing so allows you to discover hidden WiFi networks, to list which MAC addresses are in your area, and sometimes even to read the contents of other people’s transmissions. Browsing the Internet through an unsecured WiFi network can therefore be unsafe: your communication is broadcast for anyone in range to hear. This is why encryption4 is important for WiFi’s link layer.

Be careful: a network interface can be configured for its transmissions to start with any MAC address for both the recipient and the sender. Nothing stops a malicious agent from impersonating you by using your MAC address in their transmissions. This type of attack is known as MAC spoofing. When the link layer was invented, security wasn’t a concern. Protocols are evolving to become more secure and neutralize such attacks, but it’s an ongoing process.

Frames

Sometimes, a transmission must contain a lot of data, and sending out a single, big fat message is impractical. Network interfaces and computers are not all capable of the same transmission speeds. Moreover, what would happen if a collision occurred in the middle of the transmission? The entire transmission would have to be discarded, as it would be difficult for the sender and receiver to determine exactly which parts of the message were received and which were not.

To solve these issues, long messages are always split into small parts, each sent as an independent transmission. The duration between transmissions can vary according to the capabilities of both computers: slower devices needs longer breaks. If an error occurs, it is only necessary to discard and resend the small transmission that failed.

Figure 1.7 An Ethernet frame. Once it is transmitted in a copper wire, it becomes a series of electric signals that encode a number. The Ethernet protocol instructs how to interpret this number. For instance, the first 12 hex digits of the number encode the destination MAC address.

Each independent transmission is called a frame. Standard WiFi protocols cap the size of frames to 2,346 bytes. Thirty-four bytes are needed for MAC addresses and error-detecting codes. Therefore, a WiFi frame can ultimately carry up to 2,312 bytes of data, called the payload.5 In wired networks, the maximum frame size is usually 1,526 bytes, with room for a 1,500 byte payload.

On rare occasions, disturbances in the medium interfere with a transmission, and the receiver picks up signals that don’t encode exactly the same information that the sender intended to transmit. Let’s see the special field that was added to address this problem.

FCS — The last part of the frame is the FCS (Frame Check Sequence), and it ensures that information was transmitted accurately. It doesn’t add new information to the transmission: it is merely the result of a calculation using the contents of all other fields. Changing any content before the FCS should cause the FCS number to change as well.

Upon receiving a frame, a computer calculates the expected FCS number from the information it received and compares it to the received FCS. If they don’t match, the frame is discarded. If they match, we know that the message wasn’t garbled and trust that the received payload is error-free.

TYPE — The frame shown in Figure 1.7 has one last field we haven’t talked about: the payload type. It tells the receiver which rules should be followed to interpret the data in the frame’s payload. In the next section, we’ll explore the most common set of such rules.

1.2 Internet

We’ve seen that the link layer enables directly connected computers to exchange messages inside frames. The internet layer, also known as the network layer, specifies how to transmit these messages between computers that are not directly connected.

The trick is to equip some computers, called routers, with multiple network interfaces. All computers in a network are then linked to at least one router, and all routers are linked to at least one other router. When a router receives a message at one of its network interfaces, it can forward it to another router through a different network interface.

LOCAL AREA NETWORKS — We can ask a router we’re linked with to forward a message to a computer we’re not linked with. Suppose you have a wired network in your home connecting a router and a desktop computer. Suppose the router is also directly connected to a smartphone in a different, wireless network.

Even though the desktop computer and the smartphone are not directly connected to the same network, they can send messages to each other using the router as a relay. Computers from different networks in close vicinity that can talk to each other through routers form a larger network, called a Local Area Network (LAN).

In a home or small office, one router will be enough to link all the computer networks in the area. When assembling a LAN that covers a large organization such as a university or hospital, many routers may be required to link all the different computers networks into a fully connected system.

Figure 1.8 In this small LAN, Ada and Andrew can send messages to each other through their router Charles.

WIDE AREA NETWORKS — But why stop there? If your router is linked with a router outside your home, which in turn is linked with a router at the university, you can ask for your message to be forwarded to computers on the university’s LAN. When distant LANs are connected to each other, they form a Wide Area Network (WAN).

Figure 1.9 Charles is connected to a distant router, Marie, and they both forward messages around this WAN.

A WAN can grow larger as more LANs are connected to it. Different WANs can also be connected to form an even larger WAN. The largest WAN in the world is a collection of thousands of interconnected networks that we call the Internet. It’s the network we use every day to send emails and browse the web. In 2019, this WAN contained over a billion computers. Let’s see how they all got connected.

Interconnection

The most straightforward way to connect your router to the Internet is to pay for it. Some organizations on the Internet will link one of their routers to yours, and allow messages to and from your network to pass through their network via this link. This paid service is called transit, as all of your messages will transit through their network before going to the specific router you’re aiming for.

However, transiting through a third party network is not always necessary in order to connect to another router of the Internet. If, for example, two nearby universities communicate a lot, they can link their routers in order for messages to flow directly between their networks. This can save money, as these messages would otherwise have to transit through a paid connection. The free exchange of messages between the networks of different organizations is called peering.

Routing

Any computer linked to a router of the Internet can ask for its messages to be forwarded by other routers. Messages can be routed over large distances. For instance, there is a system of submarine cables linking routers in many coastal cities:

Figure 1.10 The SAm-1 system links routers in 16 cities from 11 different countries, using over 15 thousand miles of underwater cables.

There is no direct link between the routers in Miami and Buenos Aires. However, Miami is linked with Puerto Rico, which is linked with Fortaleza, which is linked with Rio de Janeiro, which is linked with Buenos Aires. Miami and Buenos Aires can exchange messages through these cables if routers along the way forward the messages back and forth. Today, there are submarine cables linking hundreds of coastal city routers around the globe:

Figure 1.11 Fiber-optic submarine cables currently in service.

Virtually every other city on Earth is directly or indirectly linked to these coastal cities, often through cables in the ground. Communication satellites also have routers to establish wireless links to remote locations. All routers can forward messages, so a message you send on the Internet can be routed to any other computer on the Internet. That is, if a path to it can be found.

Location Addressing

In the link layer, computers are identified by a physical address. Physical addresses uniquely identify computers, but they don’t give any hints on where a computer is connected and how it can be reached. If the computer moves to the other side of the world, it will retain its physical address!

Suppose you mailed a package to Louis through the post along with a picture of him instead of his address. This package has a defined destination; however, an international postal service would have no way of knowing which direction the package should be sent in order to deliver it to Louis.

Post offices must first know to which country the package should go. The first post office in that country should then know to which province or state it should go. The next post office should know the city, and the final post office, the street address. An address containing all this information is called a hierarchical address. As with post offices, routers need a hierarchical address of the package recipient’s location:

Figure 1.12 Ada wishes to send a package to Louis, so she requests her router Charles to forward it. She writes on the package a hierarchical address of Louis. Charles then knows he must send the package to France, so he sends it to the French router he is linked with: Marie.

For this mechanism to work on a global scale, all computers involved must follow the same set of rules to create and handle package forwarding requests. A computer in China must understand a request from a computer in Nigeria, even though the two may use different languages, operating systems and hardware.

Figure 1.13 “Before the Internet”, courtesy of http://xkcd.com.

Internet Protocol

We’ve seen a computer must follow the rules of Medium Access Control to establish a link with another computer. Similarly, it must follow the Internet Protocol, or IP,6 to ask routers to forward messages to other computers on your LAN or on the Internet.

A message forwarding request that follows the IP rules is called an IP packet. The IP packet is essentially a big number, where digits in specific positions encode key information. Virtually all computers understand IP packets and are able to forward them. This makes an IP packet easily movable from one computer to the next, until it reaches its destination.

An IP packet contains the location addresses of its sender and recipient, followed by whatever data they want. To send an IP packet, we transmit a frame where the payload is the IP packet, and the frame type is 86DD. When a router receives a frame of this type, the IP packet is re-transmitted in another frame to the next computer in the path of the packet’s destination.

Figure 1.14 Ada sends an Ethernet frame to her router Charles containing an IP packet for Louis. The Ethernet frame therefore contains the physical address of Charles and the packet contains the location address of Louis. Charles will then forward the packet inside a new frame of his own containing the physical address of someone in France.

In order for IP packets to be forwarded around universally, everybody must agree on a standard for location addressing. We’ve seen how physical addresses are allocated by manufacturers according to the rules of Medium Access Control. Let’s now learn how the Internet Protocol does this for location addresses. We will then see how the Internet Protocol defines routing rules based on these addresses.

1.3 IP Addressing

The Internet Protocol sets the rules on how location addresses work–that’s why they’re called IP addresses. Computers can only send or receive IP packets after they get an IP address. Permission to use a group of IP addresses is first granted to an organization. These addresses are then assigned to computers which are directly or indirectly associated with the organization.

In order to explain how this process works, let’s define what IP addresses are and how they’re written.7 An IP address is a number 128 bits long.8 They’re typically written in hex, with colons separating eight groups of four digits. This is Facebook server’s IP address:

2a03:2880:f003:0c07:face:b00c:0000:0002

IP addresses can be shortened by omitting the leading zeros of any four-digit block:

2a03:2880:f003:c07:face:b00c::2

As with a postal address with country, city and street, IP addresses are hierarchical for routing to be possible. While the broadest part of a postal address is the country, the broadest part of an IP address is the routing prefix (2a03:2880).

The prefix shows up as the first digits of an IP address. Once an organization is granted such a prefix, it has the right to assign any IP address that begins with that prefix to its computers. The prefix has a variable length: organizations that have more computers to manage are granted shorter prefixes. Some organizations are even granted multiple prefixes.

For example, we know that all addresses that begin with 2a03:2880 are assigned to computers inside Facebook’s network. Those that begin with 2c0f:fb50:4002 are in Google’s network in Kenya. For its data center in Singapore, Google was granted the prefix 2404:6800.

For routing purposes, the LANs and WANs that share the same prefix are organized in small networks called subnets. The digits after the routing prefix and up to the middle of an IP address indicate in which subnet (f003:c07) a computer can be found.

2a03:2880:f003:c07:face:b00c::2

This means there’s a network at Facebook where all computers have IP addresses that begin with 2a03:2880:f003:c07. Together, the routing prefix and the subnet form the network ID (2a03:2880:f003:c07) of an IP address. The network ID is always 16 digits long (including omitted zeros). This means an organization with a longer routing prefix can have less subnets within it.

Finally, the next 16 digits of an IP address are called the interface ID (face:b00c::2), as they identify a specific network interface within a subnet. Many network administrators simply fill in this part of the IP address with the device’s MAC address. These digits can be any number, as long as it’s only used once per subnet.

For this addressing system to work universally, there must be a mechanism to ensure no two organizations use the same routing prefix. As was the case for MAC addresses, engineers solved this through some international coordination.

Figure 1.15 Don’t ask your boss where she lives!

IANA

Engineers worldwide agreed that an American non-profit organization, the Internet Assigned Numbers Authority (IANA), decides who gets control over which IP routing prefixes. In practice, IANA delegates most of its power to five non-profit organizations called Regional Internet Registries, or RIRs. To do so, it allocates each RIR short hex combinations that they can use as the first digits of the routing prefixes they assign.

Figure 1.16 Examples of allocations to each RIR.
Figure 1.17 IANA delegates its IP addressing power geographically: each RIR is responsible for a different region.

To obtain a routing prefix for your organization, you must make a request to the RIR of the region where your routers will be. That RIR will then assign you a prefix starting with one of their combinations of hex digits that IANA allocated them.

For example, Facebook, which has headquarters in Ireland, was granted its routing prefix by RIPE NCC. Likewise, the Swiss bank Credit Suisse has a Latin American branch that was granted a routing prefix by LACNIC:

Figure 1.18 IP address allocation chain for two companies.

This means computers in the Latin American Credit Suisse branches may be assigned IP addresses as follows:

2801:80:1380: ■ ■ ■ ■ :____:____:____:____

Network administrators in the bank will assign a unique combination of hex digits to each of their subnets such that they fit in the remaining space of the network part . Since each hex digit can have 16 different values, the bank has enough space for 164 = 65,536 different subnets. Facebook, being a larger organization, was granted a prefix with room for over 4 billion subnets!

We’ve seen that network administrators can choose how the sixteen blanks of the interface ID are to be filled for individual devices. Such devices may then send and receive IP packets to and from the Internet as long as their router has connectivity.

Internet Service Providers

Most individuals and small organizations don’t deal directly with RIRs, nor do they maintain peering links to other computer networks. Instead, they buy Internet connectivity from specialized companies, which are called Internet Service Providers (ISP). ISPs install routers close to their customers. That way, they can easily link one of their routers to a router in any customer’s premises. They also allocate a routing prefix for each of their customers.

Let’s see how it works in practice. In the United Kingdom, an ISP called Sky was granted the routing prefix 2a02:0c7f. Sky operates in many British cities, so the prefix is divided between their regional bases. For instance, they assign 2a02:c7f:48 to their Milton Keynes network and 2a02:c7f:7e to the one in Romford.9

Let’s suppose Ada lives in Romford and wants to set up a network in her home. She has a desktop computer and a printer which she wants to connect using an Ethernet wire. She also wants her own WiFi network to connect her smartphone, tablet and laptop.

Ada hires Sky, and they link their Romford router to a router in her home. Sky assigns Ada’s router a 14-digit routing prefix based on the one of their Romford base. Each network in Ada’s home (wired and wireless) gets assigned a subnet, based on the routing prefix Sky allocated to Ada. Figure 1.19 on the next page shows the full IP address allocation path from IANA to each of Ada’s devices.

Ada’s router receives IP packets from several different computers, yet it’s easy for her router to decide on which link to forward each packet it receives. Packets addressed to a computer in one of Ada’s subnets can be directly delivered. All other IP packets it receives are forwarded through the link to the ISP.

Figure 1.19 IP address allocations from IANA to Ada’s devices. Her router uses different subnets for her wireless and wired networks, and therefore has a different IP address for each.

For routers that don’t rely on an ISP, it’s not so easy: they obtain connectivity from links with several routers from multiple computer networks. But how do they decide on which link they should forward an IP packet? And how can they be sure that they are forwarding it to a router closer to their final destination?

1.4 IP Routing

Suppose Ada wants to send a message to Facebook from her laptop. She will use the Internet Protocol, so she starts by crafting an IP packet that includes her own IP address, Facebook’s IP address, and her message as the payload. She then transmits the packet in a WiFi frame from her laptop to her home router:

Figure 1.20 An IP packet transmitted over WiFi.10

Several routers, starting with the one at Ada’s home, retransmit the packet until it reaches Facebook. Along the way, each of those routers must choose in which direction the packet should “hop” to reach the next router. The last router will then make the packet “hop” towards its final destination computer.

Tables of Addresses

Routers choose the next hop of a packet based on its destination IP address. In order to do so, they are equipped with a table filled with addresses. Rows list possible IP addresses the router is configured to recognize. For each address, the table indicates which computer should be the next hop of a packet destined to that address. Every router has a unique table that reflects how the router is linked. For example, here is how Ada’s router is linked:

Figure 1.21 Ada’s router is connected to a desktop computer and a printer via Ethernet, a notebook and a smartphone via WiFi, and to the ISP via DSL (or Digital Subscriber Line, a technology that allows digital data to flow through old telephone cables).

Figure 1.22 Table that guides Ada’s router to correctly forward IP packets to computers shown in Figure 1.21.

If the router receives a packet whose destination IP address doesn’t match any row in the table, the packet is forwarded through to the default route. For Ada’s router, routing is simple: a packet is either directly delivered to a computer in her home or forwarded to Sky Romford, her ISP.

Routing is more complicated for the ISP’s router. In addition to its peering and transit links, it receives packets from many different customers. For simplicity, let’s suppose Sky Romford’s router only serves two customers and has two peering links: one to the Sky router in Milton Keynes, and the other to Oxford University. Finally, let’s imagine it has a transit link with a larger telecom company:

Figure 1.23 Map of Sky Romford links. Ada, Charles, and Oxford University can talk using Sky’s local infrastructure only.
Figure 1.24 Table that guides Sky Romford’s router to correctly forward IP packets to networks shown in Figure 1.23.

This is where the IP addressing hierarchy comes in handy. In the forwarding table of fig. 1.24, IP addresses are grouped according to their routing prefix. This works because all IP addresses starting with 2a0a:207 are from computers in Oxford University, and all IP addresses starting with 2a02:c7f:48 are from computers serviced by Sky in Milton Keynes.

Internet Exchange Points

In order to increase capacity and speed, network administrators often set up peering links with as many other organizations as possible. The cheapest way to do this is through places called Internet Exchange Points, or IXPs. Organizations join an IXP by wiring their routers to the IXP building. Every participating organization can then establish individual peering links with other organizations connected to the building.11

In fig. 1.23, only two peering links were shown for clarity’s sake. A typical ISP actually has scores of peering links per IXP they’re wired to. In addition, it’s common in big cities for Internet corporations like Netflix and Google to establish peering links directly with ISPs, allowing them shorter and faster connections to many of their customers.

Internet Backbone

ISPs and other telecom companies typically expand their interconnections as much as possible by establishing peering links wherever they can. However, in order to reach networks they cannot peer with, they have to buy transit from other operators.

There is a handful of companies in the world that don’t pay anyone for transit. These companies operate huge networks that all peer with each other, allowing regional ISPs to be interconnected globally. These huge networks are called Tier-1 networks, and they form the backbone of the Internet. Some Tier-1 networks are operated by AT&T, Verizon, and Lumen.12

Dynamic Routing

Large telecom companies must maintain connectivity even if some of their transit or peering links break down. This means that they can’t rely on a single link for each routing prefix in their table of addresses. In fact, they have dynamic routers that map out how other networks are interconnected in order to choose which routes to prioritize in their tables.

Dynamic routers periodically exchange information with other dynamic routers they’re linked to. They tell each other which network prefixes are reachable through each of their links. This allows them to determine how many hops away each link is from every routing prefix and where these hops occur. Dynamic routers can then determine the best route to each prefix based on metrics like distance and speed.13

With this information, dynamic routers build a table that covers all routing prefixes. For each prefix, the table indicates which next hop is on the best route to the final destination. When a link is established or a link goes down, dynamic routers inform their peers. As the news spreads, all of them update their tables to keep forwarding packets towards the best routes.

There is no central entity coordinating the exchange of this information: routers share link details with their peers freely and voluntarily. Consequently, routing problems often emerge.

Routing Loop

Misconfigured routers can provoke errors. Most notably, bugged tables of addresses can send a packet back a few hops, and it gets caught in an endless cycle of doom:

Figure 1.25 Bugged tables sending a packet round in circles.

If the tables aren’t corrected, more packets with the same intended destination will be endlessly forwarded in circles. Too many packets can even saturate and clog the links. This is known as a routing loop problem. Fortunately, the Internet Protocol provides a way to identify the issue when it occurs.

HOP LIMIT — To interrupt perpetual routing loops, all IP packets carry a hop limit between 0 and 255. It indicates the number of times the packet can be forwarded by routers. Typically, packets are created with a hop limit of 64. Whenever a router forwards a packet, it reduces the hop limit by one:

Figure 1.26 A packet’s hop limit is the only element of an IP packet that routers change while forwarding.

If a packet is going around in circles, its hop limit will eventually reach zero. If a router receives an IP packet with a hop limit of zero, it can be discarded. An IP packet containing an error message should then be transmitted back to the sender by the last router, stating that the packet could not be delivered because its hop limit was reached.

Feedback through such error messages helps network administrators fix critical bugs, and routing loops are not the only ones. In fact, the Internet Protocol covers how a variety of routing problems should be dealt with.

Diagnostics

Routers discard IP packets that they are unable to handle. When this happens, they send an informational message about the incident to the packet’s sender. The Internet Protocol defines how routers must format such messages, ensuring they can be understood by any computer. These rules are a subset of the Internet Protocol called the Internet Control Message Protocol (ICMP).

ICMP assigns error codes to the most common routing problems. To report a problem, a router sends an IP packet containing the error code as the message body, formatted according to ICMP rules. Let’s see some common problems that can be reported using ICMP, starting with the routing loop problem.

TIME EXCEEDED — If a router receives an IP packet with a hop limit of zero, its travel time is up. The packet either got stuck on a routing loop, or it was granted an insufficient hop limit by the sender.

In such cases, an ICMP message with a time exceeded error code is sent back. The ICMP message includes the first bytes of the discarded packet to allow the original sender to know which packet didn’t make it to its destination.

Figure 1.27 Once a router receives a packet with a hop limit of zero, it is discarded and an ICMP error message is sent to the packet’s sender.

Notice that the IP packet Charles sends back in fig. 1.27 includes a protocol field. It’s a two-digit hex number identifying how the packet’s payload should be interpreted. The latest version of ICMP was assigned the protocol number 0x3A. All IP packets must include a protocol number. In the next section, we’ll learn more about this. For now, let’s explore other common routing problems.

DESTINATION UNREACHABLE — Sometimes, a router has nowhere to send a packet. This can happen for many different reasons, for example if the IP address isn’t in the router’s table of addresses, and the table doesn’t propose a default next hop. Sometimes, the next hop happens to be offline.

When the router doesn’t know where to forward the packet, it returns an ICMP message with the destination unreachable error code, along with the first bytes of the discarded packet’s content.

PACKET TOO BIG — We’ve seen that link layer protocols limit the amount of data that can be sent in a single frame. Frames from different types of network links can carry payloads of different sizes.

The maximum number of payload bytes that can be carried in a single frame is called its Maximum Transmission Unit (MTU). Different link layer protocols have different MTU values. For Ethernet frames, the MTU is 1,500. For WiFi frames, it’s 2,305.

If a router receives a larger packet than what the next hop can handle, it can’t be forwarded as it stands. Instead, the router returns an ICMP message with the packet too big error code, the first bytes of the problematic packet, and the MTU of the next hop. The informed sender can then trim or split the original message into smaller packets before trying again.

Figure 1.28 “MTU”, courtesy of Daniel Stori (http://turnoff.us).

PARAMETER PROBLEM — An IP packet contains a lot of extra information alongside its payload. We’ve seen it contains IP addresses, a hop limit, and a protocol number. It also includes a field indicating the size of the payload and another specifying the version of the Internet Protocol it respects. Additional fields are also there to help routers prioritize important packets.

All these fields must be ordered and formatted according to strict rules. When a router receives a packet that doesn’t conform to the protocol, it returns an ICMP message with the parameter problem error code and the location in the packet where the conflict was found. As usual, the ICMP message also contains a few bytes of the discarded packet for identification purposes.

INFORMATIONAL MESSAGES — Error reports are not the only messages ICMP defines to inspect and diagnose faulty computer networks. Most notably, the echo request and echo reply informational message pair is widely utilized. When a computer receives an ICMP echo request, it returns a packet containing an ICMP echo reply.

This is useful to test if a computer is online. There’s a program called ping that sends out an ICMP echo request message and measures how long it takes for the reply to reach you.14 Furthermore, by sending ICMP echo requests with different initial hop limits, you can trace the route packets follow to reach their destination.15


We’ve seen that computers on the Internet can exchange information—such as ICMP messages—in IP packet payloads. However, the true power of the Internet is unleashed when applications, not computers, start using IP packet payloads to send each other data. This requires extra information to be included in the IP packets so that a computer can handle multiple streams of data for the different applications it runs. This extra information is described by the transport layer, which includes the famous TCP and UDP protocols.

To keep learning about these protocols, check out our book, Computer Science Unleashed. The book will also teach you how famous Internet applications such as email and the Web works. And it explains how DNS and domain names function under the hood! Understanding these technologies is essential for being a well-rounded web developer. Besides the Internet, Computer Science Unleashed also covers other three groundbreaking technologies: data analysis, machine learning, and cryptography. And it also includes a bonus chapter explaining how to use regular expressions!

Come check out the book!


1  In day-to-day life, we almost always express numbers in decimal form, where each digit is one of ten characters: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9. Computer scientists, on the other hand, like expressing numbers in hexadecimal form, where each digit can be one of sixteen characters: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, a, b, c, d, e, f. For more about number bases, see Appendix I.

2  You can look up who manufactured a device by entering the first six digits of its MAC address at http://code.energy/mac-lookup.

3  National Security Agency, a US government spying organization.

4   Encryption allows messages to look garbled to eavesdroppers.

5   If we encode one byte per character, a WiFi frame has room for about 500 words, enough to fill a page of text.

6  By “IP”, we mean its latest version, IPv6. A legacy version of the protocol, IPv4, is still used, despite being released in 1981. IPv4 can only support about 3 billion computers. IPv6, launched in 2012, can support a virtually unlimited number of computers. As of 2020, a third of the Internet’s computers use IPv6.

7  We’ll present IP addresses as defined in the latest version of IP. Legacy IPv4 addresses are still used. They are written as four groups of up to three digit decimal numbers, separated by dots, for example, 192.168.0.1.

8  It takes 128 zeros and ones to write the number. This means it’s a number between 0 and 340,282,366,920,938,463,463,374,607,431,768,211,456.

9  This information is public, you can look up the network location of any routing prefix. The practice is called IP geolocation, and it’s how websites guess the country and city you browse from.

10  We’ve included the fields of the WiFi frame which also exist in Ethernet frames. A WiFi frame has more fields, which were hidden for simplicity.

11  IXPs are extremely important for making the Internet well connected and cheap. This video explains why: http://code.energy/IXP.

12  For an idea of how colossal these networks are, Lumen alone manages and operates 750,000 miles of fiber optic cables. That’s more than enough cable to reach the moon, three times!

13  All five RIRs constantly disclose information on all routing prefixes they delegate. Dynamic routers closely track these announcements, so they can ensure their tables have a row for every existing routing prefix.

14  You can send ICMP packets here: http://code.energy/ping.

15  An explanation of how ICMP is used to trace the routes IP packets travel through can be found at http://code.energy/traceroute.


Computer Science Unleashed, Chapter 1: Connections originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
https://css-tricks.com/computer-science-unleashed-chapter-1-connections/feed/ 0 350843
So you want to self-publish books and courses on programming https://css-tricks.com/so-you-want-to-self-publish-books-and-courses-on-programming/ https://css-tricks.com/so-you-want-to-self-publish-books-and-courses-on-programming/#respond Thu, 29 Jul 2021 14:54:00 +0000 https://css-tricks.com/?p=344993 John Resig and I recently self-published our book on GraphQL. There are tons of how-tos for self-publishing a book, or even online classes, but very little in the way of why you would want to, or whether it’s even worth …


So you want to self-publish books and courses on programming originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
John Resig and I recently self-published our book on GraphQL. There are tons of how-tos for self-publishing a book, or even online classes, but very little in the way of why you would want to, or whether it’s even worth your while. I’m going to share my experience and revenue numbers with you in this post, as well as those from others who have self-published material. I’ll go specifically into the pros and cons of self-publishing books and courses in tech.

Revenue

This is probably what you’re most curious about, right? When I originally started working on our book, I sent a book proposal to publishers. But by the time John and I joined forces, we were both set on self-publishing. He had written two popular JavaScript books and a blog post about traditional publishing for programming books, which includes:

  • Programmers aren’t that into reading books! Programming books, by and large, are poor sellers. They rarely sell more than 4,000 copies.
  • He made $7,500 on his first 4,000 copies, where his royalty rate started at 10% for print sales and 20% for digital copies.

On the topic of traditional publishing revenue, Randall Kanna says: “Nothing comes from a tech book. Just the credibility.” A book can make significantly more, but it’s rare. Martin Kleppmann’s book on machine learning was O’Reilly’s second most popular seller in 2019, and he made $478,000 in the first three years (with 108,000 copies sold, a 10% royalty on print sales, and a 25% royalty on digital sales).

The Pragmatic Bookshelf is the outlying publisher when it comes to royalties: it gives authors 50% of gross profit. In their first 10 years operating, 42% of their authors made more than $50,000, and 12% made more than $100,000.

That said, self-publishing has much higher royalty rates:

  • Amazon: 70% (for e-books; 60% minus printing cost for printed books)
  • Leanpub: 80%
  • Gumroad: 96.5% ($10 monthly membership fee)
  • Your own website: 97%

This gives authors the potential to make more money. Discover Meteor was probably the most successful self-published programming book of its time, with around $500,000 in sales (9,000 copies) between 2013 (when they launched) and 2018 (when they made it available for free). The authors Sacha Grief and Tom Coleman put a lot of effort into marketing it (described in their Gumroad case study), and it became the recommended learning resource in the Meteor community. The current best-selling book is Adam Wathan and Steve Schoger’s Refactoring UI, which I believe passed $2 million in 2020! 🤑 Their success was also largely due to their ability to market the book, in addition to addressing a significant need for a broad audience (practical user interface design for front-end developers).

That’s books. Looking at publishing video courses, there are a few options:

Like self-published books, self-published courses have a lot of potential. Level Up Tutorials, Kent C. Dodds, and Wes Bos don’t share revenue numbers for their courses, but I’m assuming they have made considerable sums. Wes, for example, has sold his courses to over 140,000 people at the time of writing!

Those are the outliers, of course. The majority of resources out there make significantly less. Take, for example, the self-published books in the GraphQL space that we were entering:

Title (Author)SalesPriceEstimated Revenue
Production Ready GraphQL (Marc-André Giroux)3,000 (this is a guess)$49–$79$147,000–$237,000
The Road to GraphQL (Robin Wieruch)2,250$30–$80$67,500–$180,000
The GraphQL Guide (John Resig and Loren Sands-Ramshaw)1,000$30–$279$78,000 in sales; $68,000 in sponsorships
Advanced GraphQL with Apollo & React (Mandi Wise)200$30–$45$10,000+
Fullstack GraphQL (Julian Mayorga)100$39$3,000

So, yes, the potential is big. But it’s not a guarantee.

Self-publishing pros and cons

ProsCons
Potential for more revenue. You get to set the price, sell different packages, and receive a larger cut.It’s much harder. A publisher does a ton of things for you: editing, gathering feedback from technical reviewers, the build toolchain, translating, an online store, getting it on Amazon and other bookstores, customer service, tracking errata, etc. Doing all of these things yourself takes a lot of time, especially if you also decide to build a Gatsby site to display the text online. 😜
Flexibility. You get to decide what goes into the book as well as how it’s formatted and sold.No built-in marketing or distribution. The success of your own book completely depends on your ability to market it. This is hard, as you can read in swyx’s notes on the topic. Books published traditionally usually sell more copies.
Updates. You have the email addresses of your readers, and can send them updated versions of the book.No print edition. While you can print on demand with some services, like Kindle Direct Publishing, most people don’t put in that effort.

These pros and cons are for books. If you’re wondering about a breakdown of pros and cons specifically for self-published courses, they’re very similar because they face the same opportunities and challenges.

Should I create a book or course?

This is the big question. And while I wish I could give you a definitive answer one way or the other, it’s always going to be the same answer we love to give in tech: it depends.

Why would you want to self-publish a book or course? Here are some reasons:

  • Income: It’s nice to put something out there and have it generate an income as long as it’s available.
  • Positive impact: Creating a digital asset has high potential leverage. For example, if something takes you X amount of resources to create, and you distribute it to a thousand people who each gain Y amount of utility from learning with it, you’ve produced 1000 * Y utility in the world, which can be much larger than X. For more on this, I recommend Kleppmann’s post on the topic.
  • Reputation: Having written a book can help you get a job, gain clients, or simply elevate your reputation. Eve Porcello says publishing boosted her credibility—and as an added benefit, many readers hire her to teach workshops.
  • Knowledge: If you’re like me, you’ll find that you learn much more about the topic you’re writing about than you knew when you started. I know I certainly did—I finally read the GraphQL spec, learned Vue and Android, ran into and solved a ton of bugs, and went through countless blog posts and conference talks. 😄
  • Enjoyment: Some people enjoy the creative process. I liked learning, building example applications, and writing. In other words, there’s a level of self-fulfillment you can get from the work.

Those are the reasons why you might want to self-publish material. But whether you should actually do it depends on:

  • Your writing ability: You absolutely need to be good at explaining complex concepts in simple terms that are easy for anyone to grasp. That’s a seriously high bar, especially if there’s existing good content on the topic.
  • Your willingness to market: You need to be willing to get the word out, because no one will do it for you (at least at first). That takes some guts. I know there are many of people out there who have a tough time promoting themselves and their work.
  • What it’s worth to you: You’ve seen a lot of the benefits that self-publishing content can offer, but are they worth it to you? Do impact, knowledge, and reputation motivate you? Maybe none of that matters and you’re simply looking for a labor of love. Whatever your motivation is, it’s important. Without it, you could lose steam and wind up with an unfinished project.
  • The opportunity cost: What else would you do with your time and energy if you didn’t self-publish? Is that thing more valuable to you? Is there anything you’d regret missing out on because of this?

For me, while writing a book had an opportunity cost of lower income (compared to doing more consulting work), I’ve made a positive impact, increased my knowledge on a subject I care about, gained reputation, and enjoyed the process. And it also feels great when someone goes out of their way to tell me they’re “blown away” and appreciate reading my book. 😃🤗✨

Thanks to Chris Coyier, Geoff Graham, Sacha Greif, Robin Wieruch, Mandi Wise, Sebastian Grebe, Julian Mayorga, and Rachel Lake for providing input for this article.


So you want to self-publish books and courses on programming originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
https://css-tricks.com/so-you-want-to-self-publish-books-and-courses-on-programming/feed/ 0 344993
Debugging CSS https://css-tricks.com/debugging-css/ Mon, 14 Dec 2020 20:32:37 +0000 https://css-tricks.com/?p=330726 High five to Ahmad Shadeed for releasing his new book, Debugging CSS. I think that’s a neat angle for a book on CSS. There are a ton of books on the general subject of CSS already, so not that …


Debugging CSS originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
High five to Ahmad Shadeed for releasing his new book, Debugging CSS. I think that’s a neat angle for a book on CSS. There are a ton of books on the general subject of CSS already, so not that they can’t be fresh takes on that, but this feels equally important and less trodden territory.

Browser DevTools help us a ton these days in debugging CSS, but there isn’t exactly a step-by-step guide about about it that I know of. This book leans into that, showing off how to debug really practical and understandable CSS issues with the help of DevTools when appropriate.

I bought it because I’m a CSS nerd obviously — not really because I feel like I need to bone up on my CSS debugging. I really wanna support Ahmad because he really got the #1 gold star ⭐️ for CSS blogging this year. Every post of his was an extremely well done deep dive into some important area of CSS.

To Shared LinkPermalink on CSS-Tricks


Debugging CSS originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
330726
Laying the Foundations https://css-tricks.com/laying-the-foundations/ Fri, 18 Oct 2019 15:22:40 +0000 https://css-tricks.com/?p=297383 Here’s a new book by Andrew Couldwell all about design systems and I’m looking forward to reading the book because it looks like his experience will offer a bunch of insightful thoughts and advice.

From the book’s description:

This is


Laying the Foundations originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
Here’s a new book by Andrew Couldwell all about design systems and I’m looking forward to reading the book because it looks like his experience will offer a bunch of insightful thoughts and advice.

A spread from Laying the Foundations

From the book’s description:

This is real talk about creating design systems and digital brand guidelines. No jargon, no glossing over the hard realities, and no company hat. Just good advice, experience, and practical tips.

System design is not a scary thing — this book aims to dispel that myth. It covers what design systems are, why they are important, and how to get stakeholder buy-in to create one. It introduces you to a simple model, and two very different approaches to creating a design system. What’s unique about this book is its focus on the importance of brand in design systems and creating documentation. It’s a comprehensive, practical guide that’s simple to follow and easy on the eye.

To Shared LinkPermalink on CSS-Tricks


Laying the Foundations originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
297383
Currently Reading: Progressive Web Apps by Jason Grigsby https://css-tricks.com/currently-reading-progressive-web-apps-by-jason-grisby/ https://css-tricks.com/currently-reading-progressive-web-apps-by-jason-grisby/#comments Fri, 03 May 2019 14:27:42 +0000 http://css-tricks.com/?p=287166 I’ve been reading Jason Grigsby’s new book on progressive web apps this past week and it’s exciting. Jason explains what PWAs are and how they work while while doing a bang-up job covering the business case for using them them, …


Currently Reading: Progressive Web Apps by Jason Grigsby originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
I’ve been reading Jason Grigsby’s new book on progressive web apps this past week and it’s exciting. Jason explains what PWAs are and how they work while while doing a bang-up job covering the business case for using them them, too. But perhaps you might be thinking that a PWA isn’t necessary for the project you’re working on right now. Well, Jason argues that progressive web apps are for everybody:

Should your website be a progressive web app? The answer is almost certainly yes. Even if you don’t think of your website as an “app,” the core features of progressive web apps can benefit any website. Who wouldn’t profit from a fast, secure, and reliable website?

One of the challenges I’ve experienced when thinking about how to apply a progressive web app to a project I’m working on is figuring out what content to cache. Should the homepage be cached? Do we make a custom offline page? What is useful information to provide a user in that context?

Jason goes there, too, and even describes how he tackles that for his own projects:

For cloudfour.com, we chose to only cache recently viewed pages because the main reason people come to our site is to read the articles. If we tried to anticipate which articles someone would want offline access to, we’d likely guess incorrectly. If we precached top-level pages, we might force people on a metered network connection to download content they would never look at…

That makes a ton of sense to me and I realize that the offline cache should probably be different depending on the situation and the website. For example, maybe a design agency website could replace the big flashy homepage with an offline page that only shows the phone number of the agency instead. Or perhaps a restaurant website could cache the food menu and make that experience offline, but remove all the images to make sure it’s not too impactful for folks on those metered networks.

Anyway, I think that Jason’s book is wonderful as it reveals to us all this complexity and a whole new set of opportunities to improve the design and experience of our websites, which, by the way, is something we should strive for in this new and exciting age of web app development.


Currently Reading: Progressive Web Apps by Jason Grigsby originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
https://css-tricks.com/currently-reading-progressive-web-apps-by-jason-grisby/feed/ 2 287166
Foreword for CSS In Depth https://css-tricks.com/foreword-for-css-in-depth/ https://css-tricks.com/foreword-for-css-in-depth/#comments Fri, 18 May 2018 19:13:04 +0000 http://css-tricks.com/?p=270803 Keith Grant recently released a brand new book on CSS: CSS in Depth. If you’re looking for a book focused specifically on learning CSS, you’ve found it. I was happy to write the foreword for it, which I’ll republish …


Foreword for CSS In Depth originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
Keith Grant recently released a brand new book on CSS: CSS in Depth. If you’re looking for a book focused specifically on learning CSS, you’ve found it. I was happy to write the foreword for it, which I’ll republish here.


“A minute to learn… A lifetime to master.” That phrase might feel a little trite these days, but I still like it. It was popularized in modern times by being the tagline for the board game Othello. In Othello, players take turns placing white or black pieces onto a grid. If, for example, a white piece is played trapping a row of black pieces between two white, all the black pieces are flipped and the row becomes entirely white.

Like Othello, it isn’t particularly hard to learn the rules of CSS. You write a selector that attempts to match elements, then you write key/value pairs that style those elements. Even folks just starting out don’t have much trouble figuring out that basic syntax. The trick to getting good at CSS, as in Othello, is knowing exactly when to do what.

CSS is one of the languages of the web, but it isn’t quite in the same wheelhouse as programming. CSS has little in the way of logic and loops. Math is limited to a single function. Only recently have variables become a possibility. Rarely do you need to consider security. CSS is closer to painting than Python. You’re free to do what you like with CSS. It won’t spit out any errors at you or fail to compile.

The journey to getting good at CSS involves learning everything CSS is capable of. The more you know, the more natural it starts to feel. The more you practice, the more easily your brain will reach for that perfect layout and spacing method. The more you read, the more confident you’ll feel in tackling any design.

Really good CSS devs aren’t deterred by any design. Every job becomes an opportunity to get clever, a puzzle to be solved. Really good CSS devs have that full and wide spectrum of knowledge of what CSS is capable of. This book you have is part of your journey to being that really good CSS dev. You’ll gain that spectrum of knowledge necessary to getting there.

If you’ll permit one more metaphor, despite CSS going on a couple of decades old, it’s a bit like the wild wild west. You can do just about whatever you want to do, as long as it’s doing what you want. There aren’t any hard and fast rules. But because you’re all on your own, with no great metrics to tell you if you’re doing a good job or not, you’ll need to be extra careful. Tiny changes can have huge effects. A stylesheet can grow and grow and become unwieldy. You can start to get scared of your own styles!

Keith covers a lot of ground in the book, and every bit of it will help you become a better CSS developer and tame this wild wild west. You’ll deep dive into the language itself, learning what CSS is capable of. Then, just as importantly, you’ll learn about ideas around the language that level you up in other ways. You’ll be better at writing code that lasts, is understandable, and performant.

Even seasoned devs will firm up their skills here. If you find yourself reading about something that you already know, you’ll firm up your skills, affirm your knowledge, and find little “oooo” bits that surprise you and extend that base.


Here’s that link to buy it again.


Foreword for CSS In Depth originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
https://css-tricks.com/foreword-for-css-in-depth/feed/ 1 270803
Server-Side Visualization With Nightmare https://css-tricks.com/server-side-visualization-with-nightmare/ https://css-tricks.com/server-side-visualization-with-nightmare/#comments Tue, 24 Apr 2018 13:36:36 +0000 http://css-tricks.com/?p=269935 This is an extract from chapter 11 of Ashley Davis’s book Data Wrangling with JavaScript now available on the Manning Early Access Program. I absolutely love this idea as there is so much data visualization stuff on the web …


Server-Side Visualization With Nightmare originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
This is an extract from chapter 11 of Ashley Davis’s book Data Wrangling with JavaScript now available on the Manning Early Access Program. I absolutely love this idea as there is so much data visualization stuff on the web that relies on fully functioning client side JavaScript and potentially more API calls. It’s not nearly as robust, accessible, or syndicatable as it could be. If you bring that data visualization back to the server, you can bring progressive enhancement to the party. All example code and data can be found on GitHub.

When doing exploratory coding or data analysis in Node.js it is very useful to be able to render a visualization from our data. If we were working in browser-based JavaScript we could choose any one of the many charting, graphics, and visualization libraries. Unfortunately, under Node.js, we don’t have any viable options, so how otherwise can we achieve this?

We could try something like faking the DOM under Node.js, but I found a better way. We can make our browser-based visualization libraries work for us under Node.js using a headless browser. This is a browser that has no user interface. You can think of it as a browser that is invisible.

I use Nightmare under Node.js to capture visualizations to PNG and PDF files and it works really well!

The headless browser

When we think of a web-browser we usually think of the graphical software that we interact with on a day to day basis when browsing the web. Normally we interact with such a browser directly, viewing it with our eyes and controlling it with our mouse and keyboard as shown in Figure 1.

Figure 1: The normal state of affairs: our visualization renders in a browser and the user interacts directly with the browser

A headless browser on the other hand is a web-browser that has no graphical user interface and no direct means for us to control it. You might ask what is the use of a browser that we can’t directly see or interact with.

Well, as developers we would typically use a headless browser for automating and testing web sites. Let’s say that you have created a web page and you want to run a suite of automated tests against it to prove that it works as expected. The test suite is automated, which means it is controlled from code and this means that we need to drive the browser from code.

We use a headless browser for automated testing because we don’t need to directly see or interact with the web page that is being tested. Viewing such an automated test in progress is unnecessary, all we need to know is if the test passed or failed — and if it failed we would like to know why. Indeed, having a GUI for the browser under test would actually be a hindrance for a continuous-integration or continuous-deployment server, where many such tests can run in parallel.

So headless browsers are often used for automated testing of our web pages, but they are also incredibly useful for capturing browser-based visualizations and outputting them to PNG images or PDF files. To make this work we need a web server and a visualization, we must then write code to instance a headless browser and point it at our web server. Our code then instructs the headless browser to take a screenshot of the web page and save it to our file system as a PNG or PDF file.

Figure 2: We can use a headless browser under Node.js to capture our visualization to a static image file

Nightmare is my headless browser of choice. It is a Node.js library (installed via npm) that is built on Electron. Electron is a framework normally used for building cross-platform desktop apps that are based on web-technologies.

Why Nightmare?

It’s called Nightmare, but it’s definitely not a Nightmare to use. In fact, it’s the simplest and most convenient headless browser that I’ve used. It automatically includes Electron, so to get started we simply install Nightmare into our Node.js project as follows:

npm install --save nightmare

That’s all we need to install Nightmare and we can start using it immediately from JavaScript!

Nightmare comes with almost everything we need: A scripting library with an embedded headless browser. It also includes the communication mechanism to control the headless browser from Node.js. For the most part it’s seamless and well-integrated to Node.js.

Electron is built on Node.js and Chromium and maintained by GitHub and is the basis for a number of popular desktop applications.

Here are the reasons that I choose to use Nightmare over any other headless browser:

  • Electron is very stable.
  • Electron has good performance.
  • The API is simple and easy to learn.
  • There is no complicated configuration (just start using it).
  • It is very well integrated with Node.js.

Nightmare and Electron

When you install Nightmare via npm it automatically comes with an embedded version of Electron. So, we can say that Nightmare is not just a library for controlling a headless browser, it effectively is the headless browser. This is another reason I like Nightmare. With some of the other headless browsers, the control library is separate, or it’s worse than that and they don’t have a Node.js control library at all. In the worst case, you have to roll your own communication mechanism to control the headless browser.

Nightmare creates an instance of the Electron process using the Node.js child_process module. It then uses inter-process communication and a custom protocol to control the Electron instance. The relationship is shown in Figure 3.

Figure 3: Nightmare allows us to control Electron running as a headless browser

Our process: Capturing visualizations with Nightmare

So what is the process of capturing a visualization to an image file? This is what we are aiming at:

  1. Acquire data.
  2. Start a local web server to host our visualization
  3. Inject our data into the web server
  4. Instance a headless browser and point it at our local web server
  5. Wait for the visualization to be displayed
  6. Capture a screenshot of the visualization to an image file
  7. Shutdown the headless browser
  8. Shutdown the local web server

Prepare a visualization to render

The first thing we need is to have a visualization. Figure 4 shows the chart we’ll work with. This a chart of New York City yearly average temperature for the past 200 years.

Figure 4: Average yearly temperature in New York City for the past 200 years

To run this code you need Node.js installed. For this first example we’ll also use live-server (any web server will do) to test the visualization (because we haven’t created our Node.js web server yet), install live server as follows:

npm install -g live-server

Then you can clone the example code repo for this blog post:

git clone https://github.com/Data-Wrangling-with-JavaScript/nodejs-visualization-example

Now go into the repo, install dependencies and run the example using live-server

cd nodejs-visualization-example/basic-visualization
bower install
live-server

When you run live-server your browser should automatically open and you should see the chart from Figure 4.

It’s a good idea to check that your visualization works directly in a browser before you try and capture it in a headless browser; there could easily be something wrong with it and problems are much easier to troubleshoot in a real browser than in the headless browser. live-server has live reload built-in, so now you have a nice little setup here when you can edit and improve the chart interactively before you try to capture it under Node.js.

This simple line chart was constructed with C3. Please take a look over the example code and maybe look at some of the examples in the C3 gallery to learn more about C3.

Starting the web server

To host our visualization, we need a web server. It’s not quite enough that we have a web server, we also need to be able to dynamically start and stop it. Listing 1 shows the code for our web server.

Listing 1 – Code for a simple web server that can be started and stopped

const express = require('express');
const path = require('path');
 
module.exports = {
  start: () => { // Export a start function so we can start the web server on demand.
    return new Promise((resolve, reject) => {
      const app = express();

      const staticFilesPath = path.join(__dirname, "public"); // Make our 'public' sub-directory accessible via HTTP. 
      const staticFilesMiddleWare = express.static(staticFilesPath);
      app.use('/', staticFilesMiddleWare);
     
      const server = app.listen(3000, err => { // Start the web server!
        if (err) {
          reject(err); // Error occurred while starting web server.
        }
        else {
          resolve(server); // Web server started ok.
        }
      });                        
    });
  }
}

The code module in listing 1 exports a start function that we can call to kickstart our web server. This technique, being able to start and stop our web server, is also very useful for doing automated integration testing on a web site. Imagine that you want to start your web server, run some tests against it and then stop it at the end.

So now we have our browser-based visualization and we have a web server that can be started and stopped on demand. These are the raw ingredients we need for capturing server-side visualizations. Let’s mix it up with Nightmare!

Rendering the web page to an image

Now let’s flesh out the code to capture a screenshot of the visualization with Nightmare. Listing 2 shows the code that instances Nightmare, points it at our web server and then takes the screenshot.

Listing 2 – Capturing our chart to an image file using Nightmare

const webServer = require('./web-server.js');
const Nightmare = require('nightmare');
 
webServer.start() // Start the web server.
.then(server => {
  const outputImagePath = "./output/nyc-temperatures.png";

  const nightmare = new Nightmare(); // Create the Nightmare instance.
  return nightmare.goto("http://localhost:3000") // Point the browser at the web server we just started.
    .wait("svg") // Wait until the chart appears on screen.
    .screenshot(outputImagePath) // Capture a screenshot to an image file.
    .end() // End the Nightmare session. Any queued operations are completed and the headless browser is terminated.
    .then(() => server.close()); // Stop the web server when we are done.
})
.then(() => {
  console.log("All done :)");
})
.catch(err => {
  console.error("Something went wrong :(");
  console.error(err);
});

Note the use of the goto function, this is what actually directs the browser to load our visualization.

Web pages usually take some time to load. That’s probably not going to be very long, especially as we are running a local web server, but still we face the danger of taking a screenshot of the headless browser before or during its initial paint. That’s why we must call the wait function to wait until the chart’s <svg> element appears in the browser’s DOM before we call the screenshot function.

Eventually, the end function is called. Up until now we have effectively built a list of commands to send to the headless browser. The end function actually sends the commands to the browser, which takes the screenshot and outputs the file nyc-temperatures.png. After the image file has been captured we finish up by shutting down the web server.

You can find the completed code under the capture-visualization sub-directory in the repo. Go into the sub-directory and install dependencies:

cd nodejs-visualization-example/capture-visualization
cd public 
bower install
cd ..
npm install
live-server

Now you can try the code for yourself:

node index.js

This has been an extract from chapter 11 of Data Wrangling with JavaScript now available on the Manning Early Access Program. Please use this discount code fccdavis3 for a 37% discount. Please check The Data Wrangler for new updates on the book.


Server-Side Visualization With Nightmare originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
https://css-tricks.com/server-side-visualization-with-nightmare/feed/ 2 269935
Creating a Book Cover Using JavaScript and p5.js https://css-tricks.com/creating-book-cover-using-javascript-p5-js/ Mon, 20 Mar 2017 12:07:47 +0000 http://css-tricks.com/?p=252847 I recently published a book and an interactive course called Coding for Visual Learners. It teaches coding to beginners from scratch using the widely popular JavaScript programming language and the p5.js programming library. Since p5.js a great and an …


Creating a Book Cover Using JavaScript and p5.js originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
I recently published a book and an interactive course called Coding for Visual Learners. It teaches coding to beginners from scratch using the widely popular JavaScript programming language and the p5.js programming library. Since p5.js a great and an easy to use drawing library, I wanted to make use of it to create the cover of my book and course as well. This is a tutorial on how to create this particular visual using JavaScript and p5.js.

Book Cover using p5.js (circling 1's and 0's around the title)

p5.js is a drawing & creative coding library that is based on the idea of sketching. Just like how sketching can be thought of as a minimal approach to drawing to quickly prototype an idea, p5.js is built on the concept of writing the minimal amount of code to translate your visual, interaction or animation ideas to the screen. p5.js is a JavaScript implementation of the popular library called Processing which is based on the Java programming language.

The concise nature of p5.js makes it a very easy library to learn. But don’t let this simplicity trick you into believing that p5.js has limited capabilities. p5.js has an impressive amount of functionality, history, and community behind it to make it a valuable learning investment if you ever wanted to create art, design, motion or interactive pieces using code. A p5.js program can be anywhere from a few lines of code to thousands.

You can use p5.js to build intricate data visualizations:

See the Pen p5.js data visualization by Engin Arslan (@enginarslan) on CodePen.

Or, generative art:

See the Pen p5.js generative art by Engin Arslan (@enginarslan) on CodePen.

In this tutorial, I will be assuming a bit of JavaScript knowledge like familiarity with if-else structures, arrays, etc. If you would like to brush up your JavaScript knowledge or would like to learn this powerful language from scratch I would highly recommend you to check out my book and the course Coding for Visual Learners. It is tailored for the absolute beginner.

I will also assume some level of familiarity with computer graphics so that concepts like coordinate systems or color modes don’t require too much explanation. But in case if anything is not clear, feel free to reach out to me and I will do my best to clarify things.

You can follow along with this write-up either using the p5.js editor on your operating system or use an online code editor. Here is a pen that can serve as a template for your p5.js projects.

Let’s get started!

Part One: p5.js Basics

setup & draw functions

Most p5.js scripts contain two function declarations called setup and draw. You will be writing all of your p5.js related code inside these two functions and p5.js will execute these functions for you in particular ways. It is important to understand how these functions are executed by p5.js since they form the backbone of any p5.js program.

  1. The setup function is where you will be writing code that is related to initialization of your program. Anything that is written inside the setup function gets executed once and it gets executed at the beginning of the program.
  2. The draw function is where you will be writing most of the drawing related functionality. draw function gets executed after the setup function and it gets executed continuously (close to 60 times, frames, a second by default) which lets you create all kinds of interactive and animated visuals using this library.

Given draw and setup functions are pretty essential to the workings of p5.js, this is the boilerplate code that you would need to use for almost every p5.js code you write.

See the Pen book-cover-step-01 by Engin Arslan (@enginarslan) on CodePen.

If you don’t explicitly instruct it, p5.js creates a canvas (the drawing area inside the web page that you will be using) using a default size which is probably too small for your purposes. That’s why you are calling the createCanvas function which creates a canvas explicitly using the given x and y dimensions. You are also calling the background function inside the draw function to be able to set a color for the canvas as well. This might not be necessary for boilerplate purposes but it helps with seeing the created canvas.

Colors & Shapes in p5.js

Color setting functions in p5.js, like the background function you are using here, works with either one, two, three or four arguments. A single argument creates a solid color using the given value for the R, G, and B (Red, Green, Blue) components. Calling a color setting function with a single value is same as calling it with the same value as three separate arguments. These two declarations below would create the same result:

background(150);
background(150, 150, 150);

A fourth argument, when provided, sets the alpha (transparency) for the color. A second argument, when is used as the last argument also controls the alpha of the color and hence the alpha of the shapes that you draw after it. Talking of shapes, let’s create a shape. Here is a rectangle, drawn by using the rect function.

See the Pen book-cover-step-02 by Engin Arslan (@enginarslan) on CodePen.

The first two arguments to the rect function set the position of the rectangle and the last two arguments are for setting the size. Notice how when used with the arguments 0 and 0, the rectangle is drawn to the top-left of the screen. 0, 0 is the origin point for the canvas and it resides at the top-left corner. Rectangle shapes are drawn from their top-left corner by default in p5.js. If you wanted to change this behavior, you can declare a function called rectMode with the p5.js variable CENTER to change the rectangle drawing mode. It makes sense to place this declaration inside the setup function since you will only have to do it once for the lifetime of a program.

See the Pen book-cover-step-03 by Engin Arslan (@enginarslan) on CodePen.

If you wanted to draw this rectangle right in the middle of the screen, you have a couple of options. You could provide it with the value 700/2 so that it would be using half of the width and half of the height. But hard-coding values like this is not a good programming practice. You could try sharing variables among the rect function and the setup and draw functions. But luckily, since placing things relative to the width and height of the canvas is a common operation, p5.js provides you with a shortcut. You can use the p5.js variables width and height to be able to get the current width and height of the canvas. Divide these variables by two to use them for the placement of the rectangle.

See the Pen book-cover-step-04 by Engin Arslan (@enginarslan) on CodePen.

So far, you know how to set the color for the background but haven’t seen how to set the color for the shapes yet. There are two functions that allow you to do so. One of them is the fill function that sets the fill color for the shapes that comes after this function declaration and then there is the stroke function that sets the color for the stroke.

How color functions work might feel bit unintuitive since they affect the shapes that come after the declaration and not before. To understand how they operate, you can think of calling these functions as setting the active color for the consecutive drawing operations.

Another related function is strokeWidth, which sets the width of the stroke of the shapes. You will be using all these three functions to create a transparent rectangle with white borders.

See the Pen book-cover-step-05 by Engin Arslan (@enginarslan) on CodePen.

You will also create a text in the middle of the screen. For this purpose, you will be using the text function. text function takes 3 inputs, the text to be drawn to the screen and the x and the y position for the text placement. You can also use the textFont function to set the desired font for the text.

See the Pen book-cover-step-06 by Engin Arslan (@enginarslan) on CodePen.

There are a couple of things to fix here. First of all, notice how the text is not center aligned. As you can guess by now, there is a function to set how text is aligned, called the textAlign function. You will be using the textAlign function in the setup function since you won’t be changing this property again. You will provide it with two arguments: CENTER, CENTER. This will make the text drawings to be horizontally and vertically aligned.

The second thing to notice is that the text shape is being affected by the fill and stroke values of the rectangle above but you probably don’t want to use these values when drawing the text. Let’s set new values before drawing the text to get rid of the previous values.

See the Pen book-cover-step-07 by Engin Arslan (@enginarslan) on CodePen.

To be able to adjust the stroke, you could have either make the stroke color to be transparent or set the strokeWeight to be 0. There is also a noStroke function that is used here which gets rid of the stroke altogether. It doesn’t really matter which one you choose in my opinion, they all have the same effect in this use case.

You will now adjust the shape of the rectangle to encompass this text a bit better. Also, you will make the background black for legibility purposes.

See the Pen book-cover-step-08 by Engin Arslan (@enginarslan) on CodePen.

Currently, the text and the rectangle is too small. You already know how to scale up the rectangle. To be able to change the size of the text you could be using a function called textSize. But you will instead use a p5.js transformation function, scale, to handle the scaling since it will allow you to control the scale for the rectangle and the text together in a more straightforward manner. Unfortunately, transformations are not very intuitive when working with p5.js so they require a further explanation.

p5.js transformation functions

Transformations in p5.js happen relative to the origin point. There is a scale function that you can use which would scale the shapes that come after itself by the given amount, but things will get scaled from the origin point (the top-left corner of the screen). This is rarely desirable. When working with shapes, you would generally want to scale them relative to their center point.

Notice how calling the scale function makes everything bigger but also displaces them since scaling is happening relative to the top-left corner.

See the Pen book-cover-step-09 by Engin Arslan (@enginarslan) on CodePen.

If only the shape was at the origin point then this scaling operation would have worked for our purposes. Luckily there is a way to achieve that. For this, you should be using the scale function alongside with the translate function. Here is how it works:

See the Pen book-cover-step-10 by Engin Arslan (@enginarslan) on CodePen.

You have set the x and y position for both the rectangle and the text to be 0. This moves the shapes to the origin point. Then you call the translate transformation function to move the shapes to their initial position at width/2 and height/2. This works because translate function actually doesn’t move the shapes, it moves the entire coordinate system. Now that the origin of the coordinate system is in the middle of the screen, you can call the scale function, which would do the scaling from this desired point.

Now if this sounds a bit convoluted to you, let me assure that you are not alone. Moving the entire coordinate system to transform a shape is not only an overkill for what you are trying to achieve but can also be impractical since it means that anything else that comes after these shapes will need to use this newly transformed coordinate system which adds a lot of complexity to the process. Let’s see it in an example by drawing a new shape.

See the Pen book-cover-step-10-B by Engin Arslan (@enginarslan) on CodePen.

As you can see, you are now drawing a circle using the ellipse function at the x and y coordinates of 120 and 0. But the problem is that even though the provided y value is at 0, you can clearly see that the circle is not at top of the screen but in the middle, which happens to be the new 0 value for the y-axis. This would be highly undesirable for most circumstances but luckily there is a way in p5.js to deal with it. Enter the push and pop functions!

push & pop

The p5.js push function allows you to create a new state and pop function restores the state to the previous conditions. This allows you to have completely different settings applied to individual objects without worrying those settings to affect the shapes that come after as long as you do everything in between a push and a pop call. Here is how it works:

See the Pen book-cover-step-11 by Engin Arslan (@enginarslan) on CodePen.

Perfect! All that transformation changes you are doing right now remains localized in between the push and pop function calls. It is important to note that you should always call push and pop functions together. Using one but not the other doesn’t make any sense. Now that you fixed the problems regarding transformations, you can get rid of the circle shape. One final thing you will be adding before finalizing this text on the screen is to add a bit of an animation to it. Let’s scale it up a little bit for the first 200 frames of the animation to add a bit more dynamism to the visual. For this purpose, you can use the frameCount p5.js variable. frameCount p5.js variable keeps track of the number of times the draw function is called during the lifetime of a p5.js program.

See the Pen book-cover-step-12 by Engin Arslan (@enginarslan) on CodePen.

The following code snippet is added to the program. If the frameCount is less than 200 it adds 1/400 of the current frameCount value to the current scale. The reason why you are using the number 400 is that when the frameCount is 200 you would like to have 0.5 added to the total scale. But this is not the most elegant or scalable way of tackling this problem.

if (frameCount < 200) {
  scale(1.5 + frameCount/400);
} else {
  scale(2);
}

One p5.js function that you can use to derive this incremental scaling value is the map function. map function maps the given value that is expected to be in between the given minimum and maximum range to a number in the desired minimum and maximum range. The following declaration:

map(frameCount, 0, 200, 0, 0.5);

will map the frameCount variable that is in between 0 and 200 to a value in between 0 and 0.5. Let’s make use of it inside the code:

See the Pen book-cover-step-13 by Engin Arslan (@enginarslan) on CodePen.

This is so much better. And the code is very scalable as well. You could just be changing the scaleFactor and maxLimit variables to adjust how much and how fast the text grows. In the next part of this walkthrough, you will be building the background effect of the final visual, which is arguably the more exciting part of this visual. But the parts you have seen so far should be enough to get you familiarized with the basics of p5.js.

Part Two: Creating the Ring Shapes

In this second part of the tutorial, you will learn about creating the animated, ring-like shapes in the background. But first, let’s move the text drawing code to its own function so that it doesn’t occupy so much space inside the draw function.

See the Pen book-cover-step-14 by Engin Arslan (@enginarslan) on CodePen.

This update didn’t introduce any functionality change but is only a structural update to the code to make it more legible. You won’t need the drawTitleText function for now, so you can comment it out to be able to focus on the background shapes.

You will use a JavaScript object to represent the numbers for the final visual on the screen. Using an object to create as shape makes it easier to think about the shape as an entity of its own with a certain set of properties and behaviors. It also helps with encapsulating the functionality that is relevant to the shape, under the shape itself, which is good for code organization.

Here, you are creating a JavaScript constructor function called Num to represent the numbers that are used in the ring. It takes a couple of arguments; a message for the shape to display, the x, y position, the rotation and the color values for the shape. You haven’t seen the rotate function before but it is pretty similar to scale or translate functions. As the name implies, it transforms the shape by rotating it.

function Num(msg, x, y, rot, clr) {
    this.x = x;
    this.y = y;
    this.rot = rot;
    this.msg = msg;
    this.color = clr;

    this.render = function() {
        push();
        fill(this.color);
        translate(this.x, this.y);
        rotate(this.rot);
        text(this.msg, 0, 0);
        pop();
    }
}

The constructor function has a render method that handles the drawing of the shape to the screen. You can now use this constructor function to initialize an instance of this shape object and draw it on the screen.

See the Pen book-cover-step-15 by Engin Arslan (@enginarslan) on CodePen.

A couple of things that are worth mentioning.

First of all, notice how the Num function is pretty generic. It could be used to render any text to the screen in a flexible manner. It is also easy to use since you can simply control the rotation by defining the desired rotation value instead of using push and pop functions externally.

Secondly, see how certain words are being avoided when declaring functions. You could have called the constructor function Number instead of Num but Number is an already existing function in JavaScript so you should try to avoid it. Things wouldn’t necessarily explode if you were to use Number but it is generally a good idea to not cause name conflicts. Also for the arguments, you are not using the rotate or color as parameter names as these are the names for built-in p5.js functions. If you are to use these names for arguments then you would not be able to use the functions that are using the same name in the context of this function. Learning how to avoid these names comes with practice.

Finally, notice how you are providing a rotation value of 90 to the number object, but the number doesn’t seem to have rotated 90 degrees. That’s because p5.js uses radians by default when performing rotations instead of degrees. You can set it to use degrees as the default rotation unit by calling the p5.js angleMode function with the DEGREES variable inside the setup function.

angleMode(DEGREES);

It is great that there is now a single number on the screen but the aim is to have several numbers in a ring formation. Let’s figure out how to do this for a single number and then you can scale the operation to do placement for an arbitrary amount of numbers.

See the Pen book-cover-step-16 by Engin Arslan (@enginarslan) on CodePen.

The code is growing in size! This is the code that is added for creating the ring layout.

var radius = 100;
var amount = 15;

push();
translate(width / 2, height / 2);

for (var i = 0; i < amount; i++) {
    rotate(i);
    var num = new Num(1, 0 + radius, 0, 90, 255);
    num.render();
}

pop();

Here we have a for-loop that creates a given amount of Num objects that are away from the current origin, by the given radius amount. This is currently only creating 15 objects. This is to illustrate a point. See how the spacing around the shapes is not even. This happens because transformation calls in p5.js (like translate, rotate, scale) have a cumulative effect. For example, these two calls that are listed below would result in a total translation of 20 pixels in the x-axis.

translate(10, 0);
translate(10, 0);

To remedy this you can use the push and pop so that the transformation effects remain localized and don’t accumulate. That should take care of the uneven spacing of shapes. You should also make it so that the shapes are evenly distributed around the imaginary circle. To do this you can just divide 360 (the total angle of a circle) with the number of shapes you have to derive how much you should rotate each shape to achieve an even distribution.

See the Pen book-cover-step-17 by Engin Arslan (@enginarslan) on CodePen.

Perfect, in the next step, you will be creating a function out of this ring drawing operation. You will make the function to accept radius and amount as arguments. Also inside the function, you will be generating an array of random numbers to be fed into the Num object so that you can pass a random value of 0 or 1 to the object, instead of always using number 1.

For this purpose, you will use the p5.js random function. Here is a snippet that generates a random floating point number in between 0 and 2 (excluding 2) that gets converted to an integer using the JavaScript parseInt function and gets pushed into an array.

var randomNumbers = [];
for (var i = 0; i <= amount; i++) {
    randomNumbers.push(parseInt(random(2), 10));
}

Now you can pass an item from this randomNumbers collection to the Num object instead of always using the number 1. Here is the entire code:

See the Pen book-cover-step-18 by Engin Arslan (@enginarslan) on CodePen.

The problem right now is that the p5.js random function is generating a random value for each draw function call but for our purposes, we would like these random values to remain the same throughout the execution of the program. To be able to do so you should use the p5.js randomSeed function. The randomSeed makes sure you are getting the same “random” values for the given seed value. You will make it so that the seed should be configurable from outside the function.

See the Pen book-cover-step-19 by Engin Arslan (@enginarslan) on CodePen.

The numbers are not flickering anymore. Since you created the function that draws a single ring, it is not hard at all at this point to draw multiple rings with varying amounts of Num objects using a loop. To keep the example simple, we are using a numeric constant to keep the density of the rings similar to each other.

See the Pen book-cover-step-19-B by Engin Arslan (@enginarslan) on CodePen.

You are almost done! In fact, I am going to just show the final code at this point, as it doesn’t contain anything you haven’t learned about.

Here are a couple of things that are updated in this version.

  • Updated the background for the Coding for Visual Learners Text so that it’s semi-transparent.
  • Introduced rotation to the rings.
  • Introduced randomness to the color of the Num objects as well.

See the Pen Coding for Visual Learners – Cover by Engin Arslan (@enginarslan) on CodePen.

In case you didn’t want the shape to be animated, you can just call a function called noLoop inside the setup function to only display the first frame of the animation. If you wanted to adjust the shape you can start off by tweaking the amount, spacing, radius and rotSpeed parameters.

I used the static image for my book cover but the animated shape to create animations for the course. To be fair, I also used Photoshop a bit for the placement of some of the elements but the base shape is created with JavaScript and p5.js which makes me happy as a programmer.


I hope you enjoyed this short introduction to p5.js! Feel free to reach out to me if you have any questions! You can find my website at enginarslan.com and I am on Twitter at @inspiratory.


Creating a Book Cover Using JavaScript and p5.js originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
252847
Clean Code JavaScript https://css-tricks.com/clean-code-javascript/ Wed, 11 Jan 2017 14:01:01 +0000 http://css-tricks.com/?p=249904 Inspired by Robert C. Martin’s book Clean Code, Ryan McDermott put together a repo with some software engineering best practices as they apply to JavaScript in particular. The repo has tons of great guidelines for beginning programmers, and good …


Clean Code JavaScript originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
Inspired by Robert C. Martin’s book Clean Code, Ryan McDermott put together a repo with some software engineering best practices as they apply to JavaScript in particular. The repo has tons of great guidelines for beginning programmers, and good reminders for seasoned maintainers.

I’m a particular fan of this style of teaching because it focuses on legibility as much as writing. This ensures that our codebases are friendly to the next developer who comes along, even if it’s ourselves.

To Shared LinkPermalink on CSS-Tricks


Clean Code JavaScript originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
249904
Resilient Web Design https://css-tricks.com/resilient-web-design/ Wed, 14 Dec 2016 12:58:47 +0000 http://css-tricks.com/?p=248980 Jeremy Keith released a new book, for free, on the web only:

This is not a handbook. It’s more like a history book.

To Shared LinkPermalink on CSS-Tricks


Resilient Web Design originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
Jeremy Keith released a new book, for free, on the web only:

This is not a handbook. It’s more like a history book.

To Shared LinkPermalink on CSS-Tricks


Resilient Web Design originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
248980
Demystifying Public Speaking https://css-tricks.com/demystifying-public-speaking/ Thu, 03 Nov 2016 18:51:27 +0000 http://css-tricks.com/?p=247412 A new book by Lara Hogan includes some of my favorite advice about public speaking:

As you stand on the stage, remember: your audience is anticipating you’ll be successful at giving this talk. To them, everything has been well thought-out


Demystifying Public Speaking originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
A new book by Lara Hogan includes some of my favorite advice about public speaking:

As you stand on the stage, remember: your audience is anticipating you’ll be successful at giving this talk. To them, everything has been well thought-out and prepared; they walk in assuming (rightly!) they’re going to learn something new or be inspired…and you’re the person who’ll show them how.

More, they want you to be successful and are quite forgiving. In my experience, you only lose them once you disrespect them (e.g. “Sorry if I’m not very prepared, I wrote this on the flight over here.” annnnnd you’ve lost me.)

Hey while you’re over at the A Book Apart store buying this, I heard this one is good.

To Shared LinkPermalink on CSS-Tricks


Demystifying Public Speaking originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
247412