Dynamic super classes (extends) in ES6

tl;dr

Create a class factory which allows dynamic super classes to by applied to an es6 class (dynamic inheritance). This will be transparent to a consumer — meaning they will interact with it in the same way as the initial class.

Problem statement:

I was recently working on some code which extended an asynchronous module to add some additional functionality. The class initially looked like this:

However, testing a module like this is difficult for two reasons.

  1. The async nature of the behavior is challenging to test and mock
  2. The explicit super class Fetcher which is imported in the module is difficult to override without reaching down into the prototype and manually modifying methods during the test. Yuck!

Solution:

Wrap the extending (child) class declaration with a function, which accepts a parameter for its super class, and a default parameter value. Then the inner class can be declared using the SuperClass parameter. This will allow the child class to reference either its default parent, or the custom super class explicitly passed in.

The child class then extends or overwrites any methods from super that are required. Finally, a new’d up instance of the child class is returned with the remaining arguments passed to the class factory function.

For consistency of use, we can force the function to be called using new, making the abstraction completely transparent to any consumer.

Now we can call the extending class (with no SuperClass property) and it will have its default and expected behavior:

Or, with the SuperClass property to dynamically set its parent:

Working Example

 

See the Pen dynamic super class by Michael Jasper (@mdjasper) on CodePen.

Adding mp3 files to a Create React App app

If you’re looking for the steps to include static files, like an mp3, to a create-react-app project — and use es6 import statements to use them in a component, here are the steps. This process will involve “ejecting” from create-react-app, so think about the implications of that before proceeding.

1) Eject from the create-react-app by running npm run eject. The create-react-app documentation describes the eject command

If you aren’t satisfied with the build tool and configuration choices, you can eject at any time. This command will remove the single build dependency from your project.

Instead, it will copy all the configuration files and the transitive dependencies (Webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except eject will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.

You don’t have to ever use eject. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.

2) Include the files you want to use somewhere in the src folder. Probably with the component which will be consuming them.

3) We need to modify our dev and prod webpack configs to allow the files to be import-ed by through webpack and included in the build folder. Add an entry to the exclude list which will test for the file. The exclude list should look like this:

Add a loader to the list of loaders for the file type you want to use:

Do this for both the dev and prod webpack files in the config folder.

3) Within the component file, you can now import the file you with to use, specifying the relative path to the file

4) Then you can use the file within your component. For the example of a mp3 file, you can create a new Audio element in the constructor, and play or pause it using some event handler and function

 

Simple React Examples

I ❤️  react, and have spent a bit of time teaching react concepts to others through bootcamp trainings, and university courses.

Here are a few examples of concepts and code I’ve written for students that might be useful for you too:

Simple Composable Drawer Component

Illustrates simple props.children composition, as well as composition with stateful components.

  • Smart component
  • composition
  • children

TODO app

Stateful component composition with user generated data. Illustrates animating-out changes to state when todos are removed from state.

  • Smart components
  • component lifecycle
  • event binding

Search with debounced input

Search-preview of the Google Books api. Illustrates a very simple debounce implementation for network request performance.

  • fetch
  • composition
  • debounce
  • performance

Higher Order Components

Use a higher order component to generalize a common task of fetching and loading data into a component.

  • composition
  • fetch
  • promises

props.children composition

Very simple composition example.

  • containers
  • composition

 

Getting Started with Data Visualization in React

A primary goal of data visualization is to communicate information clearly and efficiently via statistical graphics, plots and information graphics. Numerical data may be encoded using dots, lines, or bars, to visually communicate a quantitative message.Effective visualization helps users analyze and reason about data and evidence. It makes complex data more accessible, understandable and usable.

-https://en.wikipedia.org/wiki/Data_visualization

TL;DR: Use data visualization too:

  1. Communicate information clearly
  2. Visual communicate a quantitative message
  3. Help users analyze and reason about data and evidence
  4. It makes complex data more usable

Good and Bad Examples

A pie chart that shows the 100 most active “tweeters” of a particular hashtag? Terrible visualization. Measuring it against our criteria, it doesn’t effectively communicate a message, or enable any type of reasoning about the data — other than to reason that 100 is far to many data points for a pie chart.

Almost never use a pie chart -everyones stats teacher

