12/31/19

Building MonthPicker With React Hooks - Part 3

Reminder

Hi guys, thanks for following my blog. This post is third part of: "Building monthpicker using nothing but react hooks" series. It is better for you to have a look on previous two parts (if you didnt do it before)

Year navigation

Now for final functionalities - like navigating between years in dropdown header


   ... 
   const [year, setYear] = useState((new Date()).getFullYear());

   const incYear = e => {
      e.preventDefault();
      setYear(year + 1);
   }

   const decYear = e => {
      e.preventDefault();
      setYear(year - 1);
   }

   ...
Pressing the two ">" shaped buttons at dropdown header - will move you to prevous or next year.

One last thing - (without it the target cannot consider accomplished) is "monthClick" hadler. the month should change when some of "months" clicked. This could be easily achieved by attaching proper handler to each button:

   const monthClick = (e, idx) => {
      const currmonth = `0${idx+1}`.slice(-2);
      onChange(`${currmonth}.${year}`);
      toggleMenu();
   }
That it, you can view this codesandbox to see the whole code:

12/26/19

Building MonthPicker With React Hooks - Part 2

Outside Click Behavior

It is common feature for a menus - to be closed when user clicks somewhere else (outside the dropdown panel). To achileve this functionality - we can use this custom hook


import { useEffect } from "react";

function UseOuterClickNotifier(onOuterClick, innerRef) {
    useEffect(
      () => {
        // only add listener, if the element exists
        if (innerRef.current) {
          document.addEventListener("click", handleClick);
        }
  
        // unmount previous first in case inputs have changed
        return () => document.removeEventListener("click", handleClick);
  
        function handleClick(e) {
          innerRef.current && !innerRef.current.contains(e.target) && onOuterClick(e);
        }
      },
      [onOuterClick, innerRef] // invoke again, if inputs have changed
    );
}

export default UseOuterClickNotifier;

So now , our month menu opens when clickinh inside input and closes when clicking outside

   UseOuterClickNotifier(
      e => setShown(false),
      elRef
   );

Displaying Months

