changed 5 years ago
Linked with GitHub

Re-factoring Papad angular front-end application

Background

Papad is a web annotation client application, at this time focusing on the audio annotations.
Say how we have HTML (Hyper Text Markup Language) pages, and links to these pages that we can refer in other pages, would also be nice if the web supported, what we call Hyper Media linking, so that one can refer to a section in the audio in specific contexts.

(Discuss how much of this background should be here, or be linked to other docs)

Features

The current features of this application is

  • Discovery - discover audio
  • Annotate - Add Tags, Description fields, comments or other metadata that will feed back into Discovery and recommendation algorithms

While the above is a abstract definition of the features, we'll specifically look into our current implementation, alpha version is a angular application.

  1. Card / Grid view - To show the listing of audios
  2. Tags cloud - To filter cards by tags
  3. Add Recording - Add a audio recording
  4. Add metadata - Add tags

Why angular

Well, the answer is these modern frameworks are all over the place. It's so easy to get started with so many online resources, but sadly all of them are "Hello World" programs with very less real world use cases. The developer will find herself doing lot more learning while implementing a real app. and ofworks all these jargons that's running around two way data binding, reactive programming, component architecture, and other jazz is supposed to make the developer's life easy. But i'll tell you what happens in reality in a bit.

Papad's current directories looks like this, and the very first look at this, one will have a question about what is papad folder. That's the component that's handling the home page in the app, look at demo here

+-- Papad
    +-- src
        +-- app
            +-- navbar
            +-- pages
                +-- papad
                    -- papad.component.html
                    -- papad.component.ts
                +-- papad-details
            +-- services
            --  app.module.ts
            --  app.component.ts
            --  app.component.html
            --  app-routing.module.ts
        +-- assets
        +-- environments
        --- index.html

Demo of the papad component

Looking at the above home page, we can visually see 3 main regions,

  1. Header
  2. Left Cards grid
  3. Right Tags cloud

And the papad.component.ts is handling the items 2 and 3, but there is quite a bit going on here between those two sections.

  1. fetch data from api service
  2. render cards
  3. prepare data to render tags
  4. bind events to click on tag, to filter
  5. and all this Restful

Just like that papad.component.ts is now a 200 lines TS file, the class defines about 12 variables.

Like i said earlier re. Angular's features, all that is given up in our current implementation, and the developer's life got no better. will discuss one specific problem to demonstrate this.

Why re-factor - Tag filter usecase

The Tags cloud you saw in the demo, is a small example and below is a list of issues that came up in our issue tracker during testing. There was always issues starting with how to filter data, where to save state, how to keep it RestFul.

selectList() is a method in papad.component.ts that is called when a tag is clicked. below is the code, but don't bother going through, i can explain what is happening.

  1. get the value of tag
  2. change the background color of tag
  3. update a array of selectedTags, referred as this.collectTags in the below code.
  4. map through array of cards data
  5. find index of cards that's got the tags
  6. do array.splice and update cards collection
  7. Use some regEx to do something
  8. save all this in browser local storage
  9. Set the router url accordingly

while doing all that, say another developer who wants to fix something in this code, doing CTRL-F for all the variables and so on, and debugging just got harder. we were probably better of with jQuery code.

Expand here to see, sample tag click handler from papad.component.ts
selectList(ele, value) { var y = value.parentElement; //console.log(y); //y.style.backgroundColor = "#8395a7"; var classList = y.classList; classList.toggle('suggest-selected'); var x = value.nextSibling; this.collectEle.push(y); // this.selectedTag.push(ele) // x.addEventListener("click", function (e) { // this.closeFunction() // y.style.backgroundColor = '#ecf0f1'; // x.style.visibility = 'hidden'; // }, false); this.collectTags.map((item) => { if (item === ele) { //x.style.visibility = 'visible'; } }); this.recordData = []; this.cloneArray.map(item => { item.newTag.forEach(key => { if (key === ele) { if(classList.contains("suggest-selected")){ this.selectedTag.push(item); this.filterArr.push(ele); } else { var remIndx = this.selectedTag.findIndex(function(selItem){ return selItem.id === item.id }); this.filterArr.splice(this.filterArr.indexOf(ele), 1); this.selectedTag.splice(remIndx, 1); if(this.selectedTag.length == 0){ this.selectedTag = [...this.cloneArray]; } //console.log("remove tag", this.selectedTag, item) } } }) }) this.changeTag = this.filterArr.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); if(this.changeTag) { this.router.navigate(['/pages/papad', { tags: this.changeTag }]); } else { this.router.navigate(['/pages/papad', {}]); } this.recordData = this.selectedTag.filter((a, b) => this.selectedTag.indexOf(a) === b) sessionStorage.setItem('SelectedTag',JSON.stringify(this.recordData)); this.toaster.success( this.recordData.length + ' audio(s) filtered') }

The re-factoring story

So, let's get back to basics here. Ofcourse i had to see a couple of videos and found this youtube channel really helpful, kudvenkat on youtube as some real time example and scenarios are discussed.

Remember i said there are 3 visual sections in the demo, yes, we need to break it down into it's fundamental parts.

Re-structuring components

My new folder structure is like this now, where i've created 5 components instead of the papad component , so much to break the 200 lines TS file. But it's atleast better, coz i don't have to do find in file, but i have to do find in folder.

+-- Papad
    +-- src
        +-- app
            +-- navbar
            +-- services
            +-- item-cards
            +-- items-collection
            +-- tag-item
            +-- tags-collection
            +-- channels

Let's look at our Tag component, at tag-component.ts which is a single tag, which is a <span> HTML element. It has two properties, value and selected which is inherited from it's parent, and declares a event that it emits when the tag.selected property changes, so the parent can update other components.

import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core'; @Component({ selector: 'app-tag-item', template: ` <span (click)="toggleSelected()" [ngClass]="selected ? 'badge-secondary' : 'badge-primary'" class="tag-item badge"> {{ value }} </span> `, styleUrls: ['./tag-item.component.scss'] }) export class TagItemComponent implements OnInit { constructor() { } @Input() value: string; @Input() selected: boolean; @Output() selectToggled: EventEmitter<any> = new EventEmitter(); toggleSelected() { this.selected = !this.selected; this.selectToggled.emit(this); } ngOnInit(): void { } }

more TBA

Plugging the Router

Plumbing for event bubbling

Is there any better way?

Conclusion

Select a repo