scratch-blocks/core/tooltip.js

293 lines
8.9 KiB
JavaScript
Raw Normal View History

/**
* @license
* Visual Blocks Editor
*
* Copyright 2011 Google Inc.
2014-10-07 13:09:55 -07:00
* https://developers.google.com/blockly/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Library to create tooltips for Blockly.
* First, call Blockly.Tooltip.init() after onload.
* Second, set the 'tooltip' property on any SVG element that needs a tooltip.
* If the tooltip is a string, then that message will be displayed.
* If the tooltip is an SVG element, then that object's tooltip will be used.
* Third, call Blockly.Tooltip.bindMouseEvents(e) passing the SVG element.
* @author fraser@google.com (Neil Fraser)
*/
'use strict';
goog.provide('Blockly.Tooltip');
goog.require('goog.dom');
goog.require('goog.dom.TagName');
/**
* Is a tooltip currently showing?
*/
Blockly.Tooltip.visible = false;
2014-09-08 14:26:52 -07:00
/**
* Maximum width (in characters) of a tooltip.
*/
Blockly.Tooltip.LIMIT = 50;
/**
* PID of suspended thread to clear tooltip on mouse out.
* @private
*/
Blockly.Tooltip.mouseOutPid_ = 0;
/**
* PID of suspended thread to show the tooltip.
* @private
*/
Blockly.Tooltip.showPid_ = 0;
/**
2015-04-28 13:51:25 -07:00
* Last observed X location of the mouse pointer (freezes when tooltip appears).
* @private
*/
2015-04-28 13:51:25 -07:00
Blockly.Tooltip.lastX_ = 0;
/**
* Last observed Y location of the mouse pointer (freezes when tooltip appears).
* @private
*/
Blockly.Tooltip.lastY_ = 0;
/**
* Current element being pointed at.
* @private
*/
Blockly.Tooltip.element_ = null;
/**
* Once a tooltip has opened for an element, that element is 'poisoned' and
* cannot respawn a tooltip until the pointer moves over a different element.
* @private
*/
Blockly.Tooltip.poisonedElement_ = null;
/**
* Horizontal offset between mouse cursor and tooltip.
*/
Blockly.Tooltip.OFFSET_X = 0;
/**
* Vertical offset between mouse cursor and tooltip.
*/
Blockly.Tooltip.OFFSET_Y = 10;
/**
* Radius mouse can move before killing tooltip.
*/
Blockly.Tooltip.RADIUS_OK = 10;
/**
* Delay before tooltip appears.
*/
Blockly.Tooltip.HOVER_MS = 750;
/**
2015-04-28 13:51:25 -07:00
* Horizontal padding between tooltip and screen edge.
*/
Blockly.Tooltip.MARGINS = 5;
/**
2015-04-28 13:51:25 -07:00
* The HTML container. Set once by Blockly.Tooltip.createDom.
2015-07-13 15:03:22 -07:00
* @type {Element}
2015-04-28 13:51:25 -07:00
*/
Blockly.Tooltip.DIV = null;
/**
* Create the tooltip div and inject it onto the page.
*/
Blockly.Tooltip.createDom = function() {
2015-04-28 13:51:25 -07:00
if (Blockly.Tooltip.DIV) {
return; // Already created.
}
// Create an HTML container for popup overlays (e.g. editor widgets).
Blockly.Tooltip.DIV =
goog.dom.createDom(goog.dom.TagName.DIV, 'blocklyTooltipDiv');
2015-04-28 13:51:25 -07:00
document.body.appendChild(Blockly.Tooltip.DIV);
};
/**
* Binds the required mouse events onto an SVG element.
* @param {!Element} element SVG element onto which tooltip is to be bound.
*/
Blockly.Tooltip.bindMouseEvents = function(element) {
Blockly.bindEvent_(element, 'mouseover', null,
Blockly.Tooltip.onMouseOver_);
Blockly.bindEvent_(element, 'mouseout', null,
Blockly.Tooltip.onMouseOut_);
// Don't use bindEvent_ for mousemove since that would create a
// corresponding touch handler, even though this only makes sense in the
// context of a mouseover/mouseout.
element.addEventListener('mousemove', Blockly.Tooltip.onMouseMove_, false);
};
/**
* Hide the tooltip if the mouse is over a different object.
* Initialize the tooltip to potentially appear for this object.
* @param {!Event} e Mouse event.
* @private
*/
Blockly.Tooltip.onMouseOver_ = function(e) {
// If the tooltip is an object, treat it as a pointer to the next object in
// the chain to look at. Terminate when a string or function is found.
var element = e.target;
while (!goog.isString(element.tooltip) && !goog.isFunction(element.tooltip)) {
element = element.tooltip;
}
if (Blockly.Tooltip.element_ != element) {
Blockly.Tooltip.hide();
Blockly.Tooltip.poisonedElement_ = null;
Blockly.Tooltip.element_ = element;
}
// Forget about any immediately preceding mouseOut event.
clearTimeout(Blockly.Tooltip.mouseOutPid_);
};
/**
* Hide the tooltip if the mouse leaves the object and enters the workspace.
* @param {!Event} e Mouse event.
* @private
*/
Blockly.Tooltip.onMouseOut_ = function(/*e*/) {
// Moving from one element to another (overlapping or with no gap) generates
// a mouseOut followed instantly by a mouseOver. Fork off the mouseOut
// event and kill it if a mouseOver is received immediately.
// This way the task only fully executes if mousing into the void.
Blockly.Tooltip.mouseOutPid_ = setTimeout(function() {
2016-05-24 14:17:43 -07:00
Blockly.Tooltip.element_ = null;
Blockly.Tooltip.poisonedElement_ = null;
Blockly.Tooltip.hide();
}, 1);
clearTimeout(Blockly.Tooltip.showPid_);
};
/**
* When hovering over an element, schedule a tooltip to be shown. If a tooltip
* is already visible, hide it if the mouse strays out of a certain radius.
* @param {!Event} e Mouse event.
* @private
*/
Blockly.Tooltip.onMouseMove_ = function(e) {
if (!Blockly.Tooltip.element_ || !Blockly.Tooltip.element_.tooltip) {
// No tooltip here to show.
return;
} else if (Blockly.dragMode_ != Blockly.DRAG_NONE) {
2014-09-08 14:26:52 -07:00
// Don't display a tooltip during a drag.
return;
} else if (Blockly.WidgetDiv.isVisible()) {
// Don't display a tooltip if a widget is open (tooltip would be under it).
return;
}
if (Blockly.Tooltip.visible) {
// Compute the distance between the mouse position when the tooltip was
// shown and the current mouse position. Pythagorean theorem.
var dx = Blockly.Tooltip.lastX_ - e.pageX;
var dy = Blockly.Tooltip.lastY_ - e.pageY;
2015-08-19 17:21:05 -07:00
if (Math.sqrt(dx * dx + dy * dy) > Blockly.Tooltip.RADIUS_OK) {
Blockly.Tooltip.hide();
}
} else if (Blockly.Tooltip.poisonedElement_ != Blockly.Tooltip.element_) {
// The mouse moved, clear any previously scheduled tooltip.
clearTimeout(Blockly.Tooltip.showPid_);
// Maybe this time the mouse will stay put. Schedule showing of tooltip.
Blockly.Tooltip.lastX_ = e.pageX;
Blockly.Tooltip.lastY_ = e.pageY;
Blockly.Tooltip.showPid_ =
setTimeout(Blockly.Tooltip.show_, Blockly.Tooltip.HOVER_MS);
}
};
/**
* Hide the tooltip.
*/
Blockly.Tooltip.hide = function() {
if (Blockly.Tooltip.visible) {
Blockly.Tooltip.visible = false;
2015-04-28 13:51:25 -07:00
if (Blockly.Tooltip.DIV) {
Blockly.Tooltip.DIV.style.display = 'none';
}
}
clearTimeout(Blockly.Tooltip.showPid_);
};
/**
* Create the tooltip and show it.
* @private
*/
Blockly.Tooltip.show_ = function() {
Blockly.Tooltip.poisonedElement_ = Blockly.Tooltip.element_;
2015-04-28 13:51:25 -07:00
if (!Blockly.Tooltip.DIV) {
return;
}
// Erase all existing text.
2015-04-28 13:51:25 -07:00
goog.dom.removeChildren(/** @type {!Element} */ (Blockly.Tooltip.DIV));
2014-09-08 14:26:52 -07:00
// Get the new text.
var tip = Blockly.Tooltip.element_.tooltip;
while (goog.isFunction(tip)) {
tip = tip();
}
Merge google/develop June 22 (#441) * Localisation updates from https://translatewiki.net. * test page that creates random blocks and randomly drags them around the page * Localisation updates from https://translatewiki.net. * add missing return in fake drag * get rid of drag_tests file: * Generated JS helper functions should be camelCase. Complying with Google style guide. * Localisation updates from https://translatewiki.net. * Fix extra category error. Clean up code, rename variables, reduce line lengths, fix lint issues. * Remove claim that good.string.quote should be used. * Change the blockly workspace resizing strategy. (#386) * Add a new method to be called when the contents of the workspace change and the scrollbars need to be adjusted but the the chrome (trash, toolbox, etc) are expected to stay in the same place. Change a bunch of calls to svgResize to either be removed or call the new method instead. This is a nice performance win since the offsetHeight/Width call in svgResize can be expensive, especially when called as often as we do - there was some layout thrashing. This also paves the way for moving calls to recordDeleteAreas (which is also expensive) to a more cacheable spot than on every mouse down/touch event. of things (namely the scrollbars) * Fix size of graph demo when it first loads by calling svgResize. The graph starts with fixed width and was relying on a resize event to fire (which I believe was removed in commit 217c681b86b0f2df76c479c9efae62e6e). * Fix the resizing of the code demo. The demo's tab min-width used to match the toolbox's width was only being set on a resize event, but commit 217c681b86b0f2df76c479c9efae62e6e changed how that worked. * Fix up some comments. * Use specific workspaces rather than Blockly.getMainWorkspace(). * Make workspace required for resizeSvgContents and update some calls to send real workspaces rather than ones that are null. Remove the private tag on terminateDrag_ because it is only actually called from outside the BlockSvg object. * Remove a rogue period. * Recategorize BlockSvg.terminateDrag_ to @package instead of @private so that other developers don't use it, but it still can be used by other Blockly classes. * Add a TODO to fix issue #307. * Add @package to workspace resizeContents. * Routine recompile * Fix unit tests. * Fix inheritance on rendered connection. Closure compiler on maximum compression breaks badly due to lack of @extends attribute. * Add toolbox location and toolbox mode options to playground. * Increase commonality between playgrounds. * Properly deal with shadow statement blocks in stacks. * Localisation updates from https://translatewiki.net. * Use a comment block for function comments in generated JS, Python and Dart. * Fix typo in flyout.js (#403) * Fix typo in flyout.js (#402) * Line wrap comments in generated code. * Remove reference to undefined variable (#413) REASON_MUST_DISCONNECT was removed by a refactor in 2a1ffa1. * Fix airstrike by grabbing the correct toolbox element. (#411) Probably broken in 266e2ffa9a017d21d7ca2f151730d6ecfcecf173. * Localisation updates from https://translatewiki.net. * Fix issue #406 by calling resize from the keypress handler on text inputs. (#408) * Remove shadow blocks from Accessible Blockly demo. Update README. * Generate for loops on one line. * Introduce a common translation pipe; remove local stringMap attributes. Fix variable name error in paste functions. Minor linting. * Fix precedence on isIndex blocks. * Add indexing setting for JavaScript Generation (#419) Adding setting to allow for switching between zero and one based indexing for Blockly Blocks such that the generated code will use this flag to determine whether one based or zero based indexing should be used. One based indexing is enabled by default. * Remove unused functions and dependencies. * Remove the unnecessary construction of new services. * Fix sort block in JS to satisfy tests. * Trigger a contents resize in block's moveBy. (#422) This fixes #420 but and it also fixes some other similar problems with copy/paste and other users of moveBy. * Consolidate the usages of the 'blockly-disabled' label. * Fix error when undoing a shadow block replacement. Issue #415. * Unify setActiveDesc() and updateSelectedNode() in the TreeService. Move function calls made directly within the template to the correct hooks. * Standardize naming of components. * Prevent collisions between user functions and helper functions. * Localisation updates from https://translatewiki.net. * Fix #425. Attash the resize handler to the workspace so it can be removed (#429) when workspace.dispose() is called. * Change the TreeService to a singleton. * Remove unneeded generated parens around function calls in indexOf blocks. * Fix #423 by calling workspace's resize when the flyout reflows. (#430) * Updating URLs to reflect new docs. (#418) * Updating URLs to reflect new docs. Removing -blockly in URLs. * Rebuilt. * Routine recompile * Prevent selected block from ending up underneath a bumped block. * Fix undo on fields with validators with side effects. * Don't fire change event on fields that haven't been named yet. * Localisation updates from https://translatewiki.net. * Fix tree focus issues. * Fix remaining focus issues on block deletion. * cache delete areas instead of recalculating them onMouseDown * Cache screen CTM for performance improvement. * Call svgResizeContents from block_svg's dipose so that deleting blocks (#434) from the context menu (or anywhere really) causes the workspace to recalculate its size. Remove the call to svgResizeContents from onMouseUp's logic for determining whether the block is being dropped in the trash since it calls dispose. One side effect of this is that when you delete multiple blocks resize gets called for each of them and the scrollbars move during the operation. This is most obviously seen by doing an airstrike in the playground and then deleting all the blocks at once. * Allow terminal blocks to replace other terminal blocks (#433) * Allow terminal blocks to replace other terminal blocks * Updated test to allow replacing terminal blocks * Refactor how activeDescendant is set. Introduce helper functions to ensure that calls like pasteAbove() preserve the focus. * Localisation updates from https://translatewiki.net. * Remove unnecessary logging. * Reduce unneeded parentheses in JS and Python. * Start using field_number. * Make it easy to disable unconnected blocks. * Routine recompile. * Check if matrix is null in mouseToSvg * Remove js/ localizations pre-merge * Fix change to block_render_svg * Fix error in xml.js * Playground merge * Add simple toolboxes to playgrounds * Fix flyout reference in events listener * Move tokenizeIntepolation into Blockly.utils namespace. * Use simpler message interpolation in Code demo. * Create console stub for IE 9. * Don't output blockId if not set (e.g., toolbox category event). (#443) * Fix block in multi-playground * Increase commonality between playgrounds. # Conflicts: # tests/multi_playground.html # tests/playground.html * Remove "show flyouts" button * Recompile for merge June 22
2016-06-22 17:50:16 -04:00
tip = Blockly.utils.wrap(tip, Blockly.Tooltip.LIMIT);
2014-09-08 14:26:52 -07:00
// Create new text, line by line.
var lines = tip.split('\n');
for (var i = 0; i < lines.length; i++) {
2015-04-28 13:51:25 -07:00
var div = document.createElement('div');
div.appendChild(document.createTextNode(lines[i]));
Blockly.Tooltip.DIV.appendChild(div);
}
2015-04-28 13:51:25 -07:00
var rtl = Blockly.Tooltip.element_.RTL;
var windowSize = goog.dom.getViewportSize();
// Display the tooltip.
2015-04-28 13:51:25 -07:00
Blockly.Tooltip.DIV.style.direction = rtl ? 'rtl' : 'ltr';
Blockly.Tooltip.DIV.style.display = 'block';
Blockly.Tooltip.visible = true;
// Move the tooltip to just below the cursor.
2015-04-28 13:51:25 -07:00
var anchorX = Blockly.Tooltip.lastX_;
if (rtl) {
2015-04-28 23:43:03 -07:00
anchorX -= Blockly.Tooltip.OFFSET_X + Blockly.Tooltip.DIV.offsetWidth;
} else {
anchorX += Blockly.Tooltip.OFFSET_X;
}
2015-04-28 13:51:25 -07:00
var anchorY = Blockly.Tooltip.lastY_ + Blockly.Tooltip.OFFSET_Y;
if (anchorY + Blockly.Tooltip.DIV.offsetHeight >
windowSize.height + window.scrollY) {
// Falling off the bottom of the screen; shift the tooltip up.
2015-04-28 13:51:25 -07:00
anchorY -= Blockly.Tooltip.DIV.offsetHeight + 2 * Blockly.Tooltip.OFFSET_Y;
}
2015-04-28 13:51:25 -07:00
if (rtl) {
// Prevent falling off left edge in RTL mode.
anchorX = Math.max(Blockly.Tooltip.MARGINS - window.scrollX, anchorX);
} else {
2015-04-28 13:51:25 -07:00
if (anchorX + Blockly.Tooltip.DIV.offsetWidth >
windowSize.width + window.scrollX - 2 * Blockly.Tooltip.MARGINS) {
// Falling off the right edge of the screen;
// clamp the tooltip on the edge.
2015-04-28 13:51:25 -07:00
anchorX = windowSize.width - Blockly.Tooltip.DIV.offsetWidth -
2 * Blockly.Tooltip.MARGINS;
}
}
2015-04-28 13:51:25 -07:00
Blockly.Tooltip.DIV.style.top = anchorY + 'px';
Blockly.Tooltip.DIV.style.left = anchorX + 'px';
};