obsidian#Setting TypeScript Examples

The following examples show how to use obsidian#Setting. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: UserScriptSettingsModal.ts    From quickadd with MIT License 6 votes vote down vote up
private addFormatInput(name: string, value: string, placeholder?: string) {
        new Setting(this.contentEl).setName(name);

        const formatDisplay = this.contentEl.createEl("span");
        const input = new TextComponent(this.contentEl);
        new FormatSyntaxSuggester(this.app, input.inputEl, QuickAdd.instance);
        const displayFormatter = new FormatDisplayFormatter(this.app, QuickAdd.instance);

        input.setValue(value)
            .onChange(async value => {
                this.command.settings[name] = value
                formatDisplay.innerText = await displayFormatter.format(value);
            })
            .setPlaceholder(placeholder ?? "")

        input.inputEl.style.width = "100%";
        input.inputEl.style.marginBottom = "1em";

        (async () => formatDisplay.innerText = await displayFormatter.format(value))();
    }
Example #2
Source File: TextInputPrompt.ts    From obsidian-rss with GNU General Public License v3.0 6 votes vote down vote up
createForm(): void {
        const div = this.contentEl.createDiv();

        const text = new Setting(div).setName(this.promptText).setDesc(this.hint).addText((textComponent) => {
            textComponent
                .setValue(this.defaultValue)
                .setPlaceholder(this.placeholder)
                .onChange(() => {
                    this.removeValidationError(textComponent);
                })
                .inputEl.setAttribute("size", "50");
            this.textComponent = textComponent;
        });
        text.controlEl.addClass("rss-setting-input");

        new Setting(div).addButton((b) => {
            b
                .setButtonText(this.buttonText)
                .onClick(async () => {
                    this.resolve(this.textComponent);
                });
            return b;
        });
    }
Example #3
Source File: settings.ts    From obsidian-calendar-plugin with MIT License 6 votes vote down vote up
addDotThresholdSetting(): void {
    new Setting(this.containerEl)
      .setName("Words per dot")
      .setDesc("How many words should be represented by a single dot?")
      .addText((textfield) => {
        textfield.setPlaceholder(String(DEFAULT_WORDS_PER_DOT));
        textfield.inputEl.type = "number";
        textfield.setValue(String(this.plugin.options.wordsPerDot));
        textfield.onChange(async (value) => {
          this.plugin.writeOptions(() => ({
            wordsPerDot: value !== "" ? Number(value) : undefined,
          }));
        });
      });
  }
Example #4
Source File: settings.ts    From obsidian-todoist-plugin with MIT License 6 votes vote down vote up
debugLogging() {
    new Setting(this.containerEl)
      .setName("Debug logging")
      .setDesc("Whether debug logging should be on or off.")
      .addToggle((toggle) => {
        toggle.setValue(this.plugin.options.debugLogging);
        toggle.onChange(async (value) => {
          await this.plugin.writeOptions((old) => (old.debugLogging = value));
        });
      });
  }
Example #5
Source File: settings.ts    From obsidian-calendar-plugin with MIT License 6 votes vote down vote up
addWeeklyNoteTemplateSetting(): void {
    new Setting(this.containerEl)
      .setName("Weekly note template")
      .setDesc(
        "Choose the file you want to use as the template for your weekly notes"
      )
      .addText((textfield) => {
        textfield.setValue(this.plugin.options.weeklyNoteTemplate);
        textfield.onChange(async (value) => {
          this.plugin.writeOptions(() => ({ weeklyNoteTemplate: value }));
        });
      });
  }
Example #6
Source File: ImgurPluginSettingsTab.ts    From obsidian-imgur-plugin with MIT License 6 votes vote down vote up
private drawAnonymousClientIdSetting(containerEl: HTMLElement) {
    new Setting(containerEl)
      .setName("Client ID")
      .setTooltip(
        `Client ID is required for anonymous images upload. If you do not provide your own Client ID, the one shipped with the plugin and shared with many other users will be used. If you face issues with images upload, it's better generate your own Client ID"`
      )
      .setDesc(ImgurPluginSettingsTab.clientIdSettingDescription())
      .addText((text) =>
        text
          .setPlaceholder("Enter your client_id")
          .setValue(this.plugin.settings.clientId)
          .onChange((value) => {
            this.plugin.settings.clientId = value;
          })
      );
  }
