UNPKG

@hex2r/react-announcer

Version:

Accessible announcer component for React apps using the Context API. Renders live-region messages for screen readers and provides a simple hook for dispatching announcements from anywhere in your component tree.

3 lines (2 loc) 1.11 kB
import e,{createContext as r,useState as t,useCallback as i,useMemo as n,useContext as s}from"react";import{v4 as o}from"uuid";const a=r(void 0),c=({children:r})=>{const[s,c]=t([]),l=i(({message:e,assertive:r=!1})=>{const t={id:o(),message:e,assertive:r};c(e=>[...e,t])},[]),u=n(()=>({announce:l}),[l]);return e.createElement(a.Provider,{value:u},r(s))},l=()=>{const e=s(a);if(!e)throw new Error("useAnnouncer must be used within the AnnouncerProvider");return e},u={position:"absolute",width:"1px",height:"1px",padding:0,margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0};function d({announcements:r,srOnlySupported:t=!1,stackLimit:i=4}){const n=t?{className:"sr-only"}:{style:u};return e.createElement("div",Object.assign({role:"region","aria-live":"polite","aria-atomic":"true"},n),r.slice(-i).map(({id:r,assertive:t,message:i})=>e.createElement("div",Object.assign({key:r,role:t?"alert":"status","aria-live":t?"assertive":"polite"},n),i)))}export{d as AnnouncementRegion,a as AnnouncerContext,c as AnnouncerProvider,l as useAnnouncer}; //# sourceMappingURL=index.esm.js.map