Kahlil
Lechelt

Time is an illusion, lunchtime doubly so.

learnrx.io →

Finally some human-friendly docs about RxJS. Huge effort by Brian Troncone.

Switching To hyperHTML And HyperHTMLElement

When starting work on Static Site CMS I originally planned on using Custom Components and lit-html instead of a JavaScript framework.

In the process of setting up my development environment I was a little annoyed to realize that lit-html can only be used with ES Modules and not with CommonJS modules. Since Electron uses CommonJS that is a requirement for my current project.

I heard that hyperHTML basically does the same thing as lit-html so I went and checked it out.

I was very happy to discover that not only does hyperHTML do basically the same thing as lit-html, it also supports all module types and as a bonus there is a little ecosystem around it that enhances Custom Elements and even supports server side rendering. What?! Nice! See a chart that compares the two right here.

HyperHTMLElement is a Custom Element subclass that is exactly what I just had started to do with LitElement, only better. The author @WebReflection knows these emerging web standards very well and does an amazing job making them really usable and useful today.

In turn @WebReflection is not a fan of TypeScript so neither hyperHTML nor HyperHTMLElement have type definitions. Since I decided to use TypeScript in my app I created a simple type definition file for HyperHTMLElement. I didn’t add it to @types yet but you can grab it from my project right here.

All in all lit-html and hyperHTML are very similar in what they do. The biggest difference at the moment is that hyperHTML is more complete and feels more mature, not to mention the addition of HyperHTMLElement and server side rendering via ViperHTML.

Working Title: Static Site CMS

Product development has always been of huge interest to me. I love creating something with web technologies that solves a problem and iterating on it. That is basically what I do at work but I always wanted to have my own thing.

During the last year I have played around with a couple of ideas while trying out different JavaScript frameworks. Altogether I think I must have at least started working on 4 or 5 things. Among those I made two small barely usable products: TinyDraft and Kaf. They are very simple and incomplete but they do implement a very minimal use case quite OK.

I always end up hitting a wall when it comes to adding a backend with database, authentication and authorization. Typically I would use services for that. But since I really just get to work on my personal stuff on the road during my commute I can’t easily add any services. My connectivity is very limited during those train rides.

I also tried out using Hoodie which is great to work with locally but deploying a Hoodie backend wasn’t trivial to me and ultimately I only really want to think about the frontend side and have the backend just work and be there in local development as well as in production.

So these products are going nowhere.

I realized in order to build and iterate on anything during my very limited free time I have to remove as much friction as possible. The solution to that problem came to me just a couple weeks ago.

Recently I hooked up NetlifyCMS to my site. It uses Netlify’s auth service and GitHub to add posts to your site. If you set up automatic deployment via GitHub on Netlify that is a really great solution to adding posts to a static site through a nice UI.

But here I had the same problem. I write my stuff on the road and I can’t rely on being online. But I really liked some of the functionality that NetlifyCMS provided, namely the scaffolding of posts, easy Front Matter editing as well as the automatic Git commit functionality.

I thought to myself: “That’s cool, I wish I had that for the desktop.”

That’s the moment when it clicked! I could make this myself with Electron! I actually love working on Electron apps and I would be solving a problem for myself as well as removing my above-mentioned friction from app building. This type of Electron app can be developed without being online at all. Hooray!

I have started working on this over the holidays and I am developing it in the open, the code is on GitHub and I will be posting about my progress here.

For now the product really does not have a name. The working title is Static Site CMS.

The empty state

The empty state

In my next post I will be writing about the setup I am using to build it.

Template Instantiation

Happily stumbled upon this little video by @dassurma and @jaffathecake. Apparently there is a template instantiation proposal out there somewhere that would add lit-html / hyperHMTL - like functionality to the template element.

This would be huge if it made it into the platform. This would mean that Web Components would be complete because, as I outlined before, the only web standard missing for them to be useful out of the box is an API like lit-html that allows for their DOM to be rendered over and over again in an efficient way.

Here the (extremely short) video for your viewing pleasure:

ZeroFux - A Stateless Unidirectional Data Flow Implemented With Custom Events

