'use strict';

var obsidian = require('obsidian');

/******************************************************************************
Copyright (c) Microsoft Corporation.

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise */

var extendStatics = function(d, b) {
    extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
    return extendStatics(d, b);
};

function __extends(d, b) {
    if (typeof b !== "function" && b !== null)
        throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
    extendStatics(d, b);
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}

function __awaiter(thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
}

function __generator(thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
}

var SlidingPanesSettings = /** @class */ (function () {
    function SlidingPanesSettings() {
        this.headerWidth = 32;
        this.leafDesktopWidth = 700;
        this.leafMobileWidth = 350;
        this.leafAutoWidth = false;
        this.disabled = false;
        this.rotateHeaders = true;
        this.headerAlt = false;
        this.orienation = "mixed";
        this.stackingEnabled = true;
        this.smoothAnimation = true;
    }
    return SlidingPanesSettings;
}());
var SlidingPanesSettingTab = /** @class */ (function (_super) {
    __extends(SlidingPanesSettingTab, _super);
    function SlidingPanesSettingTab(app, plugin) {
        var _this = _super.call(this, app, plugin) || this;
        _this.plugin = plugin;
        return _this;
    }
    SlidingPanesSettingTab.prototype.display = function () {
        var _this = this;
        var containerEl = this.containerEl;
        containerEl.empty();
        new obsidian.Setting(containerEl)
            .setName("Toggle Sliding Panes")
            .setDesc("Turns sliding panes on or off globally")
            .addToggle(function (toggle) { return toggle.setValue(!_this.plugin.settings.disabled)
            .onChange(function (value) {
            _this.plugin.settings.disabled = !value;
            _this.plugin.saveData(_this.plugin.settings);
            if (_this.plugin.settings.disabled) {
                _this.plugin.disable();
            }
            else {
                _this.plugin.enable();
            }
        }); });
        new obsidian.Setting(containerEl)
            .setName('Smooth Animation')
            .setDesc('Whether to use smooth animation (on) or snapping (off)')
            .addToggle(function (toggle) { return toggle.setValue(_this.plugin.settings.smoothAnimation)
            .onChange(function (value) {
            _this.plugin.settings.smoothAnimation = value;
            _this.plugin.saveData(_this.plugin.settings);
            _this.plugin.refresh();
        }); });
        new obsidian.Setting(containerEl)
            .setName('Leaf Auto Width')
            .setDesc('If on, the width of the pane should fill the available space')
            .addToggle(function (toggle) { return toggle.setValue(_this.plugin.settings.leafAutoWidth)
            .onChange(function (value) {
            _this.plugin.settings.leafAutoWidth = value;
            _this.plugin.saveData(_this.plugin.settings);
            _this.plugin.refresh();
        }); });
        new obsidian.Setting(containerEl)
            .setName('Leaf Width on Desktop')
            .setDesc('The width of a single pane (only if auto width is off)')
            .addText(function (text) { return text.setPlaceholder('Example: 700')
            .setValue((_this.plugin.settings.leafDesktopWidth || '') + '')
            .onChange(function (value) {
            _this.plugin.settings.leafDesktopWidth = parseInt(value.trim());
            _this.plugin.saveData(_this.plugin.settings);
            _this.plugin.refresh();
        }); });
        new obsidian.Setting(containerEl)
            .setName('Leaf Width on Mobile')
            .setDesc('The width of a single pane (only if auto width is off)')
            .addText(function (text) { return text.setPlaceholder('Example: 350')
            .setValue((_this.plugin.settings.leafMobileWidth || '') + '')
            .onChange(function (value) {
            _this.plugin.settings.leafMobileWidth = parseInt(value.trim());
            _this.plugin.saveData(_this.plugin.settings);
            _this.plugin.refresh();
        }); });
        new obsidian.Setting(containerEl)
            .setName("Toggle rotated headers")
            .setDesc("Rotates headers to use as spines")
            .addToggle(function (toggle) { return toggle.setValue(_this.plugin.settings.rotateHeaders)
            .onChange(function (value) {
            _this.plugin.settings.rotateHeaders = value;
            _this.plugin.saveData(_this.plugin.settings);
            _this.plugin.refresh();
        }); });
        new obsidian.Setting(containerEl)
            .setName("Swap rotated header direction")
            .setDesc("Swaps the direction of rotated headers")
            .addToggle(function (toggle) { return toggle.setValue(_this.plugin.settings.headerAlt)
            .onChange(function (value) {
            _this.plugin.settings.headerAlt = value;
            _this.plugin.saveData(_this.plugin.settings);
            _this.plugin.refresh();
        }); });
        new obsidian.Setting(containerEl)
            .setName("Header text orientation")
            .setDesc("Select the header text orientation")
            .addDropdown(function (dropdown) {
            dropdown.addOption("sideway", "Sideway");
            dropdown.addOption("mixed", "Mixed");
            dropdown.addOption("upright", "Upright");
            dropdown.setValue(_this.plugin.settings.orienation);
            dropdown.onChange(function (value) {
                _this.plugin.settings.orienation = value;
                _this.plugin.saveData(_this.plugin.settings);
                _this.plugin.refresh();
            });
        });
        new obsidian.Setting(containerEl)
            .setName("Toggle stacking")
            .setDesc("Panes will stack up to the left and right")
            .addToggle(function (toggle) { return toggle.setValue(_this.plugin.settings.stackingEnabled)
            .onChange(function (value) {
            _this.plugin.settings.stackingEnabled = value;
            _this.plugin.saveData(_this.plugin.settings);
            _this.plugin.refresh();
        }); });
        new obsidian.Setting(containerEl)
            .setName('Spine Width')
            .setDesc('The width of the rotated header (or gap) for stacking')
            .addText(function (text) { return text.setPlaceholder('Example: 32')
            .setValue((_this.plugin.settings.headerWidth || '') + '')
            .onChange(function (value) {
            _this.plugin.settings.headerWidth = parseInt(value.trim());
            _this.plugin.saveData(_this.plugin.settings);
            _this.plugin.refresh();
        }); });
    };
    return SlidingPanesSettingTab;
}(obsidian.PluginSettingTab));
var SlidingPanesCommands = /** @class */ (function () {
    function SlidingPanesCommands(plugin) {
        this.plugin = plugin;
    }
    SlidingPanesCommands.prototype.addToggleSettingCommand = function (id, name, settingName) {
        var _this = this;
        this.plugin.addCommand({
            id: id,
            name: name,
            callback: function () {
                // switch the setting, save and refresh
                //@ts-ignore
                _this.plugin.settings[settingName] = !_this.plugin.settings[settingName];
                _this.plugin.saveData(_this.plugin.settings);
                _this.plugin.refresh();
            }
        });
    };
    SlidingPanesCommands.prototype.addCommands = function () {
        var _this = this;
        // add the toggle on/off command
        this.plugin.addCommand({
            id: 'toggle-sliding-panes',
            name: 'Toggle Sliding Panes',
            callback: function () {
                // switch the disabled setting and save
                _this.plugin.settings.disabled = !_this.plugin.settings.disabled;
                _this.plugin.saveData(_this.plugin.settings);
                // disable or enable as necessary
                _this.plugin.settings.disabled ? _this.plugin.disable() : _this.plugin.enable();
            }
        });
        // add a command to toggle smooth animation
        this.addToggleSettingCommand('toggle-sliding-panes-smooth-animation', 'Toggle Smooth Animation', 'smoothAnimation');
        // add a command to toggle leaf auto width
        this.addToggleSettingCommand('toggle-sliding-panes-leaf-auto-width', 'Toggle Leaf Auto Width', 'leafAutoWidth');
        // add a command to toggle stacking
        this.addToggleSettingCommand('toggle-sliding-panes-stacking', 'Toggle Stacking', 'stackingEnabled');
        // add a command to toggle rotated headers
        this.addToggleSettingCommand('toggle-sliding-panes-rotated-headers', 'Toggle Rotated Headers', 'rotateHeaders');
        // add a command to toggle swapped header direction
        this.addToggleSettingCommand('toggle-sliding-panes-header-alt', 'Swap rotated header direction', 'headerAlt');
    };
    return SlidingPanesCommands;
}());

