Quick Static Page with Github, Namecheap and Cloudflare

I recently published a TypeScript book that cover all features of the language from its inception to version 2.8. I wanted to have a static page that presents the book without having to host it myself. My goal was to create and publish everything in the evening.

The first step was to get a template online. Finding a template is quite easy these days. You can search for “free HTML template” and get thousands of free template. The second step is to get a domain name, I use NameCheap since many years, hence I registered typescriptbook.com. I might have many TypeScript books so I like that the domain name is significative and give me some freedom to host many of my potential TypeScript books. The third step was to write the content of the website.

The fourth step was to host the code on Github. I never used Github as a service to host a website, but they do have some configuration to use GitHub as a hosting platform. It is more straightforward than I thought. You need to create a public repository, push all your code and go to the repository’s settings to add your domain.

I choose a custom branch because of some other tutorial, but you could select the master branch instead. Nevertheless, this can give a chance to push and test before having the static files being ported to the website. Regardless, the next step is to go to NameCheap (domain provider) to set up the site.

You need to specify Cloudflare nameserver in NameCheap. You could instead keep NameCheap nameserver and create a custom DNS A entry to Github, but that doesn’t support HTTPS. Using Cloudflare brings the possibility to have HTTPS for free. To know which nameserver to use, you must set up a free Cloudflare account first. So, let’s pause the configuration of NameCheap and go in Cloudflare. Under the “DNS” tab you can find the nameserver. DNS is also the place where you need to configure the two ips from GitHub (you can find these two ips in the documentation under “how to setup Apex domain with Github”).

The current configuration allows having HTTPS and HTTP. The domain points to Cloudflare that handle the SSL certificate (HTTPS) and aim to GitHub that host the files. The three services have three specific roles and once in place work well. You may have some down period if you do a typo in the domain name or the ips — be careful. Also, the DNS propagation can take many minutes if not hours. Nevertheless, so far, I am very satisfied with this setup and the website was all done in an evening as planned.

How to have Chrome Style Inspector to Show Input Placeholder

One habit I have is to set the classes to my HTML elements and then go in Chrome to write all the style. Once I am satisfied, I copy paste everything in the style sheets. Recently, I had to modify the placeholder text to be in a specific color and style — Chrome’s inspector couldn’t bring the style of the pseudo-element ::placeholder.

The reason is that the placeholder is hidden under the “shadow-root”. The element hides in the Element Explorer, you cannot select the element to see or edit its styles. Chrome lets you configure the developer tool to bring the “shadow-root” into the Elements panel.

The first step is to go in the three dots menu and select “Settings”. Under the “Preferences” tab and the selection “Elements”, you need to check the “Show user agent shadow DOM”.

Going back to the elements panel, you will see the shadow dom under the input.

By clicking the “div” inside the “#shadow-root (user-agent)” you can see in the styles panel all the common styles as you would expect.

Why I wrote a TypeScript book?

I published a 194 pages TypeScript book last week under the name “Holistic TypeScript.”. It’s been a while since I desired to write about a single subject. I’ve been releasing since many years a compilation of my blog posts, but otherwise, it’s been a while since I focused on a single topic. The last time was with Apress with a book on Visual Studio 2013 and before with a French book around stock investment. Last year, I had a monthly objective and the December objective was to draft a TypeScript book. Indeed, I missed the schedule by three additional months and that is not that I didn’t work on it: writing a book is quite a long endeavor.

So, why TypeScript? Because it’s the language I have been using in the last four years and that I firmly believe it a considerable multiplicator in efficiency for any developer that use JavaScript. There is plenty of books, but I wanted something simple, with very targeted examples that cover the fundamental concepts of each feature. I was aiming for something between 175-200 pages that was covering everything from TypeScript 1 to TypeScript 2.8 (latest current version). I plan to add new edition every year with new feature and revisit sections that do not satisfy me. Thus, this book is the first brick on the foundation to create Holistic TypeScript as a substantial book to get a clear overview of all feature.

The second reason is that I plan to write next year a book that will be very advanced. The future book will be probably shorter, won’t talk about features but will analyze advanced typing scenario that arises in complex situations. It is still far in the future, and at the moment, I am thrilled with Holistic TypeScript. The book is available on Amazon in Kindle and paperback version. Enjoy!

Checking all options with one or many Redux action?

Imagine the situation of a UI with many checkboxes and an option to select them all. With the perspective that the feature of checking all checkboxes is new, wouldn’t it be a good idea to have the “select all” button loop the checkbox action with each ID one by one? The short answer is no, and we will see how doing so can be expensive.

It might be the most straightforward and quickest way to invoke onCheck in a loop. It has the advantage of reusing the dispatch function, as well as the action function and the reducer. The problem is the number of computations done by calling several actions in a loop. While Redux can handle quite a lot of actions fast, there are some boundaries where you will notice some slowing down. Here is an actual code I had to optimize which went from 2100ms to 16ms.

The following image is the benchmark of a code that was looping in the React component when you click a function for each checkbox with a selected value.

Chrome Performance on the Click Event Before the Modification

This is the code with a dedicated function that a middleware was creating another action with the list of all entity from the Redux’s state with the mention to select the entity which the Reducer can read once and set the state once.

Chrome Performance on the Click Event After the Modification

