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 { DEVICE_PID, DEVICE_VID } from '$lib/constants'
import { getContext, setContext } from 'svelte' import { getContext, onDestroy, setContext } from 'svelte'
import { toast } from 'svelte-sonner' import { toast } from 'svelte-sonner'
function isInkclip(dev: HIDDevice) { function isInkclip(dev: HIDDevice) {
@@ -24,18 +24,26 @@ export function createDeviceContext(): DeviceContext {
if (dev !== undefined) ctx.device = dev if (dev !== undefined) ctx.device = dev
}) })
navigator.hid.addEventListener('connect', e => { function connectIfIdle(e: HIDConnectionEvent) {
if (isInkclip(e.device) && ctx.device === null) { if (!isInkclip(e.device) || ctx.device !== null) return
toast.info('Device connected') toast.info('Device connected')
ctx.device = e.device ctx.device = e.device
} }
})
navigator.hid.addEventListener('disconnect', e => { function disconnectIfSame(e: HIDConnectionEvent) {
if (ctx.device === e.device) { if (ctx.device !== e.device) return
toast.info('Device disconnected') toast.info('Device disconnected')
ctx.device = null 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) return setContext(DeviceContextToken, ctx)
+6 -3
View File
@@ -1,3 +1,5 @@
import { onDestroy } from 'svelte'
export interface ReactiveMediaQuery { export interface ReactiveMediaQuery {
readonly matches: boolean readonly matches: boolean
} }
@@ -7,9 +9,10 @@ export function createMediaQuery(query: string): ReactiveMediaQuery {
const queryState = $state({ matches: queryList.matches }) const queryState = $state({ matches: queryList.matches })
queryList.addEventListener('change', self => { const updateQueryState = (e: MediaQueryListEvent) => (queryState.matches = e.matches)
queryState.matches = self.matches
}) queryList.addEventListener('change', updateQueryState)
onDestroy(() => queryList.removeEventListener('change', updateQueryState))
return queryState return queryState
} }