Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -1962,6 +1962,22 @@ const Example = () => {
};
```

#### activeId

Type: `string | undefined`

[`id`](#id) of the currently focused component. If there's no active focus on component right now, the value is `undefined`.

```js
import {useFocusManager} from 'ink';

const Example = () => {
const {activeId} = useFocusManager();

return <Text>Focused component ID: {activeId ?? "-"}</Text>;
};
```

### useIsScreenReaderEnabled()

Returns whether a screen reader is enabled. This is useful when you want to render different output for screen readers.
Expand Down
6 changes: 6 additions & 0 deletions src/hooks/use-focus-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,11 @@ type Output = {
Switch focus to the element with provided `id`. If there's no element with that `id`, focus will be given to the first focusable component.
*/
focus: Props['focus'];

/**
Contains the `id` of the currently focused component. If no component is focused, the value will be `undefined`.
*/
activeId: Props['activeId'];
};

/**
Expand All @@ -40,6 +45,7 @@ const useFocusManager = (): Output => {
focusNext: focusContext.focusNext,
focusPrevious: focusContext.focusPrevious,
focus: focusContext.focus,
activeId: focusContext.activeId,
};
};

Expand Down
27 changes: 27 additions & 0 deletions test/focus.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -508,3 +508,30 @@ test('skips disabled elements when wrapping around from the front', async t => {
['First', 'Second ✔', 'Third'].join('\n'),
);
});

test('the focus helper reports whichever id currently holds focus', async t => {
const stdout = createStdout();
const stdin = createStdin();

let activeId: string | undefined;

function TestActiveId() {
const focusManager = useFocusManager();
activeId = focusManager.activeId;

return <Test autoFocus />;
}

render(<TestActiveId />, {
stdout,
stdin,
debug: true,
});

await delay(100);
t.not(activeId, undefined);

emitReadable(stdin, '\u001B');
await delay(100);
t.is(activeId, undefined);
});