"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.treeApi = void 0;
/*!
 * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
 * Licensed under the MIT License.
 */
const core_utils_1 = require("@fluidframework/core-utils");
const index_js_1 = require("../util/index.js");
const index_js_2 = require("../feature-libraries/index.js");
const index_js_3 = require("../simple-tree/index.js");
const schematizingTreeView_js_1 = require("./schematizingTreeView.js");
const treeView_js_1 = require("./treeView.js");
/**
 * The `Tree` object holds various functions for interacting with {@link TreeNode}s.
 * @public
 */
exports.treeApi = {
    ...index_js_3.treeNodeApi,
    runTransaction(treeOrNode, transaction) {
        if (treeOrNode instanceof schematizingTreeView_js_1.SchematizingSimpleTreeView) {
            const t = transaction;
            runTransaction(treeOrNode.checkout, () => t(treeOrNode.root));
        }
        else {
            const node = treeOrNode;
            const t = transaction;
            const context = (0, index_js_3.getFlexNode)(node).context;
            (0, core_utils_1.assert)(context instanceof index_js_2.Context, 0x901 /* Unsupported context */);
            const treeView = treeView_js_1.contextToTreeView.get(context) ??
                (0, index_js_1.fail)("Expected view to be registered for context");
            runTransaction(treeView.checkout, () => t(node));
        }
    },
};
function runTransaction(checkout, transaction) {
    checkout.transaction.start();
    let result;
    try {
        result = transaction();
    }
    catch (e) {
        // If the transaction has an unhandled error, abort and rollback the transaction but continue to propagate the error.
        checkout.transaction.abort();
        throw e;
    }
    if (result === "rollback") {
        checkout.transaction.abort();
    }
    else {
        checkout.transaction.commit();
    }
}
//# sourceMappingURL=treeApi.js.map