HackMD
  • Beta
    Beta  Get a sneak peek of HackMD’s new design
    Turn on the feature preview and give us feedback.
    Go → Got it
      • Create new note
      • Create a note from template
    • Beta  Get a sneak peek of HackMD’s new design
      Beta  Get a sneak peek of HackMD’s new design
      Turn on the feature preview and give us feedback.
      Go → Got it
      • Sharing Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • 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
      • More (Comment, Invitee)
      • Publishing
        Please check the box to agree to the Community Guidelines.
        Everyone on the web can find and read all notes of this public team.
        After the note is published, everyone on the web can find and read this note.
        See all published notes on profile page.
      • Commenting Enable
        Disabled Forbidden Owners Signed-in users Everyone
      • Permission
        • Forbidden
        • Owners
        • Signed-in users
        • Everyone
      • Invitee
      • No invitee
      • Options
      • Versions and GitHub Sync
      • Transfer ownership
      • Delete this note
      • Template
      • Save as template
      • Insert from template
      • Export
      • Dropbox
      • Google Drive Export to Google Drive
      • Gist
      • Import
      • Dropbox
      • Google Drive Import from Google Drive
      • Gist
      • Clipboard
      • Download
      • Markdown
      • HTML
      • Raw HTML
    Menu Sharing Create Help
    Create Create new note Create a note from template
    Menu
    Options
    Versions and GitHub Sync Transfer ownership Delete this note
    Export
    Dropbox Google Drive Export to Google Drive Gist
    Import
    Dropbox Google Drive Import from Google Drive Gist Clipboard
    Download
    Markdown HTML Raw HTML
    Back
    Sharing
    Sharing Link copied
    /edit
    View mode
    • Edit mode
    • View mode
    • Book mode
    • Slide mode
    Edit mode View mode Book mode Slide mode
    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
    More (Comment, Invitee)
    Publishing
    Please check the box to agree to the Community Guidelines.
    Everyone on the web can find and read all notes of this public team.
    After the note is published, everyone on the web can find and read this note.
    See all published notes on profile page.
    More (Comment, Invitee)
    Commenting Enable
    Disabled Forbidden Owners Signed-in users Everyone
    Permission
    Owners
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Invitee
    No invitee
       owned this note    owned this note      
    Published Linked with GitHub
    Like BookmarkBookmarked
    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

    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 lost their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template is not available.


    Upgrade

    All
    • All
    • Team
    No template found.

    Create custom template


    Upgrade

    Delete template

    Do you really want to delete this template?

    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

    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

    Tutorials

    Book Mode Tutorial

    Slide Mode Tutorial

    YAML Metadata

    Contacts

    Facebook

    Twitter

    Feedback

    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

    Versions and GitHub Sync

    Sign in to link this note to GitHub Learn more
    This note is not linked with GitHub Learn more
     
    Add badge Pull Push GitHub Link Settings
    Upgrade now

    Version named by    

    More Less
    • Edit
    • Delete

    Note content is identical to the latest version.
    Compare with
      Choose a version
      No search result
      Version not found

    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. Learn more

         Sign in to GitHub

        HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.

        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
        Available push count

        Upgrade

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Upgrade

        Danger Zone

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

        Syncing

        Push failed

        Push successfully