mirror of https://github.com/sveltejs/svelte
feat: bind `activeElement` and `pointerLockElement` in `<svelte:document>` (#11879)
* feat: bind `activeElement` and `pointerLockElement` in `<svelte:document>` * add test, use focusin/focusout rather than focus/blur --------- Co-authored-by: Rich Harris <rich.harris@vercel.com>pull/11913/head
parent
f3c291d8dd
commit
c0c1a56675
@ -0,0 +1,5 @@
|
|||||||
|
---
|
||||||
|
"svelte": patch
|
||||||
|
---
|
||||||
|
|
||||||
|
feat: bind `activeElement` and `pointerLockElement` in `<svelte:document>`
|
@ -0,0 +1,17 @@
|
|||||||
|
import { listen } from './shared.js';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param {(activeElement: Element | null) => void} update
|
||||||
|
* @returns {void}
|
||||||
|
*/
|
||||||
|
export function bind_active_element(update) {
|
||||||
|
listen(document, ['focusin', 'focusout'], (event) => {
|
||||||
|
if (event && event.type === 'focusout' && /** @type {FocusEvent} */ (event).relatedTarget) {
|
||||||
|
// The tests still pass if we remove this, because of JSDOM limitations, but it is necessary
|
||||||
|
// to avoid temporarily resetting to `document.body`
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
update(document.activeElement);
|
||||||
|
});
|
||||||
|
}
|
@ -0,0 +1,16 @@
|
|||||||
|
import { flushSync } from 'svelte';
|
||||||
|
import { test } from '../../test';
|
||||||
|
|
||||||
|
// This test is slightly inaccurate, because blurring elements (or focusing the `<body>` directly)
|
||||||
|
// doesn't trigger the relevant `focusin` event in JSDOM.
|
||||||
|
export default test({
|
||||||
|
test({ assert, target, logs }) {
|
||||||
|
const [btn1, btn2] = target.querySelectorAll('button');
|
||||||
|
|
||||||
|
flushSync(() => btn1.focus());
|
||||||
|
assert.deepEqual(logs, ['...', 'BODY', 'one']);
|
||||||
|
|
||||||
|
flushSync(() => btn2.focus());
|
||||||
|
assert.deepEqual(logs, ['...', 'BODY', 'one', 'two']);
|
||||||
|
}
|
||||||
|
});
|
@ -0,0 +1,10 @@
|
|||||||
|
<script>
|
||||||
|
let active;
|
||||||
|
|
||||||
|
$: console.log(active?.id || active?.nodeName || '...');
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<svelte:document bind:activeElement={active} />
|
||||||
|
|
||||||
|
<button id="one">one</button>
|
||||||
|
<button id="two">two</button>
|
Loading…
Reference in new issue