Merge pull request #1299 from matrix-org/luke/fix-text-offsets-to-selection-state

Fix bugs in textOffsetsToSelectionState
pull/21833/head
Luke Barnard 2017-08-15 11:37:35 +01:00 committed by GitHub
commit 472b5b5350
1 changed files with 25 additions and 16 deletions

View File

@ -202,27 +202,36 @@ export function selectionStateToTextOffsets(selectionState: SelectionState,
export function textOffsetsToSelectionState({start, end}: SelectionRange, export function textOffsetsToSelectionState({start, end}: SelectionRange,
contentBlocks: Array<ContentBlock>): SelectionState { contentBlocks: Array<ContentBlock>): SelectionState {
let selectionState = SelectionState.createEmpty(); let selectionState = SelectionState.createEmpty();
// Subtract block lengths from `start` and `end` until they are less than the current
// block length (accounting for the NL at the end of each block). Set them to -1 to
// indicate that the corresponding selection state has been determined.
for (const block of contentBlocks) { for (const block of contentBlocks) {
const blockLength = block.getLength(); const blockLength = block.getLength();
if (start !== -1 && start < blockLength) { // -1 indicating that the position start position has been found
if (start !== -1) {
if (start < blockLength + 1) {
selectionState = selectionState.merge({ selectionState = selectionState.merge({
anchorKey: block.getKey(), anchorKey: block.getKey(),
anchorOffset: start, anchorOffset: start,
}); });
start = -1; start = -1; // selection state for the start calculated
} else { } else {
start -= blockLength + 1; // +1 to account for newline between blocks start -= blockLength + 1; // +1 to account for newline between blocks
} }
if (end !== -1 && end <= blockLength) { }
// -1 indicating that the position end position has been found
if (end !== -1) {
if (end < blockLength + 1) {
selectionState = selectionState.merge({ selectionState = selectionState.merge({
focusKey: block.getKey(), focusKey: block.getKey(),
focusOffset: end, focusOffset: end,
}); });
end = -1; end = -1; // selection state for the end calculated
} else { } else {
end -= blockLength + 1; // +1 to account for newline between blocks end -= blockLength + 1; // +1 to account for newline between blocks
} }
} }
}
return selectionState; return selectionState;
} }