Undirectional Data Flow, Flux, Redux, Whateverux is essentially this:

This allows you to manage interactions in your UI in a stateless and synchronous manner.

As a developer, the only thing that really interests you are the actions and the reducers, all the rest is just implementation detail. Actions and reducers shape the app‘s state.

In the following I describe a really simple way how you can implement this type of state management with Custom Events.

Actions

First let’s define what an action is. An action is a JavaScript object that has one required property with the key „type“ and two optional ones with the keys „payload“ and „error“. Here an action defined as a TypeScript interface.

{
  type: string;
  payload?: any;
  error?: boolean;
}

I think we can agree that the JavaScript community mostly agrees on this definition pioneered by Redux, maybe minus the error property. I stole that from redux-observable.

Dispatcher

So, now that we have actions how do we dispatch them through the dispatcher and what is the dispatcher?

We want to use Custom Events. Those event get dispatched on a DOM element with the dispatchEvent method. That means our dispatcher is a DOM element. It is really not important which one but let’s just use the body element since that element is present on any web app.

const dispatcher = document.querySelector('body');

Great. Now that we have the dispatcher how do we dispatch an action? That’s where the Custom Events come in. We‘re using Custom Events because they allow us to add Custom event data (which we will, sneakily, call actions).

dispatcher.dispatchEvent(
  // The first argument of the Custom Event is 
  // the event name. The event name is the same
  // as the action type.
  // The second argument are options.
  new CustomEvent('SOME_ACTION', {
    // Here goes our custom data, the action object.
    detail: { 
      // Action type and event name are the same.
      type: 'SOME_ACTION', 
      // Here goes the optional data.
      payload: someData, 
      error: false,
    },
  })
)

So now that all these actions are being piped through one point in the DOM via Custom Events, we can match them to reducers.

In your component that expects some some state, take an array of action names that the component is interested in and set up event listeners. In the event listeners callback match a reducer with the same name per action to update the component state:

// Some example action names.
const ACTIONS = [
  'INCREMENT',
  'DECREMENT',
  'ADD_TEN',
];

...

// As a convention components need a setter and 
// a getter for the state property. 
// That allows you to call a render function or similar
// whenever state is set to a new value.
set state(s) {
  this._state = s;
  // Use lit-html or some other library that efficiently
  // can update DOM in the render function. 
  this.render();
}

get state() {
  return this._state;
}

// This is a method on some component.
setReducers() {
  ACTIONS.forEach(ACTION => {
    if (reducers[ACTION]) {
      // Again we are using the reference to the body
      // element as the dispatcher.
      dispatcher.addEventListener(ACTION, e => {
        // Reducers are kept in an object and matched
        // via action name.
        this.state = reducers[ACTION](e.detail, this.state);
      });
    } else {
      throw new Error(
        `Please add a reducer for the "${ACTION}" action.`
      );
    }
  });	
}

...

The ZeroFux Library

The code above is a little boilerplate-y so let’s make a simple library out of it. No Flux plus no Redux euquals ZeroFux:

export class ZeroFux {
  constructor(element) {
    if (element) {
      this.dispatcher = element;
    } else {
      this.dispatcher = document.querySelector('body');
    }
  }

  // The dipatch method takes an action argument
  // of the previously defined action type.
  dispatch(action) {
    this.dispatcher.dispatchEvent(
      new CustomEvent(action.type, {
        detail: action,
        // In case you set a custom dispatcher element
        // and want them to bubble.
        bubbles: true,
        // In case your custom dispatcher is in the
        // Shadow DOM and you want them to bubble between
        // the borders or Shadow DOM and regular DOM.
        compose: true,
      })
    )
  }

  // This method takes an array of action types
  // that can influence a component's state,
  // an object with reducers with the same names
  // as the action types and a reference
  // to the component on which we want to set
  // the state propery.
  setReducers(actionTypes, reducers, component) {
    actionTypes.forEach(actionType => {
      if (reducers[actionType]) {
        this.on(actionType, e => {
          const action = e.detail;
          component.state = reducers[actionType](component.state, action);
        });
      } else {
        throw new Error(
          `Please add a reducer for the "${actionType}" action.`
        );
      }
    });
  }
}

