DebConf18: Talking about Ring in Taiwan!

From July 28th to August 5th, one of our team members, Hugo Lefeuvre (also a Debian Developer on his free time), attended DebConf18, the annual Debian Developer’s Conference, in Hsinchu, Taiwan. During this week, Hugo spent time preparing and giving a talk about Ring, hacking on Debian packages, discussing free software communication and distributed networks with fellow developers and users. Just like last year’s edition, DebConf18 has been a very enriching experience for us. DebConf is a great way to not only to rekindle old friendships but also make brand new connections between free software developers from all around the world. It is also a knowledge sharing platform; an excellent place to get mature and informed feedback, reviews and critical comments from a third party perspective.

        

Hugo’s talk – “Challenges of Ring – a free and universal distributed communication platform” mainly intended to give an overview of the Ring project by discussing some of the challenges arising from its development process. By choosing the developer’s point of view in order to present the Ring project, we wanted to show what it is like to be a Ring developer, and more generally, how interesting it is to be a pioneer in the free and distributed communications domain. We hope that it sparked interest among existing and the new Ring developers. The talk was followed by a Q&A session during which we discussed various topics such as privacy impact of Firebase embedded in our Android client, and how to develop a workaround to tackle this issue. Participants were also interested to explore battery footprint on Android, or the usage of blockchain in our name server. This was indeed a valuable moment to us, and hopefully to all attendees.

We’d like to thank DebConf18 organizers and sponsors for all their humble efforts to make this edition a success, and cannot wait to see you again next year DebConf19 in Brazil!

 

New Release of Ring: “Live Free or Die” Version

Montréal, July 25th, 2018 – Savoir-faire Linux, a leading open source software company in Canada, has launched a new release of its free and universal communication platform Ring, called “Live Free or Die“, which is also the official motto of the U.S. state of New Hampshire. This major release includes additions such as audio and video call recording, push notifications, as well as quality, security and stability improvements.

Since its inception, Ring has always aspired to become a truly universal and stable communication platform at the service of societies while respecting their privacy and their freedoms. Today, with its iOS application being released, it has closed the platform compatibility gap.

Everyone who uses any of the following platforms can benefit
from Ring and join its community of users.

  • GNU/Linux (Ubuntu, Debian, Fedora)
  • Android & Android TV
  • Windows
  • macOS
  • iOS (iPhone & iPad)

OpenDHT: The Technology Behind Ring

OpenDHT Logo Created by Ring’s Team

Ring is a fully distributed system based on OpenDHT technology Ethereum  Blockchain that doesn’t need any central authority, an enterprise or even a server to function. Consequently, it avoids keeping centralized registries of users and storing their personal data. In addition, Ring is based on standard security protocols and end-to-end encryption. Thus, it prevents decryption of communications over the network and consequently offers a high level of privacy and confidentiality. In addition, Ring’s technological capacity can be expanded to a wider industrial setting with use cases like Internet of Things’ projects, industrial systems as well as custom communication needs, to name a few.

Ring’s Key Features and Characteristics

  • Encrypted audio/video/messaging communications,
  • Screen sharing,
  • Audio and video call recording,
  • Push notifications,
  • Conferencing service available on GNU/Linux and Win32 clients,
  • Support of Ethereum Blockchain as a distributed public users’ database,
  • Distributed communication platform (OpenDHT),
  • Platform support on GNU/Linux, Android (4.3+), Windows (Win32 and UWP), macOS (10.10+) and iOS (9.3+),
  • Distributed under GPLv3+ license.

 

Sources and Information:
Marie Pelland (Director of Communications)
marie.pelland@savoirfairelinux.com
+1 514 276 5468 (ext. 328)

 

Mapping and Calculating Areas Autonomously: An AI Robotics Programming R&D Project

Recently, our ‘AI Robotics Programming’ Team has delivered a proof-of-concept robot used to explore and map unknown industrial and residential spaces while identifying floor types.

The robot (with the exception of its Roomba chassis) is fully built from open-source (OS) hardware and software components. The result is an elegant blend of genetic algorithms and neural networks which enable the robot to autonomously map, survey, and calculate areas of the non-trivial indoor/outdoor spaces.

As an industrial use-case, the team has showcased a demo where the robot is used by a fictional cleaning company to optimize its costs. The robot is sent to a fictional warehouse where it explores the space after business-hours and sends back a report to the cleaning company with the space’s map, areas of its various sections and floor types. This report helps the company to efficiently invoice the client for a regular maintenance contract and remove the human factor from part of its client acquisition process, thus optimizing costs.

The project is still in its early stages and we are confident that many more use-cases will be discovered along the development process – for example by adding support for outdoor spaces.

