@shopgate/engage
Version:
Shopgate's ENGAGE library.
70 lines (69 loc) • 2.04 kB
JavaScript
import React, { useState, useLayoutEffect, useCallback } from 'react';
import PropTypes from 'prop-types';
import { UIEvents } from '@shopgate/engage/core';
import LiveMessage from "../LiveMessage";
import { EVENT_LIVE_MESSAGE, LIVE_MESSAGE_TYPE_ASSERTIVE, LIVE_MESSAGE_TYPE_POLITE } from "./constants";
/**
* The LiveMessenger component can be used to broadcast `aria-live` messages to assistive
* technology. It can be placed somewhere within the DOM, and receives its updates via
* EVENT_LIVE_MESSAGE event.
* @param {string} id An optional id for the messenger.
* @returns {JSX}
*/
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
const LiveMessenger = ({
id
}) => {
const [assertive, setAssertive] = useState({
message: '',
params: null
});
const [polite, setPolite] = useState({
message: '',
params: null
});
const handleMessage = useCallback((message, options) => {
const {
type = LIVE_MESSAGE_TYPE_POLITE,
id: instanceId = null,
params = null
} = options;
if (id !== instanceId) {
return;
}
if (type === LIVE_MESSAGE_TYPE_ASSERTIVE) {
setAssertive({
message,
params
});
} else if (type === LIVE_MESSAGE_TYPE_POLITE) {
setPolite({
message,
params
});
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
useLayoutEffect(() => {
UIEvents.addListener(EVENT_LIVE_MESSAGE, handleMessage);
return () => {
UIEvents.removeListener(EVENT_LIVE_MESSAGE, handleMessage);
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return /*#__PURE__*/_jsxs("div", {
children: [/*#__PURE__*/_jsx(LiveMessage, {
"aria-live": "assertive",
message: assertive.message,
params: assertive.params
}), /*#__PURE__*/_jsx(LiveMessage, {
"aria-live": "polite",
message: polite.message,
params: polite.params
})]
});
};
LiveMessenger.defaultProps = {
id: null
};
export default LiveMessenger;