This code contains the user interface of the banking chatbot. I have used Mozilla's Web Speech API to implement the speech to text feature. After implementing it, I have faced a major bug. As soon as the user starts the speech recognition by clicking on the "Speak" button; the textarea automatically increases in size and covers or hides the Submit button which is preventing the user from submitting his/her query. I haven't been able to locate the error.
//initialize speech recognition API
window.SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
const recognition = new SpeechRecognition(); //initialize my instance of speech recognition
recognition.interimResults = true; //return results while still working on current recognition
//this is where your speech-to-text results will appear
let p = document.createElement("p")
const words = document.querySelector(".words-container")
words.appendChild(p)
//I want to select and change the color of the body, but this could be any HTML element on your page
let body = document.querySelector("body")
let cap_css_colors = ["AliceBlue","AntiqueWhite","Aqua","Aquamarine","Azure","Beige","Bisque","Black","BlanchedAlmond","Blue","BlueViolet","Brown","BurlyWood","CadetBlue","Chartreuse","Chocolate","Coral","CornflowerBlue","Cornsilk","Crimson","Cyan","DarkBlue","DarkCyan","DarkGoldenRod","DarkGray","DarkGrey","DarkGreen","DarkKhaki","DarkMagenta","DarkOliveGreen","Darkorange","DarkOrchid","DarkRed","DarkSalmon","DarkSeaGreen","DarkSlateBlue","DarkSlateGray","DarkSlateGrey","DarkTurquoise","DarkViolet","DeepPink","DeepSkyBlue","DimGray","DimGrey","DodgerBlue","FireBrick","FloralWhite","ForestGreen","Fuchsia","Gainsboro","GhostWhite","Gold","GoldenRod","Gray","Grey","Green","GreenYellow","HoneyDew","HotPink","IndianRed","Indigo","Ivory","Khaki","Lavender","LavenderBlush","LawnGreen","LemonChiffon","LightBlue","LightCoral","LightCyan","LightGoldenRodYellow","LightGray","LightGrey","LightGreen","LightPink","LightSalmon","LightSeaGreen","LightSkyBlue","LightSlateGray","LightSlateGrey","LightSteelBlue","LightYellow","Lime","LimeGreen","Linen","Magenta","Maroon","MediumAquaMarine","MediumBlue","MediumOrchid","MediumPurple","MediumSeaGreen","MediumSlateBlue","MediumSpringGreen","MediumTurquoise","MediumVioletRed","MidnightBlue","MintCream","MistyRose","Moccasin","NavajoWhite","Navy","OldLace","Olive","OliveDrab","Orange","OrangeRed","Orchid","PaleGoldenRod","PaleGreen","PaleTurquoise","PaleVioletRed","PapayaWhip","PeachPuff","Peru","Pink","Plum","PowderBlue","Purple","Red","RosyBrown","RoyalBlue","SaddleBrown","Salmon","SandyBrown","SeaGreen","SeaShell","Sienna","Silver","SkyBlue","SlateBlue","SlateGray","SlateGrey","Snow","SpringGreen","SteelBlue","Tan","Teal","Thistle","Tomato","Turquoise","Violet","Wheat","White","WhiteSmoke","Yellow","YellowGreen"];
const CSS_COLORS = cap_css_colors.map(color => {
//I need to change all color names to lower case, because comparison between words will be case sensitive
return color.toLowerCase()
})
//once speech recognition determines it has a "result", grab the texts of that result, join all of them, and add to paragraph
recognition.addEventListener("result", e => {
const transcript = Array.from(e.results)
.map(result => result[0])
.map(result => result.transcript)
.join("")
p.innerText = transcript
//once speech recognition determines it has a final result, create a new paragraph and append it to the words-container
//this way every time you add a new p to hold your speech-to-text every time you're finished with the previous results
if (e.results[0].isFinal) {
p = document.createElement("p")
words.appendChild(p)
}
//for each result, map through all color names and check if current result (transcript) contains that color
//i.e. see if a person said any color name you know
CSS_COLORS.forEach(color => {
//if find a match, change your background color to that color
if (transcript.includes(color)) {
body.style.backgroundColor = color;
}
})
})
//add your functionality to the start and stop buttons
function startRecording() {
recognition.start();
recognition.addEventListener("end", recognition.start)
document.getElementById("stop").addEventListener("click", stopRecording)
}
function stopRecording() {
console.log("okay I'll stop")
recognition.removeEventListener("end", recognition.start)
recognition.stop();
}
ul {
list-style: none;
padding: 0;
}
p {
color: #444;
}
button:focus {
outline: 0;
}
.container {
max-width: 700px;
margin: 0 auto;
padding: 100px 50px;
text-align: center;
}
.container h1 {
margin-bottom: 20px;
}
.page-description {
font-size: 1.1rem;
margin: 0 auto;
}
.tz-link {
font-size: 1em;
color: #1da7da;
text-decoration: none;
}
.no-browser-support {
display: none;
font-size: 1.2rem;
color: #e64427;
margin-top: 35px;
}
.app {
margin: 40px auto;
}
#note-textarea {
margin: 20px 0;
}
#recording-instructions {
margin: 15px auto 60px;
}
#notes {
padding-top: 20px;
}
.note .header {
font-size: 0.9em;
color: #888;
margin-bottom: 10px;
}
.note .delete-note,
.note .listen-note {
text-decoration: none;
margin-left: 15px;
}
.note .content {
margin-bottom: 40px;
}
#media (max-width: 768px) {
.container {
padding: 50px 25px;
}
button {
margin-bottom: 10px;
}
}
/* -- Demo ads -- */
#media (max-width: 1200px) {
#bsaHolder{ display:none;}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>MJ BOT </title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="{{ url_for('static', filename='styles/style.css') }}">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<!-- partial:index.partial.html -->
<section class="msger">
<header class="msger-header">
<div class="msger-header-title">
<i class=""></i> MJ Chatbot <i class=""></i>
</div>
</header>
<main class="msger-chat">
<div class="msg left-msg">
<div class="msg-img" style="background-image: url(https://image.flaticon.com/icons/svg/145/145867.svg)"></div>
<div class="msg-bubble">
<div class="msg-info">
<div class="msg-info-name"></div>
</div>
<div class="msg-text">
<p> {{ questionAsked }} </p>
</div>
</div>
</div>
</main>
<article>
<main class="msger-chat">
<div class="msg right-msg">
<div class="msg-img" style="background-image: url(https://image.flaticon.com/icons/svg/327/327779.svg)"></div>
<div class="msg-bubble">
<div class="msg-info">
<div class="msg-info-name"></div>
</div>
<div class="msg-text">
<p> {{ response }}</p>
</div>
</div>
</div>
</article>
</main>
<form id="output" class="msger-inputarea" action="signup" method="post">
<input id="output" class="msger-input" type="text" name="question"></input>
<input id='play' class="msger-send-btn" type="submit" value="Submit Message !" > </input>
<input type="button" value="Speak" onclick="runSpeechRecognition()"></input>
<button id='stop'></button>
</form>
<button id=play style="font-size:24px">Listen <i class="fas fa-file-audio"></i></button>
Send Query to Agent !
</section>
<script >onload = function() {
if ('speechSynthesis' in window) with(speechSynthesis) {
var playEle = document.querySelector('#play');
var pauseEle = document.querySelector('#pause');
var stopEle = document.querySelector('#stop');
var flag = false;
playEle.addEventListener('click', onClickPlay);
pauseEle.addEventListener('click', onClickPause);
stopEle.addEventListener('click', onClickStop);
function onClickPlay() {
if(!flag){
flag = true;
utterance = new SpeechSynthesisUtterance(document.querySelector('article').textContent);
utterance.voice = getVoices()[0];
utterance.onend = function(){
flag = false; playEle.className = pauseEle.className = ''; stopEle.className = 'stopped';
};
playEle.className = 'played';
stopEle.className = '';
speak(utterance);
}
if (paused) { /* unpause/resume narration */
playEle.className = 'played';
pauseEle.className = '';
resume();
}
}
function onClickPause() {
if(speaking && !paused){ /* pause narration */
pauseEle.className = 'paused';
playEle.className = '';
pause();
}
}
function onClickStop() {
if(speaking){ /* stop narration */
/* for safari */
stopEle.className = 'stopped';
playEle.className = pauseEle.className = '';
flag = false;
cancel();
}
}
}
else { /* speech synthesis not supported */
msg = document.createElement('h5');
msg.textContent = "Detected no support for Speech Synthesis";
msg.style.textAlign = 'center';
msg.style.backgroundColor = 'red';
msg.style.color = 'white';
msg.style.marginTop = msg.style.marginBottom = 0;
document.body.insertBefore(msg, document.querySelector('div'));
}
}
</script>
<script>
/* JS comes here */
function runSpeechRecognition() {
// get output div reference
var output = document.getElementById("output");
// get action element reference
var action = document.getElementById("help");
// new speech recognition object
var SpeechRecognition = SpeechRecognition || webkitSpeechRecognition;
var recognition = new SpeechRecognition();
// This runs when the speech recognition service starts
recognition.onstart = function() {
action.innerHTML = "<small>listening, please speak...</small>";
};
recognition.onspeechend = function() {
action.innerHTML = "<small>stopped listening, hope you are done...</small>";
recognition.stop();
}
// This runs when the speech recognition service returns result
recognition.onresult = function(event) {
var transcript = event.results[0][0].transcript;
var confidence = event.results[0][0].confidence;
output.innerHTML = "<b></b> " + transcript + "<br/> <b></b> " ;
output.classList.remove("hide");
};
// start recognition
recognition.start();
}
</script>
<!-- partial -->
<script src='https://use.fontawesome.com/releases/v5.0.13/js/all.js'></script>
</body>
</html>
recognition.onend = (event) => {
//insert your code to display button here
}
Here's the template where my button and contactList1 reside:-
<template>
<div class="chat-app">
<button v-on:click="displayList1()">Contacts List 1</button> //Button
<Conversation :contact="selectedContact" :messages="messages" #new="saveNewMessage" v-bind:class="{conversation:conversation}" />
<ContactsList :contacts="contacts" #selected="startConversationWith" v-bind:class="{contactsList1:contactsList1}"/> //contactsList
</div>
</template>
The object is default set to false
data() {
return {
contactsList1: {
default: false,
},
},
Method:-
displayList1()
{
this.contactsList1 = false;
},
Style:-
<style lang="scss" scoped>
.chat-app {
display: flex;
}
.contactsList1 {
background-color: black;
}
</style>
Even after the object being false the css is being applied, can anyone tell me what's wrong. I am just a beginner, Please help.
Your data function is returning the object contactsList1 and the full path to check the data type is this.contactsList1.default
You should also name your variables differently.
So here is a basic example on how to bind a Boolean datatype to your component class:
new Vue({
el: "#app",
data() {
return {
firstClass: {
status: false
}
}
},
methods: {
changeColour() {
this.firstClass.status = true
}
}
})
.styleFirstClass {
background: red
}
.itemBox {
padding:30px;
margin:30px;
border: 1px solid #444;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<button #click="changeColour()">Click to bind class</button>
<div class="itemBox" :class="{styleFirstClass: firstClass.status}">
This is some text
</div>
</div>
I'm writing my first web component with Stencil.
It's a pills component published here : https://github.com/reservoir-dogs/rp-pills
The component code's :
import { Component, Prop, Watch, Event, EventEmitter } from '#stencil/core';
#Component({
tag: 'rp-pills',
styleUrl: 'rp-pills.scss',
shadow: false
})
export class RpPills {
#Prop() items: any[] = [];
#Prop() displayProperty: string;
#Prop({ mutable: true }) value: any;
#Prop() class: string;
#Prop() theme: string = 'default';
#Prop() emptyMessage: string = 'No item';
classes: string;
#Event() valueChange: EventEmitter;
onClick(item: any) {
this.value = item;
this.valueChange.emit(this.value);
}
#Watch('class')
#Watch('theme')
watchHandler() {
this.classes = `nav nav-pills ${this.theme} ${this.class}`;
}
render() {
if (this.items.length > 0)
return (
<ul class={this.classes}>
{this.items.map((item) =>
<li onClick={() => this.onClick(item)} class={this.value === item ? 'active' : ''} >
<a>{item[this.displayProperty]}</a>
</li>)}
</ul>
);
else
return (
<ul class={this.classes}>
<li class="empty">
<a>{this.emptyMessage}</a>
</li>
</ul>
);
}
}
This test work fine :
it('should work with a list of items and selected item', async () => {
const cmp = new RpPills();
cmp.valueChange = {
emit: () => { }
};
const spy = jest.spyOn(cmp.valueChange, 'emit');
cmp.onClick({name:'Coucou'});
expect(spy).toHaveBeenCalledWith({ name: 'Coucou' });
});
But my HTML sample and an integration in Ionic App does not work and return the following message : {"isTrusted":false}
HTML sample :
<!DOCTYPE html>
<html dir="ltr" lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=5.0">
<title>Stencil Component Starter</title>
<script src="/build/rppills.js"></script>
</head>
<style>
.orange .active a {
background-color: #ff0000;
}
.orange a {
background-color: #ff6a00;
}
div {
float: left;
clear: both;
}
</style>
<body>
<div>
<rp-pills display-property="name" class="nav-pills-bordered" theme="orange">
</rp-pills>
<span></span>
</div>
<div>
<rp-pills display-property="name" class="nav-justified">
</rp-pills>
<span></span>
</div>
<div>
<rp-pills display-property="name" class="nav-pills-bordered nav-justified">
</rp-pills>
<span></span>
</div>
<div>
<rp-pills class="nav-pills-bordered">
</rp-pills>
<span></span>
</div>
<div>
<rp-pills empty-message="Aucun message" class="nav-pills-bordered">
</rp-pills>
<span></span>
</div>
<div>
<rp-pills>
</rp-pills>
<span></span>
</div>
<script>
var cmps = document.querySelectorAll('rp-pills');
for (var i = 0; i < cmps.length; i++) {
var cmp = cmps[i];
if (cmp.attributes.length > 0 && cmp.attributes[0].name == 'display-property') {
cmp.value = { 'name': 'Coucou' };
cmp.items = [cmp.value, { 'name': 'Comment ca va ?' }, { 'name': 'Au revoir' }];
cmp.addEventListener('valueChange', (event) => { alert(JSON.stringify(event)); });
}
}
setInterval(() => {
var cmps = document.querySelectorAll('rp-pills');
var spans = document.querySelectorAll('span');
for (var i = 0; i < cmps.length; i++) {
if (cmps[i].value != undefined)
spans[i].innerText = cmps[i].value.name;
}
}, 1000);
</script>
</body>
</html>
2 errors
I tried to do that :
<rp-pills [items]="jeux" [(value)]="partie.jeu"></rp-pills>
The event of my Stencil component's :
is not compliant with angular two-way binding
contain a property 'detail' where there is my value
Use in Ionic App
HTML code
<rp-pills [items]="jeux" [value]="partie.jeu" (valueChange)="jeuChange($event.detail)"></rp-pills>
TypeScript code
jeuChange(jeu: Jeu) {
this.partie.jeu = jeu;
}
I want to get my current location using Google Maps Geolocation by Latitude and Longitude and I also want to set the origin as my current location but I'm not getting the current location. What should I do?
This is my code:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Draggable directions</title>
<style>
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script>
<script>
var rendererOptions = {
draggable: true
};
var directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
var lat, lon, mapOptions;
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(
function(position){
lat = position.coords.latitude;
lon = position.coords.longitude;
mapOptions = {
zoom: 7,
center: new google.maps.LatLng(lat, lon),
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('directionsPanel'));
google.maps.event.addListener(directionsDisplay, 'directions_changed', function() {
computeTotalDistance(directionsDisplay.getDirections());
});
calcRoute();
},
function(error){
alert('ouch');
});
}
else {
alert("Your browser doesn't support geolocations, please consider downloading Google Chrome");
}
}
function calcRoute() {
var request = {
origin: new google.maps.LatLng(lat, lon),
destination: new google.maps.LatLng(10.5200,76.2100),
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
function computeTotalDistance(result) {
var total = 0;
var myroute = result.routes[0];
for (var i = 0; i < myroute.legs.length; i++) {
total += myroute.legs[i].distance.value;
}
total = total / 1000.0;
document.getElementById('total').innerHTML = total + ' km';
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas" style="float:left;width:70%; height:100%"></div>
<div id="directionsPanel" style="float:right;width:30%;height 100%">
<p>Total Distance: <span id="total"></span></p>
</div>
</body>
</html>
I am using J Vector Map (http://jvectormap.com/documentation/javascript-api/) to create a map of the United States.
What I want to be able to do is have a button for each state that you can click on and have the corresponding region in the map be selected (or unselected, if it already was selected). I am trying to use map.setSelectedRegion for this, but I can't get any of the code to work. Currently trying map.setSelectedRegion("US-CA") to no avail.
Any ideas on what to do?
Thanks!
There seem to be a lot of request for linking links with jvectormap.
I've put together a jsfiddle here: http://jsfiddle.net/3xZ28/117/
HTML
<ul id="countries">
<li>Romania</li>
<li>Australia</li>
</ul>
<div id="world-map" style="width: 600px; height: 400px"></div>
JS
var wrld = {
map: 'world_mill_en',
regionStyle: {
hover: {
"fill": 'red'
}
}
};
function findRegion(robj, rname) {
var code = '';
$.each(robj, function (key) {
if ( unescape(encodeURIComponent(robj[key].config.name)) === unescape(encodeURIComponent(rname)) ) {
code = key;
};
});
return code;
};
$(document).ready(function () {
$('#world-map').vectorMap(wrld);
var mapObj = $('#world-map').vectorMap('get', 'mapObject');
$('#countries').on('mouseover mouseout', 'a:first-child', function (event) {
// event.preventDefault();
var elem = event.target,
evtype = event.type,
cntrycode = findRegion(mapObj.regions, $(elem).text());
if (evtype === 'mouseover') {
mapObj.regions[cntrycode].element.setHovered(true);
} else {
mapObj.regions[cntrycode].element.setHovered(false);
};
});
});
Once you've set the handle
var mapObject = $('#your_map_div_id').vectorMap('get', 'mapObject');
Just use the built in function setSelectedRegions (mind the "s"):
mapObject.setSelectedRegions(your_region_code); //to set
mapObject.setSelectedRegions({your_region_code:false}); //to unset
If it still doesn't work, post your code, maybe it's something else.
This code is outdated, below is updated version of the code, according jvectormap latest API. Here is demo snippet:
<!DOCTYPE html>
<html>
<head>
<title>jVectorMap demo</title>
<link rel="stylesheet" href="jqvmap.min.css" type="text/css" media="screen"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="jquery.vmap.min.js"></script>
<script src="jquery.vmap.world.js"></script>
<script>
jQuery(document).ready(function () {
$('#vmap').vectorMap({
map: 'world_en',
backgroundColor: '#2f95c9',
color: '#ffffff',
hoverOpacity: 0.7,
selectedColor: '#666666',
enableZoom: true,
showTooltip: true,
scaleColors: ['#C8EEFF', '#006491'],
normalizeFunction: 'polynomial',
regionsSelectableOne: false,
regionsSelectable: false,
series: {
regions: [{
scale: ['#C8EEFF', '#0071A4'],
normalizeFunction: 'polynomial'
}]
}
});
var mapObj = $('#vmap').data('mapObject');
$('#countries').on('mouseover mouseout', 'a:first-child', function (event) {
// event.preventDefault();
var elem = event.target,
evtype = event.type;
if (evtype === 'mouseover') {
mapObj.select($(elem).attr('id'));
} else {
mapObj.deselect($(elem).attr('id'));
};
});
});
</script>
</head>
<body>
<ul id="countries">
<li><a id="RO" href="">Romania</a></li>
<li><a id="AU" href="">Australia</a></li>
</ul>
<div id="vmap" style="width: 100vw; height: 100vh;"></div>
</body>
</html>