While the novelty lies mainly in the software part, our AI team has amusingly dubbed their assembled robot, SMOB – short for Self-Mapping Open Bot.

Mapping, Surveying, and Calculating Areas Autonomously: An AI Robotics Programing R&D Project
SMOB in action, surveying and mapping the area of Savoir-faire Linux HQ

What Powers SMOB?

The project is a unique blend of hardware and software design. Since the robot needed to be resistant to collisions with objects and travel at a fair speed, using the entire TurtleBot kit was not an option under such constraints. The team has solved the problem by mating the Roomba Create base (which is well suited for heavy duty operations) with the IMU (Inertial Measurement Unit), LIDAR (Light Detection And Ranging) and Raspberry Pi3 from the TurtleBot 3 DIY kit. In order to achieve the latencies required for smooth operations, the team has also modified the Debian kernel to support the 64-bit instruction set available on the ARMv9 processor (the modifications were based on the PI64 project).

SMOB’s Algorithms

SMOB combines two different techniques to achieve its goals. The space discovery algorithm is an implementation of the genetic algorithm proposed by Mohamed Amine Yakoubi and Mohamed Tayeb Larski. The algorithm is realized in Python to work in conjecture with the ROS framework, which powers the robot’s movement.

The more complex part has been the realization of the convolutional neural network which is responsible for classifying floor types. The main challenge here is to properly identify the properties of an image (sharpness, luminosity, size, camera position, etc.) so the network can achieve maximal classification efficiency – a research that took the team substantial trial and error before getting the right parameters.

Test Results

Our experiments shows a performance of coverage of ~1m^2 per 1 minute on a low-cost robot (~600 USD).

What Makes SMOB a Unique Robot?

SMOB is unique because it is among the first-attempts to have a robot perform several complex tasks on embedded hardware. It can be safely argued that automated driving already uses algorithms that are far ahead of what SMOB can do, but they are also far more complex than SMOB’s very basic and low-processing cost solutions. SMOB is about minimalism it’s an attempt to create simple solutions to problems which are currently solved by much more power and memory hungry algorithms.

The Future of the Self-Mapping Open Bot in the Congested Robotics Field

One of the biggest challenges faced by our AI Robotics Programming Team includes outdoor operations related to LIDAR sensors and issues associated with them. LIDAR – a device that maps objects in 3-D by bouncing laser beams off its real-world surroundings – is one of the most crucial and contentious components of any vehicle (in this case SMOB) that is supposed to drive itself around (Read for example: Simonite, 2017). SMOB’s LIDAR is unable to identify glass. It also faces difficulties in loop-closure detection and navigation on complex surfaces. For example, a SMOB designed to detect potholes outdoors would most likely need a different chassis, drive-train, and would need to be able to detect potholes before reaching them; otherwise it may not be able to get out of them once trapped inside.

Stay tuned for more details on the evolution of SMOB and its added capabilities.

References
Simonite, T. (2017, March 20). Self-Driving Cars’ Spinning-Laser Problem. MIT Technology Review.

Our Experience at DrupalCamp Montreal 2018

Savoir-faire Linux participated in the tenth edition of DrupalCamp Montréal, which was held this year at Concordia University. It was the occasion to catch up with a good proportion of the Drupal developer community in Montreal, to exchange ideas with other companies that work with this technology, and to have an overview of how Drupal is evolving with the times and what is in store for it next year.

Here are notes from some particularly interesting sessions, provided by our senior Drupal developer Maxime Turcotte:

Migrate one, Migrate all: Let’s migrate to Drupal 8

With all the advantages that Drupal 8 now offers compared to Drupal 7, particularly with respect to multilingual support, more and more sites are making the transition to the new version despite the occasional obstacle. For example, even though the migration system API has been stable since fairly recently, migrations for content translation are not yet fully supported.

In addition to providing an excellent overview of the migration process, both in general and for more in-depth personalized migrations, this presentation provided solutions and examples for those looking to migrate their multilingual sites from Drupal 7 to 8.

Hosting Drupal sites? You need Aegir!

Whether it’s for a single site or for an elaborate multi-site platform, if you like building your own infrastructure using Free Software tools and to manage your sites with a helpful web or CLI interface, Aegir is for you.

During this presentation, we learn about the historical reasons that brought about the development of Aegir, the architectural challenges it faces, some little bits of wisdom for commonly encountered issues, prospects for refactoring in future versions and much more.

What I learned in 10 years of running a Drupal shop

Operating a service-oriented Web business in a constantly-transforming competitive industry is quite difficult. What better than to benefit from the accumulated experiences of two professionals that have been working in the industry for over ten years?

