2019-05-07 00:21:28 +08:00
|
|
|
/*
|
|
|
|
Copyright 2019 New Vector Ltd
|
2019-05-22 22:16:32 +08:00
|
|
|
Copyright 2019 The Matrix.org Foundation C.I.C.
|
2019-05-07 00:21:28 +08:00
|
|
|
|
|
|
|
Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
you may not use this file except in compliance with the License.
|
|
|
|
You may obtain a copy of the License at
|
|
|
|
|
|
|
|
http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
|
|
|
|
Unless required by applicable law or agreed to in writing, software
|
|
|
|
distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
See the License for the specific language governing permissions and
|
|
|
|
limitations under the License.
|
|
|
|
*/
|
|
|
|
|
2019-05-13 23:42:00 +08:00
|
|
|
export function setCaretPosition(editor, model, caretPosition) {
|
2019-05-07 00:21:28 +08:00
|
|
|
const sel = document.getSelection();
|
2019-05-13 23:42:00 +08:00
|
|
|
sel.removeAllRanges();
|
|
|
|
const range = document.createRange();
|
|
|
|
const {parts} = model;
|
|
|
|
let lineIndex = 0;
|
|
|
|
let nodeIndex = -1;
|
|
|
|
for (let i = 0; i <= caretPosition.index; ++i) {
|
|
|
|
const part = parts[i];
|
|
|
|
if (part && part.type === "newline") {
|
|
|
|
lineIndex += 1;
|
|
|
|
nodeIndex = -1;
|
|
|
|
} else {
|
|
|
|
nodeIndex += 1;
|
2019-05-08 17:12:47 +08:00
|
|
|
}
|
2019-05-07 00:21:28 +08:00
|
|
|
}
|
2019-05-13 23:42:00 +08:00
|
|
|
let focusNode;
|
|
|
|
const lineNode = editor.childNodes[lineIndex];
|
|
|
|
if (lineNode) {
|
|
|
|
if (lineNode.childNodes.length === 0 && caretPosition.offset === 0) {
|
|
|
|
focusNode = lineNode;
|
|
|
|
} else {
|
|
|
|
focusNode = lineNode.childNodes[nodeIndex];
|
|
|
|
|
|
|
|
if (focusNode && focusNode.nodeType === Node.ELEMENT_NODE) {
|
|
|
|
focusNode = focusNode.childNodes[0];
|
|
|
|
}
|
|
|
|
}
|
2019-05-13 22:21:57 +08:00
|
|
|
}
|
2019-05-10 20:25:13 +08:00
|
|
|
// node not found, set caret at end
|
|
|
|
if (!focusNode) {
|
|
|
|
range.selectNodeContents(editor);
|
|
|
|
range.collapse(false);
|
|
|
|
} else {
|
|
|
|
// make sure we have a text node
|
|
|
|
range.setStart(focusNode, caretPosition.offset);
|
|
|
|
range.collapse(true);
|
|
|
|
}
|
2019-05-08 17:12:47 +08:00
|
|
|
sel.addRange(range);
|
2019-05-07 00:21:28 +08:00
|
|
|
}
|