255
expect(document.activeElement.id).toEqual('child-b');
256
document.activeElement.blur();
257
});
258
+
259
+ // @gate enableFragmentRefs
260
+ it('keeps focus on the first focusable child if already focused', async () => {
261
+ const fragmentRef = React.createRef();
262
+ const root = ReactDOMClient.createRoot(container);
263
+
264
+ function Test() {
265
+ return (
266
+ <Fragment ref={fragmentRef}>
267
+ <a id="child-a" href="/">
268
+ A
269
+ </a>
270
+ <a id="child-b" href="/">
271
+ B
272
+ </a>
273
+ </Fragment>
274
+ );
275
+ }
276
+
277
+ await act(() => {
278
+ root.render(<Test />);
279
+ });
280
+
281
+ // Focus the first child manually
282
+ document.getElementById('child-a').focus();
283
+ expect(document.activeElement.id).toEqual('child-a');
284
+
285
+ // Calling fragment.focus() should keep focus on child-a,
286
+ // not skip to child-b
287
+ await act(() => {
288
+ fragmentRef.current.focus();
289
+ });
290
+ expect(document.activeElement.id).toEqual('child-a');
291
+ document.activeElement.blur();
292
+ });
293
+
294
+ // @gate enableFragmentRefs
295
+ it('keeps focus on a nested child if already focused', async () => {
296
+ const fragmentRef = React.createRef();
297
+ const root = ReactDOMClient.createRoot(container);
298
+
299
+ function Test() {
300
+ return (
301
+ <Fragment ref={fragmentRef}>
302
+ <div>
303
+ <input id="nested-input" />
304
+ </div>
305
+ <a id="sibling-link" href="/">
306
+ Link
307
+ </a>
308
+ </Fragment>
309
+ );
310
+ }
311
+
312
+ await act(() => {
313
+ root.render(<Test />);
314
+ });
315
+
316
+ // Focus the nested input manually
317
+ document.getElementById('nested-input').focus();
318
+ expect(document.activeElement.id).toEqual('nested-input');
319
+
320
+ // Calling fragment.focus() should keep focus on nested-input
321
+ await act(() => {
322
+ fragmentRef.current.focus();
323
+ });
324
+ expect(document.activeElement.id).toEqual('nested-input');
325
+ document.activeElement.blur();
326
+ });
327
+
328
+ // @gate enableFragmentRefs
329
+ it('focuses the first focusable child in a fieldset', async () => {
330
+ const fragmentRef = React.createRef();
331
+ const root = ReactDOMClient.createRoot(container);
332
+
333
+ function Test() {
334
+ return (
335
+ <Fragment ref={fragmentRef}>
336
+ <fieldset>
337
+ <legend>Shipping</legend>
338
+ <input id="street" name="street" />
339
+ <input id="city" name="city" />
340
+ </fieldset>
341
+ </Fragment>
342
+ );
343
+ }
344
+
345
+ await act(() => {
346
+ root.render(<Test />);
347
+ });
348
+ await act(() => {
349
+ fragmentRef.current.focus();
350
+ });
351
+ expect(document.activeElement.id).toEqual('street');
352
+ document.activeElement.blur();
353
+ });
354
});
355
356
describe('focusLast()', () => {