-
Notifications
You must be signed in to change notification settings - Fork 61
/
Copy pathspeech-input.js
169 lines (138 loc) · 5 KB
/
speech-input.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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
/*global webkitSpeechRecognition */
(function() {
'use strict';
// check for support (webkit only)
if (!('webkitSpeechRecognition' in window)) return;
var talkMsg = 'Speak now';
// seconds to wait for more input after last
var defaultPatienceThreshold = 6;
function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
var inputEls = document.getElementsByClassName('speech-input');
[].forEach.call(inputEls, function(inputEl) {
var patience = parseInt(inputEl.dataset.patience, 10) || defaultPatienceThreshold;
var micBtn, micIcon, holderIcon, newWrapper;
var shouldCapitalize = true;
// gather inputEl data
var nextNode = inputEl.nextSibling;
var parent = inputEl.parentNode;
var inputRightBorder = parseInt(getComputedStyle(inputEl).borderRightWidth, 10);
var buttonSize = 0.8 * (inputEl.dataset.buttonsize || inputEl.offsetHeight);
// default max size for textareas
if (!inputEl.dataset.buttonsize && inputEl.tagName === 'TEXTAREA' && buttonSize > 26) {
buttonSize = 26;
}
// create wrapper if not present
var wrapper = inputEl.parentNode;
if (!wrapper.classList.contains('si-wrapper')) {
wrapper = document.createElement('div');
wrapper.classList.add('si-wrapper');
wrapper.appendChild(parent.removeChild(inputEl));
newWrapper = true;
}
// create mic button if not present
micBtn = wrapper.querySelector('.si-btn');
if (!micBtn) {
micBtn = document.createElement('button');
micBtn.type = 'button';
micBtn.classList.add('si-btn');
micBtn.textContent = 'speech input';
micIcon = document.createElement('span');
holderIcon = document.createElement('span');
micIcon.classList.add('si-mic');
holderIcon.classList.add('si-holder');
micBtn.appendChild(micIcon);
micBtn.appendChild(holderIcon);
wrapper.appendChild(micBtn);
// size and position mic and input
micBtn.style.cursor = 'pointer';
micBtn.style.top = 0.125 * buttonSize + 'px';
micBtn.style.height = micBtn.style.width = buttonSize + 'px';
inputEl.style.paddingRight = buttonSize - inputRightBorder + 'px';
}
// append wrapper where input was
if (newWrapper) parent.insertBefore(wrapper, nextNode);
// setup recognition
var prefix = '';
var isSentence;
var recognizing = false;
var timeout;
var oldPlaceholder = null;
var recognition = new webkitSpeechRecognition();
recognition.continuous = true;
recognition.interimResults = true;
// if lang attribute is set on field use that
// (defaults to use the lang of the root element)
if (inputEl.lang) recognition.lang = inputEl.lang;
function restartTimer() {
timeout = setTimeout(function() {
recognition.stop();
}, patience * 1000);
}
recognition.onstart = function() {
oldPlaceholder = inputEl.placeholder;
inputEl.placeholder = inputEl.dataset.ready || talkMsg;
recognizing = true;
micBtn.classList.add('listening');
restartTimer();
};
recognition.onend = function() {
recognizing = false;
clearTimeout(timeout);
micBtn.classList.remove('listening');
if (oldPlaceholder !== null) inputEl.placeholder = oldPlaceholder;
// If the <input> has data-instant-submit and a value,
if (inputEl.dataset.instantSubmit !== undefined && inputEl.value) {
// submit the form it's in (if it is in one).
if (inputEl.form) inputEl.form.submit();
}
};
recognition.onresult = function(event) {
clearTimeout(timeout);
// get SpeechRecognitionResultList object
var resultList = event.results;
// go through each SpeechRecognitionResult object in the list
var finalTranscript = '';
var interimTranscript = '';
for (var i = event.resultIndex; i < resultList.length; ++i) {
var result = resultList[i];
// get this result's first SpeechRecognitionAlternative object
var firstAlternative = result[0];
if (result.isFinal) {
finalTranscript = firstAlternative.transcript;
} else {
interimTranscript += firstAlternative.transcript;
}
}
// capitalize transcript if start of new sentence
var transcript = finalTranscript || interimTranscript;
transcript = !prefix || isSentence ? capitalize(transcript) : transcript;
// append transcript to cached input value
inputEl.value = prefix + transcript;
// set cursur and scroll to end
inputEl.focus();
if (inputEl.tagName === 'INPUT') {
inputEl.scrollLeft = inputEl.scrollWidth;
} else {
inputEl.scrollTop = inputEl.scrollHeight;
}
restartTimer();
};
micBtn.addEventListener('click', function(event) {
event.preventDefault();
// stop and exit if already going
if (recognizing) {
recognition.stop();
return;
}
// Cache current input value which the new transcript will be appended to
var endsWithWhitespace = inputEl.value.slice(-1).match(/\s/);
prefix = !inputEl.value || endsWithWhitespace ? inputEl.value : inputEl.value + ' ';
// check if value ends with a sentence
isSentence = prefix.trim().slice(-1).match(/[\.\?\!]/);
// restart recognition
recognition.start();
}, false);
});
})();