From f6ddf9443eb3199b3ffc94beed5e7cd01abd5275 Mon Sep 17 00:00:00 2001 From: David Evans Date: Mon, 22 Jan 2018 19:52:18 +0000 Subject: [PATCH] Maintain current selection when swapping editor for CodeMirror --- scripts/interface/Interface.js | 28 +++++++++++++++++++++++++++- scripts/stubs/codemirror.js | 5 ++++- 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/scripts/interface/Interface.js b/scripts/interface/Interface.js index 6615ea9..32b84c1 100644 --- a/scripts/interface/Interface.js +++ b/scripts/interface/Interface.js @@ -30,6 +30,19 @@ define(['require'], (require) => { events.forEach((event) => element.addEventListener(event, fn)); } + function findPos(content, index) { + let p = 0; + let line = 0; + while(true) { + const nextLn = content.indexOf('\n', p) + 1; + if(index < nextLn || nextLn === 0) { + return {line, ch: index - p}; + } + p = nextLn; + ++ line; + } + } + function simplifyPreview(code) { code = code.replace(/\{Agent([0-9]*)\}/g, (match, num) => { if(num === undefined) { @@ -492,8 +505,13 @@ define(['require'], (require) => { ], (CodeMirror) => { this.diagram.registerCodeMirrorMode(CodeMirror); + const selBegin = this.code.selectionStart; + const selEnd = this.code.selectionEnd; + const value = this.code.value; + const focussed = this.code === document.activeElement; + const code = new CodeMirror(this.code.parentNode, { - value: this.code.value, + value, mode: 'sequence', globals: { themes: this.diagram.getThemeNames(), @@ -511,6 +529,10 @@ define(['require'], (require) => { }, }); this.code.parentNode.removeChild(this.code); + code.getDoc().setSelection( + findPos(value, selBegin), + findPos(value, selEnd) + ); let lastKey = 0; code.on('keydown', (cm, event) => { @@ -539,6 +561,10 @@ define(['require'], (require) => { this.diagram.setHighlight(Math.min(from, to)); }); + if(focussed) { + code.focus(); + } + this.code = code; }); } diff --git a/scripts/stubs/codemirror.js b/scripts/stubs/codemirror.js index addbf19..74c841f 100644 --- a/scripts/stubs/codemirror.js +++ b/scripts/stubs/codemirror.js @@ -7,7 +7,10 @@ define([], () => { container, options, }; - spy.doc = jasmine.createSpyObj('CodeMirror document', ['getValue']); + spy.doc = jasmine.createSpyObj('CodeMirror document', [ + 'getValue', + 'setSelection', + ]); spy.getDoc = () => spy.doc; return spy; }