Initial commit: BRAT fork with Gitea support
Tatortreiniger / tatort-reinigen (release) Has been cancelled

This commit is contained in:
olivier committed 2026-05-24 18:35:09 -04:00
1 parent bd3153fd32
commit 8de00536fa
44 files changed
+5172 -3

No files matched your search

+646
View File
@@ -0,0 +1,646 @@
import type { TextComponent } from "obsidian";
import {
ButtonComponent,
Modal,
Platform,
SecretComponent,
Setting,
} from "obsidian";
import { parseWithProvider } from "src/providers";
import type { ReleaseVersion } from "src/providers/PluginProvider";
import {
ProviderRateLimitError,
ProviderResponseError,
} from "src/providers/ProviderErrors";
import { TokenValidator } from "src/utils/TokenValidator";
import { createGitHubResourceLink } from "src/utils/utils";
import type BetaPlugins from "../features/BetaPlugins";
import type BratPlugin from "../main";
import { existBetaPluginInList, updatePluginTokenName } from "../settings";
import { toastMessage } from "../utils/notifications";
import { promotionalLinks } from "./Promotional";
import { VersionSuggestModal } from "./VersionSuggestModal";
/**
* Add a beta plugin to the list of plugins being tracked and updated.
* Supports both GitHub and Gitea repositories.
*/
export default class AddNewPluginModal extends Modal {
plugin: BratPlugin;
betaPlugins: BetaPlugins;
address: string;
openSettingsTabAfterwards: boolean;
readonly updateVersion: boolean;
version: string;
versionSetting: Setting | null = null;
// Repository Setting
repositoryAddressEl: TextComponent | null = null;
// Token Validation
secretName: string;
validToken: boolean | undefined;
tokenInputEl: SecretComponent | null = null;
validateButton: ButtonComponent | null = null;
validator: TokenValidator | null = null;
// Plugin install action
enableAfterInstall: boolean;
addPluginButton: ButtonComponent | null = null;
cancelButton: ButtonComponent | null = null;
// Gitea-specific: stored per-plugin
giteaInstanceUrl: string;
constructor(
plugin: BratPlugin,
betaPlugins: BetaPlugins,
openSettingsTabAfterwards = false,
updateVersion = false,
prefillRepo = "",
prefillVersion = "",
prefillSecretName = "",
) {
super(plugin.app);
this.plugin = plugin;
this.betaPlugins = betaPlugins;
this.address = prefillRepo;
this.version = prefillVersion;
this.secretName = prefillSecretName;
this.openSettingsTabAfterwards = openSettingsTabAfterwards;
this.updateVersion = updateVersion;
this.enableAfterInstall = plugin.settings.enableAfterInstall;
this.giteaInstanceUrl = "";
}
async submitForm(): Promise<void> {
if (this.address === "") return;
const scrubbedAddress = this.scrubAddress(this.address);
const existingFrozenPlugin =
this.plugin.settings.pluginSubListFrozenVersion.find(
(p) => p.repo === scrubbedAddress,
);
if (existingFrozenPlugin) {
const result = await this.betaPlugins.addPlugin(
scrubbedAddress,
false,
false,
false,
this.version,
true,
this.enableAfterInstall,
this.secretName,
);
if (result) this.close();
this.resetButtons();
return;
}
if (!this.version && existBetaPluginInList(this.plugin, scrubbedAddress)) {
toastMessage(
this.plugin,
"This plugin is already in the list for beta testing",
10,
);
return;
}
const result = await this.betaPlugins.addPlugin(
scrubbedAddress,
false,
false,
false,
this.version,
false,
this.enableAfterInstall,
this.secretName,
);
if (result) this.close();
this.resetButtons();
}
private resetButtons(): void {
this.cancelButton?.setDisabled(false);
this.addPluginButton?.setDisabled(false);
this.addPluginButton?.setButtonText("Add Plugin");
this.versionSetting?.setDisabled(false);
}
private updateVersionDropdown(
settingEl: Setting,
versions: ReleaseVersion[],
selected = "",
): void {
let selectedVersion: string;
settingEl.clear();
if (
versions.length > 0 &&
!selected &&
this.plugin.settings.selectLatestPluginVersionByDefault
) {
selectedVersion = "latest";
this.version = "latest";
} else {
selectedVersion = selected;
}
const VERSION_THRESHOLD = 20;
if (versions.length < VERSION_THRESHOLD || Platform.isMobile) {
settingEl.addDropdown((dropdown) => {
dropdown.addOption("", "Select a version");
dropdown.addOption("latest", "Latest version");
for (const version of versions) {
dropdown.addOption(
version.version,
`${version.version} ${version.prerelease ? "(Prerelease)" : ""}`,
);
}
dropdown.onChange((value: string) => {
this.version = value;
this.addPluginButton?.setDisabled(this.version === "");
});
dropdown.setValue(selectedVersion);
dropdown.selectEl.addClass("brat-version-selector");
dropdown.selectEl.style.width = "100%";
});
} else {
settingEl.addButton((button) => {
button
.setButtonText(
selectedVersion === "latest"
? "Latest version"
: selectedVersion || "Select a version...",
)
.setClass("brat-version-selector")
.setClass("button")
.onClick(() => {
const latest: ReleaseVersion = {
version: "latest",
prerelease: false,
};
const suggestedVersions = [latest, ...versions];
const modal = new VersionSuggestModal(
this.app,
this.address,
suggestedVersions,
selectedVersion,
(version: string) => {
this.version = version;
button.setButtonText(
version === "latest"
? "Latest version"
: version || "Select a version...",
);
this.addPluginButton?.setDisabled(this.version === "");
},
);
modal.open();
});
});
}
}
/**
* Clean up a user-supplied address. For GitHub, strip protocol/domain.
* For Gitea, keep the full URL.
*/
private scrubAddress(address: string): string {
const trimmed = address.trim();
// Bare "user/repo" → GitHub
if (/^[a-zA-Z0-9._-]+\/[a-zA-Z0-9._-]+$/.test(trimmed)) {
return trimmed;
}
// GitHub URL → strip to user/repo
if (/github\.com/i.test(trimmed)) {
return trimmed.replace(/https?:\/\/github\.com\//i, "").replace(/\.git$/i, "").replace(/\/$/, "");
}
// Gitea / other → keep full URL, strip trailing .git
return trimmed.replace(/\.git$/i, "").replace(/\/$/, "");
}
/**
* Check if an address looks like a valid repository URL (any provider)
*/
private isValidRepository(address: string): boolean {
const clean = address.trim().replace(/\.git$/i, "");
// GitHub format: user/repo or github.com/user/repo
const githubPattern =
/^(?:https?:\/\/github\.com\/)?([a-zA-Z0-9._-]+)\/([a-zA-Z0-9._-]+)$/i;
// Gitea format: hostname/owner/repo
const giteaPattern =
/^https?:\/\/[a-zA-Z0-9.-]+\/[a-zA-Z0-9._-]+\/[a-zA-Z0-9._-]+$/i;
return githubPattern.test(clean) || giteaPattern.test(clean);
}
onOpen(): void {
const heading = this.contentEl.createEl("h4");
if (this.address) {
heading.appendText("Change plugin version: ");
heading.appendChild(createGitHubResourceLink(this.address));
} else {
heading.setText("Repository for beta plugin:");
}
this.contentEl.createEl("form", {}, (formEl) => {
formEl.addClass("brat-modal");
if (!this.address || !this.updateVersion) {
const repoSetting = new Setting(formEl).setClass(
"repository-setting",
);
repoSetting.then((setting) => {
setting.addText((addressEl) => {
this.repositoryAddressEl = addressEl;
addressEl.setPlaceholder(
"Repository URL or path\n" +
"GitHub: GitHubUserName/repo (or full URL)\n" +
"Gitea: https://git.example.com/user/repo",
);
addressEl.setValue(this.address);
addressEl.onChange((value) => {
this.address = this.scrubAddress(value.trim());
// Disable version dropdown if address is empty
if (
this.version !== "" &&
(!this.address || !this.isValidRepository(this.address))
) {
if (this.versionSetting) {
this.updateVersionDropdown(this.versionSetting, []);
this.versionSetting.settingEl.classList.add(
"disabled-setting",
);
this.versionSetting.setDisabled(true);
addressEl.inputEl.classList.remove("valid-repository");
addressEl.inputEl.classList.remove("invalid-repository");
}
}
if (!this.version) {
if (this.isValidRepository(this.address))
this.addPluginButton?.setDisabled(false);
else this.addPluginButton?.setDisabled(true);
}
});
addressEl.inputEl.addEventListener(
"keydown",
async (e: KeyboardEvent) => {
if (e.key === "Enter") {
if (
this.address &&
((this.updateVersion && this.version !== "") ||
!this.updateVersion)
) {
e.preventDefault();
this.disableForm();
void this.submitForm();
}
await this.updateRepositoryVersionInfo(
this.version,
validationStatusEl,
);
}
},
);
addressEl.inputEl.addEventListener("blur", async () => {
await this.updateRepositoryVersionInfo(
this.version,
validationStatusEl,
);
});
setting.setDesc("Repository");
addressEl.inputEl.style.width = "100%";
});
});
}
const validationStatusEl = formEl.createDiv("validation-status");
if (!this.address)
validationStatusEl.setText(
"Enter a repository address to validate it.\nSupports GitHub and Gitea.",
);
// Version dropdown
this.versionSetting = new Setting(formEl)
.setClass("version-setting")
.setClass("disabled-setting");
this.updateVersionDropdown(this.versionSetting, [], this.version);
this.versionSetting.setDisabled(true);
// Token setting
const tokenElement = formEl.createDiv("token-setting");
new Setting(tokenElement)
.setName("Access Token")
.setDesc("Select a secret as token for this repository (optional)")
.addComponent((el) =>
new SecretComponent(this.plugin.app, el)
.setValue(this.secretName)
.onChange(async (selectedSecretName: string | null) => {
this.secretName = selectedSecretName?.trim() || "";
if (!this.secretName) {
if (
this.address &&
existBetaPluginInList(this.plugin, this.address)
) {
updatePluginTokenName(this.plugin, this.address, "");
toastMessage(
this.plugin,
`Token setting cleared for ${this.address}`,
3,
);
}
void this.updateRepositoryVersionInfo(
this.version,
validationStatusEl,
);
return;
}
const tokenValue = this.secretName
? this.plugin.app.secretStorage.getSecret(this.secretName)
: null;
if (tokenValue) {
this.validToken =
await this.validator?.validateToken(
tokenValue,
this.address,
);
if (!this.validToken) {
this.validateButton?.setButtonText("Invalid");
this.validateButton?.setDisabled(false);
} else {
this.validateButton?.setButtonText("Valid");
this.validateButton?.setDisabled(true);
if (this.address) {
await this.updateRepositoryVersionInfo(
this.version,
validationStatusEl,
);
if (existBetaPluginInList(this.plugin, this.address)) {
updatePluginTokenName(
this.plugin,
this.address,
this.secretName,
);
toastMessage(
this.plugin,
`Token setting updated for ${this.address}`,
3,
);
}
}
}
}
}),
);
this.validator = new TokenValidator();
if (this.secretName) {
const tokenValue = this.plugin.app.secretStorage.getSecret(
this.secretName,
);
if (tokenValue) {
void this.validator
.validateToken(tokenValue, this.address)
.then((isValid) => {
this.validToken = isValid;
if (this.validToken) {
this.validateButton?.setButtonText("Valid");
this.validateButton?.setDisabled(true);
}
});
}
}
formEl.createDiv("modal-button-container", (buttonContainerEl) => {
buttonContainerEl.createEl(
"label",
{ cls: "mod-checkbox" },
(labelEl) => {
const checkboxEl = labelEl.createEl("input", {
attr: { tabindex: -1 },
type: "checkbox",
});
checkboxEl.checked = this.enableAfterInstall;
checkboxEl.addEventListener("click", () => {
this.enableAfterInstall = checkboxEl.checked;
});
labelEl.appendText("Enable after installing the plugin");
},
);
this.cancelButton = new ButtonComponent(buttonContainerEl)
.setButtonText("Never mind")
.setClass("mod-cancel")
.onClick(() => this.close());
this.addPluginButton = new ButtonComponent(buttonContainerEl)
.setButtonText(
this.updateVersion
? this.address
? "Change version"
: "Add plugin"
: "Add plugin",
)
.setCta()
.onClick(() => {
if (this.address !== "") {
if (
(this.updateVersion && this.version !== "") ||
!this.updateVersion
) {
this.disableForm();
void this.submitForm();
}
}
});
if (this.updateVersion || this.address === "")
this.addPluginButton?.setDisabled(true);
});
const footer = formEl.createDiv();
footer.style.borderTop = "1px solid var(--background-modifier-border)";
footer.style.marginTop = "30px";
footer.style.paddingTop = "8px";
const byLine = footer.createSpan();
byLine.createEl("a", {
href: "https://bit.ly/o42-twitter",
text: "TFTHacker",
});
byLine.appendText(" and ");
byLine.createEl("a", {
href: "https://github.com/johannrichard",
text: "johannrichard",
});
byLine.appendText(" — Gitea fork");
byLine.style.fontStyle = "italic";
footer.appendChild(byLine);
promotionalLinks(footer, false);
const buttons = formEl.querySelectorAll("button");
for (const button of Array.from(buttons)) {
button.setAttribute("type", "button");
}
formEl.addEventListener("submit", (e: Event) => {
e.preventDefault();
e.stopPropagation();
});
});
if (this.address) {
window.setTimeout(async () => {
await this.updateRepositoryVersionInfo(this.version);
}, 100);
}
}
private disableForm(): void {
this.addPluginButton?.setDisabled(true);
this.addPluginButton?.setButtonText("Installing …");
this.cancelButton?.setDisabled(true);
this.versionSetting?.setDisabled(true);
}
/**
* Update the repository validation and version dropdown.
* Works with both GitHub and Gitea.
*/
private async updateRepositoryVersionInfo(
selectedVersion = "",
validationStatusEl?: HTMLElement,
): Promise<void> {
const validateInputEl = this.repositoryAddressEl;
if (!this.address) {
validationStatusEl?.setText("Repository address is required.");
validationStatusEl?.addClass("validation-status-error");
return;
}
if (!this.isValidRepository(this.address)) {
validationStatusEl?.setText(
"Invalid address. Expected: user/repo (GitHub) or https://host/user/repo (Gitea).",
);
validationStatusEl?.addClass("validation-status-error");
return;
}
validationStatusEl?.setText("Validating repository...");
validationStatusEl?.removeClass("validation-status-error");
if (this.versionSetting && this.updateVersion) {
this.updateVersionDropdown(this.versionSetting, []);
}
const scrubbedAddress = this.scrubAddress(this.address);
try {
// Get token value
let tokenToUse = "";
if (this.secretName) {
const tokenValue = this.plugin.app.secretStorage.getSecret(
this.secretName,
);
if (tokenValue) tokenToUse = tokenValue;
} else if (this.plugin.settings.globalTokenName) {
const globalToken = this.plugin.app.secretStorage.getSecret(
this.plugin.settings.globalTokenName,
);
if (globalToken) tokenToUse = globalToken;
}
// Use provider to fetch versions
const { provider, parsed } = parseWithProvider(scrubbedAddress);
const versions = await provider.listReleases(parsed, tokenToUse);
if (versions && versions.length > 0) {
validateInputEl?.inputEl.classList.remove("invalid-repository");
validateInputEl?.inputEl.classList.add("valid-repository");
validationStatusEl?.setText("");
if (this.versionSetting) {
this.versionSetting.settingEl.classList.remove("disabled-setting");
this.versionSetting.setDisabled(false);
this.updateVersionDropdown(
this.versionSetting,
versions,
selectedVersion,
);
}
} else {
validateInputEl?.inputEl.classList.remove("valid-repository");
validateInputEl?.inputEl.classList.add("invalid-repository");
validationStatusEl?.setText(
"No releases found in this repository.",
);
validationStatusEl?.addClass("validation-status-error");
this.versionSetting?.settingEl.classList.add("disabled-setting");
this.versionSetting?.setDisabled(true);
this.addPluginButton?.setDisabled(true);
}
} catch (error: unknown) {
if (error instanceof ProviderRateLimitError) {
validateInputEl?.inputEl.classList.remove("valid-repository");
validateInputEl?.inputEl.classList.add("validation-error");
validationStatusEl?.setText(
`API rate limit exceeded. Try again in ${error.getMinutesToReset()} minutes.`,
);
this.disableVersionAndButton();
toastMessage(
this.plugin,
`${error.message} Consider adding an access token in settings.`,
20,
);
} else if (error instanceof ProviderResponseError) {
switch (error.status) {
case 404:
validationStatusEl?.setText(
"Repository not found. Check the address or provide a valid token for private repos.",
);
break;
case 403:
validationStatusEl?.setText(
"Access denied. Check your access token.",
);
break;
default:
validationStatusEl?.setText(`Error: ${error.message}`);
}
validationStatusEl?.addClass("validation-status-error");
this.disableVersionAndButton();
toastMessage(this.plugin, error.message, 20);
} else {
validationStatusEl?.setText(
`Unexpected error: ${error}. Enable debug mode for details.`,
);
validationStatusEl?.addClass("validation-status-error");
this.disableVersionAndButton();
}
}
}
private disableVersionAndButton(): void {
this.versionSetting?.setDisabled(true);
this.addPluginButton?.setDisabled(true);
}
onClose(): void {
if (this.openSettingsTabAfterwards) {
// @ts-expect-error
this.plugin.app.setting.open();
// @ts-expect-error
this.plugin.app.setting.openTabById(this.plugin.APP_ID);
}
}
}
+119
View File
@@ -0,0 +1,119 @@
import { ButtonComponent, Modal, Setting } from "obsidian";
import { themeSave } from "../features/themes";
import type BratPlugin from "../main";
import { existBetaThemeinInList } from "../settings";
import { toastMessage } from "../utils/notifications";
import { promotionalLinks } from "./Promotional";
/**
* Add a beta theme to the list of plugins being tracked and updated
*/
export default class AddNewTheme extends Modal {
plugin: BratPlugin;
address: string;
openSettingsTabAfterwards: boolean;
constructor(plugin: BratPlugin, openSettingsTabAfterwards = false) {
super(plugin.app);
this.plugin = plugin;
this.address = "";
this.openSettingsTabAfterwards = openSettingsTabAfterwards;
}
async submitForm(): Promise<void> {
if (this.address === "") return;
const scrubbedAddress = this.address.replace("https://github.com/", "");
if (existBetaThemeinInList(this.plugin, scrubbedAddress)) {
toastMessage(
this.plugin,
"This theme is already in the list for beta testing",
10,
);
return;
}
if (await themeSave(this.plugin, scrubbedAddress, true)) {
this.close();
}
}
onOpen(): void {
this.contentEl.createEl("h4", {
text: "Github repository for beta theme:",
});
this.contentEl.createEl("form", {}, (formEl) => {
formEl.addClass("brat-modal");
new Setting(formEl).addText((textEl) => {
textEl.setPlaceholder(
"Repository (example: https://github.com/user/repo or https://git.example.com/user/repo)",
);
textEl.setValue(this.address);
textEl.onChange((value) => {
this.address = value.trim();
});
textEl.inputEl.addEventListener("keydown", (e: KeyboardEvent) => {
if (e.key === "Enter" && this.address !== " ") {
e.preventDefault();
void this.submitForm();
}
});
textEl.inputEl.style.width = "100%";
window.setTimeout(() => {
const title = document.querySelector(".setting-item-info");
if (title) title.remove();
textEl.inputEl.focus();
}, 10);
});
formEl.createDiv("modal-button-container", (buttonContainerEl) => {
new ButtonComponent(buttonContainerEl)
.setButtonText("Never mind")
.onClick(() => {
this.close();
});
new ButtonComponent(buttonContainerEl)
.setButtonText("Add theme")
.setCta()
.onClick((e: Event) => {
e.preventDefault();
console.log("Add theme button clicked");
if (this.address !== "") void this.submitForm();
});
});
const newDiv = formEl.createDiv();
newDiv.style.borderTop = "1px solid #ccc";
newDiv.style.marginTop = "30px";
const byTfThacker = newDiv.createSpan();
byTfThacker.createEl("a", {
href: "https://bit.ly/o42-twitter",
text: "TFTHacker",
});
byTfThacker.appendText(" and ");
byTfThacker.createEl("a", {
href: "https://github.com/johannrichard",
text: "johannrichard",
});
byTfThacker.style.fontStyle = "italic";
newDiv.appendChild(byTfThacker);
promotionalLinks(newDiv, false);
window.setTimeout(() => {
const title = formEl.querySelectorAll(".brat-modal .setting-item-info");
for (const titleEl of Array.from(title)) {
titleEl.remove();
}
}, 50);
});
}
onClose(): void {
if (this.openSettingsTabAfterwards) {
// @ts-expect-error
this.plugin.app.setting.openTab();
// @ts-expect-error
this.plugin.app.setting.openTabById(this.plugin.APP_ID);
}
}
}
+67
View File
@@ -0,0 +1,67 @@
import type { App } from "obsidian";
import { ButtonComponent, Modal } from "obsidian";
interface ConfirmOptions {
app: App;
cancelButtonText?: string;
cssClass?: string;
message: DocumentFragment | string;
okButtonText?: string;
title?: DocumentFragment | string;
}
type PromiseResolve<T> = undefined extends T
? (value?: PromiseLike<T> | T) => void
: (value: PromiseLike<T> | T) => void;
class ConfirmModal extends Modal {
private isConfirmed = false;
private options: Required<ConfirmOptions>;
public constructor(
options: ConfirmOptions,
private readonly resolve: PromiseResolve<boolean>,
) {
super(options.app);
const DEFAULT_OPTIONS: Required<ConfirmOptions> = {
app: options.app,
cancelButtonText: "Cancel",
cssClass: "",
message: options.message,
okButtonText: "OK",
title: "",
};
this.options = { ...DEFAULT_OPTIONS, ...options };
this.containerEl.addClass("confirm-modal");
}
public override onClose(): void {
super.onClose();
this.resolve(this.isConfirmed);
}
public override onOpen(): void {
super.onOpen();
this.titleEl.setText(this.options.title);
this.contentEl.createEl("p", { text: this.options.message });
const okButton = new ButtonComponent(this.contentEl);
okButton.setClass("ok-button");
okButton.setButtonText(this.options.okButtonText);
okButton.setCta();
okButton.onClick(() => {
this.isConfirmed = true;
this.close();
});
const cancelButton = new ButtonComponent(this.contentEl);
cancelButton.setButtonText(this.options.cancelButtonText);
cancelButton.onClick(this.close.bind(this));
}
}
export async function confirm(options: ConfirmOptions): Promise<boolean> {
return await new Promise<boolean>((resolve) => {
const modal = new ConfirmModal(options, resolve);
modal.open();
});
}
+75
View File
@@ -0,0 +1,75 @@
import { FuzzySuggestModal } from "obsidian";
import type { FuzzyMatch } from "obsidian";
import type BratPlugin from "../main";
/**
* Simple interface for what should be displayed and stored for suggester
*/
export interface SuggesterItem {
// displayed to user
display: string;
// supplmental info for the callback
info: (() => void) | string;
}
/**
* Generic suggester for quick reuse
*/
export class GenericFuzzySuggester extends FuzzySuggestModal<SuggesterItem> {
data: SuggesterItem[] = [];
callbackFunction!: (item: SuggesterItem, evt: MouseEvent | KeyboardEvent) => void;
constructor(plugin: BratPlugin) {
super(plugin.app);
this.scope.register(["Shift"], "Enter", (evt) => {
this.enterTrigger(evt);
});
this.scope.register(["Ctrl"], "Enter", (evt) => {
this.enterTrigger(evt);
});
}
setSuggesterData(suggesterData: SuggesterItem[]): void {
this.data = suggesterData;
}
display(callBack: (item: SuggesterItem, evt: MouseEvent | KeyboardEvent) => void) {
this.callbackFunction = callBack;
this.open();
}
getItems(): SuggesterItem[] {
return this.data;
}
getItemText(item: SuggesterItem): string {
return item.display;
}
onChooseItem(): void {
return;
}
renderSuggestion(item: FuzzyMatch<SuggesterItem>, el: HTMLElement): void {
el.createEl("div", { text: item.item.display });
}
enterTrigger(evt: KeyboardEvent): void {
const selectedText = document.querySelector(".suggestion-item.is-selected div")?.textContent;
const item = this.data.find((i) => i.display === selectedText);
if (item) {
this.invokeCallback(item, evt);
this.close();
}
}
onChooseSuggestion(item: FuzzyMatch<SuggesterItem>, evt: MouseEvent | KeyboardEvent): void {
this.invokeCallback(item.item, evt);
}
invokeCallback(item: SuggesterItem, evt: MouseEvent | KeyboardEvent): void {
if (typeof this.callbackFunction === "function") {
(this.callbackFunction as (item: SuggesterItem, evt: MouseEvent | KeyboardEvent) => void)(item, evt);
}
}
}
+398
View File
@@ -0,0 +1,398 @@
import type { SettingTab } from "obsidian";
import type { CommunityPlugin, CommunityTheme } from "../features/communityUtils";
import {
grabCommmunityPluginList,
grabCommmunityThemesList,
} from "../features/communityUtils";
import { themesCheckAndUpdates } from "../features/themes";
import type BratPlugin from "../main";
import { toastMessage } from "../utils/notifications";
import AddNewTheme from "./AddNewTheme";
import type { SuggesterItem } from "./GenericFuzzySuggester";
import { GenericFuzzySuggester } from "./GenericFuzzySuggester";
export default class PluginCommands {
plugin: BratPlugin;
bratCommands = [
{
id: "AddBetaPlugin",
icon: "BratIcon",
name: "Plugins: Add a beta plugin for testing (with or without version)",
showInRibbon: true,
callback: () => {
this.plugin.betaPlugins.displayAddNewPluginModal(false, true);
},
},
{
id: "checkForUpdatesAndUpdate",
icon: "BratIcon",
name: "Plugins: Check for updates to all beta plugins and UPDATE",
showInRibbon: true,
callback: async () => {
await this.plugin.betaPlugins.checkForPluginUpdatesAndInstallUpdates(
true,
false,
);
},
},
{
id: "checkForUpdatesAndDontUpdate",
icon: "BratIcon",
name: "Plugins: Only check for updates to beta plugins, but don't Update",
showInRibbon: true,
callback: async () => {
await this.plugin.betaPlugins.checkForPluginUpdatesAndInstallUpdates(
true,
true,
);
},
},
{
id: "updateOnePlugin",
icon: "BratIcon",
name: "Plugins: Choose a single plugin version to update",
showInRibbon: true,
callback: () => {
const frozenVersions = new Map(
this.plugin.settings.pluginSubListFrozenVersion.map((f) => [
f.repo,
{
version: f.version,
token: f.token,
},
]),
);
const pluginList: SuggesterItem[] = Object.values(
this.plugin.settings.pluginList,
)
.filter((repo) => {
const frozen = frozenVersions.get(repo);
return !frozen?.version || frozen.version === "latest";
})
.map((repo) => {
return {
display: repo,
info: repo,
};
});
const gfs = new GenericFuzzySuggester(this.plugin);
gfs.setSuggesterData(pluginList);
gfs.display((results) => {
const msg = `Checking for updates for ${results.info as string}`;
const frozen = frozenVersions.get(results.info as string);
void this.plugin.log(msg, true);
toastMessage(this.plugin, `\n${msg}`, 3);
void this.plugin.betaPlugins.updatePlugin(
results.info as string,
false,
true,
false,
frozen?.token,
);
});
},
},
{
id: "reinstallOnePlugin",
icon: "BratIcon",
name: "Plugins: Choose a single plugin to reinstall",
showInRibbon: true,
callback: () => {
const pluginSubListFrozenVersionNames = new Set(
this.plugin.settings.pluginSubListFrozenVersion.map((f) => f.repo),
);
const pluginList: SuggesterItem[] = Object.values(
this.plugin.settings.pluginList,
)
.filter((f) => !pluginSubListFrozenVersionNames.has(f))
.map((m) => {
return { display: m, info: m };
});
const gfs = new GenericFuzzySuggester(this.plugin);
gfs.setSuggesterData(pluginList);
gfs.display((results) => {
const msg = `Reinstalling ${results.info as string}`;
toastMessage(this.plugin, `\n${msg}`, 3);
void this.plugin.log(msg, true);
void this.plugin.betaPlugins.updatePlugin(
results.info as string,
false,
false,
true,
);
});
},
},
{
id: "restartPlugin",
icon: "BratIcon",
name: "Plugins: Restart a plugin that is already installed",
showInRibbon: true,
callback: () => {
const pluginList: SuggesterItem[] = Object.values(
// @ts-expect-error
this.plugin.app.plugins.manifests,
).map((m) => {
// @ts-expect-error
return { display: m.id, info: m.id };
});
const gfs = new GenericFuzzySuggester(this.plugin);
gfs.setSuggesterData(pluginList);
gfs.display((results) => {
toastMessage(
this.plugin,
`${results.info as string}\nPlugin reloading .....`,
5,
);
void this.plugin.betaPlugins.reloadPlugin(results.info as string);
});
},
},
{
id: "disablePlugin",
icon: "BratIcon",
name: "Plugins: Disable a plugin - toggle it off",
showInRibbon: true,
callback: () => {
const pluginList = this.plugin.betaPlugins
.getEnabledDisabledPlugins(true)
.map((manifest) => {
return {
display: `${manifest.name} (${manifest.id})`,
info: manifest.id,
};
});
const gfs = new GenericFuzzySuggester(this.plugin);
gfs.setSuggesterData(pluginList);
gfs.display((results) => {
void this.plugin.log(`${results.display} plugin disabled`, false);
if (this.plugin.settings.debuggingMode) console.log(results.info);
// @ts-expect-error
void this.plugin.app.plugins.disablePluginAndSave(
results.info as string,
);
});
},
},
{
id: "enablePlugin",
icon: "BratIcon",
name: "Plugins: Enable a plugin - toggle it on",
showInRibbon: true,
callback: () => {
const pluginList = this.plugin.betaPlugins
.getEnabledDisabledPlugins(false)
.map((manifest) => {
return {
display: `${manifest.name} (${manifest.id})`,
info: manifest.id,
};
});
const gfs = new GenericFuzzySuggester(this.plugin);
gfs.setSuggesterData(pluginList);
gfs.display((results) => {
void this.plugin.log(`${results.display} plugin enabled`, false);
// @ts-expect-error
void this.plugin.app.plugins.enablePluginAndSave(
results.info as string,
);
});
},
},
{
id: "openGitHubZRepository",
icon: "BratIcon",
name: "Plugins: Open the GitHub repository for a plugin",
showInRibbon: true,
callback: async () => {
const communityPlugins = await grabCommmunityPluginList(
this.plugin.settings.debuggingMode,
);
if (communityPlugins) {
const communityPluginList: SuggesterItem[] = Object.values(
communityPlugins,
).map((p: CommunityPlugin) => {
return { display: `Plugin: ${p.name} (${p.repo})`, info: p.repo };
});
const bratList: SuggesterItem[] = Object.values(
this.plugin.settings.pluginList,
).map((p) => {
return { display: `BRAT: ${p}`, info: p };
});
for (const si of communityPluginList) {
bratList.push(si);
}
const gfs = new GenericFuzzySuggester(this.plugin);
gfs.setSuggesterData(bratList);
gfs.display((results) => {
if (results.info)
window.open(`https://github.com/${results.info as string}`);
});
}
},
},
{
id: "openGitHubRepoTheme",
icon: "BratIcon",
name: "Themes: Open the GitHub repository for a theme (appearance)",
showInRibbon: true,
callback: async () => {
const communityTheme = await grabCommmunityThemesList(
this.plugin.settings.debuggingMode,
);
if (communityTheme) {
const communityThemeList: SuggesterItem[] = Object.values(
communityTheme,
).map((p: CommunityTheme) => {
return { display: `Theme: ${p.name} (${p.repo})`, info: p.repo };
});
const gfs = new GenericFuzzySuggester(this.plugin);
gfs.setSuggesterData(communityThemeList);
gfs.display((results) => {
if (results.info)
window.open(`https://github.com/${results.info as string}`);
});
}
},
},
{
id: "opentPluginSettings",
icon: "BratIcon",
name: "Plugins: Open Plugin Settings Tab",
showInRibbon: true,
callback: () => {
// @ts-expect-error
const settings = this.plugin.app.setting;
const listOfPluginSettingsTabs: SuggesterItem[] = Object.values(
settings.pluginTabs,
).map((t) => {
// @ts-expect-error
return { display: `Plugin: ${t.name}`, info: t.id };
});
const gfs = new GenericFuzzySuggester(this.plugin);
const listOfCoreSettingsTabs: SuggesterItem[] = Object.values(
settings.settingTabs,
).map((t) => {
// @ts-expect-error
return { display: `Core: ${t.name}`, info: t.id };
});
for (const si of listOfPluginSettingsTabs) {
listOfCoreSettingsTabs.push(si);
}
gfs.setSuggesterData(listOfCoreSettingsTabs);
gfs.display((results) => {
settings.open();
settings.openTabById(results.info as string);
});
},
},
{
id: "GrabBetaTheme",
icon: "BratIcon",
name: "Themes: Grab a beta theme for testing from a Github repository",
showInRibbon: true,
callback: () => {
new AddNewTheme(this.plugin).open();
},
},
{
id: "updateBetaThemes",
icon: "BratIcon",
name: "Themes: Update beta themes",
showInRibbon: true,
callback: async () => {
await themesCheckAndUpdates(this.plugin, true);
},
},
{
id: "allCommands",
icon: "BratIcon",
name: "All Commands list",
showInRibbon: false,
callback: () => {
this.ribbonDisplayCommands();
},
},
];
ribbonDisplayCommands(): void {
const bratCommandList: SuggesterItem[] = [];
for (const cmd of this.bratCommands) {
if (cmd.showInRibbon)
bratCommandList.push({ display: cmd.name, info: cmd.callback });
}
const gfs = new GenericFuzzySuggester(this.plugin);
// @ts-expect-error
const settings = this.plugin.app.setting;
const listOfCoreSettingsTabs: SuggesterItem[] = Object.values(
settings.settingTabs,
// @ts-expect-error
).map((t: SettingTab) => {
return {
// @ts-expect-error
display: `Core: ${t.name}`,
info: () => {
settings.open();
// @ts-expect-error
settings.openTabById(t.id);
},
};
});
const listOfPluginSettingsTabs: SuggesterItem[] = Object.values(
settings.pluginTabs,
// @ts-expect-error
).map((t: SettingTab) => {
return {
// @ts-expect-error
display: `Plugin: ${t.name}`,
info: () => {
settings.open();
// @ts-expect-error
settings.openTabById(t.id);
},
};
});
bratCommandList.push({
display: "---- Core Plugin Settings ----",
info: () => {
this.ribbonDisplayCommands();
},
});
for (const si of listOfCoreSettingsTabs) {
bratCommandList.push(si);
}
bratCommandList.push({
display: "---- Plugin Settings ----",
info: () => {
this.ribbonDisplayCommands();
},
});
for (const si of listOfPluginSettingsTabs) {
bratCommandList.push(si);
}
gfs.setSuggesterData(bratCommandList);
gfs.display((results) => {
if (typeof results.info === "function") {
results.info();
}
});
}
constructor(plugin: BratPlugin) {
this.plugin = plugin;
for (const item of this.bratCommands) {
this.plugin.addCommand({
id: item.id,
name: item.name,
icon: item.icon,
callback: () => {
item.callback();
},
});
}
}
}
+28
View File
@@ -0,0 +1,28 @@
export const promotionalLinks = (containerEl: HTMLElement, settingsTab = true): HTMLElement => {
const linksDiv = containerEl.createEl("div");
linksDiv.style.float = "right";
if (!settingsTab) {
linksDiv.style.padding = "10px";
linksDiv.style.paddingLeft = "15px";
linksDiv.style.paddingRight = "15px";
} else {
linksDiv.style.padding = "15px";
linksDiv.style.paddingLeft = "15px";
linksDiv.style.paddingRight = "15px";
linksDiv.style.marginLeft = "15px";
}
const twitterSpan = linksDiv.createDiv("coffee");
twitterSpan.addClass("ex-twitter-span");
twitterSpan.style.paddingLeft = "10px";
const captionText = twitterSpan.createDiv();
captionText.innerText = "Learn more about my work at:";
twitterSpan.appendChild(captionText);
const twitterLink = twitterSpan.createEl("a", {
href: "https://tfthacker.com",
});
twitterLink.innerText = "https://tfthacker.com";
return linksDiv;
};
+517
View File
@@ -0,0 +1,517 @@
import type { App, ButtonComponent, ExtraButtonComponent, SecretComponent, ToggleComponent } from "obsidian";
import {
PluginSettingTab,
SecretComponent as SecretComponentClass,
Setting,
SettingGroup,
} from "obsidian";
import { parseWithProvider } from "src/providers";
import { TokenValidator } from "src/utils/TokenValidator";
import { themeDelete } from "../features/themes";
import type BratPlugin from "../main";
import { createGitHubResourceLink, createLink } from "../utils/utils";
import AddNewTheme from "./AddNewTheme";
import { promotionalLinks } from "./Promotional";
export class BratSettingsTab extends PluginSettingTab {
plugin: BratPlugin;
accessTokenSetting: SecretComponent | null = null;
accessTokenButton: ButtonComponent | null = null;
tokenInfo: HTMLElement | null = null;
validator: TokenValidator | null = null;
constructor(app: App, plugin: BratPlugin) {
super(app, plugin);
this.plugin = plugin;
}
display(): void {
const { containerEl } = this;
containerEl.empty();
containerEl.addClass("brat-settings");
new Setting(containerEl)
.setName("Auto-enable plugins after installation")
.setDesc(
'If enabled beta plugins will be automatically enabled after installtion by default. Note: you can toggle this on and off for each plugin in the "Add Plugin" form.',
)
.addToggle((cb: ToggleComponent) => {
cb.setValue(this.plugin.settings.enableAfterInstall).onChange(
async (value: boolean) => {
this.plugin.settings.enableAfterInstall = value;
await this.plugin.saveSettings();
},
);
});
new Setting(containerEl)
.setName("Auto-update plugins at startup")
.setDesc(
"If enabled all beta plugins will be checked for updates each time Obsidian starts. Note: this does not update frozen version plugins.",
)
.addToggle((cb: ToggleComponent) => {
cb.setValue(this.plugin.settings.updateAtStartup).onChange(
async (value: boolean) => {
this.plugin.settings.updateAtStartup = value;
await this.plugin.saveSettings();
},
);
});
new Setting(containerEl)
.setName("Auto-update themes at startup")
.setDesc(
"If enabled all beta themes will be checked for updates each time Obsidian starts.",
)
.addToggle((cb: ToggleComponent) => {
cb.setValue(this.plugin.settings.updateThemesAtStartup).onChange(
async (value: boolean) => {
this.plugin.settings.updateThemesAtStartup = value;
await this.plugin.saveSettings();
},
);
});
new Setting(containerEl)
.setName("Select latest plugin version by default")
.setDesc(
"If enabled the latest version will be selected by default when adding a new plugin.",
)
.addToggle((cb: ToggleComponent) => {
cb.setValue(
this.plugin.settings.selectLatestPluginVersionByDefault,
).onChange(async (value: boolean) => {
this.plugin.settings.selectLatestPluginVersionByDefault = value;
await this.plugin.saveSettings();
});
});
new Setting(containerEl)
.setName("Allow incompatible plugins")
.setDesc(
"If enabled, plugins with higher app versions will be allowed to be installed. Also it allows desktop-only plugins to be installed on mobile devices.",
)
.addToggle((cb: ToggleComponent) => {
cb.setValue(this.plugin.settings.allowIncompatiblePlugins).onChange(
async (value: boolean) => {
this.plugin.settings.allowIncompatiblePlugins = value;
await this.plugin.saveSettings();
},
);
});
promotionalLinks(containerEl, true);
containerEl.createEl("hr");
const frozenVersions = new Map(
this.plugin.settings.pluginSubListFrozenVersion.map((f) => [f.repo, f]),
);
const pluginContainers = new Map<
string,
{ container: HTMLElement; pluginName: string }
>();
const betaPluginGroup = new SettingGroup(containerEl).setHeading(
"Beta plugin list",
);
betaPluginGroup.addSearch((cb) => {
cb.setPlaceholder("Filter plugins");
cb.onChange((value: string) => {
const filterValue = value.toLowerCase().trim();
pluginContainers.forEach(({ container, pluginName }) => {
if (filterValue === "") {
container.removeAttribute("hidden");
} else {
if (pluginName.includes(filterValue)) {
container.removeAttribute("hidden");
} else {
container.setAttribute("hidden", "true");
}
}
});
});
});
betaPluginGroup.addSetting((setting) => {
const pluginListDescription = document.createDocumentFragment();
pluginListDescription.createEl("div", {
text: `Plugins added via "Add a beta plugin for testing". Supports both GitHub and Gitea repositories.`,
});
pluginListDescription.createEl("p");
pluginListDescription.createEl("div", {
text: "Click the 'Edit' button next to a plugin to change installed version. Click x to remove from list.",
});
pluginListDescription.createEl("p");
pluginListDescription.createEl("span").createEl("b", {
text: "Note: ",
});
pluginListDescription.createSpan({
text: "Removing from the list does not delete the plugin — remove from Community Plugins tab instead.",
});
setting.setDesc(pluginListDescription);
setting.addButton((cb: ButtonComponent) => {
cb.setButtonText("Add beta plugin")
.setCta()
.onClick(() => {
this.plugin.betaPlugins.displayAddNewPluginModal(true);
});
});
});
for (const p of this.plugin.settings.pluginList) {
const bp = frozenVersions.get(p);
betaPluginGroup.addSetting((pluginSettingContainer) => {
const secretName = bp?.tokenName || "";
const secretValue = secretName
? this.plugin.app.secretStorage.getSecret(secretName)
: "";
const isSecretMissing = Boolean(secretName && !secretValue);
const isGitea = !!bp?.giteaUrl;
const pluginDescription = document.createDocumentFragment();
const trackedVersionText = bp?.version
? ` Tracked version: ${bp.version} ${bp.version === "latest" ? "" : "(frozen)"}`
: "";
const incompatibleText = bp?.isIncompatible
? " (incompatible)"
: "";
const giteaText = isGitea ? " (Gitea)" : "";
pluginDescription.createDiv({
text: `${trackedVersionText}${incompatibleText}${giteaText}`,
});
if (isSecretMissing) {
pluginDescription.createDiv({
text: ` Secret not defined or empty: ${secretName}`,
cls: "mod-warning",
title:
"Token name configured but secret is missing. Add the secret or update the plugin configuration.",
});
}
pluginSettingContainer
.setName(createGitHubResourceLink(p))
.setDesc(pluginDescription);
const containerElement = pluginSettingContainer.settingEl;
containerElement.addClass("brat-plugin-item");
if (isGitea) {
containerElement.addClass("brat-plugin-gitea");
}
pluginContainers.set(p, {
container: containerElement,
pluginName: p.toLowerCase(),
});
if (!bp?.version || bp.version === "latest") {
pluginSettingContainer.addButton((btn: ButtonComponent) => {
if (isSecretMissing) {
btn
.setIcon("sync")
.setTooltip(
`Secret missing: ${secretName}. Please add the secret or update the plugin configuration.`,
)
.setWarning()
.setDisabled(true);
} else {
btn
.setIcon("sync")
.setTooltip("Check and update plugin")
.onClick(async () => {
await this.plugin.betaPlugins.updatePlugin(
p,
false,
true,
false,
bp?.tokenName || "",
);
});
}
});
}
pluginSettingContainer
.addButton((btn: ButtonComponent) => {
btn
.setIcon("edit")
.setTooltip("Change version and update settings");
if (isSecretMissing) {
btn.setWarning();
}
btn.onClick(() => {
this.plugin.betaPlugins.displayAddNewPluginModal(
true,
true,
p,
bp?.version,
bp?.tokenName || "",
);
// @ts-expect-error
this.plugin.app.setting.updatePluginSection();
});
})
.addButton((btn: ButtonComponent) => {
btn
.setIcon("cross")
.setTooltip("Remove this beta plugin")
.setWarning()
.onClick(() => {
if (btn.buttonEl.textContent === "") {
btn.setButtonText("Click once more to confirm removal");
} else {
const { buttonEl } = btn;
const { parentElement } = buttonEl;
if (parentElement?.parentElement) {
parentElement.parentElement.remove();
this.plugin.betaPlugins.deletePlugin(p);
}
}
});
});
});
}
const themeContainers = new Map<
string,
{ container: HTMLElement; themeName: string }
>();
const betaThemeGroup = new SettingGroup(containerEl).setHeading(
"Beta themes list",
);
betaThemeGroup.addSetting((setting) =>
setting.addButton((cb: ButtonComponent) => {
cb.setButtonText("Add beta theme")
.setCta()
.onClick(() => {
// @ts-expect-error
this.plugin.app.setting.close();
new AddNewTheme(this.plugin).open();
});
}),
);
betaThemeGroup.addSearch((cb) => {
cb.setPlaceholder("Filter themes");
cb.onChange((value: string) => {
const filterValue = value.toLowerCase().trim();
themeContainers.forEach(({ container, themeName }) => {
if (filterValue === "") {
container.removeAttribute("hidden");
} else {
if (themeName.includes(filterValue)) {
container.removeAttribute("hidden");
} else {
container.setAttribute("hidden", "true");
}
}
});
});
});
for (const bpTheme of this.plugin.settings.themesList) {
betaThemeGroup.addSetting((themeSettingContainer) => {
themeSettingContainer.setName(
createGitHubResourceLink(bpTheme.repo),
);
const containerElement = themeSettingContainer.settingEl;
containerElement.addClass("brat-theme-item");
themeContainers.set(bpTheme.repo, {
container: containerElement,
themeName: bpTheme.repo.toLowerCase(),
});
themeSettingContainer.addButton((btn: ButtonComponent) => {
btn
.setIcon("cross")
.setTooltip("Delete this beta theme")
.onClick(() => {
if (btn.buttonEl.textContent === "")
btn.setButtonText("Click once more to confirm removal");
else {
const { buttonEl } = btn;
const { parentElement } = buttonEl;
if (parentElement?.parentElement) {
parentElement.parentElement.remove();
themeDelete(this.plugin, bpTheme.repo);
}
}
});
});
});
}
const monitoringGroup = new SettingGroup(containerEl)
.setHeading("Monitoring")
.addSetting((setting) =>
setting
.setName("Enable notifications")
.setDesc(
"BRAT will provide popup notifications for its various activities. Turn this off means no notifications from BRAT.",
)
.addToggle((cb: ToggleComponent) => {
cb.setValue(this.plugin.settings.notificationsEnabled);
cb.onChange(async (value: boolean) => {
this.plugin.settings.notificationsEnabled = value;
await this.plugin.saveSettings();
});
}),
)
.addSetting((setting) =>
setting
.setName("Enable logging")
.setDesc("Plugin updates will be logged to a file in the log file.")
.addToggle((cb: ToggleComponent) => {
cb.setValue(this.plugin.settings.loggingEnabled).onChange(
async (value: boolean) => {
this.plugin.settings.loggingEnabled = value;
await this.plugin.saveSettings();
},
);
}),
)
.addSetting((setting) =>
setting
.setName("BRAT log file location")
.setDesc(
"Logs will be saved to this file. Don't add .md to the file name.",
)
.addSearch((cb) => {
cb.setPlaceholder("Example: BRAT-log")
.setValue(this.plugin.settings.loggingPath)
.onChange(async (newFolder) => {
this.plugin.settings.loggingPath = newFolder;
await this.plugin.saveSettings();
});
}),
)
.addSetting((setting) =>
setting
.setName("Enable verbose logging")
.setDesc("Get a lot more information in the log.")
.addToggle((cb: ToggleComponent) => {
cb.setValue(this.plugin.settings.loggingVerboseEnabled).onChange(
async (value: boolean) => {
this.plugin.settings.loggingVerboseEnabled = value;
await this.plugin.saveSettings();
},
);
}),
);
monitoringGroup.addSetting((setting) =>
setting
.setName("Debugging mode")
.setDesc(
"Atomic Bomb level console logging. Can be used for troubleshooting and development.",
)
.addToggle((cb: ToggleComponent) => {
cb.setValue(this.plugin.settings.debuggingMode).onChange(
async (value: boolean) => {
this.plugin.settings.debuggingMode = value;
await this.plugin.saveSettings();
},
);
}),
);
// Access token section
const tokenSection = new SettingGroup(containerEl).setHeading(
"Access Token",
);
let currentTokenValue = "";
tokenSection.addSetting((tokenSetting) => {
tokenSetting.setName("Personal access token").setDesc(
createLink({
prependText:
"Increase rate limits for GitHub, or access private repos. Create one in ",
url: "https://github.com/settings/tokens/new?scopes=public_repo",
text: "your GitHub settings",
appendText:
". For Gitea, create a token in your Gitea instance settings.",
}),
);
this.accessTokenSetting = new SecretComponentClass(
this.plugin.app,
tokenSetting.controlEl,
);
this.accessTokenSetting
.setValue(this.plugin.settings.globalTokenName || "")
.onChange(async (secretName: string | null) => {
const normalizedName = secretName?.trim() || "";
this.plugin.settings.globalTokenName = normalizedName;
await this.plugin.saveSettings();
if (normalizedName) {
currentTokenValue =
this.plugin.app.secretStorage.getSecret(normalizedName) || "";
this.accessTokenButton?.setDisabled(false);
} else {
currentTokenValue = "";
this.accessTokenButton?.setDisabled(true);
await this.validator?.validateToken("");
}
});
if (this.plugin.settings.globalTokenName) {
currentTokenValue =
this.plugin.app.secretStorage.getSecret(
this.plugin.settings.globalTokenName,
) || "";
}
tokenSetting
.addExtraButton((cb: ExtraButtonComponent) => {
cb.setIcon("cross")
.setTooltip("Clear personal access token")
.onClick(async () => {
this.plugin.settings.globalTokenName = "";
await this.plugin.saveSettings();
this.accessTokenSetting?.setValue("");
currentTokenValue = "";
await this.validator?.validateToken("");
});
})
.addButton((btn: ButtonComponent) => {
this.accessTokenButton = btn;
btn
.setButtonText("Validate")
.setCta()
.onClick(async () => {
if (currentTokenValue) {
await this.validator?.validateToken(currentTokenValue);
}
});
})
.then(() => {
this.tokenInfo = this.createTokenInfoElement(containerEl);
this.validator = new TokenValidator(this.tokenInfo);
this.validator
?.validateToken(currentTokenValue)
.then((valid) => {
this.accessTokenButton?.setDisabled(
valid || !this.plugin.settings.globalTokenName,
);
});
});
});
}
private createTokenInfoElement(containerEl: HTMLElement): HTMLElement {
const tokenInfo = containerEl.createDiv({ cls: "brat-token-info" });
tokenInfo.createDiv({ cls: "brat-token-status" });
tokenInfo.createDiv({ cls: "brat-token-details" });
return tokenInfo;
}
}
+55
View File
@@ -0,0 +1,55 @@
import { type App, SuggestModal } from "obsidian";
import type { ReleaseVersion } from "src/providers/PluginProvider";
export class VersionSuggestModal extends SuggestModal<ReleaseVersion> {
selected: string;
versions: ReleaseVersion[];
onChoose: (version: string) => void;
constructor(
app: App,
repository: string,
versions: ReleaseVersion[],
selected: string,
onChoose: (version: string) => void,
) {
super(app);
this.versions = versions;
this.selected = selected;
this.onChoose = onChoose;
this.setTitle("Select a version");
this.setPlaceholder(
`Type to search for a version for ${repository}`,
);
this.setInstructions([
{ command: "↑↓", purpose: "Navigate versions" },
{ command: "↵", purpose: "Select version" },
{ command: "esc", purpose: "Dismiss modal" },
]);
}
getSuggestions(query: string): ReleaseVersion[] {
const lowerQuery = query.toLowerCase();
return this.versions.filter((version) =>
version.version.toLowerCase().contains(lowerQuery),
);
}
renderSuggestion(
version: ReleaseVersion,
el: HTMLElement,
): void {
el.createEl("div", {
text: `${version.version} ${version.prerelease ? "(Prerelease)" : ""}`,
});
}
onChooseSuggestion(version: ReleaseVersion): void {
this.onChoose(version.version);
}
onNoSuggestion(): void {
this.onChoose(this.selected ? this.selected : "");
this.close();
}
}
+8
View File
@@ -0,0 +1,8 @@
import { addIcon } from "obsidian";
export function addIcons(): void {
addIcon(
"BratIcon",
`<path fill="currentColor" stroke="currentColor" d="M 41.667969 41.667969 C 41.667969 39.367188 39.800781 37.5 37.5 37.5 C 35.199219 37.5 33.332031 39.367188 33.332031 41.667969 C 33.332031 43.96875 35.199219 45.832031 37.5 45.832031 C 39.800781 45.832031 41.667969 43.96875 41.667969 41.667969 Z M 60.417969 58.582031 C 59.460938 58.023438 58.320312 57.867188 57.25 58.148438 C 56.179688 58.429688 55.265625 59.125 54.707031 60.082031 C 53.746094 61.777344 51.949219 62.820312 50 62.820312 C 48.050781 62.820312 46.253906 61.777344 45.292969 60.082031 C 44.734375 59.125 43.820312 58.429688 42.75 58.148438 C 41.679688 57.867188 40.539062 58.023438 39.582031 58.582031 C 37.597656 59.726562 36.910156 62.257812 38.042969 64.25 C 40.5 68.53125 45.0625 71.171875 50 71.171875 C 54.9375 71.171875 59.5 68.53125 61.957031 64.25 C 63.089844 62.257812 62.402344 59.726562 60.417969 58.582031 Z M 62.5 37.5 C 60.199219 37.5 58.332031 39.367188 58.332031 41.667969 C 58.332031 43.96875 60.199219 45.832031 62.5 45.832031 C 64.800781 45.832031 66.667969 43.96875 66.667969 41.667969 C 66.667969 39.367188 64.800781 37.5 62.5 37.5 Z M 50 8.332031 C 26.988281 8.332031 8.332031 26.988281 8.332031 50 C 8.332031 73.011719 26.988281 91.667969 50 91.667969 C 73.011719 91.667969 91.667969 73.011719 91.667969 50 C 91.667969 26.988281 73.011719 8.332031 50 8.332031 Z M 50 83.332031 C 33.988281 83.402344 20.191406 72.078125 17.136719 56.363281 C 14.078125 40.644531 22.628906 24.976562 37.5 19.042969 C 37.457031 19.636719 37.457031 20.238281 37.5 20.832031 C 37.5 27.738281 43.097656 33.332031 50 33.332031 C 52.300781 33.332031 54.167969 31.46875 54.167969 29.167969 C 54.167969 26.867188 52.300781 25 50 25 C 47.699219 25 45.832031 23.132812 45.832031 20.832031 C 45.832031 18.53125 47.699219 16.667969 50 16.667969 C 68.410156 16.667969 83.332031 31.589844 83.332031 50 C 83.332031 68.410156 68.410156 83.332031 50 83.332031 Z M 50 83.332031 " />`,
);
}