@huluvu424242/honey-speaker
Version:
Text to Speech component wich is reading texts from DOM elements.
714 lines (713 loc) • 19.9 kB
JavaScript
import { Component, Element, Event, h, Host, Listen, Method, Prop, State, Watch } from "@stencil/core";
import { Sprachausgabe } from "../../libs/sprachausgabe";
import { Logger } from "../../libs/logger";
import { Fileloader } from "../../libs/fileloader";
export class HoneySpeaker {
constructor() {
this.options = {
disabledHostClass: "speaker-disabled",
enabledHostClass: "speaker-enabled",
disabledTitleText: "Vorlesen deaktiviert, da keine Texte verfügbar",
pressedTitleText: "Liest gerade vor",
unpressedTitleText: "Vorlesen",
pressedAltText: "Symbol eines tönenden Lautsprechers",
unpressedAltText: "Symbol eines angehaltenen, tönenden Lautsprechers",
pressedPureAltText: "Symbol eines tönenden Lautsprechers",
unpressedPureAltText: "Symbol eines ausgeschaltenen Lautsprechers"
};
/**
* true wenn das Tag ohne alt Attribute deklariert wurde
*/
this.createAltText = false;
/**
* true wenn das Tag ohne title Attribut deklariert wurde
*/
this.createTitleText = false;
/**
* initial computed taborder
*/
this.taborder = "0";
/**
* texte to speech out
*/
this.texts = [];
/**
* if the toggle button is pressed
*/
this.isPressed = false;
/**
* use pure speaker symbol for silence state
*/
this.pure = false;
/**
* enable console logging
*/
this.verbose = false;
/**
* icon width
*/
this.iconwidth = "36";
/**
* icon height
*/
this.iconheight = "36";
/**
* i18n language ident for Web Speech API: de-DE or en or de ...
*/
this.audiolang = "de-DE";
/**
* pitch for Web Speech API
*/
this.audiopitch = 1;
/**
* rate for Web Speech API
*/
this.audiorate = 1;
/**
* volume for Web Speech API
*/
this.audiovolume = 1;
/**
* voice name used of Web Speech API
*/
this.voicename = undefined;
}
connectedCallback() {
// States initialisieren
this.ident = this.hostElement.id ? this.hostElement.id : Math.random().toString(36).substring(7);
this.initialHostClass = this.hostElement.getAttribute("class") || "";
this.createTitleText = !this.hostElement.title;
this.createAltText = !this.hostElement["alt"];
this.taborder = this.hostElement.getAttribute("tabindex") ? (this.hostElement.tabIndex + "") : "0";
// Properties auswerten
Logger.toggleLogging(this.verbose);
}
async componentWillLoad() {
this.sprachAusgabe = new Sprachausgabe(() => {
this.isPressed = true;
this.honeySpeakerStarted.emit(this.ident);
Logger.debugMessage("Vorlesen gestartet");
}, () => {
this.isPressed = false;
this.honeySpeakerFinished.emit(this.ident);
Logger.debugMessage("Vorlesen beendet");
}, () => {
this.isPressed = false;
this.honeySpeakerPaused.emit(this.ident);
Logger.debugMessage("Pause mit Vorlesen");
}, () => {
this.isPressed = true;
this.honeySpeakerResume.emit(this.ident);
Logger.debugMessage("Fortsetzen mit Vorlesen");
}, (ev) => {
this.isPressed = false;
this.honeySpeakerFailed.emit(this.ident);
Logger.errorMessage("Fehler beim Vorlesen" + JSON.stringify(ev));
}, this.audiolang, this.audiopitch, this.audiorate, this.audiovolume, this.voicename);
await this.updateTexte();
}
/**
* Update speaker options
* @param options : SpeakerOptions plain object to set the options
*/
async updateOptions(options) {
for (let prop in options) {
if (options.hasOwnProperty(prop)) {
this.options[prop] = options[prop];
}
}
this.options = Object.assign({}, this.options);
}
/**
* bricht laufende oder pausierende Ausgaben ab und startet dia Ausgabe von vorn
*/
async startSpeaker() {
// init für toggleAction
this.isPressed = false;
// negiert isPressed bricht vorher laufende Ausgaben ab
await this.toggleAction();
}
/**
* paused the speaker
*/
async pauseSpeaker() {
this.isPressed = false;
this.sprachAusgabe.pause();
}
/**
* continue speaker after paused
*/
async resumeSpeaker() {
this.isPressed = true;
this.sprachAusgabe.resume();
}
/**
* cancel the speaker
*/
async cancelSpeaker() {
this.isPressed = false;
this.sprachAusgabe.cancel();
}
/**
* call the toggle speaker action
*/
async toggleSpeaker() {
await this.toggleAction();
}
hasNoTexts() {
return (!this.texts
|| this.texts.length < 1
|| this.texts.filter(item => item.trim().length > 0).length < 1);
}
createNewTitleText() {
if (this.hasNoTexts()) {
return this.options.disabledTitleText;
}
if (this.isPressed) {
return this.options.pressedTitleText;
}
else {
return this.options.unpressedTitleText;
}
}
getTitleText() {
if (this.createTitleText) {
return this.createNewTitleText();
}
else {
return this.hostElement.title;
}
}
createNewAltText() {
if (this.isPressed) {
return this.pure ? this.options.pressedPureAltText : this.options.pressedAltText;
}
else {
return this.pure ? this.options.unpressedPureAltText : this.options.unpressedAltText;
}
}
getAltText() {
if (this.createAltText) {
return this.createNewAltText();
}
else {
return this.hostElement.getAttribute("alt");
}
}
loadDOMElementTexte() {
if (this.textids) {
const refIds = this.textids.split(",");
refIds.forEach(elementId => {
const element = document.getElementById(elementId);
if (element) {
this.texts = [...this.texts, element.innerText];
}
else {
Logger.errorMessage("text to speak not found of DOM element with id " + elementId);
}
});
}
}
async loadAudioUrlText() {
if (this.texturl) {
Logger.debugMessage("audioURL: " + this.texturl);
const audioData = await Fileloader.loadData(this.texturl);
if (audioData) {
this.texts = [...this.texts, audioData];
}
Logger.debugMessage('###Texte###' + this.texts);
}
}
async updateTexte() {
this.texts = [];
this.loadDOMElementTexte();
await this.loadAudioUrlText();
}
textidsChanged(newValue, oldValue) {
Logger.debugMessage("textids changed from" + oldValue + " to " + newValue);
this.updateTexte();
}
async texturlChanged(newValue, oldValue) {
this.texturl = newValue;
Logger.debugMessage("texturl changed from" + oldValue + " to " + newValue);
await this.updateTexte();
}
getTexte() {
if (this.texts) {
return this.texts;
}
else {
return [];
}
}
textVorlesen(text) {
this.isPressed = true;
this.sprachAusgabe.textVorlesen(text + " ");
}
async toggleAction() {
Logger.debugMessage("###TOGGLE TO" + this.isPressed);
if (!this.isPressed) {
await this.cancelSpeaker();
}
this.isPressed = !this.isPressed;
const texte = this.getTexte();
if (this.isPressed && texte.length > 0) {
const vorzulesenderText = texte.join('');
this.textVorlesen(vorzulesenderText);
}
else {
await this.cancelSpeaker();
}
}
async onClick() {
if (this.hasNoTexts())
return;
await this.toggleAction();
}
async onKeyDown(ev) {
if (this.hasNoTexts())
return;
if (ev.key === 'Enter' || ev.key === ' ') {
ev.preventDefault();
await this.toggleAction();
}
}
getHostClass() {
let hostClass = this.initialHostClass;
if (this.hasNoTexts()) {
return hostClass + " " + this.options.disabledHostClass;
}
else {
return hostClass + " " + this.options.enabledHostClass;
}
}
render() {
Logger.debugMessage('##RENDER##');
return (h(Host, { title: this.getTitleText(), alt: this.getAltText(), role: "button", tabindex: this.hasNoTexts() ? -1 : this.taborder, "aria-pressed": this.isPressed ? "true" : "false", class: this.getHostClass(), disabled: this.hasNoTexts() }, this.isPressed ? (h("svg", { id: this.ident + "-svg", xmlns: "http://www.w3.org/2000/svg", width: this.iconwidth, height: this.iconheight, role: "img", "aria-label": this.getAltText(), class: this.hasNoTexts() ? "speakerimage-disabled" : "speakerimage", viewBox: "0 0 75 75" },
h("path", { "stroke-linejoin": "round", d: "M39.389,13.769 L22.235,28.606 L6,28.606 L6,47.699 L21.989,47.699 L39.389,62.75 L39.389,13.769z" }),
h("path", { id: this.ident + "-air", fill: "none", "stroke-linecap": "round", d: "M48,27.6a19.5,19.5 0 0 1 0,21.4M55.1,20.5a30,30 0 0 1 0,35.6M61.6,14a38.8,38.8 0 0 1 0,48.6" },
h("animate", { id: "airanimation", attributeType: "CSS", attributeName: "opacity", from: "1", to: "0", dur: "1s", repeatCount: "indefinite" })))) : (h("svg", { id: this.ident + "-svg", xmlns: "http://www.w3.org/2000/svg", width: this.iconwidth, height: this.iconheight, role: "img", "aria-label": this.getAltText(), class: this.hasNoTexts() ? "speakerimage-disabled" : "speakerimage", viewBox: "0 0 75 75" },
h("path", { "stroke-linejoin": "round", d: "M39.389,13.769 L22.235,28.606 L6,28.606 L6,47.699 L21.989,47.699 L39.389,62.75 L39.389,13.769z" }),
this.pure ? (h("text", { id: this.ident + "-text", x: "60%", y: "55%" }, "OFF")) : (h("path", { id: this.ident + "-air", fill: "none", "stroke-linecap": "round", d: "M48,27.6a19.5,19.5 0 0 1 0,21.4M55.1,20.5a30,30 0 0 1 0,35.6M61.6,14a38.8,38.8 0 0 1 0,48.6" }))))));
}
static get is() { return "honey-speaker"; }
static get encapsulation() { return "shadow"; }
static get originalStyleUrls() { return {
"$": ["honey-speaker.css"]
}; }
static get styleUrls() { return {
"$": ["honey-speaker.css"]
}; }
static get assetsDirs() { return ["assets"]; }
static get properties() { return {
"pure": {
"type": "boolean",
"mutable": false,
"complexType": {
"original": "boolean",
"resolved": "boolean",
"references": {}
},
"required": false,
"optional": false,
"docs": {
"tags": [],
"text": "use pure speaker symbol for silence state"
},
"attribute": "pure",
"reflect": false,
"defaultValue": "false"
},
"textids": {
"type": "string",
"mutable": true,
"complexType": {
"original": "string",
"resolved": "string",
"references": {}
},
"required": false,
"optional": false,
"docs": {
"tags": [],
"text": "An comma separated list with ids of DOM elements\nwhich inner text should be speech."
},
"attribute": "textids",
"reflect": false
},
"texturl": {
"type": "string",
"mutable": true,
"complexType": {
"original": "string",
"resolved": "string",
"references": {}
},
"required": false,
"optional": false,
"docs": {
"tags": [],
"text": "An url to download an text file to speech."
},
"attribute": "texturl",
"reflect": false
},
"verbose": {
"type": "boolean",
"mutable": false,
"complexType": {
"original": "boolean",
"resolved": "boolean",
"references": {}
},
"required": false,
"optional": false,
"docs": {
"tags": [],
"text": "enable console logging"
},
"attribute": "verbose",
"reflect": false,
"defaultValue": "false"
},
"iconwidth": {
"type": "string",
"mutable": false,
"complexType": {
"original": "string",
"resolved": "string",
"references": {}
},
"required": false,
"optional": false,
"docs": {
"tags": [],
"text": "icon width"
},
"attribute": "iconwidth",
"reflect": false,
"defaultValue": "\"36\""
},
"iconheight": {
"type": "string",
"mutable": false,
"complexType": {
"original": "string",
"resolved": "string",
"references": {}
},
"required": false,
"optional": false,
"docs": {
"tags": [],
"text": "icon height"
},
"attribute": "iconheight",
"reflect": false,
"defaultValue": "\"36\""
},
"audiolang": {
"type": "string",
"mutable": false,
"complexType": {
"original": "string",
"resolved": "string",
"references": {}
},
"required": false,
"optional": false,
"docs": {
"tags": [],
"text": "i18n language ident for Web Speech API: de-DE or en or de ..."
},
"attribute": "audiolang",
"reflect": false,
"defaultValue": "\"de-DE\""
},
"audiopitch": {
"type": "number",
"mutable": false,
"complexType": {
"original": "number",
"resolved": "number",
"references": {}
},
"required": false,
"optional": false,
"docs": {
"tags": [],
"text": "pitch for Web Speech API"
},
"attribute": "audiopitch",
"reflect": false,
"defaultValue": "1"
},
"audiorate": {
"type": "number",
"mutable": false,
"complexType": {
"original": "number",
"resolved": "number",
"references": {}
},
"required": false,
"optional": false,
"docs": {
"tags": [],
"text": "rate for Web Speech API"
},
"attribute": "audiorate",
"reflect": false,
"defaultValue": "1"
},
"audiovolume": {
"type": "number",
"mutable": false,
"complexType": {
"original": "number",
"resolved": "number",
"references": {}
},
"required": false,
"optional": false,
"docs": {
"tags": [],
"text": "volume for Web Speech API"
},
"attribute": "audiovolume",
"reflect": false,
"defaultValue": "1"
},
"voicename": {
"type": "string",
"mutable": false,
"complexType": {
"original": "string",
"resolved": "string",
"references": {}
},
"required": false,
"optional": false,
"docs": {
"tags": [],
"text": "voice name used of Web Speech API"
},
"attribute": "voicename",
"reflect": false,
"defaultValue": "undefined"
}
}; }
static get states() { return {
"options": {},
"texts": {},
"isPressed": {}
}; }
static get events() { return [{
"method": "honeySpeakerStarted",
"name": "honeySpeakerStarted",
"bubbles": true,
"cancelable": true,
"composed": true,
"docs": {
"tags": [],
"text": "Fired if the voice is speaking."
},
"complexType": {
"original": "string",
"resolved": "string",
"references": {}
}
}, {
"method": "honeySpeakerFinished",
"name": "honeySpeakerFinished",
"bubbles": true,
"cancelable": true,
"composed": true,
"docs": {
"tags": [],
"text": "Fired if the voice has finished with speaking."
},
"complexType": {
"original": "string",
"resolved": "string",
"references": {}
}
}, {
"method": "honeySpeakerPaused",
"name": "honeySpeakerPaused",
"bubbles": true,
"cancelable": true,
"composed": true,
"docs": {
"tags": [],
"text": "Fired if the voice is paused with speaking."
},
"complexType": {
"original": "string",
"resolved": "string",
"references": {}
}
}, {
"method": "honeySpeakerResume",
"name": "honeySpeakerResume",
"bubbles": true,
"cancelable": true,
"composed": true,
"docs": {
"tags": [],
"text": "Fired if the voice is resumed after paused with speaking."
},
"complexType": {
"original": "string",
"resolved": "string",
"references": {}
}
}, {
"method": "honeySpeakerFailed",
"name": "honeySpeakerFailed",
"bubbles": true,
"cancelable": true,
"composed": true,
"docs": {
"tags": [],
"text": "Fired if the voice has failed to speak."
},
"complexType": {
"original": "string",
"resolved": "string",
"references": {}
}
}]; }
static get methods() { return {
"updateOptions": {
"complexType": {
"signature": "(options: SpeakerOptions) => Promise<void>",
"parameters": [{
"tags": [{
"text": "options : SpeakerOptions plain object to set the options",
"name": "param"
}],
"text": ": SpeakerOptions plain object to set the options"
}],
"references": {
"Promise": {
"location": "global"
},
"SpeakerOptions": {
"location": "import",
"path": "./speaker-options"
}
},
"return": "Promise<void>"
},
"docs": {
"text": "Update speaker options",
"tags": [{
"name": "param",
"text": "options : SpeakerOptions plain object to set the options"
}]
}
},
"startSpeaker": {
"complexType": {
"signature": "() => Promise<void>",
"parameters": [],
"references": {
"Promise": {
"location": "global"
}
},
"return": "Promise<void>"
},
"docs": {
"text": "bricht laufende oder pausierende Ausgaben ab und startet dia Ausgabe von vorn",
"tags": []
}
},
"pauseSpeaker": {
"complexType": {
"signature": "() => Promise<void>",
"parameters": [],
"references": {
"Promise": {
"location": "global"
}
},
"return": "Promise<void>"
},
"docs": {
"text": "paused the speaker",
"tags": []
}
},
"resumeSpeaker": {
"complexType": {
"signature": "() => Promise<void>",
"parameters": [],
"references": {
"Promise": {
"location": "global"
}
},
"return": "Promise<void>"
},
"docs": {
"text": "continue speaker after paused",
"tags": []
}
},
"cancelSpeaker": {
"complexType": {
"signature": "() => Promise<void>",
"parameters": [],
"references": {
"Promise": {
"location": "global"
}
},
"return": "Promise<void>"
},
"docs": {
"text": "cancel the speaker",
"tags": []
}
},
"toggleSpeaker": {
"complexType": {
"signature": "() => Promise<void>",
"parameters": [],
"references": {
"Promise": {
"location": "global"
}
},
"return": "Promise<void>"
},
"docs": {
"text": "call the toggle speaker action",
"tags": []
}
}
}; }
static get elementRef() { return "hostElement"; }
static get watchers() { return [{
"propName": "textids",
"methodName": "textidsChanged"
}, {
"propName": "texturl",
"methodName": "texturlChanged"
}]; }
static get listeners() { return [{
"name": "click",
"method": "onClick",
"target": undefined,
"capture": true,
"passive": false
}, {
"name": "keydown",
"method": "onKeyDown",
"target": undefined,
"capture": true,
"passive": false
}]; }
}