Example #7
Source File: view.ts    From obsidian-fantasy-calendar with MIT License 6 votes vote down vote up
async display() {
        this.contentEl.empty();
        this.contentEl.createEl("h4", { text: "View Day" });
        this.dateFieldEl = this.contentEl.createDiv(
            "fantasy-calendar-date-fields"
        );
        this.buildDateFields();

        new Setting(this.contentEl)
            .setName("Set as Current Date")
            .setDesc("Also set this date to today's date.")
            .addToggle((t) =>
                t.setValue(this.setCurrent).onChange((v) => {
                    this.setCurrent = v;
                })
            );

        const buttonEl = this.contentEl.createDiv(
            "fantasy-calendar-confirm-buttons"
        );

        new ButtonComponent(buttonEl)
            .setButtonText("Switch")
            .setCta()
            .onClick(() => {
                this.confirmed = true;
                this.date.day = this.tempCurrentDays;
                this.close();
            });
        new ButtonComponent(buttonEl).setButtonText("Cancel").onClick(() => {
            this.close();
        });
    }
Example #8
Source File: settings.ts    From obsidian-calendar-plugin with MIT License 6 votes vote down vote up
addLocaleOverrideSetting(): void {
    const { moment } = window;

    const sysLocale = navigator.language?.toLowerCase();

    new Setting(this.containerEl)
      .setName("Override locale:")
      .setDesc(
        "Set this if you want to use a locale different from the default"
      )
      .addDropdown((dropdown) => {
        dropdown.addOption("system-default", `Same as system (${sysLocale})`);
        moment.locales().forEach((locale) => {
          dropdown.addOption(locale, locale);
        });
        dropdown.setValue(this.plugin.options.localeOverride);
        dropdown.onChange(async (value) => {
          this.plugin.writeOptions(() => ({
            localeOverride: value as ILocaleOverride,
          }));
        });
      });
  }
Example #9
Source File: FieldSettingsModal.ts    From obsidian_supercharged_links with MIT License 6 votes vote down vote up
constructor(app: App, plugin: SuperchargedLinks, parentSettingContainer: HTMLElement, parentSetting?: Setting, property?: Field) {
        super(app)
        this.plugin = plugin
        this.parentSetting = parentSetting
        this.initialProperty = new Field()
        this.parentSettingContainer = parentSettingContainer
        if (property) {
            this.new = false
            this.property = property
            this.initialProperty.name = property.name
            this.initialProperty.id = property.id
            Object.keys(property.values).forEach(k => {
                this.initialProperty.values[k] = property.values[k]
            })
        } else {
            let newId = 1
            this.plugin.initialProperties.forEach(prop => {
                if (parseInt(prop.id) && parseInt(prop.id) >= newId) {
                    newId = parseInt(prop.id) + 1
                }
            })
            this.property = new Field()
            this.property.id = newId.toString()
            this.initialProperty.id = newId.toString()
        }
    }
Example #10
Source File: moons.ts    From obsidian-fantasy-calendar with MIT License 6 votes vote down vote up
async display() {
        this.contentEl.empty();
        this.contentEl.createEl("h3", {
            text: this.editing ? "Edit Moon" : "New Moon"
        });

        this.infoEl = this.contentEl.createDiv("moon-info");
        this.buildInfo();

        new Setting(this.contentEl)
            .addButton((b) => {
                b.setButtonText("Save")
                    .setCta()
                    .onClick(() => {
                        if (!this.moon.name?.length) {
                            new Notice("The moon must have a name.");
                            return;
                        }
                        if (!this.moon.cycle) {
                            new Notice("The moon must have a positive cycle.");
                            return;
                        }
                        this.saved = true;
                        this.close();
                    });
            })
            .addExtraButton((b) => {
                b.setIcon("cross")
                    .setTooltip("Cancel")
                    .onClick(() => this.close());
            });
    }
Example #11
Source File: settings.ts    From obsidian-emoji-shortcodes with MIT License 6 votes vote down vote up
display(): void {
		let { containerEl } = this;

		containerEl.empty();

		containerEl.createEl('h2', { text: 'Emoji Shortcodes Plugin' });

		new Setting(containerEl)
			.setName('Immediate Emoji Replace')
			.setDesc('If this is turned on, Emoji shortcodes will be immediately replaced after typing. Otherwise they are still stored as a shortcode and you only see the Emoji in Preview Mode.')
			.addToggle(cb => {
				cb.setValue(this.plugin.settings.immediateReplace)
					.onChange(async value => {
						this.plugin.settings.immediateReplace = value;
						await this.plugin.saveSettings();
					})
			});

		new Setting(containerEl)
			.setName('Emoji Suggester')
			.setDesc('If this is turned on, a Suggester will appear everytime you type : followed by a letter. This will help you insert Emojis. (Doesn\'t work on mobile)')
			.addToggle(cb => {
				cb.setValue(this.plugin.settings.suggester)
					.onChange(async value => {
						this.plugin.settings.suggester = value;
						await this.plugin.saveSettings();
					})
			});

		new Setting(containerEl)
			.setName('Donate')
			.setDesc('If you like this Plugin, consider donating to support continued development:')
			.addButton((bt) => {
				bt.buttonEl.outerHTML = `<a href="https://www.buymeacoffee.com/phibr0"><img src="https://img.buymeacoffee.com/button-api/?text=Buy me a coffee&emoji=&slug=phibr0&button_colour=5F7FFF&font_colour=ffffff&font_family=Inter&outline_colour=000000&coffee_colour=FFDD00"></a>`;
			});
	}
Example #12
Source File: era.ts    From obsidian-fantasy-calendar with MIT License 6 votes vote down vote up
buildEventSettings(eventEl: HTMLDivElement) {
        eventEl.empty();
        const advanced = eventEl.createDiv("era-event");
        new Setting(advanced)
            .setName("Show as Event")
            .setDesc(
                createFragment((e) => {
                    e.createSpan({
                        text: "The era will appear on its starting date as an event."
                    });
                })
            )
            .addToggle((t) =>
                t.setValue(this.era.event).onChange((v) => {
                    this.era.event = v;
                    if (!v) {
                        this.era.eventCategory = null;
                        this.era.eventDescription = null;
                    }
                    this.buildEventSettings(eventEl);
                })
            );
        if (this.era.event) {
            new Setting(advanced)
                .setName("Event Category")
                .addDropdown((d) => d);
            new Setting(advanced)
                .setName("Event Description")
                .addTextArea((t) => t);
        }
    }
Example #13
Source File: settings.ts    From obsidian-tracker with MIT License 6 votes vote down vote up
display(): void {
        let { containerEl } = this;

        containerEl.empty();

        new Setting(containerEl)
            .setName("Default folder location")
            .setDesc(
                "Files in this folder will be parsed and used as input data of the tracker plugin.\nYou can also override it using 'folder' argument in the tracker codeblock."
            )
            .addText((text) =>
                text
                    .setPlaceholder("Folder Path")
                    .setValue(this.plugin.settings.folder)
                    .onChange(async (value) => {
                        this.plugin.settings.folder = value;
                        await this.plugin.saveSettings();
                    })
            );

        new Setting(containerEl)
            .setName("Default date format")
            .setDesc(
                "This format is used to parse the date in your diary title.\nYou can also override it using 'dateFormat' argument in the tracker codeblock."
            )
            .addText((text) =>
                text
                    .setPlaceholder("YYYY-MM-DD")
                    .setValue(this.plugin.settings.dateFormat)
                    .onChange(async (value) => {
                        this.plugin.settings.dateFormat = value;
                        await this.plugin.saveSettings();
                    })
            );
    }
Example #14
Source File: settingsTab.ts    From obsidian-map-view with GNU General Public License v3.0 6 votes vote down vote up
refreshOpenInSettings(containerEl: HTMLElement) {
        containerEl.innerHTML = '';
        for (const setting of this.plugin.settings.openIn) {
            const controls = new Setting(containerEl)
                .addText((component) => {
                    component
                        .setPlaceholder('Name')
                        .setValue(setting.name)
                        .onChange(async (value: string) => {
                            setting.name = value;
                            await this.plugin.saveSettings();
                        });
                })
                .addText((component) => {
                    component
                        .setPlaceholder('URL template')
                        .setValue(setting.urlPattern)
                        .onChange(async (value: string) => {
                            setting.urlPattern = value;
                            await this.plugin.saveSettings();
                        });
                })
                .addButton((component) =>
                    component.setButtonText('Delete').onClick(async () => {
                        this.plugin.settings.openIn.remove(setting);
                        await this.plugin.saveSettings();
                        this.refreshOpenInSettings(containerEl);
                    })
                );
            controls.settingEl.style.padding = '5px';
            controls.settingEl.style.borderTop = 'none';
        }
    }
Example #15
Source File: settings.ts    From remotely-save with Apache License 2.0 6 votes vote down vote up
constructor(
    app: App,
    plugin: RemotelySavePlugin,
    authDiv: HTMLDivElement,
    revokeAuthDiv: HTMLDivElement,
    revokeAuthSetting: Setting
  ) {
    super(app);
    this.plugin = plugin;
    this.authDiv = authDiv;
    this.revokeAuthDiv = revokeAuthDiv;
    this.revokeAuthSetting = revokeAuthSetting;
  }
Example #16
Source File: switcherPlusSettingTab.ts    From obsidian-switcher-plus with GNU General Public License v3.0 6 votes vote down vote up
private setExcludeFolders(
    containerEl: HTMLElement,
    config: SwitcherPlusSettings,
  ): void {
    const settingName = 'Exclude folders';
    new Setting(containerEl)
      .setName(settingName)
      .setDesc(
        `When in Headings list mode, folder path that match any regex listed here will not be searched for suggestions. Path should start from the Vault Root. Add one path per line.`,
      )
      .addTextArea((textArea) => {
        textArea.setValue(config.excludeFolders.join('\n'));
        textArea.inputEl.addEventListener('blur', () => {
          const excludes = textArea
            .getValue()
            .split('\n')
            .filter((v) => v.length > 0);

          if (this.validateExcludeFolderList(settingName, excludes)) {
            config.excludeFolders = excludes;
            config.save();
          }
        });
      });
  }
Example #17
Source File: quickAddSettingsTab.ts    From quickadd with MIT License 6 votes vote down vote up
private addChoicesSetting(): void {
        const setting = new Setting(this.containerEl);
        setting.infoEl.remove();
        setting.settingEl.style.display = "block";

        this.choiceView = new ChoiceView({
            target: setting.settingEl,
            props: {
                app: this.app,
                plugin: this.plugin,
                choices: this.plugin.settings.choices,
                saveChoices: async (choices: IChoice[]) => {
                    this.plugin.settings.choices = choices;
                    await this.plugin.saveSettings();
                },
                macros: this.plugin.settings.macros,
                saveMacros: async (macros: IMacro[]) => {
                    this.plugin.settings.macros = macros;
                    await this.plugin.saveSettings();
                }
            }
        });
    }
Example #18
Source File: settings.ts    From remotely-save with Apache License 2.0 6 votes vote down vote up
async onOpen() {
    let { contentEl } = this;

    const t = (x: TransItemType, vars?: any) => {
      return this.plugin.i18n.t(x, vars);
    };

    t("modal_syncconfig_attn")
      .split("\n")
      .forEach((val) => {
        contentEl.createEl("p", {
          text: val,
        });
      });

    new Setting(contentEl)
      .addButton((button) => {
        button.setButtonText(t("modal_syncconfig_secondconfirm"));
        button.onClick(async () => {
          this.plugin.settings.syncConfigDir = true;
          await this.plugin.saveSettings();
          this.saveDropdownFunc();
          new Notice(t("modal_syncconfig_notice"));
          this.close();
        });
      })
      .addButton((button) => {
        button.setButtonText(t("goback"));
        button.onClick(() => {
          this.close();
        });
      });
  }
Example #19
Source File: settings.ts    From folder-note-core with MIT License 6 votes vote down vote up
setLogLevel = (containerEl: HTMLElement) => {
    new Setting(containerEl)
      .setName("Log Level of folder-note-core")
      .setDesc("Change this options if debug is required")
      .addDropdown((dp) =>
        dp
          .then((dp) =>
            Object.entries(log.levels).forEach(([key, val]) =>
              dp.addOption(val.toString(), key),
            ),
          )
          .setValue(log.getLevel().toString())
          .onChange(async (val) => {
            const level = +val as LogLevelNumbers;
            log.setLevel(level);
            this.plugin.settings.logLevel = level;
            await this.plugin.saveSettings();
          }),
      );
  };
