Global constants

One thing that was bugging me in my flex-layout performance solution was how I defined the global constants for my three layouts PHONE, TABLET, and HD. As always with constants, I’m just trying to make the code clearer to the reader. There is nothing more to this than PHONE is 1, TABLET is 2, and HD is 3.

We are not able to use the const declaration inside of class definitions.

const sizeNum = {PHONE:1,TABLET:2,HD:3}

Attempting this results in:

 error TS1248: A class member cannot have the 'const' keyword.

We could define the constants outside of the class by putting the line of code just above the class, but this isn’t good encapsulation, and code fragments in the html template cannot see the constants. With the constants defined outside of the class, something like this is impossible:

<div *ngIf="activeSize()>sizeNum.PHONE">

Because of these issues, I resorted to a plain old hardcoded object, defined as usual inside of the class:

sizeNum: Object = {PHONE:1,TABLET:2,HD:3}

This doesn’t set up true constants. It is possible to programmatically change the sizeNum object later (eg. sizeNum[‘PHONE’]=5). Also, they are not global, and so I wound up having to pass the sizeNum object as a parameter to other components. Awkward.

There is a better way.

Angular dependancy injection

I am accustomed to using dependancy injection for full fledged classes, but it also can inject simpler objects. This works nicely for global constants. Set them up in app.module.ts:

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { PlaylstService } from './playlst.service';
...
const sizeNum = {PHONE:1,TABLET:2,HD:3}
@NgModule({
  declarations: [
    AppComponent
    ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
...
    ],
  providers: [
    PlaylstService,
    { provide:'SizeConstants',useValue:sizeNum }
    ],
  bootstrap: [AppComponent]
  })
export class AppModule { }

Put them into the constructor in desired components:

import { Component,
         Inject } from '@angular/core';
import { HttpClient,
         HttpHeaders } from '@angular/common/http';
...
import { PlaylstService } from './playlst.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
  })

export class AppComponent {

