Skip to content
The Chat Archive
o1-preview-2024-09-12· OpenAI WildChat-4.8M (AI2)

Create an app using Tauri and Vanilla JavaScript, with a clean API for creating,…

  1. 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.

  2. Assistant

    Sure! Let's create a minimal Tauri application using Vanilla JavaScript that allows users to create, modify, and delete .txt files 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

    1. Create a new directory for your project:

      mkdir tauri-notes-app
      cd tauri-notes-app
      
    2. Initialize a new npm project:

      npm init -y
      
    3. Install Tauri dependencies:

      npm install @tauri-apps/cli @tauri-apps/api
      
    4. Initialize a Tauri project:

      Since we're avoiding Rust code and using npm, we'll use Tauri's JavaScript templates.

      npx tauri init
      

      During 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 No unless 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

    1. Project Structure:

      Your project should now have a src-tauri directory (for backend configuration) and a src directory (for the frontend).

    2. Clean the index.html:

      Open src/index.html and 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>
      
    3. Create main.js:

      In the src directory, create a file called main.js and 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 .txt file 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.

    1. Open src-tauri/tauri.conf.json:

      Find the tauri section and update the allowlist to 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.
    2. Security Settings:

      Ensure secure is set to true (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.

    1. Update index.html to include a list:

      <body>
        <ul id="notes-list"></ul>
        <script type="module" src="main.js"></script>
      </body>
      
    2. 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 .txt files.
      • openNote(): Opens a prompt with the note's content for editing.
      • deleteNote(): Deletes the selected note.
      • Updates event listeners to handle these interactions.
    3. 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 dev
    

    This command starts the app in development mode.


    Step 6: Build the Application

    When you're ready to build the application for distribution:

    npx tauri build
    

    This will create an executable in the src-tauri/target/release directory.


    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 localStorage for simplicity. For a more robust solution, consider using Tauri's store API 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.

    Conclusion

    You've now created a minimalistic Tauri application using Vanilla JavaScript that allows users to create, view, edit, and delete .txt notes 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.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.