“Everybody makes mistakes and there will always be more mistakes to make” was one of the big lessons from this presentation. Risk is certainly a necessary aspect to deal with when trying to succeed in this industry, but how you manage this risk is what can set the winners apart from the losers. Whether it’s in research and development, in the choice of contracts you accept or in the expenses you accept (or refuse) to make, you must be able to foresee what sort of risk is involved and if it’s worth dealing with.

But aside from risk and competition, collaboration and community involvement is what seems to be the most important thing for the two business leaders we heard from.

Push Notifications: A New Feature Added to Ring Project

Push Notifications: A New Feature Added to Ring Project

Push notifications are essential part of the effective end-user experience on mobile platforms. They tend to boost the app engagement and users find them useful and handy as they ease their communications. Although push notifications are widely considered an advantage for most apps, they are regarded most useful for messaging, email and other types of communication apps in general. For this reason, our team of developers have been working hard to make sure Ring is equipped with such critical feature in lockstep with Ring users’ expectations. Today, Ring’s push notification is available for its Android and iOS versions and the users can stay informed of their accounts’ developments while their phones have been idle.

For more details, visit : https://ring.cx/en/news

For further information:

How to Create a Light and Fast-Loading Theme with Liferay?

When It Comes to Websites, Page Speed Matters!

This article is motivated by our website project accomplished by our Integration Platforms and AI Department using Liferay 7 (the latest version of Liferay Portal) for one of our clients– a large Canadian corporation in telecommunications and media industry. Alexis, our front-end developer, shares with you his first-hand experience of this project with the overarching objective to demonstrate how to create a light and fast-loading theme using Liferay portal? 

Right off the bat, we need to acknowledge the fact that, “The average online shopper expects your pages to load in two seconds or less…; after three seconds, up to 40% will abandon your site” (Gomez Inc., 2010). Thus,”page speed is increasingly important for websites” (see Lara Callender Hogan).

Thus, “page speed is increasingly important for websites.”

However, Liferay portal technology itself is not a one-size-fits-all solution. For example, in some cases, if the integrator does not develop a context-specific front-end libraries, the website will be crippled by unnecessary delays. Some experts have also suggested a mainstream recommended method which is to extend the Liferay theme by default. This, however, would result in a technical failure thereby extended web page loading time. Thus, based on the lessons learned from our past projects, i.e. experiential learning, and lucky to have the latest Liferay portal, Liferay 7, we decided to tweak the technology, develop a new module, and adapt it to unique expectations of our client. In what follows we share with you our feedback and the positive test results.

Liferay Portal: A Powerful, Yet Delicate Tool

Liferay is an Open Source Content Management System (CMS) and Portal, written in Java. Therefore, a service provider like us has flexibility to customize it as much as required to fully adapt it to the client’s needs. It provides the developers with an extensive user management, access rights and documents. However, there are some theme specific and performance issues to consider before starting a new website project. Here is a list:

  • Generally, a Liferay theme is home to a bulk of all the front-end libraries and styles needed by Liferay and its portlets. However, a big chunk of the codes and dependencies is useless for a guest visitor. In case of our client, these kinds of visitors form the majority of their users and indubitably the unnecessary code overload will cause performance issues and slow the site down.
  • Liferay imposes the presence of its Design Language, Lexicon (or rather, its only implementation: Clay). This may also cause several problems:
    • Mismatch between Design Language and the client’s design requirements can limit the project’s design feasibility.
    • This situation causes conflicts between CSS rules, therefore increasing the development time.
    • Liferay’s template bugfixes and updates can break the developed styles causing a an increase in maintenance time.
    • With content administration being on the pages, the developed styles can break the behavior of the administration styles also contributing to the increase of the development and maintenance time.

Although these issues impose challenges on a Liferay deployment project, we can offset their impact by developing front-end libraries, as you can read in what follows.

The Solution for Creating a Light and Fast-Loading Theme with Liferay

The solution to benefit from the state-of-the-art Liferay Portal while keeping in check the loading speed is to create a light theme without any Liferay front-end libraries such as senna.js, AlloyUi, Lexicon/Clay, etc.

However, in Liferay 7 this objective cannot be obtained as easy as it looks mainly due to not having the possibility to have an administration view of the site. In order to avoid this issue, we have internally developed a stand alone liferay module which is called “Theme Switcher“. This added functionality allows us to dictate the portal to display a theme according to the role of the user. Here is the link to the github repo: savoirfairelinux/liferay-theme-switcher

5 Steps Towards Setting Up a Light Theme

Here are the five steps for creating a light theme using Liferay 7. But before we get started, let’s look at this instance of a Liferay’s light theme which can be found on GitHub: savoirfairelinux/lightweight-liferay-theme. This theme is created using Maven, and if you wish to modify it you actually can. It is all open source.

