Problem with mousetrap dependency in SvelteKit on the edge (Netlify)
jenseo opened this issue · 4 comments
Hello, I have successfully implemented and have had the pleasure to use your package in a static sveltekit-project for some time now and it's been working out really great for us! So first of all, thanks for that!
Now, in some of our environments we have moved away from a fully static prerendered site and instead run the SSR setup.
Problem is, the mousetrap dependency that are bundled with this package seems to interfere with the server part of our setup (Deno edge at Netlify).
We're getting the following error in our Edge logs:
ReferenceError: document is not defined at node_modules/mousetrap/mousetrap.js
I have tried making sure we only render what uses your trap inside an if ( browser )
statement, something like this:
if (open && browser ) {
<div use:focusTrap>
{ modalContent}
</div>
}
...but without luck unfortunately, the bundling of the code seems to be enough to break it. I guess since it evaluates on the server side anyways.
Would it be possible to get rid of the mousetrap dependency and solve those parts in another way? It seems that package is abandoned tbh, so maybe solving it in another way could be a better option?
Skimmed the code now and since this is a package I assume only is intended for a browser environment, maybe something like the following could work inside index.js:
export function focusTrap(node) {
if (typeof window === 'undefined') return;
...rest of code
}
@jenseo I am actually in the process of re-writing things right now.
Using the new sveltekit 'library' generator made it easy to move to Typescript and get some decent tests in place. Mousetrap was getting buggy and had some other small issues I wanted to solve.
I will be sure to address this ^ SSR issue when I get there and ping this thread for feedback.
@jenseo I have PR open now that will hopefully fix the SSR support for you:
#9
^ I was able to add SSR support, in that, we skip the whole directive if window.addEventListener
is not available... and because Vitest made it easy, I was able to add a test to this effect using an edge-runtime
, which mimics the Vercel runtime. https://github.com/Duder-onomy/svelte-focus-trap/pull/9/files#diff-e6b84a56fbdf9da85a6daf96f3935397070c539852e57523ec8fb057df8fe0c9
Additionally, I was able to drop the MouseTrap dependency since we were not using most of the library and it looked unsupported. I considered using Hotkeys.js instead but ended up making our own, again, because it just seemed simpler and Hotkeys.js seems to lack open-source support.
Anyhow, if you want to give this a shot and see if it works I would very much appreciate it.
I will probably merge the PR in a few days to get it moving. 👍
@Duder-onomy Sounds great to have Sveltekit support 🙌