import React, { useEffect, useState } from 'react' import { DecoderState, useSpeechContext } from '@speechly/react-client' import styled from 'styled-components' import { Info } from './Info' import { SpeechlyUiEvents } from '../types' export enum NotificationType { info = 'info', warning = 'warning', } export type NotificationItem = { type: NotificationType notificationId: string message: string footnote?: string visible: boolean } let NotificationId: number = 0 export const Notifications: React.FC = props => { const { clientState } = useSpeechContext() const [notification, setNotification] = useState(null) /* { type: NotificationType.info, message: "Could not find 'Good vibes pants'", footnote: "Try: 'Sneakers'", visible: true, } { type: NotificationType.warning, message: "Bad audio. Please say again.", visible: true, }, { type: NotificationType.warning, message: "Sorry, all we hear is silence.", visible: true, }, { type: NotificationType.info, message: "Please say again", footnote: 'Try: "Sneakers"', visible: true, } */ useEffect(() => { const subDismiss = PubSub.subscribe( SpeechlyUiEvents.DismissNotification, (message: string, payload: { state: DecoderState }) => { hideHints() }, ) const subNotification = PubSub.subscribe( SpeechlyUiEvents.Notification, (message: string, payload: { message: string, footnote?: string }) => { setNotification({ type: NotificationType.info, notificationId: `msg-${NotificationId++}`, message: payload.message, footnote: payload.footnote, visible: true, }) }, ) const subWarningNotification = PubSub.subscribe( SpeechlyUiEvents.WarningNotification, (message: string, payload: { message: string, footnote?: string }) => { setNotification({ type: NotificationType.warning, notificationId: `msg-${NotificationId++}`, message: payload.message, footnote: payload.footnote, visible: true, }) }, ) return () => { PubSub.unsubscribe(subNotification) PubSub.unsubscribe(subWarningNotification) PubSub.unsubscribe(subDismiss) } }, []) useEffect(() => { switch (clientState) { case DecoderState.Active: { hideHints() } } }, [clientState]) const hideHints = (): void => { setNotification(prev => (prev !== null ? { ...prev, visible: false } : null)) } return ( <> {notification?.type === NotificationType.info && (
{notification?.message} {notification?.footnote !== null && ( <>
{notification.footnote} )}
)} {notification?.type === NotificationType.warning && (
{notification?.message} {notification?.footnote !== null && ( <>
{notification?.footnote} )}
)} ) } const InfoIcon: React.FC<{ color: string }> = props => { return ( ) } const WarningIcon: React.FC<{ color: string }> = props => { return ( ) } const IconSvg = styled.svg` width: 1.5rem; height: 1.5rem; flex-shrink: 0; margin-right: 0.5rem; margin-bottom: auto; `