import { ChangeExcerptRange_Sender , EventHandler , NotifySender , PopupMenuOnNote_Sender , PopupMenuOnSelection_Sender , ProcessNewExcerpt_Sender , } from "@alx-plugins/marginnote" ; import PopupRecorder from "modules/recorder" ; import { showHUD } from "modules/tools" ; import { addonOnName } from "toggle-addon" ; import { SendNote , SendSel , SendToc } from "./modules/sender" ; export const onPopupMenuOnNote = ( sender ) => { if ( ! Application . sharedInstance ( ) . checkNotifySenderInWindow ( sender , self . window ) ) return ; if ( ! self [ addonOnName ] ) return ; if ( self . recorder === undefined ) { self . recorder = new PopupRecorder ( ) ; } if ( ! sender . userInfo . note ) { showHUD ( "Error: No note in sender" ) ; return ; } try { if ( self . recorder . isDuplicate ( Date . now ( ) ) ) return ; const note = sender . userInfo . note ; self . tocMode ? SendToc ( note ) : SendNote ( note ) ; } catch ( error ) { if ( error instanceof Error ) showHUD ( error . toString ( ) ) ; else showHUD ( JSON . stringify ( error ) ) ; } } ; export const onPopupMenuOnSelection = ( sender ) => { if ( ! Application . sharedInstance ( ) . checkNotifySenderInWindow ( sender , self . window ) ) return ; if ( ! self [ addonOnName ] || self . tocMode ) return ; if ( self . recorder === undefined ) { self . recorder = new PopupRecorder ( ) ; } try { const { selectionText : sel , document : book } = sender . userInfo . documentController ; if ( sel && sel . length ) { SendSel ( { sel , book } ) ; } } catch ( error ) { if ( error instanceof Error ) showHUD ( error . toString ( ) ) ; else showHUD ( JSON . stringify ( error ) ) ; } } ; type HanlderBasic < T extends NotifySender > = { handler : EventHandler < T > ; event : T [ "name" ] ; } ; type Hanlder = HanlderBasic < PopupMenuOnSelection_Sender > | HanlderBasic < ProcessNewExcerpt_Sender > | HanlderBasic < ChangeExcerptRange_Sender > | HanlderBasic < PopupMenuOnNote_Sender > ; export const bindEventHandlers = ( handlerList ) : { add : ( ) => void ; remove : ( ) => void ; handlers : { [ k ] : ( sender : any ) => void ; } ; } => { const handlers = { } ; handlerList . forEach ( ( v ) => { handlers [ "on" + v . event ] = v . handler ; } ) ; const add = ( ) => { handlerList . forEach ( ( v ) => { NSNotificationCenter . defaultCenter ( ) . addObserverSelectorName ( self , `on${ v . event }:` , v . event ) ; } ) ; } ; const remove = ( ) => { handlerList . forEach ( ( v ) => { NSNotificationCenter . defaultCenter ( ) . removeObserverName ( self , v . event ) ; } ) ; } ; return { add , remove , handlers } ; } ;