-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
106 lines (89 loc) · 2.4 KB
/
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
import "./style.css";
const synth = window.speechSynthesis;
const SpeechRecognition =
window.SpeechRecognition || window.webkitSpeechRecognition;
const list = document.getElementById("list");
const btn = document.getElementById("listen");
const btnCurrent = document.getElementById("current");
const btnComplete = document.getElementById("complete");
const recognition = new SpeechRecognition();
let doComplete = false;
recognition.addEventListener("result", (event) => {
const result = event.results[0][0].transcript;
if (doComplete) {
const todo = findTodo(result);
todo && completeTodo(todo);
} else {
const todo = createTodo(result);
todo && list.appendChild(todo);
}
recognition.stop();
});
recognition.addEventListener("nomatch", (event) => {
console.log("No match", event);
});
recognition.addEventListener("error", (event) => {
console.log("Error", event);
});
btn.addEventListener("click", () => {
doComplete = false;
recognition.start();
});
btnCurrent.addEventListener("click", async () => {
const todos = [...document.querySelectorAll("li")];
for (const todo of todos) {
await speakTodo(todo.innerText);
}
});
btnComplete.addEventListener("click", () => {
doComplete = true;
recognition.start();
});
/**
* @param {String} phrase
*/
async function speakTodo(phrase) {
return new Promise((resolve) => {
let utterance = new SpeechSynthesisUtterance(phrase);
utterance.addEventListener("end", resolve);
synth.speak(utterance);
});
}
/**
* @param {String} content
* @returns HTMLUListElement | null
*/
function createTodo(content) {
if (isDuplicate(content)) return;
const todoElement = document.createElement("li");
todoElement.innerText = content;
todoElement.setAttribute("data-content", content);
return todoElement;
}
/**
*
* @param {HTMLUListElement} todoElement
*/
function completeTodo(todoElement) {
todoElement.classList.add("complete");
}
/**
* @param {String} content
* @returns HTMLUListElement
*/
function findTodo(content) {
const todoElement = [...document.querySelectorAll("li")].find(
(element) => element.innerText.toLowerCase() === content.toLowerCase()
);
return todoElement;
}
/**
* @param {String} content
* @returns Boolean
*/
function isDuplicate(content) {
const count = [...document.querySelectorAll("li")].filter((element) => {
return element.innerText === content;
}).length;
return count > 0;
}