From 17c23da9bfd3134ee15f49887a077ef53f585bd1 Mon Sep 17 00:00:00 2001 From: Magnus Hovland Hoff Date: Mon, 1 Oct 2018 09:01:27 +0200 Subject: [PATCH] Better scroll handling when toggling editing. It will now retain the scroll position relative to the full document height when entering and leaving editing mode. This places the viewport closer to the contents you were watching. This is likely less disorienting --- assets/script.js | 25 ++++++++++++++++++------- 1 file changed, 18 insertions(+), 7 deletions(-) diff --git a/assets/script.js b/assets/script.js index 849d02d..b7211bd 100644 --- a/assets/script.js +++ b/assets/script.js @@ -82,11 +82,12 @@ function openEditor() { textarea.style.height = rendered.clientHeight + "px"; - container.classList.add('edit'); + retainScrollRatio(() => { + container.classList.add('edit'); + autosizeTextarea(textarea, shadow); + }); updateFormEnabledState(); - autosizeTextarea(textarea, shadow); - textarea.setSelectionRange(textarea.value.length, textarea.value.length); textarea.focus(); @@ -112,6 +113,18 @@ function openEditor() { // TODO: edit-link in footer? } + function retainScrollRatio(innerFunction) { + const scrollElement = document.body.parentElement; + const savedScrollRatio = scrollElement.scrollTop / (scrollElement.scrollHeight - scrollElement.clientHeight); + innerFunction(); + scrollElement.scrollTop = (scrollElement.scrollHeight - scrollElement.clientHeight) * savedScrollRatio; + } + + function closeEditor() { + retainScrollRatio(() => container.classList.remove('edit')); + document.activeElement && document.activeElement.blur(); + } + function doSave() { state.saving = true; updateFormEnabledState(); @@ -170,8 +183,7 @@ function openEditor() { } if (!result.conflict) { - container.classList.remove('edit'); - document.activeElement && document.activeElement.blur(); + closeEditor(); } state.saving = false; @@ -196,8 +208,7 @@ function openEditor() { Promise.resolve(!isEdited(form) || confirmDiscard()) .then(doReset => { if (doReset) { - container.classList.remove('edit'); - document.activeElement && document.activeElement.blur(); + closeEditor(); updateFormEnabledState(); form.reset();