← All Exercises

Track Focus Return Targets for Nested Dialogs

intermediatejavascript~15min

Background

Dialogs opened from other dialogs must restore focus to the right trigger, which is a stack rather than a single saved element.

Problem

Write trackDialogs(operations) that processes open and close operations, keeps a stack of trigger ids, and reports which element should regain focus after each close.

Input

A JSON string with an operations array such as open:menu and close.

Output

A JSON string with the remaining stack and lastFocused keys.

Sample tests

Sample 1

Input: {"operations":["open:menu-button","open:search-button","close"]}
Expected: {"stack":["menu-button"],"lastFocused":"search-button"}

Sample 2

Input: {"operations":["close"]}
Expected: {"stack":[],"lastFocused":"body"}

Sample 3

Input: {"operations":["open:settings","close","close"]}
Expected: {"stack":[],"lastFocused":"body"}

Your solution

Learning objective

Manage focus restoration for stacked dialogs with a last-in-first-out trigger stack and a safe fallback.