|
1 | | -import React, { memo, forwardRef, useState, useEffect } from "react"; |
| 1 | +import React, { memo, forwardRef, useState, useEffect, useRef } from "react"; |
2 | 2 | import type { ReactNode } from "react"; |
3 | 3 | import type { FrClassName } from "./lib/generatedFromCss/classNames"; |
4 | 4 | import { symToStr } from "tsafe/symToStr"; |
@@ -81,14 +81,37 @@ export const Alert = memo( |
81 | 81 |
|
82 | 82 | const [isClosed, setIsClosed] = useState(props_isClosed ?? false); |
83 | 83 |
|
| 84 | + const [buttonElement, setButtonElement] = useState<HTMLButtonElement | null>(null); |
| 85 | + |
| 86 | + const refShouldButtonGetFocus = useRef<boolean>(false); |
| 87 | + |
84 | 88 | useEffect(() => { |
85 | 89 | if (props_isClosed === undefined) { |
86 | 90 | return; |
87 | 91 | } |
| 92 | + setIsClosed(isClosed => { |
| 93 | + if (isClosed && !props_isClosed) { |
| 94 | + refShouldButtonGetFocus.current = true; |
| 95 | + } |
88 | 96 |
|
89 | | - setIsClosed(props_isClosed); |
| 97 | + return props_isClosed; |
| 98 | + }); |
90 | 99 | }, [props_isClosed]); |
91 | 100 |
|
| 101 | + useEffect(() => { |
| 102 | + if (!refShouldButtonGetFocus.current) { |
| 103 | + return; |
| 104 | + } |
| 105 | + |
| 106 | + if (buttonElement === null) { |
| 107 | + //NOTE: This should not be reachable |
| 108 | + return; |
| 109 | + } |
| 110 | + |
| 111 | + refShouldButtonGetFocus.current = false; |
| 112 | + buttonElement.focus(); |
| 113 | + }, [buttonElement]); |
| 114 | + |
92 | 115 | const onCloseButtonClick = useConstCallback(() => { |
93 | 116 | if (props_isClosed === undefined) { |
94 | 117 | //Uncontrolled |
@@ -123,6 +146,7 @@ export const Alert = memo( |
123 | 146 | {/* TODO: Use our button once we have one */} |
124 | 147 | {isClosable && ( |
125 | 148 | <button |
| 149 | + ref={setButtonElement} |
126 | 150 | className={cx(fr.cx("fr-link--close", "fr-link"), classes.close)} |
127 | 151 | onClick={onCloseButtonClick} |
128 | 152 | > |
|
0 commit comments