Creating a Tauri application with Vanilla JavaScript to manage text files involves several steps. Below is a comprehensive guide to help you build a minimalistic note-taking app that allows users to create, modify, and delete .txt files within a selected folder (similar to Obsidian's vaults). We'll leverage Tauri v1's built-in APIs, avoiding the need for custom Rust code, and use npm for package management.
Table of Contents
- Prerequisites
- Project Setup
- Tauri Configuration (
tauri.conf.json)
- Frontend Implementation
- Running the Application
- Directory Structure
- Complete Code Example
- Additional Notes
Prerequisites
Before starting, ensure you have the following installed on your system:
Project Setup
-
Initialize the Project Directory
Open your terminal and create a new directory for your project:
mkdir tauri-note-app
cd tauri-note-app
-
Initialize Package.json
Initialize a new package.json file using npm:
npm init -y
-
Install Tauri CLI
Install Tauri and its dependencies:
npm install @tauri-apps/cli @tauri-apps/api
-
Initialize Tauri
Use the Tauri CLI to set up the project:
npx tauri init
- Integration with Frontend: When prompted, you can specify the frontend directory. For simplicity, we'll use the root directory for frontend files.
Tauri Configuration (tauri.conf.json)
The tauri.conf.json file configures various aspects of your Tauri application. Below is a minimal configuration tailored to our requirements:
{
"package": {
"productName": "Tauri Note App",
"version": "0.1.0"
},
"tauri": {
"windows": [
{
"title": "Tauri Note App",
"width": 800,
"height": 600
}
],
"allowlist": {
"fs": {
"all": true
},
"path": {
"all": true
},
"dialog": {
"all": true
}
},
"security": {
"csp": "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline';"
}
}
}
Key Points:
- Window Configuration: Sets the title and size of the application window.
- Allowlist: Enables access to the filesystem (
fs), path operations (path), and dialog interactions (dialog).
- Security: Defines a Content Security Policy to enhance security.
Frontend Implementation
We'll create a minimalistic frontend with a blank page that listens for click events to create new .txt notes.
HTML (index.html)
Create an index.html file in the root directory with the following content:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Tauri Note App</title>
<style>
body, html {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
cursor: pointer;
background-color: #f5f5f5;
font-family: Arial, sans-serif;
}
#overlay {
position: absolute;
top: 20px;
left: 20px;
background: rgba(255, 255, 255, 0.9);
padding: 10px 20px;
border-radius: 5px;
display: none;
z-index: 1000;
}
#overlay input {
width: 200px;
padding: 5px;
}
#overlay button {
padding: 5px 10px;
}
</style>
</head>
<body>
<div id="overlay">
<input type="text" id="noteName" placeholder="Note name" />
<button id="saveNote">Save</button>
</div>
<script src="index.js"></script>
</body>
</html>
Key Elements:
- Overlay Div: A hidden overlay that appears when creating a new note, allowing the user to input the note's name.
- Styles: Basic styles to ensure the app appears clean and minimalistic.
JavaScript (index.js)
Create an index.js file in the root directory with the following content:
// Import Tauri APIs
import { appDir, path as pathModule } from '@tauri-apps/api';
import { open, save } from '@tauri-apps/api/dialog';
import { readDir, createDir, writeFile, exists, removeFile } from '@tauri-apps/api/fs';
import { join } from '@tauri-apps/api/path';
import { invoke } from '@tauri-apps/api/tauri';
// State variables
let vaultPath = null;
// Elements
const overlay = document.getElementById('overlay');
const noteNameInput = document.getElementById('noteName');
const saveNoteButton = document.getElementById('saveNote');
// Initialize the app
window.addEventListener('DOMContentLoaded', async () => {
vaultPath = localStorage.getItem('vaultPath');
if (!vaultPath) {
await selectVault();
}
});
// Select Vault Directory
async function selectVault() {
const selected = await open({
directory: true,
multiple: false,
title: "Select a folder to use as your vault",
});
if (selected && selected.length > 0) {
vaultPath = selected[0];
localStorage.setItem('vaultPath', vaultPath);
} else {
alert("You must select a folder to proceed.");
// Optionally, you can close the app or prompt again
}
}
// Handle click to create a new note
document.body.addEventListener('click', () => {
if (vaultPath) {
overlay.style.display = 'block';
noteNameInput.value = '';
noteNameInput.focus();
}
});
// Handle save note
saveNoteButton.addEventListener('click', async () => {
const noteName = noteNameInput.value.trim();
if (noteName) {
const fileName = noteName.endsWith('.txt') ? noteName : `${noteName}.txt`;
const filePath = await join(vaultPath, fileName);
const fileExists = await exists(filePath);
if (fileExists) {
alert("A note with this name already exists.");
} else {
await writeFile({ path: filePath, contents: "" });
alert(`Note "${fileName}" created.`);
}
overlay.style.display = 'none';
} else {
alert("Please enter a note name.");
}
});
// Optional: Handle outside click to hide overlay
document.body.addEventListener('click', (e) => {
if (e.target === document.body) {
overlay.style.display = 'none';
}
});
Explanation:
- Import Tauri APIs: Utilizes Tauri's
fs, path, and dialog APIs to interact with the filesystem and dialogs.
- State Management:
vaultPath stores the selected folder path.
- The path is persisted using
localStorage.
- Initialization:
- On DOM content loaded, checks if a vault path is already stored.
- If not, prompts the user to select a directory.
- Creating a New Note:
- When the user clicks anywhere on the page, displays an overlay to input the note's name.
- On saving, creates a new
.txt file in the selected directory.
- Alerts the user upon successful creation or if the file already exists.
- Overlay Management:
- Hides the overlay when clicking outside of it.
Note: Since we're avoiding custom Rust code, this implementation relies entirely on Tauri's built-in JavaScript APIs.
Running the Application
-
Build the Frontend
Since we're using Vanilla JavaScript without frameworks, no build step is required. Ensure that your index.html and index.js are in place.
-
Run Tauri in Development Mode
Use the following command to run the application in development mode:
npx tauri dev
This command will build the Rust backend and serve the frontend, launching the application window.
Directory Structure
Your project directory should look like this:
tauri-note-app/
├── src-tauri/
│ ├── build.rs
│ ├── Cargo.toml
│ └── tauri.conf.json
├── index.html
├── index.js
├── package.json
└── package-lock.json
src-tauri/: Contains Tauri-specific configuration and backend files.
index.html & index.js: Frontend files.
package.json: Project dependencies and scripts.
Complete Code Example
package.json
Ensure your package.json includes the necessary scripts and dependencies:
{
"name": "tauri-note-app",
"version": "0.1.0",
"description": "A minimalistic note-taking app using Tauri and Vanilla JavaScript.",
"main": "index.html",
"scripts": {
"tauri-dev": "tauri dev",
"tauri-build": "tauri build"
},
"dependencies": {
"@tauri-apps/api": "^1.0.0",
"@tauri-apps/cli": "^1.0.0"
},
"devDependencies": {}
}
tauri.conf.json
As previously provided, ensure your tauri.conf.json is properly configured.
index.html
As provided earlier.
index.js
As provided earlier.
Additional Notes
-
File Operations: The current implementation allows creating new .txt files. To enable modifying and deleting files, you can expand the frontend with a simple UI listing existing notes and providing edit/delete buttons. Use Tauri's readDir, readTextFile, writeFile, and removeFile APIs for these operations.
-
Persisting Vault Path: The vault path is stored in localStorage. For more secure or persistent storage, consider using Tauri's appData directories or a configuration file.
-
Error Handling: For production-ready applications, enhance error handling to manage exceptions and provide user feedback.
-
Styling: Currently, the app has minimal styling. You can enhance the UI using CSS or integrate a lightweight CSS framework if desired.
-
Packaging: When ready to distribute your app, use npx tauri build to create platform-specific binaries.
-
Security Considerations: Ensure that the app's security settings in tauri.conf.json are appropriately configured to prevent vulnerabilities, especially if expanding the app's capabilities.
-
Further Enhancements:
- Editing Notes: Implement an editor to modify the content of
.txt files.
- Listing Notes: Display a list of existing notes within the vault.
- Search Functionality: Allow users to search through their notes.
- Markdown Support: Support markdown files for richer note formatting.
By following this guide, you should have a functional Tauri-based note-taking application using Vanilla JavaScript. Feel free to expand upon this foundation to incorporate more features and improve the user experience.