Wednesday, 1 May 2019

React: overkill with Redux and where Portals save the day



Recently I encountered a situation where I needed to overlay a div on top of another div. The standard way to do this is to use CSS and absolute or fixed positioning (https://stackoverflow.com/questions/2941189/how-to-overlay-one-div-over-another-div).

Sounds simple enough, however I need to do this from within a deep hierarchy of elements:

-> Detail Component
  -> Action Bar Component
  -> Items Component: Loop through and display expandable content divs
       -> On Click : overlay a component which is a div containing "expandable content"

The "items" component uses a standard bootstrap table to align the elements like so:
item 1 item 2
item 3 item 4

This layout means that when you select the onClick() for "item 1" and you render the expandable component which is essentially just a div, and it is positioned relatively the the content will appear in place of item one in the table.
item 1
(expandable content)
item 2
item 3item 4


Cut a long story short, every which way I tried to style the popup unwanted styles would be inherited from the table and other components above it. I also found that I had to place it absolutely to get the effect I was looking for which created a raft of further problems. Finally, it was suggested that this might be a good use case for React Portals which did indeed save the day.

I also learned on this project how much Redux can be over utilized. "When you have a hammer, everything starts to look like a nail". This was said a lot, and it should be, because when you are deep into the detail of a project it can be hard to see that it has been over-engineered.

Monday, 6 August 2018

Angular Progressive Web Apps

When in doubt refer to the Offical docs. When that doesn't work - try this manual fix it like I did!

Issues with Angular-cli

First it turns out that using ng add, as below, doesn't work very well.

ng add @angular/pwa --project project_name

I thought that maybe these issues were due a change in the Angular app file hierarchy (I changed "src" to "web"). I don't think this was the problem because many other people got stuck on the same error here and here.

Error highlighted below:
Installing packages for tooling via npm.
+ @angular/pwa@0.7.2
added 2 packages in 12.443s
Installed packages for tooling via npm.
Path "/ngsw-config.json" already exist.
I was able to get going by looking to see what this process is suppose to do.

Luckily it doesn't do a great deal and it is possible to find the files by searching your node_module directory then pasting them in before changing the parameters to suit your project - for example: ngsw-config.json to the code root and manifest.json to the /src directory. 

I was also able to better understand what the process should do by looking closely at this git commit. Notice the process adds:
"buildOptimizer": true,
"serviceWorker": true

to angular.json then adds the manifest.json before referencing it in the index.html:
<link rel="manifest" href="manifest.json">
<meta name="theme-color" content="#1976d2">

Issues with testing service workers locally (A bad HTTP response code (404) was received when fetching the script)

This is a message you are will most likely see when you are attempting use the angular cli server and PWA. Probably running:

ng serve --prod

This is again a heavily documented issue yet that didn't stop me scratching my head.

ng serve will not run the required service worker compilation only ng build will do that - see.

This article also goes on to explain that only secure origins are allowed for service workers. Please consider whether it is worth the time to get this working too. The chances are that the project will work on a secure, encrypted site already now, if deployed.

Finally, you may get "ngsw.json cannot be found" or "manifest.json cannot be found". This can be remedied in Azure at least by allowing JSON MIME type to be served by the web server. Bear in mind that any other JSON in your dist directory will also be accessible.

<configuration>
    <system.webServer>
        <staticContent>
            <mimeMap fileExtension=".json" mimeType="application/json" />
     </staticContent>
    </system.webServer>
</configuration> 

Is it true that service workers only work with transport layer security (TLS or SSL)

No, you can run locally with a local node instance. You can also run chrome with parameters to tell it to always consider localhost secure if you find issues with that. See the official documentation.

Monday, 19 February 2018

The jump between Angular Material 2 Beta 10 and Material Beta 11+

Having just been through this experience I thought I would share some thoughts to help any other early Angular Material adopters navigate their way to the later Beta's - 11 and 12 as well as the subsequent release candidates.

Change 1
Angular Material no longer can be imported into your project as just one module. You must instead select all of the modules which you intend to use in the project.

Change 2 - seemingly innocuous..
The problem with upgrading between these two versions is that the Md prefix has been changed to Mat. This unfortunately now clashes with the AngularJS Material implementation... such as Md2.

We were early adopters of Angular Material, so we are still using Md2 by Promact. Originally this was used as a stopgap while essential components like the date-picker were being completed by the official Angular Material team. However, now, we wish to use both Md2 and Angular Material side by side. Especially since I was originally putting together the project with Angular 4.0.1 and now wish to upgrade to the latest.

ERROR Error: Uncaught (in promise): Error: The "mat-" prefix cannot be used in ng-material v1 compatibility mode.

To get around this you must use the "CompatibilityModule" or "NoConflictStyleCompatibilityMode" or something...?
use compatibility module if you still want to use md- prefix like this
import { CompatibilityModule } from '@angular/material';
and import it in app module
if you want to use new mat- prefix which is good you can
use NoConflictStyleCompatibilityMode like this
import {NoConflictStyleCompatibilityMode} from '@angular/material';
When I first read this comment I was still confused. I just want my solution to work - what is all this!? This comment further down these thread helped me to understand:

Issue 1 thread
Issue 2 thread and relevent comment

I tried importing from material itself but this did not clear the errors.

import { NoConflictStyleCompatibilityMode } from '@angular/material';

Instead the solution seems to be to import and therefore invoke the NoConflictStleCompatibilityMode from MD2.
import { Md2Module, NoConflictStyleCompatibilityMode } from 'md2';

This makes sense because the use of mat in an angular/material v1 context can no only be in the MD2 project.

Wednesday, 12 April 2017

Checking Out React

I started my journey at the React Tutorial Page. While reading the introduction and checking out the code example on Codepen, I then had the notion that seeing as it was a Tic-Tac-Toe game, it might be nice to do it more properly and include it on my website.

Once down this road I then decided it would be good to turn it into a mini project to find out more about yarn and webpack, as these compliment the React world and are the shiny new toys in front-end web development.

This first blog in the series is about the setup.

Notes on Yarn and WebPack
I have heard that Yarn is better than NPM as a package manager, it is faster and more reliable. Webpack is more complex/flexible than Grunt or Gulp as a builder tool but, like my personal favourite JSPM (through systemJS) it is an excellent JavaScript module loader out of the box. Webpack is much more popular than JSPM within the React community.

Back to Tick-Tac-Toe
So I used npm to install yarn, ran yarn init and then used it to bring down my dependencies React and React DOM. I was pleased to find that there is no difference in where the modules are stored - it is still in a folder called "node_modules". I was also aware that I needed to "transpile" the ES2015 React code into ES5 so I installed babel using the "webpack" option on the babel installation page.
npm install --save-dev babel-loader babel-core
Notice that this is based on npm, but this was no problem, you can just replace "npm install" with "yarn add" and the command "--save-dev" with "-D". This was all easy to find here.

Using Webpack to transpile ES2015 back down to ES5
After some research I have found that the best way to use Webpack with babel, karma and react is to use the following packages:



With this setup I was able to setup a simple "hello world" example. I will get into more detail with my next post.

Thursday, 9 March 2017

Windows Azure and Node - Remember to specify the version

I kept finding that my back end code would subtly fail on something once deployed to an Azure site despite working fine in my own environment. Having hit the problem again recently, I again looked through the server logs to try to identify the problem assuming that again Node would be throwing an error over some very simple syntax.

Then I noticed the following:

"The package.json file does not specify node.js engine version constraints"
"The node.js application will run with the default node.js version 0.10.32"

This is old, in fact to put this into perspective the contemporary node change logs start from 0.12.0 which is the beginning of 2015. I had to go through their archive to find out where this version is from, which is October 2014!

Now I know, the solution is to specify the node engine that Windows Azure should use. e.g.


As soon as I had made this change my problems went away as you may expect. Looking at the latest "how to" guide on the Azure website for node development I notice that this features at step 5. However, for those who have legacy node websites on Azure, this is not so intuitive.

Saturday, 19 November 2016

Isomorphic or Universal Javascript

Why I have decided to learn about this?
I first truly took note of the term "Isomorphic JavaScript" when a recruiter sent me through a job which I thought looked extremely interesting. At the time I was not looking for a job, but it reminded me about the long standing problem with decent SEO and Single Page Applications (SPAs). I had heard a lot about React and Angular 2 providing some way to solve the problem, so I was curious.

Notably, the company in question were listing some other design patterns and technologies which were new to me and were also of interest: 12 factor app, Mesos and Marathon, CircleCI.

Godammit man, what does Isomorphic mean!
Isomorphic means "corresponding or similar in form". So essentially we are describing some sort of server side rendering to support the client side application.

Or as the AngularJS Universal Repository puts it: "A JavaScript Application that runs in more environments than just the browser".

The advantages?
  • The application does not need to rely on JavaScript being turned on in the browser for it to function
  • The application does not need to have a loading gif to explain to the user that patience is required
  • THE BIG ONE - The application can be more easily crawled by search engines because the page is also available from a static URL.
Some disadvantages and limitations
  • "Uncanny valley" - this is a term used to describe the time between the application appearing to be functioning and available and the time before it is actually responding to the users demands. This can be confusing for the user.
  • Loss of separation between back-end and front-end application code. However, I would say, in this API/ Micro-service architecture world, that this actually makes quite a bit of sense. The User Interface will still be separated from Business Logic, we are just blurring the line between server-side "Get" request responses and view rendering.
  • This is still just a bootstrapping technique and some SEO issues do still remain.
For a more thorough discussion on why Isomorphic JavaScript is "not the answer" take a look at this discussion on ycombinator (at your own risk of course!).

Sunday, 24 July 2016

Karma Error: You need to include some adapter that implements __karma__.start method






An error message which means very little. Something has gone wrong with Karma and it is affecting mine!

It looks like some breaking changes made in Karma-Runner 1.0.0 have really screwed over all the plugin projects such as Karma-Jasmine which I very much rely upon.

The only way around it at the moment is to downgrade Karma to 0.13.22 until Karma-Jasmine is compatible with v1.x.x versions of Karma.



v1.0.0

@dignifiedquire dignifiedquire released this on Jun 23

BREAKING CHANGES

  • context: Our context.html and debug.html structures have changed to lean on context.js anddebug.js. This is in preparation for deeper context.js changes in #1984.
As a result, all customContextFile and customDebugFile options much update their format
to match this new format.



Hmm clear as mud huh?

Certainly I will be keeping a close eye on this issue to see when I can upgrade safely.

UPDATE: It looks as though this has been fixed - all the errors related to this were consolidated in issue 2194 and released just days after I wrote this post.