/** * Visual Blocks Editor * * Copyright 2016 Massachusetts Institute of Technology * All rights reserved. * * 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. */ /** * @file Field for numbers. Includes validator and numpad on touch. * @author tmickel@mit.edu (Tim Mickel) */ import * as Blockly from 'blockly/core' import { Colours } from '../colours' /** * Class for an editable number field. * In scratch-blocks, the min/max/precision properties are only used * to construct a restrictor on typable characters, and to inform the pop-up * numpad on touch devices. * These properties are included here (i.e. instead of just accepting a * decimalAllowed, negativeAllowed) to maintain API compatibility with Blockly * and Blockly for Android. * @param opt_value The initial content of the field. The value * should cast to a number, and if it does not, '0' will be used. * @param opt_min Minimum value. * @param opt_max Maximum value. * @param opt_precision Precision for value. * @param opt_validator An optional function that is called * to validate any constraints on what the user entered. Takes the new * text as an argument and returns the accepted text or null to abort * the change. */ class ScratchFieldNumber extends Blockly.FieldTextInput { private negativeAllowed_ = true private decimalAllowed_ = true private exponentialAllowed_ = true /** * Fixed width of the num-pad drop-down, in px. */ static DROPDOWN_WIDTH = 168 /** * Buttons for the num-pad, in order from the top left. * Values are strings of the number or symbol will be added to the field text * when the button is pressed. */ // Calculator order static NUMPAD_BUTTONS = ['7', '8', '9', '4', '5', '6', '1', '2', '3', '.', '0', '-', ' '] /** * Src for the delete icon to be shown on the num-pad. */ static NUMPAD_DELETE_ICON = 'data:image/svg+xml;utf8,' + '' + '' configure_(config: Blockly.FieldNumberFromJsonConfig) { super.configure_(config) this.decimalAllowed_ = typeof config.precision == 'undefined' || isNaN(config.precision) || config.precision == 0 || Math.floor(config.precision) != config.precision this.negativeAllowed_ = typeof config.min == 'undefined' || isNaN(config.min) || config.min < 0 this.exponentialAllowed_ = this.decimalAllowed_ } /** * Return an appropriate restrictor, depending on whether this FieldNumber * allows decimal or negative numbers. * @returns Regular expression for this FieldNumber's restrictor. */ getNumRestrictor() { let pattern = '[\\d]' // Always allow digits. if (this.decimalAllowed_) { pattern += '|[\\.]' } if (this.negativeAllowed_) { pattern += '|[-]' } if (this.exponentialAllowed_) { pattern += '|[eE]' } return new RegExp(pattern) } /** * Show the inline free-text editor on top of the text and the num-pad if * appropriate. * @param e The triggering pointer event. */ showEditor_(e?: PointerEvent) { // Do not focus on mobile devices so we can show the num-pad const showNumPad = e?.pointerType === 'touch' super.showEditor_(e, showNumPad) // Show a numeric keypad in the drop-down on touch if (showNumPad) { this.htmlInput_?.select() this.showNumPad_() } } onHtmlInputKeyDown_(e: KeyboardEvent) { super.onHtmlInputKeyDown_(e) // key can be things like "Backspace", so only validate when it represents a single // character so as to allow non-textual input to work as normal. if (e.key.length === 1) { const validator = this.getNumRestrictor() if (!e.key.match(validator)) { e.preventDefault() } } } /** * Show the number pad. */ private showNumPad_() { const contentDiv = Blockly.DropDownDiv.getContentDiv() // Accessibility properties contentDiv.setAttribute('role', 'menu') contentDiv.setAttribute('aria-haspopup', 'true') this.addButtons_(contentDiv) // Set colour and size of drop-down const sourceBlock = this.getSourceBlock() as Blockly.BlockSvg const parentBlock = sourceBlock.getParent() if (parentBlock) { Blockly.DropDownDiv.setColour(parentBlock.getColour(), sourceBlock.getColourTertiary()) } contentDiv.style.width = ScratchFieldNumber.DROPDOWN_WIDTH + 'px' this.position_() } /** * Figure out where to place the drop-down, and move it there. */ private position_() { // Calculate positioning for the drop-down // sourceBlock_ is the rendered shadow field input box const sourceBlock = this.getSourceBlock() as Blockly.BlockSvg const scale = sourceBlock.workspace.scale const bBox = sourceBlock.getHeightWidth() bBox.width *= scale bBox.height *= scale const position = this.getAbsoluteXY_() // If we can fit it, render below the shadow block const primaryX = position.x + bBox.width / 2 const primaryY = position.y + bBox.height // If we can't fit it, render above the entire parent block const secondaryX = primaryX const secondaryY = position.y Blockly.DropDownDiv.setBoundsElement(sourceBlock.workspace.getParentSvg().parentElement) Blockly.DropDownDiv.show( this, sourceBlock.RTL, primaryX, primaryY, secondaryX, secondaryY, false, this.onHide_.bind(this), ) } /** * Add number, punctuation, and erase buttons to the numeric keypad's content * div. * @param contentDiv The div for the numeric keypad. */ private addButtons_(contentDiv: Element) { const sourceBlock = this.getSourceBlock() as Blockly.BlockSvg const parent = sourceBlock.getParent() const buttonColour = parent?.getColour() ?? sourceBlock.getColour() const buttonBorderColour = parent?.getColourTertiary() ?? sourceBlock.getColourTertiary() // Add numeric keypad buttons const buttons = ScratchFieldNumber.NUMPAD_BUTTONS for (let i = 0, buttonText; (buttonText = buttons[i]); i++) { const button = document.createElement('button') button.setAttribute('role', 'menuitem') button.setAttribute('class', 'blocklyNumPadButton') button.setAttribute( 'style', 'background:' + buttonColour + ';' + 'border: 1px solid ' + buttonBorderColour + ';', ) button.title = buttonText button.innerHTML = buttonText Blockly.browserEvents.bind(button, 'mousedown', button, this.numPadButtonTouch.bind(this)) if (buttonText == '.' && !this.decimalAllowed_) { // Don't show the decimal point for inputs that must be round numbers button.setAttribute('style', 'visibility: hidden') } else if (buttonText == '-' && !this.negativeAllowed_) { continue } else if (buttonText == ' ' && !this.negativeAllowed_) { continue } else if (buttonText == ' ' && this.negativeAllowed_) { button.setAttribute('style', 'visibility: hidden') } contentDiv.appendChild(button) } // Add erase button to the end const eraseButton = document.createElement('button') eraseButton.setAttribute('role', 'menuitem') eraseButton.setAttribute('class', 'blocklyNumPadButton') eraseButton.setAttribute( 'style', 'background:' + buttonColour + ';' + 'border: 1px solid ' + buttonBorderColour + ';', ) eraseButton.title = 'Delete' const eraseImage = document.createElement('img') eraseImage.src = ScratchFieldNumber.NUMPAD_DELETE_ICON eraseButton.appendChild(eraseImage) Blockly.browserEvents.bind(eraseButton, 'mousedown', null, this.numPadEraseButtonTouch.bind(this)) contentDiv.appendChild(eraseButton) } /** * Call for when a num-pad number or punctuation button is touched. * Determine what the user is inputting and update the text field appropriately. * @param e DOM event triggering the touch. */ numPadButtonTouch(e: PointerEvent) { // String of the button (e.g., '7') const spliceValue = (e.target as HTMLElement).innerText // Old value of the text field const htmlInput = this.htmlInput_ if (!htmlInput) return const oldValue = htmlInput.value // Determine the selected portion of the text field const selectionStart = htmlInput.selectionStart ?? 0 const selectionEnd = htmlInput.selectionEnd ?? 0 // Splice in the new value const newValue = oldValue.slice(0, selectionStart) + spliceValue + oldValue.slice(selectionEnd) // Set new value and advance the cursor this.updateDisplay_(newValue, selectionStart + spliceValue.length) // This is just a click. Blockly.Touch.clearTouchIdentifier() // Prevent default to not lose input focus e.preventDefault() } /** * Call for when the num-pad erase button is touched. * Determine what the user is asking to erase, and erase it. * @param e DOM event triggering the touch. */ numPadEraseButtonTouch(e: PointerEvent) { // Old value of the text field const htmlInput = this.htmlInput_ if (!htmlInput) return const oldValue = htmlInput.value // Determine what is selected to erase (if anything) let selectionStart = htmlInput.selectionStart ?? 0 const selectionEnd = htmlInput.selectionEnd ?? 0 // If selection is zero-length, shift start to the left 1 character if (selectionStart == selectionEnd) { selectionStart = Math.max(0, selectionStart - 1) } // Cut out selected range const newValue = oldValue.slice(0, selectionStart) + oldValue.slice(selectionEnd) this.updateDisplay_(newValue, selectionStart) // This is just a click. Blockly.Touch.clearTouchIdentifier() // Prevent default to not lose input focus which resets cursors in Chrome e.preventDefault() } /** * Update the displayed value and resize/scroll the text field as needed. * @param newValue The new text to display. * @param newSelection The new index to put the cursor */ private updateDisplay_(newValue: string, newSelection: number) { this.setEditorValue_(newValue) // Resize and scroll the text field appropriately const htmlInput = this.htmlInput_ if (!htmlInput) return htmlInput.setSelectionRange(newSelection, newSelection) htmlInput.scrollLeft = htmlInput.scrollWidth } /** * Callback for when the drop-down is hidden. */ onHide_() { // Clear accessibility properties Blockly.DropDownDiv.getContentDiv().removeAttribute('role') Blockly.DropDownDiv.getContentDiv().removeAttribute('aria-haspopup') } } ScratchFieldNumber.prototype.DEFAULT_VALUE = '' /** * Register the field and any dependencies. */ export function registerScratchFieldNumber() { Blockly.fieldRegistry.unregister('field_number') Blockly.fieldRegistry.register('field_number', ScratchFieldNumber) }