iT邦幫忙

2022 iThome 鐵人賽

DAY 22
0
Modern Web

30天學習Tauri系列 第 22

22.實作Tauri Todo - 加入計時器

  • 分享至 

  • xImage
  •  

我們今天加入計時器來實現番茄鐘

首先我們先設定時間和時間設定


...

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

...

function App() {
  
  ...
  
  // Timer
  const [time, setTime] = useState(0);
  const [timerStart, setTimerStart] = useState(false);

接著加入計時功能

  // 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);
    }
  }

加入到UI

  ...

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

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";

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);


  // 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>
        );
      })}
    </div>
  );
}

export default App;

測試
https://ithelp.ithome.com.tw/upload/images/20221007/20108931wONwp4q6Ri.png

Reset
https://ithelp.ithome.com.tw/upload/images/20221007/20108931QD2bE8H7Q4.png

選擇10s
https://ithelp.ithome.com.tw/upload/images/20221007/20108931yXjH0ilIvB.png

開始
https://ithelp.ithome.com.tw/upload/images/20221007/201089316SUQyrfua1.png
時間到了會通知
https://ithelp.ithome.com.tw/upload/images/20221007/20108931BdiOJmtVxt.png


上一篇
21.Tauri fs
下一篇
23.實作Tauri Todo - 匯出csv
系列文
30天學習Tauri30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言