(bindings: B = {} as B)
| 1 | import { useEffect, useState } from 'react'; |
| 2 | |
| 3 | export default function useMK<B extends BindingsType>(bindings: B = {} as B): MusishMK<B> { |
| 4 | type BindingsEvent = { [s in keyof B]: MKEvent }; |
| 5 | type BindingsList = keyof B; |
| 6 | |
| 7 | const [events, setEvents] = useState<BindingsEvent>({} as BindingsEvent); |
| 8 | |
| 9 | function handleEventChange(key: string, e: MKEvent) { |
| 10 | setEvents(previousEvents => ({ |
| 11 | ...previousEvents, |
| 12 | [key]: e, |
| 13 | })); |
| 14 | } |
| 15 | |
| 16 | useEffect(() => { |
| 17 | const bindingFunctions: { [s in BindingsList]?: MKEvent } = {}; |
| 18 | |
| 19 | for (const [key, eventName] of Object.entries(bindings)) { |
| 20 | const handler = (e: MKEvent) => handleEventChange(key!, e); |
| 21 | |
| 22 | bindingFunctions[eventName as BindingsList] = handler; |
| 23 | // @ts-ignore |
| 24 | MusicKit.getInstance().addEventListener(eventName, handler); |
| 25 | } |
| 26 | |
| 27 | return () => { |
| 28 | for (const [eventName, func] of Object.entries<MKEvent>(bindingFunctions)) { |
| 29 | // @ts-ignore |
| 30 | MusicKit.getInstance().removeEventListener(eventName, func); |
| 31 | delete bindingFunctions[eventName as BindingsList]; |
| 32 | } |
| 33 | }; |
| 34 | }, []); |
| 35 | |
| 36 | return { |
| 37 | instance: MusicKit.getInstance(), |
| 38 | ...events, |
| 39 | }; |
| 40 | } |
no outgoing calls
no test coverage detected