Step 1 – Clean Up Your Themes

Remove the inclusions from the portal_normal.ftl file, mainly: <@liferay_util [" include "] page = top_head_include />. But also <@liferay_util [" include "] page = body_top_include /> and so on.

Step 2 – Repair the Themes

Unfortunately, the top_head_include variable does not only contain Liferay’s CSS and javascript libraries, but also many other things. It is therefore necessary to re-include the tags of the head that interest us. For some examples of the tags, consider the following:

  • The meta-tags that the user can define in each pages (keywords, description, etc.):

<@liferay_theme["meta-tags"] />

  • The definition of canonical URLs:
<#if !is_signed_in && layout.isPublicLayout() >
  <#assign completeURL = portalUtil.getCurrentCompleteURL(request) >
  <#assign canonicalURL = portalUtil.getCanonicalURL(completeURL, themeDisplay, layout) >
 
  <link href="${htmlUtil.escapeAttribute(canonicalURL)}" rel="canonical" />
 
  <#assign availableLocales = languageUtil.getAvailableLocales(themeDisplay.getSiteGroupId()) >
 
  <#if availableLocales?size gt 1 >
    <#list availableLocales as availableLocale>
      <#if availableLocale == localeUtil.getDefault() >
        <link href="${htmlUtil.escapeAttribute(canonicalURL) }" hreflang="x-default" rel="alternate" />
      </#if>
      <link href="${htmlUtil.escapeAttribute(portalUtil.getAlternateURL(canonicalURL, themeDisplay, availableLocale, layout)) }" hreflang="${localeUtil.toW3cLanguageId(availableLocale)}" rel="alternate" />
  </#list>
  </#if>
</#if> 

In order to know what to look for, and how, you need to know the basics of jsp which is used to generate the variable top_head_include. For more information, please consult the following link.

Step 3 – Organize the Themes

One of the challenges is that liferay-theme-tasks (link) which is a gulpfile provided by Liferay may not function smoothly. The good news is that you can organize the themes the way you want; i.e. according to your team’s development standards (sass, less, es6, etc.). In case of this client, we have used and embellished the usual gulpfile to our web projects. All headed by Maven and the front-end plugins.

Step 4 – Automate the Deployment of the Themes

Step 4 is perhaps the longest one, but as soon as it is completed you have a turnkey solution at hand. To quickly deploy the light theme files you have developed, take this advice. You do not have to compile and wait for the deployment of the theme for each modification of CSS or JavaScript (the features normally present in liferay-theme-tasks). In the OSGI context of Liferay 7, it is not possible to simply access the theme files (CSS, js, templates, etc.). Thus, you have to do the trick which you can learn by looking at the gulp `deployLocal:syncTheme` task.

The main idea is to transform the deploy module in webbundledir mode instead webbundle.

Step 5 – Enjoy the Developed and Deployed Themes

You now have a Liferay theme, which contains only what you want for your project, and which is deployable like any other Liferay themes. So, it is time to just enjoy the fruit of your efforts.

Results and Robustness Checks

In order to evaluate the performance of the theme(s) created, you can conduct three tests on each page (i.e. instance) with the same content. We have tried these tests, running each one of them on a Liferay server configured for production. Below are the three instances for which we used these tests (on a serveur with 8 CPU and 28Go of RAM, with a SSD disk).

3 Instances Tested for Robustness

  1. A Liferay vanilla theme, the “Classic” theme
  2. The light theme we developed for the client’s web page project
  3. A possible “real” case scenario: the “Classic” theme with more styles and JavaScript of the theme that we have developed for the client.

To perform these 3 tests, we used a local instance of speedtest.io (6.0.3), with Chrome 62. For each test, 10 calls were made, below is the summary of the results.

Results of the Test 1: The Classic Liferay Theme

  • 52 requests
  • 1064.77 kb
  • DOMContentLoaded: 1.24s (±31.95ms)
  • Load: 2.06s** (±52.89ms)
  • SpeedIndex: 1349 (±34.99)

We deemed these results acceptable as we could not find a single glitch in the theme as far as page performance was considered. The results are significant as they pass beyond the threshold for requests. As a rule of thumb, if the number of requests go beyond 40, it is considered a large number of requests.

Results of the Test 2: The Light Theme

  • 37 requests
  • 800.38 kb
  • DOMContentLoaded: 588ms (±42.96ms)
  • Load: 1.17s** (±55.17ms)
  • SpeedIndex: 863 (±39.57)

Fewer queries were made as it was a smaller page. Thus, this custom theme is more powerful than a basic Liferay theme!