Now - to the main purpose of the our widget: the displaying months:


   const months = ['Jan', 'Feb', 'Mar', 'Spr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
   ...

   {shown && <div className="month-menu-dropdown">
     <header>
      <div className="top-arrow"></div>
      <button onClick={decYear}>></button>
      <div className="year-holder">{year}</div>
      <button onClick={incYear}><</button>
    </header>
     {months.map((month, index) => (<button key={month} onClick={e => monthClick(e, index)}>{month}</button>))}
    </div>}

to get the buttons ordered at 3 columns and 4 rows, i will use grid-css feature:

.month-menu-dropdown {
    position: absolute;
    right: 0;
    top: 59px;
    min-width: 170px;
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    column-gap: 2px;
    row-gap: 5px;
    z-index: 3;
    background: #fff;
    border: 1px solid var(--text-color);
    border-radius: 2px;
    border: 1px solid grey;
    padding: 5px 0;
}

12/23/19

Building MonthPicker With React Hooks - Part 1

Motivation

I thought it can be interesting to make a post about - how i build a "month picker" util, by myself, using my little css/html/react knowledge and nothing else.
Searching through the web - i stumble upon this implementation of month picker, but after looking more deeply into the code i asked myself - is there some way to implement this functionality little more simplier-for-user?

Design

First step - lets think about how this monthpicker should look and how it should act.
Here is screencast of monthpicker in action:

Popup Menu

First thing to start with - i thought about "popup menu" - a dropdown menu which pops when user clicks the input


import React, {useState, useRef} from 'react';
const MonthPicker = () => {
   const [shown, setShown] = useState(false); 
   const elRef = useRef(null);
   const toggleMenu = () => {
      setShown(!shown);
   }

   return (
      <span className="month-menu-holder" ref={elRef}>
         
         <input onFocus={toggleMenu}/>
        
         {shown && <div className="month-menu-dropdown">
            <header>
               <div className="top-arrow"></div>
               <button><</button>
               <div className="year-holder">{'2019'}</div>
               <button>></button>
            </header>
            {/* here will come a days buttons */}
         </div>}
      </span>
   );
}

Currently - the "Thing" we created - just know how to make the drop menu to appear, but - that is a good start. Of course - most of the "tricks" of invisibility and positioning done by proper css:

.month-menu-holder {
    position: relative;
    display: inline-block;
}

.month-menu-dropdown {
    position: absolute;
    right: 0;
    top: 59px;
    min-width: 170px;
    ...
}


12/18/19

Interesting Code Adventure With Compare the Array Of Objects

Recently i had some interesting task: The form i was working on - was supposed to update array of objects:


[
 {id: 1, framework: 'React'},
 {id: 2, framework: 'Angular'},
 {id: 3, framework: 'Vue'},
]

The problem was - the api has a support only for only one object at time and according to design - a form was planned to have only one "save" button (which suppose to trigger a batch saving)

 POST - api/framework
 DELETE - api/framework/:id
 UPDATE -api/framework/:id

So i needed to find a way to compare the two arrays - the original and the modified, and store the changes - in order to send a proper request for each one.

I will post Solution i finally came with

Firstly i decided to compare the strings of strigified arrays:


    const isIdentical = JSON.stringify(modifiedArr) === JSON.stringify(oldArr);
    if (isIdentical) {
      alert(`no changes`);
      return;
    }

Since - if arrays identical - there is no need to perform any request...

Removed

Next step i decided to collect removed array items (if were any):


const removed = oldArr.filter(({id}) => !modifiedArr.find(item => id === item.id));

Im only checking which items i cannot find in modified array.

Added

Collect the new items:


const added = modifiedArr.filter(({id}) => !oldArr.find(item => id === item.id));

Here im checking exactly the opposite - which items i cannot find in the old array

Modified

Collect the modified items


const modified = modifiedArr.filter(modifiedItem => !oldArr.find(item => JSON.stringify(modifiedItem) === JSON.stringify(item)))

Here im checking which items are different from old Array by checking their json strings.
Note: the in all the cases - i taking advantage of filter function of an Array.

12/15/19

What is Session Authentication?

Intro

I want to post here some post for a simpletons like me, who sometimes discovers basic things about web they didn`t knew. For example - recently i asked myself: "what is exactly session?" and, shame on me - i discovered that i cannot give quick and clear answer. So i publishing here some facts i came upon while searching across the web:

Session

Some data stored at server (variable) which connected to some specific user, and "lives" when this user is connected to server. The old classic way to implement this behavior - by creating a cookie.
cookie - some piece of data that comes from server and stored at browser, it has it unique "id" given by server, and may have some other data (like expiration time). cookie should be sent at headers of each request. Server will check the cookie (or if it present) and this way server will now about user and if he is connected

Implementing Session Authentication using Express

Since express.js is the only server framework i feel comfortable with - i will do all the demonstrations using this framework.
So here is some simple server with '/login' and '/private' apis:


const express = require('express');
const app = express();
const port = 4000;
/* must use cors module for recieve requests from different domains */
app.use(require('cors')())

app.post('/login', (req, res) => res.send({user: 'Lukas'}));

app.get('/private', (req, res) => res.send({products: [{name: 'ZX10R'}]}));

app.listen(port, () => console.log(`Example app listening on port ${port}!`))

Pretty nice & simple, right?

Accessing Api`s from client

We have created a grate piece of software in previous step, but - what worth a server if nobody uses it?
In other words: lets create some client which will consume the our shiny apis!


async function bla() {

    const data = await fetch('http://localhost:4000/login', {
      method: 'POST',
      headers: {'content-type': 'application/json'}
    }).then(data => data.json())

    console.log(`hi ${data.user}!`);
    // passed login lets show some private stuff!
    const productsData = await fetch('http://localhost:4000/private', {
      method: 'GET',
      headers: {'content-type': 'application/json'}
    }).then(data => data.json())
          
   console.log(`product: ${productsData.products[0].name}`)
 
}
bla();

As you can see(if you copied the code correctly) - the data being fetched:

Restricting Private Api`s using session

Currently the '/private' api can accessed by everybody (and it is suppose to be private!), so lets make it accessible only to one who passed the login request:
We will do it using cookie-session npm package.
0. install 'cookie-session' lib (npm i cookie-session)
1. use basic configuration:


const cookieSession = require('cookie-session')
app.use(cookieSession({
    name: 'mysession',
    secret: 'your-secret',
    maxAge: 30 * 60 * 1000 // 1/2 hour
}));

2. we will add some data to our session once user passed login request (this code mimics fetching user details from DB)

app.post('/login', (req, res) => {
    req.session.user = 'Lukas';
    res.send({user: 'Lukas'});
});

3. add some middleware which will block (return 401 response) for someone who tried to access to any(except '/login') api when unauthenticated

app.use((req, res, next) => {
    if (req.url.includes('login')) {
        next();
        return; 
    }

    if (!req.session || !req.session.user) {
        res.clearCookie('mysession');
        res.status(401).send({error: 'unauthorized'});
        res.end();   
    }
});

One more thing! We need modify now also the client code:

async function bla() {
    const productsData = await fetch('http://localhost:4000/private', {
      method: 'GET',
      credentilas: 'include', /* each request should carry the cookie at its headers */
      headers: {'content-type': 'application/json'}
    }).then(data => data.json())
          
   console.log(`product: ${productsData.products[0].name}`)
}
bla();

Also at cors configuration - we need to specify "origin" to be trusted:

app.use(cors({
  origin: 'http://localhost:3000', /* host where you client runs */
  credentials: true,
}));

Now, open the "network" panel of chrome dev tools. You should should see the following:

Tada!!! you just make a client to talk to server using session !!!

8/17/19

Deboundce In The Javascript

Intro

I decided to wrote here all the things i know about the "debounce" termin
So: by saying "debounce" people mean - some functionality that blocks multiple event handlers from trigger until some specified time interval (like one second) passed.

Example: scroller, that fires lots of "scroll" events when user scrolling down, should respond only to last scroll event within second (specified time interval) and ignore all the rest of events within that second.

Implementation

The key thing for implementing debounce - is to know about "clearTimeout" method, which cancels the previously scheduled actions:


let timer = null;
const debounce = (fn, delay) => {
  // clean previously scheduled actions
  clearTimeout(timer);
  // scheduled  the last action
  timer = setTimeout(fn, delay);
};

document
  .querySelector("#myInput")
  .addEventListener("input", e =>
    debounce(_ => console.log(e.target.value), 1000)
  );
// you will see only last event appears after the delay

Or, if you want to store "timer" inside the function without polutting global scope:


var debounce = (fn, time, immediate) => {
  let timeout;
  return (...rest) => {
    const [args] = rest;

    const later = () => {
      if (!immediate) {
        timeout = null;
        fn(args);
      }
    };

    const callNow = immediate && !timeout;
    clearTimeout(timeout);
    timeout = setTimeout(later, time);

    if (callNow) {
      fn(args);
    }
  };
};
…

document
  .getElementById("app")
  .addEventListener("input", debounce(handle, 1000));

function handle(e) {
  console.log(e.target.value);
}


8/6/19

Why Do You Need "Set" In Javascript

Lets start with explanation what is set.
In the old times the only way to store some data list was by using array:

const users = ['Moshe','Vasia'];


These days some new players entering the scene:
The Set
It has "add", "delete", "clear" (for remove all the entries) methods

const users = new Set(['Moshe', 'Vasia']);
users.add('Ivan'); // will add one more entry

It also has "has" method for checking if item exists in Set:

console.log(users.has('Ivan')); // will print true

As far as I can see - the most cool feature (and may be a purpose of Set`s creation) - is uniqness: Set will not allow duplicates:

console.log(new Set([1,2,4,3,1])); // will 1,2,4,3

BUT (there must be always a "but")
all those cool features will not help you with following structure: (if the array consist of objects)

const users = new Set([
  {id:'123', name: 'Moshe'},
  {id:'124', name: 'Vasia'},
])

You will not be able to check if somebody with id '123' exist in Set using "has" method:

console.log(users.has('123')); // will be false

Also: it appears that Set not has a support for accessing entries by index And if you want to access first entry you will need to use something like this:

const user = users.values().next().value;
console.log(user); // will print "{id:123, name: 'Moshe'}"