var PluginBase = /** @class */ (function (_super) {
    __extends(PluginBase, _super);
    function PluginBase() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        // runs when the plugin is loaded
        _this.onload = function () {
            // add in the required command pallete commands
            _this.addCommands();
            // add in any settings
            _this.addSettings();
            // wait for layout to be ready to perform the rest
            _this.app.workspace.onLayoutReady(_this.onLayoutReady);
        };
        // runs when the plugin is onloaded
        _this.onunload = function () {
            // run through the disable steps
            _this.disable();
        };
        // runs once the layout is ready the first time the plugin is started
        _this.onLayoutReady = function () {
            _this.enable();
        };
        // perform any setup required to enable the plugin
        _this.enable = function () {
            document.body.toggleClass(_this.className, true);
        };
        // perform any required disable steps, leave nothing behind
        _this.disable = function () {
            document.body.toggleClass(_this.className, false);
        };
        // add in any required command pallete commands
        _this.addCommands = function () { };
        // add in any settings
        _this.addSettings = function () { };
        return _this;
    }
    Object.defineProperty(PluginBase.prototype, "className", {
        get: function () {
            if (!this._cachedClassName) {
                this._cachedClassName = 'plugin-' + this.manifest.id;
                if (this._cachedClassName.endsWith('-obsidian')) {
                    this._cachedClassName = this._cachedClassName.substring(0, this._cachedClassName.lastIndexOf('-obsidian'));
                }
            }
            return this._cachedClassName;
        },
        enumerable: false,
        configurable: true
    });
    return PluginBase;
}(obsidian.Plugin));