Results of the Test 3: The Classic Theme with JavaScript and CSS of the Client’s Light Theme

  • 56 requests
  • 1214.59 kb
  • DOMContentLoaded: 2.22s (±457.34ms)
  • Load: 2.97s** (±458.11ms)
  • SpeedIndex: 2475 (±456.71)

Conclusion

Creating a light theme with Liferay is advantageous as it empowers you to maintain control over your company’s image by managing all the items that are sent to the browser. Liferay technology as a tool coupled with our expertise and years of experience working with it offer your company a solution, a powerful website, to stay on top of your content management efforts signaling a positive image to clients.

Overall, this experience has been an instructive and informative one. Our client and us are genuinely happy for the results are satisfactory and in line with our expectations. It is indeed a powerful website worthy of bearing its brand name.

 

FOSDEM 2018: What Are the Highlights to Remember?

On February 3rd and 4th, two members of Ring’s development team took part in FOSDEM 2018 in Brussels. FOSDEM (Free and Open Source Software Developers’ European Meeting), a major event for free software developers, is held annually since 2000 during the first week-end of February at the Université libre de Bruxelles. Sébastien Blin, a Ring project’s developer, shares with us his recent discoveries made during his visit to the free and open source software world of FOSDEM.

FOSDEM 2018

Sébastien says: “This year was my first experience at FOSDEM! When I arrived in Brussels, I took the opportunity to visit this beautiful city before going into two days of talks, presentations and meetings.”

Some Highlights

FOSDEM is the place to meet countless free software experts, to attend plenty of talks and to explore the most interesting and recent free and open source software projects.

In this event, I represented Savoir-faire Linux and gave two talks: one on Ring Project and the other on OpenDHT with Adrien Béraud. I also seized the chance to personally meet some very interesting developers whom I would not have been able to get acquainted with easily outside this event. All of this kept me quite busy and engaged so much so that I could not attend all the talks on my shopping list! However, here is a brief overview on those talks I participated:

  • Python 3: 10 years later: Python’s history and developments in the last 10 years.
  • GStreamer for tiny devices: some tools to optimize the size of the GStreamer binary (or other binaries) for platforms with little memory space.
  • Anonymous Whistleblowing with SecureDrop: a talk about a software which allows journalists and their sources to exchange anonymously and securely.
  • Speech-to-Text in Jitsi Meet: I was a little bit disappointed by this talk, because they use Google Speech API to do that, and I wanted to discover an alternative to current proprietary solutions. It is still a nice project to follow. It is planned to replace Google Speech API by a solution similar to Mozilla’s Common Voice.
  • Qt GUIs with Rust and GStreamer & Rust: It still good to see big libraries coming on Rust.
  • Tizen:RT : introduction to the Tizen ecosystem and Tizen:RT 

Also, I’m currently waiting to watch the videos of these talks:

It is a different feeling to watch these projects live! You also can attend a lot of talks in the Decentralized Room such as Contributopia (by Framasoft).

Other News

Based on my experience, I believe, one of the best spots to discover new projects was Building K which housed many stands showcasing the most recent projects and novel features of the existing projects. Plus, it was a great place to meet new interesting people! Here’s what I discovered:

  • Godot 3.0 is out!
  • VLC 3.0 is coming out!
  • Krita is now compatible with Python scripts!
  • I discover GitMate.io, I’ll try it soon!

I also discovered many other new features on Fedora, Mozilla, Qubes OS, Nextcloud, SecureDrop, Tor, etc.

My Talks

In FOSDEM I delivered two talks with my colleague Adrien. The details of them are below:

  • Ring as a free universal distributed communication platform

A conference about the state of Ring Project in 2018. The video is here and slides here . In order to explore more resources please check out the GitHub here.

  • OpenDHT: make your distributed project

A conference about OpenDHT. I mainly talked about the proxy feature and push notifications support. Watch the video here.

It was the first time I gave presentations in English in front of more than 200 attendants. It was… awesome! The public was receptive, questions were precise and they led to interesting discussions.

Final Remarks

First, I would like to thank Savoir-faire Linux for offering me the opportunity to talk at FOSDEM. I would also like to thank FOSDEM’s organizing team. They did a fantastic job of organizing about 10,000 participants along with logistics and operations such as scheduling, recording and publishing more than 100 talks online just in a matter of 2 days. It was indeed impressive. My own personal experience organizing tech events made me further realize and appreciate the efforts of the team behind the scene especially as the final outcome wowed the crowd!

Probably the only flip side of FOSDEM 2018 has been the lack of diversity in terms of gender and regions represented in the event. Perhaps, it would be great to encourage more female developers to join the event in 2019 and provide some further support to bring in the free software enthusiasts from less privileged sides of the planet. Free software community is an all inclusive crowd with no boundaries and for this reason we must do our best to celebrate diversity and empower those who need our support.

