diff --git a/src/lib/editor/ToolbarExpanded.svelte b/src/lib/editor/ToolbarExpanded.svelte index d62ed50..30e2c5e 100644 --- a/src/lib/editor/ToolbarExpanded.svelte +++ b/src/lib/editor/ToolbarExpanded.svelte @@ -77,12 +77,21 @@ let fontOpen = $state(false); let sizeOpen = $state(false); + let sizeInputFocused = $state(false); + let sizeInputValue = $state(''); let savedFrom: number | null = null; let savedTo: number | null = null; + $effect(() => { + if (!sizeInputFocused) { + sizeInputValue = currentFontSize ? currentFontSize.replace('pt', '') : ''; + } + }); + function openFontPicker() { if (!editor) return; sizeOpen = false; + sizeInputFocused = false; // Save selection before the picker button steals focus. savedFrom = editor.state.selection.from; savedTo = editor.state.selection.to; @@ -107,17 +116,8 @@ return { destroy() { window.removeEventListener('mousedown', handler); } }; } - function openSizePicker() { + function applyFontSize(size: number) { if (!editor) return; - fontOpen = false; - savedFrom = editor.state.selection.from; - savedTo = editor.state.selection.to; - sizeOpen = !sizeOpen; - } - - function pickSize(size: number) { - if (!editor) return; - sizeOpen = false; const from = savedFrom ?? editor.state.selection.from; const to = savedTo ?? editor.state.selection.to; savedFrom = null; @@ -125,9 +125,54 @@ editor.chain().focus().setTextSelection({ from, to }).setFontSize(`${size}pt`).run(); } + function onSizeInputFocus(e: FocusEvent) { + if (!editor) return; + sizeInputFocused = true; + fontOpen = false; + savedFrom = editor.state.selection.from; + savedTo = editor.state.selection.to; + (e.target as HTMLInputElement).select(); + } + + function onSizeInputKeydown(e: KeyboardEvent) { + if (e.key === 'Enter') { + e.preventDefault(); + const num = parseInt(sizeInputValue, 10); + if (!isNaN(num) && num >= 1 && num <= 400) applyFontSize(num); + sizeInputFocused = false; + (e.target as HTMLInputElement).blur(); + } else if (e.key === 'Escape') { + sizeInputFocused = false; + (e.target as HTMLInputElement).blur(); + } + } + + function onSizeInputBlur() { + sizeInputFocused = false; + } + + function openSizePicker() { + if (!editor) return; + fontOpen = false; + if (!sizeInputFocused) { + savedFrom = editor.state.selection.from; + savedTo = editor.state.selection.to; + } + sizeOpen = !sizeOpen; + } + + function pickSize(size: number) { + if (!editor) return; + sizeOpen = false; + sizeInputFocused = false; + applyFontSize(size); + } + function sizePickerClickOutside(node: HTMLElement) { function handler(e: MouseEvent) { - if (!node.contains(e.target as Node)) sizeOpen = false; + if (!node.contains(e.target as Node)) { + sizeOpen = false; + } } window.addEventListener('mousedown', handler); return { destroy() { window.removeEventListener('mousedown', handler); } }; @@ -160,12 +205,23 @@