Skip to content

Commit

Permalink
fix: prevent trapping keyboard focus (#3)
Browse files Browse the repository at this point in the history
  • Loading branch information
jmjuanes committed Sep 13, 2023
1 parent 5d6a922 commit 99fd006
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 2 deletions.
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,12 @@ CodeCake.create(parent, {
});
```

## Preventing keyboard trap

The `Tab` key is commonly used by developers to indent code. However, this can sometimes lead to unexpected behavior, where the focus remains trapped within the editor, disrupting the workflow. To address this, we have introduced the `Esc` `Tab` key combination to move to the next focusable element, and the `Esc` `Shift + Tab` key combination to move to the previous focusable element.

Please note that **we do not provide built-in help or a dedicated user interface for this feature**. This is because the editor is designed as a lightweight code editor component, not a standalone application. Users are encouraged to consult the documentation or any user guides provided within the context of the web application that incorporates this component for information on available keyboard shortcuts and features.

## License

CodeCake is released under the [MIT License](./LICENSE).
7 changes: 5 additions & 2 deletions codecake.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ export const create = (parent, options = {}) => {
let prevCode = "";
let focus = false;
let linesCount = -1;
let escKeyPressed = false;
const listeners = {}; // Store events listeners
const tab = options?.indentWithTabs ? "\t" : " ".repeat(options.tabSize || 4);
const endl = String.fromCharCode(10);
Expand Down Expand Up @@ -130,7 +131,7 @@ export const create = (parent, options = {}) => {
insertText(endl + indentation);
}
// Handle backspace
else if (event.key === "Backspace" || (event.key === "Tab" && event.shiftKey)) {
else if (event.key === "Backspace" || (event.key === "Tab" && !escKeyPressed && event.shiftKey)) {
if (window.getSelection().type === "Caret") {
let removeChars = 0;
const pos = savePosition();
Expand All @@ -148,10 +149,12 @@ export const create = (parent, options = {}) => {
}
}
// Handle insert tab
else if (event.key === "Tab" && !event.shiftKey) {
else if (event.key === "Tab" && !escKeyPressed && !event.shiftKey) {
event.preventDefault();
insertText(tab);
}
// Save if escape key has been pressed to avoid trapping keyboard focus
escKeyPressed = event.key === "Escape";
}
});
editor.addEventListener("keyup", event => {
Expand Down

0 comments on commit 99fd006

Please sign in to comment.