/*
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD
if you want to view the source, please visit the github repository of this plugin
*/

var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __commonJS = (cb, mod) => function __require() {
  return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// manifest.json
var require_manifest = __commonJS({
  "manifest.json"(exports, module2) {
    module2.exports = {
      id: "lazy-plugins",
      name: "Lazy Plugin Loader",
      version: "1.0.18",
      minAppVersion: "1.6.0",
      description: "Load plugins with a delay on startup, so that you can get your app startup down into the sub-second loading time.",
      author: "Alan Grainger",
      authorUrl: "https://github.com/alangrainger",
      fundingUrl: "https://ko-fi.com/alan_",
      isDesktopOnly: false
    };
  }
});

// src/main.ts
var main_exports = {};
__export(main_exports, {
  default: () => LazyPlugin
});
module.exports = __toCommonJS(main_exports);
var import_obsidian2 = require("obsidian");

// src/settings.ts
var import_obsidian = require("obsidian");
var DEFAULT_DEVICE_SETTINGS = {
  shortDelaySeconds: 5,
  longDelaySeconds: 15,
  delayBetweenPlugins: 40,
  // milliseconds
  defaultStartupType: null,
  showDescriptions: true,
  plugins: {}
};
var DEFAULT_SETTINGS = {
  dualConfigs: false,
  showConsoleLog: false,
  desktop: DEFAULT_DEVICE_SETTINGS
};
var LoadingMethods = {
  disabled: "\u26D4 Disable plugin",
  instant: "\u26A1 Instant",
  short: "\u231A Short delay",
  long: "\u{1F4A4} Long delay"
};
var SettingsTab = class extends import_obsidian.PluginSettingTab {
  constructor(app, plugin) {
    super(app, plugin);
    this.dropdowns = [];
    this.app = app;
    this.lazyPlugin = plugin;
  }
  async display() {
    const { containerEl } = this;
    this.containerEl = containerEl;
    await this.lazyPlugin.loadSettings();
    this.buildDom();
  }
  /**
   * Build the Settings modal DOM elements
   */
  buildDom() {
    const pluginSettings = this.lazyPlugin.settings.plugins;
    this.containerEl.empty();
    new import_obsidian.Setting(this.containerEl).setName("Separate desktop/mobile configuration").setDesc(`Enable this if you want to have different settings depending whether you're using a desktop or mobile device. All of the settings below can be configured differently on desktop and mobile. You're currently using the ${this.lazyPlugin.device} settings.`).addToggle((toggle) => {
      toggle.setValue(this.lazyPlugin.data.dualConfigs).onChange(async (value) => {
        this.lazyPlugin.data.dualConfigs = value;
        await this.lazyPlugin.saveSettings();
        await this.lazyPlugin.loadSettings();
        this.buildDom();
      });
    });
    new import_obsidian.Setting(this.containerEl).setName("Lazy Loader settings").setHeading();
    Object.entries({
      shortDelaySeconds: "Short delay (seconds)",
      longDelaySeconds: "Long delay (seconds)"
    }).forEach(([key, name]) => {
      new import_obsidian.Setting(this.containerEl).setName(name).addText((text) => text.setValue(this.lazyPlugin.settings[key].toString()).onChange(async (value) => {
        this.lazyPlugin.settings[key] = parseFloat(parseFloat(value).toFixed(3));
        await this.lazyPlugin.saveSettings();
      }));
    });
    new import_obsidian.Setting(this.containerEl).setName("Default startup type for new plugins").addDropdown((dropdown) => {
      dropdown.addOption("", "Nothing configured");
      this.addDelayOptions(dropdown);
      dropdown.setValue(this.lazyPlugin.settings.defaultStartupType || "").onChange(async (value) => {
        this.lazyPlugin.settings.defaultStartupType = value || null;
        await this.lazyPlugin.saveSettings();
      });
    });
    new import_obsidian.Setting(this.containerEl).setName("Show plugin descriptions").addToggle((toggle) => {
      toggle.setValue(this.lazyPlugin.settings.showDescriptions).onChange(async (value) => {
        this.lazyPlugin.settings.showDescriptions = value;
        await this.lazyPlugin.saveSettings();
        this.buildDom();
      });
    });
    new import_obsidian.Setting(this.containerEl).setName("Set the delay for all plugins at once").addDropdown((dropdown) => {
      dropdown.addOption("", "Set all plugins to be:");
      this.addDelayOptions(dropdown);
      dropdown.onChange(async (value) => {
        this.lazyPlugin.manifests.forEach((plugin) => {
          pluginSettings[plugin.id] = { startupType: value };
        });
        this.dropdowns.forEach((dropdown2) => dropdown2.setValue(value));
        dropdown.setValue("");
        await this.lazyPlugin.saveSettings();
      });
    });
    new import_obsidian.Setting(this.containerEl).setName("Plugins").setHeading().setDesc("Filter by: ").then((setting) => {
      this.addFilterButton(setting.descEl, "All");
      Object.keys(LoadingMethods).forEach((key) => this.addFilterButton(setting.descEl, LoadingMethods[key], key));
    });
    this.lazyPlugin.manifests.forEach((plugin) => {
      const currentValue = this.lazyPlugin.getPluginStartup(plugin.id);
      if (this.filter && currentValue !== this.filter)
        return;
      new import_obsidian.Setting(this.containerEl).setName(plugin.name).addDropdown((dropdown) => {
        this.dropdowns.push(dropdown);
        this.addDelayOptions(dropdown);
        dropdown.setValue(currentValue).onChange(async (value) => {
          await this.lazyPlugin.updatePluginSettings(plugin.id, value);
          this.lazyPlugin.setPluginStartup(plugin.id).then();
        });
      }).then((setting) => {
        if (this.lazyPlugin.settings.showDescriptions) {
          setting.setDesc(plugin.description);
        }
      });
    });
  }
  /**
   * Add the dropdown select options for each delay type
   */
  addDelayOptions(el) {
    Object.keys(LoadingMethods).forEach((key) => {
      el.addOption(key, LoadingMethods[key]);
    });
  }
  /**
   * Add a filter button in the header of the plugin list
   */
  addFilterButton(el, text, value) {
    const link = el.createEl("button", { text });
    link.addClass("lazy-plugin-filter");
    link.onclick = () => {
      this.filter = value;
      this.buildDom();
    };
  }
};

// src/main.ts
var lazyPluginId = require_manifest().id;
var LazyPlugin = class extends import_obsidian2.Plugin {
  constructor() {
    super(...arguments);
    this.device = "desktop/global";
    this.pendingTimeouts = [];
  }
  async onload() {
    await this.loadSettings();
    this.manifests = Object.values(this.app.plugins.manifests).filter((plugin) => plugin.id !== lazyPluginId && // Filter out the Lazy Loader plugin
    !(import_obsidian2.Platform.isMobile && plugin.isDesktopOnly)).sort((a, b) => a.name.localeCompare(b.name));
    await this.setInitialPluginsConfiguration();
    this.addSettingTab(new SettingsTab(this.app, this));
    this.manifests.forEach((plugin) => this.setPluginStartup(plugin.id));
  }
  /**
   * Configure and load a plugin based on its startup settings.
   */
  async setPluginStartup(pluginId) {
    var _a, _b;
    const obsidian = this.app.plugins;
    const startupType = this.getPluginStartup(pluginId);
    const isActiveOnStartup = obsidian.enabledPlugins.has(pluginId);
    const isRunning = (_b = (_a = obsidian.plugins) == null ? void 0 : _a[pluginId]) == null ? void 0 : _b._loaded;
    switch (startupType) {
      case "disabled" /* disabled */:
        await obsidian.disablePluginAndSave(pluginId);
        break;
      case "instant" /* instant */:
        if (!isActiveOnStartup && !isRunning)
          await obsidian.enablePluginAndSave(pluginId);
        break;
      case "short" /* short */:
      case "long" /* long */:
        if (isActiveOnStartup) {
          await obsidian.disablePluginAndSave(pluginId);
          await obsidian.enablePlugin(pluginId);
        } else if (!isRunning) {
          const seconds = startupType === "short" /* short */ ? this.settings.shortDelaySeconds : this.settings.longDelaySeconds;
          const stagger = isNaN(this.settings.delayBetweenPlugins) ? 40 : this.settings.delayBetweenPlugins;
          const delay = this.manifests.findIndex((x) => x.id === pluginId) * stagger;
          const timeout = setTimeout(async () => {
            var _a2, _b2;
            if (!((_b2 = (_a2 = obsidian.plugins) == null ? void 0 : _a2[pluginId]) == null ? void 0 : _b2._loaded)) {
              if (this.data.showConsoleLog) {
                console.log(`Starting ${pluginId} after a ${startupType} delay`);
              }
              await obsidian.enablePlugin(pluginId);
            }
          }, seconds * 1e3 + delay);
          this.pendingTimeouts.push(timeout);
        }
        break;
    }
  }
  /**
   * Get the startup type for a given pluginId, falling back to Obsidian's current
   * loading method (enabled/disabled) if no configuration is found for this plugin.
   */
  getPluginStartup(pluginId) {
    var _a, _b;
    return ((_b = (_a = this.settings.plugins) == null ? void 0 : _a[pluginId]) == null ? void 0 : _b.startupType) || this.settings.defaultStartupType || (this.app.plugins.enabledPlugins.has(pluginId) ? "instant" /* instant */ : "disabled" /* disabled */);
  }
  async loadSettings() {
    this.data = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
    this.data.desktop = Object.assign({}, DEFAULT_DEVICE_SETTINGS, this.data.desktop);
    if (this.data.dualConfigs && import_obsidian2.Platform.isMobile) {
      if (!this.data.mobile) {
        this.data.mobile = Object.assign({}, this.data.desktop);
      } else {
        this.data.mobile = Object.assign({}, DEFAULT_DEVICE_SETTINGS, this.data.mobile);
      }
      this.settings = this.data.mobile;
      this.device = "mobile";
    } else {
      this.settings = this.data.desktop;
      this.device = "desktop/global";
    }
  }
  async saveSettings() {
    await this.saveData(this.data);
  }
  /**
   * Set the initial config value for all installed plugins. This will also set the value
   * for any new plugin in the future, depending on what default value is chosen in the
   * Settings page.
   */
  async setInitialPluginsConfiguration() {
    var _a, _b;
    for (const plugin of this.manifests) {
      if (!((_b = (_a = this.settings.plugins) == null ? void 0 : _a[plugin.id]) == null ? void 0 : _b.startupType)) {
        await this.updatePluginSettings(plugin.id, this.getPluginStartup(plugin.id));
      }
    }
  }
  /**
   * Update an individual plugin's configuration in the settings file
   */
  async updatePluginSettings(pluginId, startupType) {
    this.settings.plugins[pluginId] = { startupType };
    await this.saveSettings();
  }
  /*
   * Originally this was set up so that when the plugin unloaded, it would enablePluginAndSave()
   * the other plugins based on their Lazy Loader startup config.
   *
   * The problem with that is that the onunload() function is called during plugin *update* also,
   * which means that every time you get an update for this plugin, it would cause:
   *
   * a) A slowdown across the vault for the next 1-2 restarts.
   * b) The possibility of plugins being loaded twice / duplicated.
   *
   * Since across all users, updating the plugin is common, and uninstalling the plugin is less
   * common, I decided to remove this function.
   *
   * I apologise to the people who have to manually re-enable their plugins once they uninstall this one :(
   *
   * --------------------
   *
   * When the Lazy Loader plugin is disabled / deleted from Obsidian, iterate over
   * the configured plugins and re-enable any that are set to be delayed.
   *
   * This will cause a short slowdown as each plugin has to be disabled and then
   * re-enabled to save its new startup state.
   *
  async onunload () {
    // Clear any pending timeouts
    this.pendingTimeouts.forEach(timeout => clearTimeout(timeout))
    // Iterate over the configured plugins
    for (const plugin of this.manifests) {
      const startupType = this.settings.plugins?.[plugin.id]?.startupType
      if (startupType !== LoadingMethod.disabled) {
        await this.app.plugins.disablePlugin(plugin.id)
        await this.app.plugins.enablePluginAndSave(plugin.id)
        console.log(`Set ${plugin.id} back to instant start`)
      }
    }
  } */
};

/* nosourcemap */