Skip to content

Commit cb6e601

Browse files
rcosta358codex
andcommitted
Scroll smoothly before focusing diagnostic locations
Co-authored-by: Codex <codex@openai.com>
1 parent 693f03f commit cb6e601

2 files changed

Lines changed: 34 additions & 3 deletions

File tree

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
function scrollTo(element, top, behavior) {
2+
const target = Math.max(0, Math.min(top, element.scrollHeight - element.clientHeight));
3+
if (Math.abs(target - element.scrollTop) < 1) return Promise.resolve();
4+
return new Promise(resolve => {
5+
const events = element === document.scrollingElement ? document : element;
6+
if (behavior === 'smooth') events.addEventListener('scrollend', resolve, { once: true });
7+
element.scrollTo({ top: target, behavior });
8+
if (behavior === 'instant') resolve();
9+
});
10+
}
11+
12+
export function navigateTo(view, anchor) {
13+
view.requestMeasure({
14+
read: () => {
15+
const line = view.lineBlockAt(anchor);
16+
const editor = view.dom.getBoundingClientRect();
17+
return {
18+
editorTop: line.top + line.height / 2 - view.scrollDOM.clientHeight / 2,
19+
pageTop: window.scrollY + editor.top + editor.height / 2 - window.innerHeight / 2
20+
};
21+
},
22+
write: async ({ editorTop, pageTop }) => {
23+
const behavior = matchMedia('(prefers-reduced-motion: reduce)').matches ? 'instant' : 'smooth';
24+
await Promise.all([
25+
scrollTo(view.scrollDOM, editorTop, behavior),
26+
scrollTo(document.scrollingElement, pageTop, behavior)
27+
]);
28+
view.dispatch({ selection: { anchor } });
29+
view.focus();
30+
}
31+
});
32+
}

‎scripts/playground/editor.js‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { examples } from './examples.mjs';
44
import { diagnosticHtml, editorDiagnostic } from './diagnostics.mjs';
55
import { editorJava, editorTheme } from './editor-theme.mjs';
66
import { editorSetup } from './editor-setup.mjs';
7+
import { navigateTo } from './editor-navigation.mjs';
78

89
const root = document.querySelector('#lj-playground');
910
const example = document.querySelector('#lj-example');
@@ -67,9 +68,7 @@ function render(result) {
6768
const mark = issue && editorDiagnostic(issue, view.state.doc.length);
6869
const line = view.state.doc.line(lineNumber);
6970
const anchor = mark?.from ?? line.from + line.text.search(/\S|$/);
70-
view.dom.scrollIntoView({ block: 'center', inline: 'nearest' });
71-
view.dispatch({ selection: { anchor }, effects: EditorView.scrollIntoView(anchor, { y: 'center' }) });
72-
view.focus();
71+
navigateTo(view, anchor);
7372
};
7473
}
7574
pre.append(code);

0 commit comments

Comments
 (0)