Example #20
Source File: index.ts    From obsidian-hypothesis-plugin with MIT License 6 votes vote down vote up
private async manageGroups(): Promise<void> {
    const descFragment = document.createRange().createContextualFragment(`Add/remove group(s) to be synced.<br/>
      ${(get(settingsStore).groups).length} group(s) synced from Hypothesis<br/>`);

    new Setting(this.containerEl)
      .setName('Groups')
      .setDesc(descFragment)
      .addExtraButton((button) => {
        return button
          .setIcon('switch')
          .setTooltip('Reset group selections')
          .setDisabled(!get(settingsStore).isConnected)
          .onClick(async () => {
            await settingsStore.actions.resetGroups();
            await this.syncGroup.startSync();
            this.display(); // rerender
          });
      })
      .addButton((button) => {
        return button
          .setButtonText('Manage')
          .setCta()
          .setDisabled(!get(settingsStore).isConnected)
          .onClick(async () => {
            const manageGroupsModal = new ManageGroupsModal(this.app);
            await manageGroupsModal.waitForClose;
            this.display(); // rerender
          });
      });
  }
Example #21
Source File: settings.ts    From Obsidian_to_Anki with GNU General Public License v3.0 6 votes vote down vote up
setup_custom_regexp(note_type: string, row_cells: HTMLCollection) {
		const plugin = (this as any).plugin
		let regexp_section = plugin.settings["CUSTOM_REGEXPS"]
		let custom_regexp = new Setting(row_cells[1] as HTMLElement)
			.addText(
					text => text.setValue(
					regexp_section.hasOwnProperty(note_type) ? regexp_section[note_type] : ""
					)
					.onChange((value) => {
						plugin.settings["CUSTOM_REGEXPS"][note_type] = value
						plugin.saveAllData()
					})
			)
		custom_regexp.settingEl = row_cells[1] as HTMLElement
		custom_regexp.infoEl.remove()
		custom_regexp.controlEl.className += " anki-center"
	}
Example #22
Source File: index.ts    From obsidian-hypothesis-plugin with MIT License 6 votes vote down vote up
private dateFormat(): void {
    const descFragment = document
      .createRange()
      .createContextualFragment(datetimeInstructions);

    new Setting(this.containerEl)
      .setName('Date & time format')
      .setDesc(descFragment)
      .addText((text) => {
        text
          .setPlaceholder('YYYY-MM-DD HH:mm:ss')
          .setValue(get(settingsStore).dateTimeFormat)
          .onChange(async (value) => {
            await settingsStore.actions.setDateTimeFormat(value);
          });
      });
  }
Example #23
Source File: settings.ts    From Obsidian_to_Anki with GNU General Public License v3.0 6 votes vote down vote up
setup_folder_deck(folder: TFolder, row_cells: HTMLCollection) {
		const plugin = (this as any).plugin
		let folder_decks = plugin.settings.FOLDER_DECKS
		if (!(folder_decks.hasOwnProperty(folder.path))) {
			folder_decks[folder.path] = ""
		}
		let folder_deck = new Setting(row_cells[1] as HTMLElement)
			.addText(
				text => text.setValue(folder_decks[folder.path])
				.onChange((value) => {
					plugin.settings.FOLDER_DECKS[folder.path] = value
					plugin.saveAllData()
				})
			)
		folder_deck.settingEl = row_cells[1] as HTMLElement
		folder_deck.infoEl.remove()
		folder_deck.controlEl.className += " anki-center"
	}
Example #24
Source File: index.ts    From obsidian-hypothesis-plugin with MIT License 6 votes vote down vote up
private resetSyncHistory(): void {
    new Setting(this.containerEl)
      .setName('Reset sync')
      .setDesc('Wipe sync history to allow for resync')
      .addButton((button) => {
        return button
          .setButtonText('Reset')
          .setDisabled(!get(settingsStore).isConnected)
          .setWarning()
          .onClick(async () => {
            await settingsStore.actions.resetSyncHistory();
            this.display(); // rerender
          });
      });
  }