Disappointing!
So, when this "Set" might be needed? you may ask...
The answer I found so far - is following scenario:
Remove duplicates:

const users = [
   {id:123, name: 'Moshe'},
   {id:124, name:'Vasia'},
   {id:125, name:'Ivan'},
   {id:123, name: 'Moshe'}// same Moshe one more time
];
const dedupedIds = Array.from(new Set(users.map(({id}) => id)))
console.log(dedupedIds); // will print 123,124,125

Conclusion

Although Set looks cool and promising - it seems there is not a much cases to use it (As far as I can see now)

7/20/19

Array and Object And When to Use Each Of Them

Where are lot of articles about this exact subject around the web, but, since I feel this doesn't clear anought for me - I feel like write a post about...

Object(Old good javascript object)

Pretty common scenario - when you have list of objects came from API:


const users = [
  {id:'123', name: 'Moshe'},
  {id:'124', name: 'Vasia'},
]

and you need to access one of the objects by its 'id' - you can do it by searching through the array, like this:

const currentUser = users.find(({id}) => id === '123');

But, of course, if you have array with lot of users - it will be much quicker to access some certain user by id - if "users" were stored inside Object with following structure:

const users = {
  '123': {id:'123', name: 'Moshe'},
  '124': {id:'124', name: 'Vasia'},
}
const currentUser = users['123'];

BTW, for optimize your performance you can restructure the users collection from array to object using following code:

let optimizedUsers = users.reduce((acc, user) => {
  return {
    ...acc,
    [user.id]: user  
  };
}, {});
const currenttUser = optimizedUsers['123'];
console.log(currenttUser.name); // will print "Moshe" 

You just saw the scenario with advantage of using Object upon Array

7/16/19

3 Design Patterns With Javascript By Example

Hi readers. I decided to list here some 3 design patterns i knew (Or so i think) implemented with Javascript:

1. Observer

Lets start with Observer pattern:
the special thing about this pattern is that:
it keep tracking changes on some object, and if changes occurred - it broadcasts the changes the to dependent objects.

Subject

To implement the pattern in javascript we need firstly create a "subject":

let Subject = function() {
  let observers = [];
  return {
    subscribe(ob) {
      observers.push(ob)
    }
    unsubscribe(ob) {
      observers.splice(observers.indexOf(ob), 1)
    },
    notify(ob) {
      if(observers.indexOf(ob)===-1) {return;}
      observers[observers.indexOf(ob)].notify()
    }
  }
}

As you can see, subject must contain "subscribe", "unsubscribe", and "notify" methods and store all the "observers" at some inner storage/variable

Observers

Next thing - lets create the Observer object/class - the only thing it must have - is a "notify" method (for being notified)

let Observer = function(num){
 return { notify: () => console.log(`num ${num} notified`)}
}

Thats it - from now we can create observers, subscribe and notify to observers that subscribed:

let s = new Subject();
let ob1 = new Observer(1)
s.subscribe(ob1);
s.notify(ob1);
s.unsubscribe(ob1);
s.notify(ob1); // will not print, because it unsubscribed

The example of this pattern usage, is "addEventListener" method where we can subscribe to some browser events (like click)

2. Factory

This pattern lets users to create objects ONLY by using "creator" (not directly by using "new" keyword)


let CarCreator = function(modl) {
  switch(modl) {
    case "zaporojets":
     return new Zaporojets(); // only creator can use "new"
     break;
    case "volga":
     return new Volga(); // only creator can use "new"   
     break;
  }
 

The idea here to simplify the objects instantiation for users - they only need to supply the type of car as a string:

 let my= CarCreator("volga");


3. Singelton

The idea of this pattern is NOT to let creation of more than one instance of some object:
Here is one of the ways i can think of - not to let users to use "new" keyword:


var Singelton = (function(){
  function someObj() {
    return {
      name:'vasia'
    }
  }
  // only here you can use the 'new'
  return new someObj();
  
}())
console.log(Singelton.name);// will print "vasia"
console.log(new Singelton);// will cause error

The example of this pattern usage, can be the great old JQuery library - that allows you only to use their "$" object without any "new"s prior to it...

7/11/19

Hooks in React

What is this new React feature everybody is talking about?
Well, it seems the main problem it tries to solve is - how to use state inside functional components.
Functional... what?
Ok, lets start from the beginning:
Usually to build the component with React you should use the following syntax:

class HelloMessage extends React.Component {
  render() {
    return (
      <div>;
        Hello {this.props.name}
      </div>
    );
  }
}

It also called the class syntax
The Interesting thing is - this is not the only way. There is another way to create react component, it called functional :

function Example(props) {
   return  ( 
      <div>;
        Hello {this.props.name}
      </div>
     );
}

This way is much more simpler and clear and testable, because - it is just javascript function!
BUT! (There is always but) - one of the limitations of functional components is - that here you cannot use the "state" feature of React.
State - it is inner data of the component which is not accessible from the parent

class UserForm extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      username:'',
      lastname: ''
    };
  }
  render() {
    return (
      <form>
        username: <input value={this.state.username}/>  <br/>
        lastname:  <input value={this.state.lastname}/>
      </form>
    );
  }
}

ReactDOM.render(
  <UserForm  />,
  document.getElementById('user-form')
);

So now (from React 16.8 and later) you can use state feature event inside functional components (Yes You Can!)- by using following syntax:

import React, { useState } from 'react';

export default function Example() {
    const [userModel, setUserModel] = useState({username:'ss', lastname:'dd'});

    return (
      <form>
        username: <input value={userModel.username}/>  <br/>
        lastname:  <input value={userModel.lastname}/>
      </form>
    );
  }

Note that "setUserModel" is for modify the state:

<button onClick={()=>setUserModel({username: 'shlomo', lastname: 'shlomovitz'})}/>click</button>

Pretty Cool, huh?

7/6/19

Tagged Template Literals

Ok, everybody heard about "backticks" ES6 feature...


 const hero = 'Splinter'
 console.log(`My name is ${hero}`); 
// will print "My name is Splinter"

But recently I stumble upon following code I could not understand:

import { css, cx } from 'emotion'

const color = 'white'