export const zeroFux = new ZeroFux();

🎉 tadaa!

It’s up on Github and npm right now if you want to try it.

You can see ZeroFux in action in this CodePen.

Side Effects

“Ah-haaa! How do we manage side effects with ZeroFux?”, you may ask. Well, there is actually a simple zero-fux way to deal with this.

Since these custom events are all streaming through one point in the DOM, the point that we can access via zeroFux.dispatcher, we can just listen to these events separately and fire effects on certain actions.

These side effects have to fire an action themselves when they are done with whatever they were doing. That’s how we introduce data coming from theses side effects synchronously back into the the data flow.

This is how your SideEffects class could look:

import { zeroFux } from 'zero-fux';

export class SideEffects {
  run() {
    const on = zeroFux.dispatcher.addEventListener;
    on('SOME_ACTION', () => { 
      someApi.doSomethingAsync()
        .then(data => zeroFux.dispatch({
          type: 'SOME_RESPONSE_ACTION',
          payload: data,
        }));
    });
    
    ...
  }
}

See it in action in the CodePen.

Conclusion

So there it is, a bare bones, straight forward unidirectional data flow implementation using custom events.

It uses the same principle I have also used in oddstream, a unidirectional data flow library implemented with RxJS: matching a “stream of actions” to reducers. This just has zero dependencies and is practically no code.

In Node this could be implemented using EventEmitter.

I think this solution for a unidirectional data flow could be used in apps of any size because ultimately all you have to manage and think about is actions and reducers, same as in any other unidirectional data flow solutions.

Use Web Components To Build JavaScript Apps

Web Components are generally described as “custom, reusable, encapsulated HTML tags” that encapsulate some DOM, some styling and behavior implemented with JavaScript.

I don’t understand why this use case is pushed so extensively when Web Components offer a perfectly good component abstraction for building complete JavaScript web apps.

I’m not so much interested in Web Components for individual new custom tags à la <google-maps></google-maps> or something. I’m interested in using Web Components for building full fledged JavaScript apps with a component-tree architecture, unidirectional data flow and efficient DOM rendering. And I think they are perfect for it!

And they are perfect for it now.

Web Components are typically described as the combination of the following four web standards:

First of all let’s forget about HTML Imports. Vendors don’t agree on them, they block rendering and honestly they feel super clunky to me.

We have ES Modules. Web Components don’t work without JavaScript anyway so let’s import them via ES Modules or bundle them up and serve them from a server or CDN.

Mikeal Rogers actually already built a solution for himself that allows him to write Web Components in JavaScript, publish them to npm and automatically serve them automatically on a CDN via unpkg.

That’s totally the way to go. But he also talks about isolated components as far as I can see.

Like I said I think they are the perfect building blocks for building JavaScript web apps how we build them today with React, Vue, Angular and so on.

My opinionated list of things that of what Web Components consist looks like this.

Custom Components are the heart. They are the building blocks for web applications. Shadow DOM should always be used for encapsulation and HTML Template should be used to efficiently build the DOM for the component.

The developer should really just interact with a Custom Component class without having to think about Shadow DOM and the HTML Template.

What Custom Components are missing is an efficient way to automatically update the DOM on component state changes.

Basically something like React‘s vDOM.

But adding a vDOM library doesn’t feel right because one of the big wins of Web Components is that you don’t have to manage a separate DOM next to the one in the browser. So what to do?

While watching the talks of the 2017 Polymer Summit I stumbled on this talk about lit-html and I was impressed by it right away.

It’s a genius little 2k-sized library that goes with Web Components beautifully. It allows you to build the DOM for your Custom Component with a tagged template literal.

Tagged Template Literals are a JavaScript standard. They are Template Literals that are marked by a function name. The string contained in the Template Literal is processed by that function before it’s returned. In the case of lit-html it looks like this:

const markup = html`
  <div>
    ${state.someValue}
  </div>
`;

lit-html comes with the html-function to use with Template Literals and with a render function that efficiently renders updated state to the DOM.