Example #25
Source File: Settings.ts    From Templater with GNU Affero General Public License v3.0 6 votes vote down vote up
add_template_folder_setting(): void {
        new Setting(this.containerEl)
            .setName("Template folder location")
            .setDesc("Files in this folder will be available as templates.")
            .addSearch((cb) => {
                new FolderSuggest(this.app, cb.inputEl);
                cb.setPlaceholder("Example: folder1/folder2")
                    .setValue(this.plugin.settings.templates_folder)
                    .onChange((new_folder) => {
                        this.plugin.settings.templates_folder = new_folder;
                        this.plugin.save_settings();
                    });
                // @ts-ignore
                cb.containerEl.addClass("templater_search");
            });
    }
Example #26
Source File: index.ts    From obsidian-hypothesis-plugin with MIT License 6 votes vote down vote up
private folderPath(): void {
    new Setting(this.containerEl)
    .setName('Use domain folders')
    .setDesc('Group generated files into folders based on the domain of the annotated URL')
    .addToggle((toggle) =>
      toggle
        .setValue(get(settingsStore).useDomainFolders)
        .onChange(async (value) => {
          await settingsStore.actions.setUseDomainFolder(value);
        })
    );
  }
Example #27
Source File: settings.ts    From alx-folder-note with MIT License 6 votes vote down vote up
getInitGuide(
    desc: string,
    targetPluginID: string,
    container: HTMLElement,
  ): Setting {
    return new Setting(container)
      .setDesc(
        desc +
          "use the buttons to install & enable it then reload alx-folder-note to take effects",
      )
      .addButton((btn) =>
        btn
          .setIcon("down-arrow-with-tail")
          .setTooltip("Go to Plugin Page")
          .onClick(() =>
            window.open(`obsidian://show-plugin?id=${targetPluginID}`),
          ),
      )
      .addButton((btn) =>
        btn
          .setIcon("reset")
          .setTooltip("Reload alx-folder-note")
          .onClick(async () => {
            await this.app.plugins.disablePlugin(this.plugin.manifest.id);
            await this.app.plugins.enablePlugin(this.plugin.manifest.id);
            this.app.setting.openTabById(this.plugin.manifest.id);
          }),
      );
  }
Example #28
Source File: index.ts    From obsidian-hypothesis-plugin with MIT License 6 votes vote down vote up
private disconnect(): void {
    const syncMessage = get(settingsStore).lastSyncDate
      ? `Last sync ${moment(get(settingsStore).lastSyncDate).fromNow()}`
      : 'Sync has never run';

    const descFragment = document.createRange().createContextualFragment(`
      ${get(settingsStore).history.totalArticles} article(s) & ${get(settingsStore).history.totalHighlights} highlight(s) synced<br/>
      ${syncMessage}
    `);

    new Setting(this.containerEl)
      .setName(`Connected to Hypothes.is as ${(get(settingsStore).user).match(/([^:]+)@/)[1]}`)
      .setDesc(descFragment)
      .addButton((button) => {
        return button
          .setButtonText('Disconnect')
          .setCta()
          .onClick(async () => {
            button
              .removeCta()
              .setButtonText('Removing API token...')
              .setDisabled(true);

            await settingsStore.actions.disconnect();

            this.display(); // rerender
          });
      });
  }
Example #29
Source File: settings.ts    From alx-folder-note with MIT License 6 votes vote down vote up
setMigrate() {
    new Setting(this.containerEl)
      .setName("Migrate settings to Folder Note Core")
      .setDesc(
        "Some settings has not been migrated to Folder Note Core, " +
          "click Migrate to migrate old config " +
          "or Cancel to use config in Folder Note Core in favor of old config",
      )
      .addButton((cb) =>
        cb.setButtonText("Migrate").onClick(async () => {
          const toImport = old.reduce(
            (obj, k) => ((obj[k] = this.plugin.settings[k] ?? undefined), obj),
            {} as any,
          );
          this.plugin.CoreApi.importSettings(toImport);
          old.forEach((k) => ((this.plugin.settings as any)[k] = null));
          await this.plugin.saveSettings();
          this.display();
        }),
      )
      .addButton((cb) =>
        cb.setButtonText("Cancel").onClick(async () => {
          old.forEach((k) => ((this.plugin.settings as any)[k] = null));
          await this.plugin.saveSettings();
          this.display();
        }),
      );
  }