Open obsidian-helper in Script Kit

// Name: Obsidian Helper
// Author: Ambushfall
// Description: Usable script to easily add small additions to obsidian and allows preview and edit of markdown files directly.
// This is just for speed of use.
import '@johnlindquist/kit'
import { Choice } from '@johnlindquist/kit'
import { readFileSync } from 'fs'
import _ from 'lodash'
let { obsidiandir, write } = await db('obsidiandir')
let route =
obsidiandir.length > 0
? await arg(
{
placeholder: 'Select Obsidian vault',
shortcuts: [
{
name: 'Cancel',
key: 'escape',
bar: 'right',
onPress: () => mainScript(),
visible: true
}
],
onNoChoices: async input => {
setPanel(
md(
`# Vault location not found <code>${input}</code>\n Type <kbd>enter</kbd> to create a new vault at this location: <code>${input}</code>`
)
)
},
onChoiceFocus: async (_, state) => {
const Files: string[] = await readdir(state.focused?.value)
const FilteredDir: string[] = Files.filter((file: string) =>
file.toLowerCase().includes('.md')
)
let html = `<h1>Note List:</h1><ul style="margin:20px; padding:10px;">\n`
FilteredDir.forEach(e => {
html += `<li>${e}</li>`
})
html += `</ul>`
setPreview(html)
}
},
obsidiandir.map((e: string) => {
return {
type: 'text',
name: e.split('\\').at(-1),
value: e
}
})
)
: await path({
hint: 'Paste path to your obsidian vault!'
})
if (!obsidiandir.find((e: string) => e == route) || obsidiandir.length == 0) {
obsidiandir.push(route)
await write()
}
if (isDir(route)) {
const Files: string[] = await readdir(route)
const FilteredDir: string[] = Files.filter((file: string) =>
file.toLowerCase().includes('.md')
)
let { filename } = await arg(
{
placeholder: 'select File'
},
(): Choice[] => {
return FilteredDir.map((file: string) => {
const str = readFileSync(path.join(route, file), 'utf-8')
// log(str)
return {
type: 'text',
name: file.replaceAll('.md', ''),
value: {
filename: file
},
preview: () => md(str)
}
})
}
)
/**
* This is taken directly from the examples for editor functionality
*
*/
let changed = false
let filePath = path.join(route, filename)
let autoSave = _.debounce(async input => {
await writeFile(filePath, input.trim())
}, 3000)
let value = await ensureReadFile(filePath)
let cmd = isWin ? 'ctrl' : 'cmd'
let content = await editor({
value,
scrollTo: 'bottom',
shortcuts: [
{
name: 'Save',
key: `${cmd}+s`,
onPress: input => {
submit(input)
},
bar: 'right'
},
{
name: 'Open',
key: `${cmd}+o`,
onPress: async () => {
open(filePath)
},
bar: 'right'
}
],
onEscape: async input => {
submit(input)
},
onAbandon: async input => {
submit(input)
},
onInput: async input => {
changed = true
autoSave(input)
}
})
hide()
let trimmed = content.trim()
if (changed) {
await writeFile(filePath, trimmed)
}
}
process.exit(0)