var MIN_PANE_WIDTH = 200;
var SlidingPanesPlugin = /** @class */ (function (_super) {
    __extends(SlidingPanesPlugin, _super);
    function SlidingPanesPlugin() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        // helper variables
        _this.activeLeafIndex = 0;
        _this.prevRootLeaves = [];
        // runs when the plugin is loaded
        _this.onload = function () { return __awaiter(_this, void 0, void 0, function () {
            var _a, _b, _c, _d;
            return __generator(this, function (_e) {
                switch (_e.label) {
                    case 0:
                        // load settings
                        _a = this;
                        _c = (_b = Object).assign;
                        _d = [new SlidingPanesSettings()];
                        return [4 /*yield*/, this.loadData()];
                    case 1:
                        // load settings
                        _a.settings = _c.apply(_b, _d.concat([_e.sent()]));
                        // add in the required command pallete commands
                        this.addCommands();
                        // add in any settings
                        this.addSettings();
                        // wait for layout to be ready to perform the rest
                        this.app.workspace.onLayoutReady(this.onLayoutReady);
                        return [2 /*return*/];
                }
            });
        }); };
        // add in any required command pallete commands
        _this.addCommands = function () {
            // add the commands
            new SlidingPanesCommands(_this).addCommands();
        };
        // add in any settings
        _this.addSettings = function () {
            // add the settings tab
            _this.addSettingTab(new SlidingPanesSettingTab(_this.app, _this));
        };
        // enable andy mode
        _this.enable = function () {
            var _a;
            if (!((_a = _this.settings) === null || _a === void 0 ? void 0 : _a.disabled)) {
                // add the event handlers
                _this.registerEvent(_this.app.workspace.on('resize', _this.handleResize));
                _this.registerEvent(_this.app.workspace.on('layout-change', _this.handleLayoutChange));
                _this.registerEvent(_this.app.workspace.on('active-leaf-change', _this.handleActiveLeafChange));
                _this.registerEvent(_this.app.workspace.on('window-open', _this.handleWindowOpen));
                _this.registerEvent(_this.app.vault.on('delete', _this.handleDelete));
                // wait for layout to be ready to perform the rest
                if (_this.app.workspace.layoutReady)
                    _this.reallyEnable();
            }
        };
        _this.handleWindowOpen = function (window) {
            _this.swizzleChildResize(window);
        };
        // really enable things (once the layout is ready)
        _this.reallyEnable = function () {
            // we don't need the event handler anymore
            _this.app.workspace.off('layout-ready', _this.reallyEnable);
            // add some extra classes that can't fit in the styles.css
            // because they use settings
            _this.addStyle();
            // get and loop through the root splits (there may be more than one if using popout windows)
            var rootSplits = _this.getRootSplits();
            rootSplits.forEach(function (rootSplit) {
                _this.swizzleChildResize(rootSplit);
            });
            // do all the calucations necessary for the workspace leaves
            _this.recalculateLeaves();
        };
        // shut down andy mode
        _this.disable = function () {
            // get rid of the extra style tag we added
            _this.removeStyle();
            // get and loop through the root splits (there may be more than one if using popout windows)
            var rootSplits = _this.getRootSplits();
            rootSplits.forEach(function (rootSplit) {
                _this.unswizzleChildResize(rootSplit);
                var rootLeaves = rootSplit.children;
                // loop through all the leaves
                rootLeaves.forEach(_this.clearLeaf);
            });
            _this.app.workspace.off('resize', _this.handleResize);
            _this.app.workspace.off('layout-change', _this.handleLayoutChange);
            _this.app.workspace.off('active-leaf-change', _this.handleActiveLeafChange);
            _this.app.workspace.off('window-open', _this.handleWindowOpen);
            _this.app.vault.off('delete', _this.handleDelete);
        };
        _this.clearLeaf = function (leaf) {
            leaf.containerEl.style.width = null;
            leaf.containerEl.style.left = null;
            leaf.containerEl.style.right = null;
            leaf.containerEl.style.flex = null;
            leaf.containerEl.style.flexGrow = leaf.dimension;
            leaf.containerEl.classList.remove('mod-am-left-of-active');
            leaf.containerEl.classList.remove('mod-am-right-of-active');
            var iconEl = leaf.view.iconEl;
            var iconText = iconEl.getAttribute("aria-label");
            if (iconText.includes("(")) {
                iconEl.setAttribute("aria-label", iconText.substring(iconText.lastIndexOf('(') + 1, iconText.lastIndexOf(')')));
            }
        };
        // refresh funcion for when we change settings
        _this.refresh = function () {
            // re-load the style
            _this.updateStyle();
            // recalculate leaf positions
            _this.recalculateLeaves();
        };
        // remove the stlying elements we've created
        _this.removeStyle = function () {
            var el = document.getElementById('plugin-sliding-panes');
            if (el)
                el.remove();
            document.body.classList.remove('plugin-sliding-panes');
            document.body.classList.remove('plugin-sliding-panes-rotate-header');
            document.body.classList.remove('plugin-sliding-panes-header-alt');
            document.body.classList.remove('plugin-sliding-panes-stacking');
        };
        // add the styling elements we need
        _this.addStyle = function () {
            // add a css block for our settings-dependent styles
            var css = document.createElement('style');
            css.id = 'plugin-sliding-panes';
            document.getElementsByTagName("head")[0].appendChild(css);
            // add the main class
            document.body.classList.add('plugin-sliding-panes');
            // update the style with the settings-dependent styles
            _this.updateStyle();
        };
        // update the styles (at the start, or as the result of a settings change)
        _this.updateStyle = function () {
            // if we've got rotate headers on, add the class which enables it
            document.body.classList.toggle('plugin-sliding-panes-rotate-header', _this.settings.rotateHeaders);
            document.body.classList.toggle('plugin-sliding-panes-header-alt', _this.settings.headerAlt);
            // do the same for stacking
            document.body.classList.toggle('plugin-sliding-panes-stacking', _this.settings.stackingEnabled);
            // get the custom css element
            var el = document.getElementById('plugin-sliding-panes');
            if (!el)
                throw "plugin-sliding-panes element not found!";
            else {
                // set the settings-dependent css
                el.innerText = "body.plugin-sliding-panes{--header-width:".concat(_this.settings.headerWidth, "px;}");
                if (!_this.settings.leafAutoWidth) {
                    if (obsidian.Platform.isDesktop) {
                        el.innerText += "body.plugin-sliding-panes .mod-root>.workspace-leaf,body.plugin-sliding-panes .mod-root>.workspace-split{width:".concat(_this.settings.leafDesktopWidth + _this.settings.headerWidth, "px;}");
                    }
                    else {
                        el.innerText += "body.plugin-sliding-panes .mod-root>.workspace-leaf,body.plugin-sliding-panes .mod-root>.workspace-split{width:".concat(_this.settings.leafMobileWidth + _this.settings.headerWidth, "px;}");
                    }
                }
            }
            if (_this.settings.rotateHeaders) {
                _this.selectOrientation(_this.settings.orienation);
            }
        };
        _this.handleResize = function () {
            if (_this.app.workspace.layoutReady) {
                _this.recalculateLeaves();
            }
        };
        _this.handleLayoutChange = function () {
            // get and loop through the root splits (there may be more than one if using popout windows)
            var rootSplits = _this.getRootSplits();
            var rootLeaves = [];
            rootSplits.forEach(function (rootSplit) {
                rootLeaves.push.apply(rootLeaves, rootSplit.children);
            });
            if (rootLeaves.length < _this.prevRootLeaves.length) {
                _this.prevRootLeaves.forEach(function (leaf) {
                    if (!rootLeaves.contains(leaf)) {
                        _this.clearLeaf(leaf);
                    }
                });
            }
            _this.prevRootLeaves = rootLeaves;
            //this.recalculateLeaves();
        };
        _this.unswizzleChildResize = function (rootSplit) {
            rootSplit.onChildResizeStart = rootSplit.oldChildResizeStart;
        };
        _this.swizzleChildResize = function (rootSplit) {
            rootSplit.oldChildResizeStart = rootSplit.onChildResizeStart;
            rootSplit.onChildResizeStart = function (leaf, event) {
                // only really apply this to vertical splits
                if (rootSplit.direction === "vertical") {
                    // this is the width the leaf started at before resize
                    var startWidth_1 = leaf.width;
                    // the mousemove event to trigger while resizing
                    var mousemove_1 = function (e) {
                        // get the difference between the first position and current
                        var deltaX = e.pageX - event.pageX;
                        // adjust the start width by the delta
                        leaf.width = startWidth_1 + deltaX;
                        if (leaf.width < MIN_PANE_WIDTH)
                            leaf.width = MIN_PANE_WIDTH;
                        leaf.containerEl.style.width = leaf.width + "px";
                    };
                    // the mouseup event to trigger at the end of resizing
                    var mouseup_1 = function () {
                        // if stacking is enabled, we need to re-jig the "right" value
                        if (_this.settings.stackingEnabled) {
                            // we need the leaf count and index to calculate the correct value
                            var rootLeaves = rootSplit.children;
                            var leafCount = rootLeaves.length;
                            var leafIndex = rootLeaves.findIndex(function (l) { return l == leaf; });
                            for (var i = leafIndex; i < leafCount; i++) {
                                rootLeaves[i].containerEl.style.right = (((leafCount - i) * _this.settings.headerWidth) - rootLeaves[i].width) + "px";
                            }
                        }
                        // remove these event listeners. We're done with them
                        rootSplit.doc.removeEventListener("mousemove", mousemove_1);
                        rootSplit.doc.removeEventListener("mouseup", mouseup_1);
                        document.body.removeClass("is-grabbing");
                    };
                    // Add the above two event listeners
                    rootSplit.doc.addEventListener("mousemove", mousemove_1);
                    rootSplit.doc.addEventListener("mouseup", mouseup_1);
                    document.body.addClass("is-grabbing");
                }
            };
        };
        // Recalculate the leaf sizing and positions
        _this.recalculateLeaves = function () {
            var activeLeaf = _this.app.workspace.getLeaf();
            // get and loop through the root splits (there may be more than one if using popout windows)
            var rootSplits = _this.getRootSplits();
            rootSplits.forEach(function (rootSplit) {
                var rootContainerEl = rootSplit.containerEl;
                // get the client width of the root container once, before looping through the leaves
                var rootContainerElWidth = rootContainerEl.clientWidth;
                var rootLeaves = rootSplit.children;
                var leafCount = rootLeaves.length;
                var leafWidth = _this.settings.leafAutoWidth
                    ? (rootContainerElWidth - ((leafCount - 1) * _this.settings.headerWidth))
                    : (obsidian.Platform.isDesktop ? _this.settings.leafDesktopWidth : _this.settings.leafMobileWidth);
                var totalWidthEstimate = leafCount * leafWidth;
                var widthChange = false;
                // loop through all the leaves
                rootLeaves.forEach(function (leaf, i) {
                    var containerEl = leaf.containerEl;
                    // the default values for the leaf
                    var flex = '1 0 0';
                    var width = leaf.width;
                    // if the leaf was previously "flex", then the width will be out of whack
                    if (containerEl.style.flexBasis)
                        width = leafWidth;
                    var left = null;
                    var right = null;
                    if (totalWidthEstimate > rootContainerElWidth) {
                        // if the total width is greater than the root container width, we need to limit the leaves
                        flex = null;
                        if (!width)
                            width = leafWidth;
                        if (_this.settings.stackingEnabled) {
                            // if stacking is enabled, we need to set the left and right values
                            left = (i * _this.settings.headerWidth) + "px";
                            right = (((leafCount - i) * _this.settings.headerWidth) - leafWidth) + "px";
                        }
                    }
                    // set the html attributes for the leaf (if they have changed)
                    if (containerEl.style.flex != flex || containerEl.style.width != width + "px" || containerEl.style.left != left || containerEl.style.right != right) {
                        widthChange = containerEl.style.width != width + "px";
                        var style = { flex: flex, left: left, right: right, width: width + "px" };
                        Object.assign(containerEl.style, style);
                    }
                    // set the leaf's width for later reference
                    leaf.width = width;
                    if (leaf instanceof obsidian.WorkspaceLeaf) {
                        var iconEl = leaf.view.iconEl;
                        var iconText = iconEl.getAttribute("aria-label");
                        if (!iconText.includes("(")) {
                            iconEl.setAttribute("aria-label", "".concat(leaf.getDisplayText(), " (").concat(iconText, ")"));
                        }
                    }
                });
                // if the active leaf is in the current container, and the width has changed, refocus the active leaf
                if (activeLeaf.getContainer() === rootSplit && widthChange)
                    _this.focusLeaf(activeLeaf, !_this.settings.leafAutoWidth);
            });
        };
        _this.handleActiveLeafChange = function (leaf) {
            if (leaf) {
                _this.focusLeaf(leaf);
            }
        };
        // hande when a file is deleted
        _this.handleDelete = function (file) {
            // close any leaves with the deleted file open
            // detaching a leaf while iterating messes with the iteration
            var leavesToDetach = [];
            _this.app.workspace.iterateRootLeaves(function (leaf) {
                if (leaf.view instanceof obsidian.FileView && leaf.view.file == file) {
                    leavesToDetach.push(leaf);
                }
            });
            leavesToDetach.forEach(function (leaf) { return leaf.detach(); });
        };
        _this.getRootSplits = function () {
            var rootSplits = [];
            // push the main window's root split to the list
            rootSplits.push(_this.app.workspace.rootSplit);
            var floatingSplit = _this.app.workspace.floatingSplit;
            floatingSplit.children.forEach(function (child) {
                // if this is a window, push it to the list 
                if (child instanceof obsidian.WorkspaceWindow) {
                    rootSplits.push(child);
                }
            });
            return rootSplits;
        };
        return _this;
    }
    SlidingPanesPlugin.prototype.selectOrientation = function (orient) {
        document.body.classList.toggle('plugin-sliding-select-orientation-mixed', orient == 'mixed');
        document.body.classList.toggle('plugin-sliding-select-orientation-upright', orient == 'upright');
        document.body.classList.toggle('plugin-sliding-select-orientation-sideway', orient == 'sideway');
    };
    SlidingPanesPlugin.prototype.focusLeaf = function (activeLeaf, animated) {
        var _this = this;
        if (animated === void 0) { animated = true; }
        var rootSplit = activeLeaf.getContainer();
        while (activeLeaf != null && activeLeaf.parentSplit != null && activeLeaf.parentSplit !== rootSplit) {
            activeLeaf = activeLeaf.parentSplit;
        }
        if (activeLeaf != null && activeLeaf.parentSplit != null && activeLeaf.parentSplit === rootSplit) {
            var rootContainerEl = rootSplit.containerEl;
            var rootLeaves = rootSplit.children;
            var leafCount = rootLeaves.length;
            // get the index of the active leaf
            // also, get the position of this leaf, so we can scroll to it
            // as leaves are resizable, we have to iterate through all leaves to the
            // left until we get to the active one and add all their widths together
            var position_1 = 0;
            this.activeLeafIndex = -1;
            rootLeaves.forEach(function (leaf, index) {
                var containerEl = leaf.containerEl;
                // this is the active one
                if (leaf == activeLeaf) {
                    _this.activeLeafIndex = index;
                    containerEl.classList.remove('mod-am-left-of-active');
                    containerEl.classList.remove('mod-am-right-of-active');
                }
                else if (_this.activeLeafIndex == -1 || index < _this.activeLeafIndex) {
                    // this is before the active one, add the width
                    position_1 += containerEl.clientWidth;
                    containerEl.classList.add('mod-am-left-of-active');
                    containerEl.classList.remove('mod-am-right-of-active');
                }
                else {
                    // this is right of the active one
                    containerEl.classList.remove('mod-am-left-of-active');
                    containerEl.classList.add('mod-am-right-of-active');
                }
            });
            // get this leaf's left value (the amount of space to the left for sticky headers)
            var left = parseInt(activeLeaf.containerEl.style.left) || 0;
            // the amount of space to the right we need to leave for sticky headers
            var headersToRightWidth = this.settings.stackingEnabled ? (leafCount - this.activeLeafIndex - 1) * this.settings.headerWidth : 0;
            // determine whether to request 'smooth' animations or 'auto' snap
            var behavior = animated && this.settings.smoothAnimation ? 'smooth' : 'auto';
            // it's too far left
            if (rootContainerEl.scrollLeft > position_1 - left) {
                // scroll the left side of the pane into view
                rootContainerEl.scrollTo({ left: position_1 - left, top: 0, behavior: behavior });
            }
            // it's too far right
            else if (rootContainerEl.scrollLeft + rootContainerEl.clientWidth < position_1 + activeLeaf.containerEl.clientWidth + headersToRightWidth) {
                // scroll the right side of the pane into view
                rootContainerEl.scrollTo({ left: position_1 + activeLeaf.containerEl.clientWidth + headersToRightWidth - rootContainerEl.clientWidth, top: 0, behavior: behavior });
            }
        }
    };
    return SlidingPanesPlugin;
}(PluginBase));

module.exports = SlidingPanesPlugin;
//# sourceMappingURL=data:application/json;charset=utf-8;base64,[encoded data, 91480 characters]