A tree chart with shows the worlds defense budgets? Great visualization. It is clear and understandable, and illustrates a message to the viewer.

A map of the 2012 Electoral College results by state? I believe this is an excellent visualization. It shows not only the states votes, but shows the weight each state has in the electoral college. It is accessible to the viewer.

A chart of the 100 most popular websites per month? At a quick glance, which is most popular? Is it the largest, or closest to the center? Which is the largest anyway? This is an ineffective visualization.

Technologies to visualize data on the web

There are three ways the data can be presented/visualized on the web

  1. Images: Visualization is designed in a tool like photoshop, illustrator, or tableu
  2. CSS: Css properties, such as width or height determine the shape and size of objects which can represent data points.
  3. Javascript: Using a javascript library that will create SVG or Canvas elements, and add interactive behavior to them

Javascript visualization libraries

There are many popular visualization and charting libraries. Three very popular and robust are:

D3

http://d3js.org

https://www.npmjs.com/package/react-vis

Vis

http://visjs.org/

https://www.npmjs.com/package/react-graph-vis

Highcharts

https://www.highcharts.com/

https://www.npmjs.com/package/react-highcharts

Building a data driven chart in React step-by-step

We’re going to use Facebook’s excellent Create-react-app starter kit, so first, let’s create a clean install of CRA:

Then install dependancies

Let’s use d3 with the React-vis wrapper. First install the react-vis package into our project

At this time, there is an unmet dependency problem with will prevent the app from compiling, so also install the peer dependency

Finally, run the project

Now the project is running, we can consume the react-vis package in our app. In the “App.js” file (the main component rendered by the app at this time), import the react-vis components and css.

We are now ready to use the components from the react-vis package in our App. Somewhere in your app insert a element:

We can now look at the page in our browser and see the chart rendered:

Creating an API for our chart to consume

 

 

Front-end Series 3: Templating syntax review

  1. Template syntax families
  2. Binding simple values
  3. Binding values using Scope Blocks
  4. Grammars
  5. Parsing
  6. Consistency leads to Predictability
  7. Comparison of popular templating syntaxes
    1. String Insertion
    2. Iteration
    3. If

Templating syntax (and language syntax in general) is very interesting. How a template is written somewhat informs mental-model of how it behaves, and how the data should be structured.

The following is a syntax review of common features in front-end templating systems. This is an initial pass! If you see any errors or optimizations, please correct me in the comments and I’ll quickly correct them. Also, this isn’t a review of the (sometimes very extensive) templating engines themselves — just the template syntax.

Template syntax families

At a very high-level, template syntax falls generally into two families: element-attribute renderers, and inline-token renderers.

Element-attribute style syntax binds data, logic, and state to a template by attributes on an individual node:  <element directive="property" /> . These templates are often parsed using traditional DOM parsing techniques, looking for element attributes that match a set of defined directives for that framework.

