support update callback setting selection instead of caret

This commit is contained in:
Bruno Windels 2019-09-04 16:04:06 +02:00
parent 037ac29c57
commit 2ea556e0b4
3 changed files with 40 additions and 10 deletions

View file

@ -16,12 +16,39 @@ limitations under the License.
*/
import {needsCaretNodeBefore, needsCaretNodeAfter} from "./render";
import Range from "./range";
export function setSelection(editor, model, selection) {
if (selection instanceof Range) {
setDocumentRangeSelection(editor, model, selection);
} else {
setCaretPosition(editor, model, selection);
}
}
function setDocumentRangeSelection(editor, model, range) {
const sel = document.getSelection();
sel.removeAllRanges();
const selectionRange = document.createRange();
const start = getNodeAndOffsetForPosition(editor, model, range.start);
selectionRange.setStart(start.node, start.offset);
const end = getNodeAndOffsetForPosition(editor, model, range.end);
selectionRange.setEnd(end.node, end.offset);
sel.addRange(selectionRange);
}
export function setCaretPosition(editor, model, caretPosition) {
const sel = document.getSelection();
sel.removeAllRanges();
const range = document.createRange();
const {offset, lineIndex, nodeIndex} = getLineAndNodePosition(model, caretPosition);
const {node, offset} = getNodeAndOffsetForPosition(editor, model, caretPosition);
range.setStart(node, offset);
range.collapse(true);
sel.addRange(range);
}
function getNodeAndOffsetForPosition(editor, model, position) {
const {offset, lineIndex, nodeIndex} = getLineAndNodePosition(model, position);
const lineNode = editor.childNodes[lineIndex];
let focusNode;
@ -35,9 +62,7 @@ export function setCaretPosition(editor, model, caretPosition) {
focusNode = focusNode.firstChild;
}
}
range.setStart(focusNode, offset);
range.collapse(true);
sel.addRange(range);
return {node: focusNode, offset};
}
export function getLineAndNodePosition(model, caretPosition) {

View file

@ -433,7 +433,12 @@ export default class EditorModel {
*/
transform(callback) {
const pos = callback();
const acPromise = this._setActivePart(pos, true);
let acPromise = null;
if (!(pos instanceof Range)) {
acPromise = this._setActivePart(pos, true);
} else {
acPromise = Promise.resolve();
}
this._updateCallback(pos);
return acPromise;
}