render(
  <div
    className={css`
      padding: 32px;
      background-color: hotpink;
      font-size: 24px;
      border-radius: 4px;
      &:hover {
        color: ${color};
      }
    `}
  >
    Hover to change color.
  </div>
)

What is this strange syntax?

Tagged Template Literals

Well it appears you can tag a template with function
Like this:

 const hero = 'Splinter';

 const printHero = html`My name is ${hero}`;
 // here is the function:
 function html(strings, ...values) {
   let str = '';
   strings.forEach((string, i) => {
       str += `${string} ${values[i] || ''}`;
   });
   return str;
 }

/*
printHero will print:
"My name is  <span class='hl'>Splinter</span> <span class='hl'></span>"
*/

Using tagged template gives you ability to control the way the template is parsed.

6/6/19

When You Should Use Subject

Subject - Who are you?

Yes, lot of us (angular people) have heard about subjects. Yes, it is something that acts like observable (you can subscribe to it):


const subject = new Subject();
...
subject.subscribe(x => console.log(x));

And simultaneously you also can call "next" method, like in observer:

 ...
 const button = document.querySelector('button')
 button.addEventListener("click", () => subject.next('click')); 
 ...

Ok, great, but... when it is good practice to use this Subject thing? you may ask...

Lets look on what Angular guys are Doing

Everybody who starts with "get started" section of angular - knows about "heroes tour" tutorial.
Quick search shows the use of "Subject" in the HeroSearchComponent.
Here you have a pretty common scenario: a search input which have to trigger a search request and populate with response results a list below the input...
So in "input" event handler you expect to see something like this:


  search(term: string): void {
    this.heroService.searchHeroes(term).subscribe(results => this.heroes = results);
  }

Or, when displaying the data using "Async" pipe, something like:

/*    
   <li *ngFor="let hero of heroes$ | async" >
      <a routerLink="/detail/{{hero.id}}">
        {{hero.name}}
      </a>
    </li>
*/
  search(term: string): void {
    this.heroes$ = this.heroService.searchHeroes(term);
  }

The problem with this code (although it will work) - is that the subscription to "searchHeroes" method is done each time when search terms changes, (not mention is already done at "ngOnInit" lifehook of the component):

 ngOnInit(): void {
    this.heroes$ = this.searchTerms.pipe( // pipe is the equivalent of "subscribe"
      // wait 300ms after each keystroke before considering the term
      debounceTime(300),

      // ignore new term if same as previous term
      distinctUntilChanged(),

      // switch to new search observable each time the term changes
      switchMap((term: string) => this.heroService.searchHeroes(term)),
    );
  }

And it is bad to subscribe multiple times, because of memory leaks potential. Instead - by using searchTerms Subject(like Angular guys did), you can call the "next" and trigger the service again, which is much more accurate:

  // Push a search term into the observable stream.
  search(term: string): void {
    this.searchTerms.next(term);
  }
 

5/2/19

How To Attach 'AddEvenlistener' Correctly

One of my recent tasks was - to implement the site side menu list (using vanilla javascript), and I was very glad to take a challenge - and practice my vanilla skills. I like to use vanilla - since I think it will replace in short future all the frameworks like react & angular...
Yes it sad (because I big fun of frameworks) but lets face the truth - javascript (or ECMASCRIPT) is developing very fast and already doing most of things we needed frameworks for...

Lets Focus, The Menu

So, menu is the very simple one, with links to all site subpages, but the goal is - that clicks on items should be handled only by javascript


<ul class="menu">
  <li><a href="javascript: void(0)">1 menu</a></li>
  <li><a href="javascript: void(0)">2 menu</a></li>
  <li><a href="javascript: void(0)">3 menu</a></li>
</ul>

For simplicity sake - lets say that "handle" means - to print the textContent of clicked item to the console.

First Try

So my first solution was to capture all the 'a' elements using "querySelectorAll" native method, and attach listeners to each of the using "forEach" loop:


document.querySelectorAll('ul.menu a')
.forEach(menuItem => menuItem.addEventListener('click', ({target}) => {
  console.log(target.textContent); // printing '1 menu' when first menu clicked 
}))

Second Look

After giving the code a second look - I suddenly figured out the things may be done much more simply - by attaching the listener only to parent 'ul' element:


document.querySelector('ul.menu').addEventListener('click', ({target}) => {
  console.log(target.textContent)
})

The advantage (except from simplicity) of this attitude is that instead of many listeners we using only one (which is much more performant)

Conclusion

The main reason we can use only one listener for many elements is the advantage of using "target" - the way to identify the element user clicked inside the parent element. The important thing here - is to know that event argument has also "currentTarget" property, and unlike "target"(which set to element the user actually clicked upon) - the "currentTarget" set to element the listener attached to

4/14/19

For the first time in my life - i dare to interview the interviewer

Recently I went to some job interview, which i, lets face the truth - totally failed. Since my career as developer last longer than 10 years, and had chance to work in a lot of places and on a lot of projects - it is definitely not my first interview, and event not first failed interview. Yet, at this post I want to tell you about some unique experiences I had during this particular adventure.

Details

Lets start from the beginning: It was an interview for the front-end position, and i was asked some javascript questions, like: how to check if a variable is an Array, or: how to prevent click event from bubbling from a child element to its parent. To be honest - I found myself caught unprepared for those questions (since almost year im working as a devops and completely forgot the differences between currentTarget and target, e.preventDefault and e.stopPropagation - shame on me!).
Yet the interesting thing was, that at some point, instead of focusing on my loose situation - I found myself trying to analyze the situation of the team that seeking to hire some frontend developer - and how it would be feel like working at this team

Conclusions

Here are some conclusions I come up with:

  • The interviewer didnt knew about ES Array.isArray method (instead - the answer he considered right was
    
    variableToCheck.constructor === Array
    
    
    )
  • Interviewer was surprised to find about existence of native javascript "fetch" method - instead he preferred to use jQuery ajax method for doing ajax request
  • The question about stopPropagation was a part of question:
    "how do you prevent a click on some element inside modal window to propagate to an overlay, when implementing modal dialog"
    - i tried to point out that nowadays browsers come up with a dialog HTML5 element which do exactly the dialog scenario (without need of coding anything) - but again caught the interviewer by surprise