In inline-token renderers, binding is performed by code (or expressions) in-place, using special tokens to set it apart from the markup: like  {{ , <@ , or  <% . These templates are parsed using string or pattern matching techniques on the tokens, then evaluating their contents.

These are general distinctions, and some templating frameworks use both syntax styles.

Binding simple values

Inline-token style syntax really shines when binding single values to a template:

Because the templates are parsed as strings, using pattern matching regular expressions to find tokens, the binding can occur anywhere within the template, making them very powerful:

Element-attribute syntax expressions bind simple data easily, but quickly become verbose and unwieldy when replacing complex content:

 Binding values using Scope Blocks

Many templates also include some logic expressions, such as  if, foreach, and  using. Inline-token expressions can be limited when working with logic blocks — one reason is scope management. Element-attribute syntax declares expressions on the elements themselves, which have a natural scope within the DOM tree: they start, end, and have children. This makes data binding when scope is required simple:

Inline-token expressions are parsed with pattern-matching and could occur anywhere, so the parser must maintain the scope of any logic blocks used in a template. Additionally, the template syntax must contain closing tags for each opening logic block.

Grammars

handlebars-grammarEach templating syntax comes with its own grammar — or structure. A study of language grammar is a post on its own (or a degree of its own!), but a brief look at grammar is useful to understand the different syntax of each templating framework.

A grammar is a logical structure that defines what is acceptable in a language. Although templating frameworks can have a grammar, they aren’t necessarily languages on their own.

Lets look at the handlebars templating framework:

A handlebars expression starts with the tokens  {{ , and contains three sections:

  • An optional additional  { token
  • An optional logic expression :  #with , #using , #if , #else , #unless
  • A variable or object

Once defined, a basic grammar can be represented as a regular expression. Regular expressions can be represented differently in different languages, but this one should be generic enough:

{{{?(#[a-z]+ )?[a-z]+.[a-z]*}?}}

Meaning:

  • Match the string  {{ (opening token)
  • followed by zero or one  { (unescape token)
  • followed by zero or one  #[a-z]  strings (logic directives)
  • followed by an  [a-z]  string (variable or expression)
  • Followed by zero or more  .[a-z] strings (dot-operator variables)
  • followed by zero or one  } (closing unescape token)
  • followed by the string  }} (closing token)

Grammars can be wildly complex, but these simple principles can be applied to any of the templating frameworks to get a better understanding of how they work.

Parsing

Regular expressions are not only useful for understanding how a templates syntax is structured, but are also used in parsing inline-token syntax templates.

Handlebars’ parser uses a technique which involves searching a template for the  {{ token, then “looking ahead” for the closing  }}, and saving everything between the two in a buffer. When the end token is found, the buffer contents are then parsed and types are returned based on their content.

The contents of those blocks are then passed again into the same parser, to look for further operators:

After the parser has finished iterating on the template string, it is left with a stack of logical operations and functions which are then supplied the data for rendering.

Consistency leads to Predictability

One of the keys to a language’s (and templating engine’s) success and adoption is consistency in syntax. Based on previous experience with a given syntax, a programmer should be able to successfully create new code without diving into the documentation. “If that similar structure took a key-value-pair before, I bet this one here does too.”

Inline-token syntax parsers self-enforce consistency of the language, due to the nature of the parser. It must find a specific token, followed by a set of allowable expressions, which themselves might contain expressions. It’s easy to remember that an underscore block always looks like this  <@= ... @>, because it must per the parser.

Element-attribute syntaxes have a harder time enforcing consistency, and it must be created through the framework creators insistence on following a pattern for their “language.”

A generic element-attribute syntax could consist of

Framework creators must choose a pattern for their element-attributes and insist that the pattern is followed for new directives that are added to the language.

Let’s create a pretend framework, called Bob. Bob’s starts simply, and only binds strings:

We continue to use Bob, and need to add some logic:

And later, repeating sections. Since repeat doesn’t really need a value, let’s write it like so:

Now we need to replace multiple attributes:

And finally, replace specific strings within attributes:

The moment a second programmer tries to implement Bob, it becomes clear that we’ve implemented a totally unpredictable syntax! Is a directive part of the attribute name ( bob-string="name"), or in the value ( bob="repeat")? What is the valid syntax for a  bob-bind attribute? A single value or a key-value pair? The  bob-replace value is JSON apparently?

Regardless of the frameworks speed or other technical features, a syntax implemented in this way will kill adoption.

Comparison of popular framework syntaxes

String insertion

angular
closure
handlebars
knockout
pure
underscore

Iteration

angular
closure
handlebars
knockout
pure
underscore

If

angular
closure
handlebars
knockout
pure
underscore

That’s all folks!

Templating frameworks are very useful, and their syntax is one of the main way which a programmer interacts with them. Understanding the differences that syntaxes and template philosophies can help you choose the right one for your use-case!

Arabic web design and web fonts

Going a little way towards displaying Arabic is a native way creates a delightful user experience. Arabic Web-fonts, layout, and language CSS help create that experience.

header

An Arabic speaking translator and web content-producer recently told me

The state of web support for Arabic and other right-to-left language speakers has historically been so poor, that making efforts to properly display their language can create an exceptionally delightful experience for the users.

In the course of development for a multi-language website, I’ve had the wonderful opportunity to explore some of the ways to create “delightful experiences” for these users, mostly focusing on font-selection and typography, and page layout.

Font choice and Typography

System Fonts

The fonts used on the web for Arabic are unfortunately still limited to the default Ariel, Verdana, Tahoma and most of the time the font used is Tahoma because it is the most legible on the web. – http://www.smashingmagazine.com/2010/09/19/showcase-of-web-design-in-the-arab-world/

Web Fonts

Although there are many beautiful Arabic fonts (from calligraphic to modern), the selection of web-font choice is limited. While latin web-fonts are widely available from Google Fonts, Typekit, and other similar services — Arabic fonts are only currently (April 2014) available in Google’s “Early Access” program. This program  showcases fonts that Google will consider mainstreaming with their other Web Fonts, if they are popular and get enough usage. Therefore, fonts in this program have no guarantee of long-term availability.

Many fonts are available from the Early Access program, the following is a curated list with previews of Arabic Fonts. Because of possible limited availability, I’ve provided the previews in image format. Visit my CodePen for full code previews.

Amiri

amiri

Droid Arabic Kufi

droid-kufi

Droid Arabic Naskh

droid-naskh

Lateef

lateef

Scheherazade

shaherazad

Thabit

thabit

Layout

Arabic is a RTL (right-to-left) language. Not only is the text read and displayed from right-to-left, but pages are layed-out right-to-left as well. Ideally, an Arabic translation of an English page would not only flip the text, but “mirror” as much of the page as possible.

mirror-site

CSS

There are a few CSS rules to keep in-mind when developing Arabic (and other RTL) language web-pages.

direction:ltr|rtl (docs) changes the text flow of block level elements and text. It will not, however affect the layout of the page.

float:right|left Remember to float left things right, and right things left

:before :after Some things (like icons) in pseudo-elements can be repositioned by changing :before’s to :afters. These will often require custom CSS as many pseudo-elements are positioned relatively to their parent.

Faded gradient separator bars

Here is a technique for creating both horizontal and vertical separator bars with pure css.

See the Pen Sexyline 2 – verticlal by Michael Jasper (@mdjasper) on CodePen

Using CSS3 radial gradients positioned off element, just the tip of the gradient is show, giving the line a nice shadowed/faded look:

This technique can be applied to <hr>  tags for semantic breaks in content, or they can be applied to any element or class as an effect.

See the Pen Sexyline 2 by Michael Jasper (@mdjasper) on CodePen

Properly aligning and wrapping image captions

Easily align and wrap captions to images of unknown size with two relatively unknown CSS properties.

I recently learned a new css trick to align and wrap captions properly to images of unknown size.  This is a common problem when dealing with any content management system that allows users to upload images to pages or articles.

The problem:

This is a caption of slightly longer length. It should wrap, regardless of the size of the image.

The css solution:

This is a caption of slightly longer length. It should wrap, regardless of the size of the image.

Voilà!

Front-end Series: JavaScript debugging tips and tricks

Note: many of these tips are written with Chrome in mind, but are applicable to any modern browser with developer tools.

  1. Understand what is happening in your code
  2. Set and use Breakpoints
  3. Use the Console api
  4. De-minify
  5. Modify scripts locally
  6. Use a Unit-Testing framework

1. Understand what is happening in your code

A prerequisite to debugging is understanding the code in question. Before debugging, you should be able to answer: what is the purpose of this function? What should the parameters be? How will this line affect local and global variables?

Basically, run the code mentally before trying to debug.

2. Set and use Breakpoints

Once you understand how the code should function, set execution breakpoints at key places. When reached, a breakpoint will pause the execution of script on that line. You can then “step-through” the code one line at a time. This view also allows you to inspect any global or local values to ensure they are what you expect them to be. Often times, you can observe a variable which should contain a value, but is undefined. From there it is easy to trace your way back up and see where the error is occurring.

Breakpoints can be set by clicking on the line-number in the script tab of chrome developer tools, or programmatically using the  debugger; directive.

debug-breakpoints

Use the console api

While sprinkling a few  console.log ‘s sparingly throughout your code can be useful, the console api has many useful functions that might serve the purpose better. Here are a few console api methods I have found useful:

console.dir

Displays all the properties of an object.

console.dir

 console.table

Formats arrays and objects as tables, and allows sorting on columns.
console.table

console.time

Starts and stops a timer (string tag based), logs time (in ms) of intermediate code.
console.time

console.memory

Returns heap information for this process.
console.memory

console.trace

Returns a stack trace for the function where it is called.

console.trace

4. De-minify

When debugging, it can be very frustrating to see an error like:

When at all possible, swap out the minified version for a full expanded and commented version of the script.

When a full version is not available, Chrome’s developer tools come to the rescue. The curly brace button below the script will automatically expand lines for better breakpointing and debugging. It does not however rename obfuscated variable names.
de-minify

Minification bugs

Every so often, you can run into the maddening bug of a full script working, and the same minified script breaking. Luckily, these bugs often attributable to one of a few small problems (mostly having to do with missing semicolons).

For example:

These bugs can also creep in from preceding scripts, or when multiple scripts are concatenated together. This is the reason that jQuery plugins typically start with a  ; . It is a preventative measure against misbehaving code above it.

5. Modify scripts locally

Chrome allows you to modify script files and run them locally. Simply double click into source file, type, and CTRL-S to save. Not much more to explain, but very useful trick!

6. Use a Unit Testing framework

There are a handful of very good third-party unit-testing frameworks for JavaScript, each with their own philosophy and syntax.

See this great Stack Overflow post for many more.

Front-end Series: Part 1 – Architecture

This is part 1 in the Front-end Series. As a front-end developer at a large organization, I work daily on architecture, performance, automation, localization, and compatibility, and other topics which I will share during this series. Feel free to post topic ideas in the comment section!

Large scale web application architecture is much more than a server and a /www folder. The build process can scale with need, but the basic setup contains building assets to a development area, then production environment, caching, and delivery via cdn.

This is example architecture diagram — showing building to different environments, pushing to cdn boxes, and caching.

Front-end-archetecture

Building static assets via source control

Working with other developers at any scale necessitates use of a version control system. Whether Git, Subversion, Mercurial, or the next new hotness, a DVCS is an absolute must. After developing in a local environment, assets are pushed to a development version-controlled server.

The assets here are never directly used by the application, but are pushed to a CDN server (or a mock-cdn for development).  The source control and CDN can be can be synchronized by a few different methods:

  • CRON task that rebuilds one folder from the other
  • Post-commit hook that runs similar script
  • 3rd party build software, like Anthill

Server environments, or “lanes”

It’s necessary to duplicate asset servers for different audiences. The most basic are:

  • Development
  • Testing
  • Staging
  • Production

A typical pipeline is:

  • Assets are developed locally
  • Files are moved into the Development environment to be integrated with other developers work and preliminary tested
  • Quality Assurance tests the application.  Feedback provided to developers (loop back)
  • Once testing is successful,  the assets are moved to the staging server, which serves as a place for stakeholders to preview the application, and approve it for production
  • When okay-ed, the files are moved to production where they are publicly accessible. They are now “live”

Caching and Content Delivery

Linking directly to assets on a server is an excellent way to kill your site, when it goes viral (the Reddit hug of death, or the slashdot effect). The most basic level of defense is on server caching. On smaller sites, this can be an effective protection. Many CMS’s (like WordPress) have plugins that can caching dynamic content (php generated files saved as static html). WP-SuperCache is an excellent example of this layer of defense.

The second layer of defense is a Caching Appliance. This is a server (or cluster of servers) that specializes in serving static files with extreme speed. This appliance has only one function, which allows it to maximize its resources for the one purpose of serving content.

The top layer for serving files is utilizing a Content Delivery Network to distribute and cache assets globally.  At it’s core, a CDN is a network of servers placed in strategic locations around the world, each containing duplicate and synchronized files. These servers, ideally located on backbone connections, serve files to customers quickly in different areas of the globe. For example, a user in France is served assets from a UK server, rather then making the transatlantic trip to Virginia.

For smaller sites (such as this one) there are free or inexpensive CDN options. This website uses CloudFlare to serve static assets to viewers (your CSS file was probably served from this CDN, reducing my server load. Yay!) An excellent CDN for large-scale websites is Akamai. You’ve almost certainly been served assets from Akamai (Facebook, Adobe, Microsoft, and many more use it).  If you’re in the market, take a look at CloudFront as well.

So there you have it: The front-end build and architecture for one of the largest publishing organizations in the world!

Big Picture

What I’ve described is the front-end server and building process for a large scale web application. This setup will typically be mirrored by the application codebase (back-end).

back-end-architecture

Comments, feedback or criticism? Let me know in the comments: