Browse Source

impl Editor.setScrollTopByLine using CodeMirror.charCoords

Yuki Takei 8 years ago
parent
commit
37e3621e0b

+ 1 - 1
resource/js/components/PageEditor.js

@@ -52,7 +52,7 @@ export default class PageEditor extends React.Component {
     // create throttled function
     this.scrollPreviewByEditorLineWithThrottle = throttle(20, this.scrollPreviewByEditorLine);
     this.scrollPreviewByCursorMovingWithThrottle = throttle(20, this.scrollPreviewByCursorMoving);
-    this.scrollEditorByPreviewScrollWithThrottle = throttle(50, this.scrollEditorByPreviewScroll);
+    this.scrollEditorByPreviewScrollWithThrottle = throttle(20, this.scrollEditorByPreviewScroll);
     this.renderWithDebounce = debounce(50, throttle(100, this.renderPreview));
     this.saveDraftWithDebounce = debounce(800, this.saveDraft);
   }

+ 4 - 10
resource/js/components/PageEditor/Editor.js

@@ -100,11 +100,7 @@ export default class Editor extends React.Component {
     const editor = this.getCodeMirror();
     const linePosition = Math.max(0, line);
 
-    // scroll to the bottom for a moment
-    const lastLine = editor.getDoc().lastLine();
-    editor.scrollIntoView(lastLine);
-
-    editor.scrollIntoView(linePosition);
+    this.setScrollTopByLine(linePosition);
     editor.setCursor({line: linePosition});   // leave 'ch' field as null/undefined to indicate the end of line
   }
 
@@ -113,12 +109,10 @@ export default class Editor extends React.Component {
    * @param {number} line
    */
   setScrollTopByLine(line) {
-    console.log(line);
-
     const editor = this.getCodeMirror();
-    const scrollInfo = editor.getScrollInfo();
-
-    editor.scrollIntoView(line);
+    // get top position of the line
+    var top = editor.charCoords({line, ch: 0}, 'local').top;
+    editor.scrollTo(null, top);
   }
 
   /**

+ 13 - 0
resource/js/components/PageEditor/ScrollSyncHelper.js

@@ -120,6 +120,12 @@ class ScrollSyncHelper {
 	 * @param {number} line
 	 */
 	scrollPreview(previewElement, line) {
+    // turn off the flag
+    if (this.isSyncScrollToEditorFired) {
+      this.isSyncScrollToEditorFired = false;
+      return;
+    }
+
 		const { previous, next } = this.getElementsForSourceLine(previewElement, line);
 		// marker.update(previous && previous.element);
 		if (previous) {
@@ -183,6 +189,13 @@ class ScrollSyncHelper {
 		}
   }
 
+  /**
+   * Attempt to scroll Editor component for the offset of the element in the Preview component.
+   *
+   * @param {Editor} editor
+   * @param {Element} previewElement
+   * @param {number} offset
+   */
   scrollEditor(editor, previewElement, offset) {
     // turn off the flag
     if (this.isSyncScrollToPreviewFired) {