Create an app using Tauri and Vanilla JavaScript, with a clean API for creating,…
- User
Create an app using Tauri and Vanilla JavaScript, with a clean API for creating, modifying, and deleting files. The frontend should be minimalistic, just a blank page that allows you to create a new note (.txt file) by clicking anywhere on the page. Upon the first launch, the app will prompt you to select a folder to store and access its files, similar to how Obsidian handles vaults. Consider we use npm instead of cargo, so avoid rust code.
Also, consider we are using tauri v1.
- Assistant
Sure! Let's create a minimal Tauri application using Vanilla JavaScript that allows users to create, modify, and delete
.txtfiles in a selected directory. We'll set up the project using npm, avoiding any Rust code manually (since Tauri handles Rust code under the hood). We'll use Tauri's JavaScript APIs for filesystem access.Here's a step-by-step guide to get you started.
Prerequisites
Step 1: Initialize the Project
-
Create a new directory for your project:
mkdir tauri-notes-app cd tauri-notes-app -
Initialize a new npm project:
npm init -y -
Install Tauri dependencies:
npm install @tauri-apps/cli @tauri-apps/api -
Initialize a Tauri project:
Since we're avoiding Rust code and using npm, we'll use Tauri's JavaScript templates.
npx tauri initDuring the initialization:
- Package Name: Press Enter to accept the default.
- Frontend Type: Choose
"Vanilla". - npm manager: Press Enter to accept
npm. - Windows MSI installer: (Windows) Choose
Nounless you need it. - App Name: Provide a name or accept the default.
- Window title: Provide a title or accept the default.
Tauri will generate the necessary files for your project.
Step 2: Set Up the Frontend
-
Project Structure:
Your project should now have a
src-tauridirectory (for backend configuration) and asrcdirectory (for the frontend). -
Clean the
index.html:Open
src/index.htmland replace its contents with:<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline';"/> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Tauri Notes App</title> </head> <body> <script type="module" src="main.js"></script> </body> </html> -
Create
main.js:In the
srcdirectory, create a file calledmain.jsand add the following code:import { open } from '@tauri-apps/api/dialog'; import { appDir, join } from '@tauri-apps/api/path'; import { writeTextFile, readTextFile, BaseDirectory, createDir } from '@tauri-apps/api/fs'; // Variable to store the selected directory let notesDirectory = ''; // Function to prompt user to select a folder async function selectNotesDirectory() { notesDirectory = await open({ directory: true, multiple: false, defaultPath: await appDir(), }); if (notesDirectory) { // Save this path for future use, e.g., using localStorage or Tauri's storage APIs localStorage.setItem('notesDirectory', notesDirectory); } else { // Handle the case where no directory was selected alert('You must select a directory to store your notes.'); } } // Check if we have a saved directory const savedDirectory = localStorage.getItem('notesDirectory'); if (!savedDirectory) { // First launch, prompt user to select a directory selectNotesDirectory(); } else { notesDirectory = savedDirectory; } // Add event listener to the body to create a new note on click document.body.addEventListener('click', async () => { if (!notesDirectory) { await selectNotesDirectory(); } const noteName = prompt('Enter note name:', 'Untitled Note'); if (noteName) { const notePath = await join(notesDirectory, `${noteName}.txt`); await writeTextFile(notePath, '', { dir: BaseDirectory.None }); alert(`Created note: ${notePath}`); } });This script does the following:
-
On first launch, prompts the user to select a directory to store notes.
-
Saves the selected directory for future use.
-
Adds a click event listener to the body that:
- Prompts for a note name.
- Creates a
.txtfile with that name in the selected directory.
-
Step 3: Configure Tauri Allowlist
For security, Tauri requires you to specify which APIs and features your app will use.
-
Open
src-tauri/tauri.conf.json:Find the
taurisection and update theallowlistto include the necessary APIs:{ "tauri": { "allowlist": { "all": false, "dialog": { "open": true }, "fs": { "all": false, "readTextFile": true, "writeFile": true, "createDir": true }, "path": { "all": true } } } }This configuration allows:
- Opening file dialogs.
- Reading and writing text files.
- Creating directories.
- Using path APIs.
-
Security Settings:
Ensure
secureis set totrue(which is the default). This enforces Content Security Policies.{ "tauri": { "security": { "csp": null } } }
Step 4: Enhance Functionality (Modify and Delete Notes)
To modify and delete notes, we need to list existing notes and provide options to interact with them.
-
Update
index.htmlto include a list:<body> <ul id="notes-list"></ul> <script type="module" src="main.js"></script> </body> -
Update
main.js:First, import the necessary functions:
import { readDir, removeFile } from '@tauri-apps/api/fs';Then, add functions to list notes, open notes, edit notes, and delete notes.
// Function to list notes async function listNotes() { if (!notesDirectory) return; const entries = await readDir(notesDirectory, { recursive: false }); const notesList = document.getElementById('notes-list'); notesList.innerHTML = ''; entries.forEach(entry => { if (entry.children === undefined) { const listItem = document.createElement('li'); listItem.textContent = entry.name; // Open note on click listItem.addEventListener('click', () => openNote(entry.path)); // Right-click to delete listItem.addEventListener('contextmenu', (e) => { e.preventDefault(); if (confirm(`Delete ${entry.name}?`)) { deleteNote(entry.path); } }); notesList.appendChild(listItem); } }); } // Function to open a note async function openNote(notePath) { const content = await readTextFile(notePath, { dir: BaseDirectory.None }); const newContent = prompt('Edit note:', content); if (newContent !== null) { await writeTextFile(notePath, newContent, { dir: BaseDirectory.None }); } } // Function to delete a note async function deleteNote(notePath) { await removeFile(notePath, { dir: BaseDirectory.None }); listNotes(); } // Update the body click event listener document.body.addEventListener('click', async (e) => { if (e.target.tagName.toLowerCase() === 'body') { // Only trigger when clicking on the body, not on list items if (!notesDirectory) { await selectNotesDirectory(); } const noteName = prompt('Enter note name:', 'Untitled Note'); if (noteName) { const notePath = await join(notesDirectory, `${noteName}.txt`); await writeTextFile(notePath, '', { dir: BaseDirectory.None }); alert(`Created note: ${notePath}`); listNotes(); } } }); // Initial listing of notes if (notesDirectory) { listNotes(); }What this code does:
- listNotes(): Reads the selected directory and lists all
.txtfiles. - openNote(): Opens a prompt with the note's content for editing.
- deleteNote(): Deletes the selected note.
- Updates event listeners to handle these interactions.
- listNotes(): Reads the selected directory and lists all
-
Style the List (Optional):
You can add some basic styles to make the list look better. In
index.html, add:<style> ul { list-style-type: none; padding: 0; } li { padding: 8px; cursor: pointer; } li:hover { background-color: #f0f0f0; } </style>
Step 5: Run the Application
To run your Tauri app:
npx tauri devThis command starts the app in development mode.
Step 6: Build the Application
When you're ready to build the application for distribution:
npx tauri buildThis will create an executable in the
src-tauri/target/releasedirectory.
Additional Notes
-
Error Handling: The above code is minimal and doesn't include comprehensive error handling. Consider adding try-catch blocks and handling exceptions gracefully.
-
Directory Persistence: We used
localStoragefor simplicity. For a more robust solution, consider using Tauri'sstoreAPI or saving the config in a file. -
Security: Since the app interacts with the filesystem, ensure you trust the directories and files you're interacting with. Tauri's security model is robust, but always be cautious with file operations.
-
Further Enhancements:
- Implement a rich text editor instead of
prompt()for editing notes. - Add the ability to rename notes.
- Implement search functionality.
- Sync notes using a cloud service or local network.
- Implement a rich text editor instead of
Conclusion
You've now created a minimalistic Tauri application using Vanilla JavaScript that allows users to create, view, edit, and delete
.txtnotes in a selected directory. This application prompts the user to select a folder upon the first launch, similar to how Obsidian handles vaults.Feel free to customize and enhance the app to suit your needs!
If you have any questions or need further assistance, don't hesitate to ask.
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.