123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111import React,{ ReactElement, useCallback, useEffect, useState }from"react";import{
Message,
MessagePriority,
MessageQueue,
useAddMessage,
useQueue,}from"@react-md/alert";import{ Button }from"@react-md/button";import{ Fieldset, Form, Radio, useChoice }from"@react-md/form";import{ Text }from"@react-md/typography";import styles from"./UpdatingMessagePriority.module.scss";interfaceExampleMessageextendsRequired<Pick<Message,"messageId"|"messagePriority">>{
children:string;}constPRIORITIES: MessagePriority[]=["next","immediate","replace"];functionUpdatingMessagePriority(): ReactElement {const addMessage =useAddMessage<ExampleMessage>();const[priority, handlePriorityChange]=useChoice<MessagePriority>("next");const queue =useQueue<ExampleMessage>();const[running, setRunning]=useState(false);if(running &&!queue.length){setRunning(false);}const exampleNextFlow =useCallback(()=>{addMessage({
messageId:"message-1",
children:"First normal message",
messagePriority:"normal",});addMessage({
messageId:"message-2",
children:"Second normal message",
messagePriority:"normal",});setRunning(true);},[addMessage]);useEffect(()=>{if(!running){return;}const timeout = window.setTimeout(()=>{addMessage({
messageId: priority ==="replace"?"message-1":"message-3",
children:"Incoming Message!",
messagePriority: priority,});},2000);return()=>{
window.clearTimeout(timeout);};// only want to run on running chagnes// eslint-disable-next-line react-hooks/exhaustive-deps},[running]);return(<><divclassName={styles.output}><Texttype="headline-6"margin="bottom">
Message queue:
</Text>{queue.map((message, i)=>(// actually want to disable it since when the immediate flow is triggered, there will be two messageId// with "message-1" for a few milliseconds<prekey={i}>{JSON.stringify(message,null,2)}</pre>))}</div><FormonSubmit={exampleNextFlow}><Fieldsetlegend="Priority">{PRIORITIES.map((p)=>(<Radiokey={p}id={`priority-${p}`}name="messagePriority"label={`Example with "${p}" priority`}value={p}checked={p === priority}onChange={handlePriorityChange}/>))}</Fieldset><Buttonid="update-message-priority-submit"type="submit"disabled={queue.length >0}>
Create message
</Button></Form></>);}exportdefaultfunctionDemoContainer(): ReactElement {return(<MessageQueue<ExampleMessage> id="updating-message-priority"><Demo/></MessageQueue>);}