// Name: Img to Base64 Markdown
// Description: Convert image to Base64 Markdown and save to journal.
// Author: ffael
import '@johnlindquist/kit'
// Get selected file path or prompt user to select an image file
let imagePath: string = await getSelectedFile()
if (!imagePath) { imagePath = await selectFile(`Choose an image:`)
}
if (!imagePath) {
// Exit if no image path is selected by the user
exit()
}
const extension: string = path.extname(imagePath)
const allowImageExtensions: string[] = ['.png', '.jpg', '.jpeg', '.gif']
// Validate if the selected file is a supported image type
if (!allowImageExtensions.includes(extension)) {
await div(md(`Selected file is not a supported image type.`))
exit()
}
// Read the image file as a Buffer
let imageBuffer: Buffer
try {
imageBuffer = await readFile(imagePath)
} catch (error) {
// Handle file reading errors
console.error(`Error reading file: ${imagePath}`, error)
await div(md(`Failed to read image file.`))
exit()
throw error // Re-throw to stop script execution
}
// Convert the image Buffer to a Base64 string
const base64Image: string = `data:image/${extension.slice(1)};base64,${imageBuffer.toString('base64')}`
// Prompt user for alt text for the image
const altText: string = await arg('Enter alt text for the image:')
const markdown: string = `![${altText}](${base64Image})`
// Get or prompt user to set the journal directory from environment variable
const journalDir: string = await env('IMAGE_JOURNAL_DIR', async () => {
return await path({
hint: 'Select a directory to store image journal entries',
})
})
if (!journalDir) {
// Exit if no journal directory is selected by the user
exit()
}
const journalPath = createPathResolver(journalDir)
await ensureDir(journalPath()) // Ensure the journal directory exists
const dashedDate: string = formatDate(new Date(), 'yyyy-MM-dd')
const journalFilePath: string = journalPath(`${dashedDate}.md`)
/**
* Adds a new entry to the journal file with a timestamp.
* @param filePath - Path to the journal file.
* @param content - Markdown content to add to the journal entry.
*/
const addEntry = async (filePath: string, content: string): Promise<void> => {
const timestamp: string = formatDate(new Date(), 'hh:mmaa')
const entry: string = `\n## ${timestamp}\n${content}\n`
try {
await appendFile(filePath, entry)
} catch (error) {
// Handle file appending errors
console.error(`Error appending to file: ${filePath}`, error)
await div(md(`Failed to add entry to journal.`))
exit()
throw error // Re-throw to stop script execution
}
}
await addEntry(journalFilePath, markdown)
// Notify user and copy markdown to clipboard
await div(md(`Added image to journal entry: [${dashedDate}](${journalFilePath})`))
await clipboard.writeText(markdown)