/*!
 * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
 * Licensed under the MIT License.
 */
import { assert } from "@fluidframework/core-utils/internal";
import { Context } from "../feature-libraries/index.js";
import { getFlexNode, treeNodeApi } from "../simple-tree/index.js";
import { fail } from "../util/index.js";
import { SchematizingSimpleTreeView } from "./schematizingTreeView.js";
import { contextToTreeView } from "./treeView.js";
/**
 * The `Tree` object holds various functions for interacting with {@link TreeNode}s.
 * @public
 */
export const treeApi = {
    ...treeNodeApi,
    runTransaction(treeOrNode, transaction) {
        if (treeOrNode instanceof SchematizingSimpleTreeView) {
            const t = transaction;
            runTransaction(treeOrNode.checkout, () => t(treeOrNode.root));
        }
        else {
            const node = treeOrNode;
            const t = transaction;
            const context = getFlexNode(node).context;
            assert(context instanceof Context, 0x901 /* Unsupported context */);
            const treeView = contextToTreeView.get(context) ??
                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