Inno Weekly #11

Web Development

Getting Started with Server-Side Rendering in Angular

By Kévin Barralon

This week we released a tutorial for developers using the Angular JavaScript framework to set them up with a pre-configured server-side rendering environment. This environment allows for the pre-rendering of an Angular site so that its contents can be made visible to robots (e.g. Google, Facebook, Twitter) and to improve the performance of Angular, as the state of the application is transferred from the server side to the client side.

As these features are new to the framework, the latest version of Angular (v5) is used for the tutorial. You can access the extensive version of this tutorial by reading the blog article: How to Create an Angular Application with Server-Side Rendering?

Bundle Your JavaScript Apps Using Parcel

By Jacob Cook

The JavaScript ecosystem is notorious for evolving very quickly. The modern JS application stack requires a variety of tooling mechanisms, including “bundlers”, which handle the generation and packaging of proper assets for the creation of a Web page. Up until now, two projects have reigned supreme in this space: Browserify and Webpack. They are not particularly known for their ease-of-use: for a preview, you only need to Google “Why is Webpack…” to get thousands of results like “Why is Webpack so slow?” or “Why is Webpack so complicated?”

It’s clear that the ecosystem needs some new utilities that can improve the startup process for cutting-edge JavaScript web applications. There is a new project on the scene called Parcel. This project aims to be an answer to many Webpack-related headaches. It does many things that Webpack does (code splitting, hot module replacement, code transpilation and transformation) with very little if any manual setup and no labyrinthine configuration files to write. It also uses a multicore compilation system, allowing CPU-hogging build operations to be spread across multiple workers and to better take advantage of those fancy processors we all use nowadays.

It remains to be seen if it will emerge as a solid competitor to Webpack, but if initial indications prove true, Parcel will be a huge boon to Web developers that want to get going with a modern project without having to run through their bottles of aspirin. Check out Parcel: https://parceljs.org/

Winter Break!

Thanks for following us for the past 11 editions. Our team wishes you a very happy and restful holiday season.

See you in January 2018!
Your Inno Weekly Team

How to Create an Angular Application with Server-Side Rendering?

Server-Side Rendering Management: An Angular’s Novelty Imposing a Challenge

Angular is a framework using the TypeScript Programming Language. Its 5th version (pentagonal-donut) was released in November 2017, containing new features and bugfixes. It is accompanied by the command line tool Angular CLI and new features such as a server-side rendering framework that has become very popular within the community of Angular users and developers.

However, one of the recurring problems that can be encountered when setting up a website with a modern library (e.g. Angular, React, Vue.js, etc.) is that, in general, web crawlers and robots will not be able to read that website! Therefore, if you want to share your article on Facebook, or simply be well referenced on search engines (i.e. SEO), this part may be complicated (although in the case of Google, it seems that their robots have recently learned to read pages generated by JavaScript).

The reason for this is simple: most robots do not know when your page will be entirely generated by JavaScript. Therefore, they will only be able to read a tiny part of your HTML – which is often a small ‘Loading …‘ message, and not very explicit! So, we are addressing this issue today in this post.

How To Create an Angular Application with Server-Side Rendering?

To overcome this problem we can use Angular CLI – the tool that helps to generate an Angular application from the command line. With its version 5 now available, it is now possible to manage a server state transfer to the client. For example, an application that makes a request to a REST API will not make the same request twice (i.e. on both server as well as client sides) while it can transfer the server-side result to the client. We will study these two cases successively in order to start an application with server-side rendering.

How to Initialize Your Angular Project?

Follow these steps in order to initialize your Angular project:

  • Start by installing the Angular CLI tool: npm i -g @angular/cli
  • Then, initialize the project: ng new ssr-app style = scss # Because it's better with SCSS.
  • Then, go to the directory of the generated application and launch the development server:
cd ssr-app
ng serve
  • Finally, visit http://localhost:4200/ and enjoy!

Now it’s time to configure the server-side rendering management.

How to Configure Server-Side Rendering?

Let’s start by installing the platform-server package: npm i -S @ angular / platform-server

In the file .angular-cli.json at the root of the project, you must add in the “apps” part, the following configuration:

{
   "name": "universal",
   "platform": "server",
   "root": "src",
   "outDir": "dist-server",
   "main": "main.server.ts",
   "tsconfig": "tsconfig.server.json",
   "environmentSource": "environments/environment.ts",
   "environments": {
      "dev": "environments/environment.ts",
      "prod": "environments/environment.prod.ts"
   }
}