Under the hood lit-html uses HTML Template to efficiently clone the markup. The html function returns something called a TemplateResult which gets passed to the render function along with the DOM element to which it should be rendered. lit-html remembers the dynamic parts of the template and makes sure these get updated when needed. The static parts of the template are always just rendered once.

According to this talk from the Google Web Summit lit-html fairs pretty well performance-wise.

I think it is the perfect library for managing DOM updates of Custom Components because it it just uses Web Standards to do its job and refrains from maintaining a second DOM tree in order to be fast.

With a little luck some sort of efficient DOM updating will also land in the browser as a standard but for now this is great!

So in conclusion: the perfect web app building block for me is just a Custom Component that uses a base class that hides away creating the Shadow DOM and the usage of lit-html.

I made such a subclass for my little Café search app, it’s called LitElement and it is str8 🔥.

// A super chill custom element subclass with
// some nifty default behavior.
export class LitElement extends HTMLElement {
  constructor() {
    super();
    // Initialize the state variable.
    this.state = {};
    // Create the Shadow DOM for this element.
    this.attachShadow({ mode: 'open' });
    // Just a convenient alias for addEventListener
    this.on = this.addEventListener;
  }
  
  // The state getter.
  get state() {
    return this._state;
  }
  
  // The state setter calls the 
  // invalidate function, which invalidates the
  // state and calls render.
  set state(s) {
    this._state = s;
    this.invalidate();
  }

