Paste block at location of context menu?

165 views
Skip to first unread message

Alex Lynch

unread,
May 10, 2017, 1:59:47 PM5/10/17
to Blockly
When the context menu is opened, the following code is run:

Blockly.WidgetDiv.position(x, y, windowSize, scrollOffset, rtl);
(contextmenu.js, 114)

I then add this below it:
Blockly.ContextMenu.LastLeft = parseInt(Blockly.WidgetDiv.DIV.style.left);
Blockly.ContextMenu.LastTop = parseInt(Blockly.WidgetDiv.DIV.style.top);

I'd then like to paste a block at the location of the location of the menu, so I do the following:

var workspace = Blockly.getMainWorkspace();

var xmlDoc = Blockly.Xml.textToDom(xmlString);
xmlDoc.childNodes[0].setAttribute('x', 0);
xmlDoc.childNodes[0].setAttribute('y', 0);

var blockIds = Blockly.Xml.domToWorkspace(xmlDoc, workspace);
var block = workspace.getBlockById(blockIds[0]);

block.moveBy(
Blockly.ContextMenu.LastLeft,
Blockly.ContextMenu.LastTop);

But this doesn't put the block in the same place. In fact it seems offset to the right by some value. Also if I move the scrollbars it changes the location it pastes at. Is there some metric I need to subtract/add that i am missing perhaps?

Rachel Fenichel

unread,
May 10, 2017, 4:39:39 PM5/10/17
to Blockly
Hi Alex,

Are you aiming to put the block at the same location as the context menu specifically, or are you using that as a proxy for the same location as the right click?

You're running into problems with coordinate systems.  The context menu's coordinates are relative to the top left corner of your browser window--window coordinates, as explained on this page.

Block positions are in workspace coordinates.  These are positions on the imaginary plane that is a Blockly workspace.  The origin of this coordinate system is the top left corner of the visible workspace when you first inject Blockly, and that origin moves relative to the window coordinate origin when you scroll the page or the blockly workspace.  Workspace coordinates do not change as you zoom in and out with the Blockly zoom buttons.

Hope this helps,
Rachel

Alex Lynch

unread,
May 11, 2017, 2:04:21 PM5/11/17
to Blockly
Hi Rachel,

Yes i wanted to use the mouse position, but seeing as you can only get that from mouse events (I think?) I decided to use the context menu position. This worked in the end:


var metrics = workspace.getMetrics();
newBlock.moveBy(
Blockly.ContextMenu.LastLeft + metrics.viewLeft - metrics.toolboxWidth,
Blockly.ContextMenu.LastTop + metrics.viewTop);

Reply all
Reply to author
Forward
0 new messages