Summary

Things can have various - a negative and a positive angles. At least I finally find out that as much important as to prepare yourself well for an interview - It is also important to try and figure out: what kind of work need to be done in the place you apply for. For example - this place did the impression of building some kind of new javascript framework instead of using some current, much better and simplier existing tools - a work I for sure would not be comfortable doing...

3/31/19

My Own Responsive Admin Template - Part 2

Almost every template/website is using some font icons (because it is easier use font rather than loading images) So In my case I will use font-awesome icons library.
when using this battle tested (and free!) library - you could display icons by using "fa" prefixed classes in your HTML:

      <header class="topbar">
          <a id="sidebar-toggle" class="sidebar-toggle" href="javascript:void(0);">
            <i class="fa fa-bars"></i>
          </a>
          <div class="input-wrapper">
            <input type="text"><i class="fa fa-search"></i>
          </div>

          <nav class="right-nav">
            <a href="javascript:void(0);">
                <i class="fa fa-bell"></i>     
            </a> 
            <a href="javascript:void(0);">
                <i class="fa fa-comment"></i>     
            </a>           
          </nav>
      </header>
Instead of install the library files locally I prefer to use online CDN. That way it can easily included in project:
https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.8.1/css/all.css

3/29/19

My Own Responsive Admin Template - Part 1

Motivation

There are lot of various admin templates out there across the internet like here and there (some even free) and you can find every combination you need instead of creating admin dashboard by yourself.
Yet, since I consider myself an experienced front end programmer - I decided to create responsive admin template of my own, sticking to recent best practices of web development.
Lets see there this little journey will take me and what discoveries I will make

Skeleton

So here I'm starting by create the first skeleton of dashboard using the basic HTML5 tags: aside, nav, main, section


  <div class="wrapper">
      <aside><!--for side nav-->
      </aside>
      <header class="topbar"><!--for topbar-->
         <nav> </nav>
      </header>
      <main>
      </main>
  </div>

Basic css

First thing here - I will declare css variables for each section:


:root {
    --topbar-bg-color: #2A62FF;
    --main-bg-color: #EDF5F8; 
    --sidebar-bg-color: #FFF; 
    --card-bg-color: #FFF;
    --text-color: #2F2F2F;
}

body { 
    background: var(--main-bg-color);
    color: var(--text-color);
}

/*  topbar  */
.topbar {
    background: var(--topbar-bg-color);
}
/*  aside  */
aside {
  width: 240px;
  background: var(--sidebar-bg-color);
}
/*  main  */
main {
    background: var(--main-bg-color);
}
/*  card  */
.card {
    background: var(--card-bg-color);    
}

Basic Layout using CSS Grid

Css grid - is a grate CSS3 feature for build various layouts
It gives you the ability to associate html elements with various grid areas


.wrapper {
    display: grid;
    height: 100vh;
    grid-template-areas:
    "aside topbar"
    "aside main";
    grid-template-columns: 240px auto;
    grid-template-rows: 40px auto;
}
.topbar {
    grid-area: topbar;
}
aside {
    grid-area: aside;
}
main {
    grid-area: main;  
}

3/25/19

Implementing javascript Promise by myself

Motivation

I remember that once (at some job interview) i was asked to write the Promise implementation by myself. Since it was long ago, and i dont remember what i wrote then (or if) - I decided to take the challenge again.
So i will write here about the process of implementation step by step.

Class

First of all - i decided to take advantage of ES6 feature - the classes, which makes you to write classes instead of functions:


// using ES6 "class" feature
class MyPromise {
  constructor() {
    console.log('constructor called');
  }
}
const p = new MyPromise();

Executor

One of the most significant specifications of Promise - is that it must receive an "executor" as parameter
Executor must be passed by user and it must be function
I implemented it - by placing executor as a constructor parameter:


class MyPromise {
  constructor(executor) {
    executor();
  }
}
// must get executor fired 
const p = new MyPromise(()=>{
  console.log('executor fired')
});

Resolve and Reject

A Promise executor must have two parameters - resolve and reject.
These "resolve" and "reject" are promise methods which can be passed as parameters to function where user can inject them according to his needs


// passing "res" and "rej" memebers to executor
class MyPromise {
  constructor(executor) {
    executor(this.resolve, this.reject);
  }
  resolve() {
    console.log('resolve fired');
  }
  reject() {
    console.log('reject fired');
  }  
}
const p = new MyPromise((res, rej)=>{
  res(); // calling the resolve
});

Then

Until now it was pretty easy...
Now comes the hard part: the "then"
The Promise must return the "then" and "catch" methods in which user should be able to pass success and error callbacks
It is not difficult to get "then" method returned:


class MyPromise {
  constructor(executor) {
    executor(this.resolve, this.reject);
  }
  ...
  ...
  then() { // then added to "myPromise" object
 
  }
  catch(err)  {
    
  }
}

The goal here is to get "success" callback to fire if "resolve" method called inside the executor
Here where is had 2 difficulties:
- the success callback must be already set when resolve method called (since resolve must trigger it! )
- how to pass "this" into resolve, since it called from "outside"!
I manage to solve the first obstacle by using "setTimeout", to call the executor asyncronously

// then must be returned
class MyPromise {
  constructor(executor) {
    setTimeout(()=>{executor(() => this.resolve(), () => this.reject());});   
  }
  
  resolve() {
   this.success && this.success(); // this.success should be set before resolve called 
  }
  reject() {
    console.log('reject fired');
  }
  then(cb) {
    this.success = cb;
  }
  catch(err)  {
    
  }
}
const p = new MyPromise((res, rej) => {
  res();
});
p.then(() => {
   console.log(`then callback fired `);
})

Data of Resolve

The last specification i decided to implement - is make "resolve" to able pass data to "success"
Here is what i come with:


//  "res" should pass data
class MyPromise {
  constructor(executor) {
    setTimeout(()=>{executor((d) => this.resolve(d), () => this.reject());}); 
  }
  
  resolve(data) {
   this.success(data);
  }
  reject() {
    console.log('reject fired');
  }
  then(cb) {
    this.success = cb;
  }
  catch(err)  {
    
  }
}
const p = new MyPromise((res, rej) => {
  res('o'); // "o" is the example data
});
p.then((data) => {
   console.log(`then fired ${data}`);
})

