import Point from '../../common/Point' ; import Rect from '../../common/Rect' ; export default class Widget { protected parent : Widget | null ; protected canvas : HTMLCanvasElement ; protected children : Array < Widget > ; protected offsetRect : Rect ; constructor ( parent , canvas ) { this . parent = parent || null ; if ( canvas == null ) { if ( this . parent == null ) throw Error ( "Widget must have canvas!" ) ; else this . canvas = this . parent . canvas ; } else { this . canvas = canvas ; } this . children = new Array ( ) ; this . offsetRect = new Rect ( 0 , 0 , 0 , 0 ) ; if ( this . parent != null ) this . parent . addChild ( this ) ; this . eachChild ( el => el . onPaint ( ) ) ; } addChild ( child ) { if ( ! this . hasChild ( child ) ) { this . children . push ( child ) ; } child . parent = this ; } removeChild ( child ) { let i = this . children . indexOf ( child ) ; return this . children . splice ( i , 1 ) [ 0 ] ; } hasChild ( child ) { return this . children . indexOf ( child ) >= 0 ; } protected eachChild ( callback , bottomUp = true ) { if ( ! bottomUp ) { for ( let i = this . children . length - 1 ; i >= 0 ; i -- ) { if ( callback ( this . children [ i ] ) ) break ; } } else { for ( let i = 0 ; i < this . children . length ; i ++ ) { if ( callback ( this . children [ i ] ) ) break ; } } } public moveChildToTop ( child ) { child = this . removeChild ( child ) ; if ( child != null ) this . children . push ( child ) ; } protected onMouseDown ( point ) { this . eachChild ( function ( el ) { if ( el . hitTest ( point ) ) { el . onMouseDown ( point ) ; return true ; } else { return false ; } } , false ) ; } protected onMouseUp ( point ) { this . eachChild ( function ( el ) { if ( el . hitTest ( point ) ) { el . onMouseUp ( point ) ; return true ; } else { return false ; } } , false ) ; } protected onMouseMove ( point ) { this . eachChild ( function ( el ) { return el . onMouseMove ( point ) ; } , false ) ; } protected onPaint ( ) { } ; public redraw ( ) { this . onPaint ( ) ; this . eachChild ( function ( el ) { el . redraw ( ) ; } ) ; } public show ( ) { this . redraw ( ) ; } protected hitTest ( point ) { return this . offsetRect . isPointIn ( point ) ; } protected onDestroy ( ) { this . eachChild ( function ( el ) { el . onDestroy ( ) ; } ) ; this . children = [ ] ; if ( this . parent != null ) this . parent . removeChild ( this ) ; } }