Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: focus [autofocus] element in a popup #2736

Merged
merged 2 commits into from
Jun 18, 2024
Merged

feat: focus [autofocus] element in a popup #2736

merged 2 commits into from
Jun 18, 2024

Conversation

limonte
Copy link
Member

@limonte limonte commented Jun 18, 2024

Summary by CodeRabbit

  • New Features

    • Enhanced focus behavior in modal dialogs by ensuring elements with the autofocus attribute receive initial focus.
  • Tests

    • Added a new end-to-end test case to verify the focus behavior of modal dialogs with the autofocus attribute.

Copy link
Contributor

coderabbitai bot commented Jun 18, 2024

Warning

Rate limit exceeded

@limonte has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 32 minutes and 35 seconds before requesting another review.

How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

Commits

Files that changed from the base of the PR and between a149618 and 24b8de0.

Walkthrough

The updates introduce a new test case in the Cypress end-to-end tests to verify autofocus behavior for modals. Additionally, the SweetAlert.js file incorporates a new focusAutofocus function to better manage focus in popups, ensuring elements with the autofocus attribute receive attention when a modal opens.

Changes

File Change Summary
cypress/e2e/accessibility.cy.js Added a new test case for verifying autofocus behavior in modal dialogs.
src/SweetAlert.js Introduced focusAutofocus function to handle initializing focus in popups and updated initFocus to utilize this new function.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant CypressTest
    participant ModalComponent
    participant SweetAlert

    User->>CypressTest: Trigger modal open
    CypressTest->>ModalComponent: Open modal
    ModalComponent->>SweetAlert: Request to initialize focus
    SweetAlert->>SweetAlert: Execute focusAutofocus
    SweetAlert->>ModalComponent: Set focus on autofocus element
    ModalComponent-->>User: Modal with autofocus active
Loading

Poem

In shadows of code where popups arise,
A sweet alert ensures your eyes,
Are guided to the autofocus bright,
Ensuring it's the first in sight.
Cypress tests in kind they sing,
Making sure the focus has the proper fling!
🐇✨


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

Outside diff range and nitpick comments (3)
src/SweetAlert.js (3)

Line range hint 77-77: Optimize performance by avoiding the use of the delete operator.

The use of the delete operator on properties (like globalState.timeout) can lead to performance degradations because it modifies the object's shape. Consider setting the property to undefined instead, which avoids these issues:

- delete globalState.timeout;
+ globalState.timeout = undefined;

Apply this change wherever the delete operator is used on properties.

Also applies to: 208-208


Line range hint 214-214: Use optional chaining for safer and cleaner code.

Consider using optional chaining when accessing properties on potentially null or undefined objects to prevent runtime errors:

- if (globalState.timeout && globalState.timeout.running) {
+ if (globalState.timeout?.running) {

This change ensures that the code is more robust and easier to read.

Also applies to: 354-354


Line range hint 353-358: Convert function expressions to arrow functions for consistency.

The function expressions used in the event handlers can be converted to arrow functions for better consistency and to avoid issues related to the this context:

- SweetAlert[key] = function (...args) {
+ SweetAlert[key] = (...args) => {
    if (currentInstance && currentInstance[key]) {
      return currentInstance[key](...args);
    }
    return null;
}

This change aligns with modern JavaScript practices and improves the readability of the code.

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between b856f8d and 462e8cc.

Files selected for processing (2)
  • cypress/e2e/accessibility.cy.js (1 hunks)
  • src/SweetAlert.js (1 hunks)
Files skipped from review due to trivial changes (1)
  • cypress/e2e/accessibility.cy.js
Additional context used
Biome
src/SweetAlert.js

[error] 77-77: Avoid the delete operator which can impact performance. (lint/performance/noDelete)

Unsafe fix: Use an undefined assignment instead.


[error] 208-208: Avoid the delete operator which can impact performance. (lint/performance/noDelete)

Unsafe fix: Use an undefined assignment instead.


[error] 214-214: Change to an optional chain. (lint/complexity/useOptionalChain)

Unsafe fix: Change to an optional chain.


[error] 354-354: Change to an optional chain. (lint/complexity/useOptionalChain)

Unsafe fix: Change to an optional chain.


[error] 353-358: This function expression can be turned into an arrow function. (lint/complexity/useArrowFunction)

Function expressions that don't use this can be turned into arrow functions.
Safe fix: Use an arrow function instead.


[error] 93-93: Do not add then to a class. (lint/suspicious/noThenProperty)

Comment on lines 261 to 267
const focusAutofocus = (domCache) => {
const autofocusElement = domCache.popup.querySelector('[autofocus]')
if (autofocusElement instanceof HTMLElement && dom.isVisible(autofocusElement)) {
autofocusElement.focus()
return true
}
return false
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ensure proper accessibility handling when focusing elements.

The focusAutofocus function correctly identifies and focuses an element with the [autofocus] attribute. However, consider verifying that this behavior aligns with accessibility standards, especially in scenarios where multiple autofocus elements might be present, which is generally discouraged but should still be handled gracefully.

Comment on lines 224 to 255
* Initialize focus in the popup:
*
* 1. If `toast` is `true`, don't steal focus from the document.
* 2. Else if there is an [autofocus] element, focus it.
* 3. Else if `focusConfirm` is `true` and confirm button is visible, focus it.
* 4. Else if `focusDeny` is `true` and deny button is visible, focus it.
* 5. Else if `focusCancel` is `true` and cancel button is visible, focus it.
* 6. Else focus the first focusable element in a popup (if any).
*
* @param {DomCache} domCache
* @param {SweetAlertOptions} innerParams
*/
const initFocus = (domCache, innerParams) => {
if (innerParams.toast) {
return
}

// TODO: this is dumb, remove `allowEnterKey` param in the next major version
if (!callIfFunction(innerParams.allowEnterKey)) {
blurActiveElement()
return
}

if (!focusButton(domCache, innerParams)) {
setFocus(-1, 1)
if (focusAutofocus(domCache)) {
return
}

if (focusButton(domCache, innerParams)) {
return
}

setFocus(-1, 1)
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Refactor initFocus to improve readability and maintainability.

The initFocus function has several conditional checks to determine where the focus should be set. To improve readability and maintainability, consider restructuring this function to reduce nesting and clarify the logic flow:

const initFocus = (domCache, innerParams) => {
  if (innerParams.toast) return;

  if (!callIfFunction(innerParams.allowEnterKey)) {
    blurActiveElement();
    return;
  }

  const focusHandlers = [
    () => focusAutofocus(domCache),
    () => focusButton(domCache, innerParams)
  ];

  for (const handler of focusHandlers) {
    if (handler()) return;
  }

  setFocus(-1, 1);
}

This refactoring uses an array of functions that encapsulate the focus logic, making it easier to add or remove focus strategies and improving the code's testability.

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
* Initialize focus in the popup:
*
* 1. If `toast` is `true`, don't steal focus from the document.
* 2. Else if there is an [autofocus] element, focus it.
* 3. Else if `focusConfirm` is `true` and confirm button is visible, focus it.
* 4. Else if `focusDeny` is `true` and deny button is visible, focus it.
* 5. Else if `focusCancel` is `true` and cancel button is visible, focus it.
* 6. Else focus the first focusable element in a popup (if any).
*
* @param {DomCache} domCache
* @param {SweetAlertOptions} innerParams
*/
const initFocus = (domCache, innerParams) => {
if (innerParams.toast) {
return
}
// TODO: this is dumb, remove `allowEnterKey` param in the next major version
if (!callIfFunction(innerParams.allowEnterKey)) {
blurActiveElement()
return
}
if (!focusButton(domCache, innerParams)) {
setFocus(-1, 1)
if (focusAutofocus(domCache)) {
return
}
if (focusButton(domCache, innerParams)) {
return
}
setFocus(-1, 1)
}
/**
* Initialize focus in the popup:
*
* 1. If `toast` is `true`, don't steal focus from the document.
* 2. Else if there is an [autofocus] element, focus it.
* 3. Else if `focusConfirm` is `true` and confirm button is visible, focus it.
* 4. Else if `focusDeny` is `true` and deny button is visible, focus it.
* 5. Else if `focusCancel` is `true` and cancel button is visible, focus it.
* 6. Else focus the first focusable element in a popup (if any).
*
* @param {DomCache} domCache
* @param {SweetAlertOptions} innerParams
*/
const initFocus = (domCache, innerParams) => {
if (innerParams.toast) return;
if (!callIfFunction(innerParams.allowEnterKey)) {
blurActiveElement();
return;
}
const focusHandlers = [
() => focusAutofocus(domCache),
() => focusButton(domCache, innerParams)
];
for (const handler of focusHandlers) {
if (handler()) return;
}
setFocus(-1, 1);
}

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 462e8cc and a149618.

Files selected for processing (2)
  • cypress/e2e/accessibility.cy.js (1 hunks)
  • src/SweetAlert.js (1 hunks)
Files skipped from review as they are similar to previous changes (1)
  • cypress/e2e/accessibility.cy.js
Additional context used
Biome
src/SweetAlert.js

[error] 77-77: Avoid the delete operator which can impact performance. (lint/performance/noDelete)

Unsafe fix: Use an undefined assignment instead.


[error] 208-208: Avoid the delete operator which can impact performance. (lint/performance/noDelete)

Unsafe fix: Use an undefined assignment instead.


[error] 214-214: Change to an optional chain. (lint/complexity/useOptionalChain)

Unsafe fix: Change to an optional chain.


[error] 356-356: Change to an optional chain. (lint/complexity/useOptionalChain)

Unsafe fix: Change to an optional chain.


[error] 355-360: This function expression can be turned into an arrow function. (lint/complexity/useArrowFunction)

Function expressions that don't use this can be turned into arrow functions.
Safe fix: Use an arrow function instead.


[error] 93-93: Do not add then to a class. (lint/suspicious/noThenProperty)

Additional comments not posted (2)
src/SweetAlert.js (2)

224-255: The refactoring of initFocus to include focusAutofocus is well-integrated. The step-by-step focusing logic is clear and maintainable. However, consider using an array of focus strategies as suggested in a previous review to further improve readability and maintainability.
[REFACTOR_SUGGESTion]

const initFocus = (domCache, innerParams) => {
  if (innerParams.toast) return;

  if (!callIfFunction(innerParams.allowEnterKey)) {
    blurActiveElement();
    return;
  }

  const focusHandlers = [
    () => focusAutofocus(domCache),
    () => focusButton(domCache, innerParams)
  ];

  for (const handler of focusHandlers) {
    if (handler()) return;
  }

  setFocus(-1, 1);
}

261-269: The implementation of focusAutofocus correctly focuses the first visible element with the [autofocus] attribute. This aligns with accessibility best practices as mentioned in the previous review. However, ensure that this behavior is consistent across all supported browsers, especially in handling multiple autofocus elements.

@limonte limonte merged commit 52fedf3 into main Jun 18, 2024
2 checks passed
@limonte limonte deleted the feat/autofocus branch June 18, 2024 10:40
github-actions bot pushed a commit that referenced this pull request Jun 18, 2024
# [11.12.0](v11.11.1...v11.12.0) (2024-06-18)

### Bug Fixes

* **styles:** :focus -> :focus-visible for buttons ([#2733](#2733)) ([9be8249](9be8249))

### Features

* focus `[autofocus]` element in a popup ([#2736](#2736)) ([52fedf3](52fedf3))
@limonte
Copy link
Member Author

limonte commented Jun 18, 2024

🎉 This PR is included in version 11.12.0 🎉

The release is available on:

Your semantic-release bot 📦🚀

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

1 participant