Summary

The "creating my own Promise" challenge - made me to think about few interesting question I nave not thought until now
I'm not sure i did the best solution possible here, but now i have motivation to look and search for implementations of better javascript coders ...

3/12/19

Hot vs Cold Observables

Recently I noticed the following code In the tests of some effect:

   const action = new fromActions.LoadPosts();
   actions$.stream = hot('-a', { a: action });
   const expected = cold('-b', { b: completion });
   
   expect(effects.loadPosts$).toBeObservable(expected);
This effect purpose is to activate request in response of "load posts" action:
Here is the effect code:

   loadPosts$ = this.actions$.ofType(postActions.LOAD_POSTS).pipe(
    switchMap(() => {
      return this.postService
        .getPosts()
        .pipe(map(posts => new postActions.LoadPostsSuccess(posts)));
    })
  );

According to Ben Lesh's explanation here: "observable is cold if its underlying producer is created and activated during the subscription"
In our case - the producer is Ajax request to "/post" API.
Since request is NOT made until someone subscribed to it - it considered cold
Unlike "loadPosts" action - which is hot:

export class LoadPosts implements Action {
  readonly type = LOAD_POSTS;
}
And here is what the test us checking - is in response to hot action, the cold request is following

2/24/19

SPA with vanilla javascript

It is 2019 now and javascript (es2019) is much more powerful than in the old days.
The following article is encourages me to try and see what can be gone when you using only plain js:
For example - to display a list of GitHub users from previous post it is anough to use the native javascript "map" :

document.querySelector('#container')
  .innerHTML = users.map(({login, count}) => `<li>${login} - <span>${count}</span></li>`).join(''); 
As result - the list with usernames and repos number will created on the page.
For completion of the picture we can add the "next" button that will display the next page:

 <button onClick="go()">next</button>
 <span>page:
    <i id='currPage'></i>
 </span>
 <ul id='container'>
 </ul>
The code for all this UI logic will be no more than 20 lines:

// getting data for page & displaying
function getPage(currentPage = -1) {
  currentPage++;
  // display loadign animation
  showLoader();
  
  getData(currentPage * 10).then((users) => {
     // display the number of page 
     updatePage(currentPage + 1);
     document.querySelector('#container')
       .innerHTML = users.map(({login, count}) => `<li>${login} - <span>${count}</span></li>`).join(''); 
  });
  return currentPage;
}

// display loading animation
function showLoader() {
  const img = '';
  document.querySelector('#container').innerHTML = img;
}

// displayes page number
function updatePage(page) {
  document.querySelector('#currPage').innerText = page;
}

// goes to nex page
function go() {
  page = getPage(page);
}

// getting page first time
page = getPage();
This is very minimalistic, but yet - kind of SPA!

2/18/19

What Is GraphQl

GraphQl - is query language.
A way you can quickly and clear explain what kind of data you want
Graphql can be compared to REST API:

In REST:

By sending request to "/users" url you telling server that you asking for users
By sending request to "/users/123" url you telling server that you asking for user with id 123

In GraphQl

the ways to "explain" to server what exactly you want are much wider:
Here is example how we can achieve the total repos count of user, only instead of using v3 GitHub api (like in previous posts)
we using GitHub grpahQL v4 api:

function getReposCount(user) {
  // graphQL query
  const query = `query {
     user(login: ${user}) {
       repositories {
         totalCount
       }
     }
  }`;

  const body = JSON.stringify({ query });

  const uri = `https://api.github.com/graphql`;
  return fetch(uri, {
    method: "POST",
    headers: { Authorization: `bearer ${token}` },
    body
  })
  .then(d => d.json())
  .then(data => {
    // extract only count field
    const {
      data: {
        user: {
          repositories: { totalCount: total }
        }
      }
    } = data;
    return total;
  });
}

2/11/19

Handle nested requests with rxjs

In the previous post i manage to get data using nested requests - by vanilla javascript.
In this post I will try to explain how to do the same thing, but using angular + rxjs library.
Firstly - lets write here the usual angular service which has "getUsers" and "getRepos" methods:

import { HttpClient,  HttpErrorResponse } from '@angular/common/http';
import { Observable} from 'rxjs';
import { from } from 'rxjs';

@Injectable({
  providedIn: 'root',
})
export class DataService {
  token = 'PUT-YOUR-TOKEN-HERE';
  constructor(private http: HttpClient) { }
  
  getUsers(since=0) : Observable {
    return this.http.get(`https://api.github.com/users?per_page=10&since=${since}&access_token=${this.token}`)
      .pipe(
        catchError(this.handleError('getUsers'))
      ) as Observable;
  }

  getReposCount(user) : Observable {   
    return this.http.get(`https://api.github.com/users/${user}/repos?per_page=10000&access_token=${this.token}`)
      .pipe(
        map(repos => repos.length || 0 ),
        catchError(this.handleError('getReposCount'))
      ) as Observable;
  }
  ...
  ...
}

But how to combine those two requests to work together as nested requests?
After googling around I came up with following code:

  getData(since) {
     return this.getUsers(since)
       .pipe(
         concatMap(users => from(users)),
         mergeMap((user) => this.getReposCount(user.login)
            .pipe(
              map(count => ({login: user.login, avatar: user.avatar_url, count}))
            )         
         ),
         toArray()
       )
  }
What a mess! - What is "form"? What are those "concatMap" and "mergeMap"? and why this "toArray" needed?
I will try to understand myself

Big Picture (as i understood so far)

The big picture of what is need to be done here - is:
* We need to convert the stream which brings as a collection to stream which brings us single user (one by one)
* For each user we need to send the request to get repos count and update the user object
* Stream of single users need to be converted back to stream of arrays


concatMap

according to the docs: Map values to inner observable, subscribe and emit in order (same as mergeMap but preserves the order)

from

according to this article - converts an array to an observable. - need for converting the observable of users array to observable of single users

mergeMap

Map to observable, emit values

why not switchMap?

