iT邦幫忙

2022 iThome 鐵人賽

DAY 23
0
Modern Web

30天學習Tauri系列 第 23

23.實作Tauri Todo - 匯出csv

  • 分享至 

  • xImage
  •  

我們今天來將我們的todo以csv格式匯出到下載

打開todo\src-tauri\tauri.conf.json

加入
{
  "tauri": {
    "allowlist": {
      "fs": {
        "all": true,
        "scope": ["$DOWNLOAD/*"]
      }
  }
}

回到todo\src\pages\index.tsx

加入
import { writeTextFile, BaseDirectory } from '@tauri-apps/api/fs';

  // Export
  const handleExportFile = async () => {
    const separator = ',';
    const keys = Object.keys(todos[0]);
    const csvContent =
      keys.join(separator) +
      '\n' +
      todos.map(row => {
        return keys.map(k => {
          let cell = row[k] === null || row[k] === undefined ? '' : row[k];
          cell = cell instanceof Date
            ? cell.toLocaleString()
            : cell.toString().replace(/"/g, '""');
          if (cell.search(/("|,|\n)/g) >= 0) {
            cell = `"${cell}"`;
          }
          return cell;
        }).join(separator);
      }).join('\n');
    console.log(csvContent);

    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    let text = await blob.text();
    await writeTextFile('todos.csv', text, { dir: BaseDirectory.Download });
    await message('Export todos!!', 'Export done!!');
  }

UI

...
      {/* export */}
      <hr/>

      <div>
        <button type="button" onClick={() => handleExportFile()}>
          Export
        </button>
      </div>

    </div>
  );
}

export default App;

測試後,會發現將他export
https://ithelp.ithome.com.tw/upload/images/20221008/20108931wS4nO6vdzV.png

todo\src\pages\index.tsx

import { useEffect, useState } from "react";
import { invoke } from '@tauri-apps/api/tauri';
import { message, confirm, ask } from '@tauri-apps/api/dialog';
import { sendNotification } from "@tauri-apps/api/notification";
import { writeTextFile, BaseDirectory } from '@tauri-apps/api/fs';

const itemStyle = {
  padding: '8px',
};

const buttons = [
  {
    value: 10, display: "10s",
  },
  {
    value: 1800, display: "30m",
  }
];

interface Todo {
  id: number,
  title: string,
  date: string,
  done: boolean
}

function App() {
  
  const [todos, setTodos] = useState<Todo[]>([]);
  const [todo, setTodo] = useState<Todo>({id: -1, title: "", date: "None", done: false});
  // Timer
  const [time, setTime] = useState(0);
  const [timerStart, setTimerStart] = useState(false);


  // Export
  const handleExportFile = async () => {
    const separator = ',';
    const keys = Object.keys(todos[0]);
    const csvContent =
      keys.join(separator) +
      '\n' +
      todos.map(row => {
        return keys.map(k => {
          let cell = row[k] === null || row[k] === undefined ? '' : row[k];
          cell = cell instanceof Date
            ? cell.toLocaleString()
            : cell.toString().replace(/"/g, '""');
          if (cell.search(/("|,|\n)/g) >= 0) {
            cell = `"${cell}"`;
          }
          return cell;
        }).join(separator);
      }).join('\n');
    console.log(csvContent);

    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    let text = await blob.text();
    await writeTextFile('todos.csv', text, { dir: BaseDirectory.Download });
    await message('Export todos!!', 'Export done!!');
  }

  // Pomodoro
  useEffect(() => {
    const hanleInterval = setInterval(() => {
      if(timerStart) {
        if(time > 0) {
          setTime(time -1);
        } else if (time == 0) {
          sendNotification({
            title: `Time up!!`,
            body: `Done Pomodoro`,
          });
          clearInterval(hanleInterval);
        }
      }
    }, 1000);
    return () => clearInterval(hanleInterval);
  }, [timerStart, time]);

  const toggleTimer = () => {
    setTimerStart(!timerStart);
  }

  const triggerResetDialog = async () => {
    let shouldReset = await ask("Reset?", {
      title: "Pomodoro Timer",
      type: "warning",
    })
    if(shouldReset) {
      setTime(900);
      setTimerStart(false);
    }
  }
  
  // Todo
  useEffect(()=> {
    fetchAllTodo();
  }, [todos]);

  const fetchAllTodo = async () => {
    setTodos(await invoke("get_todos"));
  }

  const handleTitleChange = (e: React.FormEvent<HTMLInputElement>) => {
    let value = e.currentTarget.value;
    setTodo({...todo, title: value});
  }

  const handleTodoAdd = async () => {
    await invoke("new_todo", { title: todo.title, date: Date.now.toString() });
    setTodo({...todo, title: ""});
  }

  const handleTodoDelete = async (id: number) => {
    console.log(id);
    const confirmed = await confirm('This action cannot be reverted. Are you sure?', { title: 'Tauri', type: 'warning' });
    if(confirmed) {
      await invoke("delete_todo", { id: id});
    }
    setTodo({...todo, title: ""});
  }

  const handleChecked = async (index: number) => {
    await invoke("done_todo", {id : todos[index].id, msg: todos[index].title});
    if(!todos[index].done) {
      await message("Done", { title: 'Todo' });
      await handleDoneNotification();
    }
  }

  const handleDoneNotification = async () => {
    await sendNotification({
      title: `Todo is done`,
      body: `Great, you did it!!!!!!!!!`,
    });
  }

  return (
    <div className="container">
      <div>
        <h1>
          {`${
              Math.floor(time / 60) < 10
                ? `0${Math.floor(time / 60)}`
                : `${Math.floor(time / 60)}`
            }:${time % 60 < 10 ? `0${time % 60}` : time % 60}`}
        </h1>
      </div>
      <div className="row" style={{margin: 10}}>
        <button onClick={toggleTimer}>
          {!timerStart ? "Start" : "Pause"}
        </button>
        <button onClick={triggerResetDialog}>
          Reset Timer
        </button>
      </div>
      <div>
        {buttons.map(({value, display}) => (
          <button type="button" onClick={() => {
            setTimerStart(false);
            setTime(value);
          }}>
            {display}
          </button>
        ))}
      </div>

      <h1>Todo List</h1>
      
      <div className="row">
        <input
          id="greet-input"
          onChange={(e) => handleTitleChange(e)}
          placeholder="Enter a task..."
          value={todo.title}
        />
        <button type="button" onClick={() => handleTodoAdd()}>
          Add
        </button>
        
      </div>
      <hr />
      {todos.map((todo, index) => {
        return (
          <div className="row" key={index}>
            <div style={itemStyle}></div>
            <span 
              onClick={() => handleChecked(index)}
              style={{
                textDecoration: todos[index].done && 'line-through',
              }}
            >
              {todo.title}
            </span>
            <button type="button" onClick={() => handleTodoDelete(todo.id)}>
              Delete
            </button>
          </div>
        );
      })}

      {/* export */}
      <hr/>

      <div>
        <button type="button" onClick={() => handleExportFile()}>
          Export
        </button>
      </div>

    </div>
  );
}

export default App;

上一篇
22.實作Tauri Todo - 加入計時器
下一篇
24.實作Tauri Todo - 匯入csv
系列文
30天學習Tauri30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言