"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.placeCursor = void 0;
const constants_1 = require("../../../../json-crdt-extensions/peritext/rga/constants");
const json_crdt_patch_1 = require("../../../../json-crdt-patch");
/**
 * Given an undo/redo patch/batch, calculates a good cursor position to place
 * the cursor after the patch is applied, so that the user can continue typing
 * from the same logical position.
 *
 * @param patch Undo/Redo patch
 * @returns Range
 */
const placeCursor = (txt, batch) => {
    const batchLength = batch.length;
    for (let j = batchLength - 1; j >= 0; j--) {
        const patch = batch[j];
        const ops = patch.ops;
        const length = ops.length;
        for (let i = length - 1; i >= 0; i--) {
            const op = ops[i];
            if (op instanceof json_crdt_patch_1.InsStrOp || op instanceof json_crdt_patch_1.InsBinOp || op instanceof json_crdt_patch_1.InsArrOp) {
                const opId = op.id;
                const lastCharId = new json_crdt_patch_1.Timestamp(opId.sid, opId.time + op.span() - 1);
                const point = txt.point(lastCharId, constants_1.Anchor.After);
                const cursor = txt.range(point);
                return cursor;
            }
            else if (op instanceof json_crdt_patch_1.DelOp && (0, json_crdt_patch_1.equal)(op.obj, txt.str.id)) {
                const lastSpan = op.what[op.what.length - 1];
                if (lastSpan) {
                    const point = txt.point(lastSpan, constants_1.Anchor.Before);
                    point.halfstep(-1);
                    const cursor = txt.range(point);
                    return cursor;
                }
            }
        }
    }
    return;
};
exports.placeCursor = placeCursor;
//# sourceMappingURL=annals.js.map