Skip to content
This repository was archived by the owner on Sep 11, 2024. It is now read-only.

Commit 472b5b5

Browse files
authored
Merge pull request #1299 from matrix-org/luke/fix-text-offsets-to-selection-state
Fix bugs in textOffsetsToSelectionState
2 parents 004cc42 + 65dc9fd commit 472b5b5

File tree

1 file changed

+25
-16
lines changed

1 file changed

+25
-16
lines changed

src/RichText.js

Lines changed: 25 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -202,25 +202,34 @@ export function selectionStateToTextOffsets(selectionState: SelectionState,
202202
export function textOffsetsToSelectionState({start, end}: SelectionRange,
203203
contentBlocks: Array<ContentBlock>): SelectionState {
204204
let selectionState = SelectionState.createEmpty();
205+
// Subtract block lengths from `start` and `end` until they are less than the current
206+
// block length (accounting for the NL at the end of each block). Set them to -1 to
207+
// indicate that the corresponding selection state has been determined.
205208
for (const block of contentBlocks) {
206209
const blockLength = block.getLength();
207-
if (start !== -1 && start < blockLength) {
208-
selectionState = selectionState.merge({
209-
anchorKey: block.getKey(),
210-
anchorOffset: start,
211-
});
212-
start = -1;
213-
} else {
214-
start -= blockLength + 1; // +1 to account for newline between blocks
210+
// -1 indicating that the position start position has been found
211+
if (start !== -1) {
212+
if (start < blockLength + 1) {
213+
selectionState = selectionState.merge({
214+
anchorKey: block.getKey(),
215+
anchorOffset: start,
216+
});
217+
start = -1; // selection state for the start calculated
218+
} else {
219+
start -= blockLength + 1; // +1 to account for newline between blocks
220+
}
215221
}
216-
if (end !== -1 && end <= blockLength) {
217-
selectionState = selectionState.merge({
218-
focusKey: block.getKey(),
219-
focusOffset: end,
220-
});
221-
end = -1;
222-
} else {
223-
end -= blockLength + 1; // +1 to account for newline between blocks
222+
// -1 indicating that the position end position has been found
223+
if (end !== -1) {
224+
if (end < blockLength + 1) {
225+
selectionState = selectionState.merge({
226+
focusKey: block.getKey(),
227+
focusOffset: end,
228+
});
229+
end = -1; // selection state for the end calculated
230+
} else {
231+
end -= blockLength + 1; // +1 to account for newline between blocks
232+
}
224233
}
225234
}
226235
return selectionState;

0 commit comments

Comments
 (0)