'use strict';
var Writable = require('stream').Writable;
var util = require('util');
var defaults = require('defaults');
/**
* Writable stream that accepts results in either object or string mode and outputs the text to a supplied html element
*
* Can show interim results when in objectMode
*
* @param {Object} options
* @param {String|DOMElement} options.outputElement
* @param {String} [options.property] what property of the element should the text be set to. Defaults to `value` for `<input>`s and `<textarea>`s, `textContent` for everything else
* @param {Boolean} [options.clear=true] delete any previous text
* @constructor
*/
function WritableElementStream(options) {
this.options = options = defaults(options, {
decodeStrings: false, // false = don't convert strings to buffers before passing to _write (only applies in string mode)
property: null,
clear: true
});
this.el = typeof options.outputElement === 'string' ? document.querySelector(options.outputElement) : options.outputElement;
if (!this.el) {
throw new Error('Watson Speech to Text WritableElementStream: missing outputElement');
}
Writable.call(this, options);
// for most elements we set the textContent, but for form elements, the value property is probably the expected target
var propMap = {
INPUT: 'value',
TEXTAREA: 'value'
};
this.prop = options.property || propMap[this.el.nodeName] || 'textContent';
if (options.clear) {
this.el[this.prop] = '';
}
if (options.objectMode) {
this.finalizedText = this.el[this.prop];
this._write = this.writeObject;
} else {
this._write = this.writeString;
}
}
util.inherits(WritableElementStream, Writable);
WritableElementStream.prototype.writeString = function writeString(text, encoding, next) {
this.el[this.prop] += text;
next();
};
WritableElementStream.prototype.writeObject = function writeObject(data, encoding, next) {
if (Array.isArray(data.results)) {
data.results.forEach(
function(result) {
if (result.final) {
this.finalizedText += result.alternatives[0].transcript;
this.el[this.prop] = this.finalizedText;
} else {
this.el[this.prop] = this.finalizedText + result.alternatives[0].transcript;
}
},
this
);
}
next();
};
module.exports = WritableElementStream;