Bhanu
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee
    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee
  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    # Re-factoring Papad angular front-end application [TOC] ## 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.test.openrun.net) ``` +-- 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 ![](https://i.imgur.com/xioxZTz.png) 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. * [#29 Tag filter not filtering all cards when all tags selected](https://gitlab.com/thiya1995/papad/-/issues/29) * [#30 Tag highlight state should be Restful](https://gitlab.com/thiya1995/papad/-/issues/30) * [#68 Filtering not working when unclicking tag](https://gitlab.com/thiya1995/papad/-/issues/68) * [#74 Another bug re. tags](https://gitlab.com/thiya1995/papad/-/issues/74) `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. :::spoiler Expand here to see, sample tag click handler from `papad.component.ts` ```typescript=88 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](https://www.youtube.com/user/kudvenkat) as some real time example and scenarios are discussed. Remember i said there are 3 visual sections in the [demo](#Demo-of-the-papad-component), 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. ```typescript= 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

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully