import { Component , ElementRef , HostBinding , HostListener , Input , OnDestroy , OnInit } from '@angular/core' ; import { EditorView } from 'prosemirror-view' ; import { Subscription } from 'rxjs' ; import { NgxEditorService } from '../../../editor.service' ; import { MenuService } from '../menu.service' ; import { ToggleCommands } from '../MenuCommands' ; import { TBHeadingItems } from '../../../types' ; @ Component ( { selector : 'ngx-dropdown' , templateUrl : './dropdown.component.html' , styleUrls : [ './dropdown.component.scss' ] } ) export class DropdownComponent implements OnInit , OnDestroy { private editorView : EditorView ; private updateSubscription : Subscription ; @ Input ( ) group : string ; @ Input ( ) items : TBHeadingItems [ ] ; isDropdownOpen = false ; private activeItems : TBHeadingItems [ ] = [ ] ; disabledItems : string [ ] = [ ] ; activeItem : string | null ; constructor ( private ngxeService , private menuService , private el ) { } @ HostBinding ( 'class.NgxEditor__Dropdown--Selected' ) get isSelected ( ) : boolean { return Boolean ( this . activeItem || this . isDropdownOpen ) ; } @ HostBinding ( 'class.NgxEditor--Disabled' ) get isDropdownDisabled ( ) : boolean { return this . disabledItems . length === this . items . length ; } @ HostListener ( 'document:mousedown' , [ '$event.target' ] ) onDocumentClick ( target ) { if ( ! this . el . nativeElement . contains ( target ) && this . isDropdownOpen ) { this . isDropdownOpen = false ; } } getName ( key ) { return this . ngxeService . locals . get ( key ) ; } toggleDropdown ( e ) { e . preventDefault ( ) ; this . isDropdownOpen = ! this . isDropdownOpen ; } onClick ( e , item ) { e . preventDefault ( ) ; if ( e . button !== 0 ) { return ; } const command = ToggleCommands [ item ] ; const { state , dispatch } = this . editorView ; command . toggle ( ) ( state , dispatch ) ; this . isDropdownOpen = false ; } private update = ( view ) => { const { state } = view ; this . activeItems = [ ] ; this . disabledItems = [ ] ; this . items . forEach ( ( item ) => { const command = ToggleCommands [ item ] ; const isActive = command . isActive ( state ) ; if ( isActive ) { this . activeItems . push ( item ) ; } if ( ! command . canExecute ( state ) ) { this . disabledItems . push ( item ) ; } } ) ; if ( this . activeItems . length === 1 ) { this . activeItem = this . activeItems [ 0 ] ; } else { this . activeItem = null ; } } ; ngOnInit ( ) { this . editorView = this . menuService . editor . view ; this . updateSubscription = this . menuService . editor . update . subscribe ( ( view ) => { this . update ( view ) ; } ) ; } ngOnDestroy ( ) { this . updateSubscription . unsubscribe ( ) ; } }