|
| 1 | +import {Peritext} from '../../../json-crdt-extensions'; |
| 2 | +import {Anchor} from '../../../json-crdt-extensions/peritext/rga/constants'; |
| 3 | +import {DelOp, equal, InsArrOp, InsBinOp, InsStrOp, Patch, Timestamp} from '../../../json-crdt-patch'; |
| 4 | +import type {Range} from '../../../json-crdt-extensions/peritext/rga/Range'; |
| 5 | + |
| 6 | +/** |
| 7 | + * Given an undo/redo patch/batch, calculates a good cursor position to place |
| 8 | + * the cursor after the patch is applied, so that the user can continue typing |
| 9 | + * from the same logical position. |
| 10 | + * |
| 11 | + * @param patch Undo/Redo patch |
| 12 | + * @returns Range |
| 13 | + */ |
| 14 | +export const placeCursor = (txt: Peritext, batch: Patch[]): Range | undefined => { |
| 15 | + const batchLength = batch.length; |
| 16 | + for (let j = batchLength - 1; j >= 0; j--) { |
| 17 | + const patch = batch[j]; |
| 18 | + const ops = patch.ops; |
| 19 | + const length = ops.length; |
| 20 | + for (let i = length - 1; i >= 0; i--) { |
| 21 | + const op = ops[i]; |
| 22 | + if (op instanceof InsStrOp || op instanceof InsBinOp || op instanceof InsArrOp) { |
| 23 | + const opId = op.id; |
| 24 | + const lastCharId = new Timestamp(opId.sid, opId.time + op.span() - 1); |
| 25 | + const point = txt.point(lastCharId, Anchor.After); |
| 26 | + const cursor = txt.range(point); |
| 27 | + return cursor; |
| 28 | + } else if (op instanceof DelOp && equal(op.obj, txt.str.id)) { |
| 29 | + const lastSpan = op.what[op.what.length - 1]; |
| 30 | + if (lastSpan) { |
| 31 | + const point = txt.point(lastSpan, Anchor.Before); |
| 32 | + point.halfstep(-1); |
| 33 | + const cursor = txt.range(point); |
| 34 | + return cursor; |
| 35 | + } |
| 36 | + } |
| 37 | + } |
| 38 | + } |
| 39 | + return; |
| 40 | +}; |
0 commit comments