  // This function makes sure that 
  // the lit-html render function is called 
  // when invalidate() is called. 
  // But it makes sure it is always called 
  // on next tick so that render calls are 
  // batched.
  invalidate() {
    if (!this.needsRender) {
      this.needsRender = true;
      Promise.resolve().then(() => {
        this.needsRender = false;
        // this.render is the render function of 
        // the Custom Component that subclasses this
        // class and it returns a TemplateResult created
        // with the lit-html html-function and a Tagged 
        // Template Literal. 
        // The location to which the DOM is rendered to is
        // always the shadow root of the component.
        render(this.render(this.state), this.shadowRoot);
      });
    }
}

❤️ the platform.

Web Components And The CMD-R Development Workflow

A couple of months ago I stumbled across Mikeal Rogers’ article I’ve seen the future, it’s full of HTML. in which he lays out his reasons why he started to dive into Web Components for the web apps he is working on right now and hinted to the workflow he uses.

His enthusiasm for Web Components is infectious and because I have a lot of respect for Mikeal and his work, his article was a strong signal for me personally that Web Components might be something to take a closer look at.

I have ignored them so far because the little I knew about them seemed a little gross to me: HTML imports? HTML, CSS and JavaScript in one file? Ewww. Who wants to write code like that?

Polymer didn’t help a lot either: all I heard was Polyfills and Bower and WTF is Shady DOM?

And oh yeah everybody kept screaming “OH PRAISETH OUR NEW LORD AND SAVIOR HIS HOLINESS THE REACT”.

So I kept ignoring it.

But then Mikeal came along and showed how to write Web Components purely with JavaScript. He said the only tooling he uses is a little Browserify in order to package the component so he can distribute it via npm and automatically serve it via a CDN.

I was like: “No tooling? Hmmm… that sounds pretty sweet.”

A few weeks ago I took some time to write a tiny application just with Web Components. I used no tooling, no compilation no polyfills, no nothing. Just Chrome, ES 2015+, ES Modules, <template>, Custom Elements and an “actions up data down” data flow with Custom Events.

I used the CMD-R (CTRL-R on Windows) web development workflow as Alex Russel calls it.

Now that’s a developer experience 😉!

It was surprising to me how freeing it was to be able to use modern syntax, modules and a component architecture in the browser without any tooling. Not to mention the excellent debuggability since you are feeding the browser what you write directly.

The browser has become the only tool and even the only “framework” we need to write JavaScript apps.

Just write your app using Chrome and then make a bundle with dynamically loaded polyfills to make it work everywhere.

As it stands currently that latest versions of Google Chrome, Safari and Opera support these technologies natively, Firefox and Edge are lagging behind but working on it.

Netflix functions without client-side React, and it’s a good thing →

Jake Archibald on Netflix removing React from their landing page:

Netflix has shown you could start with React on the server, then activate the client side parts if you need them, when you need them, and where you need them.

I hope this starts to become state of the art.

Working Draft Podcast, Revision 314: DDD, CQRS und WTF →

In this episode of the German podcast Working Draft Golo Roden does a great job explaining what DDD (Domain-Driven Design), CQRS (Command Query Responsibility Segregation) and Event Sourcing is and how his new project wolkenkit can help developers applying those principles and patterns.

Why I wrote Just. by Angus Croll →

Just is a collection of dependency-free modules for common operations on Arrays, Collections, Strings, Objects and Functions started by @angustweets. “Do we really need something like that when we have Lodash?” you might ask.

Angus does a great job explaining why he started Just:

Just is designed for those who value easy to follow, debuggable utilities over version lotto and yak-shaving down the module tree. There’s nothing fancy or particularly clever here. You won’t find elaborate routines that optimize for trillion element arrays; just short, cohesive, readable code––the sort of helper functions we all inline in our projects every day because edge case optimizations that we’ll never need aren’t worth the overhead and the uncertainty of a sprawling dependency chain.

I Finally Understood Functions As A Service

Since I heard it for the first time, I was struggling to understand what “Functions As A Service” like AWS Lambda really is. I heard people explaining it on podcasts and read what it said on the AWS Lambda landing page but it just didn’t click.

Last week me and Henning recorded the lastest episode of our podcast REACTIVE. On that episode Henning talks about how he uses AWS Lambda and an AWS database to build an API for their app at work. This made me finally understand what this is all about.

They built the API by writing some code that parses request parameters, retrieves some data from the database and then sends that data back as JSON in the JSON API format. That code is the function that is being provided “as a service”.

That is it.

The HTTP layer, security and scalability is all provided by AWS services. Functions As A Service also means that you only pay for computing time when the function is used. When there is no requests to the API then you don’t pay.

This is an incredibly fast and efficient way to build an API that is production ready in no time.

On the podcast we also talked about how more and more of these “solved problems” like security and scalability will be packed up into some service and how the usage of them will certainly be very widespread in the not so distant future.

@codepo8 said it best on Twitter yesterday:

How Matt Mullenweg Single-Handedly Made Facebook Relicense React to MIT

OK, I have no proof that this is actually true, but it is a fun thought experiment / conspiracy theory. Here me out.

Facebook just announced that they are relicensing a few of their open source projects to the MIT license.

I am pretty sure this change will be extremely well received by everybody using React.

It will also ensure that the majority of React users will switch to React 16 (the first version under the MIT license) because their BSD + patents license is widely mistrusted and / or disliked.

I for one like to think that this change was triggered by the shots that Matt Mullenweg fired in his post “On WordPress and React” a few days ago. I re-read his post a couple of times because I found some of the statements he made very interesting. At first glance the post reads like “OK WordPress just ditched React no big dizzle” but after re-reading it I realized that Matt just deprived React of a quantum leap in growth. Wow. Let’s go through the interesting points:

First 💥:

Big companies like to bury unpleasant news on Fridays

This statement is in context of Facebook’s post about sticking with the BSD + patents license after the Apache Foundation put their license on the black list.

Right in the beginning of his article he accuses Facebook of shady behavior.

Second 💥:

I’m not judging Facebook or saying they’re wrong, it’s not my place.

This is hilarious. Translation: “I am judging Facebook and I am saying they are wrong.”

Third 💥:

We had a many-thousand word announcement talking about how great React is and how we’re officially adopting it for WordPress, and encouraging plugins to do the same. I’ve been sitting on that post, hoping that the patent issue would be resolved in a way we were comfortable passing down to our users.

Now for the squeeze.

Translation: “We were going to officially adopt React as the WordPress JavaScript thing and make a big fuss about it which would have been massive promo for you for free and would most likely have pushed React adoption into jQuery-like spheres. But now we’re not doing that, lol.”

Fourth 💥:

Squeeze even harder:

Core WordPress updates go out to over a quarter of all websites, having them all inherit the patents clause isn’t something I’m comfortable with.

Translation: “For realz Facebook?!?!? You don’t want your Framework to be used by over 25% of all websites on the internet with a snap of a finger!?!? Maybe y’allz want to think about that a little bit?”

Fifth 💥:

Now for the kill:

But we have a lot of problems to tackle, and convincing the world that Facebook’s patent clause is fine isn’t ours to take on. It’s their fight.

Translation: “We don’t need all your drama. You’re on your own.”

We’ll look for something with most of the benefits of React, but without the baggage of a patents clause that’s confusing and threatening to many people.

Translation: “React is not indispensable and can easily be switched out with something similar, thank you.”

So good. He whacked them over the head in the nicest way possible.

It makes total sense to me that Matt’s post would make them rethink their licensing strategy. The Apache Foundation reject did not really mean a big impediment to their growth but loosing WordPress would deprive them of more massive adoption and may even mean a decline in React adoption going forward because Matt and WordPress as a project are just incredibly influential in the web development community.

Potentially being the JavaScript thing for WordPress and WordPress plugins and the growth React would gain by that must outweigh the litigation costs they would save by sticking with BSD + patents.

Matt has already reacted to Facebook’s anouncement:

I am surprised and excited to see the news that Facebook is going to drop the patent clause that I wrote about last week. They’ve announced that with React 16 the license will just be regular MIT with no patent addition. I applaud Facebook for making this move, and I hope that patent clause use is re-examined across all their open source projects.

Matt is pleased about the change.

But Facebook has lost the chance to be the designated WordPress JavaScript framework:

Particularly with Gutenberg there may be an approach that allows developers to write Gutenberg blocks (Gutenblocks) in the library of their choice including Preact, Polymer, or Vue, and now React could be an officially-supported option as well.

Looks like the WordPress team found out about this new-fangled compiler that Jason Miller of Preact-fame is working on which compiles, Web Components, VueJS components and Preact components into highly optimized Preact components. That’s awesome.

Interestingly Matt is not mentioning if they will still switch away from React for Calypso. Somebody opened an issue asking about it but nobody has responded yet.

Meanwhile React 16 has been released and the license is indeed MIT.

All New

My blog used to be a Medium publication with a linked domain but I ditched Medium. I was disappointed with the design directions they are taking. I was a big fan of Medium’s design before the recent change to the new serif wordmark. It feels disjointed to me now and it is apparent that they are pushing their paid services and are working hard to make an actual business out of Medium. That’s all good and fine but I don’t like the changes and that made me realize I need to have more control over my blog again.

Also I wanted to consolidate kahlil.info and kahlillechelt.com. So here we are. New blog same old me.

For now I am leaving my old blog posts over there on Medium. I will port them over eventually. Maybe. I will be cross posting my blog posts from here over at Medium as well. The readership you get over there via their network is really nice.

Design

The initial inspiration for the design was a quick study that @magalhini posted to Twitter a while ago. I played around with it but wanted a different font pairing. After some googling I found Typewolf Google Fonts and Great Simple, two websites that suggest Google font pairings. I ended up choosing Roboto Mono as a main font and Rubik for my wordmark.

I found the pairing here and after I saw it I kept coming back to it. So I went with it. I really like using a monospace font for the body text.

I am happy with it. Keeping it simple.

It’s A Static Site

As a web developer I have to use a static site generator of course. Which one you ask?

Hugo!

Hugo is written in Go and comes as a binary. It’s wicked fast and can easily deal with huge amounts of posts.

It has been around for a while now and is really flexible. It works very similarly to other static site generators like Jekyll or Metalsmith.

Hosting

For hosting I went with Netlify, I’ve been really impressed with their user experience for hosting static pages. If your site is on Github it is incredibly easy to deploy it to Netlify:

Done!

The site gets redeployed every time you push to master (this feature can be turned off) and if I push a branch to the site’s Github repo Netlify will attempt to deploy a preview automatically. It’s truly a joy to use.

If you are interested in the code for this site you can find it on Github.