Last active
August 11, 2023 03:31
-
-
Save doitian/f5c184327e364e17274bab325a2b0fe4 to your computer and use it in GitHub Desktop.
Obisidian CustomJS module to ask for user input
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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