In our src / app folder, we now need an app.server.module.ts file next to our app.module.ts file. This will be our entry point for our server-side application. Its content is:

import {NgModule} from '@angular/core';
import {ServerModule} from '@angular/platform-server';

import {AppModule} from './app.module';
import {AppComponent} from './app.component';

@NgModule({
   imports: [
      AppModule,
      ServerModule
   ],
   bootstrap: [AppComponent]
})
export class AppServerModule {
}

The file simply inherits modules from the app.module.ts file and adds the ServerModule module. As for the main.server.js file in the .angular-cli.json, we need to create it next to the main.ts file in the src / directory with the following content:

import {enableProdMode} from '@angular/core';
export {AppServerModule} from './app/app.server.module';

enableProdMode();

We also need to create a tsconfig.app.server.json file for TypeScript compilation next to tsconfig.app.json in the same directory:

{
   "extends": "./tsconfig.app.json",
   "compilerOptions": {
      "outDir": "../out-tsc/server",
      "module": "commonjs"
   },
   "exclude": [
      "test.ts",
      "**/*.spec.ts"
   ],
   "angularCompilerOptions": {
      "entryModule": "app/app.server.module#AppServerModule"
   }
}

In the src / app directory, we now need to modify the app.module.ts file by adding a method to our BrowserModule module:

import {BrowserModule} from '@angular/platform-browser';
import {NgModule} from '@angular/core';
import {AppComponent} from './app.component';

@NgModule({
   declarations: [
      AppComponent
   ],
   imports: [
      BrowserModule.withServerTransition({ appId: 'universal' })
   ],
   providers: [],
   bootstrap: [AppComponent]
})
export class AppModule {
}

We can now build our server side / client side application. To do so, add a line in the scripts of our package.json:

"scripts": {
   ...
   "universal": "ng build --prod && ng build --prod --app universal --output-hashing=none",
   ...
}

You may ask, what is this command for? It simply generates, on the one hand, a client-side build and, on the other hand, a server-side build (with reference to our app configured in the .angular-cli.json file). For the server side, we remove the creation of a hash on the file generated main.bundle.js for reference later.

If we run the npm run universal command, we get our two builds in two separate files, dist / and dist-server /.

From now on, we want to be able to launch our server. For now, the Angular Universal Package only supports Node.js and ASP.NET. We will write our server in Node.js.

We must first install the package @nguniversal/express-engine that will bootstrap our server Node.js with the Express framework. So just run the command npm i -S @nguniversal/express-engine.

We will then write a server.js file to the root of our project with this content:

require('zone.js/dist/zone-node');

const express = require('express');
const ngUniversal = require('@nguniversal/express-engine');

/**
* On charge le seul fichier de notre build côté serveur
*/
const bootstrap = require('./dist-server/main.bundle');

/**
* On crée motre instance Express
*/
const app = express();

app.get('/', (req, res) => res.render('index', {req, res}));

/**
* Obtient les fichiers statics provenant de la build dist/
*/
app.use(express.static(`${__dirname}/dist`));

/**
* Configuration de Express Engine
*/
app.engine('html', ngUniversal.ngExpressEngine({
   bootstrap: bootstrap.AppServerModuleNgFactory
}));
app.set('view engine', 'html');
app.set('views', 'dist');

/**
* Toutes les URLs renvoient à l'index.html du répertoire dist/
* Angular se charge se rediriger vers les bonnes routes
*/
app.get('*', (req, res) => res.render('index', {req, res}));

/**
* On lance notre serveur
*/
app.listen(3000, () => console.log(`Listening on http://localhost:3000`));

Time to celebrate! We have successfully configured our Angular application as well as our Node.js server.

Launch the server by typing ‘node server.js’ and go to the URL http://localhost:3000. Your page is server-side generated at launch, and then supported by the client-side build when loaded. If you disable JavaScript in your browser, your page is still generated because you have already properly configured it following these instructions.

How to Transfer the State of the Application?

Although our application works perfectly with this configuration, it is not completely optimal. If your application requires requests via a Rest API, for example, these will be done twice instead of once. Indeed, if the server is requested to make a request, the browser does not know it and will perform the same request a second time when the server side will take over.

For example, we can start by adding the HttpClientModule in our app.module.ts and our app.server.module.ts (the ideal would be to have a module file in common, but I leave you the freedom to do it!):

import {HttpClientModule} from '@angular/common/http';

@NgModule({
   ...
   imports: [
      ...
      HttpClientModule
   ],
   ...
})
export class AppModule {
}

Let’s go into our app.component.ts and delete the content we will replace with:

import {Component, OnInit} from '@angular/core';
import {HttpClient} from '@angular/common/http';

@Component({
   selector: 'app-root',
   templateUrl: './app.component.html'
})
export class AppComponent implements OnInit {
   image: any;

   constructor(private http: HttpClient) {
}

ngOnInit() {
   this.http.get('http://www.splashbase.co/api/v1/images/random')
      .subscribe(data => this.image = data);
    }
}

We will display a random image retrieved via a Rest API.

For rendering, let’s edit our app.component.html file that we will replace with this unique tag:

< img *ngIf="image" [src]="image.url" >

This image will be the result of our request to the API.

If we start a build with npm run universal and launch our server with ‘node server.js’, we have our page working correctly. The only downside is that the image appears a few milliseconds and is then replaced by another image. The reason is the same as before, a request is made server side, and another is made client side once the page loaded. The client-side query is therefore useless.

The idea here is to transfer the state of our request to the client side so as not to multiply unnecessary requests. To do so, we will import the ServerTransferStateModule in our app.server.module.ts and the BrowserTransferStateModule in our app.module.ts:

/* app.server.module.ts */
import {ServerTransferStateModule} from '@angular/platform-server';

@NgModule({
   imports: [
      ServerTransferStateModule /* Ici ! */
   ],
   bootstrap: [AppComponent],
})
export class AppServerModule {}

/* app.module.ts */
import {BrowserTransferStateModule} from '@angular/platform-browser'

@NgModule({
imports: [
   ...
   BrowserTransferStateModule /* Ici ! */
   ],
   bootstrap: [AppComponent],
})
export class AppServerModule {}

Once the configuration is done, we can go to our app.component.ts file in order to create a key before the declaration of our Class and to add TransferState in our constructor, such as the following:

import {makeStateKey, TransferState} from '@angular/platform-browser';

const IMAGE_KEY = makeStateKey('image');

@Component({
   selector: 'app-root',
   templateUrl: './app.component.html'
})
export class AppComponent implements OnInit {
   ...
   constructor(private http: HttpClient,
      private state: TransferState) {
   }
...
}

Then we modify our ngOnInit method in the following way:

ngOnInit() {
   const image: any = this.state.get(IMAGE_KEY, null);

   /**
   * Si l'image n'est pac contenue dans notre clef, on effectue la requête
   */
   if (!image) {
      this.http.get('http://www.splashbase.co/api/v1/images/random')
         .subscribe(data => {
            this.image = data;
            this.state.set(IMAGE_KEY, data as any);
          });
   }

   /**
   * Sinon, on récupère le contenu de notre clef
   */
   else {
      this.image = image;
   }
}

We then launch a build of our application as well as our server.

npm run universal
node server.js

Now, the content of the image is transferred from the server to the client and the request is made only once!

Conclusion

You are now well equipped with all you need to start an Angular application with server-side rendering configuration. As a precaution, you may now refrain from using all objects available in your browser unreservedly. For example, you may want to verify whether an object is client side or not. Consider the following example:

import { PLATFORM_ID, Inject } from '@angular/core';
import { isPlatformBrowser } from '@angular/common';

   constructor(
      @Inject(PLATFORM_ID) private platformId: Object,
      @Inject(APP_ID) private appId: string) {
      if (isPlatformBrowser(platformId)) {
         console.log('Je suis appelé côté client !')
      }
    }

All these tips are meant to simplify your Angular developments with all the benefits of server-side rendering! Please stay tuned for more helpful tips…

Press Review Inno #10

Design

What Is Design System?

By Patrick Bracquart

For several years now, the complexity of the websites and applications has pushed us towards rethinking the concept of design, as well as the methodologies we use in the design process. This rethink is pushed by an ever-expanding field of necessary skills and positions in design such as web analyst, UI/UX designer, interaction designer, front-end developer and so forth. It is within this context that the idea of “design systems” has come forward.

A design system is the primary UI/UX reference of a project. It provides us with a guide that can serve as a support for the entire chain of production, no matter the subject matter (fashion, style, food, services, …), the terminal (laptop, mobile phone, smartwatch, …) or even the deliverable (websites, mobile applications, management interfaces, …).

More complete than a simple set of guidelines, this guide does not just describe the (atomic) design elements or the user interactions, it also lays out the development standards that should be followed, the accessibility standards to put in place, as well as iconography and video, to name a few. These guidelines and standards ensure that the entire Design Ecosystem remains perfectly coherent.

Mobile

How to Use Versatile Namespace in Swift?

By Thibault Wittemberg

In Swift, some APIs such as RxSwift use a technique that confines the code they are exposing in a dedicated namespace. This eases a lot the code reading and allows to extend this namespace to add your very own features.

In this post we will see that it is quite simple to create your own namespace and so generically that it allows an external contributor to extend it in an elegant way.