import * as $ from 'jquery' ; import { fromEventPattern , merge , Observable , Observer } from 'rxjs' ; export function elementRemoved$ ( elem ) { let mutationObserver ; return fromEventPattern < any > ( ( handler ) => { mutationObserver = new MutationObserver ( ( mutations ) => { mutations . forEach ( ( mutation ) => { const nodes = $ . makeArray ( mutation . removedNodes ) ; if ( nodes . some ( ( node ) => node . contains ( elem ) ) ) { handler ( ) ; } } ) ; } ) ; observeAllNodes ( mutationObserver ) ; return mutationObserver ; } , ( ) => mutationObserver . disconnect ( ) ) ; } export function elementAdded$ ( test ) { let mutationObserver ; return fromEventPattern < Node > ( ( handler ) => { mutationObserver = new MutationObserver ( ( mutations ) => { mutations . forEach ( ( mutation ) => { const nodes = $ . makeArray ( mutation . addedNodes ) ; nodes . forEach ( ( node ) => { if ( test ( node ) ) { handler ( node ) ; } } ) ; } ) ; } ) ; observeAllNodes ( mutationObserver ) ; return mutationObserver ; } , ( ) => mutationObserver . disconnect ( ) ) ; } export function elementExist$ ( selector ) { return Observable . create ( ( observer ) => { const nodes = $ ( selector ) ; nodes . each ( ( i ) => { observer . next ( nodes [ i ] ) ; } ) ; observer . complete ( ) ; } ) ; } export function elementExistOrAdded$ ( selector ) { return merge ( elementExist$ ( selector ) , elementAdded$ ( ( node ) => $ ( node ) . is ( selector ) ) ) ; } function observeAllNodes ( mutationObserver ) { mutationObserver . observe ( document . body , { childList : true , subtree : true , } ) ; }