Skip to content

Instantly share code, notes, and snippets.

@doitian
Last active August 11, 2023 03:31
Show Gist options
  • Save doitian/f5c184327e364e17274bab325a2b0fe4 to your computer and use it in GitHub Desktop.
Save doitian/f5c184327e364e17274bab325a2b0fe4 to your computer and use it in GitHub Desktop.
Obisidian CustomJS module to ask for user input
class Input {
PromptModal = class extends customJS.obsidian.Modal {
title = "Input";
value = "";
submitted = false;
placeholder = "Type text here";
constructor(opts = {}) {
super(app);
Object.assign(this, opts);
}
onOpen() {
const { TextComponent } = customJS.obsidian;
const { titleEl, contentEl, title } = this;
titleEl.setText(title);
const textInput = new TextComponent(contentEl);
textInput.inputEl.style.width = "100%";
textInput.setPlaceholder(this.placeholder);
textInput.setValue(this.value);
textInput.onChange((value) => (this.value = value));
textInput.inputEl.addEventListener("keydown", (event) =>
this.enterCallback(event)
);
}
onClose() {
if (this.resolve) {
this.resolve(this.submitted ? this.value : null);
}
}
enterCallback(event) {
if (event.key === "Enter") {
this.submitted = true;
event.preventDefault();
this.close();
}
}
};
SuggestModal = class extends customJS.obsidian.FuzzySuggestModal {
selected = null;
items = [];
constructor(opts = {}) {
super(app);
Object.assign(this, opts);
}
getItems() {
return this.items;
}
getItemText(item) {
if (typeof item === "object") {
return item.title;
}
return item;
}
onChooseItem(item) {
this.selected = item;
}
onClose() {
if (this.resolve) {
this.resolve(this.selected);
}
}
};
async prompt(opts = {}) {
const { PromptModal } = this;
return new Promise((resolve) => {
const modal = new PromptModal({
...opts,
resolve,
});
modal.open();
});
}
async suggester(items, opts = {}) {
const { SuggestModal } = this;
return new Promise((resolve) => {
const modal = new SuggestModal({
...opts,
items,
resolve,
});
modal.open();
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment