Remove event listeners on dismount for reactive primitives

This commit is contained in:
daylily
2025-04-05 02:18:35 -04:00
parent 845040d9c4
commit d3740f20ef
2 changed files with 20 additions and 9 deletions
+14 -6
View File
@@ -1,5 +1,5 @@
import { DEVICE_PID, DEVICE_VID } from '$lib/constants'
import { getContext, setContext } from 'svelte'
import { getContext, onDestroy, setContext } from 'svelte'
import { toast } from 'svelte-sonner'
function isInkclip(dev: HIDDevice) {
@@ -24,18 +24,26 @@ export function createDeviceContext(): DeviceContext {
if (dev !== undefined) ctx.device = dev
})
navigator.hid.addEventListener('connect', e => {
if (isInkclip(e.device) && ctx.device === null) {
function connectIfIdle(e: HIDConnectionEvent) {
if (!isInkclip(e.device) || ctx.device !== null) return
toast.info('Device connected')
ctx.device = e.device
}
})
navigator.hid.addEventListener('disconnect', e => {
if (ctx.device === e.device) {
function disconnectIfSame(e: HIDConnectionEvent) {
if (ctx.device !== e.device) return
toast.info('Device disconnected')
ctx.device = null
}
navigator.hid.addEventListener('connect', connectIfIdle)
navigator.hid.addEventListener('disconnect', disconnectIfSame)
onDestroy(() => {
navigator.hid.removeEventListener('connect', connectIfIdle)
navigator.hid.removeEventListener('disconnect', disconnectIfSame)
})
return setContext(DeviceContextToken, ctx)
+6 -3
View File
@@ -1,3 +1,5 @@
import { onDestroy } from 'svelte'
export interface ReactiveMediaQuery {
readonly matches: boolean
}
@@ -7,9 +9,10 @@ export function createMediaQuery(query: string): ReactiveMediaQuery {
const queryState = $state({ matches: queryList.matches })
queryList.addEventListener('change', self => {
queryState.matches = self.matches
})
const updateQueryState = (e: MediaQueryListEvent) => (queryState.matches = e.matches)
queryList.addEventListener('change', updateQueryState)
onDestroy(() => queryList.removeEventListener('change', updateQueryState))
return queryState
}