feat: Paste where context menu was opened by johnnesky · Pull Request #9093 · RaspberryPiFoundation/blockly

The basics

The details

Resolves

Fixes #9088

Proposed Changes

I updated the KeyboardShortcut callback for pasteShortcut to detect whether the initiating event is a PointerEvent, in which case it infers that the callback was called by a context menu item that wraps the callback. (Otherwise, the event would typically be a KeyboardEvent.) If a context menu was used, then the location of the PointerEvent is used as the location where the block will be pasted.

Reason for Changes

It is commonly expected that if a context menu is used to add a block, then the block will be added where the context menu was opened.

Test Coverage

I have not created any new unit tests for this yet.

Documentation

Probably none needed beyond the code comment I added, although the behavior might be unexpected if someone encounters a different situation where a KeyboardShortcut callback sees a PointerEvent, or if a different context menu implementation forwards events differently.

Additional Information

There are a few ways we could implement this. I think the above strategy is the least amount of code changes and the only solution that can be done in a single PR, but it makes some assumptions.

Alternatively, we could alter the API of KeyboardShortcuts to allow explicitly providing a location at which to apply the shortcut's effects, and then update the context menu item wrapper (which is in a different repo) to provide this location. This strategy might be a little more robust, although it's a little weird that a KeyboardShortcut is being used for an action that has a location in the first place and this would just be further committing to that weirdness.

Maybe a better alternative would be to refactor the copying and pasting to be public functions outside of the KeyboardShortcut interface, so that external code can call them more directly. Notably, there's an existing copyInternal function that could be useful for this, but it's currently private to core Blockly and it doesn't share clipboard data with the KeyboardShortcut version for some reason. After we make these changes to this repo, we would need to update the external repo to make use of the new API.