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

Give ui.browseableMessage the ability to show copy and close buttons after the message, and add buttons to some instances (2nd try) #5

Closed
wants to merge 2 commits into from

Conversation

korbit-ai[bot]
Copy link

@korbit-ai korbit-ai bot commented Aug 21, 2024

Link to issue number:

Fixes #14641
Addresses #16995
Addresses #16996

Summary of the issue:

In #14641 @Qchristensen reported that some users are confused by browseableMessages, and their lack of definite closure mechanisms.
In the conversation, it was pointed out that in some cases, a user might also desire a copy button.
During work on the PR (originally #16369), it was requested that the copy button be given an accelerator key.

Description of user facing changes

Added copy and close buttons to some browseableMessages, and the capability to add them to others.

Description of development approach

  • Thanks to @michaelDCurran, we now use a Scripting.Dictionary to carry arbitrary query-string-equivalent style parameters to the mshtml instance behind browseableMessage. Thus, it is now possible to pass in values for two new buttons, and various translatable messages, without any contortions.
  • Tried different methods in the JS and CSS of message.html, and eventually settled on one which displayed the two buttons side-by-side, under a separator. If neither button's label is supplied, the div containing the HR and buttons remains hidden.
  • The "Copy" button can be activated with Ctrl+Shift+C, and the "Close" button by Escape. Ctrl+Shift+C is indicated to the user via an accessibility label.
  • Per the issue, modified the Report Link Destination, Report Current Selection, and Report Character Information messages, to have both Copy and Close buttons.
  • Per request in PR comments, used a live region to present a "Copy complete" or "copy failed" message to the user. This message remains on screen for five seconds.
  • Went back to the method adopted in #12005, to solve #16995.
    • A text only message, can not be assigned to the div via '.innerText' inside a pre element, without causing extra blank lines to appear for each blank line.
    • Additionally, if a pre is created, assigning to it by .innerText, results in the same.
    • So does styling a div with "white-space: pre" (or any of its variants), and then assigning through .innerText.
    • The only thing that works, is assigning a text string already containing the <pre> element, to the div's .innerHTML method, as was originally done in #12005.
    • I tried, per @michaelDCurran's guidance in In ui.browseableMessage, every other line is empty nvaccess/nvda#16995 (comment), changing various things in the MSHTML virtual buffer code, but got nowhere. This needs further exploration. by someone with more familiarity with screen layout's interaction with NVDAHelper.

Miscellaneous additional development items

  • The AI suggested covering for more failures in the initialization and configuration of MSHTML. I used its suggested exception checking, but added a private function to display an error message to the user when one of the components fail, so at least some kind of user notice can be given. I based it on the already extant private function for messaging the user if a browseableMessage is called on a secure screen.
  • Both of the warning functions for browseableMessage unavailable situations, are now self-contained, with respect to wx.
  • Fixed up some docstring parameter listings to match modern format.
  • Added an immediate return if the MSHTML window is opened without providing the dialog arguments (i.e. the message and title, at least). That situation should never actually occur, but in the unlikely event that a failure passes the error checking we have in browseableMessage, this will return immediately, instead of stranding the user in a blank window with no obvious close mechanism. This is not logged or reported to the user directly.

Testing strategy:

  • Tested using the report link destination window, that the basic functionality worked as expected.
  • Tested that copying using the copy button, correctly formatted the clipboard result. That is so far only possible when using .innerHTML.
  • Tested that presentation with screen layout off, does not include extra blank lines (per #16995).
  • Tested that the component failure error dialog works correctly, by causing a component to fail.
  • Tested that the Can't run on UAC, etc. screens warning works correctly after changes.

Known issues with pull request:

  • Ctrl+Shift+C is not an ideal key to activate the copy button, and it can not be changed by translators.
  • In addition to the others, it was requested that the OCR results window provide a close button. This is more difficult, and I'd rather leave it to a separate PR in case it is not desired after all.
  • Security of text only messages, is currently only provided by Python's html.escape(). I don't believe security is degraded by this PR, but it is not improved, either.

Code Review Checklist:

  • Documentation:
    • Change log entry
    • User Documentation
    • Developer / Technical Documentation
    • Context sensitive help for GUI changes
  • Testing:
    • Unit tests
    • System (end to end) tests
    • Manual testing
  • UX of all users considered:
    • Speech
    • Braille
    • Low Vision
    • Different web browsers
    • Localization in other languages / culture than English
  • API is compatible with existing add-ons.
  • Security precautions taken.

Summary by CodeRabbit

  • New Features

    • Added "Copy" and customizable "Close" buttons to message dialogs, improving usability.
    • Enhanced key handling for closing windows and copying text using keyboard shortcuts.
    • Introduced user notifications for copy operation success or failure, providing immediate feedback.
  • Bug Fixes

    • Improved error handling and user notifications for messaging components, ensuring reliability.
  • Documentation

    • Updated user documentation to reflect new interactive elements and usability improvements.

Description by Korbit AI

What change is being made?

Enhance ui.browseableMessage to support optional "Copy" and "Close" buttons, and integrate these buttons into the Report link destination, Character formatting information, and Speak selection dialogs.

Why are these changes being made?

These changes improve user convenience by allowing users to easily copy message content to the clipboard and close the message window directly from the dialog. This enhancement addresses user feedback requesting more interactive and accessible message dialogs.

Luke Davis and others added 2 commits August 16, 2024 06:07
…instances.

* Report link destination, Speak selection command, & character formatting browseableMessages given close and copy buttons.
* Added a new browsable message component failure messaging function.
* Used a live region to alert users about the status of the copy operation.
* Added some further error handling, as proposed by the AI.
* Change onkeypress to onkeydown, in order to pick up modifier keys in message.html.
* Used Ctrl+Shift+C for the copy button accelerator key, because Alt+C makes a Windows error ding.
* Switch to innerText from innerHTML where possible.
* Remove invalid language attribute on body element in message.html per review.
* Solve for MSHTML bug in the use of aria-labelledby.
* Close the MSHTML Window if args wasn't provided for some reason.
Copy link
Author

korbit-ai bot commented Aug 21, 2024

Clone of the PR nvaccess/nvda#17018

Copy link

My review is in progress 📖 - I will have feedback for you in a few minutes!

1 similar comment
Copy link
Author

korbit-ai bot commented Aug 21, 2024

My review is in progress 📖 - I will have feedback for you in a few minutes!

Copy link

coderabbitai bot commented Aug 21, 2024

Walkthrough

The changes involve enhancements to the user interface across multiple files, focusing on improving the functionality of message dialogs. Key updates include the addition of "Close" and "Copy" buttons in various UI components and modifications to function signatures to accommodate new parameters. These changes aim to provide a more interactive and user-friendly experience when managing messages and interactions within the application.

Changes

Files Change Summary
source/globalCommands.py Modified methods to enhance messaging functionality with new parameters for "copyButton" and "closeButton".
source/message.html Updated JavaScript functions for improved keyboard handling, added new functions for button actions, and modified HTML elements for better usability.
source/ui.py Enhanced error handling and updated function signatures to accept additional parameters for improved message handling and user feedback.
user_docs/en/changes.md Documented the addition of "Close" and "Copy" buttons, updated ui.browseableMessage function signatures to reflect new parameter options.

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.

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
Author

@korbit-ai korbit-ai bot left a comment

Choose a reason for hiding this comment

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

I have reviewed your code and did not find any issues!


Please note that I can make mistakes, and you should still encourage your team to review your code as well.

Copy link

@development-korbit-ai-mentor development-korbit-ai-mentor bot left a comment

Choose a reason for hiding this comment

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

I have reviewed your code and found 1 potential issue.

Code Execution

  • Add error handling for windll.mshtml.ShowHTMLDialogEx to prevent unexpected behavior and silent failures.

Code Health

  • No additional comments for code health.

Comment on lines +205 to +212
windll.mshtml.ShowHTMLDialogEx(
gui.mainFrame.Handle,
moniker,
HTMLDLG_MODELESS,
byref(dialogArgsVar),
DIALOG_OPTIONS,
None,
)

Choose a reason for hiding this comment

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

category Functionality severity potentially major

It's recommended to add error handling for the windll.mshtml.ShowHTMLDialogEx call. If this operation fails, it could lead to unexpected behavior or silent failures. By catching potential exceptions and providing user feedback, we can improve the reliability of the browseableMessage function. Consider wrapping the call in a try-except block:

try:
    windll.mshtml.ShowHTMLDialogEx(
        gui.mainFrame.Handle,
        moniker,
        HTMLDLG_MODELESS,
        byref(dialogArgsVar),
        DIALOG_OPTIONS,
        None,
    )
except Exception as e:
    log.error(f"Failed to show HTML dialog: {e}")
    _warnBrowsableMessageComponentFailure(title)
    return

This change will ensure that users are informed if the browseable message cannot be displayed due to this specific failure.

Chat with Korbit by mentioning @development-korbit-ai-mentor, and give a 👍 or 👎 to help Korbit improve your reviews.

Copy link

Copy link

System configuration at time of review:

- category__name: {'enabled': True, 'user_values': {'minimum_severity': 'nit'}}
- category__database_operations: {'enabled': True, 'user_values': {'minimum_severity': 'nit'}}
- category__documentation: {'enabled': True, 'user_values': {'minimum_severity': 'nit'}}
- category__logging: {'enabled': True, 'user_values': {'minimum_severity': 'nit'}}
- category__error_handling: {'enabled': True, 'user_values': {'minimum_severity': 'nit'}}
- category__systems_and_environment: {'enabled': True, 'user_values': {'minimum_severity': 'nit'}}
- category__objects_and_data_structures: {'enabled': True, 'user_values': {'minimum_severity': 'nit'}}
- category__tests: {'enabled': False, 'user_values': {'minimum_severity': 'nit'}}
- category__readability_and_maintainability: {'enabled': True, 'user_values': {'minimum_severity': 'nit'}}
- category__asynchronous_processing: {'enabled': True, 'user_values': {'minimum_severity': 'nit'}}
- category__design_patterns: {'enabled': True, 'user_values': {'minimum_severity': 'nit'}}
- category__third_party_libraries: {'enabled': True, 'user_values': {'minimum_severity': 'nit'}}
- category__performance: {'enabled': True, 'user_values': {'minimum_severity': 'nit'}}
- category__security: {'enabled': True, 'user_values': {'minimum_severity': 'nit'}}
- pull_request_review_schedule: {'enabled': True, 'user_values': {'review_schedule': 'non-draft'}}
- maximum_shown_issues: {'enabled': True, 'user_values': {'max_issues': 10}}
- auto_pr_description: {'enabled': True, 'user_values': {}}
- category__functionality: {'enabled': True, 'user_values': {'minimum_severity': 'nit'}}

Copy link

@coderabbitai full review

Copy link

@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: 1

Outside diff range, codebase verification and nitpick comments (2)
user_docs/en/changes.md (2)

27-27: Replace the placeholder with the correct issue or PR number.

The entry uses #placeholder, which should be replaced with the actual issue or PR number for accurate tracking.

* The Report link destination, Character formatting information, and Speak selection dialogs, now include "Close" and "Copy" buttons for user convenience. (#14641, @XLTechie)

63-63: Replace the placeholder with the correct issue or PR number.

The entry uses #placeholder, which should be replaced with the actual issue or PR number for accurate tracking.

* `ui.browseableMessage` may now be called with options to present a button for copying to clipboard, and/or a button for closing the window. (#14641, @XLTechie)

Comment on lines +20 to +39
function onCopyButtonPress() {
// Copy code came from http://www.codestore.net/store.nsf/unid/DOMM-4QHQE8/
var rng = document.body.createTextRange();
rng.moveToElementText(messageDiv);
rng.scrollIntoView();
rng.select();
var success = rng.execCommand("Copy");
rng.collapse(false);
rng.select();
copyStatusDiv.innerHTML = '<p id="copyStatusText" style="font-weight:bold; text-align:center;"></p>';
if (success) { // Notify the user about the copy result
copyStatusText.innerText = args.item('copySuccessfulAlertText');
} else {
copyStatusText.innerText = args.item('copyFailedAlertText');
}
};
// Time out the user alert message
setTimeout(function() {
copyStatusDiv.innerHTML = '';
}, copyStatusTimeout);
}
Copy link

Choose a reason for hiding this comment

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

Consider modernizing the copy functionality.

The current implementation uses createTextRange, which is specific to older versions of Internet Explorer. Consider using the Clipboard API for broader browser support.

Suggested change
function onCopyButtonPress() {
// Copy code came from http://www.codestore.net/store.nsf/unid/DOMM-4QHQE8/
var rng = document.body.createTextRange();
rng.moveToElementText(messageDiv);
rng.scrollIntoView();
rng.select();
var success = rng.execCommand("Copy");
rng.collapse(false);
rng.select();
copyStatusDiv.innerHTML = '<p id="copyStatusText" style="font-weight:bold; text-align:center;"></p>';
if (success) { // Notify the user about the copy result
copyStatusText.innerText = args.item('copySuccessfulAlertText');
} else {
copyStatusText.innerText = args.item('copyFailedAlertText');
}
};
// Time out the user alert message
setTimeout(function() {
copyStatusDiv.innerHTML = '';
}, copyStatusTimeout);
}
function onCopyButtonPress() {
try {
navigator.clipboard.writeText(messageDiv.innerText).then(() => {
copyStatusText.innerText = args.item('copySuccessfulAlertText');
}, () => {
copyStatusText.innerText = args.item('copyFailedAlertText');
});
} catch (err) {
copyStatusText.innerText = args.item('copyFailedAlertText');
}
setTimeout(function() {
copyStatusDiv.innerHTML = '';
}, copyStatusTimeout);
}

@furwellness
Copy link
Owner

/review

Copy link

PR Reviewer Guide 🔍

⏱️ Estimated effort to review: 3 🔵🔵🔵⚪⚪
🧪 No relevant tests
🔒 Security concerns

XSS vulnerability:
In the browseableMessage function in source/ui.py, there's a potential for XSS attacks if the message parameter contains malicious HTML when isHtml is True. The function logs a warning but doesn't sanitize the input, which could lead to the execution of arbitrary JavaScript in the context of the NVDA application. This could potentially lead to unauthorized access or data exfiltration. It's recommended to implement proper HTML sanitization before rendering user-provided HTML content.

⚡ Key issues to review

Error Handling
The new function _warnBrowsableMessageComponentFailure is called in multiple places, but it's not clear how it handles different error scenarios. Consider adding more specific error messages or logging for different failure modes.

Security Concern
The function browseableMessage now accepts HTML content directly. There's a warning log, but no sanitization is performed, which could lead to XSS vulnerabilities if the input is not properly validated elsewhere.

Accessibility
The new copy and close buttons are added, but it's not clear if they are fully accessible. Consider adding ARIA attributes or ensuring they work well with screen readers.

Copy link

/review

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

Successfully merging this pull request may close these issues.

1 participant