  accessToken: string;      // access token for the session.  we grep this outta the url
...
  constructor (
    private http: HttpClient,
    private plistSvc: PlaylstService,
    @Inject('SizeConstants') public szNum: any
    ) {
    // initializations
    try {this.accessToken=window.location.hash.match(/^#access_token=([^&]+)/)[1];}
    catch (ERR) {this.accessToken='BAD';}
...

Make use of them, no problem even in html code fragments:

<div *ngIf="activeSize()>szNum.PHONE">

Styling mat-menu items

Problem

I want Angular Material drop-down menu items to go wider before resorting to elipsis.

Here is a simplified example.  Angular Material cuts off the item, displaying elipsis

html:

<mat-menu #playlistMenu="matMenu">
  <button mat-menu-item>
    aaaa bbbb cccc dddd eeee ffff gggg hhhh iiii jjjj kkkk llll
  </button>
</mat-menu>
<button mat-button class="mat-title" 
  [matMenuTriggerFor]="playlistMenu">
  Playlist <i class="material-icons">arrow_drop_down</i>
</button>

Results:

Solution

By providing my own class with a selector that is more specific than what Angular Material is using, my style declarations come in as overrides.  All other stylings remain in effect.

In styles.css:

div.plMenuCSS { 
  max-width:500px;
  background-color:lightgreen;
  }

Then in the html:

<mat-menu #playlistMenu="matMenu">
  <button mat-menu-item class="plMenuCSS">
    aaaa bbbb cccc dddd eeee ffff gggg hhhh iiii jjjj kkkk llll
  </button>
</mat-menu>
<button mat-button class="mat-title" 
  [matMenuTriggerFor]="playlistMenu">
  Playlist <i class="material-icons">arrow_drop_down</i>
</button>

Results:

Animation

In web app development, animation is automation of the position and display characteristics of DOM elements.  Angular provides its own programming interface for animations, insulating the developer from browser compatibility concerns.  The developer defines styles for different states a DOM element can take on, and defines transitions for how to change from one state to another.  Let’s first look at a non-animated example, and then animate it.

Hard cut

Say we have component with a variable named mood.  Sometimes it holds the value “friendly” and sometimes it holds the value “mad.”  In the component’s html template we display the value, but additionally we want a red background if mad.  So far none of this requires Angular animation.  We can use stock Angular to set the background color based on the mood value.

<p [style.background-color]=”mood==’mad’?’red’:’green'”>{{mood}}</p>

mad

This creates what Rachel Nabors calls a hard cut.  This term comes from video/film editing and means there is no transition from one scene to the next.  The first scene ends and the next scene appears abruptly.  In our case, the moment the value for mood changes, the background color instantly changes.  The text does too, but for simplicity let’s just focus our work on the background color.

Crossfade

We can introduce Angular animation to create a transition instead of a hard cut.  Say we want the colors to slowly transition for three seconds when the mood changes state, a rudimentary animation known in video/film editing as a crossfade.

Instead of directly setting the style for mad, we define an animation trigger.  In the trigger we define the style for mad (red) and the style for friendly (green), and how to animate the transition (take a leisurely 3 seconds to change color instead of doing it instantly).  I have named the animation trigger moodAni.

<p [@moodAni]=’mood’>{{mood}}</p>

mad

In Angular Typescript, in addition to the usual @Component selector and template, we define animations.  The <=> means do the transition when going either way, from mad to friendly or from friendly to mad:

@Component({
  selector: 'app-root',
  template: '<p [@moodAni]="mood">{{mood}}</p>',
  animations: [ trigger('moodAni',
    [ state('mad',style({backgroundColor:'red'})),
      state('friendly',style({backgroundColor:'green'})),
      transition('friendly <=> mad',animate('3s')) ]
    ) ]
  })
Crossfade?

The term “crossfade” isn’t in the code.  Any transition for an element that isn’t changing size or position is a crossfade.  More generally, what the Angular animation module does is known as tweening.  We define states or keyframes and then specify how long to take between each.  This is quite a bit like CSS transitions.  Indeed, you might be wondering how I managed to get Angular examples working directly inside this blog.  I didn’t.  They are pure CSS equivalents.

Nice corral you got there, Angular

If you haven’t made the plunge yet into Angular animations, you might be wondering if you’d be better off sticking with CSS transitions.  It is possible.  It’s what I was doing before I discovered Angular animations.  I like the Angular way better.  I don’t have to worry about browser differences, and the coding for animation is corralled into the component’s animations specification.

But some horses can get through that fence

Notice in the crossfade example above that if you click the button a second time quickly, the new animation immediately takes over.  In Shufflizer I have a case where this isn’t desirable — the download progress spinner.  For small playlists sometimes it would not fade smoothly in and out.  When the download was done before the fade-in was done, the progress spinner would cut over to the fade-out animation.  Nothing was technically wrong, but it was strange and unpolished.  Here is how I solved it.

Angular provides an event that fires at the beginning and the end of an animation.  I use this event to prevent shutting the progress spinner while the fade-in animation is still running.

<div class="dimmed"
  style="text-align:center;padding-top:100px;padding-left:20%;padding-right:20%" 
  *ngIf="dimSet()" 
  [@dimAnim] 
  (@dimAnim.start)="setAnim($event)" 
  (@dimAnim.done)="setAnim($event)">
  <mat-card class="webLandscape">
    <mat-card-content>
      <h2 class="example-h2">{{plLoadingDirection()}}loading...   {{progressPcnt()}}%</h2>
      <mat-progress-spinner mode="determinate" [value]="progressPcnt()" style="margin-left:auto;margin-right:auto">
      </mat-progress-spinner>
    </mat-card-content>
  </mat-card>
</div>

The progress spinner renders when dimSet() is true.  setAnim simply stashes the event object into a variable so dimSet can use it.

It all comes down to the last line in dimSet.  Return true if a playlist is loading or if the fade-in animation is still running.

setAnim(ev): void {
  this.anim=ev;
  }

dimSet(): boolean {
  let animStillRunning=this.anim 
    && this.anim.triggerName == 'dimAnim' 
    && this.anim.totalTime > 1 
    && this.anim.phaseName == 'start' 
    && this.anim.fromState == 'void' ;
  return this.playlistService.plIsLoading 
    || animStillRunning;
  }

I found the names of the event attributes on the AnimationEvent documentation page.

So I like the animations “corral” but when we need to know the status of an animation, it’s not an animation we can just set into motion and forget about, then special coding for animations comes back into our TypeScript code.

For more information about Angular animation, see the Angular animations page. It’s where I learned most of what I know about Angular animations.

Look of mat-raised-button verses mat-card

I choose raised for my upload to Spotify button because I wanted to convey its significance over the other buttons on the page.  The upload button commits the user’s changes.  Everything else is “just playing around” and easily discarded until the user clicks this button.  It’s the “serious” button.

One morning, looking at my interface with a fresh mind, I realized this creates an inconsistent UI when also using mat-card.  They both have the same raised style:

A user might think “the session minutes remaining button doesn’t do anything when I click it.”  It’s not a button but it looks like the button that is sitting right next to it, the most serious button of all.

I could have changed the upload button to a flat button, so it would be consistent with all of the other buttons on the page, but I still wanted to set it apart somehow.  So I decided to make it green.  My picklist for downloading a playlist is also green.  With this change, I am consistently using the color green to indicate where the user initiates playlist data transfer with Spotify, download and upload.  I like the tie to Spotify’s branding color, which is a similar shade of green.

This still leaves the upload button and the card with the same raised style, but I am satisfied.  When I make Shufflizer available to users, I will get some feedback about this.

 

 

Playlist song display

Each entry in a playlist is a song, displaying the song title, artist, and album.

On the left, the song’s position in the playlist is displayed, and also the beenhere listen indicator.  This indicator tells whether you have listened to the song recently in Spotify.  Songs with the beenhere listen indicator are pushed to the bottom of the playlist when you randomize.  If you click on the indicator, it clears.

The play button plays a preview clip of the song.  This does not count as a listen in Spotify.  It will not influence the beenhere listen indicator.

The remaining buttons are song position controls.  Clicking 1st move the song to the first position.  This example song already is in the first position, so the button is disabled.  Clicking down moves the song down one position.  In the tablet and hd layouts a few more buttons like these appear, such as an up button.

The rand button is the main attraction.  Think of it as the Shufflize button.  It randomizes the order of the songs, starting with the song you have clicked.  Songs above do not move.  Songs with the beenhere listen indicator are moved to the end of the playlist.

Downloading. Uploading.

Shufflizer download

When Shufflizer says it is downloading it means just the track listing, not the songs themselves:

Shufflizer upload

In Shufflizer, when you are done editing  a playlist, you upload it.  This commits your edits to Spotify:

There is a date added for each song in a Spotify playlist.  Because Shufflizer upload is redefining the playlist, all of these dates change to the current date.  Here is an example showing the dates in the Spotify desktop app, right after an upload from Shufflizer:

Spotify download

Spotify also has a download.  It means something different.  In Spotify, download means downloading the songs themselves, so you can then play them without incurring data charges or when you don’t have an Internet connection.

Shufflizer doesn’t know about and is not in any way affected by Spotify download.

 

Dups. Local files.

Dups

Shufflizer automatically removes duplicates from your playlist.  When it does this, it lets you know with an alert.

It was simpler for me to make Shufflizer delete duplicates than to make it accommodate them.  A fundamental motivation for Shufflizer is to not hear songs repeated.  Having the same song more than once in a playlist undermines this.

Local files

Shufflizer automatically removes local files from your playlist.  When it does this, it lets you know with an alert.

Probably most Spotify users don’t have local files in their playlists, or even know what they are.  Local files are mp3’s you have on your PC that you want Spotify to play.  They are not supported by the underlying technology upon which Shufflizer is built, the Spotify Web API, so I must remove them.

Don’t like these automatic actions?

Shufflizer isn’t immediately changing your playlist in Spotify when you see either of these alerts, and it certainly isn’t going to delete any files from your PC.  Shufflizer is making these adjustments to the copy of the playlist it is loading for you to edit.  A playlist is just a track listing, not the songs themselves, and no changes to your playlist are saved until you upload.  Don’t like these automatic actions?  Don’t upload.

 

 

Session timer solution

In my previous blog post I described a flaw in my implementation of a session timer.  Spotify doesn’t provide a way to monitor how much time is left but we know that the session lasts for sixty minutes, so I start my own sixty minute timer.  My problem was that I was inadvertently creating more than one.

A singleton timer

My solution is to create a singleton timer, by subscribing only once.  Instead of my class exposing the observable, it exposes the results – a simple numeric variable for the minutes remaining:

Observable.timer(0, 60000)
  .map(mins => 60 - mins)
  .takeWhile(minsRemaining => minsRemaining >= 0)
  .subscribe(x => this.minsRemaining=x);

In the HTML, I rely on Angular to automatically detect changes to minsRemaining.  Here is the button disable expression now.  The async pipe subscribe is gone:

<button (click)="uploadToSpotify()" mat-raised-button
  [disabled]="!playlistIsEdited()||minsRemaining<=0">
  <i class="material-icons">file_upload</i>Upload to Spotify
</button>

I had two other subscribes, not just one more, as I thought in my previous post.  I removed them.  Now everything references minsRemaining:

<mat-card style="width:120px;text-align:center;" 
  [style.background-color]="minsRemaining <= 5 ? 'red' : 'transparent'">
  <mat-card-content>Session minutes remaining</mat-card-content>
  <mat-card-content style="font-size:30pt;padding-top:10px;padding-bottom:10px;">
    {{minsRemaining}}
  </mat-card-content>
</mat-card>
Survive not only page reloads, but also sleeping

With the above in place, I started working on how to keep it accurate through page reloads.  I got something working, but then found that timer stalls when a PC goes to sleep.  I’d wake up a sleeping PC and the timer was off by the number of minutes slept.

So I changed to examining time elapsed on the clock, rather than trying to make my process accurately tick each minute.  The following code survives both page reloads and sleeping.

I am refreshing every five seconds now.  This keeps my precision to within 5 seconds after page reload or sleeping.  The 3600 is 60 minutes in seconds:

// sessionStorage survives page reloads

if (!sessionStorage.getItem(this.accessToken)) {
  sessionStorage
  .setItem(this.accessToken,Date.now().toString());
  }

//Date.now()-startedAt survives sleeping

Observable.timer(0,5000)
  .map(() => parseInt(sessionStorage.getItem(this.accessToken)))
  .map(startedAt => 3600-(Date.now()-startedAt)/1000)
  .map(secsRemaining => Math.ceil(secsRemaining/60))
  .takeWhile(minsRemaining => minsRemaining >= 0)
  .subscribe(x => this.minsRemaining=x);
expires_in=3600

Spotify indicates the number of seconds for the session in the url they return.  It’s always been 3600 seconds, which is 60 minutes, but if they ever do return something different, I should honor it.  So instead of hardcoding 3600, I parse it out of the url.  This is not some sophisticated thing that I could tap into to find out how much time is left.  It’s simply how many seconds total the token is good for.  It stays the same even when the page is refreshed.

try {this.expiresIn=parseInt(
  window.location.hash.match(/expires_in=(\d+)/)[1]
  );}
catch (ERR) {this.expiresIn=0}

// sessionStorage survives page reloads

if (!sessionStorage.getItem(this.accessToken)) {
  sessionStorage
  .setItem(this.accessToken,Date.now().toString());
  }

//Date.now()-startedAt survives sleeping 

Observable.timer(0,5000)
  .map(() => parseInt(sessionStorage.getItem(this.accessToken)))
  .map(startedAt => this.expiresIn-(Date.now()-startedAt)/1000)
  .map(secsRemaining => Math.ceil(secsRemaining/60))
  .takeWhile(minsRemaining => minsRemaining >= 0)
  .subscribe(x => this.minsRemaining=x);

 

Session timer problem

Spotify’s web API uses OAuth for user authentication.  I am using the option that produces an access token that works for sixty minutes and then expires.  I want the user to know about this, so that it is clear what has happened if the session expires.  Ordinary use of Shufflizer should not take more than a minute or two, but, of course, users can behave differently from what we expect, including simply leaving the app sitting open for a while and then returning.

My initial solution

I have created an Observable.timer that counts down minutes.  I render this in a box.  I turn the background red when we are down to five minutes.  When we are down to zero then I also disable the upload to spotify button.  It isn’t going to work any more.

Problem:  Observable.timer is cold

This has been working, but not exactly right.  After a bit of testing I have concluded that timer is a cold observable, rather than hot.  I am starting two sixty minutes timers, not one.  The first timer starts when the page loads.  It is reported in the box.  This is good.  The second timer starts when the user makes an edit to the playlist.  It controls the disable of the button.  This is bad.  Waiting until the user makes an edit is not what I intended and is not accurate.

Here is my observable.  This counts down minutes from 60:

this.sessionCountdown = Observable.timer(0, 60000)
  .map(mins => 60 - mins)
  .takeWhile(minsRemaining => minsRemaining >= 0);

My problem is in my HTML template, in my TypeScript expression for the disable.  TypeScript’s or operator (the double-bar ||) does not execute its second part unless its first part is false.  I coded an async pipe subscribe for the second part, not realizing that this subscribe creates its own instance of the timer.  The user finally makes an edit to the playlist.  Only then does TypeScript flop over to the other side of the double-bar, therefore starting the timer:

<button (click)="uploadToSpotify()"
  mat-raised-button
  [disabled]="!playlistIsEdited()||(sessionCountdown | async)<=0">
  <i class="material-icons">file_upload</i>
  Upload to Spotify
</button>

I am going to work on making the timer a singleton, so that I get something more like a hot observable.

While I am working on this, I also need to deal with page reloads.  I think I will do that with session storage.  The timer should not start over if the page reloads.

Scroll only a portion of the screen with flexbox

So far I am finding that flexbox does indeed work well for positioning and sizing items within the viewport.  I like its approach when we are creating an app rather than a document, and of course this usually is the case with Angular.  Here is an example.

A perfect scrollbar

Do you have content you want to stay at the top of the window instead of scroll away?  This means you have to take control of your content sizing such that the operating system’s native scrollbar for the window never appears.  This comes naturally to flexbox.  When there is only one flex item it takes all of the space – all of the remaining space, to be precise.  So use two div’s, with just the second one designated flex.  The first div will stay fixed at the top.  The second div will scroll.  There will be no wasted space, and no double scrollbars.  Here it is in pure HTML/CSS:

<html>
<body>
<div style="display:flex;
  flex-flow:column;
  height:100%">
  <div>my fixed content</div>
  <div style="flex:1;overflow-y:auto;">
    <p>my scrolling content</p>
    ... lots of content here ...
  </div>
</div>
</body>
</html>

In Angular we can use the flex-layout module to express the div tags more concisely:

<div fxLayout="column" style="height:100%">
  <div>my fixed content</div>
  <div fxFlex style="overflow-y:auto">
    <p>my scrolling content</p>
    ... lots of content here ...
  </div>
</div>

Here is an image of the results I get using this technique in my Shufflizer app:

[14-May-2018 For some reason, in Shufflizer I had to specify 100vh instead of 100%.  Using 100% resulted in simple whole app scrolling.  Using vh instead solved it except eventually I noticed a problem in MicroSoft Edge – div’s overlapped as if they didn’t know about each other, all starting at the top of the viewport.  So I went back to the pure HTML/CSS way, but using vh instead of %.  That worked in all the browsers I am testing (FireFox, Edge, Chrome).]