Creating the additional dispatch function, passing this one down to the component and creating the actions was more work. It takes about 20 minutes mostly because I wanted to have the middleware to handle the logic of selecting all because I keep all reducers very slim and dummy. So, I had to create 2 actions. However, this 20 minutes was well worth it because the user sees a user interface that is O(1) when clicking the “select all” instead of being O(n).

The underlying problem is that every action goes back to a full Redux’s lifetime loop. The portion of the life cycle that is consuming is the denormalization which creates back the entity in a rich (and deep) format. Indeed, optimization can occur at that level as well, but avoiding starting Redux’s cycle was a step in sound practice.

React Dropdown Mounting Optimization from 400ms to 2ms

I always have the Chrome’s developer tool open without exception when developing websites. I am having this habit since the first FireBug extension was released from FireFox a very while ago! Once in a while, I collect performance and look at the result. It keeps me on my toes if regression occurs or merely to have a real picture of what is going on. What I found is that checking performance is even more critical when using React and Redux because many lifecycle events can generate a lot of performance hits. Recently, I noticed that one of the websites I was working was rendering a drop down that was taking 400ms to mount. The drop-down is visible in the main menu of the site hence it’s a 400ms that is costly right from the start of the application. I also noticed that the value of this dropdown is change once in a while, thus a very expensive 400ms.

The profiler was very clear about the issue: every item of the drop-down was mounting, and the number of choices was reaching up to a thousand. Not that it is essential, but the control was from React Semantic-UI. The component doesn’t have a lazy loading bake-in feature. So, I ended up coding a rapid change to render the drop-down, but no item until the user opens the drop-down.

The hosting React component of the dropdown is receiving by property the list of elements to add in the drop-down. The solution was to instead of to bound the list directly to create a state to the control. The component’s state contains two fields. One that indicates if the list of elements is mounted to the control and the actual list of items. Here is the TypeScript’s interface that defines the state.

export interface PickerStates<T> {
    isItemsMounted: boolean;
    items: T[];
}

The constructor of the hosting React component initializes the state to false and to an empty list.

constructor(props: PickerProps) {
    super(props);
    this.state = {
        isItemsMounted: false,
        items: []
    };
 }

The render needs to render the Semantic React Dropdown control. This one leverages its capability of being able to have a caption label to write the actual selected value. This is great since it gives the possibility to have an active element that is not even yet mounted. The options property, which is the list of item, is set to the state which is empty at the first render. The trick is coded in the “onOpen” method which executes code when the user clicks to open the drop-down. It transfers the list into the state. Since the state change, the render is executed again and render the list with all items. The recursive render is executed only once because of the boolean guard and mounts all the items.

<Dropdown
    item={true}
    value={this.props.selectedItemId.toString()}
    options={this.state.items}
    search={true}
    onOpen={() => {
        if (!this.state.isItemsMounted) {
            this.setState({ isItemsMounted: true, items: this.props.items });
        }
    }}
    text={selectedElementText}
/>

A fraction of the users perceive the delay of 400ms and at a time not crucial than the bootstrap of the application. In the end, the justification of using React’s state remains adequate by not performing deep logic which keeps the component dummy.

NPM locally to increase coding velocity between two projects

One advantage having a big repository is to be able to change a part quickly and see the result right away. Recently, I moved a piece of code into another library. The reason was to reuse the library on several systems. The concept of breaking apart into different cohesive library make sense, however, it comes with the price that a quick one line change can become more demanding. I found that it’s roughly 5 to 10 times slower. The reason is that a single line of change require to save the file and the code is ready to use. The same change in another repository needs to package the source code and to fetch the new package. The major problem is that everyone using the package sees the version bumping and the release may not even be ready to share. Ideally, a library is self-contained, and a group of unit tests ensures that the quality is as expected. However, in reality, it appears that a shareable version may require some checks directly on the browser.

NPM provides a solution. The solution is to share the library code locally to a local project. The beauty is that no code modification is required. The solution tells NPM to link locally instead of getting the package from the remote server.

The first step is to have your project that consumes the library and the library locally on your computer. Both projects can reside anywhere.

The second step is to go at with your command line at the location of the package.json of your library. NPM has a command called “link”. The execution of the command will specify if the creation is a success or not. If it is a success, you can use your command prompt to move to the project that consumes the library. Again, at the level of the package.json the command “npm link” must be executed. The difference is the argument that needs to specify which library to link. The name of the library is the name specified in the package.json of the library that we “npm link” at the second step. This command succeeds with an output that shows that node_modules points to the local directory.

Finally, once you are done and want to use the node_module library, you can unlink. The command to unlink is “npm unlink ” where the parameter is the parameter of the library linked. The library can also be unlinked by going back to the library and executed “npm unlink”.

As a recap:

// 1) At the library level
npm link
// 2) At the project level (consumer)
npm link my-library-name
// 3) Stop using the local version
npm unlink my-library-name
// 4) Stop sharing locally my-library-name (must move back to library level)
npm unlink

The technique works with TypeScript. The compilation of the library needs to occur since the link to the library read the package.json and will look for the “files” property which is mostly pointing to the build folder.

Before closing on the subject, make sure that both libraries are running on the same NodeJS and npm version. Each NodeJS version links to a different folder. You can confirm the location of the link by using “node -v”. Another tips is for people using “create-react-app”. In that case, you may have to close and open the development server on each change. The reason is that Webpack does not notice the change in node_modules folder and will serve you the same files of the startup.