In many examples, demonstrating how to do some operation on the stream - the "switchMap" method is widely used:


  getQuote(): Observable {
    return Observable.create(observer => observer.next(this.nextId++)).pipe(
      // here
      switchMap((id: number) => this.http.get(`api/quotes/${id}`)),
      map((q: Quote) => q.quote),
      ...
    )
SwitchMap is also maps the observable to different one , however - the main feature of switchMap is that it "kills" the previous observable, thus it cannot fit for our case...

2/8/19

Fetch the data using nested requests

Recently I was challenged with relatively common task - to fetch the data using nested requests.
More into the details:
the task was "to fetch GitHub users using GitHub API"(which s easy, but here is caveat:) each user must have a repoCount field (where total count of his owned repos should display):
The GitHub api ave the endpoint which brings you GitHub users, but each user has only "repos_url" field - a link to fetching repos

const token = 'your-github-access-token-here';

function getUsers(since=0) {
 const gitUri =`https://api.github.com`;
 const usersUri = `${gitUri}/users?per_page=10&since=${since}&access_token=${token}`;
 fetch(usersUri)
   .then(d => d.json())
   .then(data => {
      //  must get only those relevant two fields
      const modified_users = data.map(({login, repos_url}) => ({login, repos_url}));
      console.log(modified_users[0]);
   });
}

getUsers(0);
Outcome:
To bring the repos-count you will need to make one more request for each user to fill the missing data:

function getReposCount(repos_url) {
   // lets set "per_page" param to 10000
   // assuming no one can have so much repos
   // this way we will get the count using "length" property
   const reposUri = `${repos_url}?per_page=10000&access_token=${token}`;
   return fetch(reposUri)
   .then(d => d.json())
   .then(repos => {
     return repos.length || 0;
   })
}

Now we must change our "getUsers" so it will loop through all users and modify each user`s data properly:

 fetch(usersUri)
   .then(d => d.json())
   .then(data => {
      // loop through collection of users
      let promises = data.map(({login, repos_url}) => getReposCount(repos_url)
        .then(count => ({login, count}))); 
   
      Promise.all(promises).then((users) => {
         // lets display the data of ninth user
         console.log(users[9]); 
      })
   });

Now you can see the output:
The "count" field is added to user object!

2/3/19

Testing Angular directive using Jasmine Marbles

Directive in contemporary angular - means piece of code which doing something on the html block is attached to as attribute.

For example lets take a directive which changes value 'text-align' css rule, depending on "currentLang" property of translate service.

import { Directive, ElementRef, OnInit, OnDestroy } from '@angular/core';
import { TranslateService, LangChangeEvent } from '@ngx-translate/core';
import { Subscription } from 'rxjs';

@Directive({
  selector: '[rtl]'
})
export class RtlSupportDirective implements OnInit, OnDestroy {
  private subscription: Subscription;
  constructor(private el: ElementRef, public translate: TranslateService) {
    el.nativeElement.style.textAlign =
      translate.currentLang === 'he' ? 'right' : 'left';
 
  }
  ngOnInit() {
    this.subscription = this.translate.onLangChange.subscribe(
      (event: LangChangeEvent) => {
        this.el.nativeElement.style.textAlign =
          event.lang === 'he' ? 'right' : 'left';
      }
    );
  }

  ngOnDestroy() {
    if (this.subscription) {
      this.subscription.unsubscribe();
    }
  }
}
The idea is that Hebrew is "rtl" (right to left) language, and thus - the align must be changed to "right" in case of Hebrew.

How To Test

As you can see - the directive doing only two things:
1. setting text align according to current language
2. changing text align of element when language changed

Before Testing

Prior to testing directive - we need to create some component is will be placed on:


@Component({
  template: `
  <h2 rtl>Something Yellow</h2>
  `
})
class TestComponent {}

First Test

Testing the first behaviour is very easy: you only need to access the HTML element and check if "test-align" style property is set correctly:



  let fixture: ComponentFixture;
  let des: DebugElement[];

  beforeEach(() => {
    fixture = TestBed.configureTestingModule({
      imports: [TranslateModule.forRoot()],
      declarations: [RtlSupportDirective, TestComponent],
      providers: [
        {
          provide: TranslateService,
          useValue: {
            currentLang: 'he',
            onLangChange: of({lang: 'he'})
          }
        }
      ]
    }).createComponent(TestComponent);
    fixture.detectChanges(); // initial binding

    // all elements with an attached RtlDirective
    des = fixture.debugElement.queryAll(By.directive(RtlSupportDirective));

  });



  it('should set "text-align" rule value to "right" if current language is hebrew', () => {
    const textAlign = des[0].nativeElement.style.textAlign;
    expect(textAlign).toBe('right');
  });

Marbles

How to test the handling of "onLangChange" event (which is observable)?
One strategy in such scenario - is to use jasmine marbles


import { cold, getTestScheduler } from 'jasmine-marbles';
...
...
...

  beforeEach(() => {
    fixture = TestBed.configureTestingModule({
      imports: [TranslateModule.forRoot()],
      declarations: [RtlSupportDirective, TestComponent],
      providers: [
        {
          provide: TranslateService,
          useValue: {
            currentLang: 'he',
            onLangChange: cold('--x--y|', { //<-- here is the magic!
              x: { lang: 'he' },
              y: { lang: 'de' }
            })
          }
        }
      ]
    }).createComponent(TestComponent);

    getTestScheduler().flush(); // flush the observables
    fixture.detectChanges(); // initial binding
Note that first time the "flush" command is firing at "beforeEach" block and makes the language to be set with "he" value.

Testing The Change

To test handling of language change - we must simulate the "onLangChange" fired one more time
Since we use jasmine-marbles - to make this happen we only need to call "getTestScheduler().flush()"


  it('should set "text-align" rule value to "left" after current language changed to NOT hebrew', () => {
    getTestScheduler().flush(); // flush the observables
    fixture.detectChanges();

    const textAlign = des[0].nativeElement.style.textAlign;
    expect(textAlign).toBe('left');

1/20/19

Why you should use onPush detection strategy - Part 2

In the previous part you saw that "onPush" change detection strategy option - used for prevent angular to run the checks in vain (when no change which can affect the component made). Only when the thing that changed is the value passed to the component through input - the change detection will run, and reflect the change at HTML.

export class AppComponent  {
  name = 'Angular';
  onChangeNameClick() { 
    this.name = 'Angular the awesome'; // change the "name" which passed to inner
  }
}

Objects

But what about values which are not strings (like in example), but objects?
Lets say we have inner component that suppose to display selected product, When user clicks the "selectProduct" button - the new product should be displayed at inner component:

export class AppComponent  {
  product = {
    model: 'GSX1000R',
    manufacturer: 'Suzuki'
  };
  selectProductClick() { // nothing will change at inner component
    this.product.model = 'Z900';
    this.product.manufacturer = 'Kawassaki';
  }
}
As you can see - nothing changes at inner component after the click. But why?
The answer is - that angular consider the the input value changed only when object reference changed. In other words - the change will apply only when input value will receive new different object:

  selectProductCorrectClick() { // will display the change because reference changed
    this.product = {
      model: 'Z900',
      manufacturer: 'Kawassaki'
    }   
  }

1/18/19

Why you should use onPush detection strategy - Part 1

Angular is powerful framework. It gives you various options to write your components.
The simple one - using "Default" change detection strategy:

@Component({
  selector: 'my-app',
  templateUrl: `
   <div>
    <!-- some inner component here -->
    <inner></inner>
   </div>
  `
  // changeDetection not specified - means Default Strategy
})
export class AppComponent  {
  name = 'Angular';
}
"Default Strategy" means angular run change detection check every time he thinks that change is possible. (Changes may come as result of mouse or key events or Ajax requests)
That makes sense - every possibility of change requires careful check if HTML views need to be updated too.
But what if you have a dumb component that gets its data through the "input" property:

@Component({
  selector: 'inner',
  template: `
    

{{name}}

{{somePublicMethod()}} ` }) export class InnerComponent { @Input() name; somePublicMethod() { console.log('change check runned'); // will run twice no matter what kind of event happened } }
"somePublicMethod" will run twice no matter what kind of event happened (which is bad in terms of performance)
So, is there any way you can "help" angular not to do any unneeded checks inside this component unless the input data changed?
That is where "onPush" strategy appears very handful:

@Component({
  selector: 'my-app',
  templateUrl: `
   <div>
    <!-- some inner component here -->
    <inner [name]="name"></inner>
    <button (click)="onlyClick()">click to trigger some event</button>
   </div>
  `
})
export class AppComponent  {
  name = 'Angular';

  onlyClick() {
    // nothing changed, but mouse event "click" triggered
  }
}

...

@Component({
  selector: 'inner',
  template: `
    

{{name}}

`, // onPush is used!!! changeDetection: ChangeDetectionStrategy.OnPush }) export class InnerComponent { @Input() name; }
No change check will be run at "inner" component or its children in response to some event. The only case when check will run - is only when "name" property changed Read more in the next part

1/8/19

How to connect to gcp cluster from local terminal

Firstly you need Kubernetes installed on your machine

brew install kubernetes-cli
Open the cloud console UI, and navigate to "clusters" tab.
You will present with popup that displays command with exact parameters of the specific cluster

Note: if you already logged with different account - run "gcloud auth revoke --all"
and then: "gcloud auth login"

Now you can run the command in the console. It may happen you will be prompted with chrome asking for cloud credentials. After you get logged in, you can verify that you are in the correct cluster by, for example, checking for pods status:

kubectl get pods

1/3/19

How to unit test python

Lets start with something simple:
Lets say you have one method called "simple_inc" at module my:

# my.py
def simple_inc(x):   
    return x + 1 
Lets build some test using pytest framework:

# test_my.py
from my import simple_inc
def test_answer():
    res = simple_inc(3)
    assert res == 4
So far so good

Sub Method

Now lets change the code, so the "simple_inc" will use some sub method, lets call it "simple_child_inc":

def simple_inc(x):   
    return simple_child_inc(x)

def simple_child_inc(x):   
    return x + 1   
Now the test still should run as before, without any problems...

Mocking Sub Method

Since we want to stick to single responsibility principle, it will be better not to call the "real" submethod but its mock :

@mock.patch('my.simple_child_inc') 
def test_answer(mock_simple_child_inc):
    mock_simple_child_inc.return_value = 4 // correct val
    res = simple_inc(3)
    assert res == 4

If we change the correct value of the mock - the test will fail

@mock.patch('my.simple_child_inc') 
def test_answer(mock_simple_child_inc):
    mock_simple_child_inc.return_value = 4 // INCORRECT val
    res = simple_inc(3)
    assert res == 4

Async Method

Lets say the method we are testing is asynchronous:


import asyncio
async def inc(x):
    await asyncio.sleep(0.1)
    return x + 1

So the test should be modified in following way:

import asyncio

@pytest.mark.asyncio
async def test_answer():
    res = await inc(3)
    assert res == 4
The following test will also work if we make "inc" method to call "child_inc" (which is also async)

import asyncio

async def inc(x):
    res = await child_inc(x)
    return res

async def child_inc(x):
    await asyncio.sleep(0.1)
    return x + 1

Mocking Async Method

All we have to do is add asynctest package:


pip install asynctest
Now can change test:

import asynctest


@pytest.mark.asyncio
@asynctest.patch('my.child_inc')
async def test_answer(mock_child_inc):
    mock_child_inc.return_value = 4
    res = await inc(3)
    assert res == 4

1/1/19

What is decorator

After a lot of time working with angular, I suddenly found myself wondering: What exactly this syntax (like here):

@Component({
  selector: 'kinder-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent {
  showFeddback = false;
}
(which I use so lot of times) means?
In other words: what is exactly decorator?
According to angularjs docs:
Decorators are a design pattern that is used to separate modification or decoration of a class without modifying the original source code Which means: after you create some class - the decorator adds some additional functionality to it.
I decided to to experiment with creating my own decorator (to see how it feels to write decorator):


import { Component } from '@angular/core';
export function Vasia() {  
     console.log(`hhh!!!!`)   
}
@Vasia()
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Beautifull Girl';
}
Now each time you refresh the page - you will see 'stay with me!!!!' output in the console

Getting started with docker

It is very simple to get started usig docker. All you need to do-is download the docker desktop for your system Once you get docker syste...