From 2e3de4985135423122fe521fa0b9f4f81fd6e233 Mon Sep 17 00:00:00 2001 From: Elijah Duffy Date: Tue, 22 Jul 2025 15:39:21 -0700 Subject: [PATCH] focus: add selectAll helper, fix focus next behavior with selected text --- src/lib/focus.ts | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/src/lib/focus.ts b/src/lib/focus.ts index 2b22add..584dbd0 100644 --- a/src/lib/focus.ts +++ b/src/lib/focus.ts @@ -1,3 +1,4 @@ +import { tick } from 'svelte'; import type { Attachment } from 'svelte/attachments'; export type FocusKeymap = Record; @@ -73,7 +74,8 @@ export class FocusManager { }); } - /** Returns an attachment that adds a button element to the focus manager. + /** + * Returns an attachment that adds a button element to the focus manager. */ button(): Attachment { return (node) => { @@ -107,7 +109,7 @@ export class FocusManager { /** * Returns an attachment that adds an input element to the focus manager. */ - input(opts?: { keymap?: FocusKeymap }): Attachment { + input(opts?: { keymap?: FocusKeymap; selectAll?: boolean }): Attachment { return (node) => { this.add(node); this.attachFocusHandlers(node); @@ -126,6 +128,7 @@ export class FocusManager { this.focusPrevious(); } else if ( (e.key === 'ArrowRight' || e.key === 'End') && + target.selectionStart === target.selectionEnd && target.selectionEnd === target.value.length ) { this.focusNext(); @@ -150,6 +153,13 @@ export class FocusManager { e.preventDefault(); }); + if (opts?.selectAll) { + node.addEventListener('focus', async () => { + await tick(); + node.select(); + }); + } + return () => this.remove(node); }; }