import type { ErrorListener , ParserErrorCode , MathfieldErrorCode , } from '../public/core' ; import { ModelPrivate } from './model-private' ; export type ModelListeners = { onContentWillChange : ( sender : ModelPrivate ) => void ; onContentDidChange : ( sender : ModelPrivate ) => void ; onSelectionWillChange : ( sender : ModelPrivate ) => void ; onSelectionDidChange : ( sender : ModelPrivate ) => void ; onPlaceholderDidChange : ( sender : ModelPrivate , placeholderId : string ) => void ; onError : ErrorListener < ParserErrorCode | MathfieldErrorCode > ; } ; export function selectionDidChange ( model ) { if ( typeof model . listeners ?. onSelectionDidChange === 'function' && ! model . suppressChangeNotifications ) { model . suppressChangeNotifications = true ; model . listeners . onSelectionDidChange ( model ) ; model . suppressChangeNotifications = false ; } } export function contentDidChange ( model ) { if ( typeof model . listeners ?. onContentDidChange === 'function' && ! model . suppressChangeNotifications ) { model . suppressChangeNotifications = true ; model . listeners . onContentDidChange ( model ) ; model . suppressChangeNotifications = false ; } } export function placeholderDidChange ( model , placeholderId ) { if ( typeof model . listeners ?. onPlaceholderDidChange === 'function' && ! model . suppressChangeNotifications ) { model . suppressChangeNotifications = true ; model . listeners . onPlaceholderDidChange ( model , placeholderId ) ; model . suppressChangeNotifications = false ; } } export interface Disposable { dispose ( ) : void ; } export type EventListener = ( ... payload : any [ ] ) => void ; export class EventEmitter { events : Map < string , EventListener [ ] > ; constructor ( ) { this . events = new Map ( ) ; } addListener ( event , listener , options ? ) { if ( ! this . events . has ( event ) ) { this . events . set ( event , [ ] ) ; } options = options ?? { } ; if ( options . once ?? false ) { listener = ( ... payload ) : void => { this . events . get ( event ) ?. filter ( ( x ) => x !== listener ) ; listener . apply ( this , ... payload ) ; } ; } this . events . get ( event ) ?. push ( listener ) ; return { dispose : ( ) : void => { this . events . set ( event , this . events . get ( event ) ! . filter ( ( x ) => x !== listener ) ) ; } , } ; } on ( event , listener ) { return this . addListener ( event , listener ) ; } once ( event , listener ) { return this . addListener ( event , listener , { once : true } ) ; } emit ( event , ... payload ) { const listeners = this . events . get ( event ) ; if ( listeners && listeners . length > 0 ) { for ( const listener of listeners ) listener . apply ( this , ... payload ) ; return true ; } return false ; } }