From c929b3015bb1b3138d11979df056e7021fe5c1e8 Mon Sep 17 00:00:00 2001 From: Neil Fraser Date: Fri, 15 Oct 2021 09:17:04 -0700 Subject: [PATCH] chore: Convert == to === and != to !== where possible. (#5599) --- appengine/storage.js | 12 +- blocks/lists.js | 54 ++++----- blocks/logic.js | 2 +- blocks/loops.js | 6 +- blocks/math.js | 8 +- blocks/procedures.js | 56 ++++----- blocks/text.js | 38 +++---- blocks/variables.js | 4 +- blocks/variables_dynamic.js | 8 +- core/block.js | 106 +++++++++--------- core/block_dragger.js | 6 +- core/block_svg.js | 42 +++---- core/blockly.js | 2 +- core/browser_events.js | 14 +-- core/bubble.js | 8 +- core/bubble_dragger.js | 2 +- core/comment.js | 4 +- core/common.js | 4 +- core/connection.js | 22 ++-- core/connection_checker.js | 14 +-- core/connection_db.js | 10 +- core/contextmenu_items.js | 10 +- core/contextmenu_registry.js | 8 +- core/events/events_block_base.js | 2 +- core/events/events_block_change.js | 10 +- core/events/events_block_create.js | 2 +- core/events/events_block_delete.js | 4 +- core/events/events_block_move.js | 6 +- core/events/events_comment_base.js | 2 +- core/events/events_comment_change.js | 6 +- core/events/events_marker_move.js | 2 +- core/events/events_ui.js | 6 +- core/events/events_ui_base.js | 2 +- core/events/events_var_base.js | 2 +- core/events/events_var_rename.js | 2 +- core/events/utils.js | 18 +-- core/events/workspace_events.js | 2 +- core/extensions.js | 32 +++--- core/field.js | 8 +- core/field_angle.js | 12 +- core/field_checkbox.js | 4 +- core/field_colour.js | 8 +- core/field_dropdown.js | 28 ++--- core/field_image.js | 6 +- core/field_number.js | 6 +- core/field_textinput.js | 10 +- core/field_variable.js | 16 +-- core/flyout_base.js | 16 +-- core/flyout_horizontal.js | 20 ++-- core/flyout_vertical.js | 24 ++-- core/generator.js | 16 +-- core/gesture.js | 8 +- core/inject.js | 4 +- core/input.js | 8 +- core/insertion_marker_manager.js | 24 ++-- core/keyboard_nav/ast_node.js | 14 +-- core/keyboard_nav/basic_cursor.js | 6 +- core/keyboard_nav/cursor.js | 14 +-- core/keyboard_nav/tab_navigate_cursor.js | 2 +- core/menu.js | 8 +- core/menuitem.js | 2 +- core/metrics_manager.js | 20 ++-- core/mutator.js | 14 +-- core/names.js | 14 +-- core/options.js | 8 +- core/positionable_helpers.js | 6 +- core/procedures.js | 14 +-- core/registry.js | 10 +- core/rendered_connection.js | 26 ++--- core/renderers/common/constants.js | 10 +- core/renderers/common/debugger.js | 8 +- core/renderers/common/drawer.js | 4 +- core/renderers/common/info.js | 28 ++--- core/renderers/common/marker_svg.js | 18 +-- core/renderers/common/renderer.js | 4 +- core/renderers/geras/highlighter.js | 2 +- core/renderers/geras/info.js | 16 +-- core/renderers/measurables/input_row.js | 2 +- core/renderers/measurables/round_corner.js | 2 +- core/renderers/measurables/square_corner.js | 2 +- core/renderers/measurables/top_row.js | 2 +- core/renderers/thrasos/info.js | 4 +- core/renderers/zelos/constants.js | 8 +- core/renderers/zelos/info.js | 30 ++--- core/renderers/zelos/renderer.js | 4 +- core/scrollbar.js | 30 ++--- core/scrollbar_pair.js | 28 ++--- core/serialization/blocks.js | 4 +- core/shortcut_registry.js | 10 +- core/theme.js | 6 +- core/toolbox/category.js | 8 +- core/toolbox/collapsible_category.js | 10 +- core/toolbox/toolbox.js | 30 ++--- core/tooltip.js | 12 +- core/touch.js | 10 +- core/touch_gesture.js | 2 +- core/trashcan.js | 12 +- core/utils.js | 44 ++++---- core/utils/colour.js | 6 +- core/utils/coordinate.js | 4 +- core/utils/dom.js | 8 +- core/utils/object.js | 2 +- core/utils/size.js | 4 +- core/utils/string.js | 24 ++-- core/utils/style.js | 4 +- core/utils/toolbox.js | 20 ++-- core/utils/useragent.js | 2 +- core/variable_map.js | 18 +-- core/variables.js | 18 +-- core/warning.js | 4 +- core/widgetdiv.js | 2 +- core/workspace.js | 4 +- core/workspace_audio.js | 2 +- core/workspace_comment.js | 2 +- core/workspace_comment_svg.js | 12 +- core/workspace_drag_surface_svg.js | 2 +- core/workspace_svg.js | 32 +++--- core/xml.js | 88 +++++++-------- demos/blockfactory/app_controller.js | 20 ++-- .../blockfactory/block_exporter_controller.js | 6 +- demos/blockfactory/block_exporter_tools.js | 2 +- .../blockfactory/block_library_controller.js | 4 +- demos/blockfactory/block_library_storage.js | 2 +- demos/blockfactory/block_library_view.js | 4 +- demos/blockfactory/blocks.js | 32 +++--- demos/blockfactory/cp.js | 2 +- demos/blockfactory/factory.js | 28 ++--- demos/blockfactory/factory_utils.js | 84 +++++++------- demos/blockfactory/index.html | 2 +- .../workspacefactory/wfactory_controller.js | 62 +++++----- .../workspacefactory/wfactory_generator.js | 14 +-- .../workspacefactory/wfactory_init.js | 28 ++--- .../workspacefactory/wfactory_model.js | 52 ++++----- .../workspacefactory/wfactory_view.js | 24 ++-- demos/blockfactory_old/blocks.js | 16 +-- demos/blockfactory_old/factory.js | 68 +++++------ demos/code/code.js | 34 +++--- demos/custom-dialogs/custom-dialog.js | 4 +- demos/custom-fields/turtle/blocks.js | 8 +- demos/custom-fields/turtle/field_turtle.js | 18 +-- demos/generator/index.html | 2 +- demos/graph/index.html | 2 +- demos/minimap/minimap.js | 4 +- demos/plane/plane.js | 20 ++-- demos/plane/slider.js | 16 +-- generators/dart.js | 2 +- generators/dart/lists.js | 76 ++++++------- generators/dart/logic.js | 10 +- generators/dart/loops.js | 4 +- generators/dart/math.js | 20 ++-- generators/dart/text.js | 14 +-- generators/javascript.js | 2 +- generators/javascript/lists.js | 76 ++++++------- generators/javascript/logic.js | 10 +- generators/javascript/loops.js | 4 +- generators/javascript/math.js | 36 +++--- generators/javascript/text.js | 28 ++--- generators/lua.js | 2 +- generators/lua/lists.js | 54 ++++----- generators/lua/logic.js | 8 +- generators/lua/loops.js | 4 +- generators/lua/math.js | 10 +- generators/lua/text.js | 46 ++++---- generators/php.js | 2 +- generators/php/lists.js | 64 +++++------ generators/php/logic.js | 10 +- generators/php/loops.js | 4 +- generators/php/math.js | 12 +- generators/php/procedures.js | 2 +- generators/php/text.js | 24 ++-- generators/python.js | 6 +- generators/python/lists.js | 62 +++++----- generators/python/logic.js | 10 +- generators/python/loops.js | 8 +- generators/python/math.js | 22 ++-- generators/python/procedures.js | 2 +- generators/python/text.js | 12 +- scripts/gulpfiles/appengine_tasks.js | 4 +- scripts/gulpfiles/cleanup_tasks.js | 10 +- tests/generators/golden/generated.js | 58 +++++----- tests/generators/index.html | 4 +- tests/generators/unittest_dart.js | 6 +- tests/generators/unittest_javascript.js | 10 +- 183 files changed, 1409 insertions(+), 1409 deletions(-) diff --git a/appengine/storage.js b/appengine/storage.js index 82a74052a..22df87874 100644 --- a/appengine/storage.js +++ b/appengine/storage.js @@ -59,7 +59,7 @@ BlocklyStorage.link = function(opt_workspace) { var xml = Blockly.Xml.workspaceToDom(workspace, true); // Remove x/y coordinates from XML if there's only one block stack. // There's no reason to store this, removing it helps with anonymity. - if (workspace.getTopBlocks(false).length == 1 && xml.querySelector) { + if (workspace.getTopBlocks(false).length === 1 && xml.querySelector) { var block = xml.querySelector('block'); if (block) { block.removeAttribute('x'); @@ -116,17 +116,17 @@ BlocklyStorage.makeRequest_ = function(url, name, content, workspace) { * @private */ BlocklyStorage.handleRequest_ = function() { - if (BlocklyStorage.httpRequest_.readyState == 4) { - if (BlocklyStorage.httpRequest_.status != 200) { + if (BlocklyStorage.httpRequest_.readyState === 4) { + if (BlocklyStorage.httpRequest_.status !== 200) { BlocklyStorage.alert(BlocklyStorage.HTTPREQUEST_ERROR + '\n' + 'httpRequest_.status: ' + BlocklyStorage.httpRequest_.status); } else { var data = BlocklyStorage.httpRequest_.responseText.trim(); - if (BlocklyStorage.httpRequest_.name == 'xml') { + if (BlocklyStorage.httpRequest_.name === 'xml') { window.location.hash = data; BlocklyStorage.alert(BlocklyStorage.LINK_ALERT.replace('%1', window.location.href)); - } else if (BlocklyStorage.httpRequest_.name == 'key') { + } else if (BlocklyStorage.httpRequest_.name === 'key') { if (!data.length) { BlocklyStorage.alert(BlocklyStorage.HASH_ERROR.replace('%1', window.location.hash)); @@ -153,7 +153,7 @@ BlocklyStorage.monitorChanges_ = function(workspace) { function change() { var xmlDom = Blockly.Xml.workspaceToDom(workspace); var xmlText = Blockly.Xml.domToText(xmlDom); - if (startXmlText != xmlText) { + if (startXmlText !== xmlText) { window.location.hash = ''; workspace.removeChangeListener(change); } diff --git a/blocks/lists.js b/blocks/lists.js index 5aa43b269..ad88176c2 100644 --- a/blocks/lists.js +++ b/blocks/lists.js @@ -201,7 +201,7 @@ Blockly.Blocks['lists_create_with'] = { // Disconnect any children that don't belong. for (var i = 0; i < this.itemCount_; i++) { var connection = this.getInput('ADD' + i).connection.targetConnection; - if (connection && connections.indexOf(connection) == -1) { + if (connection && connections.indexOf(connection) === -1) { connection.disconnect(); } } @@ -245,7 +245,7 @@ Blockly.Blocks['lists_create_with'] = { if (!this.getInput('ADD' + i)) { var input = this.appendValueInput('ADD' + i) .setAlign(Blockly.ALIGN_RIGHT); - if (i == 0) { + if (i === 0) { input.appendField(Blockly.Msg['LISTS_CREATE_WITH_INPUT_WITH']); } } @@ -341,7 +341,7 @@ Blockly.Blocks['lists_getIndex'] = { this.setHelpUrl(Blockly.Msg['LISTS_GET_INDEX_HELPURL']); this.setStyle('list_blocks'); var modeMenu = new Blockly.FieldDropdown(MODE, function(value) { - var isStatement = (value == 'REMOVE'); + var isStatement = (value === 'REMOVE'); this.getSourceBlock().updateStatement_(isStatement); }); this.appendValueInput('VALUE') @@ -405,8 +405,8 @@ Blockly.Blocks['lists_getIndex'] = { tooltip = Blockly.Msg['LISTS_GET_INDEX_TOOLTIP_REMOVE_RANDOM']; break; } - if (where == 'FROM_START' || where == 'FROM_END') { - var msg = (where == 'FROM_START') ? + if (where === 'FROM_START' || where === 'FROM_END') { + var msg = (where === 'FROM_START') ? Blockly.Msg['LISTS_INDEX_FROM_START_TOOLTIP'] : Blockly.Msg['LISTS_INDEX_FROM_END_TOOLTIP']; tooltip += ' ' + msg.replace('%1', @@ -425,7 +425,7 @@ Blockly.Blocks['lists_getIndex'] = { var container = Blockly.utils.xml.createElement('mutation'); var isStatement = !this.outputConnection; container.setAttribute('statement', isStatement); - var isAt = this.getInput('AT').type == Blockly.INPUT_VALUE; + var isAt = this.getInput('AT').type === Blockly.INPUT_VALUE; container.setAttribute('at', isAt); return container; }, @@ -437,9 +437,9 @@ Blockly.Blocks['lists_getIndex'] = { domToMutation: function(xmlElement) { // Note: Until January 2013 this block did not have mutations, // so 'statement' defaults to false and 'at' defaults to true. - var isStatement = (xmlElement.getAttribute('statement') == 'true'); + var isStatement = (xmlElement.getAttribute('statement') === 'true'); this.updateStatement_(isStatement); - var isAt = (xmlElement.getAttribute('at') != 'false'); + var isAt = (xmlElement.getAttribute('at') !== 'false'); this.updateAt_(isAt); }, @@ -457,7 +457,7 @@ Blockly.Blocks['lists_getIndex'] = { */ updateStatement_: function(newStatement) { var oldStatement = !this.outputConnection; - if (newStatement != oldStatement) { + if (newStatement !== oldStatement) { this.unplug(true, true); if (newStatement) { this.setOutput(false); @@ -491,9 +491,9 @@ Blockly.Blocks['lists_getIndex'] = { this.appendDummyInput('AT'); } var menu = new Blockly.FieldDropdown(this.WHERE_OPTIONS, function(value) { - var newAt = (value == 'FROM_START') || (value == 'FROM_END'); + var newAt = (value === 'FROM_START') || (value === 'FROM_END'); // The 'isAt' variable is available due to this function being a closure. - if (newAt != isAt) { + if (newAt !== isAt) { var block = this.getSourceBlock(); block.updateAt_(newAt); // This menu has been destroyed and replaced. Update the replacement. @@ -578,7 +578,7 @@ Blockly.Blocks['lists_setIndex'] = { tooltip = Blockly.Msg['LISTS_SET_INDEX_TOOLTIP_INSERT_RANDOM']; break; } - if (where == 'FROM_START' || where == 'FROM_END') { + if (where === 'FROM_START' || where === 'FROM_END') { tooltip += ' ' + Blockly.Msg['LISTS_INDEX_FROM_START_TOOLTIP'] .replace('%1', thisBlock.workspace.options.oneBasedIndex ? '#1' : '#0'); @@ -593,7 +593,7 @@ Blockly.Blocks['lists_setIndex'] = { */ mutationToDom: function() { var container = Blockly.utils.xml.createElement('mutation'); - var isAt = this.getInput('AT').type == Blockly.INPUT_VALUE; + var isAt = this.getInput('AT').type === Blockly.INPUT_VALUE; container.setAttribute('at', isAt); return container; }, @@ -605,7 +605,7 @@ Blockly.Blocks['lists_setIndex'] = { domToMutation: function(xmlElement) { // Note: Until January 2013 this block did not have mutations, // so 'at' defaults to true. - var isAt = (xmlElement.getAttribute('at') != 'false'); + var isAt = (xmlElement.getAttribute('at') !== 'false'); this.updateAt_(isAt); }, @@ -635,9 +635,9 @@ Blockly.Blocks['lists_setIndex'] = { this.appendDummyInput('AT'); } var menu = new Blockly.FieldDropdown(this.WHERE_OPTIONS, function(value) { - var newAt = (value == 'FROM_START') || (value == 'FROM_END'); + var newAt = (value === 'FROM_START') || (value === 'FROM_END'); // The 'isAt' variable is available due to this function being a closure. - if (newAt != isAt) { + if (newAt !== isAt) { var block = this.getSourceBlock(); block.updateAt_(newAt); // This menu has been destroyed and replaced. Update the replacement. @@ -697,9 +697,9 @@ Blockly.Blocks['lists_getSublist'] = { */ mutationToDom: function() { var container = Blockly.utils.xml.createElement('mutation'); - var isAt1 = this.getInput('AT1').type == Blockly.INPUT_VALUE; + var isAt1 = this.getInput('AT1').type === Blockly.INPUT_VALUE; container.setAttribute('at1', isAt1); - var isAt2 = this.getInput('AT2').type == Blockly.INPUT_VALUE; + var isAt2 = this.getInput('AT2').type === Blockly.INPUT_VALUE; container.setAttribute('at2', isAt2); return container; }, @@ -709,8 +709,8 @@ Blockly.Blocks['lists_getSublist'] = { * @this {Blockly.Block} */ domToMutation: function(xmlElement) { - var isAt1 = (xmlElement.getAttribute('at1') == 'true'); - var isAt2 = (xmlElement.getAttribute('at2') == 'true'); + var isAt1 = (xmlElement.getAttribute('at1') === 'true'); + var isAt2 = (xmlElement.getAttribute('at2') === 'true'); this.updateAt_(1, isAt1); this.updateAt_(2, isAt2); }, @@ -745,10 +745,10 @@ Blockly.Blocks['lists_getSublist'] = { } var menu = new Blockly.FieldDropdown(this['WHERE_OPTIONS_' + n], function(value) { - var newAt = (value == 'FROM_START') || (value == 'FROM_END'); + var newAt = (value === 'FROM_START') || (value === 'FROM_END'); // The 'isAt' variable is available due to this function being a // closure. - if (newAt != isAt) { + if (newAt !== isAt) { var block = this.getSourceBlock(); block.updateAt_(n, newAt); // This menu has been destroyed and replaced. @@ -759,7 +759,7 @@ Blockly.Blocks['lists_getSublist'] = { }); this.getInput('AT' + n) .appendField(menu, 'WHERE' + n); - if (n == 1) { + if (n === 1) { this.moveInputBefore('AT1', 'AT2'); if (this.getInput('ORDINAL1')) { this.moveInputBefore('ORDINAL1', 'AT2'); @@ -839,9 +839,9 @@ Blockly.Blocks['lists_split'] = { this.setOutput(true, 'Array'); this.setTooltip(function() { var mode = thisBlock.getFieldValue('MODE'); - if (mode == 'SPLIT') { + if (mode === 'SPLIT') { return Blockly.Msg['LISTS_SPLIT_TOOLTIP_SPLIT']; - } else if (mode == 'JOIN') { + } else if (mode === 'JOIN') { return Blockly.Msg['LISTS_SPLIT_TOOLTIP_JOIN']; } throw Error('Unknown mode: ' + mode); @@ -855,7 +855,7 @@ Blockly.Blocks['lists_split'] = { */ updateType_: function(newMode) { var mode = this.getFieldValue('MODE'); - if (mode != newMode) { + if (mode !== newMode) { var inputConnection = this.getInput('INPUT').connection; inputConnection.setShadowDom(null); var inputBlock = inputConnection.targetBlock(); @@ -868,7 +868,7 @@ Blockly.Blocks['lists_split'] = { } } } - if (newMode == 'SPLIT') { + if (newMode === 'SPLIT') { this.outputConnection.setCheck('Array'); this.getInput('INPUT').setCheck('String'); } else { diff --git a/blocks/logic.js b/blocks/logic.js index a00fdba0a..386ec95cd 100644 --- a/blocks/logic.js +++ b/blocks/logic.js @@ -635,7 +635,7 @@ Blockly.Constants.Logic.LOGIC_TERNARY_ONCHANGE_MIXIN = { // Disconnect blocks that existed prior to this change if they don't match. if ((blockA || blockB) && parentConnection) { for (var i = 0; i < 2; i++) { - var block = (i == 1) ? blockA : blockB; + var block = (i === 1) ? blockA : blockB; if (block && !block.workspace.connectionChecker.doTypeChecks( block.outputConnection, parentConnection)) { diff --git a/blocks/loops.js b/blocks/loops.js index cbb76b59e..613a654b9 100644 --- a/blocks/loops.js +++ b/blocks/loops.js @@ -254,7 +254,7 @@ Blockly.Constants.Loops.CUSTOM_CONTEXT_MENU_CREATE_VARIABLES_GET_MIXIN = { } var variable = this.getField('VAR').getVariable(); var varName = variable.name; - if (!this.isCollapsed() && varName != null) { + if (!this.isCollapsed() && varName !== null) { var option = {enabled: true}; option.text = Blockly.Msg['VARIABLES_SET_CREATE_GET'].replace('%1', varName); @@ -310,7 +310,7 @@ Blockly.Constants.Loops.CONTROL_FLOW_IN_LOOP_CHECK_MIXIN = { // Is the block nested in a loop? do { if (Blockly.Constants.Loops.CONTROL_FLOW_IN_LOOP_CHECK_MIXIN.LOOP_TYPES - .indexOf(block.type) != -1) { + .indexOf(block.type) !== -1) { return block; } block = block.getSurroundParent(); @@ -329,7 +329,7 @@ Blockly.Constants.Loops.CONTROL_FLOW_IN_LOOP_CHECK_MIXIN = { // * It's at the start of a drag. // * It's not a move event. if (!this.workspace.isDragging || this.workspace.isDragging() || - e.type != Blockly.Events.BLOCK_MOVE) { + e.type !== Blockly.Events.BLOCK_MOVE) { return; } var enabled = Blockly.Constants.Loops.CONTROL_FLOW_IN_LOOP_CHECK_MIXIN diff --git a/blocks/math.js b/blocks/math.js index 62eb81337..e52d0fa17 100644 --- a/blocks/math.js +++ b/blocks/math.js @@ -451,7 +451,7 @@ Blockly.Constants.Math.IS_DIVISIBLEBY_MUTATOR_MIXIN = { */ mutationToDom: function() { var container = Blockly.utils.xml.createElement('mutation'); - var divisorInput = (this.getFieldValue('PROPERTY') == 'DIVISIBLE_BY'); + var divisorInput = (this.getFieldValue('PROPERTY') === 'DIVISIBLE_BY'); container.setAttribute('divisor_input', divisorInput); return container; }, @@ -462,7 +462,7 @@ Blockly.Constants.Math.IS_DIVISIBLEBY_MUTATOR_MIXIN = { * @this {Blockly.Block} */ domToMutation: function(xmlElement) { - var divisorInput = (xmlElement.getAttribute('divisor_input') == 'true'); + var divisorInput = (xmlElement.getAttribute('divisor_input') === 'true'); this.updateShape_(divisorInput); }, @@ -500,7 +500,7 @@ Blockly.Constants.Math.IS_DIVISIBLEBY_MUTATOR_MIXIN = { */ Blockly.Constants.Math.IS_DIVISIBLE_MUTATOR_EXTENSION = function() { this.getField('PROPERTY').setValidator(function(option) { - var divisorInput = (option == 'DIVISIBLE_BY'); + var divisorInput = (option === 'DIVISIBLE_BY'); this.getSourceBlock().updateShape_(divisorInput); }); }; @@ -530,7 +530,7 @@ Blockly.Constants.Math.LIST_MODES_MUTATOR_MIXIN = { * @this {Blockly.Block} */ updateType_: function(newOp) { - if (newOp == 'MODE') { + if (newOp === 'MODE') { this.outputConnection.setCheck('Array'); } else { this.outputConnection.setCheck('Number'); diff --git a/blocks/procedures.js b/blocks/procedures.js index 34697ce50..c24fad86d 100644 --- a/blocks/procedures.js +++ b/blocks/procedures.js @@ -132,13 +132,13 @@ Blockly.Blocks['procedures_defnoreturn'] = { this.arguments_ = []; this.argumentVarModels_ = []; for (var i = 0, childNode; (childNode = xmlElement.childNodes[i]); i++) { - if (childNode.nodeName.toLowerCase() == 'arg') { + if (childNode.nodeName.toLowerCase() === 'arg') { var varName = childNode.getAttribute('name'); var varId = childNode.getAttribute('varid') || childNode.getAttribute('varId'); this.arguments_.push(varName); var variable = Blockly.Variables.getOrCreateVariablePackage( this.workspace, varId, varName, ''); - if (variable != null) { + if (variable !== null) { this.argumentVarModels_.push(variable); } else { console.log('Failed to create a variable with name ' + varName + ', ignoring.'); @@ -242,7 +242,7 @@ Blockly.Blocks['procedures_defnoreturn'] = { var containerBlock = Blockly.Xml.domToBlock(containerBlockNode, workspace); - if (this.type == 'procedures_defreturn') { + if (this.type === 'procedures_defreturn') { containerBlock.setFieldValue(this.hasStatements_, 'STATEMENTS'); } else { containerBlock.removeInput('STATEMENT_INPUT'); @@ -279,8 +279,8 @@ Blockly.Blocks['procedures_defnoreturn'] = { // Show/hide the statement input. var hasStatements = containerBlock.getFieldValue('STATEMENTS'); if (hasStatements !== null) { - hasStatements = hasStatements == 'TRUE'; - if (this.hasStatements_ != hasStatements) { + hasStatements = hasStatements === 'TRUE'; + if (this.hasStatements_ !== hasStatements) { if (hasStatements) { this.setStatements_(true); // Restore the stack, if one was saved. @@ -339,7 +339,7 @@ Blockly.Blocks['procedures_defnoreturn'] = { */ renameVarById: function(oldId, newId) { var oldVariable = this.workspace.getVariableById(oldId); - if (oldVariable.type != '') { + if (oldVariable.type !== '') { // Procedure arguments always have the empty type. return; } @@ -348,7 +348,7 @@ Blockly.Blocks['procedures_defnoreturn'] = { var change = false; for (var i = 0; i < this.argumentVarModels_.length; i++) { - if (this.argumentVarModels_[i].getId() == oldId) { + if (this.argumentVarModels_[i].getId() === oldId) { this.arguments_[i] = newVar.name; this.argumentVarModels_[i] = newVar; change = true; @@ -371,7 +371,7 @@ Blockly.Blocks['procedures_defnoreturn'] = { var newName = variable.name; var change = false; for (var i = 0; i < this.argumentVarModels_.length; i++) { - if (this.argumentVarModels_[i].getId() == variable.getId()) { + if (this.argumentVarModels_[i].getId() === variable.getId()) { var oldName = this.arguments_[i]; this.arguments_[i] = newName; change = true; @@ -395,7 +395,7 @@ Blockly.Blocks['procedures_defnoreturn'] = { if (this.mutator && this.mutator.isVisible()) { var blocks = this.mutator.workspace_.getAllBlocks(false); for (var i = 0, block; (block = blocks[i]); i++) { - if (block.type == 'procedures_mutatorarg' && + if (block.type === 'procedures_mutatorarg' && Blockly.Names.equals(oldName, block.getFieldValue('NAME'))) { block.setFieldValue(newName, 'NAME'); } @@ -586,12 +586,12 @@ Blockly.Blocks['procedures_mutatorarg'] = { var blocks = workspace.getAllBlocks(false); var caselessName = varName.toLowerCase(); for (var i = 0; i < blocks.length; i++) { - if (blocks[i].id == this.getSourceBlock().id) { + if (blocks[i].id === this.getSourceBlock().id) { continue; } // Other blocks values may not be set yet when this is loaded. var otherVar = blocks[i].getFieldValue('NAME'); - if (otherVar && otherVar.toLowerCase() == caselessName) { + if (otherVar && otherVar.toLowerCase() === caselessName) { return null; } } @@ -603,7 +603,7 @@ Blockly.Blocks['procedures_mutatorarg'] = { } var model = outerWs.getVariable(varName, ''); - if (model && model.name != varName) { + if (model && model.name !== varName) { // Rename the variable (case change) outerWs.renameVariableById(model.getId(), varName); } @@ -631,7 +631,7 @@ Blockly.Blocks['procedures_mutatorarg'] = { } for (var i = 0; i < this.createdVariables_.length; i++) { var model = this.createdVariables_[i]; - if (model.name != newText) { + if (model.name !== newText) { outerWs.deleteVariableById(model.getId()); } } @@ -716,12 +716,12 @@ Blockly.Blocks['procedures_callnoreturn'] = { } // Test arguments (arrays of strings) for changes. '\n' is not a valid // argument name character, so it is a valid delimiter here. - if (paramNames.join('\n') == this.arguments_.join('\n')) { + if (paramNames.join('\n') === this.arguments_.join('\n')) { // No change. this.quarkIds_ = paramIds; return; } - if (paramIds.length != paramNames.length) { + if (paramIds.length !== paramNames.length) { throw RangeError('paramNames and paramIds must be the same length.'); } this.setCollapsed(false); @@ -740,7 +740,7 @@ Blockly.Blocks['procedures_callnoreturn'] = { var connection = input.connection.targetConnection; this.quarkConnections_[this.quarkIds_[i]] = connection; if (mutatorOpen && connection && - paramIds.indexOf(this.quarkIds_[i]) == -1) { + paramIds.indexOf(this.quarkIds_[i]) === -1) { // This connection should no longer be attached to this block. connection.disconnect(); connection.getSourceBlock().bumpNeighbours(); @@ -853,7 +853,7 @@ Blockly.Blocks['procedures_callnoreturn'] = { var args = []; var paramIds = []; for (var i = 0, childNode; (childNode = xmlElement.childNodes[i]); i++) { - if (childNode.nodeName.toLowerCase() == 'arg') { + if (childNode.nodeName.toLowerCase() === 'arg') { args.push(childNode.getAttribute('name')); paramIds.push(childNode.getAttribute('paramId')); } @@ -919,15 +919,15 @@ Blockly.Blocks['procedures_callnoreturn'] = { // Events not generated by user. Skip handling. return; } - if (event.type == Blockly.Events.BLOCK_CREATE && - event.ids.indexOf(this.id) != -1) { + if (event.type === Blockly.Events.BLOCK_CREATE && + event.ids.indexOf(this.id) !== -1) { // Look for the case where a procedure call was created (usually through // paste) and there is no matching definition. In this case, create // an empty definition block with the correct signature. var name = this.getProcedureCall(); var def = Blockly.Procedures.getDefinition(name, this.workspace); - if (def && (def.type != this.defType_ || - JSON.stringify(def.getVars()) != JSON.stringify(this.arguments_))) { + if (def && (def.type !== this.defType_ || + JSON.stringify(def.getVars()) !== JSON.stringify(this.arguments_))) { // The signatures don't match. def = null; } @@ -968,7 +968,7 @@ Blockly.Blocks['procedures_callnoreturn'] = { Blockly.Xml.domToWorkspace(xml, this.workspace); Blockly.Events.setGroup(false); } - } else if (event.type == Blockly.Events.BLOCK_DELETE) { + } else if (event.type === Blockly.Events.BLOCK_DELETE) { // Look for the case where a procedure definition has been deleted, // leaving this block (a procedure call) orphaned. In this case, delete // the orphan. @@ -979,10 +979,10 @@ Blockly.Blocks['procedures_callnoreturn'] = { this.dispose(true); Blockly.Events.setGroup(false); } - } else if (event.type == Blockly.Events.CHANGE && event.element == 'disabled') { + } else if (event.type === Blockly.Events.CHANGE && event.element === 'disabled') { var name = this.getProcedureCall(); var def = Blockly.Procedures.getDefinition(name, this.workspace); - if (def && def.id == event.blockId) { + if (def && def.id === event.blockId) { // in most cases the old group should be '' var oldGroup = Blockly.Events.getGroup(); if (oldGroup) { @@ -1102,7 +1102,7 @@ Blockly.Blocks['procedures_ifreturn'] = { */ domToMutation: function(xmlElement) { var value = xmlElement.getAttribute('value'); - this.hasReturnValue_ = (value == 1); + this.hasReturnValue_ = (value === '1'); if (!this.hasReturnValue_) { this.removeInput('VALUE'); this.appendDummyInput('VALUE') @@ -1129,7 +1129,7 @@ Blockly.Blocks['procedures_ifreturn'] = { // Is the block nested in a procedure? var block = this; do { - if (this.FUNCTION_TYPES.indexOf(block.type) != -1) { + if (this.FUNCTION_TYPES.indexOf(block.type) !== -1) { legal = true; break; } @@ -1137,12 +1137,12 @@ Blockly.Blocks['procedures_ifreturn'] = { } while (block); if (legal) { // If needed, toggle whether this block has a return value. - if (block.type == 'procedures_defnoreturn' && this.hasReturnValue_) { + if (block.type === 'procedures_defnoreturn' && this.hasReturnValue_) { this.removeInput('VALUE'); this.appendDummyInput('VALUE') .appendField(Blockly.Msg['PROCEDURES_DEFRETURN_RETURN']); this.hasReturnValue_ = false; - } else if (block.type == 'procedures_defreturn' && + } else if (block.type === 'procedures_defreturn' && !this.hasReturnValue_) { this.removeInput('VALUE'); this.appendValueInput('VALUE') diff --git a/blocks/text.js b/blocks/text.js index a226752e1..a634eb79b 100644 --- a/blocks/text.js +++ b/blocks/text.js @@ -266,9 +266,9 @@ Blockly.Blocks['text_getSubstring'] = { */ mutationToDom: function() { var container = Blockly.utils.xml.createElement('mutation'); - var isAt1 = this.getInput('AT1').type == Blockly.INPUT_VALUE; + var isAt1 = this.getInput('AT1').type === Blockly.INPUT_VALUE; container.setAttribute('at1', isAt1); - var isAt2 = this.getInput('AT2').type == Blockly.INPUT_VALUE; + var isAt2 = this.getInput('AT2').type === Blockly.INPUT_VALUE; container.setAttribute('at2', isAt2); return container; }, @@ -279,8 +279,8 @@ Blockly.Blocks['text_getSubstring'] = { * @this {Blockly.Block} */ domToMutation: function(xmlElement) { - var isAt1 = (xmlElement.getAttribute('at1') == 'true'); - var isAt2 = (xmlElement.getAttribute('at2') == 'true'); + var isAt1 = (xmlElement.getAttribute('at1') === 'true'); + var isAt2 = (xmlElement.getAttribute('at2') === 'true'); this.updateAt_(1, isAt1); this.updateAt_(2, isAt2); }, @@ -314,17 +314,17 @@ Blockly.Blocks['text_getSubstring'] = { this.appendDummyInput('AT' + n); } // Move tail, if present, to end of block. - if (n == 2 && Blockly.Msg['TEXT_GET_SUBSTRING_TAIL']) { + if (n === 2 && Blockly.Msg['TEXT_GET_SUBSTRING_TAIL']) { this.removeInput('TAIL', true); this.appendDummyInput('TAIL') .appendField(Blockly.Msg['TEXT_GET_SUBSTRING_TAIL']); } var menu = new Blockly.FieldDropdown(this['WHERE_OPTIONS_' + n], function(value) { - var newAt = (value == 'FROM_START') || (value == 'FROM_END'); + var newAt = (value === 'FROM_START') || (value === 'FROM_END'); // The 'isAt' variable is available due to this function being a // closure. - if (newAt != isAt) { + if (newAt !== isAt) { var block = this.getSourceBlock(); block.updateAt_(n, newAt); // This menu has been destroyed and replaced. @@ -337,7 +337,7 @@ Blockly.Blocks['text_getSubstring'] = { this.getInput('AT' + n) .appendField(menu, 'WHERE' + n); - if (n == 1) { + if (n === 1) { this.moveInputBefore('AT1', 'AT2'); if (this.getInput('ORDINAL1')) { this.moveInputBefore('ORDINAL1', 'AT2'); @@ -432,7 +432,7 @@ Blockly.Blocks['text_prompt_ext'] = { .appendField(dropdown, 'TYPE'); this.setOutput(true, 'String'); this.setTooltip(function() { - return (thisBlock.getFieldValue('TYPE') == 'TEXT') ? + return (thisBlock.getFieldValue('TYPE') === 'TEXT') ? Blockly.Msg['TEXT_PROMPT_TOOLTIP_TEXT'] : Blockly.Msg['TEXT_PROMPT_TOOLTIP_NUMBER']; }); @@ -444,7 +444,7 @@ Blockly.Blocks['text_prompt_ext'] = { * @this {Blockly.Block} */ updateType_: function(newOp) { - this.outputConnection.setCheck(newOp == 'NUMBER' ? 'Number' : 'String'); + this.outputConnection.setCheck(newOp === 'NUMBER' ? 'Number' : 'String'); }, /** * Create XML to represent the output type. @@ -500,7 +500,7 @@ Blockly.Blocks['text_prompt'] = { .appendField(this.newQuote_(false)); this.setOutput(true, 'String'); this.setTooltip(function() { - return (thisBlock.getFieldValue('TYPE') == 'TEXT') ? + return (thisBlock.getFieldValue('TYPE') === 'TEXT') ? Blockly.Msg['TEXT_PROMPT_TOOLTIP_TEXT'] : Blockly.Msg['TEXT_PROMPT_TOOLTIP_NUMBER']; }); @@ -643,7 +643,7 @@ Blockly.Constants.Text.QUOTE_IMAGE_MIXIN = { quoteField_: function(fieldName) { for (var i = 0, input; (input = this.inputList[i]); i++) { for (var j = 0, field; (field = input.fieldRow[j]); j++) { - if (fieldName == field.name) { + if (fieldName === field.name) { input.insertFieldAt(j, this.newQuote_(true)); input.insertFieldAt(j + 2, this.newQuote_(false)); return; @@ -763,7 +763,7 @@ Blockly.Constants.Text.TEXT_JOIN_MUTATOR_MIXIN = { // Disconnect any children that don't belong. for (var i = 0; i < this.itemCount_; i++) { var connection = this.getInput('ADD' + i).connection.targetConnection; - if (connection && connections.indexOf(connection) == -1) { + if (connection && connections.indexOf(connection) === -1) { connection.disconnect(); } } @@ -808,7 +808,7 @@ Blockly.Constants.Text.TEXT_JOIN_MUTATOR_MIXIN = { if (!this.getInput('ADD' + i)) { var input = this.appendValueInput('ADD' + i) .setAlign(Blockly.ALIGN_RIGHT); - if (i == 0) { + if (i === 0) { input.appendField(Blockly.Msg['TEXT_JOIN_TITLE_CREATEWITH']); } } @@ -880,7 +880,7 @@ Blockly.Constants.Text.TEXT_CHARAT_MUTATOR_MIXIN = { domToMutation: function(xmlElement) { // Note: Until January 2013 this block did not have mutations, // so 'at' defaults to true. - var isAt = (xmlElement.getAttribute('at') != 'false'); + var isAt = (xmlElement.getAttribute('at') !== 'false'); this.updateAt_(isAt); }, @@ -924,8 +924,8 @@ Blockly.Constants.Text.TEXT_CHARAT_MUTATOR_MIXIN = { Blockly.Constants.Text.TEXT_CHARAT_EXTENSION = function() { var dropdown = this.getField('WHERE'); dropdown.setValidator(function(value) { - var newAt = (value == 'FROM_START') || (value == 'FROM_END'); - if (newAt != this.isAt_) { + var newAt = (value === 'FROM_START') || (value === 'FROM_END'); + if (newAt !== this.isAt_) { var block = this.getSourceBlock(); block.updateAt_(newAt); } @@ -936,8 +936,8 @@ Blockly.Constants.Text.TEXT_CHARAT_EXTENSION = function() { this.setTooltip(function() { var where = thisBlock.getFieldValue('WHERE'); var tooltip = Blockly.Msg['TEXT_CHARAT_TOOLTIP']; - if (where == 'FROM_START' || where == 'FROM_END') { - var msg = (where == 'FROM_START') ? + if (where === 'FROM_START' || where === 'FROM_END') { + var msg = (where === 'FROM_START') ? Blockly.Msg['LISTS_INDEX_FROM_START_TOOLTIP'] : Blockly.Msg['LISTS_INDEX_FROM_END_TOOLTIP']; if (msg) { diff --git a/blocks/variables.js b/blocks/variables.js index aabc9ec51..3d999af24 100644 --- a/blocks/variables.js +++ b/blocks/variables.js @@ -89,7 +89,7 @@ Blockly.Constants.Variables.CUSTOM_CONTEXT_MENU_VARIABLE_GETTER_SETTER_MIXIN = { customContextMenu: function(options) { if (!this.isInFlyout) { // Getter blocks have the option to create a setter block, and vice versa. - if (this.type == 'variables_get') { + if (this.type === 'variables_get') { var opposite_type = 'variables_set'; var contextMenuMsg = Blockly.Msg['VARIABLES_GET_CREATE_SET']; } else { @@ -110,7 +110,7 @@ Blockly.Constants.Variables.CUSTOM_CONTEXT_MENU_VARIABLE_GETTER_SETTER_MIXIN = { options.push(option); // Getter blocks have the option to rename or delete that variable. } else { - if (this.type == 'variables_get' || this.type == 'variables_get_reporter') { + if (this.type === 'variables_get' || this.type === 'variables_get_reporter') { var renameOption = { text: Blockly.Msg.RENAME_VARIABLE, enabled: true, diff --git a/blocks/variables_dynamic.js b/blocks/variables_dynamic.js index 041d1144a..0dfb12851 100644 --- a/blocks/variables_dynamic.js +++ b/blocks/variables_dynamic.js @@ -90,7 +90,7 @@ Blockly.Constants.VariablesDynamic.CUSTOM_CONTEXT_MENU_VARIABLE_GETTER_SETTER_MI var id = this.getFieldValue('VAR'); var variableModel = this.workspace.getVariableById(id); var varType = variableModel.type; - if (this.type == 'variables_get_dynamic') { + if (this.type === 'variables_get_dynamic') { opposite_type = 'variables_set_dynamic'; contextMenuMsg = Blockly.Msg['VARIABLES_GET_CREATE_SET']; } else { @@ -111,8 +111,8 @@ Blockly.Constants.VariablesDynamic.CUSTOM_CONTEXT_MENU_VARIABLE_GETTER_SETTER_MI option.callback = Blockly.ContextMenu.callbackFactory(this, xmlBlock); options.push(option); } else { - if (this.type == 'variables_get_dynamic' || - this.type == 'variables_get_reporter_dynamic') { + if (this.type === 'variables_get_dynamic' || + this.type === 'variables_get_reporter_dynamic') { var renameOption = { text: Blockly.Msg.RENAME_VARIABLE, enabled: true, @@ -138,7 +138,7 @@ Blockly.Constants.VariablesDynamic.CUSTOM_CONTEXT_MENU_VARIABLE_GETTER_SETTER_MI onchange: function(_e) { var id = this.getFieldValue('VAR'); var variableModel = Blockly.Variables.getVariable(this.workspace, id); - if (this.type == 'variables_get_dynamic') { + if (this.type === 'variables_get_dynamic') { this.outputConnection.setCheck(variableModel.type); } else { this.getInput('VALUE').connection.setCheck(variableModel.type); diff --git a/core/block.js b/core/block.js index 0b4b6a814..059e6fd2b 100644 --- a/core/block.js +++ b/core/block.js @@ -75,7 +75,7 @@ goog.require('Blockly.Events.BlockMove'); */ const Block = function(workspace, prototypeName, opt_id) { const Generator = goog.module.get('Blockly.Generator'); - if (Generator && typeof Generator.prototype[prototypeName] != 'undefined') { + if (Generator && typeof Generator.prototype[prototypeName] !== 'undefined') { // Occluding Generator class members is not allowed. throw Error( 'Block prototypeName "' + prototypeName + @@ -214,7 +214,7 @@ const Block = function(workspace, prototypeName, opt_id) { /** @type {string} */ this.type = prototypeName; const prototype = Blocks[prototypeName]; - if (!prototype || typeof prototype != 'object') { + if (!prototype || typeof prototype !== 'object') { throw TypeError('Unknown block type: ' + prototypeName); } object.mixin(this, prototype); @@ -234,7 +234,7 @@ const Block = function(workspace, prototypeName, opt_id) { try { // Call an initialization function, if it exists. - if (typeof this.init == 'function') { + if (typeof this.init === 'function') { eventUtils.setRecordUndo(false); this.init(); eventUtils.setRecordUndo(initialUndoFlag); @@ -258,7 +258,7 @@ const Block = function(workspace, prototypeName, opt_id) { this.inputsInlineDefault = this.inputsInline; // Bind an onchange function, if it exists. - if (typeof this.onchange == 'function') { + if (typeof this.onchange === 'function') { this.setOnChange(this.onchange); } }; @@ -417,7 +417,7 @@ Block.prototype.dispose = function(healStack) { // well as corruption of the connection database. Therefore we must // methodically step through the blocks and carefully disassemble them. - if (common.getSelected() == this) { + if (common.getSelected() === this) { common.setSelected(null); } @@ -529,7 +529,7 @@ Block.prototype.getOnlyValueConnection_ = function() { let connection = null; for (let i = 0; i < this.inputList.length; i++) { const thisConnection = this.inputList[i].connection; - if (thisConnection && thisConnection.type == ConnectionType.INPUT_VALUE && + if (thisConnection && thisConnection.type === ConnectionType.INPUT_VALUE && thisConnection.targetConnection) { if (connection) { return null; // More than one value input found. @@ -641,7 +641,7 @@ Block.prototype.getParent = function() { */ Block.prototype.getInputWithBlock = function(block) { for (let i = 0, input; (input = this.inputList[i]); i++) { - if (input.connection && input.connection.targetBlock() == block) { + if (input.connection && input.connection.targetBlock() === block) { return input; } } @@ -664,7 +664,7 @@ Block.prototype.getSurroundParent = function() { // Ran off the top. return null; } - } while (block.getNextBlock() == prevBlock); + } while (block.getNextBlock() === prevBlock); // This block is an enclosing parent, not just a statement in a stack. return block; }; @@ -694,7 +694,7 @@ Block.prototype.getPreviousBlock = function() { Block.prototype.getFirstStatementConnection = function() { for (let i = 0, input; (input = this.inputList[i]); i++) { if (input.connection && - input.connection.type == ConnectionType.NEXT_STATEMENT) { + input.connection.type === ConnectionType.NEXT_STATEMENT) { return input.connection; } } @@ -728,7 +728,7 @@ Block.prototype.getTopStackBlock = function() { let previous; do { previous = block.getPreviousBlock(); - } while (previous && previous.getNextBlock() == block && (block = previous)); + } while (previous && previous.getNextBlock() === block && (block = previous)); return block; }; @@ -949,11 +949,11 @@ Block.prototype.isDisposed = function() { Block.prototype.getMatchingConnection = function(otherBlock, conn) { const connections = this.getConnections_(true); const otherConnections = otherBlock.getConnections_(true); - if (connections.length != otherConnections.length) { + if (connections.length !== otherConnections.length) { throw Error('Connection lists did not match in length.'); } for (let i = 0; i < otherConnections.length; i++) { - if (otherConnections[i] == conn) { + if (otherConnections[i] === conn) { return connections[i]; } } @@ -1040,7 +1040,7 @@ Block.prototype.setStyle = function(blockStyleName) { * @throws {Error} if onchangeFn is not falsey and not a function. */ Block.prototype.setOnChange = function(onchangeFn) { - if (onchangeFn && typeof onchangeFn != 'function') { + if (onchangeFn && typeof onchangeFn !== 'function') { throw Error('onchange must be a function.'); } if (this.onchangeWrapper_) { @@ -1124,7 +1124,7 @@ Block.prototype.getVarModels = function() { Block.prototype.updateVarName = function(variable) { for (let i = 0, input; (input = this.inputList[i]); i++) { for (let j = 0, field; (field = input.fieldRow[j]); j++) { - if (field.referencesVariables() && variable.getId() == field.getValue()) { + if (field.referencesVariables() && variable.getId() === field.getValue()) { field.refreshVariableName(); } } @@ -1141,7 +1141,7 @@ Block.prototype.updateVarName = function(variable) { Block.prototype.renameVarById = function(oldId, newId) { for (let i = 0, input; (input = this.inputList[i]); i++) { for (let j = 0, field; (field = input.fieldRow[j]); j++) { - if (field.referencesVariables() && oldId == field.getValue()) { + if (field.referencesVariables() && oldId === field.getValue()) { field.setValue(newId); } } @@ -1273,7 +1273,7 @@ Block.prototype.setOutput = function(newBoolean, opt_check) { * @param {boolean} newBoolean True if inputs are horizontal. */ Block.prototype.setInputsInline = function(newBoolean) { - if (this.inputsInline != newBoolean) { + if (this.inputsInline !== newBoolean) { eventUtils.fire(new (eventUtils.get(eventUtils.BLOCK_CHANGE))( this, 'inline', null, this.inputsInline, newBoolean)); this.inputsInline = newBoolean; @@ -1285,21 +1285,21 @@ Block.prototype.setInputsInline = function(newBoolean) { * @return {boolean} True if inputs are horizontal. */ Block.prototype.getInputsInline = function() { - if (this.inputsInline != undefined) { + if (this.inputsInline !== undefined) { // Set explicitly. return this.inputsInline; } // Not defined explicitly. Figure out what would look best. for (let i = 1; i < this.inputList.length; i++) { - if (this.inputList[i - 1].type == inputTypes.DUMMY && - this.inputList[i].type == inputTypes.DUMMY) { + if (this.inputList[i - 1].type === inputTypes.DUMMY && + this.inputList[i].type === inputTypes.DUMMY) { // Two dummy inputs in a row. Don't inline them. return false; } } for (let i = 1; i < this.inputList.length; i++) { - if (this.inputList[i - 1].type == inputTypes.VALUE && - this.inputList[i].type == inputTypes.DUMMY) { + if (this.inputList[i - 1].type === inputTypes.VALUE && + this.inputList[i].type === inputTypes.DUMMY) { // Dummy input after a value input. Inline them. return true; } @@ -1336,7 +1336,7 @@ Block.prototype.isEnabled = function() { * @param {boolean} enabled True if enabled. */ Block.prototype.setEnabled = function(enabled) { - if (this.isEnabled() != enabled) { + if (this.isEnabled() !== enabled) { const oldValue = this.disabled; this.disabled = !enabled; eventUtils.fire(new (eventUtils.get(eventUtils.BLOCK_CHANGE))( @@ -1374,7 +1374,7 @@ Block.prototype.isCollapsed = function() { * @param {boolean} collapsed True if collapsed. */ Block.prototype.setCollapsed = function(collapsed) { - if (this.collapsed_ != collapsed) { + if (this.collapsed_ !== collapsed) { eventUtils.fire(new (eventUtils.get(eventUtils.BLOCK_CHANGE))( this, 'collapsed', null, this.collapsed_, collapsed)); this.collapsed_ = collapsed; @@ -1410,15 +1410,15 @@ Block.prototype.toString = function(opt_maxLength, opt_emptyToken) { checks = connection.targetConnection.getCheck(); } return !!checks && - (checks.indexOf('Boolean') != -1 || checks.indexOf('Number') != -1); + (checks.indexOf('Boolean') !== -1 || checks.indexOf('Number') !== -1); } /** * Check that we haven't circled back to the original root node. */ function checkRoot() { - if (node && node.getType() == rootNode.getType() && - node.getLocation() == rootNode.getLocation()) { + if (node && node.getType() === rootNode.getType() && + node.getLocation() === rootNode.getLocation()) { node = null; } } @@ -1437,7 +1437,7 @@ Block.prototype.toString = function(opt_maxLength, opt_emptyToken) { } case ASTNode.types.FIELD: { const field = /** @type {Field} */ (node.getLocation()); - if (field.name != constants.COLLAPSED_FIELD_NAME) { + if (field.name !== constants.COLLAPSED_FIELD_NAME) { text.push(field.getText()); } break; @@ -1454,7 +1454,7 @@ Block.prototype.toString = function(opt_maxLength, opt_emptyToken) { node = node.out(); checkRoot(); // If we hit an input on the way up, possibly close out parentheses. - if (node && node.getType() == ASTNode.types.INPUT && + if (node && node.getType() === ASTNode.types.INPUT && shouldAddParentheses( /** @type {!Connection} */ (node.getLocation()))) { text.push(')'); @@ -1473,7 +1473,7 @@ Block.prototype.toString = function(opt_maxLength, opt_emptyToken) { // around single field blocks. // E.g. ['repeat', '(', '10', ')', 'times', 'do', '?'] for (let i = 2; i < text.length; i++) { - if (text[i - 2] == '(' && text[i] == ')') { + if (text[i - 2] === '(' && text[i] === ')') { text[i - 2] = text[i - 1]; text.splice(i - 1, 2); } @@ -1481,7 +1481,7 @@ Block.prototype.toString = function(opt_maxLength, opt_emptyToken) { // Join the text array, removing spaces around added parentheses. text = text.reduce(function(acc, value) { - return acc + ((acc.substr(-1) == '(' || value == ')') ? '' : ' ') + value; + return acc + ((acc.substr(-1) === '(' || value === ')') ? '' : ' ') + value; }, ''); text = text.trim() || '???'; if (opt_maxLength) { @@ -1597,7 +1597,7 @@ Block.prototype.jsonInit = function(json) { const localizedValue = utils.replaceMessageReferences(rawValue); this.setHelpUrl(localizedValue); } - if (typeof json['extensions'] == 'string') { + if (typeof json['extensions'] === 'string') { console.warn( warningPrefix + 'JSON attribute \'extensions\' should be an array of' + ' strings. Found raw string in JSON for \'' + json['type'] + @@ -1664,7 +1664,7 @@ Block.prototype.jsonInitStyle_ = function(json, warningPrefix) { * @param {boolean=} opt_disableCheck Option flag to disable overwrite checks. */ Block.prototype.mixin = function(mixinObj, opt_disableCheck) { - if (opt_disableCheck !== undefined && typeof opt_disableCheck != 'boolean') { + if (opt_disableCheck !== undefined && typeof opt_disableCheck !== 'boolean') { throw Error('opt_disableCheck must be a boolean if provided'); } if (!opt_disableCheck) { @@ -1733,7 +1733,7 @@ Block.prototype.validateTokens_ = function(tokens, argsCount) { let visitedArgsCount = 0; for (let i = 0; i < tokens.length; i++) { const token = tokens[i]; - if (typeof token != 'number') { + if (typeof token !== 'number') { continue; } if (token < 1 || token > argsCount) { @@ -1749,7 +1749,7 @@ Block.prototype.validateTokens_ = function(tokens, argsCount) { visitedArgsHash[token] = true; visitedArgsCount++; } - if (visitedArgsCount != argsCount) { + if (visitedArgsCount !== argsCount) { throw Error( 'Block "' + this.type + '": ' + 'Message does not reference all ' + argsCount + ' arg(s).'); @@ -1772,11 +1772,11 @@ Block.prototype.interpolateArguments_ = function(tokens, args, lastDummyAlign) { const elements = []; for (let i = 0; i < tokens.length; i++) { let element = tokens[i]; - if (typeof element == 'number') { + if (typeof element === 'number') { element = args[element - 1]; } // Args can be strings, which is why this isn't elseif. - if (typeof element == 'string') { + if (typeof element === 'string') { element = this.stringToFieldJson_(element); if (!element) { continue; @@ -1810,7 +1810,7 @@ Block.prototype.interpolateArguments_ = function(tokens, args, lastDummyAlign) { Block.prototype.fieldFromJson_ = function(element) { const field = fieldRegistry.fromJson(element); if (!field && element['alt']) { - if (typeof element['alt'] == 'string') { + if (typeof element['alt'] === 'string') { const json = this.stringToFieldJson_(element['alt']); return json ? this.fieldFromJson_(json) : null; } @@ -1876,8 +1876,8 @@ Block.prototype.inputFromJson_ = function(element, warningPrefix) { * @private */ Block.prototype.isInputKeyword_ = function(str) { - return str == 'input_value' || str == 'input_statement' || - str == 'input_dummy'; + return str === 'input_value' || str === 'input_statement' || + str === 'input_dummy'; }; /** @@ -1908,10 +1908,10 @@ Block.prototype.stringToFieldJson_ = function(str) { */ Block.prototype.appendInput_ = function(type, name) { let connection = null; - if (type == inputTypes.VALUE || type == inputTypes.STATEMENT) { + if (type === inputTypes.VALUE || type === inputTypes.STATEMENT) { connection = this.makeConnection_(type); } - if (type == inputTypes.STATEMENT) { + if (type === inputTypes.STATEMENT) { this.statementInputCount++; } const input = new Input(type, name, this, connection); @@ -1927,29 +1927,29 @@ Block.prototype.appendInput_ = function(type, name) { * or null to be the input at the end. */ Block.prototype.moveInputBefore = function(name, refName) { - if (name == refName) { + if (name === refName) { return; } // Find both inputs. let inputIndex = -1; let refIndex = refName ? -1 : this.inputList.length; for (let i = 0, input; (input = this.inputList[i]); i++) { - if (input.name == name) { + if (input.name === name) { inputIndex = i; - if (refIndex != -1) { + if (refIndex !== -1) { break; } - } else if (refName && input.name == refName) { + } else if (refName && input.name === refName) { refIndex = i; - if (inputIndex != -1) { + if (inputIndex !== -1) { break; } } } - if (inputIndex == -1) { + if (inputIndex === -1) { throw Error('Named input "' + name + '" not found.'); } - if (refIndex == -1) { + if (refIndex === -1) { throw Error('Reference input "' + refName + '" not found.'); } this.moveNumberedInputBefore(inputIndex, refIndex); @@ -1962,7 +1962,7 @@ Block.prototype.moveInputBefore = function(name, refName) { */ Block.prototype.moveNumberedInputBefore = function(inputIndex, refIndex) { // Validate arguments. - if (inputIndex == refIndex) { + if (inputIndex === refIndex) { throw Error('Can\'t move input to itself.'); } if (inputIndex >= this.inputList.length) { @@ -1991,8 +1991,8 @@ Block.prototype.moveNumberedInputBefore = function(inputIndex, refIndex) { */ Block.prototype.removeInput = function(name, opt_quiet) { for (let i = 0, input; (input = this.inputList[i]); i++) { - if (input.name == name) { - if (input.type == inputTypes.STATEMENT) { + if (input.name === name) { + if (input.type === inputTypes.STATEMENT) { this.statementInputCount--; } input.dispose(); @@ -2013,7 +2013,7 @@ Block.prototype.removeInput = function(name, opt_quiet) { */ Block.prototype.getInput = function(name) { for (let i = 0, input; (input = this.inputList[i]); i++) { - if (input.name == name) { + if (input.name === name) { return input; } } @@ -2045,7 +2045,7 @@ Block.prototype.getCommentText = function() { * @param {?string} text The text, or null to delete. */ Block.prototype.setCommentText = function(text) { - if (this.commentModel.text == text) { + if (this.commentModel.text === text) { return; } eventUtils.fire(new (eventUtils.get(eventUtils.BLOCK_CHANGE))( diff --git a/core/block_dragger.js b/core/block_dragger.js index e0eda456b..8b472712f 100644 --- a/core/block_dragger.js +++ b/core/block_dragger.js @@ -243,7 +243,7 @@ BlockDragger.prototype.drag = function(e, currentDragDeltaXY) { this.draggedConnectionManager_.update(delta, this.dragTarget_); const oldWouldDeleteBlock = this.wouldDeleteBlock_; this.wouldDeleteBlock_ = this.draggedConnectionManager_.wouldDeleteBlock(); - if (oldWouldDeleteBlock != this.wouldDeleteBlock_) { + if (oldWouldDeleteBlock !== this.wouldDeleteBlock_) { // Prevent unnecessary add/remove class calls. this.updateCursorDuringBlockDrag_(); } @@ -386,9 +386,9 @@ BlockDragger.prototype.updateToolboxStyle_ = function(isEnd) { const style = this.draggingBlock_.isDeletable() ? 'blocklyToolboxDelete' : 'blocklyToolboxGrab'; - if (isEnd && typeof toolbox.removeStyle == 'function') { + if (isEnd && typeof toolbox.removeStyle === 'function') { toolbox.removeStyle(style); - } else if (!isEnd && typeof toolbox.addStyle == 'function') { + } else if (!isEnd && typeof toolbox.addStyle === 'function') { toolbox.addStyle(style); } } diff --git a/core/block_svg.js b/core/block_svg.js index 14188846d..1df8dae6d 100644 --- a/core/block_svg.js +++ b/core/block_svg.js @@ -287,7 +287,7 @@ BlockSvg.prototype.select = function() { this.getParent().select(); return; } - if (common.getSelected() == this) { + if (common.getSelected() === this) { return; } let oldId = null; @@ -313,7 +313,7 @@ BlockSvg.prototype.select = function() { * if the block is currently selected. */ BlockSvg.prototype.unselect = function() { - if (common.getSelected() != this) { + if (common.getSelected() !== this) { return; } const event = new (eventUtils.get(eventUtils.SELECTED))( @@ -376,7 +376,7 @@ BlockSvg.prototype.getIcons = function() { */ BlockSvg.prototype.setParent = function(newParent) { const oldParent = this.parentBlock_; - if (newParent == oldParent) { + if (newParent === oldParent) { return; } @@ -436,15 +436,15 @@ BlockSvg.prototype.getRelativeToSurfaceXY = function() { // If this element is the current element on the drag surface, include // the translation of the drag surface itself. if (this.useDragSurface_ && - this.workspace.getBlockDragSurface().getCurrentBlock() == element) { + this.workspace.getBlockDragSurface().getCurrentBlock() === element) { const surfaceTranslation = this.workspace.getBlockDragSurface().getSurfaceTranslation(); x += surfaceTranslation.x; y += surfaceTranslation.y; } element = /** @type {!SVGElement} */ (element.parentNode); - } while (element && element != this.workspace.getCanvas() && - element != dragSurfaceGroup); + } while (element && element !== this.workspace.getCanvas() && + element !== dragSurfaceGroup); } return new Coordinate(x, y); }; @@ -631,7 +631,7 @@ BlockSvg.prototype.markDirty = function() { * @param {boolean} collapsed True if collapsed. */ BlockSvg.prototype.setCollapsed = function(collapsed) { - if (this.collapsed_ == collapsed) { + if (this.collapsed_ === collapsed) { return; } BlockSvg.superClass_.setCollapsed.call(this, collapsed); @@ -655,7 +655,7 @@ BlockSvg.prototype.updateCollapsed_ = function() { const collapsedFieldName = constants.COLLAPSED_FIELD_NAME; for (let i = 0, input; (input = this.inputList[i]); i++) { - if (input.name != collapsedInputName) { + if (input.name !== collapsedInputName) { input.setVisible(!collapsed); } } @@ -728,7 +728,7 @@ BlockSvg.prototype.onMouseDown_ = function(e) { */ BlockSvg.prototype.showHelp = function() { const url = - (typeof this.helpUrl == 'function') ? this.helpUrl() : this.helpUrl; + (typeof this.helpUrl === 'function') ? this.helpUrl() : this.helpUrl; if (url) { window.open(url); } @@ -860,7 +860,7 @@ BlockSvg.prototype.setShadow = function(shadow) { * @package */ BlockSvg.prototype.setInsertionMarker = function(insertionMarker) { - if (this.isInsertionMarker_ == insertionMarker) { + if (this.isInsertionMarker_ === insertionMarker) { return; // No change. } this.isInsertionMarker_ = insertionMarker; @@ -899,12 +899,12 @@ BlockSvg.prototype.dispose = function(healStack, animate) { // contents once the block is disposed. const blockWorkspace = this.workspace; // If this block is being dragged, unlink the mouse events. - if (common.getSelected() == this) { + if (common.getSelected() === this) { this.unselect(); this.workspace.cancelCurrentGesture(); } // If this block has a context menu open, close it. - if (ContextMenu.getCurrentBlock() == this) { + if (ContextMenu.getCurrentBlock() === this) { ContextMenu.hide(); } @@ -1033,13 +1033,13 @@ BlockSvg.prototype.setCommentText = function(text) { if (!Comment) { throw Error('Missing require for Blockly.Comment'); } - if (this.commentModel.text == text) { + if (this.commentModel.text === text) { return; } BlockSvg.superClass_.setCommentText.call(this, text); - const shouldHaveComment = text != null; - if (!!this.commentIcon_ == shouldHaveComment) { + const shouldHaveComment = text !== null; + if (!!this.commentIcon_ === shouldHaveComment) { // If the comment's state of existence is correct, but the text is new // that means we're just updating a comment. this.commentIcon_.updateText(); @@ -1105,7 +1105,7 @@ BlockSvg.prototype.setWarningText = function(text, opt_id) { } let changedState = false; - if (typeof text == 'string') { + if (typeof text === 'string') { // Bubble up to add a warning on top-most collapsed block. let parent = this.getSurroundParent(); let collapsedParent = null; @@ -1137,7 +1137,7 @@ BlockSvg.prototype.setWarningText = function(text, opt_id) { if (!newText) { this.warning.dispose(); } - changedState = oldText != newText; + changedState = oldText !== newText; } } if (changedState && this.rendered) { @@ -1172,7 +1172,7 @@ BlockSvg.prototype.setMutator = function(mutator) { * @param {boolean} enabled True if enabled. */ BlockSvg.prototype.setEnabled = function(enabled) { - if (this.isEnabled() != enabled) { + if (this.isEnabled() !== enabled) { BlockSvg.superClass_.setEnabled.call(this, enabled); if (this.rendered && !this.getInheritedDisabled()) { this.updateDisabled(); @@ -1552,7 +1552,7 @@ BlockSvg.prototype.bumpNeighbours = function() { // either one of them is unconnected, then there could be confusion. if (!connection.isConnected() || !otherConnection.isConnected()) { // Only bump blocks if they are from different tree structures. - if (otherConnection.getSourceBlock().getRootBlock() != rootBlock) { + if (otherConnection.getSourceBlock().getRootBlock() !== rootBlock) { // Always bump the inferior block. if (connection.isSuperior()) { otherConnection.bumpAwayFrom(connection); @@ -1602,8 +1602,8 @@ BlockSvg.prototype.positionNearConnection = function( sourceConnection, targetConnection) { // We only need to position the new block if it's before the existing one, // otherwise its position is set by the previous block. - if (sourceConnection.type == ConnectionType.NEXT_STATEMENT || - sourceConnection.type == ConnectionType.INPUT_VALUE) { + if (sourceConnection.type === ConnectionType.NEXT_STATEMENT || + sourceConnection.type === ConnectionType.INPUT_VALUE) { const dx = targetConnection.x - sourceConnection.x; const dy = targetConnection.y - sourceConnection.y; diff --git a/core/blockly.js b/core/blockly.js index 65140f269..463e0d208 100644 --- a/core/blockly.js +++ b/core/blockly.js @@ -413,7 +413,7 @@ const defineBlocksWithJsonArray = function(jsonArray) { 'Skipping.'); } else { const typename = elem.type; - if (typename == null || typename === '') { + if (!typename) { console.warn( 'Block definition #' + i + ' in JSON array is missing a type attribute. Skipping.'); diff --git a/core/browser_events.js b/core/browser_events.js index 483e214c0..c3208d78d 100644 --- a/core/browser_events.js +++ b/core/browser_events.js @@ -146,7 +146,7 @@ const bind = function(node, name, thisObject, func) { if (name in Touch.TOUCH_MAP) { const touchWrapFunc = function(e) { // Punt on multitouch events. - if (e.changedTouches && e.changedTouches.length == 1) { + if (e.changedTouches && e.changedTouches.length === 1) { // Map the touch event's properties to the event. const touchPoint = e.changedTouches[0]; e.clientX = touchPoint.clientX; @@ -195,12 +195,12 @@ exports.unbind = unbind; * @alias Blockly.browserEvents.isTargetInput */ const isTargetInput = function(e) { - return e.target.type == 'textarea' || e.target.type == 'text' || - e.target.type == 'number' || e.target.type == 'email' || - e.target.type == 'password' || e.target.type == 'search' || - e.target.type == 'tel' || e.target.type == 'url' || + return e.target.type === 'textarea' || e.target.type === 'text' || + e.target.type === 'number' || e.target.type === 'email' || + e.target.type === 'password' || e.target.type === 'search' || + e.target.type === 'tel' || e.target.type === 'url' || e.target.isContentEditable || - (e.target.dataset && e.target.dataset.isTextInput == 'true'); + (e.target.dataset && e.target.dataset.isTextInput === 'true'); }; exports.isTargetInput = isTargetInput; @@ -216,7 +216,7 @@ const isRightButton = function(e) { // WebKit on Mac OS X fails to change button to 2 (but Gecko does). return true; } - return e.button == 2; + return e.button === 2; }; exports.isRightButton = isRightButton; diff --git a/core/bubble.js b/core/bubble.js index 952d47117..ebf5afe39 100644 --- a/core/bubble.js +++ b/core/bubble.js @@ -495,17 +495,17 @@ Bubble.prototype.layoutBubble_ = function() { const mostOverlap = Math.max( topPositionOverlap, startPositionOverlap, closerPositionOverlap, fartherPositionOverlap); - if (topPositionOverlap == mostOverlap) { + if (topPositionOverlap === mostOverlap) { this.relativeLeft_ = topPosition.x; this.relativeTop_ = topPosition.y; return; } - if (startPositionOverlap == mostOverlap) { + if (startPositionOverlap === mostOverlap) { this.relativeLeft_ = startPosition.x; this.relativeTop_ = startPosition.y; return; } - if (closerPositionOverlap == mostOverlap) { + if (closerPositionOverlap === mostOverlap) { this.relativeLeft_ = closerPosition.x; this.relativeTop_ = closerPosition.y; return; @@ -753,7 +753,7 @@ Bubble.prototype.renderArrow_ = function() { // Find the relative coordinates of the center of the anchor. let relAnchorX = -this.relativeLeft_; let relAnchorY = -this.relativeTop_; - if (relBubbleX == relAnchorX && relBubbleY == relAnchorY) { + if (relBubbleX === relAnchorX && relBubbleY === relAnchorY) { // Null case. Bubble is directly on top of the anchor. // Short circuit this rather than wade through divide by zeros. steps.push('M ' + relBubbleX + ',' + relBubbleY); diff --git a/core/bubble_dragger.js b/core/bubble_dragger.js index 7f7864717..954fb30eb 100644 --- a/core/bubble_dragger.js +++ b/core/bubble_dragger.js @@ -145,7 +145,7 @@ BubbleDragger.prototype.dragBubble = function(e, currentDragDeltaXY) { const oldWouldDeleteBubble = this.wouldDeleteBubble_; this.wouldDeleteBubble_ = this.shouldDelete_(this.dragTarget_); - if (oldWouldDeleteBubble != this.wouldDeleteBubble_) { + if (oldWouldDeleteBubble !== this.wouldDeleteBubble_) { // Prevent unnecessary add/remove class calls. this.updateCursorDuringBubbleDrag_(); } diff --git a/core/comment.js b/core/comment.js index 72b432ff6..10ea9470f 100644 --- a/core/comment.js +++ b/core/comment.js @@ -184,7 +184,7 @@ Comment.prototype.createEditor_ = function() { }); this.onChangeWrapper_ = browserEvents.conditionalBind(textarea, 'change', this, function(_e) { - if (this.cachedText_ != this.model_.text) { + if (this.cachedText_ !== this.model_.text) { eventUtils.fire(new (eventUtils.get(eventUtils.BLOCK_CHANGE))( this.block_, 'comment', null, this.cachedText_, this.model_.text)); @@ -247,7 +247,7 @@ Comment.prototype.resizeTextarea_ = function() { * @param {boolean} visible True if the bubble should be visible. */ Comment.prototype.setVisible = function(visible) { - if (visible == this.isVisible()) { + if (visible === this.isVisible()) { return; } eventUtils.fire(new (eventUtils.get(eventUtils.BUBBLE_OPEN))( diff --git a/core/common.js b/core/common.js index d1a0e2ac2..0380fd08a 100644 --- a/core/common.js +++ b/core/common.js @@ -136,11 +136,11 @@ const svgResize = function(workspace) { } const width = div.offsetWidth; const height = div.offsetHeight; - if (cachedSize.width != width) { + if (cachedSize.width !== width) { svg.setAttribute('width', width + 'px'); mainWorkspace.setCachedParentSvgSize(width, null); } - if (cachedSize.height != height) { + if (cachedSize.height !== height) { svg.setAttribute('height', height + 'px'); mainWorkspace.setCachedParentSvgSize(null, height); } diff --git a/core/connection.js b/core/connection.js index dfcbba1eb..5c7d3cc03 100644 --- a/core/connection.js +++ b/core/connection.js @@ -198,8 +198,8 @@ Connection.prototype.getSourceBlock = function() { * @return {boolean} True if connection faces down or right. */ Connection.prototype.isSuperior = function() { - return this.type == ConnectionType.INPUT_VALUE || - this.type == ConnectionType.NEXT_STATEMENT; + return this.type === ConnectionType.INPUT_VALUE || + this.type === ConnectionType.NEXT_STATEMENT; }; /** @@ -241,7 +241,7 @@ Connection.prototype.checkConnection = function(target) { 'the workspace\'s connection checker'); const checker = this.getConnectionChecker(); const reason = checker.canConnectWithReason(this, target, false); - if (reason != Connection.CAN_CONNECT) { + if (reason !== Connection.CAN_CONNECT) { throw new Error(checker.getErrorMessage(reason, this, target)); } }; @@ -287,7 +287,7 @@ Connection.prototype.onFailedConnect = function(_otherConnection) { * @return {boolean} Whether the the blocks are now connected or not. */ Connection.prototype.connect = function(otherConnection) { - if (this.targetConnection == otherConnection) { + if (this.targetConnection === otherConnection) { // Already connected together. NOP. return true; } @@ -412,7 +412,7 @@ Connection.prototype.disconnect = function() { if (!otherConnection) { throw Error('Source connection not connected.'); } - if (otherConnection.targetConnection != this) { + if (otherConnection.targetConnection !== this) { throw Error('Target connection not connected to source connection.'); } let parentBlock, childBlock, parentConnection; @@ -655,16 +655,16 @@ Connection.prototype.toString = function() { return 'Orphan Connection'; } let msg; - if (block.outputConnection == this) { + if (block.outputConnection === this) { msg = 'Output Connection of '; - } else if (block.previousConnection == this) { + } else if (block.previousConnection === this) { msg = 'Previous Connection of '; - } else if (block.nextConnection == this) { + } else if (block.nextConnection === this) { msg = 'Next Connection of '; } else { let parentInput = null; for (let i = 0, input; (input = block.inputList[i]); i++) { - if (input.connection == this) { + if (input.connection === this) { parentInput = input; break; } @@ -771,14 +771,14 @@ Connection.prototype.createShadowBlock_ = function(attemptToConnect) { if (shadowDom) { blockShadow = Xml.domToBlock(shadowDom, parentBlock.workspace); if (attemptToConnect) { - if (this.type == ConnectionType.INPUT_VALUE) { + if (this.type === ConnectionType.INPUT_VALUE) { if (!blockShadow.outputConnection) { throw new Error('Shadow block is missing an output connection'); } if (!this.connect(blockShadow.outputConnection)) { throw new Error('Could not connect shadow block to connection'); } - } else if (this.type == ConnectionType.NEXT_STATEMENT) { + } else if (this.type === ConnectionType.NEXT_STATEMENT) { if (!blockShadow.previousConnection) { throw new Error('Shadow block is missing previous connection'); } diff --git a/core/connection_checker.js b/core/connection_checker.js index ae368fb48..a98f83066 100644 --- a/core/connection_checker.js +++ b/core/connection_checker.js @@ -51,7 +51,7 @@ const ConnectionChecker = function() {}; */ ConnectionChecker.prototype.canConnect = function( a, b, isDragging, opt_distance) { - return this.canConnectWithReason(a, b, isDragging, opt_distance) == + return this.canConnectWithReason(a, b, isDragging, opt_distance) === Connection.CAN_CONNECT; }; @@ -71,7 +71,7 @@ ConnectionChecker.prototype.canConnect = function( ConnectionChecker.prototype.canConnectWithReason = function( a, b, isDragging, opt_distance) { const safety = this.doSafetyChecks(a, b); - if (safety != Connection.CAN_CONNECT) { + if (safety !== Connection.CAN_CONNECT) { return safety; } @@ -149,9 +149,9 @@ ConnectionChecker.prototype.doSafetyChecks = function(a, b) { blockB = a.getSourceBlock(); blockA = b.getSourceBlock(); } - if (blockA == blockB) { + if (blockA === blockB) { return Connection.REASON_SELF_CONNECTION; - } else if (b.type != internalConstants.OPPOSITE_TYPE[a.type]) { + } else if (b.type !== internalConstants.OPPOSITE_TYPE[a.type]) { return Connection.REASON_WRONG_TYPE; } else if (blockA.workspace !== blockB.workspace) { return Connection.REASON_DIFFERENT_WORKSPACES; @@ -180,7 +180,7 @@ ConnectionChecker.prototype.doTypeChecks = function(a, b) { } // Find any intersection in the check lists. for (let i = 0; i < checkArrayOne.length; i++) { - if (checkArrayTwo.indexOf(checkArrayOne[i]) != -1) { + if (checkArrayTwo.indexOf(checkArrayOne[i]) !== -1) { return true; } } @@ -245,7 +245,7 @@ ConnectionChecker.prototype.doDragChecks = function(a, b, distance) { } // Don't let blocks try to connect to themselves or ones they nest. - if (common.draggingConnections.indexOf(b) != -1) { + if (common.draggingConnections.indexOf(b) !== -1) { return false; } @@ -269,7 +269,7 @@ ConnectionChecker.prototype.canConnectToPrevious_ = function(a, b) { } // Don't let blocks try to connect to themselves or ones they nest. - if (common.draggingConnections.indexOf(b) != -1) { + if (common.draggingConnections.indexOf(b) !== -1) { return false; } diff --git a/core/connection_db.js b/core/connection_db.js index 24c38e1b1..501ecfd05 100644 --- a/core/connection_db.js +++ b/core/connection_db.js @@ -94,8 +94,8 @@ ConnectionDB.prototype.findIndexOfConnection_ = function(conn, yPos) { yPos = conn.y; // Walk forward and back on the y axis looking for the connection. let pointer = bestGuess; - while (pointer >= 0 && this.connections_[pointer].y == yPos) { - if (this.connections_[pointer] == conn) { + while (pointer >= 0 && this.connections_[pointer].y === yPos) { + if (this.connections_[pointer] === conn) { return pointer; } pointer--; @@ -103,8 +103,8 @@ ConnectionDB.prototype.findIndexOfConnection_ = function(conn, yPos) { pointer = bestGuess; while (pointer < this.connections_.length && - this.connections_[pointer].y == yPos) { - if (this.connections_[pointer] == conn) { + this.connections_[pointer].y === yPos) { + if (this.connections_[pointer] === conn) { return pointer; } pointer++; @@ -147,7 +147,7 @@ ConnectionDB.prototype.calculateIndexForYPos_ = function(yPos) { */ ConnectionDB.prototype.removeConnection = function(connection, yPos) { const index = this.findIndexOfConnection_(connection, yPos); - if (index == -1) { + if (index === -1) { throw Error('Unable to find connection in connectionDB.'); } this.connections_.splice(index, 1); diff --git a/core/contextmenu_items.js b/core/contextmenu_items.js index 14727e2bf..018c2a8d5 100644 --- a/core/contextmenu_items.js +++ b/core/contextmenu_items.js @@ -287,7 +287,7 @@ const registerDeleteAll = function() { return; } const deletableBlocksLength = getDeletableBlocks_(scope.workspace).length; - if (deletableBlocksLength == 1) { + if (deletableBlocksLength === 1) { return Msg['DELETE_BLOCK']; } else { return Msg['DELETE_X_BLOCKS'].replace( @@ -441,8 +441,8 @@ const registerInline = function() { for (let i = 1; i < block.inputList.length; i++) { // Only display this option if there are two value or dummy inputs // next to each other. - if (block.inputList[i - 1].type != inputTypes.STATEMENT && - block.inputList[i].type != inputTypes.STATEMENT) { + if (block.inputList[i - 1].type !== inputTypes.STATEMENT && + block.inputList[i].type !== inputTypes.STATEMENT) { return 'enabled'; } } @@ -555,7 +555,7 @@ const registerDelete = function() { // Blocks in the current stack would survive this block's deletion. descendantCount -= nextBlock.getDescendants(false).length; } - return (descendantCount == 1) ? + return (descendantCount === 1) ? Msg['DELETE_BLOCK'] : Msg['DELETE_X_BLOCKS'].replace('%1', String(descendantCount)); }, @@ -593,7 +593,7 @@ const registerHelp = function() { preconditionFn: function(/** @type {!ContextMenuRegistry.Scope} */ scope) { const block = scope.block; - const url = (typeof block.helpUrl == 'function') ? block.helpUrl() : + const url = (typeof block.helpUrl === 'function') ? block.helpUrl() : block.helpUrl; if (url) { return 'enabled'; diff --git a/core/contextmenu_registry.js b/core/contextmenu_registry.js index 37733cbb6..8a0e73dff 100644 --- a/core/contextmenu_registry.js +++ b/core/contextmenu_registry.js @@ -145,16 +145,16 @@ ContextMenuRegistry.prototype.getContextMenuOptions = function( const registry = this.registry_; Object.keys(registry).forEach(function(id) { const item = registry[id]; - if (scopeType == item.scopeType) { + if (scopeType === item.scopeType) { const precondition = item.preconditionFn(scope); - if (precondition != 'hidden') { - const displayText = typeof item.displayText == 'function' ? + if (precondition !== 'hidden') { + const displayText = typeof item.displayText === 'function' ? item.displayText(scope) : item.displayText; /** @type {!ContextMenuRegistry.ContextMenuOption} */ const menuOption = { text: displayText, - enabled: (precondition == 'enabled'), + enabled: (precondition === 'enabled'), callback: item.callback, scope: scope, weight: item.weight, diff --git a/core/events/events_block_base.js b/core/events/events_block_base.js index 44c317616..9092447c9 100644 --- a/core/events/events_block_base.js +++ b/core/events/events_block_base.js @@ -32,7 +32,7 @@ const {Block} = goog.requireType('Blockly.Block'); */ const BlockBase = function(opt_block) { BlockBase.superClass_.constructor.call(this); - this.isBlank = typeof opt_block == 'undefined'; + this.isBlank = typeof opt_block === 'undefined'; /** * The block ID for the block this event pertains to diff --git a/core/events/events_block_change.js b/core/events/events_block_change.js index 2a3fe11d6..4ec197929 100644 --- a/core/events/events_block_change.js +++ b/core/events/events_block_change.js @@ -45,10 +45,10 @@ const BlockChange = function( if (!opt_block) { return; // Blank event to be populated by fromJson. } - this.element = typeof opt_element == 'undefined' ? '' : opt_element; - this.name = typeof opt_name == 'undefined' ? '' : opt_name; - this.oldValue = typeof opt_oldValue == 'undefined' ? '' : opt_oldValue; - this.newValue = typeof opt_newValue == 'undefined' ? '' : opt_newValue; + this.element = typeof opt_element === 'undefined' ? '' : opt_element; + this.name = typeof opt_name === 'undefined' ? '' : opt_name; + this.oldValue = typeof opt_oldValue === 'undefined' ? '' : opt_oldValue; + this.newValue = typeof opt_newValue === 'undefined' ? '' : opt_newValue; }; object.inherits(BlockChange, BlockBase); @@ -90,7 +90,7 @@ BlockChange.prototype.fromJson = function(json) { * @return {boolean} False if something changed. */ BlockChange.prototype.isNull = function() { - return this.oldValue == this.newValue; + return this.oldValue === this.newValue; }; /** diff --git a/core/events/events_block_create.js b/core/events/events_block_create.js index bf702b020..ac52835bd 100644 --- a/core/events/events_block_create.js +++ b/core/events/events_block_create.js @@ -105,7 +105,7 @@ BlockCreate.prototype.run = function(forward) { const block = workspace.getBlockById(id); if (block) { block.dispose(false); - } else if (id == this.blockId) { + } else if (id === this.blockId) { // Only complain about root-level block. console.warn('Can\'t uncreate non-existent block: ' + id); } diff --git a/core/events/events_block_delete.js b/core/events/events_block_delete.js index 69736b3cf..d448e9800 100644 --- a/core/events/events_block_delete.js +++ b/core/events/events_block_delete.js @@ -96,7 +96,7 @@ BlockDelete.prototype.fromJson = function(json) { this.oldXml = Xml.textToDom(json['oldXml']); this.ids = json['ids']; this.wasShadow = - json['wasShadow'] || this.oldXml.tagName.toLowerCase() == 'shadow'; + json['wasShadow'] || this.oldXml.tagName.toLowerCase() === 'shadow'; this.oldJson = /** @type {!blocks.State} */ (json['oldJson']); if (json['recordUndo'] !== undefined) { this.recordUndo = json['recordUndo']; @@ -115,7 +115,7 @@ BlockDelete.prototype.run = function(forward) { const block = workspace.getBlockById(id); if (block) { block.dispose(false); - } else if (id == this.blockId) { + } else if (id === this.blockId) { // Only complain about root-level block. console.warn('Can\'t delete non-existent block: ' + id); } diff --git a/core/events/events_block_move.js b/core/events/events_block_move.js index ba20a984f..a7e2a6f5a 100644 --- a/core/events/events_block_move.js +++ b/core/events/events_block_move.js @@ -134,8 +134,8 @@ BlockMove.prototype.currentLocation_ = function() { * @return {boolean} False if something changed. */ BlockMove.prototype.isNull = function() { - return this.oldParentId == this.newParentId && - this.oldInputName == this.newInputName && + return this.oldParentId === this.newParentId && + this.oldInputName === this.newInputName && Coordinate.equals(this.oldCoordinate, this.newCoordinate); }; @@ -176,7 +176,7 @@ BlockMove.prototype.run = function(forward) { if (input) { parentConnection = input.connection; } - } else if (connectionType == ConnectionType.PREVIOUS_STATEMENT) { + } else if (connectionType === ConnectionType.PREVIOUS_STATEMENT) { parentConnection = parentBlock.nextConnection; } if (parentConnection) { diff --git a/core/events/events_comment_base.js b/core/events/events_comment_base.js index a09836a7b..295f5f70c 100644 --- a/core/events/events_comment_base.js +++ b/core/events/events_comment_base.js @@ -42,7 +42,7 @@ const CommentBase = function(opt_comment) { * Whether or not an event is blank. * @type {boolean} */ - this.isBlank = typeof opt_comment == 'undefined'; + this.isBlank = typeof opt_comment === 'undefined'; /** * The ID of the comment this event pertains to. diff --git a/core/events/events_comment_change.js b/core/events/events_comment_change.js index ba32474ca..c63c07a57 100644 --- a/core/events/events_comment_change.js +++ b/core/events/events_comment_change.js @@ -41,9 +41,9 @@ const CommentChange = function(opt_comment, opt_oldContents, opt_newContents) { } this.oldContents_ = - typeof opt_oldContents == 'undefined' ? '' : opt_oldContents; + typeof opt_oldContents === 'undefined' ? '' : opt_oldContents; this.newContents_ = - typeof opt_newContents == 'undefined' ? '' : opt_newContents; + typeof opt_newContents === 'undefined' ? '' : opt_newContents; }; object.inherits(CommentChange, CommentBase); @@ -79,7 +79,7 @@ CommentChange.prototype.fromJson = function(json) { * @return {boolean} False if something changed. */ CommentChange.prototype.isNull = function() { - return this.oldContents_ == this.newContents_; + return this.oldContents_ === this.newContents_; }; /** diff --git a/core/events/events_marker_move.js b/core/events/events_marker_move.js index 0721ed175..640934186 100644 --- a/core/events/events_marker_move.js +++ b/core/events/events_marker_move.js @@ -43,7 +43,7 @@ const {Block} = goog.requireType('Blockly.Block'); */ const MarkerMove = function(opt_block, isCursor, opt_oldNode, opt_newNode) { let workspaceId = opt_block ? opt_block.workspace.id : undefined; - if (opt_newNode && opt_newNode.getType() == ASTNode.types.WORKSPACE) { + if (opt_newNode && opt_newNode.getType() === ASTNode.types.WORKSPACE) { workspaceId = (/** @type {!Workspace} */ (opt_newNode.getLocation())).id; } MarkerMove.superClass_.constructor.call(this, workspaceId); diff --git a/core/events/events_ui.js b/core/events/events_ui.js index caae11f25..2a5cb3000 100644 --- a/core/events/events_ui.js +++ b/core/events/events_ui.js @@ -44,9 +44,9 @@ const Ui = function(opt_block, opt_element, opt_oldValue, opt_newValue) { Ui.superClass_.constructor.call(this, workspaceId); this.blockId = opt_block ? opt_block.id : null; - this.element = typeof opt_element == 'undefined' ? '' : opt_element; - this.oldValue = typeof opt_oldValue == 'undefined' ? '' : opt_oldValue; - this.newValue = typeof opt_newValue == 'undefined' ? '' : opt_newValue; + this.element = typeof opt_element === 'undefined' ? '' : opt_element; + this.oldValue = typeof opt_oldValue === 'undefined' ? '' : opt_oldValue; + this.newValue = typeof opt_newValue === 'undefined' ? '' : opt_newValue; }; object.inherits(Ui, UiBase); diff --git a/core/events/events_ui_base.js b/core/events/events_ui_base.js index 9ec457492..42271642a 100644 --- a/core/events/events_ui_base.js +++ b/core/events/events_ui_base.js @@ -41,7 +41,7 @@ const UiBase = function(opt_workspaceId) { * Whether or not the event is blank (to be populated by fromJson). * @type {boolean} */ - this.isBlank = typeof opt_workspaceId == 'undefined'; + this.isBlank = typeof opt_workspaceId === 'undefined'; /** * The workspace identifier for this event. diff --git a/core/events/events_var_base.js b/core/events/events_var_base.js index d4c42cb8d..aaf886665 100644 --- a/core/events/events_var_base.js +++ b/core/events/events_var_base.js @@ -32,7 +32,7 @@ const object = goog.require('Blockly.utils.object'); */ const VarBase = function(opt_variable) { VarBase.superClass_.constructor.call(this); - this.isBlank = typeof opt_variable == 'undefined'; + this.isBlank = typeof opt_variable === 'undefined'; /** * The variable id for the variable this event pertains to. diff --git a/core/events/events_var_rename.js b/core/events/events_var_rename.js index 79b1c3626..7b859a34d 100644 --- a/core/events/events_var_rename.js +++ b/core/events/events_var_rename.js @@ -40,7 +40,7 @@ const VarRename = function(opt_variable, newName) { } this.oldName = opt_variable.name; - this.newName = typeof newName == 'undefined' ? '' : newName; + this.newName = typeof newName === 'undefined' ? '' : newName; }; object.inherits(VarRename, VarBase); diff --git a/core/events/utils.js b/core/events/utils.js index 73dc172de..f4078206a 100644 --- a/core/events/utils.js +++ b/core/events/utils.js @@ -375,24 +375,24 @@ const filter = function(queueIn, forward) { // move events. hash[key] = {event: event, index: i}; mergedQueue.push(event); - } else if (event.type == MOVE && lastEntry.index == i - 1) { + } else if (event.type === MOVE && lastEntry.index === i - 1) { // Merge move events. lastEvent.newParentId = event.newParentId; lastEvent.newInputName = event.newInputName; lastEvent.newCoordinate = event.newCoordinate; lastEntry.index = i; } else if ( - event.type == CHANGE && event.element == lastEvent.element && - event.name == lastEvent.name) { + event.type === CHANGE && event.element === lastEvent.element && + event.name === lastEvent.name) { // Merge change events. lastEvent.newValue = event.newValue; - } else if (event.type == VIEWPORT_CHANGE) { + } else if (event.type === VIEWPORT_CHANGE) { // Merge viewport change events. lastEvent.viewTop = event.viewTop; lastEvent.viewLeft = event.viewLeft; lastEvent.scale = event.scale; lastEvent.oldScale = event.oldScale; - } else if (event.type == CLICK && lastEvent.type == BUBBLE_OPEN) { + } else if (event.type === CLICK && lastEvent.type === BUBBLE_OPEN) { // Drop click events caused by opening/closing bubbles. } else { // Collision: newer events should merge into this event to maintain @@ -413,7 +413,7 @@ const filter = function(queueIn, forward) { // Move mutation events to the top of the queue. // Intentionally skip first event. for (let i = 1, event; (event = queue[i]); i++) { - if (event.type == CHANGE && event.element == 'mutation') { + if (event.type === CHANGE && event.element === 'mutation') { queue.unshift(queue.splice(i, 1)[0]); } } @@ -458,7 +458,7 @@ exports.enable = enable; * @alias Blockly.Events.utils.isEnabled */ const isEnabled = function() { - return disabled == 0; + return disabled === 0; }; exports.isEnabled = isEnabled; @@ -479,7 +479,7 @@ exports.getGroup = getGroup; * @alias Blockly.Events.utils.setGroup */ const setGroup = function(state) { - if (typeof state == 'boolean') { + if (typeof state === 'boolean') { group = state ? idGenerator.genUid() : ''; } else { group = state; @@ -545,7 +545,7 @@ exports.get = get; * @alias Blockly.Events.utils.disableOrphans */ const disableOrphans = function(event) { - if (event.type == MOVE || event.type == CREATE) { + if (event.type === MOVE || event.type === CREATE) { if (!event.workspaceId) { return; } diff --git a/core/events/workspace_events.js b/core/events/workspace_events.js index 5da3de913..24c051517 100644 --- a/core/events/workspace_events.js +++ b/core/events/workspace_events.js @@ -40,7 +40,7 @@ const FinishedLoading = function(opt_workspace) { * Whether or not the event is blank (to be populated by fromJson). * @type {boolean} */ - this.isBlank = typeof opt_workspace == 'undefined'; + this.isBlank = typeof opt_workspace === 'undefined'; /** * The workspace identifier for this event. diff --git a/core/extensions.js b/core/extensions.js index 0ec4f03bc..86db6f0e8 100644 --- a/core/extensions.js +++ b/core/extensions.js @@ -47,13 +47,13 @@ exports.TEST_ONLY = {allExtensions}; * @alias Blockly.Extensions.register */ const register = function(name, initFn) { - if ((typeof name != 'string') || (name.trim() == '')) { + if ((typeof name !== 'string') || (name.trim() === '')) { throw Error('Error: Invalid extension name "' + name + '"'); } if (allExtensions[name]) { throw Error('Error: Extension "' + name + '" is already registered.'); } - if (typeof initFn != 'function') { + if (typeof initFn !== 'function') { throw Error('Error: Extension "' + name + '" must be a function'); } allExtensions[name] = initFn; @@ -69,7 +69,7 @@ exports.register = register; * @alias Blockly.Extensions.registerMixin */ const registerMixin = function(name, mixinObj) { - if (!mixinObj || typeof mixinObj != 'object') { + if (!mixinObj || typeof mixinObj !== 'object') { throw Error('Error: Mixin "' + name + '" must be a object'); } register(name, function() { @@ -98,7 +98,7 @@ const registerMutator = function(name, mixinObj, opt_helperFn, opt_blockList) { checkHasMutatorProperties(errorPrefix, mixinObj); var hasMutatorDialog = checkMutatorDialog(mixinObj, errorPrefix); - if (opt_helperFn && (typeof opt_helperFn != 'function')) { + if (opt_helperFn && (typeof opt_helperFn !== 'function')) { throw Error(errorPrefix + 'Extension "' + name + '" is not a function'); } @@ -159,7 +159,7 @@ exports.isRegistered = isRegistered; */ const apply = function(name, block, isMutator) { const extensionFn = allExtensions[name]; - if (typeof extensionFn != 'function') { + if (typeof extensionFn !== 'function') { throw Error('Error: Extension "' + name + '" not found.'); } let mutatorProperties; @@ -266,9 +266,9 @@ const checkHasFunctionPair = function(object, name1, name2, errorPrefix) { var has2 = object[name2] !== undefined; if (has1 && has2) { - if (typeof object[name1] != 'function') { + if (typeof object[name1] !== 'function') { throw Error(errorPrefix + name1 + ' must be a function.'); - } else if (typeof object[name2] != 'function') { + } else if (typeof object[name2] !== 'function') { throw Error(errorPrefix + name2 + ' must be a function.'); } return true; @@ -339,11 +339,11 @@ const getMutatorProperties = function(block) { */ const mutatorPropertiesMatch = function(oldProperties, block) { const newProperties = getMutatorProperties(block); - if (newProperties.length != oldProperties.length) { + if (newProperties.length !== oldProperties.length) { return false; } for (let i = 0; i < newProperties.length; i++) { - if (oldProperties[i] != newProperties[i]) { + if (oldProperties[i] !== newProperties[i]) { return false; } } @@ -378,7 +378,7 @@ const buildTooltipForDropdown = function(dropdownName, lookupTable) { // Wait for load, in case Blockly.Msg is not yet populated. // utils.runAfterPageLoad() does not run in a Node.js environment due to lack // of document object, in which case skip the validation. - if (typeof document == 'object') { // Relies on document.readyState + if (typeof document === 'object') { // Relies on document.readyState utils.runAfterPageLoad(function() { for (let key in lookupTable) { // Will print warnings if reference is missing. @@ -392,7 +392,7 @@ const buildTooltipForDropdown = function(dropdownName, lookupTable) { * @this {Block} */ const extensionFn = function() { - if (this.type && blockTypesChecked.indexOf(this.type) == -1) { + if (this.type && blockTypesChecked.indexOf(this.type) === -1) { checkDropdownOptionsInTable(this, dropdownName, lookupTable); blockTypesChecked.push(this.type); } @@ -400,12 +400,12 @@ const buildTooltipForDropdown = function(dropdownName, lookupTable) { this.setTooltip(function() { const value = String(this.getFieldValue(dropdownName)); let tooltip = lookupTable[value]; - if (tooltip == null) { - if (blockTypesChecked.indexOf(this.type) == -1) { + if (tooltip === null) { + if (blockTypesChecked.indexOf(this.type) === -1) { // Warn for missing values on generated tooltips. let warning = 'No tooltip mapping for value ' + value + ' of field ' + dropdownName; - if (this.type != null) { + if (this.type !== null) { warning += (' of block type ' + this.type); } console.warn(warning + '.'); @@ -434,7 +434,7 @@ const checkDropdownOptionsInTable = function(block, dropdownName, lookupTable) { const options = dropdown.getOptions(); for (let i = 0; i < options.length; ++i) { const optionKey = options[i][1]; // label, then value - if (lookupTable[optionKey] == null) { + if (lookupTable[optionKey] === null) { console.warn( 'No tooltip mapping for value ' + optionKey + ' of field ' + dropdownName + ' of block type ' + block.type); @@ -458,7 +458,7 @@ const buildTooltipWithFieldText = function(msgTemplate, fieldName) { // Wait for load, in case Blockly.Msg is not yet populated. // utils.runAfterPageLoad() does not run in a Node.js environment due to lack // of document object, in which case skip the validation. - if (typeof document == 'object') { // Relies on document.readyState + if (typeof document === 'object') { // Relies on document.readyState utils.runAfterPageLoad(function() { // Will print warnings if reference is missing. utils.checkMessageReferences(msgTemplate); diff --git a/core/field.js b/core/field.js index 3b145e250..5606d7fbc 100644 --- a/core/field.js +++ b/core/field.js @@ -287,7 +287,7 @@ Field.prototype.SERIALIZABLE = false; */ Field.prototype.configure_ = function(config) { let tooltip = config['tooltip']; - if (typeof tooltip == 'string') { + if (typeof tooltip === 'string') { tooltip = utils.replaceMessageReferences(config['tooltip']); } tooltip && this.setTooltip(tooltip); @@ -627,7 +627,7 @@ Field.prototype.isVisible = function() { * @package */ Field.prototype.setVisible = function(visible) { - if (this.visible_ == visible) { + if (this.visible_ === visible) { return; } this.visible_ = visible; @@ -715,7 +715,7 @@ Field.prototype.showEditor = function(opt_e) { */ Field.prototype.updateSize_ = function(opt_margin) { const constants = this.getConstants(); - const xOffset = opt_margin != undefined ? + const xOffset = opt_margin !== undefined ? opt_margin : (this.borderRect_ ? this.getConstants().FIELD_BORDER_RECT_X_PADDING : 0); let totalWidth = xOffset * 2; @@ -795,7 +795,7 @@ Field.prototype.getSize = function() { if (this.isDirty_) { this.render_(); this.isDirty_ = false; - } else if (this.visible_ && this.size_.width == 0) { + } else if (this.visible_ && this.size_.width === 0) { // If the field is not visible the width will be 0 as well, one of the // problems with the old system. console.warn( diff --git a/core/field_angle.js b/core/field_angle.js index 35d218272..6d1c66885 100644 --- a/core/field_angle.js +++ b/core/field_angle.js @@ -218,27 +218,27 @@ FieldAngle.prototype.configure_ = function(config) { // Allow individual settings to override the mode setting. const clockwise = config['clockwise']; - if (typeof clockwise == 'boolean') { + if (typeof clockwise === 'boolean') { this.clockwise_ = clockwise; } // If these are passed as null then we should leave them on the default. let offset = config['offset']; - if (offset != null) { + if (offset !== null) { offset = Number(offset); if (!isNaN(offset)) { this.offset_ = offset; } } let wrap = config['wrap']; - if (wrap != null) { + if (wrap !== null) { wrap = Number(wrap); if (!isNaN(wrap)) { this.wrap_ = wrap; } } let round = config['round']; - if (round != null) { + if (round !== null) { round = Number(round); if (!isNaN(round)) { this.round_ = round; @@ -331,7 +331,7 @@ FieldAngle.prototype.dropdownCreate_ = function() { 'x1': FieldAngle.HALF + FieldAngle.RADIUS, 'y1': FieldAngle.HALF, 'x2': - FieldAngle.HALF + FieldAngle.RADIUS - (angle % 45 == 0 ? 10 : 5), + FieldAngle.HALF + FieldAngle.RADIUS - (angle % 45 === 0 ? 10 : 5), 'y2': FieldAngle.HALF, 'class': 'blocklyAngleMarks', 'transform': 'rotate(' + angle + ',' + FieldAngle.HALF + ',' + @@ -430,7 +430,7 @@ FieldAngle.prototype.displayMouseOrKeyboardValue_ = function(angle) { angle = Math.round(angle / this.round_) * this.round_; } angle = this.wrapValue_(angle); - if (angle != this.value_) { + if (angle !== this.value_) { this.setEditorValue_(angle); } }; diff --git a/core/field_checkbox.js b/core/field_checkbox.js index bafd7c1fc..e865b22f1 100644 --- a/core/field_checkbox.js +++ b/core/field_checkbox.js @@ -232,8 +232,8 @@ FieldCheckbox.prototype.getText = function() { * @private */ FieldCheckbox.prototype.convertValueToBool_ = function(value) { - if (typeof value == 'string') { - return value == 'TRUE'; + if (typeof value === 'string') { + return value === 'TRUE'; } else { return !!value; } diff --git a/core/field_colour.js b/core/field_colour.js index 9eea803d7..4156f5972 100644 --- a/core/field_colour.js +++ b/core/field_colour.js @@ -213,7 +213,7 @@ FieldColour.prototype.applyColour = function() { * @protected */ FieldColour.prototype.doClassValidation_ = function(opt_newValue) { - if (typeof opt_newValue != 'string') { + if (typeof opt_newValue !== 'string') { return null; } return colour.parse(opt_newValue); @@ -540,7 +540,7 @@ FieldColour.prototype.dropdownCreate_ = function() { aria.setState(table, aria.State.COLCOUNT, columns); let row; for (let i = 0; i < colours.length; i++) { - if (i % columns == 0) { + if (i % columns === 0) { row = document.createElement('tr'); aria.setRole(row, aria.Role.ROW); table.appendChild(row); @@ -553,9 +553,9 @@ FieldColour.prototype.dropdownCreate_ = function() { cell.setAttribute('data-index', i); aria.setRole(cell, aria.Role.GRIDCELL); aria.setState(cell, aria.State.LABEL, colours[i]); - aria.setState(cell, aria.State.SELECTED, colours[i] == selectedColour); + aria.setState(cell, aria.State.SELECTED, colours[i] === selectedColour); cell.style.backgroundColor = colours[i]; - if (colours[i] == selectedColour) { + if (colours[i] === selectedColour) { cell.className = 'blocklyColourSelected'; this.highlightedIndex_ = i; } diff --git a/core/field_dropdown.js b/core/field_dropdown.js index e9c63a31d..0dce01b94 100644 --- a/core/field_dropdown.js +++ b/core/field_dropdown.js @@ -53,7 +53,7 @@ const utilsString = goog.require('Blockly.utils.string'); * @alias Blockly.FieldDropdown */ const FieldDropdown = function(menuGenerator, opt_validator, opt_config) { - if (typeof menuGenerator != 'function') { + if (typeof menuGenerator !== 'function') { validateOptions(menuGenerator); } @@ -361,7 +361,7 @@ FieldDropdown.prototype.dropdownCreate_ = function() { for (let i = 0; i < options.length; i++) { let content = options[i][0]; // Human-readable text or image. const value = options[i][1]; // Language-neutral value. - if (typeof content == 'object') { + if (typeof content === 'object') { // An image, not text. const image = new Image(content['width'], content['height']); image.src = content['src']; @@ -373,8 +373,8 @@ FieldDropdown.prototype.dropdownCreate_ = function() { menuItem.setRightToLeft(this.sourceBlock_.RTL); menuItem.setCheckable(true); menu.addChild(menuItem); - menuItem.setChecked(value == this.value_); - if (value == this.value_) { + menuItem.setChecked(value === this.value_); + if (value === this.value_) { this.selectedMenuItem_ = menuItem; } menuItem.onAction(this.handleMenuActionEvent_, this); @@ -429,10 +429,10 @@ FieldDropdown.prototype.trimOptions_ = function() { // Localize label text and image alt text. for (let i = 0; i < options.length; i++) { const label = options[i][0]; - if (typeof label == 'string') { + if (typeof label === 'string') { options[i][0] = utils.replaceMessageReferences(label); } else { - if (label.alt != null) { + if (label.alt !== null) { options[i][0].alt = utils.replaceMessageReferences(label.alt); } hasImages = true; @@ -492,7 +492,7 @@ FieldDropdown.applyTrim_ = function(options, prefixLength, suffixLength) { * Otherwise false. */ FieldDropdown.prototype.isOptionListDynamic = function() { - return typeof this.menuGenerator_ == 'function'; + return typeof this.menuGenerator_ === 'function'; }; /** @@ -525,7 +525,7 @@ FieldDropdown.prototype.doClassValidation_ = function(opt_newValue) { const options = this.getOptions(true); for (let i = 0, option; (option = options[i]); i++) { // Options are tuples of human-readable text and language-neutral values. - if (option[1] == opt_newValue) { + if (option[1] === opt_newValue) { isValueValid = true; break; } @@ -552,7 +552,7 @@ FieldDropdown.prototype.doValueUpdate_ = function(newValue) { FieldDropdown.superClass_.doValueUpdate_.call(this, newValue); const options = this.getOptions(true); for (let i = 0, option; (option = options[i]); i++) { - if (option[1] == this.value_) { + if (option[1] === this.value_) { this.selectedOption_ = option; } } @@ -594,7 +594,7 @@ FieldDropdown.prototype.render_ = function() { // Show correct element. const option = this.selectedOption_ && this.selectedOption_[0]; - if (option && typeof option == 'object') { + if (option && typeof option === 'object') { this.renderSelectedImage_( /** @type {!FieldDropdown.ImageProperties} */ (option)); } else { @@ -724,7 +724,7 @@ FieldDropdown.prototype.getText_ = function() { return null; } const option = this.selectedOption_[0]; - if (typeof option == 'object') { + if (typeof option === 'object') { return option['alt']; } return option; @@ -751,15 +751,15 @@ const validateOptions = function(options) { 'Invalid option[' + i + ']: Each FieldDropdown option must be an ' + 'array. Found: ', tuple); - } else if (typeof tuple[1] != 'string') { + } else if (typeof tuple[1] !== 'string') { foundError = true; console.error( 'Invalid option[' + i + ']: Each FieldDropdown option id must be ' + 'a string. Found ' + tuple[1] + ' in: ', tuple); } else if ( - tuple[0] && (typeof tuple[0] != 'string') && - (typeof tuple[0].src != 'string')) { + tuple[0] && (typeof tuple[0] !== 'string') && + (typeof tuple[0].src !== 'string')) { foundError = true; console.error( 'Invalid option[' + i + ']: Each FieldDropdown option must have a ' + diff --git a/core/field_image.js b/core/field_image.js index 1983a6956..352ae49ed 100644 --- a/core/field_image.js +++ b/core/field_image.js @@ -108,7 +108,7 @@ const FieldImage = function( */ this.clickHandler_ = null; - if (typeof opt_onClick == 'function') { + if (typeof opt_onClick === 'function') { this.clickHandler_ = opt_onClick; } @@ -215,7 +215,7 @@ FieldImage.prototype.updateSize_ = function() { * @protected */ FieldImage.prototype.doClassValidation_ = function(opt_newValue) { - if (typeof opt_newValue != 'string') { + if (typeof opt_newValue !== 'string') { return null; } return opt_newValue; @@ -250,7 +250,7 @@ FieldImage.prototype.getFlipRtl = function() { * @public */ FieldImage.prototype.setAlt = function(alt) { - if (alt == this.altText_) { + if (alt === this.altText_) { return; } this.altText_ = alt || ''; diff --git a/core/field_number.js b/core/field_number.js index fdd603874..ad819106e 100644 --- a/core/field_number.js +++ b/core/field_number.js @@ -231,14 +231,14 @@ FieldNumber.prototype.setPrecision = function(precision) { FieldNumber.prototype.setPrecisionInternal_ = function(precision) { this.precision_ = Number(precision) || 0; let precisionString = String(this.precision_); - if (precisionString.indexOf('e') != -1) { + if (precisionString.indexOf('e') !== -1) { // String() is fast. But it turns .0000001 into '1e-7'. // Use the much slower toLocaleString to access all the digits. precisionString = this.precision_.toLocaleString('en-US', {maximumFractionDigits: 20}); } const decimalIndex = precisionString.indexOf('.'); - if (decimalIndex == -1) { + if (decimalIndex === -1) { // If the precision is 0 (float) allow any number of decimals, // otherwise allow none. this.decimalPlaces_ = precision ? 0 : null; @@ -292,7 +292,7 @@ FieldNumber.prototype.doClassValidation_ = function(opt_newValue) { n = Math.round(n / this.precision_) * this.precision_; } // Clean up floating point errors. - if (this.decimalPlaces_ != null) { + if (this.decimalPlaces_ !== null) { n = Number(n.toFixed(this.decimalPlaces_)); } return n; diff --git a/core/field_textinput.js b/core/field_textinput.js index bbf7ad506..ad2d708aa 100644 --- a/core/field_textinput.js +++ b/core/field_textinput.js @@ -146,7 +146,7 @@ FieldTextInput.prototype.CURSOR = 'text'; */ FieldTextInput.prototype.configure_ = function(config) { FieldTextInput.superClass_.configure_.call(this, config); - if (typeof config['spellcheck'] == 'boolean') { + if (typeof config['spellcheck'] === 'boolean') { this.spellcheck_ = config['spellcheck']; } }; @@ -282,7 +282,7 @@ FieldTextInput.prototype.render_ = function() { * @param {boolean} check True if checked. */ FieldTextInput.prototype.setSpellcheck = function(check) { - if (check == this.spellcheck_) { + if (check === this.spellcheck_) { return; } this.spellcheck_ = check; @@ -457,14 +457,14 @@ FieldTextInput.prototype.unbindInputEvents_ = function() { * @protected */ FieldTextInput.prototype.onHtmlInputKeyDown_ = function(e) { - if (e.keyCode == KeyCodes.ENTER) { + if (e.keyCode === KeyCodes.ENTER) { WidgetDiv.hide(); DropDownDiv.hideWithoutAnimation(); - } else if (e.keyCode == KeyCodes.ESC) { + } else if (e.keyCode === KeyCodes.ESC) { this.setValue(this.htmlInput_.untypedDefaultValue_); WidgetDiv.hide(); DropDownDiv.hideWithoutAnimation(); - } else if (e.keyCode == KeyCodes.TAB) { + } else if (e.keyCode === KeyCodes.TAB) { WidgetDiv.hide(); DropDownDiv.hideWithoutAnimation(); this.sourceBlock_.tab(this, !e.shiftKey); diff --git a/core/field_variable.js b/core/field_variable.js index d040b0cbe..72ff3d7ab 100644 --- a/core/field_variable.js +++ b/core/field_variable.js @@ -152,7 +152,7 @@ FieldVariable.prototype.initModel = function() { FieldVariable.prototype.shouldAddBorderRect_ = function() { return FieldVariable.superClass_.shouldAddBorderRect_.call(this) && (!this.getConstants().FIELD_DROPDOWN_NO_BORDER_RECT_SHADOW || - this.sourceBlock_.type != 'variables_get'); + this.sourceBlock_.type !== 'variables_get'); }; /** @@ -172,7 +172,7 @@ FieldVariable.prototype.fromXml = function(fieldElement) { this.sourceBlock_.workspace, id, variableName, variableType); // This should never happen :) - if (variableType != null && variableType !== variable.type) { + if (variableType !== null && variableType !== variable.type) { throw Error( 'Serialized variable type with id \'' + variable.getId() + '\' had type ' + variable.type + ', and ' + @@ -352,7 +352,7 @@ FieldVariable.prototype.typeIsAllowed_ = function(type) { return true; // If it's null, all types are valid. } for (let i = 0; i < typeList.length; i++) { - if (type == typeList[i]) { + if (type === typeList[i]) { return true; } } @@ -375,7 +375,7 @@ FieldVariable.prototype.getVariableTypes_ = function() { } } variableTypes = variableTypes || ['']; - if (variableTypes.length == 0) { + if (variableTypes.length === 0) { // Throw an error if variableTypes is an empty list. const name = this.getText(); throw Error( @@ -401,14 +401,14 @@ FieldVariable.prototype.setTypes_ = function( const defaultType = opt_defaultType || ''; let variableTypes; // Set the allowable variable types. Null means all types on the workspace. - if (opt_variableTypes == null || opt_variableTypes == undefined) { + if (opt_variableTypes === null || opt_variableTypes === undefined) { variableTypes = null; } else if (Array.isArray(opt_variableTypes)) { variableTypes = opt_variableTypes; // Make sure the default type is valid. let isInArray = false; for (let i = 0; i < variableTypes.length; i++) { - if (variableTypes[i] == defaultType) { + if (variableTypes[i] === defaultType) { isInArray = true; } } @@ -492,11 +492,11 @@ FieldVariable.prototype.onItemSelected_ = function(menu, menuItem) { const id = menuItem.getValue(); // Handle special cases. if (this.sourceBlock_ && this.sourceBlock_.workspace) { - if (id == internalConstants.RENAME_VARIABLE_ID) { + if (id === internalConstants.RENAME_VARIABLE_ID) { // Rename variable. Variables.renameVariable(this.sourceBlock_.workspace, this.variable_); return; - } else if (id == internalConstants.DELETE_VARIABLE_ID) { + } else if (id === internalConstants.DELETE_VARIABLE_ID) { // Delete variable. this.sourceBlock_.workspace.deleteVariableById(this.variable_.getId()); return; diff --git a/core/flyout_base.js b/core/flyout_base.js index 7db011276..bdf4c4eb2 100644 --- a/core/flyout_base.js +++ b/core/flyout_base.js @@ -413,7 +413,7 @@ Flyout.prototype.isVisible = function() { * @param {boolean} visible True if visible. */ Flyout.prototype.setVisible = function(visible) { - const visibilityChanged = (visible != this.isVisible()); + const visibilityChanged = (visible !== this.isVisible()); this.isVisible_ = visible; if (visibilityChanged) { @@ -431,7 +431,7 @@ Flyout.prototype.setVisible = function(visible) { * @param {boolean} visible Whether the container is visible. */ Flyout.prototype.setContainerVisible = function(visible) { - const visibilityChanged = (visible != this.containerVisible_); + const visibilityChanged = (visible !== this.containerVisible_); this.containerVisible_ = visible; if (visibilityChanged) { this.updateDisplay_(); @@ -469,7 +469,7 @@ Flyout.prototype.positionAt_ = function(width, height, x, y) { this.svgGroup_.setAttribute('height', height); this.workspace_.setCachedParentSvgSize(width, height); - if (this.svgGroup_.tagName == 'svg') { + if (this.svgGroup_.tagName === 'svg') { const transform = 'translate(' + x + 'px,' + y + 'px)'; dom.setCssTransform(this.svgGroup_, transform); } else { @@ -531,7 +531,7 @@ Flyout.prototype.show = function(flyoutDef) { this.clearOldBlocks_(); // Handle dynamic categories, represented by a name instead of a list. - if (typeof flyoutDef == 'string') { + if (typeof flyoutDef === 'string') { flyoutDef = this.getDynamicCategoryContents_(flyoutDef); } this.setVisible(true); @@ -646,7 +646,7 @@ Flyout.prototype.getDynamicCategoryContents_ = function(categoryName) { // valid XML list. const fnToApply = this.workspace_.targetWorkspace.getToolboxCategoryCallback(categoryName); - if (typeof fnToApply != 'function') { + if (typeof fnToApply !== 'function') { throw TypeError( 'Couldn\'t find a callback function when opening' + ' a toolbox category.'); @@ -722,12 +722,12 @@ Flyout.prototype.createFlyoutBlock_ = function(blockInfo) { Flyout.prototype.getRecycledBlock_ = function(blockType) { let index = -1; for (let i = 0; i < this.recycledBlocks_.length; i++) { - if (this.recycledBlocks_[i].type == blockType) { + if (this.recycledBlocks_[i].type === blockType) { index = i; break; } } - return index == -1 ? undefined : this.recycledBlocks_.splice(index, 1)[0]; + return index === -1 ? undefined : this.recycledBlocks_.splice(index, 1)[0]; }; /** @@ -1031,7 +1031,7 @@ Flyout.prototype.moveRectToBlock_ = function(rect, block) { Flyout.prototype.filterForCapacity_ = function() { const blocks = this.workspace_.getTopBlocks(false); for (let i = 0, block; (block = blocks[i]); i++) { - if (this.permanentlyDisabled_.indexOf(block) == -1) { + if (this.permanentlyDisabled_.indexOf(block) === -1) { const enable = this.targetWorkspace.isCapacityAvailable( utils.getBlockTypeCounts(block)); while (block) { diff --git a/core/flyout_horizontal.js b/core/flyout_horizontal.js index 6a5fe0f0b..c0ad2c2a1 100644 --- a/core/flyout_horizontal.js +++ b/core/flyout_horizontal.js @@ -62,7 +62,7 @@ HorizontalFlyout.prototype.setMetrics_ = function(xyRatio) { const viewMetrics = metricsManager.getViewMetrics(); const absoluteMetrics = metricsManager.getAbsoluteMetrics(); - if (typeof xyRatio.x == 'number') { + if (typeof xyRatio.x === 'number') { this.workspace_.scrollX = -(scrollMetrics.left + (scrollMetrics.width - viewMetrics.width) * xyRatio.x); @@ -96,9 +96,9 @@ HorizontalFlyout.prototype.getY = function() { const toolboxMetrics = metricsManager.getToolboxMetrics(); let y = 0; - const atTop = this.toolboxPosition_ == toolbox.Position.TOP; + const atTop = this.toolboxPosition_ === toolbox.Position.TOP; // If this flyout is not the trashcan flyout (e.g. toolbox or mutator). - if (this.targetWorkspace.toolboxPosition == this.toolboxPosition_) { + if (this.targetWorkspace.toolboxPosition === this.toolboxPosition_) { // If there is a category toolbox. if (this.targetWorkspace.getToolbox()) { if (atTop) { @@ -163,7 +163,7 @@ HorizontalFlyout.prototype.position = function() { * @private */ HorizontalFlyout.prototype.setBackgroundPath_ = function(width, height) { - const atTop = this.toolboxPosition_ == toolbox.Position.TOP; + const atTop = this.toolboxPosition_ === toolbox.Position.TOP; // Start at top left. const path = ['M 0,' + (atTop ? 0 : this.CORNER_RADIUS)]; @@ -251,7 +251,7 @@ HorizontalFlyout.prototype.layout_ = function(contents, gaps) { } for (let i = 0, item; (item = contents[i]); i++) { - if (item.type == 'block') { + if (item.type === 'block') { const block = item.block; const allBlocks = block.getDescendants(false); for (let j = 0, child; (child = allBlocks[j]); j++) { @@ -278,7 +278,7 @@ HorizontalFlyout.prototype.layout_ = function(contents, gaps) { cursorX += (blockHW.width + gaps[i]); this.addBlockListeners_(root, block, rect); - } else if (item.type == 'button') { + } else if (item.type === 'button') { this.initFlyoutButton_(item.button, cursorX, cursorY); cursorX += (item.button.width + gaps[i]); } @@ -330,7 +330,7 @@ HorizontalFlyout.prototype.getClientRect = function() { const BIG_NUM = 1000000000; const top = flyoutRect.top; - if (this.toolboxPosition_ == toolbox.Position.TOP) { + if (this.toolboxPosition_ === toolbox.Position.TOP) { const height = flyoutRect.height; return new Rect(-BIG_NUM, top + height, -BIG_NUM, BIG_NUM); } else { // Bottom. @@ -358,15 +358,15 @@ HorizontalFlyout.prototype.reflowInternal_ = function() { flyoutHeight *= this.workspace_.scale; flyoutHeight += Scrollbar.scrollbarThickness; - if (this.height_ != flyoutHeight) { + if (this.height_ !== flyoutHeight) { for (let i = 0, block; (block = blocks[i]); i++) { if (block.flyoutRect_) { this.moveRectToBlock_(block.flyoutRect_, block); } } - if (this.targetWorkspace.toolboxPosition == this.toolboxPosition_ && - this.toolboxPosition_ == toolbox.Position.TOP && + if (this.targetWorkspace.toolboxPosition === this.toolboxPosition_ && + this.toolboxPosition_ === toolbox.Position.TOP && !this.targetWorkspace.getToolbox()) { // This flyout is a simple toolbox. Reposition the workspace so that (0,0) // is in the correct position relative to the new absolute edge (ie diff --git a/core/flyout_vertical.js b/core/flyout_vertical.js index 3f275003e..45fced2f3 100644 --- a/core/flyout_vertical.js +++ b/core/flyout_vertical.js @@ -70,7 +70,7 @@ VerticalFlyout.prototype.setMetrics_ = function(xyRatio) { const viewMetrics = metricsManager.getViewMetrics(); const absoluteMetrics = metricsManager.getAbsoluteMetrics(); - if (typeof xyRatio.y == 'number') { + if (typeof xyRatio.y === 'number') { this.workspace_.scrollY = -(scrollMetrics.top + (scrollMetrics.height - viewMetrics.height) * xyRatio.y); @@ -95,17 +95,17 @@ VerticalFlyout.prototype.getX = function() { let x = 0; // If this flyout is not the trashcan flyout (e.g. toolbox or mutator). - if (this.targetWorkspace.toolboxPosition == this.toolboxPosition_) { + if (this.targetWorkspace.toolboxPosition === this.toolboxPosition_) { // If there is a category toolbox. if (this.targetWorkspace.getToolbox()) { - if (this.toolboxPosition_ == toolbox.Position.LEFT) { + if (this.toolboxPosition_ === toolbox.Position.LEFT) { x = toolboxMetrics.width; } else { x = viewMetrics.width - this.width_; } // Simple (flyout-only) toolbox. } else { - if (this.toolboxPosition_ == toolbox.Position.LEFT) { + if (this.toolboxPosition_ === toolbox.Position.LEFT) { x = 0; } else { // The simple flyout does not cover the workspace. @@ -114,7 +114,7 @@ VerticalFlyout.prototype.getX = function() { } // Trashcan flyout is opposite the main flyout. } else { - if (this.toolboxPosition_ == toolbox.Position.LEFT) { + if (this.toolboxPosition_ === toolbox.Position.LEFT) { x = 0; } else { // Because the anchor point of the flyout is on the left, but we want @@ -169,7 +169,7 @@ VerticalFlyout.prototype.position = function() { * @private */ VerticalFlyout.prototype.setBackgroundPath_ = function(width, height) { - const atRight = this.toolboxPosition_ == toolbox.Position.RIGHT; + const atRight = this.toolboxPosition_ === toolbox.Position.RIGHT; const totalWidth = width + this.CORNER_RADIUS; // Decide whether to start on the left or right. @@ -238,7 +238,7 @@ VerticalFlyout.prototype.layout_ = function(contents, gaps) { let cursorY = margin; for (let i = 0, item; (item = contents[i]); i++) { - if (item.type == 'block') { + if (item.type === 'block') { const block = item.block; const allBlocks = block.getDescendants(false); for (let j = 0, child; (child = allBlocks[j]); j++) { @@ -259,7 +259,7 @@ VerticalFlyout.prototype.layout_ = function(contents, gaps) { this.addBlockListeners_(root, block, rect); cursorY += blockHW.height + gaps[i]; - } else if (item.type == 'button') { + } else if (item.type === 'button') { this.initFlyoutButton_(item.button, cursorX, cursorY); cursorY += item.button.height + gaps[i]; } @@ -310,7 +310,7 @@ VerticalFlyout.prototype.getClientRect = function() { const BIG_NUM = 1000000000; const left = flyoutRect.left; - if (this.toolboxPosition_ == toolbox.Position.LEFT) { + if (this.toolboxPosition_ === toolbox.Position.LEFT) { const width = flyoutRect.width; return new Rect(-BIG_NUM, BIG_NUM, -BIG_NUM, left + width); } else { // Right @@ -341,7 +341,7 @@ VerticalFlyout.prototype.reflowInternal_ = function() { flyoutWidth *= this.workspace_.scale; flyoutWidth += Scrollbar.scrollbarThickness; - if (this.width_ != flyoutWidth) { + if (this.width_ !== flyoutWidth) { for (let i = 0, block; (block = blocks[i]); i++) { if (this.RTL) { // With the flyoutWidth known, right-align the blocks. @@ -366,8 +366,8 @@ VerticalFlyout.prototype.reflowInternal_ = function() { } } - if (this.targetWorkspace.toolboxPosition == this.toolboxPosition_ && - this.toolboxPosition_ == toolbox.Position.LEFT && + if (this.targetWorkspace.toolboxPosition === this.toolboxPosition_ && + this.toolboxPosition_ === toolbox.Position.LEFT && !this.targetWorkspace.getToolbox()) { // This flyout is a simple toolbox. Reposition the workspace so that (0,0) // is in the correct position relative to the new absolute edge (ie diff --git a/core/generator.js b/core/generator.js index f98381866..6ddcb6740 100644 --- a/core/generator.js +++ b/core/generator.js @@ -201,7 +201,7 @@ Generator.prototype.blockToCode = function(block, opt_thisOnly) { } const func = this[block.type]; - if (typeof func != 'function') { + if (typeof func !== 'function') { throw Error( 'Language "' + this.name_ + '" does not know how to generate ' + 'code for block type "' + block.type + '".'); @@ -217,7 +217,7 @@ Generator.prototype.blockToCode = function(block, opt_thisOnly) { throw TypeError('Expecting string from statement block: ' + block.type); } return [this.scrub_(block, code[0], opt_thisOnly), code[1]]; - } else if (typeof code == 'string') { + } else if (typeof code === 'string') { if (this.STATEMENT_PREFIX && !block.suppressPrefixSuffix) { code = this.injectId(this.STATEMENT_PREFIX, block) + code; } @@ -274,8 +274,8 @@ Generator.prototype.valueToCode = function(block, name, outerOrder) { const outerOrderClass = Math.floor(outerOrder); const innerOrderClass = Math.floor(innerOrder); if (outerOrderClass <= innerOrderClass) { - if (outerOrderClass == innerOrderClass && - (outerOrderClass == 0 || outerOrderClass == 99)) { + if (outerOrderClass === innerOrderClass && + (outerOrderClass === 0 || outerOrderClass === 99)) { // Don't generate parens around NONE-NONE and ATOMIC-ATOMIC pairs. // 0 is the atomic order, 99 is the none order. No parentheses needed. // In all known languages multiple such code blocks are not order @@ -287,8 +287,8 @@ Generator.prototype.valueToCode = function(block, name, outerOrder) { parensNeeded = true; // Check for special exceptions. for (let i = 0; i < this.ORDER_OVERRIDES.length; i++) { - if (this.ORDER_OVERRIDES[i][0] == outerOrder && - this.ORDER_OVERRIDES[i][1] == innerOrder) { + if (this.ORDER_OVERRIDES[i][0] === outerOrder && + this.ORDER_OVERRIDES[i][1] === innerOrder) { parensNeeded = false; break; } @@ -317,7 +317,7 @@ Generator.prototype.statementToCode = function(block, name) { let code = this.blockToCode(targetBlock); // Value blocks must return code and order of operations info. // Statement blocks must only return code. - if (typeof code != 'string') { + if (typeof code !== 'string') { throw TypeError( 'Expecting code from statement block: ' + (targetBlock && targetBlock.type)); @@ -478,7 +478,7 @@ Generator.prototype.provideFunction_ = function(desiredName, code) { // character first, then replace them all with the indent. // We are assuming that no provided functions contain a literal null char. let oldCodeText; - while (oldCodeText != codeText) { + while (oldCodeText !== codeText) { oldCodeText = codeText; codeText = codeText.replace(/^(( {2})*) {2}/gm, '$1\0'); } diff --git a/core/gesture.js b/core/gesture.js index 8fc52c887..3e7892c15 100644 --- a/core/gesture.js +++ b/core/gesture.js @@ -511,9 +511,9 @@ Gesture.prototype.doStart = function(e) { return; } - if ((e.type.toLowerCase() == 'touchstart' || - e.type.toLowerCase() == 'pointerdown') && - e.pointerType != 'mouse') { + if ((e.type.toLowerCase() === 'touchstart' || + e.type.toLowerCase() === 'pointerdown') && + e.pointerType !== 'mouse') { Touch.longStart(e, this); } @@ -837,7 +837,7 @@ Gesture.prototype.setStartBlock = function(block) { // If the gesture already went through a bubble, don't set the start block. if (!this.startBlock_ && !this.startBubble_) { this.startBlock_ = block; - if (block.isInFlyout && block != block.getRootBlock()) { + if (block.isInFlyout && block !== block.getRootBlock()) { this.setTargetBlock_(block.getRootBlock()); } else { this.setTargetBlock_(block); diff --git a/core/inject.js b/core/inject.js index a50b503bc..1465d905b 100644 --- a/core/inject.js +++ b/core/inject.js @@ -50,7 +50,7 @@ const {BlockDragSurfaceSvg} = goog.require('Blockly.BlockDragSurfaceSvg'); * @alias Blockly.inject */ const inject = function(container, opt_options) { - if (typeof container == 'string') { + if (typeof container === 'string') { container = document.getElementById(container) || document.querySelector(container); } @@ -235,7 +235,7 @@ const init = function(mainWorkspace) { // Build a fixed flyout with the root blocks. flyout.init(mainWorkspace); flyout.show(options.languageTree); - if (typeof flyout.scrollToStart == 'function') { + if (typeof flyout.scrollToStart === 'function') { flyout.scrollToStart(); } } diff --git a/core/input.js b/core/input.js index 0561de18b..9fa58040e 100644 --- a/core/input.js +++ b/core/input.js @@ -43,7 +43,7 @@ goog.require('Blockly.FieldLabel'); * @alias Blockly.Input */ const Input = function(type, name, block, connection) { - if (type != inputTypes.DUMMY && !name) { + if (type !== inputTypes.DUMMY && !name) { throw Error('Value inputs and statement inputs must have non-empty name.'); } /** @type {number} */ @@ -110,12 +110,12 @@ Input.prototype.insertFieldAt = function(index, field, opt_name) { } // Falsy field values don't generate a field, unless the field is an empty // string and named. - if (!field && !(field == '' && opt_name)) { + if (!field && !(field === '' && opt_name)) { return index; } // Generate a FieldLabel when given a plain text field. - if (typeof field == 'string') { + if (typeof field === 'string') { field = /** @type {!Field} **/ (fieldRegistry.fromJson({ 'type': 'field_label', 'text': field, @@ -199,7 +199,7 @@ Input.prototype.setVisible = function(visible) { // because this function is package. If this function goes back to being a // public API tests (lots of tests) should be added. let renderList = []; - if (this.visible_ == visible) { + if (this.visible_ === visible) { return renderList; } this.visible_ = visible; diff --git a/core/insertion_marker_manager.js b/core/insertion_marker_manager.js index 274278f04..549559e25 100644 --- a/core/insertion_marker_manager.js +++ b/core/insertion_marker_manager.js @@ -307,7 +307,7 @@ InsertionMarkerManager.prototype.createMarkerBlock_ = function(sourceBlock) { // child blocks here. for (let i = 0; i < sourceBlock.inputList.length; i++) { const sourceInput = sourceBlock.inputList[i]; - if (sourceInput.name == constants.COLLAPSED_INPUT_NAME) { + if (sourceInput.name === constants.COLLAPSED_INPUT_NAME) { continue; // Ignore the collapsed input. } const resultInput = result.inputList[i]; @@ -351,7 +351,7 @@ InsertionMarkerManager.prototype.initAvailableConnections_ = function() { const available = this.topBlock_.getConnections_(false); // Also check the last connection on this stack const lastOnStack = this.topBlock_.lastConnectionInStack(true); - if (lastOnStack && lastOnStack != this.topBlock_.nextConnection) { + if (lastOnStack && lastOnStack !== this.topBlock_.nextConnection) { available.push(lastOnStack); this.lastOnStack_ = lastOnStack; if (this.lastMarker_) { @@ -389,8 +389,8 @@ InsertionMarkerManager.prototype.shouldUpdatePreviews_ = function( // Decide whether the new connection has higher priority. if (this.localConnection_ && this.closestConnection_) { // The connection was the same as the current connection. - if (this.closestConnection_ == candidateClosest && - this.localConnection_ == candidateLocal) { + if (this.closestConnection_ === candidateClosest && + this.localConnection_ === candidateLocal) { return false; } const xDiff = this.localConnection_.x + dxy.x - this.closestConnection_.x; @@ -511,7 +511,7 @@ InsertionMarkerManager.prototype.maybeShowPreview_ = function(candidate) { } // Something went wrong and we're trying to connect to an invalid connection. - if (closest == this.closestConnection_ || + if (closest === this.closestConnection_ || closest.getSourceBlock().isInsertionMarker()) { console.log('Trying to connect to an insertion marker'); return; @@ -571,8 +571,8 @@ InsertionMarkerManager.prototype.maybeHidePreview_ = function(candidate) { // If there's a new preview and there was an preview before, and either // connection has changed, remove the old preview. const hadPreview = this.closestConnection_ && this.localConnection_; - const closestChanged = this.closestConnection_ != candidate.closest; - const localChanged = this.localConnection_ != candidate.local; + const closestChanged = this.closestConnection_ !== candidate.closest; + const localChanged = this.localConnection_ !== candidate.local; // Also hide if we had a preview before but now we're going to delete // instead. @@ -617,11 +617,11 @@ InsertionMarkerManager.prototype.showInsertionMarker_ = function() { const local = this.localConnection_; const closest = this.closestConnection_; - const isLastInStack = this.lastOnStack_ && local == this.lastOnStack_; + const isLastInStack = this.lastOnStack_ && local === this.lastOnStack_; const imBlock = isLastInStack ? this.lastMarker_ : this.firstMarker_; const imConn = imBlock.getMatchingConnection(local.getSourceBlock(), local); - if (imConn == this.markerConnection_) { + if (imConn === this.markerConnection_) { throw Error( 'Made it to showInsertionMarker_ even though the marker isn\'t ' + 'changing'); @@ -663,9 +663,9 @@ InsertionMarkerManager.prototype.hideInsertionMarker_ = function() { const markerOutput = imBlock.outputConnection; const isFirstInStatementStack = - (imConn == markerNext && !(markerPrev && markerPrev.targetConnection)); + (imConn === markerNext && !(markerPrev && markerPrev.targetConnection)); - const isFirstInOutputStack = imConn.type == ConnectionType.INPUT_VALUE && + const isFirstInOutputStack = imConn.type === ConnectionType.INPUT_VALUE && !(markerOutput && markerOutput.targetConnection); // The insertion marker is the first block in a stack. Unplug won't do // anything in that case. Instead, unplug the following block. @@ -674,7 +674,7 @@ InsertionMarkerManager.prototype.hideInsertionMarker_ = function() { } // Inside of a C-block, first statement connection. else if ( - imConn.type == ConnectionType.NEXT_STATEMENT && imConn != markerNext) { + imConn.type === ConnectionType.NEXT_STATEMENT && imConn !== markerNext) { const innerConnection = imConn.targetConnection; innerConnection.getSourceBlock().unplug(false); diff --git a/core/keyboard_nav/ast_node.js b/core/keyboard_nav/ast_node.js index a3db5b34c..cc509f22d 100644 --- a/core/keyboard_nav/ast_node.js +++ b/core/keyboard_nav/ast_node.js @@ -160,16 +160,16 @@ ASTNode.createConnectionNode = function(connection) { return null; } const type = connection.type; - if (type == ConnectionType.INPUT_VALUE) { + if (type === ConnectionType.INPUT_VALUE) { return ASTNode.createInputNode(connection.getParentInput()); } else if ( - type == ConnectionType.NEXT_STATEMENT && connection.getParentInput()) { + type === ConnectionType.NEXT_STATEMENT && connection.getParentInput()) { return ASTNode.createInputNode(connection.getParentInput()); - } else if (type == ConnectionType.NEXT_STATEMENT) { + } else if (type === ConnectionType.NEXT_STATEMENT) { return new ASTNode(ASTNode.types.NEXT, connection); - } else if (type == ConnectionType.OUTPUT_VALUE) { + } else if (type === ConnectionType.OUTPUT_VALUE) { return new ASTNode(ASTNode.types.OUTPUT, connection); - } else if (type == ConnectionType.PREVIOUS_STATEMENT) { + } else if (type === ConnectionType.PREVIOUS_STATEMENT) { return new ASTNode(ASTNode.types.PREVIOUS, connection); } return null; @@ -444,10 +444,10 @@ ASTNode.prototype.navigateBetweenStacks_ = function(forward) { const topBlocks = curRoot.workspace.getTopBlocks(true); for (let i = 0; i < topBlocks.length; i++) { const topBlock = topBlocks[i]; - if (curRoot.id == topBlock.id) { + if (curRoot.id === topBlock.id) { const offset = forward ? 1 : -1; const resultIndex = i + offset; - if (resultIndex == -1 || resultIndex == topBlocks.length) { + if (resultIndex === -1 || resultIndex === topBlocks.length) { return null; } return ASTNode.createStackNode(topBlocks[resultIndex]); diff --git a/core/keyboard_nav/basic_cursor.js b/core/keyboard_nav/basic_cursor.js index a953b1b16..bdc18b7bd 100644 --- a/core/keyboard_nav/basic_cursor.js +++ b/core/keyboard_nav/basic_cursor.js @@ -174,9 +174,9 @@ BasicCursor.prototype.getPreviousNode_ = function(node, isValid) { BasicCursor.prototype.validNode_ = function(node) { let isValid = false; const type = node && node.getType(); - if (type == ASTNode.types.OUTPUT || type == ASTNode.types.INPUT || - type == ASTNode.types.FIELD || type == ASTNode.types.NEXT || - type == ASTNode.types.PREVIOUS || type == ASTNode.types.WORKSPACE) { + if (type === ASTNode.types.OUTPUT || type === ASTNode.types.INPUT || + type === ASTNode.types.FIELD || type === ASTNode.types.NEXT || + type === ASTNode.types.PREVIOUS || type === ASTNode.types.WORKSPACE) { isValid = true; } return isValid; diff --git a/core/keyboard_nav/cursor.js b/core/keyboard_nav/cursor.js index 11895bb83..751be8b99 100644 --- a/core/keyboard_nav/cursor.js +++ b/core/keyboard_nav/cursor.js @@ -54,8 +54,8 @@ Cursor.prototype.next = function() { let newNode = curNode.next(); while (newNode && newNode.next() && - (newNode.getType() == ASTNode.types.NEXT || - newNode.getType() == ASTNode.types.BLOCK)) { + (newNode.getType() === ASTNode.types.NEXT || + newNode.getType() === ASTNode.types.BLOCK)) { newNode = newNode.next(); } @@ -78,8 +78,8 @@ Cursor.prototype.in = function() { } // If we are on a previous or output connection, go to the block level before // performing next operation. - if (curNode.getType() == ASTNode.types.PREVIOUS || - curNode.getType() == ASTNode.types.OUTPUT) { + if (curNode.getType() === ASTNode.types.PREVIOUS || + curNode.getType() === ASTNode.types.OUTPUT) { curNode = curNode.next(); } const newNode = curNode.in(); @@ -104,8 +104,8 @@ Cursor.prototype.prev = function() { let newNode = curNode.prev(); while (newNode && newNode.prev() && - (newNode.getType() == ASTNode.types.NEXT || - newNode.getType() == ASTNode.types.BLOCK)) { + (newNode.getType() === ASTNode.types.NEXT || + newNode.getType() === ASTNode.types.BLOCK)) { newNode = newNode.prev(); } @@ -128,7 +128,7 @@ Cursor.prototype.out = function() { } let newNode = curNode.out(); - if (newNode && newNode.getType() == ASTNode.types.BLOCK) { + if (newNode && newNode.getType() === ASTNode.types.BLOCK) { newNode = newNode.prev() || newNode; } diff --git a/core/keyboard_nav/tab_navigate_cursor.js b/core/keyboard_nav/tab_navigate_cursor.js index 58463ead4..176110f9c 100644 --- a/core/keyboard_nav/tab_navigate_cursor.js +++ b/core/keyboard_nav/tab_navigate_cursor.js @@ -47,7 +47,7 @@ TabNavigateCursor.prototype.validNode_ = function(node) { const type = node && node.getType(); if (node) { const location = /** @type {Field} */ (node.getLocation()); - if (type == ASTNode.types.FIELD && location && location.isTabNavigable() && + if (type === ASTNode.types.FIELD && location && location.isTabNavigable() && location.isClickable()) { isValid = true; } diff --git a/core/menu.js b/core/menu.js index 133585eaa..ab160bb21 100644 --- a/core/menu.js +++ b/core/menu.js @@ -244,11 +244,11 @@ Menu.prototype.getMenuItem_ = function(elem) { // a menu item's div, or some element within the menu item. // Walk up parents until one meets either the menu's root element, or // a menu item's div. - while (elem && elem != menuElem) { + while (elem && elem !== menuElem) { if (dom.hasClass(elem, 'blocklyMenuItem')) { // Having found a menu item's div, locate that menu item in this menu. for (let i = 0, menuItem; (menuItem = this.menuItems_[i]); i++) { - if (menuItem.getElement() == elem) { + if (menuItem.getElement() === elem) { return menuItem; } } @@ -351,7 +351,7 @@ Menu.prototype.handleMouseOver_ = function(e) { if (menuItem) { if (menuItem.isEnabled()) { - if (this.highlightedItem_ != menuItem) { + if (this.highlightedItem_ !== menuItem) { this.setHighlighted(menuItem); } } else { @@ -369,7 +369,7 @@ Menu.prototype.handleClick_ = function(e) { const oldCoords = this.openingCoords; // Clear out the saved opening coords immediately so they're not used twice. this.openingCoords = null; - if (oldCoords && typeof e.clientX == 'number') { + if (oldCoords && typeof e.clientX === 'number') { const newCoords = new Coordinate(e.clientX, e.clientY); if (Coordinate.distance(oldCoords, newCoords) < 1) { // This menu was opened by a mousedown and we're handling the consequent diff --git a/core/menuitem.js b/core/menuitem.js index 05239babd..84abee8fa 100644 --- a/core/menuitem.js +++ b/core/menuitem.js @@ -131,7 +131,7 @@ MenuItem.prototype.createDom = function() { } let contentDom = /** @type {!HTMLElement} */ (this.content_); - if (typeof this.content_ == 'string') { + if (typeof this.content_ === 'string') { contentDom = document.createTextNode(this.content_); } content.appendChild(contentDom); diff --git a/core/metrics_manager.js b/core/metrics_manager.js index 65835aaad..bb1406e7f 100644 --- a/core/metrics_manager.js +++ b/core/metrics_manager.js @@ -179,8 +179,8 @@ MetricsManager.prototype.getAbsoluteMetrics = function() { const toolboxPosition = doesToolboxExist ? toolboxMetrics.position : flyoutMetrics.position; - const atLeft = toolboxPosition == toolboxUtils.Position.LEFT; - const atTop = toolboxPosition == toolboxUtils.Position.TOP; + const atLeft = toolboxPosition === toolboxUtils.Position.LEFT; + const atTop = toolboxPosition === toolboxUtils.Position.TOP; if (doesToolboxExist && atLeft) { absoluteLeft = toolboxMetrics.width; } else if (doesFlyoutExist && atLeft) { @@ -220,21 +220,21 @@ MetricsManager.prototype.getViewMetrics = function( doesToolboxExist ? toolboxMetrics.position : flyoutMetrics.position; if (this.workspace_.getToolbox()) { - if (toolboxPosition == toolboxUtils.Position.TOP || - toolboxPosition == toolboxUtils.Position.BOTTOM) { + if (toolboxPosition === toolboxUtils.Position.TOP || + toolboxPosition === toolboxUtils.Position.BOTTOM) { svgMetrics.height -= toolboxMetrics.height; } else if ( - toolboxPosition == toolboxUtils.Position.LEFT || - toolboxPosition == toolboxUtils.Position.RIGHT) { + toolboxPosition === toolboxUtils.Position.LEFT || + toolboxPosition === toolboxUtils.Position.RIGHT) { svgMetrics.width -= toolboxMetrics.width; } } else if (this.workspace_.getFlyout(true)) { - if (toolboxPosition == toolboxUtils.Position.TOP || - toolboxPosition == toolboxUtils.Position.BOTTOM) { + if (toolboxPosition === toolboxUtils.Position.TOP || + toolboxPosition === toolboxUtils.Position.BOTTOM) { svgMetrics.height -= flyoutMetrics.height; } else if ( - toolboxPosition == toolboxUtils.Position.LEFT || - toolboxPosition == toolboxUtils.Position.RIGHT) { + toolboxPosition === toolboxUtils.Position.LEFT || + toolboxPosition === toolboxUtils.Position.RIGHT) { svgMetrics.width -= flyoutMetrics.width; } } diff --git a/core/mutator.js b/core/mutator.js index 3f36d8692..1667d79be 100644 --- a/core/mutator.js +++ b/core/mutator.js @@ -295,7 +295,7 @@ Mutator.prototype.onBubbleMove_ = function() { * @param {boolean} visible True if the bubble should be visible. */ Mutator.prototype.setVisible = function(visible) { - if (visible == this.isVisible()) { + if (visible === this.isVisible()) { // No change. return; } @@ -378,8 +378,8 @@ Mutator.prototype.setVisible = function(visible) { */ Mutator.prototype.workspaceChanged_ = function(e) { if (!(e.isUiEvent || - (e.type == eventUtils.CHANGE && e.element == 'disabled') || - e.type == eventUtils.CREATE)) { + (e.type === eventUtils.CHANGE && e.element === 'disabled') || + e.type === eventUtils.CREATE)) { this.updateWorkspace_(); } }; @@ -418,7 +418,7 @@ Mutator.prototype.updateWorkspace_ = function() { } // When the mutator's workspace changes, update the source block. - if (this.rootBlock_.workspace == this.workspace_) { + if (this.rootBlock_.workspace === this.workspace_) { eventUtils.setGroup(true); const block = /** @type {!BlockSvg} */ (this.block_); const oldExtraState = BlockChange.getExtraBlockState_(block); @@ -440,7 +440,7 @@ Mutator.prototype.updateWorkspace_ = function() { } const newExtraState = BlockChange.getExtraBlockState_(block); - if (oldExtraState != newExtraState) { + if (oldExtraState !== newExtraState) { eventUtils.fire(new (eventUtils.get(eventUtils.BLOCK_CHANGE))( block, 'mutation', null, oldExtraState, newExtraState)); // Ensure that any bump is part of this mutation's event group. @@ -505,8 +505,8 @@ Mutator.reconnect = function(connectionChild, block, inputName) { } const connectionParent = block.getInput(inputName).connection; const currentParent = connectionChild.targetBlock(); - if ((!currentParent || currentParent == block) && - connectionParent.targetConnection != connectionChild) { + if ((!currentParent || currentParent === block) && + connectionParent.targetConnection !== connectionChild) { if (connectionParent.isConnected()) { // There's already something connected here. Get rid of it. connectionParent.disconnect(); diff --git a/core/names.js b/core/names.js index aafba1396..b57a0c565 100644 --- a/core/names.js +++ b/core/names.js @@ -145,7 +145,7 @@ Names.prototype.populateProcedures = function(workspace) { */ Names.prototype.getName = function(nameOrId, realm) { let name = nameOrId; - if (realm == internalConstants.VARIABLE_CATEGORY_NAME) { + if (realm === internalConstants.VARIABLE_CATEGORY_NAME) { const varName = this.getNameForUserVariable_(nameOrId); if (varName) { // Successful ID lookup. @@ -154,8 +154,8 @@ Names.prototype.getName = function(nameOrId, realm) { } const normalizedName = name.toLowerCase(); - const isVar = realm == internalConstants.VARIABLE_CATEGORY_NAME || - realm == Names.DEVELOPER_VARIABLE_TYPE; + const isVar = realm === internalConstants.VARIABLE_CATEGORY_NAME || + realm === Names.DEVELOPER_VARIABLE_TYPE; const prefix = isVar ? this.variablePrefix_ : ''; if (!(realm in this.db_)) { @@ -201,8 +201,8 @@ Names.prototype.getDistinctName = function(name, realm) { } safeName += i; this.dbReverse_[safeName] = true; - const isVar = realm == internalConstants.VARIABLE_CATEGORY_NAME || - realm == Names.DEVELOPER_VARIABLE_TYPE; + const isVar = realm === internalConstants.VARIABLE_CATEGORY_NAME || + realm === Names.DEVELOPER_VARIABLE_TYPE; const prefix = isVar ? this.variablePrefix_ : ''; return prefix + safeName; }; @@ -224,7 +224,7 @@ Names.prototype.safeName_ = function(name) { // https://github.com/google/blockly/issues/1654 name = encodeURI(name.replace(/ /g, '_')).replace(/[^\w]/g, '_'); // Most languages don't allow names with leading numbers. - if ('0123456789'.indexOf(name[0]) != -1) { + if ('0123456789'.indexOf(name[0]) !== -1) { name = 'my_' + name; } } @@ -240,7 +240,7 @@ Names.prototype.safeName_ = function(name) { */ Names.equals = function(name1, name2) { // name1.localeCompare(name2) is slower. - return name1.toLowerCase() == name2.toLowerCase(); + return name1.toLowerCase() === name2.toLowerCase(); }; exports = Names; diff --git a/core/options.js b/core/options.js index 724bbf88c..bc499c913 100644 --- a/core/options.js +++ b/core/options.js @@ -94,7 +94,7 @@ const Options = function(options) { toolboxPosition = toolboxAtStart ? toolbox.Position.TOP : toolbox.Position.BOTTOM; } else { - toolboxPosition = (toolboxAtStart == rtl) ? toolbox.Position.RIGHT : + toolboxPosition = (toolboxAtStart === rtl) ? toolbox.Position.RIGHT : toolbox.Position.LEFT; } @@ -261,7 +261,7 @@ Options.parseMoveOptions_ = function(options, hasCategories) { const moveOptions = {}; if (move['scrollbars'] === undefined && options['scrollbars'] === undefined) { moveOptions.scrollbars = hasCategories; - } else if (typeof move['scrollbars'] == 'object') { + } else if (typeof move['scrollbars'] === 'object') { moveOptions.scrollbars = {}; moveOptions.scrollbars.horizontal = !!move['scrollbars']['horizontal']; moveOptions.scrollbars.vertical = !!move['scrollbars']['vertical']; @@ -281,7 +281,7 @@ Options.parseMoveOptions_ = function(options, hasCategories) { if (!moveOptions.scrollbars || move['wheel'] === undefined) { // Defaults to true if single-direction scroll is enabled. - moveOptions.wheel = typeof moveOptions.scrollbars == 'object'; + moveOptions.wheel = typeof moveOptions.scrollbars === 'object'; } else { moveOptions.wheel = !!move['wheel']; } @@ -373,7 +373,7 @@ Options.parseGridOptions_ = function(options) { */ Options.parseThemeOptions_ = function(options) { const theme = options['theme'] || Classic; - if (typeof theme == 'string') { + if (typeof theme === 'string') { return /** @type {!Theme} */ ( registry.getObject(registry.Type.THEME, theme)); } else if (theme instanceof Theme) { diff --git a/core/positionable_helpers.js b/core/positionable_helpers.js index 58f97b121..09c81b6c5 100644 --- a/core/positionable_helpers.js +++ b/core/positionable_helpers.js @@ -103,7 +103,7 @@ const getStartPositionRect = function( if (hasVerticalScrollbar && workspace.RTL) { left += Scrollbar.scrollbarThickness; } - } else { // position.horizontal == horizontalPosition.RIGHT + } else { // position.horizontal === horizontalPosition.RIGHT left = metrics.absoluteMetrics.left + metrics.viewMetrics.width - size.width - horizontalPadding; if (hasVerticalScrollbar && !workspace.RTL) { @@ -114,7 +114,7 @@ const getStartPositionRect = function( let top = 0; if (position.vertical === verticalPosition.TOP) { top = metrics.absoluteMetrics.top + verticalPadding; - } else { // position.vertical == verticalPosition.BOTTOM + } else { // position.vertical === verticalPosition.BOTTOM top = metrics.absoluteMetrics.top + metrics.viewMetrics.height - size.height - verticalPadding; if (workspace.scrollbar && workspace.scrollbar.canScrollHorizontally()) { @@ -176,7 +176,7 @@ const bumpPositionRect = function(startRect, margin, bumpDir, savedPositions) { if (boundingRect.intersects(otherEl)) { if (bumpDir === bumpDirection.UP) { top = otherEl.top - height - margin; - } else { // bumpDir == bumpDirection.DOWN + } else { // bumpDir === bumpDirection.DOWN top = otherEl.bottom + margin; } // Recheck other savedPositions diff --git a/core/procedures.js b/core/procedures.js index f646ffe05..0332b8a95 100644 --- a/core/procedures.js +++ b/core/procedures.js @@ -146,7 +146,7 @@ const isNameUsed = function(name, workspace, opt_exclude) { const blocks = workspace.getAllBlocks(false); // Iterate through every block and check the name. for (let i = 0; i < blocks.length; i++) { - if (blocks[i] == opt_exclude) { + if (blocks[i] === opt_exclude) { continue; } if (blocks[i].getProcedureDef) { @@ -176,7 +176,7 @@ const rename = function(name) { name, /** @type {!Block} */ (this.getSourceBlock())); const oldName = this.getValue(); - if (oldName != name && oldName != legalName) { + if (oldName !== name && oldName !== legalName) { // Rename any callers. const blocks = this.getSourceBlock().workspace.getAllBlocks(false); for (let i = 0; i < blocks.length; i++) { @@ -307,14 +307,14 @@ const updateMutatorFlyout = function(workspace) { * @package */ const mutatorOpenListener = function(e) { - if (!(e.type == eventUtils.BUBBLE_OPEN && e.bubbleType === 'mutator' && + if (!(e.type === eventUtils.BUBBLE_OPEN && e.bubbleType === 'mutator' && e.isOpen)) { return; } const workspaceId = /** @type {string} */ (e.workspaceId); const block = Workspace.getById(workspaceId).getBlockById(e.blockId); const type = block.type; - if (type != 'procedures_defnoreturn' && type != 'procedures_defreturn') { + if (type !== 'procedures_defnoreturn' && type !== 'procedures_defreturn') { return; } const workspace = block.mutator.getWorkspace(); @@ -329,8 +329,8 @@ exports.mutatorOpenListener = mutatorOpenListener; * @param {!Abstract} e The event that triggered this listener. */ const mutatorChangeListener = function(e) { - if (e.type != eventUtils.BLOCK_CREATE && e.type != eventUtils.BLOCK_DELETE && - e.type != eventUtils.BLOCK_CHANGE) { + if (e.type !== eventUtils.BLOCK_CREATE && e.type !== eventUtils.BLOCK_DELETE && + e.type !== eventUtils.BLOCK_CHANGE) { return; } const workspaceId = /** @type {string} */ (e.workspaceId); @@ -382,7 +382,7 @@ const mutateCallers = function(defBlock) { caller.domToMutation(xmlElement); const newMutationDom = caller.mutationToDom(); const newMutation = newMutationDom && Xml.domToText(newMutationDom); - if (oldMutation != newMutation) { + if (oldMutation !== newMutation) { // Fire a mutation on every caller block. But don't record this as an // undo action since it is deterministically tied to the procedure's // definition mutation. diff --git a/core/registry.js b/core/registry.js index 5b2865575..79d257b24 100644 --- a/core/registry.js +++ b/core/registry.js @@ -155,15 +155,15 @@ Type.SERIALIZER = new Type('serializer'); * @alias Blockly.registry.register */ const register = function(type, name, registryItem, opt_allowOverrides) { - if ((!(type instanceof Type) && typeof type != 'string') || - String(type).trim() == '') { + if ((!(type instanceof Type) && typeof type !== 'string') || + String(type).trim() === '') { throw Error( 'Invalid type "' + type + '". The type must be a' + ' non-empty string or a Blockly.registry.Type.'); } type = String(type).toLowerCase(); - if ((typeof name != 'string') || (name.trim() == '')) { + if ((typeof name !== 'string') || (name.trim() === '')) { throw Error( 'Invalid name "' + name + '". The name must be a' + ' non-empty string.'); @@ -204,7 +204,7 @@ exports.register = register; const validate = function(type, registryItem) { switch (type) { case String(Type.FIELD): - if (typeof registryItem.fromJson != 'function') { + if (typeof registryItem.fromJson !== 'function') { throw Error('Type "' + type + '" must have a fromJson function'); } break; @@ -374,7 +374,7 @@ const getClassFromOptions = function(type, options, opt_throwIfMissing) { const plugin = options.plugins[typeName] || DEFAULT; // If the user passed in a plugin class instead of a registered plugin name. - if (typeof plugin == 'function') { + if (typeof plugin === 'function') { return plugin; } return getClass(type, plugin, opt_throwIfMissing); diff --git a/core/rendered_connection.js b/core/rendered_connection.js index ebe2a5709..4d601b6d4 100644 --- a/core/rendered_connection.js +++ b/core/rendered_connection.js @@ -111,7 +111,7 @@ RenderedConnection.TrackedState = { */ RenderedConnection.prototype.dispose = function() { RenderedConnection.superClass_.dispose.call(this); - if (this.trackedState_ == RenderedConnection.TrackedState.TRACKED) { + if (this.trackedState_ === RenderedConnection.TrackedState.TRACKED) { this.db_.removeConnection(this, this.y); } }; @@ -207,10 +207,10 @@ RenderedConnection.prototype.bumpAwayFrom = function(staticConnection) { * @param {number} y New absolute y coordinate, in workspace coordinates. */ RenderedConnection.prototype.moveTo = function(x, y) { - if (this.trackedState_ == RenderedConnection.TrackedState.WILL_TRACK) { + if (this.trackedState_ === RenderedConnection.TrackedState.WILL_TRACK) { this.db_.addConnection(this, y); this.trackedState_ = RenderedConnection.TrackedState.TRACKED; - } else if (this.trackedState_ == RenderedConnection.TrackedState.TRACKED) { + } else if (this.trackedState_ === RenderedConnection.TrackedState.TRACKED) { this.db_.removeConnection(this, this.y); this.db_.addConnection(this, y); } @@ -264,7 +264,7 @@ RenderedConnection.prototype.getOffsetInBlock = function() { RenderedConnection.prototype.tighten = function() { const dx = this.targetConnection.x - this.x; const dy = this.targetConnection.y - this.y; - if (dx != 0 || dy != 0) { + if (dx !== 0 || dy !== 0) { const block = this.targetBlock(); const svgRoot = block.getSvgRoot(); if (!svgRoot) { @@ -300,8 +300,8 @@ RenderedConnection.prototype.highlight = function() { const sourceBlockSvg = /** @type {!BlockSvg} */ (this.sourceBlock_); const renderConstants = sourceBlockSvg.workspace.getRenderer().getConstants(); const shape = renderConstants.shapeFor(this); - if (this.type == ConnectionType.INPUT_VALUE || - this.type == ConnectionType.OUTPUT_VALUE) { + if (this.type === ConnectionType.INPUT_VALUE || + this.type === ConnectionType.OUTPUT_VALUE) { // Vertical line, puzzle tab, vertical line. const yLen = renderConstants.TAB_OFFSET_FROM_TOP; steps = svgPaths.moveBy(0, -yLen) + svgPaths.lineOnAxis('v', yLen) + @@ -341,9 +341,9 @@ RenderedConnection.prototype.unhighlight = function() { */ RenderedConnection.prototype.setTracking = function(doTracking) { if ((doTracking && - this.trackedState_ == RenderedConnection.TrackedState.TRACKED) || + this.trackedState_ === RenderedConnection.TrackedState.TRACKED) || (!doTracking && - this.trackedState_ == RenderedConnection.TrackedState.UNTRACKED)) { + this.trackedState_ === RenderedConnection.TrackedState.UNTRACKED)) { return; } if (this.sourceBlock_.isInFlyout) { @@ -355,7 +355,7 @@ RenderedConnection.prototype.setTracking = function(doTracking) { this.trackedState_ = RenderedConnection.TrackedState.TRACKED; return; } - if (this.trackedState_ == RenderedConnection.TrackedState.TRACKED) { + if (this.trackedState_ === RenderedConnection.TrackedState.TRACKED) { this.db_.removeConnection(this, this.y); } this.trackedState_ = RenderedConnection.TrackedState.UNTRACKED; @@ -401,8 +401,8 @@ RenderedConnection.prototype.startTrackingAll = function() { // of lower blocks. Also, since rendering a block renders all its parents, // we only need to render the leaf nodes. const renderList = []; - if (this.type != ConnectionType.INPUT_VALUE && - this.type != ConnectionType.NEXT_STATEMENT) { + if (this.type !== ConnectionType.INPUT_VALUE && + this.type !== ConnectionType.NEXT_STATEMENT) { // Only spider down. return renderList; } @@ -553,8 +553,8 @@ RenderedConnection.prototype.connect_ = function(childConnection) { childBlock.updateDisabled(); } if (parentRendered && childRendered) { - if (parentConnection.type == ConnectionType.NEXT_STATEMENT || - parentConnection.type == ConnectionType.PREVIOUS_STATEMENT) { + if (parentConnection.type === ConnectionType.NEXT_STATEMENT || + parentConnection.type === ConnectionType.PREVIOUS_STATEMENT) { // Child block may need to square off its corners if it is in a stack. // Rendering a child will render its parent. childBlock.render(); diff --git a/core/renderers/common/constants.js b/core/renderers/common/constants.js index ad49475e9..4dea326d7 100644 --- a/core/renderers/common/constants.js +++ b/core/renderers/common/constants.js @@ -614,7 +614,7 @@ ConstantProvider.prototype.setDynamicProperties_ = function(theme) { this.setComponentConstants_(theme); this.ADD_START_HATS = - theme.startHats != null ? theme.startHats : this.ADD_START_HATS; + theme.startHats !== null ? theme.startHats : this.ADD_START_HATS; }; /** @@ -624,15 +624,15 @@ ConstantProvider.prototype.setDynamicProperties_ = function(theme) { */ ConstantProvider.prototype.setFontConstants_ = function(theme) { this.FIELD_TEXT_FONTFAMILY = - theme.fontStyle && theme.fontStyle['family'] != undefined ? + theme.fontStyle && theme.fontStyle['family'] !== undefined ? theme.fontStyle['family'] : this.FIELD_TEXT_FONTFAMILY; this.FIELD_TEXT_FONTWEIGHT = - theme.fontStyle && theme.fontStyle['weight'] != undefined ? + theme.fontStyle && theme.fontStyle['weight'] !== undefined ? theme.fontStyle['weight'] : this.FIELD_TEXT_FONTWEIGHT; this.FIELD_TEXT_FONTSIZE = - theme.fontStyle && theme.fontStyle['size'] != undefined ? + theme.fontStyle && theme.fontStyle['size'] !== undefined ? theme.fontStyle['size'] : this.FIELD_TEXT_FONTSIZE; @@ -686,7 +686,7 @@ ConstantProvider.prototype.getBlockStyleForColour = function(colour) { */ ConstantProvider.prototype.getBlockStyle = function(blockStyleName) { return this.blockStyles[blockStyleName || ''] || - (blockStyleName && blockStyleName.indexOf('auto_') == 0 ? + (blockStyleName && blockStyleName.indexOf('auto_') === 0 ? this.getBlockStyleForColour(blockStyleName.substring(5)).style : this.createBlockStyle_('#000000')); }; diff --git a/core/renderers/common/debugger.js b/core/renderers/common/debugger.js index 0458c5241..363e10db9 100644 --- a/core/renderers/common/debugger.js +++ b/core/renderers/common/debugger.js @@ -231,19 +231,19 @@ Debug.prototype.drawConnection = function(conn) { let colour; let size; let fill; - if (conn.type == ConnectionType.INPUT_VALUE) { + if (conn.type === ConnectionType.INPUT_VALUE) { size = 4; colour = 'magenta'; fill = 'none'; - } else if (conn.type == ConnectionType.OUTPUT_VALUE) { + } else if (conn.type === ConnectionType.OUTPUT_VALUE) { size = 2; colour = 'magenta'; fill = colour; - } else if (conn.type == ConnectionType.NEXT_STATEMENT) { + } else if (conn.type === ConnectionType.NEXT_STATEMENT) { size = 4; colour = 'goldenrod'; fill = 'none'; - } else if (conn.type == ConnectionType.PREVIOUS_STATEMENT) { + } else if (conn.type === ConnectionType.PREVIOUS_STATEMENT) { size = 2; colour = 'goldenrod'; fill = colour; diff --git a/core/renderers/common/drawer.js b/core/renderers/common/drawer.js index c9ecdb2fa..6bc226832 100644 --- a/core/renderers/common/drawer.js +++ b/core/renderers/common/drawer.js @@ -179,7 +179,7 @@ Drawer.prototype.drawValueInput_ = function(row) { const input = row.getLastInput(); this.positionExternalValueConnection_(row); - const pathDown = (typeof input.shape.pathDown == 'function') ? + const pathDown = (typeof input.shape.pathDown === 'function') ? input.shape.pathDown(input.height) : input.shape.pathDown; @@ -268,7 +268,7 @@ Drawer.prototype.drawLeft_ = function() { if (outputConnection) { const tabBottom = outputConnection.connectionOffsetY + outputConnection.height; - const pathUp = (typeof outputConnection.shape.pathUp == 'function') ? + const pathUp = (typeof outputConnection.shape.pathUp === 'function') ? outputConnection.shape.pathUp(outputConnection.height) : outputConnection.shape.pathUp; diff --git a/core/renderers/common/info.js b/core/renderers/common/info.js index 15ec49feb..e52741edb 100644 --- a/core/renderers/common/info.js +++ b/core/renderers/common/info.js @@ -292,7 +292,7 @@ RenderInfo.prototype.populateTopRow_ = function() { } const precedesStatement = this.block_.inputList.length && - this.block_.inputList[0].type == inputTypes.STATEMENT; + this.block_.inputList[0].type === inputTypes.STATEMENT; // This is the minimum height for the row. If one of its elements has a // greater height it will be overwritten in the compute pass. @@ -316,7 +316,7 @@ RenderInfo.prototype.populateBottomRow_ = function() { this.bottomRow.hasNextConnection = !!this.block_.nextConnection; const followsStatement = this.block_.inputList.length && - this.block_.inputList[this.block_.inputList.length - 1].type == + this.block_.inputList[this.block_.inputList.length - 1].type === inputTypes.STATEMENT; // This is the minimum height for the row. If one of its elements has a @@ -362,16 +362,16 @@ RenderInfo.prototype.populateBottomRow_ = function() { */ RenderInfo.prototype.addInput_ = function(input, activeRow) { // Non-dummy inputs have visual representations onscreen. - if (this.isInline && input.type == inputTypes.VALUE) { + if (this.isInline && input.type === inputTypes.VALUE) { activeRow.elements.push(new InlineInput(this.constants_, input)); activeRow.hasInlineInput = true; - } else if (input.type == inputTypes.STATEMENT) { + } else if (input.type === inputTypes.STATEMENT) { activeRow.elements.push(new StatementInput(this.constants_, input)); activeRow.hasStatement = true; - } else if (input.type == inputTypes.VALUE) { + } else if (input.type === inputTypes.VALUE) { activeRow.elements.push(new ExternalValueInput(this.constants_, input)); activeRow.hasExternalInput = true; - } else if (input.type == inputTypes.DUMMY) { + } else if (input.type === inputTypes.DUMMY) { // Dummy inputs have no visual representation, but the information is still // important. activeRow.minHeight = Math.max( @@ -381,7 +381,7 @@ RenderInfo.prototype.addInput_ = function(input, activeRow) { this.constants_.DUMMY_INPUT_MIN_HEIGHT); activeRow.hasDummyInput = true; } - if (activeRow.align == null) { + if (activeRow.align === null) { activeRow.align = input.align; } }; @@ -400,12 +400,12 @@ RenderInfo.prototype.shouldStartNewRow_ = function(input, lastInput) { return false; } // A statement input or an input following one always gets a new row. - if (input.type == inputTypes.STATEMENT || - lastInput.type == inputTypes.STATEMENT) { + if (input.type === inputTypes.STATEMENT || + lastInput.type === inputTypes.STATEMENT) { return true; } // Value and dummy inputs get new row if inputs are not inlined. - if (input.type == inputTypes.VALUE || input.type == inputTypes.DUMMY) { + if (input.type === inputTypes.VALUE || input.type === inputTypes.DUMMY) { return !this.isInline; } return false; @@ -579,14 +579,14 @@ RenderInfo.prototype.addAlignmentPadding_ = function(row, missingSpace) { } // Decide where the extra padding goes. - if (row.align == constants.ALIGN.LEFT) { + if (row.align === constants.ALIGN.LEFT) { // Add padding to the end of the row. lastSpacer.width += missingSpace; - } else if (row.align == constants.ALIGN.CENTRE) { + } else if (row.align === constants.ALIGN.CENTRE) { // Split the padding between the beginning and end of the row. firstSpacer.width += missingSpace / 2; lastSpacer.width += missingSpace / 2; - } else if (row.align == constants.ALIGN.RIGHT) { + } else if (row.align === constants.ALIGN.RIGHT) { // Add padding at the beginning of the row. firstSpacer.width += missingSpace; } else { @@ -632,7 +632,7 @@ RenderInfo.prototype.addRowSpacing_ = function() { for (let r = 0; r < oldRows.length; r++) { this.rows.push(oldRows[r]); - if (r != oldRows.length - 1) { + if (r !== oldRows.length - 1) { this.rows.push(this.makeSpacerRow_(oldRows[r], oldRows[r + 1])); } } diff --git a/core/renderers/common/marker_svg.js b/core/renderers/common/marker_svg.js index 6e62ac9f7..4d4fa6277 100644 --- a/core/renderers/common/marker_svg.js +++ b/core/renderers/common/marker_svg.js @@ -139,7 +139,7 @@ MarkerSvg.prototype.getMarker = function() { * @return {boolean} True if the marker is a cursor, false otherwise. */ MarkerSvg.prototype.isCursor = function() { - return this.marker_.type == 'cursor'; + return this.marker_.type === 'cursor'; }; /** @@ -217,21 +217,21 @@ MarkerSvg.prototype.showAtLocation_ = function(curNode) { const curNodeAsConnection = /** @type {!Connection} */ (curNode.getLocation()); const connectionType = curNodeAsConnection.type; - if (curNode.getType() == ASTNode.types.BLOCK) { + if (curNode.getType() === ASTNode.types.BLOCK) { this.showWithBlock_(curNode); - } else if (curNode.getType() == ASTNode.types.OUTPUT) { + } else if (curNode.getType() === ASTNode.types.OUTPUT) { this.showWithOutput_(curNode); - } else if (connectionType == ConnectionType.INPUT_VALUE) { + } else if (connectionType === ConnectionType.INPUT_VALUE) { this.showWithInput_(curNode); - } else if (connectionType == ConnectionType.NEXT_STATEMENT) { + } else if (connectionType === ConnectionType.NEXT_STATEMENT) { this.showWithNext_(curNode); - } else if (curNode.getType() == ASTNode.types.PREVIOUS) { + } else if (curNode.getType() === ASTNode.types.PREVIOUS) { this.showWithPrevious_(curNode); - } else if (curNode.getType() == ASTNode.types.FIELD) { + } else if (curNode.getType() === ASTNode.types.FIELD) { this.showWithField_(curNode); - } else if (curNode.getType() == ASTNode.types.WORKSPACE) { + } else if (curNode.getType() === ASTNode.types.WORKSPACE) { this.showWithCoordinates_(curNode); - } else if (curNode.getType() == ASTNode.types.STACK) { + } else if (curNode.getType() === ASTNode.types.STACK) { this.showWithStack_(curNode); } }; diff --git a/core/renderers/common/renderer.js b/core/renderers/common/renderer.js index 48e5f4d9b..d83301e0a 100644 --- a/core/renderers/common/renderer.js +++ b/core/renderers/common/renderer.js @@ -273,8 +273,8 @@ Renderer.prototype.orphanCanConnectAtEnd = function( */ Renderer.prototype.getConnectionPreviewMethod = function( closest, local, topBlock) { - if (local.type == ConnectionType.OUTPUT_VALUE || - local.type == ConnectionType.PREVIOUS_STATEMENT) { + if (local.type === ConnectionType.OUTPUT_VALUE || + local.type === ConnectionType.PREVIOUS_STATEMENT) { if (!closest.isConnected() || this.orphanCanConnectAtEnd( topBlock, diff --git a/core/renderers/geras/highlighter.js b/core/renderers/geras/highlighter.js index f218c1fbd..6816620b1 100644 --- a/core/renderers/geras/highlighter.js +++ b/core/renderers/geras/highlighter.js @@ -101,7 +101,7 @@ Highlighter.prototype.drawTopCorner = function(row) { this.steps_ += this.notchPaths_.pathLeft; } else if (Types.isHat(elem)) { this.steps_ += this.startPaths_.path(this.RTL_); - } else if (Types.isSpacer(elem) && elem.width != 0) { + } else if (Types.isSpacer(elem) && elem.width !== 0) { // The end point of the spacer needs to be offset by the highlight amount. // So instead of using the spacer's width for a relative horizontal, use // its width and position for an absolute horizontal move. diff --git a/core/renderers/geras/info.js b/core/renderers/geras/info.js index 012555d6f..96288bc93 100644 --- a/core/renderers/geras/info.js +++ b/core/renderers/geras/info.js @@ -71,7 +71,7 @@ RenderInfo.prototype.populateBottomRow_ = function() { RenderInfo.superClass_.populateBottomRow_.call(this); const followsStatement = this.block_.inputList.length && - this.block_.inputList[this.block_.inputList.length - 1].type == + this.block_.inputList[this.block_.inputList.length - 1].type === inputTypes.STATEMENT; // The minimum height of the bottom row is smaller in Geras than in other @@ -89,16 +89,16 @@ RenderInfo.prototype.populateBottomRow_ = function() { */ RenderInfo.prototype.addInput_ = function(input, activeRow) { // Non-dummy inputs have visual representations onscreen. - if (this.isInline && input.type == inputTypes.VALUE) { + if (this.isInline && input.type === inputTypes.VALUE) { activeRow.elements.push(new InlineInput(this.constants_, input)); activeRow.hasInlineInput = true; - } else if (input.type == inputTypes.STATEMENT) { + } else if (input.type === inputTypes.STATEMENT) { activeRow.elements.push(new StatementInput(this.constants_, input)); activeRow.hasStatement = true; - } else if (input.type == inputTypes.VALUE) { + } else if (input.type === inputTypes.VALUE) { activeRow.elements.push(new ExternalValueInput(this.constants_, input)); activeRow.hasExternalInput = true; - } else if (input.type == inputTypes.DUMMY) { + } else if (input.type === inputTypes.DUMMY) { // Dummy inputs have no visual representation, but the information is still // important. activeRow.minHeight = @@ -106,7 +106,7 @@ RenderInfo.prototype.addInput_ = function(input, activeRow) { activeRow.hasDummyInput = true; } // Ignore row alignment if inline. - if (!this.isInline && activeRow.align == null) { + if (!this.isInline && activeRow.align === null) { activeRow.align = input.align; } }; @@ -278,7 +278,7 @@ RenderInfo.prototype.getInRowSpacing_ = function(prev, next) { // Spacing between two fields of the same editability. if (Types.isField(prev) && next && Types.isField(next) && - ((/** @type {Field} */ (prev)).isEditable == + ((/** @type {Field} */ (prev)).isEditable === (/** @type {Field} */ (next)).isEditable)) { return this.constants_.LARGE_PADDING; } @@ -435,7 +435,7 @@ RenderInfo.prototype.finalize_ = function() { Math.max(widestRowWithConnectedBlocks, row.widthWithConnectedBlocks); // Add padding to the bottom row if block height is less than minimum const heightWithoutHat = yCursor - this.topRow.ascenderHeight; - if (row == this.bottomRow && + if (row === this.bottomRow && heightWithoutHat < this.constants_.MIN_BLOCK_HEIGHT) { // But the hat height shouldn't be part of this. const diff = this.constants_.MIN_BLOCK_HEIGHT - heightWithoutHat; diff --git a/core/renderers/measurables/input_row.js b/core/renderers/measurables/input_row.js index 7131c0285..ce87ec656 100644 --- a/core/renderers/measurables/input_row.js +++ b/core/renderers/measurables/input_row.js @@ -60,7 +60,7 @@ InputRow.prototype.measure = function() { if (Types.isInput(elem)) { if (Types.isStatementInput(elem)) { connectedBlockWidths += elem.connectedBlockWidth; - } else if (Types.isExternalInput(elem) && elem.connectedBlockWidth != 0) { + } else if (Types.isExternalInput(elem) && elem.connectedBlockWidth !== 0) { connectedBlockWidths += (elem.connectedBlockWidth - elem.connectionWidth); } diff --git a/core/renderers/measurables/round_corner.js b/core/renderers/measurables/round_corner.js index a01372b1a..ab6470b42 100644 --- a/core/renderers/measurables/round_corner.js +++ b/core/renderers/measurables/round_corner.js @@ -38,7 +38,7 @@ const object = goog.require('Blockly.utils.object'); const RoundCorner = function(constants, opt_position) { RoundCorner.superClass_.constructor.call(this, constants); this.type = - ((!opt_position || opt_position == 'left') ? Types.LEFT_ROUND_CORNER : + ((!opt_position || opt_position === 'left') ? Types.LEFT_ROUND_CORNER : Types.RIGHT_ROUND_CORNER) | Types.CORNER; this.width = this.constants_.CORNER_RADIUS; diff --git a/core/renderers/measurables/square_corner.js b/core/renderers/measurables/square_corner.js index f75ea830b..77d1ab456 100644 --- a/core/renderers/measurables/square_corner.js +++ b/core/renderers/measurables/square_corner.js @@ -38,7 +38,7 @@ const object = goog.require('Blockly.utils.object'); const SquareCorner = function(constants, opt_position) { SquareCorner.superClass_.constructor.call(this, constants); this.type = - ((!opt_position || opt_position == 'left') ? Types.LEFT_SQUARE_CORNER : + ((!opt_position || opt_position === 'left') ? Types.LEFT_SQUARE_CORNER : Types.RIGHT_SQUARE_CORNER) | Types.CORNER; this.height = this.constants_.NO_PADDING; diff --git a/core/renderers/measurables/top_row.js b/core/renderers/measurables/top_row.js index 62172aaf8..690ffcaee 100644 --- a/core/renderers/measurables/top_row.js +++ b/core/renderers/measurables/top_row.js @@ -87,7 +87,7 @@ TopRow.prototype.hasLeftSquareCorner = function(block) { const prevBlock = block.getPreviousBlock(); return !!block.outputConnection || hasHat || - (prevBlock ? prevBlock.getNextBlock() == block : false); + (prevBlock ? prevBlock.getNextBlock() === block : false); }; /** diff --git a/core/renderers/thrasos/info.js b/core/renderers/thrasos/info.js index fbcf130e2..ee875edf1 100644 --- a/core/renderers/thrasos/info.js +++ b/core/renderers/thrasos/info.js @@ -213,7 +213,7 @@ RenderInfo.prototype.getInRowSpacing_ = function(prev, next) { // Spacing between two fields of the same editability. if (Types.isField(prev) && next && Types.isField(next) && - ((/** @type {Field} */ (prev)).isEditable == + ((/** @type {Field} */ (prev)).isEditable === (/** @type {Field} */ (next)).isEditable)) { return this.constants_.LARGE_PADDING; } @@ -303,7 +303,7 @@ RenderInfo.prototype.finalize_ = function() { Math.max(widestRowWithConnectedBlocks, row.widthWithConnectedBlocks); // Add padding to the bottom row if block height is less than minimum const heightWithoutHat = yCursor - this.topRow.ascenderHeight; - if (row == this.bottomRow && + if (row === this.bottomRow && heightWithoutHat < this.constants_.MIN_BLOCK_HEIGHT) { // But the hat height shouldn't be part of this. const diff = this.constants_.MIN_BLOCK_HEIGHT - heightWithoutHat; diff --git a/core/renderers/zelos/constants.js b/core/renderers/zelos/constants.js index 8b8fe75b8..7ccee2128 100644 --- a/core/renderers/zelos/constants.js +++ b/core/renderers/zelos/constants.js @@ -650,7 +650,7 @@ ConstantProvider.prototype.shapeFor = function(connection) { case ConnectionType.OUTPUT_VALUE: outputShape = connection.getSourceBlock().getOutputShape(); // If the block has an output shape set, use that instead. - if (outputShape != null) { + if (outputShape !== null) { switch (outputShape) { case this.SHAPES.HEXAGONAL: return this.HEXAGONAL; @@ -661,13 +661,13 @@ ConstantProvider.prototype.shapeFor = function(connection) { } } // Includes doesn't work in IE. - if (checks && checks.indexOf('Boolean') != -1) { + if (checks && checks.indexOf('Boolean') !== -1) { return this.HEXAGONAL; } - if (checks && checks.indexOf('Number') != -1) { + if (checks && checks.indexOf('Number') !== -1) { return this.ROUNDED; } - if (checks && checks.indexOf('String') != -1) { + if (checks && checks.indexOf('String') !== -1) { return this.ROUNDED; } return this.ROUNDED; diff --git a/core/renderers/zelos/info.js b/core/renderers/zelos/info.js index 397100aa7..c3f7049f2 100644 --- a/core/renderers/zelos/info.js +++ b/core/renderers/zelos/info.js @@ -131,12 +131,12 @@ RenderInfo.prototype.shouldStartNewRow_ = function(input, lastInput) { return false; } // A statement input or an input following one always gets a new row. - if (input.type == inputTypes.STATEMENT || - lastInput.type == inputTypes.STATEMENT) { + if (input.type === inputTypes.STATEMENT || + lastInput.type === inputTypes.STATEMENT) { return true; } // Value and dummy inputs get new row if inputs are not inlined. - if (input.type == inputTypes.VALUE || input.type == inputTypes.DUMMY) { + if (input.type === inputTypes.VALUE || input.type === inputTypes.DUMMY) { return !this.isInline || this.isMultiRow; } return false; @@ -266,17 +266,17 @@ RenderInfo.prototype.addInput_ = function(input, activeRow) { // If we have two dummy inputs on the same row, one aligned left and the other // right, keep track of the right aligned dummy input so we can add padding // later. - if (input.type == inputTypes.DUMMY && activeRow.hasDummyInput && - activeRow.align == constants.ALIGN.LEFT && - input.align == constants.ALIGN.RIGHT) { + if (input.type === inputTypes.DUMMY && activeRow.hasDummyInput && + activeRow.align === constants.ALIGN.LEFT && + input.align === constants.ALIGN.RIGHT) { activeRow.rightAlignedDummyInput = input; - } else if (input.type == inputTypes.STATEMENT) { + } else if (input.type === inputTypes.STATEMENT) { // Handle statements without next connections correctly. activeRow.elements.push( new StatementInput(this.constants_, input)); activeRow.hasStatement = true; - if (activeRow.align == null) { + if (activeRow.align === null) { activeRow.align = input.align; } return; @@ -296,7 +296,7 @@ RenderInfo.prototype.addAlignmentPadding_ = function(row, missingSpace) { alignmentDivider = elem; } if (Types.isField(elem) && - elem.parentInput == row.rightAlignedDummyInput) { + elem.parentInput === row.rightAlignedDummyInput) { break; } } @@ -327,7 +327,7 @@ RenderInfo.prototype.adjustXPosition_ = function() { const row = this.rows[i]; const nextSpacer = this.rows[i + 1]; - const hasPrevNotch = i == 2 ? !!this.topRow.hasPreviousConnection : + const hasPrevNotch = i === 2 ? !!this.topRow.hasPreviousConnection : !!prevSpacer.followsStatement; const hasNextNotch = i + 2 >= this.rows.length - 1 ? !!this.bottomRow.hasNextConnection : @@ -337,7 +337,7 @@ RenderInfo.prototype.adjustXPosition_ = function() { row.measure(); minXPos = row.width - row.getLastInput().width + notchTotalWidth; } else if ( - hasPrevNotch && (i == 2 || hasNextNotch) && Types.isInputRow(row) && + hasPrevNotch && (i === 2 || hasNextNotch) && Types.isInputRow(row) && !row.hasStatement) { let xCursor = row.xPos; let prevInRowSpacer = null; @@ -506,14 +506,14 @@ RenderInfo.prototype.getNegativeSpacing_ = function(elem) { return 0; } // Special case for hexagonal output. - if (outerShape == constants.SHAPES.HEXAGONAL && outerShape != innerShape) { + if (outerShape === constants.SHAPES.HEXAGONAL && outerShape !== innerShape) { return 0; } return connectionWidth - this.constants_.SHAPE_IN_SHAPE_PADDING[outerShape][innerShape]; } else if (Types.isField(elem)) { // Special case for text inputs. - if (outerShape == constants.SHAPES.ROUND && + if (outerShape === constants.SHAPES.ROUND && elem.field instanceof FieldTextInput) { return connectionWidth - (2.75 * constants.GRID_UNIT); } @@ -542,7 +542,7 @@ RenderInfo.prototype.finalizeVerticalAlignment_ = function() { const row = this.rows[i]; const nextSpacer = this.rows[i + 1]; - const firstRow = i == 2; + const firstRow = i === 2; const hasPrevNotch = firstRow ? !!this.topRow.hasPreviousConnection : !!prevSpacer.followsStatement; const hasNextNotch = i + 2 >= this.rows.length - 1 ? @@ -550,7 +550,7 @@ RenderInfo.prototype.finalizeVerticalAlignment_ = function() { !!nextSpacer.precedesStatement; if (hasPrevNotch) { - const hasSingleTextOrImageField = row.elements.length == 3 && + const hasSingleTextOrImageField = row.elements.length === 3 && (row.elements[1].field instanceof FieldLabel || row.elements[1].field instanceof FieldImage); if (!firstRow && hasSingleTextOrImageField) { diff --git a/core/renderers/zelos/renderer.js b/core/renderers/zelos/renderer.js index a51461ce8..af35101fa 100644 --- a/core/renderers/zelos/renderer.js +++ b/core/renderers/zelos/renderer.js @@ -119,7 +119,7 @@ Renderer.prototype.makePathObject = function(root, style) { * @override */ Renderer.prototype.shouldHighlightConnection = function(conn) { - return conn.type != ConnectionType.INPUT_VALUE && + return conn.type !== ConnectionType.INPUT_VALUE && conn.type !== ConnectionType.OUTPUT_VALUE; }; @@ -128,7 +128,7 @@ Renderer.prototype.shouldHighlightConnection = function(conn) { */ Renderer.prototype.getConnectionPreviewMethod = function( closest, local, topBlock) { - if (local.type == ConnectionType.OUTPUT_VALUE) { + if (local.type === ConnectionType.OUTPUT_VALUE) { if (!closest.isConnected()) { return InsertionMarkerManager.PREVIEW_TYPE.INPUT_OUTLINE; } diff --git a/core/scrollbar.js b/core/scrollbar.js index 85ce1cec2..96d2cf725 100644 --- a/core/scrollbar.js +++ b/core/scrollbar.js @@ -212,15 +212,15 @@ Scrollbar.DEFAULT_SCROLLBAR_MARGIN = 0.5; */ Scrollbar.metricsAreEquivalent_ = function(first, second) { return ( - first.viewWidth == second.viewWidth && - first.viewHeight == second.viewHeight && - first.viewLeft == second.viewLeft && first.viewTop == second.viewTop && - first.absoluteTop == second.absoluteTop && - first.absoluteLeft == second.absoluteLeft && - first.scrollWidth == second.scrollWidth && - first.scrollHeight == second.scrollHeight && - first.scrollLeft == second.scrollLeft && - first.scrollTop == second.scrollTop); + first.viewWidth === second.viewWidth && + first.viewHeight === second.viewHeight && + first.viewLeft === second.viewLeft && first.viewTop === second.viewTop && + first.absoluteTop === second.absoluteTop && + first.absoluteLeft === second.absoluteLeft && + first.scrollWidth === second.scrollWidth && + first.scrollHeight === second.scrollHeight && + first.scrollLeft === second.scrollLeft && + first.scrollTop === second.scrollTop); }; /** @@ -460,9 +460,9 @@ Scrollbar.prototype.resizeContentHorizontal = function(hostMetrics) { // Compute the handle offset. // The position of the handle can be between: // 0 and this.scrollbarLength_ - handleLength - // If viewLeft == scrollLeft + // If viewLeft === scrollLeft // then the offset should be 0 - // If viewRight == scrollRight + // If viewRight === scrollRight // then viewLeft = scrollLeft + scrollWidth - viewWidth // then the offset should be max offset @@ -554,9 +554,9 @@ Scrollbar.prototype.resizeContentVertical = function(hostMetrics) { // Compute the handle offset. // The position of the handle can be between: // 0 and this.scrollbarLength_ - handleLength - // If viewTop == scrollTop + // If viewTop === scrollTop // then the offset should be 0 - // If viewBottom == scrollBottom + // If viewBottom === scrollBottom // then viewTop = scrollTop + scrollHeight - viewHeight // then the offset should be max offset @@ -624,7 +624,7 @@ Scrollbar.prototype.isVisible = function() { * @param {boolean} visible Whether the container is visible */ Scrollbar.prototype.setContainerVisible = function(visible) { - const visibilityChanged = (visible != this.containerVisible_); + const visibilityChanged = (visible !== this.containerVisible_); this.containerVisible_ = visible; if (visibilityChanged) { @@ -638,7 +638,7 @@ Scrollbar.prototype.setContainerVisible = function(visible) { * @param {boolean} visible True if visible. */ Scrollbar.prototype.setVisible = function(visible) { - const visibilityChanged = (visible != this.isVisible()); + const visibilityChanged = (visible !== this.isVisible()); // Ideally this would also apply to scrollbar pairs, but that's a bigger // headache (due to interactions with the corner square). diff --git a/core/scrollbar_pair.js b/core/scrollbar_pair.js index 2b5bb5c86..24d4048f4 100644 --- a/core/scrollbar_pair.js +++ b/core/scrollbar_pair.js @@ -115,25 +115,25 @@ ScrollbarPair.prototype.resize = function() { let resizeH = false; let resizeV = false; if (!this.oldHostMetrics_ || - this.oldHostMetrics_.viewWidth != hostMetrics.viewWidth || - this.oldHostMetrics_.viewHeight != hostMetrics.viewHeight || - this.oldHostMetrics_.absoluteTop != hostMetrics.absoluteTop || - this.oldHostMetrics_.absoluteLeft != hostMetrics.absoluteLeft) { + this.oldHostMetrics_.viewWidth !== hostMetrics.viewWidth || + this.oldHostMetrics_.viewHeight !== hostMetrics.viewHeight || + this.oldHostMetrics_.absoluteTop !== hostMetrics.absoluteTop || + this.oldHostMetrics_.absoluteLeft !== hostMetrics.absoluteLeft) { // The window has been resized or repositioned. resizeH = true; resizeV = true; } else { // Has the content been resized or moved? if (!this.oldHostMetrics_ || - this.oldHostMetrics_.scrollWidth != hostMetrics.scrollWidth || - this.oldHostMetrics_.viewLeft != hostMetrics.viewLeft || - this.oldHostMetrics_.scrollLeft != hostMetrics.scrollLeft) { + this.oldHostMetrics_.scrollWidth !== hostMetrics.scrollWidth || + this.oldHostMetrics_.viewLeft !== hostMetrics.viewLeft || + this.oldHostMetrics_.scrollLeft !== hostMetrics.scrollLeft) { resizeH = true; } if (!this.oldHostMetrics_ || - this.oldHostMetrics_.scrollHeight != hostMetrics.scrollHeight || - this.oldHostMetrics_.viewTop != hostMetrics.viewTop || - this.oldHostMetrics_.scrollTop != hostMetrics.scrollTop) { + this.oldHostMetrics_.scrollHeight !== hostMetrics.scrollHeight || + this.oldHostMetrics_.viewTop !== hostMetrics.viewTop || + this.oldHostMetrics_.scrollTop !== hostMetrics.scrollTop) { resizeV = true; } } @@ -156,13 +156,13 @@ ScrollbarPair.prototype.resize = function() { if (this.hScroll && this.vScroll) { // Reposition the corner square. if (!this.oldHostMetrics_ || - this.oldHostMetrics_.viewWidth != hostMetrics.viewWidth || - this.oldHostMetrics_.absoluteLeft != hostMetrics.absoluteLeft) { + this.oldHostMetrics_.viewWidth !== hostMetrics.viewWidth || + this.oldHostMetrics_.absoluteLeft !== hostMetrics.absoluteLeft) { this.corner_.setAttribute('x', this.vScroll.position.x); } if (!this.oldHostMetrics_ || - this.oldHostMetrics_.viewHeight != hostMetrics.viewHeight || - this.oldHostMetrics_.absoluteTop != hostMetrics.absoluteTop) { + this.oldHostMetrics_.viewHeight !== hostMetrics.viewHeight || + this.oldHostMetrics_.absoluteTop !== hostMetrics.absoluteTop) { this.corner_.setAttribute('y', this.hScroll.position.y); } } diff --git a/core/serialization/blocks.js b/core/serialization/blocks.js index d0a6bc020..43ebee692 100644 --- a/core/serialization/blocks.js +++ b/core/serialization/blocks.js @@ -480,7 +480,7 @@ const tryToConnectParent = function(parentConnection, child, state) { let connected = false; let childConnection; - if (parentConnection.type == inputTypes.VALUE) { + if (parentConnection.type === inputTypes.VALUE) { childConnection = child.outputConnection; if (!childConnection) { throw new MissingConnection('output', child, state); @@ -502,7 +502,7 @@ const tryToConnectParent = function(parentConnection, child, state) { childConnection, parentConnection, false), childConnection, parentConnection), - parentConnection.type == inputTypes.VALUE ? + parentConnection.type === inputTypes.VALUE ? 'output connection' : 'previous connection', child, state); diff --git a/core/shortcut_registry.js b/core/shortcut_registry.js index bafe184f4..b3e500757 100644 --- a/core/shortcut_registry.js +++ b/core/shortcut_registry.js @@ -166,7 +166,7 @@ ShortcutRegistry.prototype.removeKeyMapping = function( const shortcutIdx = shortcutNames.indexOf(shortcutName); if (shortcutIdx > -1) { shortcutNames.splice(shortcutIdx, 1); - if (shortcutNames.length == 0) { + if (shortcutNames.length === 0) { delete this.keyMap_[keyCode]; } return true; @@ -290,13 +290,13 @@ ShortcutRegistry.prototype.serializeKeyEvent_ = function(e) { let serializedKey = ''; for (const modifier in ShortcutRegistry.modifierKeys) { if (e.getModifierState(modifier)) { - if (serializedKey != '') { + if (serializedKey !== '') { serializedKey += '+'; } serializedKey += modifier; } } - if (serializedKey != '' && e.keyCode) { + if (serializedKey !== '' && e.keyCode) { serializedKey = serializedKey + '+' + e.keyCode; } else if (e.keyCode) { serializedKey = e.keyCode.toString(); @@ -336,7 +336,7 @@ ShortcutRegistry.prototype.createSerializedKey = function(keyCode, modifiers) { for (const modifier in ShortcutRegistry.modifierKeys) { const modifierKeyCode = ShortcutRegistry.modifierKeys[modifier]; if (modifiers.indexOf(modifierKeyCode) > -1) { - if (serializedKey != '') { + if (serializedKey !== '') { serializedKey += '+'; } serializedKey += modifier; @@ -344,7 +344,7 @@ ShortcutRegistry.prototype.createSerializedKey = function(keyCode, modifiers) { } } - if (serializedKey != '' && keyCode) { + if (serializedKey !== '' && keyCode) { serializedKey = serializedKey + '+' + keyCode; } else if (keyCode) { serializedKey = keyCode.toString(); diff --git a/core/theme.js b/core/theme.js index a60099be8..ec5f036d4 100644 --- a/core/theme.js +++ b/core/theme.js @@ -168,7 +168,7 @@ Theme.prototype.setCategoryStyle = function(categoryStyleName, categoryStyle) { */ Theme.prototype.getComponentStyle = function(componentName) { const style = this.componentStyles[componentName]; - if (style && typeof style == 'string' && + if (style && typeof style === 'string' && this.getComponentStyle(/** @type {string} */ (style))) { return this.getComponentStyle(/** @type {string} */ (style)); } @@ -211,7 +211,7 @@ Theme.defineTheme = function(name, themeObj) { const theme = new Theme(name); let base = themeObj['base']; if (base) { - if (typeof base == 'string') { + if (typeof base === 'string') { base = registry.getObject(registry.Type.THEME, base); } if (base instanceof Theme) { @@ -224,7 +224,7 @@ Theme.defineTheme = function(name, themeObj) { object.deepMerge(theme.categoryStyles, themeObj['categoryStyles']); object.deepMerge(theme.componentStyles, themeObj['componentStyles']); object.deepMerge(theme.fontStyle, themeObj['fontStyle']); - if (themeObj['startHats'] != null) { + if (themeObj['startHats'] !== null) { theme.startHats = themeObj['startHats']; } diff --git a/core/toolbox/category.js b/core/toolbox/category.js index 15ffbe780..c3c1f3f54 100644 --- a/core/toolbox/category.js +++ b/core/toolbox/category.js @@ -221,7 +221,7 @@ ToolboxCategory.prototype.parseContents_ = function(categoryDef) { */ ToolboxCategory.prototype.init = function() { this.createDom_(); - if (this.toolboxItemDef_['hidden'] == 'true') { + if (this.toolboxItemDef_['hidden'] === 'true') { this.hide(); } }; @@ -425,7 +425,7 @@ ToolboxCategory.prototype.parseColour_ = function(colourValue) { // Decode the colour for any potential message references // (eg. `%{BKY_MATH_HUE}`). const colour = utils.replaceMessageReferences(colourValue); - if (colour == null || colour === '') { + if (colour === null || colour === '') { // No attribute. No colour. return ''; } else { @@ -482,7 +482,7 @@ ToolboxCategory.prototype.setVisible_ = function(isVisible) { this.htmlDiv_.style.display = isVisible ? 'block' : 'none'; this.isHidden_ = !isVisible; - if (this.parentToolbox_.getSelectedItem() == this) { + if (this.parentToolbox_.getSelectedItem() === this) { this.parentToolbox_.clearSelection(); } }; @@ -623,7 +623,7 @@ ToolboxCategory.prototype.getContents = function() { ToolboxCategory.prototype.updateFlyoutContents = function(contents) { this.flyoutItems_ = []; - if (typeof contents == 'string') { + if (typeof contents === 'string') { this.toolboxItemDef_['custom'] = contents; } else { // Removes old custom field when contents is updated. diff --git a/core/toolbox/collapsible_category.js b/core/toolbox/collapsible_category.js index 91c679d78..0b63a1829 100644 --- a/core/toolbox/collapsible_category.js +++ b/core/toolbox/collapsible_category.js @@ -119,7 +119,7 @@ CollapsibleToolboxCategory.prototype.parseContents_ = function(categoryDef) { // Separators can exist as either a flyout item or a toolbox item so // decide where it goes based on the type of the previous item. if (!registry.hasItem(registry.Type.TOOLBOX_ITEM, itemDef['kind']) || - (itemDef['kind'].toLowerCase() == ToolboxSeparator.registrationName && + (itemDef['kind'].toLowerCase() === ToolboxSeparator.registrationName && prevIsFlyoutItem)) { const flyoutItem = /** @type {toolbox.FlyoutItemInfo} */ (itemDef); this.flyoutItems_.push(flyoutItem); @@ -144,7 +144,7 @@ CollapsibleToolboxCategory.prototype.createToolboxItem_ = function(itemDef) { // Categories that are collapsible are created using a class registered under // a diffferent name. - if (registryName.toUpperCase() == 'CATEGORY' && + if (registryName.toUpperCase() === 'CATEGORY' && toolbox.isCategoryCollapsible(categoryDef)) { registryName = CollapsibleToolboxCategory.registrationName; } @@ -161,7 +161,7 @@ CollapsibleToolboxCategory.prototype.init = function() { CollapsibleToolboxCategory.superClass_.init.call(this); this.setExpanded( - this.toolboxItemDef_['expanded'] == 'true' || + this.toolboxItemDef_['expanded'] === 'true' || this.toolboxItemDef_['expanded']); }; @@ -223,7 +223,7 @@ CollapsibleToolboxCategory.prototype.createSubCategoriesDom_ = function( * @public */ CollapsibleToolboxCategory.prototype.setExpanded = function(isExpanded) { - if (this.expanded_ == isExpanded) { + if (this.expanded_ === isExpanded) { return; } this.expanded_ = isExpanded; @@ -252,7 +252,7 @@ CollapsibleToolboxCategory.prototype.setVisible_ = function(isVisible) { } this.isHidden_ = !isVisible; - if (this.parentToolbox_.getSelectedItem() == this) { + if (this.parentToolbox_.getSelectedItem() === this) { this.parentToolbox_.clearSelection(); } }; diff --git a/core/toolbox/toolbox.js b/core/toolbox/toolbox.js index 8aa4ac35d..4f959a751 100644 --- a/core/toolbox/toolbox.js +++ b/core/toolbox/toolbox.js @@ -316,7 +316,7 @@ Toolbox.prototype.attachEvents_ = function(container, contentsContainer) { * @protected */ Toolbox.prototype.onClick_ = function(e) { - if (browserEvents.isRightButton(e) || e.target == this.HtmlDiv) { + if (browserEvents.isRightButton(e) || e.target === this.HtmlDiv) { // Close flyout. common.getMainWorkspace().hideChaff(false); } else { @@ -465,7 +465,7 @@ Toolbox.prototype.createToolboxItem_ = function(toolboxItemDef, fragment) { // Categories that are collapsible are created using a class registered under // a different name. - if (registryName.toUpperCase() == 'CATEGORY' && + if (registryName.toUpperCase() === 'CATEGORY' && toolbox.isCategoryCollapsible( /** @type {!toolbox.CategoryInfo} */ (toolboxItemDef))) { registryName = CollapsibleToolboxCategory.registrationName; @@ -559,11 +559,11 @@ Toolbox.prototype.getClientRect = function() { // Assumes that the toolbox is on the SVG edge. If this changes // (e.g. toolboxes in mutators) then this code will need to be more complex. - if (this.toolboxPosition == toolbox.Position.TOP) { + if (this.toolboxPosition === toolbox.Position.TOP) { return new Rect(-BIG_NUM, bottom, -BIG_NUM, BIG_NUM); - } else if (this.toolboxPosition == toolbox.Position.BOTTOM) { + } else if (this.toolboxPosition === toolbox.Position.BOTTOM) { return new Rect(top, BIG_NUM, -BIG_NUM, BIG_NUM); - } else if (this.toolboxPosition == toolbox.Position.LEFT) { + } else if (this.toolboxPosition === toolbox.Position.LEFT) { return new Rect(-BIG_NUM, BIG_NUM, -BIG_NUM, right); } else { // Right return new Rect(-BIG_NUM, BIG_NUM, left, BIG_NUM); @@ -759,13 +759,13 @@ Toolbox.prototype.position = function() { toolboxDiv.style.width = '100%'; this.height_ = toolboxDiv.offsetHeight; this.width_ = workspaceMetrics.viewWidth; - if (this.toolboxPosition == toolbox.Position.TOP) { + if (this.toolboxPosition === toolbox.Position.TOP) { toolboxDiv.style.top = '0'; } else { // Bottom toolboxDiv.style.bottom = '0'; } } else { - if (this.toolboxPosition == toolbox.Position.RIGHT) { + if (this.toolboxPosition === toolbox.Position.RIGHT) { toolboxDiv.style.right = '0'; } else { // Left toolboxDiv.style.left = '0'; @@ -785,10 +785,10 @@ Toolbox.prototype.handleToolboxItemResize = function() { // to the new absolute edge (ie toolbox edge). const workspace = this.workspace_; const rect = this.HtmlDiv.getBoundingClientRect(); - const newX = this.toolboxPosition == toolbox.Position.LEFT ? + const newX = this.toolboxPosition === toolbox.Position.LEFT ? workspace.scrollX + rect.width : workspace.scrollX; - const newY = this.toolboxPosition == toolbox.Position.TOP ? + const newY = this.toolboxPosition === toolbox.Position.TOP ? workspace.scrollY + rect.height : workspace.scrollY; workspace.translate(newX, newY); @@ -874,11 +874,11 @@ Toolbox.prototype.setSelectedItem = function(newItem) { } newItem = /** @type {ISelectableToolboxItem} */ (newItem); - if (this.shouldDeselectItem_(oldItem, newItem) && oldItem != null) { + if (this.shouldDeselectItem_(oldItem, newItem) && oldItem !== null) { this.deselectItem_(oldItem); } - if (this.shouldSelectItem_(oldItem, newItem) && newItem != null) { + if (this.shouldSelectItem_(oldItem, newItem) && newItem !== null) { this.selectItem_(oldItem, newItem); } @@ -898,7 +898,7 @@ Toolbox.prototype.setSelectedItem = function(newItem) { Toolbox.prototype.shouldDeselectItem_ = function(oldItem, newItem) { // Deselect the old item unless the old item is collapsible and has been // previously clicked on. - return oldItem != null && (!oldItem.isCollapsible() || oldItem != newItem); + return oldItem !== null && (!oldItem.isCollapsible() || oldItem !== newItem); }; /** @@ -912,7 +912,7 @@ Toolbox.prototype.shouldDeselectItem_ = function(oldItem, newItem) { */ Toolbox.prototype.shouldSelectItem_ = function(oldItem, newItem) { // Select the new item unless the old item equals the new item. - return newItem != null && newItem != oldItem; + return newItem !== null && newItem !== oldItem; }; /** @@ -969,7 +969,7 @@ Toolbox.prototype.selectItemByPosition = function(position) { * @protected */ Toolbox.prototype.updateFlyout_ = function(oldItem, newItem) { - if ((oldItem == newItem && !newItem.isCollapsible()) || !newItem || + if ((oldItem === newItem && !newItem.isCollapsible()) || !newItem || !newItem.getContents().length) { this.flyout_.hide(); } else { @@ -990,7 +990,7 @@ Toolbox.prototype.fireSelectEvent_ = function(oldItem, newItem) { const oldElement = oldItem && oldItem.getName(); let newElement = newItem && newItem.getName(); // In this case the toolbox closes, so the newElement should be null. - if (oldItem == newItem) { + if (oldItem === newItem) { newElement = null; } const event = new (eventUtils.get(eventUtils.TOOLBOX_ITEM_SELECT))( diff --git a/core/tooltip.js b/core/tooltip.js index 8d8d86e04..46ae14a1b 100644 --- a/core/tooltip.js +++ b/core/tooltip.js @@ -204,10 +204,10 @@ const getTooltipOfObject = function(object) { const obj = getTargetObject(object); if (obj) { let tooltip = obj.tooltip; - while (typeof tooltip == 'function') { + while (typeof tooltip === 'function') { tooltip = tooltip(); } - if (typeof tooltip != 'string') { + if (typeof tooltip !== 'string') { throw Error('Tooltip function must return a string.'); } return tooltip; @@ -225,8 +225,8 @@ exports.getTooltipOfObject = getTooltipOfObject; */ const getTargetObject = function(obj) { while (obj && obj.tooltip) { - if ((typeof obj.tooltip == 'string') || - (typeof obj.tooltip == 'function')) { + if ((typeof obj.tooltip === 'string') || + (typeof obj.tooltip === 'function')) { return obj; } obj = obj.tooltip; @@ -296,7 +296,7 @@ const 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. const newElement = /** @type {Element} */ (getTargetObject(e.currentTarget)); - if (element != newElement) { + if (element !== newElement) { hide(); poisonedElement = null; element = newElement; @@ -348,7 +348,7 @@ const onMouseMove = function(e) { if (Math.sqrt(dx * dx + dy * dy) > RADIUS_OK) { hide(); } - } else if (poisonedElement != element) { + } else if (poisonedElement !== element) { // The mouse moved, clear any previously scheduled tooltip. clearTimeout(showPid); // Maybe this time the mouse will stay put. Schedule showing of tooltip. diff --git a/core/touch.js b/core/touch.js index 872848711..9568928d6 100644 --- a/core/touch.js +++ b/core/touch.js @@ -91,7 +91,7 @@ let longPid_ = 0; const longStart = function(e, gesture) { longStop(); // Punt on multitouch events. - if (e.changedTouches && e.changedTouches.length != 1) { + if (e.changedTouches && e.changedTouches.length !== 1) { return; } longPid_ = setTimeout(function() { @@ -160,7 +160,7 @@ exports.shouldHandleEvent = shouldHandleEvent; * @alias Blockly.Touch.getTouchIdentifierFromEvent */ const getTouchIdentifierFromEvent = function(e) { - return e.pointerId != undefined ? + return e.pointerId !== undefined ? e.pointerId : (e.changedTouches && e.changedTouches[0] && e.changedTouches[0].identifier !== undefined && @@ -191,10 +191,10 @@ const checkTouchIdentifier = function(e) { if (touchIdentifier_ !== undefined && touchIdentifier_ !== null) { // We're already tracking some touch/mouse event. Is this from the same // source? - return touchIdentifier_ == identifier; + return touchIdentifier_ === identifier; } - if (e.type == 'mousedown' || e.type == 'touchstart' || - e.type == 'pointerdown') { + if (e.type === 'mousedown' || e.type === 'touchstart' || + e.type === 'pointerdown') { // No identifier set yet, and this is the start of a drag. Set it and // return. touchIdentifier_ = identifier; diff --git a/core/touch_gesture.js b/core/touch_gesture.js index f81a92497..5e1c765fa 100644 --- a/core/touch_gesture.js +++ b/core/touch_gesture.js @@ -241,7 +241,7 @@ TouchGesture.prototype.handleTouchStart = function(e) { this.cachedPoints_[pointerId] = this.getTouchPoint(e); const pointers = Object.keys(this.cachedPoints_); // If two pointers are down, store info - if (pointers.length == 2) { + if (pointers.length === 2) { const point0 = /** @type {!Coordinate} */ (this.cachedPoints_[pointers[0]]); const point1 = /** @type {!Coordinate} */ (this.cachedPoints_[pointers[1]]); this.startDistance_ = Coordinate.distance(point0, point1); diff --git a/core/trashcan.js b/core/trashcan.js index 608a1832e..8dc02cdc9 100644 --- a/core/trashcan.js +++ b/core/trashcan.js @@ -111,7 +111,7 @@ const Trashcan = function(workspace) { // Create vertical or horizontal flyout. if (this.workspace_.horizontalLayout) { flyoutWorkspaceOptions.toolboxPosition = - this.workspace_.toolboxPosition == toolbox.Position.TOP ? + this.workspace_.toolboxPosition === toolbox.Position.TOP ? toolbox.Position.BOTTOM : toolbox.Position.TOP; const HorizontalFlyout = registry.getClassFromOptions( @@ -120,7 +120,7 @@ const Trashcan = function(workspace) { this.flyout = new HorizontalFlyout(flyoutWorkspaceOptions); } else { flyoutWorkspaceOptions.toolboxPosition = - this.workspace_.toolboxPosition == toolbox.Position.RIGHT ? + this.workspace_.toolboxPosition === toolbox.Position.RIGHT ? toolbox.Position.LEFT : toolbox.Position.RIGHT; const VerticalFlyout = registry.getClassFromOptions( @@ -547,7 +547,7 @@ Trashcan.prototype.onDrop = function(_dragElement) { * @package */ Trashcan.prototype.setLidOpen = function(state) { - if (this.isLidOpen == state) { + if (this.isLidOpen === state) { return; } clearTimeout(this.lidTask_); @@ -585,7 +585,7 @@ Trashcan.prototype.animateLid_ = function() { */ Trashcan.prototype.setLidAngle_ = function(lidAngle) { const openAtRight = - this.workspace_.toolboxPosition == toolbox.Position.RIGHT || + this.workspace_.toolboxPosition === toolbox.Position.RIGHT || (this.workspace_.horizontalLayout && this.workspace_.RTL); this.svgLid_.setAttribute( 'transform', @@ -677,9 +677,9 @@ Trashcan.prototype.onDelete_ = function(event) { if (this.workspace_.options.maxTrashcanContents <= 0) { return; } - if (event.type == eventUtils.BLOCK_DELETE && !event.wasShadow) { + if (event.type === eventUtils.BLOCK_DELETE && !event.wasShadow) { const cleanedJson = this.cleanBlockJson_(event.oldJson); - if (this.contents_.indexOf(cleanedJson) != -1) { + if (this.contents_.indexOf(cleanedJson) !== -1) { return; } this.contents_.unshift(cleanedJson); diff --git a/core/utils.js b/core/utils.js index 3a04cebb4..a10d11199 100644 --- a/core/utils.js +++ b/core/utils.js @@ -159,7 +159,7 @@ const getInjectionDivXY = function(element) { x = x + xy.x; y = y + xy.y; const classes = element.getAttribute('class') || ''; - if ((' ' + classes + ' ').indexOf(' injectionDiv ') != -1) { + if ((' ' + classes + ' ').indexOf(' injectionDiv ') !== -1) { break; } element = /** @type {!Element} */ (element.parentNode); @@ -264,11 +264,11 @@ exports.tokenizeInterpolation = tokenizeInterpolation; * @alias Blockly.utils.replaceMessageReferences */ const replaceMessageReferences = function(message) { - if (typeof message != 'string') { + if (typeof message !== 'string') { return message; } const interpolatedResult = tokenizeInterpolation_(message, false); - // When parseInterpolationTokens == false, interpolatedResult should be at + // When parseInterpolationTokens === false, interpolatedResult should be at // most length 1. return interpolatedResult.length ? String(interpolatedResult[0]) : ''; }; @@ -292,7 +292,7 @@ const checkMessageReferences = function(message) { const m = message.match(/%{BKY_[A-Z]\w*}/ig); for (let i = 0; i < m.length; i++) { const msgKey = m[i].toUpperCase(); - if (msgTable[msgKey.slice(6, -1)] == undefined) { + if (msgTable[msgKey.slice(6, -1)] === undefined) { console.warn('No message string for ' + m[i] + ' in ' + message); validSoFar = false; // Continue to report other errors. } @@ -325,8 +325,8 @@ const tokenizeInterpolation_ = function(message, parseInterpolationTokens) { let number = null; for (let i = 0; i < chars.length; i++) { const c = chars[i]; - if (state == 0) { - if (c == '%') { + if (state === 0) { + if (c === '%') { const text = buffer.join(''); if (text) { tokens.push(text); @@ -336,8 +336,8 @@ const tokenizeInterpolation_ = function(message, parseInterpolationTokens) { } else { buffer.push(c); // Regular char. } - } else if (state == 1) { - if (c == '%') { + } else if (state === 1) { + if (c === '%') { buffer.push(c); // Escaped %: %% state = 0; } else if (parseInterpolationTokens && '0' <= c && c <= '9') { @@ -348,13 +348,13 @@ const tokenizeInterpolation_ = function(message, parseInterpolationTokens) { tokens.push(text); } buffer.length = 0; - } else if (c == '{') { + } else if (c === '{') { state = 3; } else { buffer.push('%', c); // Not recognized. Return as literal. state = 0; } - } else if (state == 2) { + } else if (state === 2) { if ('0' <= c && c <= '9') { number += c; // Multi-digit number. } else { @@ -362,13 +362,13 @@ const tokenizeInterpolation_ = function(message, parseInterpolationTokens) { i--; // Parse this char again. state = 0; } - } else if (state == 3) { // String table reference - if (c == '') { + } else if (state === 3) { // String table reference + if (c === '') { // Premature end before closing '}' buffer.splice(0, 0, '%{'); // Re-insert leading delimiter i--; // Parse this char again. state = 0; // and parse as string literal. - } else if (c != '}') { + } else if (c !== '}') { buffer.push(c); } else { const rawKey = buffer.join(''); @@ -384,7 +384,7 @@ const tokenizeInterpolation_ = function(message, parseInterpolationTokens) { null; if (bklyKey && bklyKey in Msg) { const rawValue = Msg[bklyKey]; - if (typeof rawValue == 'string') { + if (typeof rawValue === 'string') { // Attempt to dereference substrings, too, appending to the end. Array.prototype.push.apply( tokens, @@ -420,7 +420,7 @@ const tokenizeInterpolation_ = function(message, parseInterpolationTokens) { const mergedTokens = []; buffer.length = 0; for (let i = 0; i < tokens.length; ++i) { - if (typeof tokens[i] == 'string') { + if (typeof tokens[i] === 'string') { buffer.push(tokens[i]); } else { text = buffer.join(''); @@ -513,15 +513,15 @@ exports.is3dSupported = is3dSupported; * @alias Blockly.utils.runAfterPageLoad */ const runAfterPageLoad = function(fn) { - if (typeof document != 'object') { + if (typeof document !== 'object') { throw Error('runAfterPageLoad() requires browser document.'); } - if (document.readyState == 'complete') { + if (document.readyState === 'complete') { fn(); // Page has already loaded. Call immediately. } else { // Poll readyState. const readyStateCheckInterval = setInterval(function() { - if (document.readyState == 'complete') { + if (document.readyState === 'complete') { clearInterval(readyStateCheckInterval); fn(); } @@ -557,7 +557,7 @@ exports.getViewportBBox = getViewportBBox; */ const arrayRemove = function(arr, value) { const i = arr.indexOf(value); - if (i == -1) { + if (i === -1) { return false; } arr.splice(i, 1); @@ -574,7 +574,7 @@ exports.arrayRemove = arrayRemove; const getDocumentScroll = function() { const el = document.documentElement; const win = window; - if (userAgent.IE && win.pageYOffset != el.scrollTop) { + if (userAgent.IE && win.pageYOffset !== el.scrollTop) { // The keyboard on IE10 touch devices shifts the page using the pageYOffset // without modifying scrollTop. For this case, we want the body scroll // offsets. @@ -666,7 +666,7 @@ exports.screenToWsCoordinates = screenToWsCoordinates; */ const parseBlockColour = function(colour) { const dereferenced = - (typeof colour == 'string') ? replaceMessageReferences(colour) : colour; + (typeof colour === 'string') ? replaceMessageReferences(colour) : colour; const hue = Number(dereferenced); if (!isNaN(hue) && 0 <= hue && hue <= 360) { @@ -683,7 +683,7 @@ const parseBlockColour = function(colour) { return {hue: null, hex: hex}; } else { let errorMsg = 'Invalid colour: "' + dereferenced + '"'; - if (colour != dereferenced) { + if (colour !== dereferenced) { errorMsg += ' (from "' + colour + '")'; } throw Error(errorMsg); diff --git a/core/utils/colour.js b/core/utils/colour.js index 7c56601f4..ea25d0821 100644 --- a/core/utils/colour.js +++ b/core/utils/colour.js @@ -42,8 +42,8 @@ const parse = function(str) { // e.g. 'red' return hex; } - hex = str.substring(0, 2) == '0x' ? '#' + str.substring(2) : str; - hex = hex[0] == '#' ? hex : '#' + hex; + hex = str.substring(0, 2) === '0x' ? '#' + str.substring(2) : str; + hex = hex[0] === '#' ? hex : '#' + hex; if (/^#[0-9a-f]{6}$/.test(hex)) { // e.g. '#00ff88' return hex; @@ -117,7 +117,7 @@ const hsvToHex = function(h, s, v) { let red = 0; let green = 0; let blue = 0; - if (s == 0) { + if (s === 0) { red = v; green = v; blue = v; diff --git a/core/utils/coordinate.js b/core/utils/coordinate.js index 9abef7214..f45c51f52 100644 --- a/core/utils/coordinate.js +++ b/core/utils/coordinate.js @@ -49,13 +49,13 @@ const Coordinate = function(x, y) { * @return {boolean} True iff the coordinates are equal, or if both are null. */ Coordinate.equals = function(a, b) { - if (a == b) { + if (a === b) { return true; } if (!a || !b) { return false; } - return a.x == b.x && a.y == b.y; + return a.x === b.x && a.y === b.y; }; /** diff --git a/core/utils/dom.js b/core/utils/dom.js index a22bbbf77..ac233fffc 100644 --- a/core/utils/dom.js +++ b/core/utils/dom.js @@ -123,7 +123,7 @@ exports.createSvgElement = createSvgElement; */ const addClass = function(element, className) { let classes = element.getAttribute('class') || ''; - if ((' ' + classes + ' ').indexOf(' ' + className + ' ') != -1) { + if ((' ' + classes + ' ').indexOf(' ' + className + ' ') !== -1) { return false; } if (classes) { @@ -159,12 +159,12 @@ exports.removeClasses = removeClasses; */ const removeClass = function(element, className) { const classes = element.getAttribute('class'); - if ((' ' + classes + ' ').indexOf(' ' + className + ' ') == -1) { + if ((' ' + classes + ' ').indexOf(' ' + className + ' ') === -1) { return false; } const classList = classes.split(/\s+/); for (let i = 0; i < classList.length; i++) { - if (!classList[i] || classList[i] == className) { + if (!classList[i] || classList[i] === className) { classList.splice(i, 1); i--; } @@ -188,7 +188,7 @@ exports.removeClass = removeClass; */ const hasClass = function(element, className) { const classes = element.getAttribute('class'); - return (' ' + classes + ' ').indexOf(' ' + className + ' ') != -1; + return (' ' + classes + ' ').indexOf(' ' + className + ' ') !== -1; }; exports.hasClass = hasClass; diff --git a/core/utils/object.js b/core/utils/object.js index fe23f0b45..18eafaac9 100644 --- a/core/utils/object.js +++ b/core/utils/object.js @@ -64,7 +64,7 @@ exports.mixin = mixin; */ const deepMerge = function(target, source) { for (const x in source) { - if (source[x] != null && typeof source[x] === 'object') { + if (source[x] !== null && typeof source[x] === 'object') { target[x] = deepMerge(target[x] || Object.create(null), source[x]); } else { target[x] = source[x]; diff --git a/core/utils/size.js b/core/utils/size.js index 4857d76d8..e456f03b3 100644 --- a/core/utils/size.js +++ b/core/utils/size.js @@ -51,13 +51,13 @@ const Size = function(width, height) { * heights, or if both are null. */ Size.equals = function(a, b) { - if (a == b) { + if (a === b) { return true; } if (!a || !b) { return false; } - return a.width == b.width && a.height == b.height; + return a.width === b.width && a.height === b.height; }; exports = Size; diff --git a/core/utils/string.js b/core/utils/string.js index d557cb661..e2505f936 100644 --- a/core/utils/string.js +++ b/core/utils/string.js @@ -30,7 +30,7 @@ goog.module('Blockly.utils.string'); * @alias Blockly.utils.string.startsWith */ const startsWith = function(str, prefix) { - return str.lastIndexOf(prefix, 0) == 0; + return str.lastIndexOf(prefix, 0) === 0; }; exports.startsWith = startsWith; @@ -63,7 +63,7 @@ exports.shortestStringLength = shortestStringLength; const commonWordPrefix = function(array, opt_shortest) { if (!array.length) { return 0; - } else if (array.length == 1) { + } else if (array.length === 1) { return array[0].length; } let wordPrefix = 0; @@ -72,17 +72,17 @@ const commonWordPrefix = function(array, opt_shortest) { for (len = 0; len < max; len++) { const letter = array[0][len]; for (let i = 1; i < array.length; i++) { - if (letter != array[i][len]) { + if (letter !== array[i][len]) { return wordPrefix; } } - if (letter == ' ') { + if (letter === ' ') { wordPrefix = len + 1; } } for (let i = 1; i < array.length; i++) { const letter = array[i][len]; - if (letter && letter != ' ') { + if (letter && letter !== ' ') { return wordPrefix; } } @@ -101,7 +101,7 @@ exports.commonWordPrefix = commonWordPrefix; const commonWordSuffix = function(array, opt_shortest) { if (!array.length) { return 0; - } else if (array.length == 1) { + } else if (array.length === 1) { return array[0].length; } let wordPrefix = 0; @@ -110,17 +110,17 @@ const commonWordSuffix = function(array, opt_shortest) { for (len = 0; len < max; len++) { const letter = array[0].substr(-len - 1, 1); for (let i = 1; i < array.length; i++) { - if (letter != array[i].substr(-len - 1, 1)) { + if (letter !== array[i].substr(-len - 1, 1)) { return wordPrefix; } } - if (letter == ' ') { + if (letter === ' ') { wordPrefix = len + 1; } } for (let i = 1; i < array.length; i++) { const letter = array[i].charAt(array[i].length - len - 1); - if (letter && letter != ' ') { + if (letter && letter !== ' ') { return wordPrefix; } } @@ -226,9 +226,9 @@ const wrapScore = function(words, wordBreaks, limit) { score -= Math.pow(maxLength - lineLengths[i], 1.5); // Optimize for structure. // Add score to line endings after punctuation. - if ('.?!'.indexOf(linePunctuation[i]) != -1) { + if ('.?!'.indexOf(linePunctuation[i]) !== -1) { score += limit / 3; - } else if (',;)]}'.indexOf(linePunctuation[i]) != -1) { + } else if (',;)]}'.indexOf(linePunctuation[i]) !== -1) { score += limit / 4; } } @@ -257,7 +257,7 @@ const wrapMutate = function(words, wordBreaks, limit) { let bestBreaks; // Try shifting every line break forward or backward. for (let i = 0; i < wordBreaks.length - 1; i++) { - if (wordBreaks[i] == wordBreaks[i + 1]) { + if (wordBreaks[i] === wordBreaks[i + 1]) { continue; } const mutatedWordBreaks = [].concat(wordBreaks); diff --git a/core/utils/style.js b/core/utils/style.js index 74ea969fe..effaad083 100644 --- a/core/utils/style.js +++ b/core/utils/style.js @@ -32,7 +32,7 @@ const Size = goog.require('Blockly.utils.Size'); * @alias Blockly.utils.style.getSize */ const getSize = function(element) { - if (getStyle(element, 'display') != 'none') { + if (getStyle(element, 'display') !== 'none') { return getSizeWithDisplay(element); } @@ -196,7 +196,7 @@ exports.setElementShown = setElementShown; * @alias Blockly.utils.style.isRightToLeft */ const isRightToLeft = function(el) { - return 'rtl' == getStyle(el, 'direction'); + return 'rtl' === getStyle(el, 'direction'); }; exports.isRightToLeft = isRightToLeft; diff --git a/core/utils/toolbox.js b/core/utils/toolbox.js index 6be5d872e..9e7b79852 100644 --- a/core/utils/toolbox.js +++ b/core/utils/toolbox.js @@ -246,7 +246,7 @@ const convertToolboxDefToJson = function(toolboxDef) { return null; } - if (toolboxDef instanceof Element || typeof toolboxDef == 'string') { + if (toolboxDef instanceof Element || typeof toolboxDef === 'string') { toolboxDef = parseToolboxTree(toolboxDef); toolboxDef = convertToToolboxJson(toolboxDef); } @@ -268,8 +268,8 @@ const validateToolbox = function(toolboxJson) { const toolboxContents = toolboxJson['contents']; if (toolboxKind) { - if (toolboxKind != FLYOUT_TOOLBOX_KIND && - toolboxKind != CATEGORY_TOOLBOX_KIND) { + if (toolboxKind !== FLYOUT_TOOLBOX_KIND && + toolboxKind !== CATEGORY_TOOLBOX_KIND) { throw Error( 'Invalid toolbox kind ' + toolboxKind + '.' + ' Please supply either ' + FLYOUT_TOOLBOX_KIND + ' or ' + @@ -323,11 +323,11 @@ const hasCategories = function(toolboxJson) { const toolboxKind = toolboxJson['kind']; if (toolboxKind) { - return toolboxKind == CATEGORY_TOOLBOX_KIND; + return toolboxKind === CATEGORY_TOOLBOX_KIND; } const categories = toolboxJson['contents'].filter(function(item) { - return item['kind'].toUpperCase() == 'CATEGORY'; + return item['kind'].toUpperCase() === 'CATEGORY'; }); return !!categories.length; }; @@ -347,7 +347,7 @@ const isCategoryCollapsible = function(categoryInfo) { } const categories = categoryInfo['contents'].filter(function(item) { - return item['kind'].toUpperCase() == 'CATEGORY'; + return item['kind'].toUpperCase() === 'CATEGORY'; }); return !!categories.length; }; @@ -395,7 +395,7 @@ const xmlToJsonArray = function(toolboxDef) { obj['kind'] = tagName; // Store the XML for a block. - if (tagName == 'BLOCK') { + if (tagName === 'BLOCK') { obj['blockxml'] = child; } else if (child.childNodes && child.childNodes.length > 0) { // Get the contents of a category @@ -435,7 +435,7 @@ const addAttributes = function(node, obj) { */ const parseToolboxTree = function(toolboxDef) { if (toolboxDef) { - if (typeof toolboxDef != 'string') { + if (typeof toolboxDef !== 'string') { if (userAgent.IE && toolboxDef.outerHTML) { // In this case the tree will not have been properly built by the // browser. The HTML will be contained in the element, but it will @@ -446,9 +446,9 @@ const parseToolboxTree = function(toolboxDef) { toolboxDef = null; } } - if (typeof toolboxDef == 'string') { + if (typeof toolboxDef === 'string') { toolboxDef = Xml.textToDom(toolboxDef); - if (toolboxDef.nodeName.toLowerCase() != 'xml') { + if (toolboxDef.nodeName.toLowerCase() !== 'xml') { throw TypeError('Toolbox should be an document.'); } } diff --git a/core/utils/useragent.js b/core/utils/useragent.js index db8017f93..fadcf9c16 100644 --- a/core/utils/useragent.js +++ b/core/utils/useragent.js @@ -77,7 +77,7 @@ const rawUpper = rawUserAgent.toUpperCase(); * @return {boolean} True if name is present. */ function has(name) { - return rawUpper.indexOf(name.toUpperCase()) != -1; + return rawUpper.indexOf(name.toUpperCase()) !== -1; } // Browsers. Logic from: diff --git a/core/variable_map.js b/core/variable_map.js index 56e0ee10f..61adb5b7a 100644 --- a/core/variable_map.js +++ b/core/variable_map.js @@ -81,7 +81,7 @@ VariableMap.prototype.renameVariable = function(variable, newName) { eventUtils.setGroup(true); try { // The IDs may match if the rename is a simple case change (name1 -> Name1). - if (!conflictVar || conflictVar.getId() == variable.getId()) { + if (!conflictVar || conflictVar.getId() === variable.getId()) { this.renameVariableAndUses_(variable, newName, blocks); } else { this.renameVariableWithConflict_(variable, newName, conflictVar, blocks); @@ -143,7 +143,7 @@ VariableMap.prototype.renameVariableWithConflict_ = function( const type = variable.type; const oldCase = conflictVar.name; - if (newName != oldCase) { + if (newName !== oldCase) { // Simple rename to change the case and update references. this.renameVariableAndUses_(conflictVar, newName, blocks); } @@ -176,7 +176,7 @@ VariableMap.prototype.renameVariableWithConflict_ = function( VariableMap.prototype.createVariable = function(name, opt_type, opt_id) { let variable = this.getVariable(name, opt_type); if (variable) { - if (opt_id && variable.getId() != opt_id) { + if (opt_id && variable.getId() !== opt_id) { throw Error( 'Variable "' + name + '" is already in use and its id is "' + variable.getId() + '" which conflicts with the passed in ' + @@ -214,7 +214,7 @@ VariableMap.prototype.deleteVariable = function(variable) { const variableList = this.variableMap_[variable.type]; for (let i = 0; i < variableList.length; i++) { const tempVar = variableList[i]; - if (tempVar.getId() == variableId) { + if (tempVar.getId() === variableId) { variableList.splice(i, 1); eventUtils.fire(new (eventUtils.get(eventUtils.VAR_DELETE))(variable)); return; @@ -234,8 +234,8 @@ VariableMap.prototype.deleteVariableById = function(id) { const variableName = variable.name; const uses = this.getVariableUsesById(id); for (let i = 0, block; (block = uses[i]); i++) { - if (block.type == 'procedures_defnoreturn' || - block.type == 'procedures_defreturn') { + if (block.type === 'procedures_defnoreturn' || + block.type === 'procedures_defreturn') { const procedureName = block.getFieldValue('NAME'); const deleteText = Msg['CANNOT_DELETE_VARIABLE_PROCEDURE'] .replace('%1', variableName) @@ -323,7 +323,7 @@ VariableMap.prototype.getVariableById = function(id) { for (let i = 0; i < keys.length; i++) { const key = keys[i]; for (let j = 0, variable; (variable = this.variableMap_[key][j]); j++) { - if (variable.getId() == id) { + if (variable.getId() === id) { return variable; } } @@ -365,7 +365,7 @@ VariableMap.prototype.getVariableTypes = function(ws) { const types = Object.keys(variableMap); let hasEmpty = false; for (let i = 0; i < types.length; i++) { - if (types[i] == '') { + if (types[i] === '') { hasEmpty = true; } } @@ -415,7 +415,7 @@ VariableMap.prototype.getVariableUsesById = function(id) { const blockVariables = blocks[i].getVarModels(); if (blockVariables) { for (let j = 0; j < blockVariables.length; j++) { - if (blockVariables[j].getId() == id) { + if (blockVariables[j].getId() === id) { uses.push(blocks[i]); } } diff --git a/core/variables.js b/core/variables.js index cfc31e516..44e4c11c7 100644 --- a/core/variables.js +++ b/core/variables.js @@ -224,7 +224,7 @@ const generateUniqueNameFromOptions = function(startChar, usedNames) { while (true) { let inUse = false; for (let i = 0; i < usedNames.length; i++) { - if (usedNames[i].toLowerCase() == potName) { + if (usedNames[i].toLowerCase() === potName) { inUse = true; break; } @@ -234,7 +234,7 @@ const generateUniqueNameFromOptions = function(startChar, usedNames) { } letterIndex++; - if (letterIndex == letters.length) { + if (letterIndex === letters.length) { // Reached the end of the character sequence so back to 'i'. letterIndex = 0; suffix = Number(suffix) + 1; @@ -272,7 +272,7 @@ const createVariableButtonHandler = function( const existing = nameUsedWithAnyType(text, workspace); if (existing) { let msg; - if (existing.type == type) { + if (existing.type === type) { msg = Msg['VARIABLE_ALREADY_EXISTS'].replace('%1', existing.name); } else { msg = Msg['VARIABLE_ALREADY_EXISTS_FOR_ANOTHER_TYPE']; @@ -360,7 +360,7 @@ const promptName = function(promptText, defaultText, callback) { // Beyond this, all names are legal. if (newVar) { newVar = newVar.replace(/[\s\xa0]+/g, ' ').trim(); - if (newVar == Msg['RENAME_VARIABLE'] || newVar == Msg['NEW_VARIABLE']) { + if (newVar === Msg['RENAME_VARIABLE'] || newVar === Msg['NEW_VARIABLE']) { // Ok, not ALL names are legal... newVar = null; } @@ -385,7 +385,7 @@ const nameUsedWithOtherType = function(name, type, workspace) { name = name.toLowerCase(); for (let i = 0, variable; (variable = allVariables[i]); i++) { - if (variable.name.toLowerCase() == name && variable.type != type) { + if (variable.name.toLowerCase() === name && variable.type !== type) { return variable; } } @@ -406,7 +406,7 @@ const nameUsedWithAnyType = function(name, workspace) { name = name.toLowerCase(); for (let i = 0, variable; (variable = allVariables[i]); i++) { - if (variable.name.toLowerCase() == name) { + if (variable.name.toLowerCase() === name) { return variable; } } @@ -489,7 +489,7 @@ const getVariable = function(workspace, id, opt_name, opt_type) { // If there was no ID, or there was an ID but it didn't match any variables, // look up by name and type. if (opt_name) { - if (opt_type == undefined) { + if (opt_type === undefined) { throw Error('Tried to look up a variable by name without a type'); } // Otherwise look up by name and type. @@ -546,12 +546,12 @@ const createVariable = function(workspace, id, opt_name, opt_type) { const getAddedVariables = function(workspace, originalVariables) { const allCurrentVariables = workspace.getAllVariables(); const addedVariables = []; - if (originalVariables.length != allCurrentVariables.length) { + if (originalVariables.length !== allCurrentVariables.length) { for (let i = 0; i < allCurrentVariables.length; i++) { const variable = allCurrentVariables[i]; // For any variable that is present in allCurrentVariables but not // present in originalVariables, add the variable to addedVariables. - if (originalVariables.indexOf(variable) == -1) { + if (originalVariables.indexOf(variable) === -1) { addedVariables.push(variable); } } diff --git a/core/warning.js b/core/warning.js index 996324c83..197844100 100644 --- a/core/warning.js +++ b/core/warning.js @@ -91,7 +91,7 @@ Warning.prototype.drawIcon_ = function(group) { * @param {boolean} visible True if the bubble should be visible. */ Warning.prototype.setVisible = function(visible) { - if (visible == this.isVisible()) { + if (visible === this.isVisible()) { return; } eventUtils.fire(new (eventUtils.get(eventUtils.BUBBLE_OPEN))( @@ -133,7 +133,7 @@ Warning.prototype.disposeBubble_ = function() { * multiple warnings. */ Warning.prototype.setText = function(text, id) { - if (this.text_[id] == text) { + if (this.text_[id] === text) { return; } if (text) { diff --git a/core/widgetdiv.js b/core/widgetdiv.js index 543264eb4..1b1e35272 100644 --- a/core/widgetdiv.js +++ b/core/widgetdiv.js @@ -188,7 +188,7 @@ exports.isVisible = isVisible; * @alias Blockly.WidgetDiv.hideIfOwner */ const hideIfOwner = function(oldOwner) { - if (owner == oldOwner) { + if (owner === oldOwner) { hide(); } }; diff --git a/core/workspace.js b/core/workspace.js index 7b4d336d4..d9ecf2832 100644 --- a/core/workspace.js +++ b/core/workspace.js @@ -596,7 +596,7 @@ Workspace.prototype.isCapacityAvailable = function(typeCountsMap) { * @return {boolean} True if it has block limits, false otherwise. */ Workspace.prototype.hasBlockLimits = function() { - return this.options.maxBlocks != Infinity || !!this.options.maxInstances; + return this.options.maxBlocks !== Infinity || !!this.options.maxInstances; }; /** @@ -631,7 +631,7 @@ Workspace.prototype.undo = function(redo) { let events = [inputEvent]; // Do another undo/redo if the next one is of the same group. while (inputStack.length && inputEvent.group && - inputEvent.group == inputStack[inputStack.length - 1].group) { + inputEvent.group === inputStack[inputStack.length - 1].group) { events.push(inputStack.pop()); } // Push these popped events on the opposite stack. diff --git a/core/workspace_audio.js b/core/workspace_audio.js index 7093505ef..ba5e5ae2a 100644 --- a/core/workspace_audio.js +++ b/core/workspace_audio.js @@ -139,7 +139,7 @@ WorkspaceAudio.prototype.play = function(name, opt_volume) { if (sound) { // Don't play one sound on top of another. const now = new Date; - if (this.lastSound_ != null && + if (this.lastSound_ !== null && now - this.lastSound_ < internalConstants.SOUND_LIMIT) { return; } diff --git a/core/workspace_comment.js b/core/workspace_comment.js index 20a0172aa..a0d286225 100644 --- a/core/workspace_comment.js +++ b/core/workspace_comment.js @@ -272,7 +272,7 @@ WorkspaceComment.prototype.getContent = function() { * @package */ WorkspaceComment.prototype.setContent = function(content) { - if (this.content_ != content) { + if (this.content_ !== content) { eventUtils.fire(new (eventUtils.get(eventUtils.COMMENT_CHANGE))( this, this.content_, content)); this.content_ = content; diff --git a/core/workspace_comment_svg.js b/core/workspace_comment_svg.js index a40a0b4bb..eddabeb97 100644 --- a/core/workspace_comment_svg.js +++ b/core/workspace_comment_svg.js @@ -172,7 +172,7 @@ WorkspaceCommentSvg.prototype.dispose = function() { return; } // If this comment is being dragged, unlink the mouse events. - if (common.getSelected() == this) { + if (common.getSelected() === this) { this.unselect(); this.workspace.cancelCurrentGesture(); } @@ -259,7 +259,7 @@ WorkspaceCommentSvg.prototype.showContextMenu = function(e) { * @package */ WorkspaceCommentSvg.prototype.select = function() { - if (common.getSelected() == this) { + if (common.getSelected() === this) { return; } let oldId = null; @@ -285,7 +285,7 @@ WorkspaceCommentSvg.prototype.select = function() { * @package */ WorkspaceCommentSvg.prototype.unselect = function() { - if (common.getSelected() != this) { + if (common.getSelected() !== this) { return; } const event = new (eventUtils.get(eventUtils.SELECTED))( @@ -362,15 +362,15 @@ WorkspaceCommentSvg.prototype.getRelativeToSurfaceXY = function() { // If this element is the current element on the drag surface, include // the translation of the drag surface itself. if (this.useDragSurface_ && - this.workspace.getBlockDragSurface().getCurrentBlock() == element) { + this.workspace.getBlockDragSurface().getCurrentBlock() === element) { const surfaceTranslation = this.workspace.getBlockDragSurface().getSurfaceTranslation(); x += surfaceTranslation.x; y += surfaceTranslation.y; } element = element.parentNode; - } while (element && element != this.workspace.getBubbleCanvas() && - element != dragSurfaceGroup); + } while (element && element !== this.workspace.getBubbleCanvas() && + element !== dragSurfaceGroup); } this.xy_ = new Coordinate(x, y); return this.xy_; diff --git a/core/workspace_drag_surface_svg.js b/core/workspace_drag_surface_svg.js index 14afdc9b8..c9f63bf22 100644 --- a/core/workspace_drag_surface_svg.js +++ b/core/workspace_drag_surface_svg.js @@ -138,7 +138,7 @@ WorkspaceDragSurfaceSvg.prototype.clearAndHide = function(newSurface) { // If there is a previous sibling, put the blockCanvas back right afterwards, // otherwise insert it as the first child node in newSurface. - if (this.previousSibling_ != null) { + if (this.previousSibling_ !== null) { dom.insertAfter(blockCanvas, this.previousSibling_); } else { newSurface.insertBefore(blockCanvas, newSurface.firstChild); diff --git a/core/workspace_svg.js b/core/workspace_svg.js index 3f7f27ae3..46f347174 100644 --- a/core/workspace_svg.js +++ b/core/workspace_svg.js @@ -795,14 +795,14 @@ WorkspaceSvg.prototype.getSvgXY = function(element) { do { // Loop through this block and every parent. const xy = utils.getRelativeXY(element); - if (element == this.getCanvas() || element == this.getBubbleCanvas()) { + if (element === this.getCanvas() || element === this.getBubbleCanvas()) { // After the SVG canvas, don't scale the coordinates. scale = 1; } x += xy.x * scale; y += xy.y * scale; element = /** @type {!SVGElement} */ (element.parentNode); - } while (element && element != this.getParentSvg()); + } while (element && element !== this.getParentSvg()); return new Coordinate(x, y); }; @@ -844,7 +844,7 @@ WorkspaceSvg.prototype.getInjectionDiv = function() { let element = this.svgGroup_; while (element) { const classes = element.getAttribute('class') || ''; - if ((' ' + classes + ' ').indexOf(' injectionDiv ') != -1) { + if ((' ' + classes + ' ').indexOf(' injectionDiv ') !== -1) { this.injectionDiv_ = element; break; } @@ -901,7 +901,7 @@ WorkspaceSvg.prototype.createDom = function(opt_backgroundClass) { {'height': '100%', 'width': '100%', 'class': opt_backgroundClass}, this.svgGroup_); - if (opt_backgroundClass == 'blocklyMainBackground' && this.grid_) { + if (opt_backgroundClass === 'blocklyMainBackground' && this.grid_) { this.svgBackground_.style.fill = 'url(#' + this.grid_.getPatternId() + ')'; } else { @@ -1271,7 +1271,7 @@ WorkspaceSvg.prototype.getParentSvg = function() { if (!this.cachedParentSvg_) { let element = this.svgGroup_; while (element) { - if (element.tagName == 'svg') { + if (element.tagName === 'svg') { this.cachedParentSvg_ = element; break; } @@ -1293,7 +1293,7 @@ WorkspaceSvg.prototype.maybeFireViewportChangeEvent = function() { const scale = this.scale; const top = -this.scrollY; const left = -this.scrollX; - if (scale == this.oldScale_ && Math.abs(top - this.oldTop_) < 1 && + if (scale === this.oldScale_ && Math.abs(top - this.oldTop_) < 1 && Math.abs(left - this.oldLeft_) < 1) { // Ignore sub-pixel changes in top and left. Due to #4192 there are a lot of // negligible changes in viewport top/left. @@ -1502,7 +1502,7 @@ WorkspaceSvg.prototype.highlightBlock = function(id, opt_state) { // Using Set here would be great, but at the cost of IE10 support. if (!state) { utils.arrayRemove(this.highlightedBlocks_, block); - } else if (this.highlightedBlocks_.indexOf(block) == -1) { + } else if (this.highlightedBlocks_.indexOf(block) === -1) { this.highlightedBlocks_.push(block); } block.setHighlighted(state); @@ -1529,7 +1529,7 @@ WorkspaceSvg.prototype.paste = function(state) { this.pasteBlock_(null, /** @type {!blocks.State} */ (state)); } else { const xmlBlock = /** @type {!Element} */ (state); - if (xmlBlock.tagName.toLowerCase() == 'comment') { + if (xmlBlock.tagName.toLowerCase() === 'comment') { this.pasteWorkspaceComment_(xmlBlock); } else { this.pasteBlock_(xmlBlock, null); @@ -1791,7 +1791,7 @@ WorkspaceSvg.prototype.moveDrag = function(e) { * @return {boolean} True if currently dragging or scrolling. */ WorkspaceSvg.prototype.isDragging = function() { - return this.currentGesture_ != null && this.currentGesture_.isDragging(); + return this.currentGesture_ !== null && this.currentGesture_.isDragging(); }; /** @@ -2079,7 +2079,7 @@ WorkspaceSvg.prototype.zoom = function(x, y, amount) { const speed = this.options.zoomOptions.scaleSpeed; let scaleChange = Math.pow(speed, amount); const newScale = this.scale * scaleChange; - if (this.scale == newScale) { + if (this.scale === newScale) { return; // No change in zoom. } @@ -2407,12 +2407,12 @@ WorkspaceSvg.prototype.scroll = function(x, y) { WorkspaceSvg.setTopLevelWorkspaceMetrics_ = function(xyRatio) { const metrics = this.getMetrics(); - if (typeof xyRatio.x == 'number') { + if (typeof xyRatio.x === 'number') { this.scrollX = -(metrics.scrollLeft + (metrics.scrollWidth - metrics.viewWidth) * xyRatio.x); } - if (typeof xyRatio.y == 'number') { + if (typeof xyRatio.y === 'number') { this.scrollY = -(metrics.scrollTop + (metrics.scrollHeight - metrics.viewHeight) * xyRatio.y); @@ -2547,7 +2547,7 @@ WorkspaceSvg.prototype.clear = function() { * given button is clicked. */ WorkspaceSvg.prototype.registerButtonCallback = function(key, func) { - if (typeof func != 'function') { + if (typeof func !== 'function') { throw TypeError('Button callbacks must be functions.'); } this.flyoutButtonCallbacks_[key] = func; @@ -2582,7 +2582,7 @@ WorkspaceSvg.prototype.removeButtonCallback = function(key) { * call when the given toolbox category is opened. */ WorkspaceSvg.prototype.registerToolboxCategoryCallback = function(key, func) { - if (typeof func != 'function') { + if (typeof func !== 'function') { throw TypeError('Toolbox category callbacks must be functions.'); } this.toolboxCategoryCallbacks_[key] = func; @@ -2618,8 +2618,8 @@ WorkspaceSvg.prototype.removeToolboxCategoryCallback = function(key) { */ WorkspaceSvg.prototype.getGesture = function(e) { const isStart = - (e.type == 'mousedown' || e.type == 'touchstart' || - e.type == 'pointerdown'); + (e.type === 'mousedown' || e.type === 'touchstart' || + e.type === 'pointerdown'); const gesture = this.currentGesture_; if (gesture) { diff --git a/core/xml.js b/core/xml.js index c950e68ee..0e46d189f 100644 --- a/core/xml.js +++ b/core/xml.js @@ -217,23 +217,23 @@ const blockToDom = function(block, opt_noId) { const input = block.inputList[i]; let container; let empty = true; - if (input.type == inputTypes.DUMMY) { + if (input.type === inputTypes.DUMMY) { continue; } else { const childBlock = input.connection.targetBlock(); - if (input.type == inputTypes.VALUE) { + if (input.type === inputTypes.VALUE) { container = utilsXml.createElement('value'); - } else if (input.type == inputTypes.STATEMENT) { + } else if (input.type === inputTypes.STATEMENT) { container = utilsXml.createElement('statement'); } - const shadow = input.connection.getShadowDom(); - if (shadow && (!childBlock || !childBlock.isShadow())) { - container.appendChild(cloneShadow(shadow, opt_noId)); + const childShadow = input.connection.getShadowDom(); + if (childShadow && (!childBlock || !childBlock.isShadow())) { + container.appendChild(cloneShadow(childShadow, opt_noId)); } if (childBlock) { - const elem = blockToDom(childBlock, opt_noId); - if (elem.nodeType == dom.NodeType.ELEMENT_NODE) { - container.appendChild(elem); + const childElem = blockToDom(childBlock, opt_noId); + if (childElem.nodeType === dom.NodeType.ELEMENT_NODE) { + container.appendChild(childElem); empty = false; } } @@ -243,8 +243,8 @@ const blockToDom = function(block, opt_noId) { element.appendChild(container); } } - if (block.inputsInline != undefined && - block.inputsInline != block.inputsInlineDefault) { + if (block.inputsInline !== undefined && + block.inputsInline !== block.inputsInlineDefault) { element.setAttribute('inline', block.inputsInline); } if (block.isCollapsed()) { @@ -266,16 +266,16 @@ const blockToDom = function(block, opt_noId) { const nextBlock = block.getNextBlock(); let container; if (nextBlock) { - const elem = blockToDom(nextBlock, opt_noId); - if (elem.nodeType == dom.NodeType.ELEMENT_NODE) { + const nextElem = blockToDom(nextBlock, opt_noId); + if (nextElem.nodeType === dom.NodeType.ELEMENT_NODE) { container = utilsXml.createElement('next'); - container.appendChild(elem); + container.appendChild(nextElem); element.appendChild(container); } } - const shadow = block.nextConnection && block.nextConnection.getShadowDom(); - if (shadow && (!nextBlock || !nextBlock.isShadow())) { - container.appendChild(cloneShadow(shadow, opt_noId)); + const nextShadow = block.nextConnection && block.nextConnection.getShadowDom(); + if (nextShadow && (!nextBlock || !nextBlock.isShadow())) { + container.appendChild(cloneShadow(nextShadow, opt_noId)); } return element; @@ -294,7 +294,7 @@ const cloneShadow = function(shadow, opt_noId) { let node = shadow; let textNode; while (node) { - if (opt_noId && node.nodeName == 'shadow') { + if (opt_noId && node.nodeName === 'shadow') { // Strip off IDs from shadow blocks. There should never be a 'block' as // a child of a 'shadow', so no need to check that. node.removeAttribute('id'); @@ -305,8 +305,8 @@ const cloneShadow = function(shadow, opt_noId) { while (node && !node.nextSibling) { textNode = node; node = node.parentNode; - if (textNode.nodeType == dom.NodeType.TEXT_NODE && - textNode.data.trim() == '' && node.firstChild != textNode) { + if (textNode.nodeType === dom.NodeType.TEXT_NODE && + textNode.data.trim() === '' && node.firstChild !== textNode) { // Prune whitespace after a tag. dom.removeNode(textNode); } @@ -314,8 +314,8 @@ const cloneShadow = function(shadow, opt_noId) { if (node) { textNode = node; node = node.nextSibling; - if (textNode.nodeType == dom.NodeType.TEXT_NODE && - textNode.data.trim() == '') { + if (textNode.nodeType === dom.NodeType.TEXT_NODE && + textNode.data.trim() === '') { // Prune whitespace before a tag. dom.removeNode(textNode); } @@ -357,11 +357,11 @@ const domToPrettyText = function(dom) { let indent = ''; for (let i = 1; i < lines.length; i++) { const line = lines[i]; - if (line[0] == '/') { + if (line[0] === '/') { indent = indent.substring(2); } lines[i] = indent + '<' + line; - if (line[0] != '/' && line.slice(-2) != '/>') { + if (line[0] !== '/' && line.slice(-2) !== '/>') { indent += ' '; } } @@ -450,8 +450,8 @@ const domToWorkspace = function(xml, workspace) { for (let i = 0, xmlChild; (xmlChild = xml.childNodes[i]); i++) { const name = xmlChild.nodeName.toLowerCase(); const xmlChildElement = /** @type {!Element} */ (xmlChild); - if (name == 'block' || - (name == 'shadow' && !eventUtils.getRecordUndo())) { + if (name === 'block' || + (name === 'shadow' && !eventUtils.getRecordUndo())) { // Allow top-level shadow blocks if recordUndo is disabled since // that means an undo is in progress. Such a block is expected // to be moved to a nested destination in the next operation. @@ -467,9 +467,9 @@ const domToWorkspace = function(xml, workspace) { block.moveBy(workspace.RTL ? width - blockX : blockX, blockY); } variablesFirst = false; - } else if (name == 'shadow') { + } else if (name === 'shadow') { throw TypeError('Shadow block cannot be a top-level block.'); - } else if (name == 'comment') { + } else if (name === 'comment') { if (workspace.rendered) { const WorkspaceCommentSvg = goog.module.get('Blockly.WorkspaceCommentSvg'); @@ -492,7 +492,7 @@ const domToWorkspace = function(xml, workspace) { WorkspaceComment.fromXml(xmlChildElement, workspace); } } - } else if (name == 'variables') { + } else if (name === 'variables') { if (variablesFirst) { domToVariables(xmlChildElement, workspace); } else { @@ -536,7 +536,7 @@ const appendDomToWorkspace = function(xml, workspace) { } // Load the new blocks into the workspace and get the IDs of the new blocks. const newBlockIds = domToWorkspace(xml, workspace); - if (bbox && bbox.top != bbox.bottom) { // check if any previous block + if (bbox && bbox.top !== bbox.bottom) { // check if any previous block let offsetY = 0; // offset to add to y of the new block let offsetX = 0; const farY = bbox.bottom; // bottom position @@ -654,7 +654,7 @@ exports.domToBlock = domToBlock; const domToVariables = function(xmlVariables, workspace) { for (let i = 0; i < xmlVariables.childNodes.length; i++) { const xmlChild = xmlVariables.childNodes[i]; - if (xmlChild.nodeType != dom.NodeType.ELEMENT_NODE) { + if (xmlChild.nodeType !== dom.NodeType.ELEMENT_NODE) { continue; // Skip text nodes. } const type = xmlChild.getAttribute('type'); @@ -691,7 +691,7 @@ const mapSupportedXmlTags = function(xmlBlock) { {mutation: [], comment: [], data: [], field: [], input: [], next: []}; for (let i = 0; i < xmlBlock.childNodes.length; i++) { const xmlChild = xmlBlock.childNodes[i]; - if (xmlChild.nodeType == dom.NodeType.TEXT_NODE) { + if (xmlChild.nodeType === dom.NodeType.TEXT_NODE) { // Ignore any text at the level. It's all whitespace anyway. continue; } @@ -764,7 +764,7 @@ const applyCommentTagNodes = function(xmlChildren, block) { for (let i = 0; i < xmlChildren.length; i++) { const xmlChild = xmlChildren[i]; const text = xmlChild.textContent; - const pinned = xmlChild.getAttribute('pinned') == 'true'; + const pinned = xmlChild.getAttribute('pinned') === 'true'; const width = parseInt(xmlChild.getAttribute('w'), 10); const height = parseInt(xmlChild.getAttribute('h'), 10); @@ -817,10 +817,10 @@ const findChildBlocks = function(xmlNode) { const childBlockInfo = {childBlockElement: null, childShadowElement: null}; for (let i = 0; i < xmlNode.childNodes.length; i++) { const xmlChild = xmlNode.childNodes[i]; - if (xmlChild.nodeType == dom.NodeType.ELEMENT_NODE) { - if (xmlChild.nodeName.toLowerCase() == 'block') { + if (xmlChild.nodeType === dom.NodeType.ELEMENT_NODE) { + if (xmlChild.nodeName.toLowerCase() === 'block') { childBlockInfo.childBlockElement = /** @type {!Element} */ (xmlChild); - } else if (xmlChild.nodeName.toLowerCase() == 'shadow') { + } else if (xmlChild.nodeName.toLowerCase() === 'shadow') { childBlockInfo.childShadowElement = /** @type {!Element} */ (xmlChild); } } @@ -956,29 +956,29 @@ const domToBlockHeadless = function( const inline = xmlBlock.getAttribute('inline'); if (inline) { - block.setInputsInline(inline == 'true'); + block.setInputsInline(inline === 'true'); } const disabled = xmlBlock.getAttribute('disabled'); if (disabled) { - block.setEnabled(disabled != 'true' && disabled != 'disabled'); + block.setEnabled(disabled !== 'true' && disabled !== 'disabled'); } const deletable = xmlBlock.getAttribute('deletable'); if (deletable) { - block.setDeletable(deletable == 'true'); + block.setDeletable(deletable === 'true'); } const movable = xmlBlock.getAttribute('movable'); if (movable) { - block.setMovable(movable == 'true'); + block.setMovable(movable === 'true'); } const editable = xmlBlock.getAttribute('editable'); if (editable) { - block.setEditable(editable == 'true'); + block.setEditable(editable === 'true'); } const collapsed = xmlBlock.getAttribute('collapsed'); if (collapsed) { - block.setCollapsed(collapsed == 'true'); + block.setCollapsed(collapsed === 'true'); } - if (xmlBlock.nodeName.toLowerCase() == 'shadow') { + if (xmlBlock.nodeName.toLowerCase() === 'shadow') { // Ensure all children are also shadows. const children = block.getChildren(false); for (let i = 0; i < children.length; i++) { @@ -1021,7 +1021,7 @@ const domToField = function(block, fieldName, xml) { const deleteNext = function(xmlBlock) { for (let i = 0; i < xmlBlock.childNodes.length; i++) { const child = xmlBlock.childNodes[i]; - if (child.nodeName.toLowerCase() == 'next') { + if (child.nodeName.toLowerCase() === 'next') { xmlBlock.removeChild(child); break; } diff --git a/demos/blockfactory/app_controller.js b/demos/blockfactory/app_controller.js index 62157b04a..e5ae002f1 100644 --- a/demos/blockfactory/app_controller.js +++ b/demos/blockfactory/app_controller.js @@ -201,7 +201,7 @@ AppController.prototype.getBlockTypeFromXml_ = function(xmlText) { var fields = factoryBaseBlockXml.getElementsByTagName('field'); for (var i = 0; i < fields.length; i++) { // The field whose name is 'NAME' holds the block type as its value. - if (fields[i].getAttribute('name') == 'NAME') { + if (fields[i].getAttribute('name') === 'NAME') { return fields[i].childNodes[0].nodeValue; } } @@ -258,8 +258,8 @@ AppController.prototype.onTab = function() { var workspaceFactoryTab = this.tabMap[AppController.WORKSPACE_FACTORY]; // Warn user if they have unsaved changes when leaving Block Factory. - if (this.lastSelectedTab == AppController.BLOCK_FACTORY && - this.selectedTab != AppController.BLOCK_FACTORY) { + if (this.lastSelectedTab === AppController.BLOCK_FACTORY && + this.selectedTab !== AppController.BLOCK_FACTORY) { var hasUnsavedChanges = !FactoryUtils.savedBlockChanges(this.blockLibraryController); @@ -280,12 +280,12 @@ AppController.prototype.onTab = function() { // Only enable key events in workspace factory if workspace factory tab is // selected. this.workspaceFactoryController.keyEventsEnabled = - this.selectedTab == AppController.WORKSPACE_FACTORY; + this.selectedTab === AppController.WORKSPACE_FACTORY; // Turn selected tab on and other tabs off. this.styleTabs_(); - if (this.selectedTab == AppController.EXPORTER) { + if (this.selectedTab === AppController.EXPORTER) { BlocklyDevTools.Analytics.onNavigateTo('Exporter'); // Hide other tabs. @@ -308,7 +308,7 @@ AppController.prototype.onTab = function() { // Update the exporter's preview to reflect any changes made to the blocks. this.exporter.updatePreview(); - } else if (this.selectedTab == AppController.BLOCK_FACTORY) { + } else if (this.selectedTab === AppController.BLOCK_FACTORY) { BlocklyDevTools.Analytics.onNavigateTo('BlockFactory'); // Hide other tabs. @@ -317,7 +317,7 @@ AppController.prototype.onTab = function() { // Show Block Factory. FactoryUtils.show('blockFactoryContent'); - } else if (this.selectedTab == AppController.WORKSPACE_FACTORY) { + } else if (this.selectedTab === AppController.WORKSPACE_FACTORY) { // TODO: differentiate Workspace and Toolbox editor, based on the other tab state. BlocklyDevTools.Analytics.onNavigateTo('WorkspaceFactory'); @@ -343,7 +343,7 @@ AppController.prototype.onTab = function() { */ AppController.prototype.styleTabs_ = function() { for (var tabName in this.tabMap) { - if (this.selectedTab == tabName) { + if (this.selectedTab === tabName) { this.tabMap[tabName].classList.replace('taboff', 'tabon'); } else { this.tabMap[tabName].classList.replace('tabon', 'taboff'); @@ -585,7 +585,7 @@ AppController.prototype.initializeBlocklyStorage = function() { * Handle resizing of elements. */ AppController.prototype.onresize = function(event) { - if (this.selectedTab == AppController.BLOCK_FACTORY) { + if (this.selectedTab === AppController.BLOCK_FACTORY) { // Handle resizing of Block Factory elements. var expandList = [ document.getElementById('blocklyPreviewContainer'), @@ -600,7 +600,7 @@ AppController.prototype.onresize = function(event) { expand.style.width = (expand.parentNode.offsetWidth - 2) + 'px'; expand.style.height = (expand.parentNode.offsetHeight - 2) + 'px'; } - } else if (this.selectedTab == AppController.EXPORTER) { + } else if (this.selectedTab === AppController.EXPORTER) { // Handle resize of Exporter block options. this.exporter.view.centerPreviewBlocks(); } diff --git a/demos/blockfactory/block_exporter_controller.js b/demos/blockfactory/block_exporter_controller.js index b195bf374..0b22e00e2 100644 --- a/demos/blockfactory/block_exporter_controller.js +++ b/demos/blockfactory/block_exporter_controller.js @@ -93,7 +93,7 @@ BlockExporterController.prototype.export = function() { BlocklyDevTools.Analytics.onExport( BlocklyDevTools.Analytics.BLOCK_DEFINITIONS, { - format: (definitionFormat == 'JSON' ? + format: (definitionFormat === 'JSON' ? BlocklyDevTools.Analytics.FORMAT_JSON : BlocklyDevTools.Analytics.FORMAT_JS) }); @@ -226,9 +226,9 @@ BlockExporterController.prototype.selectUsedBlocks = function() { var unstoredCustomBlockTypes = []; for (var i = 0, blockType; blockType = this.usedBlockTypes[i]; i++) { - if (storedBlockTypes.indexOf(blockType) != -1) { + if (storedBlockTypes.indexOf(blockType) !== -1) { sharedBlockTypes.push(blockType); - } else if (StandardCategories.coreBlockTypes.indexOf(blockType) == -1) { + } else if (StandardCategories.coreBlockTypes.indexOf(blockType) === -1) { unstoredCustomBlockTypes.push(blockType); } } diff --git a/demos/blockfactory/block_exporter_tools.js b/demos/blockfactory/block_exporter_tools.js index 1af4ace60..2b949a6b7 100644 --- a/demos/blockfactory/block_exporter_tools.js +++ b/demos/blockfactory/block_exporter_tools.js @@ -90,7 +90,7 @@ BlockExporterTools.prototype.getBlockDefinitions = } // Surround json with [] and comma separate items. - if (definitionFormat == "JSON") { + if (definitionFormat === "JSON") { return "[" + blockCode.join(",\n") + "]"; } return blockCode.join("\n\n"); diff --git a/demos/blockfactory/block_library_controller.js b/demos/blockfactory/block_library_controller.js index c4ab6ac68..c4a7a1d12 100644 --- a/demos/blockfactory/block_library_controller.js +++ b/demos/blockfactory/block_library_controller.js @@ -111,7 +111,7 @@ BlockLibraryController.prototype.clearBlockLibrary = function() { BlockLibraryController.prototype.saveToBlockLibrary = function() { var blockType = this.getCurrentBlockType(); // If user has not changed the name of the starter block. - if (blockType == 'block_type') { + if (blockType === 'block_type') { // Do not save block if it has the default type, 'block_type'. var msg = 'You cannot save a block under the name "block_type". Try ' + 'changing the name before saving. Then, click on the "Block Library"' + @@ -151,7 +151,7 @@ BlockLibraryController.prototype.saveToBlockLibrary = function() { */ BlockLibraryController.prototype.has = function(blockType) { var blockLibrary = this.storage.blocks; - return (blockType in blockLibrary && blockLibrary[blockType] != null); + return (blockType in blockLibrary && blockLibrary[blockType] !== null); }; /** diff --git a/demos/blockfactory/block_library_storage.js b/demos/blockfactory/block_library_storage.js index 38a822cb2..01f4609c3 100644 --- a/demos/blockfactory/block_library_storage.js +++ b/demos/blockfactory/block_library_storage.js @@ -26,7 +26,7 @@ function BlockLibraryStorage(blockLibraryName, opt_blocks) { if (!opt_blocks) { // Initialize this.blocks by loading from local storage. this.loadFromLocalStorage(); - if (this.blocks == null) { + if (this.blocks === null) { this.blocks = Object.create(null); // The line above is equivalent of {} except that this object is TRULY // empty. It doesn't have built-in attributes/functions such as length or diff --git a/demos/blockfactory/block_library_view.js b/demos/blockfactory/block_library_view.js index 61779fdf6..3a9f2f559 100644 --- a/demos/blockfactory/block_library_view.js +++ b/demos/blockfactory/block_library_view.js @@ -64,7 +64,7 @@ BlockLibraryView.prototype.setSelectedBlockType = function(blockTypeToSelect) { // if null or invalid block type selected. for (var blockType in this.optionMap) { var option = this.optionMap[blockType]; - if (blockType == blockTypeToSelect) { + if (blockType === blockTypeToSelect) { this.selectOption_(option); } else { this.deselectOption_(option); @@ -127,7 +127,7 @@ BlockLibraryView.prototype.updateButtons = // If block type is the default, 'block_type', make button red to alert // user. - if (blockType == 'block_type') { + if (blockType === 'block_type') { buttonFormatClass = 'button_alert'; } this.saveButton.classList.add(buttonFormatClass); diff --git a/demos/blockfactory/blocks.js b/demos/blockfactory/blocks.js index 65f75665e..8ddd8c57e 100644 --- a/demos/blockfactory/blocks.js +++ b/demos/blockfactory/blocks.js @@ -95,21 +95,21 @@ Blockly.Blocks['factory_base'] = { var outputExists = this.getInput('OUTPUTTYPE'); var topExists = this.getInput('TOPTYPE'); var bottomExists = this.getInput('BOTTOMTYPE'); - if (option == 'LEFT') { + if (option === 'LEFT') { if (!outputExists) { this.addTypeInput_('OUTPUTTYPE', 'output type'); } } else if (outputExists) { this.removeInput('OUTPUTTYPE'); } - if (option == 'TOP' || option == 'BOTH') { + if (option === 'TOP' || option === 'BOTH') { if (!topExists) { this.addTypeInput_('TOPTYPE', 'top type'); } } else if (topExists) { this.removeInput('TOPTYPE'); } - if (option == 'BOTTOM' || option == 'BOTH') { + if (option === 'BOTTOM' || option === 'BOTH') { if (!bottomExists) { this.addTypeInput_('BOTTOMTYPE', 'bottom type'); } @@ -352,7 +352,7 @@ Blockly.Blocks['field_dropdown'] = { domToMutation: function(container) { // Parse XML to restore the menu options. var value = JSON.parse(container.getAttribute('options')); - if (typeof value == 'number') { + if (typeof value === 'number') { // Old format from before images were added. November 2016. this.optionList_ = []; for (var i = 0; i < value; i++) { @@ -384,9 +384,9 @@ Blockly.Blocks['field_dropdown'] = { this.optionList_.length = 0; var data = []; while (optionBlock) { - if (optionBlock.type == 'field_dropdown_option_text') { + if (optionBlock.type === 'field_dropdown_option_text') { this.optionList_.push('text'); - } else if (optionBlock.type == 'field_dropdown_option_image') { + } else if (optionBlock.type === 'field_dropdown_option_image') { this.optionList_.push('image'); } data.push([optionBlock.userData_, optionBlock.cpuData_]); @@ -398,7 +398,7 @@ Blockly.Blocks['field_dropdown'] = { for (var i = 0; i < this.optionList_.length; i++) { var userData = data[i][0]; if (userData !== undefined) { - if (typeof userData == 'string') { + if (typeof userData === 'string') { this.setFieldValue(userData || 'option', 'USER' + i); } else { this.setFieldValue(userData.src, 'SRC' + i); @@ -434,13 +434,13 @@ Blockly.Blocks['field_dropdown'] = { var src = 'https://www.gstatic.com/codesite/ph/images/star_on.gif'; for (var i = 0; i <= this.optionList_.length; i++) { var type = this.optionList_[i]; - if (type == 'text') { + if (type === 'text') { this.appendDummyInput('OPTION' + i) .appendField('•') .appendField(new Blockly.FieldTextInput('option'), 'USER' + i) .appendField(',') .appendField(new Blockly.FieldTextInput('OPTIONNAME'), 'CPU' + i); - } else if (type == 'image') { + } else if (type === 'image') { this.appendDummyInput('OPTION' + i) .appendField('•') .appendField('image') @@ -466,10 +466,10 @@ Blockly.Blocks['field_dropdown'] = { } }, getUserData: function(n) { - if (this.optionList_[n] == 'text') { + if (this.optionList_[n] === 'text') { return this.getFieldValue('USER' + n); } - if (this.optionList_[n] == 'image') { + if (this.optionList_[n] === 'image') { return { src: this.getFieldValue('SRC' + n), width: Number(this.getFieldValue('WIDTH' + n)), @@ -633,7 +633,7 @@ Blockly.Blocks['type_group'] = { for (var i = 0; i < this.typeCount_; i++) { var input = this.appendValueInput('TYPE' + i) .setCheck('Type'); - if (i == 0) { + if (i === 0) { input.appendField('any of'); } } @@ -664,7 +664,7 @@ Blockly.Blocks['type_group'] = { // Disconnect any children that don't belong. for (var i = 0; i < this.typeCount_; i++) { var connection = this.getInput('TYPE' + i).connection.targetConnection; - if (connection && connections.indexOf(connection) == -1) { + if (connection && connections.indexOf(connection) === -1) { connection.disconnect(); } } @@ -693,7 +693,7 @@ Blockly.Blocks['type_group'] = { for (var i = 0; i < this.typeCount_; i++) { if (!this.getInput('TYPE' + i)) { var input = this.appendValueInput('TYPE' + i); - if (i == 0) { + if (i === 0) { input.appendField('any of'); } } @@ -863,7 +863,7 @@ function fieldNameCheck(referenceBlock) { for (var i = 0, block; block = blocks[i]; i++) { var otherName = block.getFieldValue('FIELDNAME'); if (!block.disabled && !block.getInheritedDisabled() && - otherName && otherName.toLowerCase() == name) { + otherName && otherName.toLowerCase() === name) { count++; } } @@ -888,7 +888,7 @@ function inputNameCheck(referenceBlock) { for (var i = 0, block; block = blocks[i]; i++) { var otherName = block.getFieldValue('INPUTNAME'); if (!block.disabled && !block.getInheritedDisabled() && - otherName && otherName.toLowerCase() == name) { + otherName && otherName.toLowerCase() === name) { count++; } } diff --git a/demos/blockfactory/cp.js b/demos/blockfactory/cp.js index 863aa7a9b..962481761 100644 --- a/demos/blockfactory/cp.js +++ b/demos/blockfactory/cp.js @@ -105,7 +105,7 @@ function cp_open(e) { } else { div.innerHTML = 'X'; } - if (currentColour == colour.toLowerCase()) { + if (currentColour === colour.toLowerCase()) { div.className = 'cp_current' } } diff --git a/demos/blockfactory/factory.js b/demos/blockfactory/factory.js index 78c53416c..44f2f583c 100644 --- a/demos/blockfactory/factory.js +++ b/demos/blockfactory/factory.js @@ -86,8 +86,8 @@ BlockFactory.formatChange = function() { var mask = document.getElementById('blocklyMask'); var languagePre = document.getElementById('languagePre'); var languageTA = document.getElementById('languageTA'); - if (document.getElementById('format').value == 'Manual-JSON' || - document.getElementById('format').value == 'Manual-JS') { + if (document.getElementById('format').value === 'Manual-JSON' || + document.getElementById('format').value === 'Manual-JS') { Blockly.common.getMainWorkspace().hideChaff(); mask.style.display = 'block'; languagePre.style.display = 'none'; @@ -123,9 +123,9 @@ BlockFactory.updateLanguage = function() { if (!BlockFactory.updateBlocksFlag) { var format = document.getElementById('format').value; - if (format == 'Manual-JSON') { + if (format === 'Manual-JSON') { format = 'JSON'; - } else if (format == 'Manual-JS') { + } else if (format === 'Manual-JS') { format = 'JavaScript'; } @@ -159,11 +159,11 @@ BlockFactory.updateGenerator = function(block) { BlockFactory.updatePreview = function() { // Toggle between LTR/RTL if needed (also used in first display). var newDir = document.getElementById('direction').value; - if (BlockFactory.oldDir != newDir) { + if (BlockFactory.oldDir !== newDir) { if (BlockFactory.previewWorkspace) { BlockFactory.previewWorkspace.dispose(); } - var rtl = newDir == 'rtl'; + var rtl = newDir === 'rtl'; BlockFactory.previewWorkspace = Blockly.inject('preview', {rtl: rtl, media: '../../media/', @@ -190,14 +190,14 @@ BlockFactory.updatePreview = function() { delete Blockly.Blocks[key]; } - if (format == 'JSON') { + if (format === 'JSON') { var json = JSON.parse(code); Blockly.Blocks[json.type || BlockFactory.UNNAMED] = { init: function() { this.jsonInit(json); } }; - } else if (format == 'JavaScript') { + } else if (format === 'JavaScript') { try { eval(code); } catch (e) { @@ -229,11 +229,11 @@ BlockFactory.updatePreview = function() { // Warn user only if their block type is already exists in Blockly's // standard library. var rootBlock = FactoryUtils.getRootBlock(BlockFactory.mainWorkspace); - if (StandardCategories.coreBlockTypes.indexOf(blockType) != -1) { + if (StandardCategories.coreBlockTypes.indexOf(blockType) !== -1) { rootBlock.setWarningText('A core Blockly block already exists ' + 'under this name.'); - } else if (blockType == 'block_type') { + } else if (blockType === 'block_type') { // Warn user to let them know they can't save a block under the default // name 'block_type' rootBlock.setWarningText('You cannot save a block with the default ' + @@ -284,7 +284,7 @@ BlockFactory.disableEnableLink = function() { var linkButton = document.getElementById('linkButton'); var saveBlockButton = document.getElementById('localSaveButton'); var saveToLibButton = document.getElementById('saveToBlockLibraryButton'); - var disabled = document.getElementById('format').value.substr(0, 6) == 'Manual'; + var disabled = document.getElementById('format').value.substr(0, 6) === 'Manual'; linkButton.disabled = disabled; saveBlockButton.disabled = disabled; saveToLibButton.disabled = disabled; @@ -308,11 +308,11 @@ BlockFactory.isStarterBlock = function() { // The starter block does not have blocks nested into the factory_base block. rootBlock.getChildren().length > 0 || // The starter block's name is the default, 'block_type'. - rootBlock.getFieldValue('NAME').trim().toLowerCase() != 'block_type' || + rootBlock.getFieldValue('NAME').trim().toLowerCase() !== 'block_type' || // The starter block has no connections. - rootBlock.getFieldValue('CONNECTIONS') != 'NONE' || + rootBlock.getFieldValue('CONNECTIONS') !== 'NONE' || // The starter block has automatic inputs. - rootBlock.getFieldValue('INLINE') != 'AUTO' + rootBlock.getFieldValue('INLINE') !== 'AUTO' ); }; diff --git a/demos/blockfactory/factory_utils.js b/demos/blockfactory/factory_utils.js index 93ca8ba97..cc2e6ed76 100644 --- a/demos/blockfactory/factory_utils.js +++ b/demos/blockfactory/factory_utils.js @@ -108,7 +108,7 @@ FactoryUtils.getGeneratorStub = function(block, generatorLanguage) { " = block.getFieldValue('" + name + "');"); } else if (field instanceof Blockly.FieldCheckbox) { code.push(makeVar('checkbox', name) + - " = block.getFieldValue('" + name + "') == 'TRUE';"); + " = block.getFieldValue('" + name + "') === 'TRUE';"); } else if (field instanceof Blockly.FieldDropdown) { code.push(makeVar('dropdown', name) + " = block.getFieldValue('" + name + "');"); @@ -122,11 +122,11 @@ FactoryUtils.getGeneratorStub = function(block, generatorLanguage) { } var name = input.name; if (name) { - if (input.type == Blockly.INPUT_VALUE) { + if (input.type === Blockly.INPUT_VALUE) { code.push(makeVar('value', name) + " = Blockly." + language + ".valueToCode(block, '" + name + "', Blockly." + language + ".ORDER_ATOMIC);"); - } else if (input.type == Blockly.NEXT_STATEMENT) { + } else if (input.type === Blockly.NEXT_STATEMENT) { code.push(makeVar('statements', name) + " = Blockly." + language + ".statementToCode(block, '" + name + "');"); @@ -176,7 +176,7 @@ FactoryUtils.formatJson_ = function(blockType, rootBlock) { var fields = FactoryUtils.getFieldsJson_( contentsBlock.getInputTargetBlock('FIELDS')); for (var i = 0; i < fields.length; i++) { - if (typeof fields[i] == 'string') { + if (typeof fields[i] === 'string') { message.push(fields[i].replace(/%/g, '%%')); } else { args.push(fields[i]); @@ -186,7 +186,7 @@ FactoryUtils.formatJson_ = function(blockType, rootBlock) { var input = {type: contentsBlock.type}; // Dummy inputs don't have names. Other inputs do. - if (contentsBlock.type != 'input_dummy') { + if (contentsBlock.type !== 'input_dummy') { input.name = contentsBlock.getFieldValue('INPUTNAME'); } var check = JSON.parse( @@ -195,7 +195,7 @@ FactoryUtils.formatJson_ = function(blockType, rootBlock) { input.check = check; } var align = contentsBlock.getFieldValue('ALIGN'); - if (align != 'LEFT') { + if (align !== 'LEFT') { input.align = align; } args.push(input); @@ -206,11 +206,11 @@ FactoryUtils.formatJson_ = function(blockType, rootBlock) { contentsBlock.nextConnection.targetBlock(); } // Remove last input if dummy and not empty. - if (lastInput && lastInput.type == 'input_dummy') { + if (lastInput && lastInput.type === 'input_dummy') { var fields = lastInput.getInputTargetBlock('FIELDS'); - if (fields && FactoryUtils.getFieldsJson_(fields).join('').trim() != '') { + if (fields && FactoryUtils.getFieldsJson_(fields).join('').trim() !== '') { var align = lastInput.getFieldValue('ALIGN'); - if (align != 'LEFT') { + if (align !== 'LEFT') { JS.lastDummyAlign0 = align; } args.pop(); @@ -222,9 +222,9 @@ FactoryUtils.formatJson_ = function(blockType, rootBlock) { JS.args0 = args; } // Generate inline/external switch. - if (rootBlock.getFieldValue('INLINE') == 'EXT') { + if (rootBlock.getFieldValue('INLINE') === 'EXT') { JS.inputsInline = false; - } else if (rootBlock.getFieldValue('INLINE') == 'INT') { + } else if (rootBlock.getFieldValue('INLINE') === 'INT') { JS.inputsInline = true; } // Generate output, or next/previous connections. @@ -287,7 +287,7 @@ FactoryUtils.formatJavaScript_ = function(blockType, rootBlock, workspace) { if (!contentsBlock.disabled && !contentsBlock.getInheritedDisabled()) { var name = ''; // Dummy inputs don't have names. Other inputs do. - if (contentsBlock.type != 'input_dummy') { + if (contentsBlock.type !== 'input_dummy') { name = JSON.stringify(contentsBlock.getFieldValue('INPUTNAME')); } @@ -297,7 +297,7 @@ FactoryUtils.formatJavaScript_ = function(blockType, rootBlock, workspace) { code.push(' .setCheck(' + check + ')'); } var align = contentsBlock.getFieldValue('ALIGN'); - if (align != 'LEFT') { + if (align !== 'LEFT') { code.push(' .setAlign(Blockly.ALIGN_' + align + ')'); } var fields = FactoryUtils.getFieldsJs_( @@ -312,9 +312,9 @@ FactoryUtils.formatJavaScript_ = function(blockType, rootBlock, workspace) { contentsBlock.nextConnection.targetBlock(); } // Generate inline/external switch. - if (rootBlock.getFieldValue('INLINE') == 'EXT') { + if (rootBlock.getFieldValue('INLINE') === 'EXT') { code.push(' this.setInputsInline(false);'); - } else if (rootBlock.getFieldValue('INLINE') == 'INT') { + } else if (rootBlock.getFieldValue('INLINE') === 'INT') { code.push(' this.setInputsInline(true);'); } // Generate output, or next/previous connections. @@ -410,11 +410,11 @@ FactoryUtils.getFieldsJs_ = function(block) { Number(block.getFieldValue('PRECISION')) ]; // Remove any trailing arguments that aren't needed. - if (args[3] == 0) { + if (args[3] === 0) { args.pop(); - if (args[2] == Infinity) { + if (args[2] === Infinity) { args.pop(); - if (args[1] == -Infinity) { + if (args[1] === -Infinity) { args.pop(); } } @@ -541,7 +541,7 @@ FactoryUtils.getFieldsJson_ = function(block) { fields.push({ type: block.type, name: block.getFieldValue('FIELDNAME'), - checked: block.getFieldValue('CHECKED') == 'TRUE' + checked: block.getFieldValue('CHECKED') === 'TRUE' }); break; case 'field_colour': @@ -579,7 +579,7 @@ FactoryUtils.getFieldsJson_ = function(block) { width: Number(block.getFieldValue('WIDTH')), height: Number(block.getFieldValue('HEIGHT')), alt: block.getFieldValue('ALT'), - flipRtl: block.getFieldValue('FLIP_RTL') == 'TRUE' + flipRtl: block.getFieldValue('FLIP_RTL') === 'TRUE' }); break; } @@ -598,11 +598,11 @@ FactoryUtils.getFieldsJson_ = function(block) { */ FactoryUtils.getOptTypesFrom = function(block, name) { var types = FactoryUtils.getTypesFrom_(block, name); - if (types.length == 0) { + if (types.length === 0) { return undefined; - } else if (types.indexOf('null') != -1) { + } else if (types.indexOf('null') !== -1) { return 'null'; - } else if (types.length == 1) { + } else if (types.length === 1) { return types[0]; } else { return '[' + types.join(', ') + ']'; @@ -622,9 +622,9 @@ FactoryUtils.getTypesFrom_ = function(block, name) { var types; if (!typeBlock || typeBlock.disabled) { types = []; - } else if (typeBlock.type == 'type_other') { + } else if (typeBlock.type === 'type_other') { types = [JSON.stringify(typeBlock.getFieldValue('TYPE'))]; - } else if (typeBlock.type == 'type_group') { + } else if (typeBlock.type === 'type_group') { types = []; for (var n = 0; n < typeBlock.typeCount_; n++) { types = types.concat(FactoryUtils.getTypesFrom_(typeBlock, 'TYPE' + n)); @@ -652,7 +652,7 @@ FactoryUtils.getTypesFrom_ = function(block, name) { FactoryUtils.getRootBlock = function(workspace) { var blocks = workspace.getTopBlocks(false); for (var i = 0, block; block = blocks[i]; i++) { - if (block.type == 'factory_base') { + if (block.type === 'factory_base') { return block; } } @@ -735,7 +735,7 @@ FactoryUtils.getDefinedBlock = function(blockType, workspace) { FactoryUtils.getBlockTypeFromJsDefinition = function(blockDef) { var indexOfStartBracket = blockDef.indexOf('[\''); var indexOfEndBracket = blockDef.indexOf('\']'); - if (indexOfStartBracket != -1 && indexOfEndBracket != -1) { + if (indexOfStartBracket !== -1 && indexOfEndBracket !== -1) { return blockDef.substring(indexOfStartBracket + 2, indexOfEndBracket); } else { throw Error('Could not parse block type out of JavaScript block ' + @@ -777,9 +777,9 @@ FactoryUtils.parseJsBlockDefinitions = function(blockDefsString) { var blockDefArray = []; var defStart = blockDefsString.indexOf('Blockly.Blocks'); - while (blockDefsString.indexOf('Blockly.Blocks', defStart) != -1) { + while (blockDefsString.indexOf('Blockly.Blocks', defStart) !== -1) { var nextStart = blockDefsString.indexOf('Blockly.Blocks', defStart + 1); - if (nextStart == -1) { + if (nextStart === -1) { // This is the last block definition. nextStart = blockDefsString.length; } @@ -807,12 +807,12 @@ FactoryUtils.parseJsonBlockDefinitions = function(blockDefsString) { // are balanced. for (var i = 0; i < blockDefsString.length; i++) { var currentChar = blockDefsString[i]; - if (currentChar == '{') { + if (currentChar === '{') { unbalancedBracketCount++; } - else if (currentChar == '}') { + else if (currentChar === '}') { unbalancedBracketCount--; - if (unbalancedBracketCount == 0 && i > 0) { + if (unbalancedBracketCount === 0 && i > 0) { // The brackets are balanced. We've got a complete block definition. var blockDef = blockDefsString.substring(defStart, i + 1); blockDefArray.push(blockDef); @@ -833,7 +833,7 @@ FactoryUtils.defineAndGetBlockTypes = function(blockDefsString, format) { var blockTypes = []; // Define blocks and get block types. - if (format == 'JSON') { + if (format === 'JSON') { var blockDefArray = FactoryUtils.parseJsonBlockDefinitions(blockDefsString); // Populate array of blocktypes and define each block. @@ -848,7 +848,7 @@ FactoryUtils.defineAndGetBlockTypes = function(blockDefsString, format) { } }; } - } else if (format == 'JavaScript') { + } else if (format === 'JavaScript') { var blockDefArray = FactoryUtils.parseJsBlockDefinitions(blockDefsString); // Populate array of block types. @@ -890,8 +890,8 @@ FactoryUtils.injectCode = function(code, id) { */ FactoryUtils.sameBlockXml = function(blockXml1, blockXml2) { // Each XML element should contain a single child element with a 'block' tag - if (blockXml1.tagName.toLowerCase() != 'xml' || - blockXml2.tagName.toLowerCase() != 'xml') { + if (blockXml1.tagName.toLowerCase() !== 'xml' || + blockXml2.tagName.toLowerCase() !== 'xml') { throw Error('Expected two XML elements, received elements with tag ' + 'names: ' + blockXml1.tagName + ' and ' + blockXml2.tagName + '.'); } @@ -916,7 +916,7 @@ FactoryUtils.sameBlockXml = function(blockXml1, blockXml2) { blockXmlText2 = blockXmlText2.replace(/\s+/g, ''); // Return whether or not changes have been saved. - return blockXmlText1 == blockXmlText2; + return blockXmlText1 === blockXmlText2; }; /** @@ -982,11 +982,11 @@ FactoryUtils.hasVariableField = function(block) { */ FactoryUtils.isProcedureBlock = function(block) { return block && - (block.type == 'procedures_defnoreturn' || - block.type == 'procedures_defreturn' || - block.type == 'procedures_callnoreturn' || - block.type == 'procedures_callreturn' || - block.type == 'procedures_ifreturn'); + (block.type === 'procedures_defnoreturn' || + block.type === 'procedures_defreturn' || + block.type === 'procedures_callnoreturn' || + block.type === 'procedures_callreturn' || + block.type === 'procedures_ifreturn'); }; /** diff --git a/demos/blockfactory/index.html b/demos/blockfactory/index.html index ec4d59402..ef154942c 100644 --- a/demos/blockfactory/index.html +++ b/demos/blockfactory/index.html @@ -369,7 +369,7 @@ // Manual JavaScript works but requires use of eval(). // TODO(#1269): Replace eval() with JS-Interpreter before // re-enabling "Manual JavaScript" mode. - if (document.location.href.indexOf('file://') == 0) { + if (document.location.href.indexOf('file://') === 0) { document.write( ''); } diff --git a/demos/blockfactory/workspacefactory/wfactory_controller.js b/demos/blockfactory/workspacefactory/wfactory_controller.js index 471a007e1..67a74e8d3 100644 --- a/demos/blockfactory/workspacefactory/wfactory_controller.js +++ b/demos/blockfactory/workspacefactory/wfactory_controller.js @@ -247,7 +247,7 @@ WorkspaceFactoryController.prototype.switchElement = function(id) { Blockly.Events.disable(); // Caches information to reload or generate XML if switching to/from element. // Only saves if a category is selected. - if (this.model.getSelectedId() != null && id != null) { + if (this.model.getSelectedId() !== null && id !== null) { this.model.getSelected().saveFromWorkspace(this.toolboxWorkspace); } // Load element. @@ -263,13 +263,13 @@ WorkspaceFactoryController.prototype.switchElement = function(id) { */ WorkspaceFactoryController.prototype.clearAndLoadElement = function(id) { // Unselect current tab if switching to and from an element. - if (this.model.getSelectedId() != null && id != null) { + if (this.model.getSelectedId() !== null && id !== null) { this.view.setCategoryTabSelection(this.model.getSelectedId(), false); } // If switching to another category, set category selection in the model and // view. - if (id != null) { + if (id !== null) { // Set next category. this.model.setSelectedById(id); @@ -301,7 +301,7 @@ WorkspaceFactoryController.prototype.clearAndLoadElement = function(id) { */ WorkspaceFactoryController.prototype.exportXmlFile = function(exportMode) { // Get file name. - if (exportMode == WorkspaceFactoryController.MODE_TOOLBOX) { + if (exportMode === WorkspaceFactoryController.MODE_TOOLBOX) { var fileName = prompt('File Name for toolbox XML:', 'toolbox.xml'); } else { var fileName = prompt('File Name for pre-loaded workspace XML:', @@ -312,12 +312,12 @@ WorkspaceFactoryController.prototype.exportXmlFile = function(exportMode) { } // Generate XML. - if (exportMode == WorkspaceFactoryController.MODE_TOOLBOX) { + if (exportMode === WorkspaceFactoryController.MODE_TOOLBOX) { // Export the toolbox XML. var configXml = Blockly.Xml.domToPrettyText( this.generator.generateToolboxXml()); this.hasUnsavedToolboxChanges = false; - } else if (exportMode == WorkspaceFactoryController.MODE_PRELOAD) { + } else if (exportMode === WorkspaceFactoryController.MODE_PRELOAD) { // Export the pre-loaded block XML. var configXml = Blockly.Xml.domToPrettyText( this.generator.generateWorkspaceXml()); @@ -333,11 +333,11 @@ WorkspaceFactoryController.prototype.exportXmlFile = function(exportMode) { var data = new Blob([configXml], {type: 'text/xml'}); this.view.createAndDownloadFile(fileName, data); - if (exportMode == WorkspaceFactoryController.MODE_TOOLBOX) { + if (exportMode === WorkspaceFactoryController.MODE_TOOLBOX) { BlocklyDevTools.Analytics.onExport( BlocklyDevTools.Analytics.TOOLBOX, { format: BlocklyDevTools.Analytics.FORMAT_XML }); - } else if (exportMode == WorkspaceFactoryController.MODE_PRELOAD) { + } else if (exportMode === WorkspaceFactoryController.MODE_PRELOAD) { BlocklyDevTools.Analytics.onExport( BlocklyDevTools.Analytics.WORKSPACE_CONTENTS, { format: BlocklyDevTools.Analytics.FORMAT_XML }); @@ -402,7 +402,7 @@ WorkspaceFactoryController.prototype.updatePreview = function() { this.generator.generateToolboxXml()); // No categories, creates a simple flyout. - if (tree.getElementsByTagName('category').length == 0) { + if (tree.getElementsByTagName('category').length === 0) { // No categories, creates a simple flyout. if (this.previewWorkspace.toolbox_) { this.reinjectPreview(tree); // Switch to simple flyout, expensive. @@ -436,20 +436,20 @@ WorkspaceFactoryController.prototype.updatePreview = function() { * be called after making changes to the workspace. */ WorkspaceFactoryController.prototype.saveStateFromWorkspace = function() { - if (this.selectedMode == WorkspaceFactoryController.MODE_TOOLBOX) { + if (this.selectedMode === WorkspaceFactoryController.MODE_TOOLBOX) { // If currently editing the toolbox. // Update flags if toolbox has been changed. - if (this.model.getSelectedXml() != + if (this.model.getSelectedXml() !== Blockly.Xml.workspaceToDom(this.toolboxWorkspace)) { this.hasUnsavedToolboxChanges = true; } this.model.getSelected().saveFromWorkspace(this.toolboxWorkspace); - } else if (this.selectedMode == WorkspaceFactoryController.MODE_PRELOAD) { + } else if (this.selectedMode === WorkspaceFactoryController.MODE_PRELOAD) { // If currently editing the pre-loaded workspace. // Update flags if preloaded blocks have been changed. - if (this.model.getPreloadXml() != + if (this.model.getPreloadXml() !== Blockly.Xml.workspaceToDom(this.toolboxWorkspace)) { this.hasUnsavedPreloadChanges = true; } @@ -486,7 +486,7 @@ WorkspaceFactoryController.prototype.changeSelectedCategory = function(name, colour) { var selected = this.model.getSelected(); // Return if a category is not selected. - if (selected.type != ListElement.TYPE_CATEGORY) { + if (selected.type !== ListElement.TYPE_CATEGORY) { return; } // Change colour of selected category. @@ -571,12 +571,12 @@ WorkspaceFactoryController.prototype.loadCategoryByName = function(name) { if (!this.isStandardCategoryName(name)) { return; } - if (this.model.hasVariables() && name.toLowerCase() == 'variables') { + if (this.model.hasVariables() && name.toLowerCase() === 'variables') { alert('A Variables category already exists. You cannot create multiple' + ' variables categories.'); return; } - if (this.model.hasProcedures() && name.toLowerCase() == 'functions') { + if (this.model.hasProcedures() && name.toLowerCase() === 'functions') { alert('A Functions category already exists. You cannot create multiple' + ' functions categories.'); return; @@ -704,7 +704,7 @@ WorkspaceFactoryController.prototype.importFile = function(file, importMode) { // Print error message if fail. try { var tree = Blockly.Xml.textToDom(reader.result); - if (importMode == WorkspaceFactoryController.MODE_TOOLBOX) { + if (importMode === WorkspaceFactoryController.MODE_TOOLBOX) { // Switch mode. controller.setMode(WorkspaceFactoryController.MODE_TOOLBOX); @@ -724,7 +724,7 @@ WorkspaceFactoryController.prototype.importFile = function(file, importMode) { controller.importToolboxFromTree_(tree); BlocklyDevTools.Analytics.onImport('Toolbox.xml'); - } else if (importMode == WorkspaceFactoryController.MODE_PRELOAD) { + } else if (importMode === WorkspaceFactoryController.MODE_PRELOAD) { // Switch mode. controller.setMode(WorkspaceFactoryController.MODE_PRELOAD); @@ -772,7 +772,7 @@ WorkspaceFactoryController.prototype.importToolboxFromTree_ = function(tree) { this.model.clearToolboxList(); this.view.clearToolboxTabs(); - if (tree.getElementsByTagName('category').length == 0) { + if (tree.getElementsByTagName('category').length === 0) { // No categories present. // Load all the blocks into a single category evenly spaced. Blockly.Xml.domToWorkspace(tree, this.toolboxWorkspace); @@ -788,7 +788,7 @@ WorkspaceFactoryController.prototype.importToolboxFromTree_ = function(tree) { // Categories/separators present. for (var i = 0, item; item = tree.children[i]; i++) { - if (item.tagName == 'category') { + if (item.tagName === 'category') { // If the element is a category, create a new category and switch to it. this.createCategory(item.getAttribute('name'), false); var category = this.model.getElementByIndex(i); @@ -1016,12 +1016,12 @@ WorkspaceFactoryController.prototype.convertShadowBlocks = function() { */ WorkspaceFactoryController.prototype.setMode = function(mode) { // No work to change mode that's currently set. - if (this.selectedMode == mode) { + if (this.selectedMode === mode) { return; } // No work to change mode that's currently set. - if (this.selectedMode == mode) { + if (this.selectedMode === mode) { return; } @@ -1034,7 +1034,7 @@ WorkspaceFactoryController.prototype.setMode = function(mode) { // Update help text above workspace. this.view.updateHelpText(mode); - if (mode == WorkspaceFactoryController.MODE_TOOLBOX) { + if (mode === WorkspaceFactoryController.MODE_TOOLBOX) { // Open the toolbox editing space. this.model.savePreloadXml (Blockly.Xml.workspaceToDom(this.toolboxWorkspace)); @@ -1115,7 +1115,7 @@ WorkspaceFactoryController.prototype.readOptions_ = function() { } else { var maxBlocksValue = document.getElementById('option_maxBlocks_number').value; - optionsObj['maxBlocks'] = typeof maxBlocksValue == 'string' ? + optionsObj['maxBlocks'] = typeof maxBlocksValue === 'string' ? parseInt(maxBlocksValue) : maxBlocksValue; } optionsObj['trashcan'] = @@ -1142,10 +1142,10 @@ WorkspaceFactoryController.prototype.readOptions_ = function() { var grid = Object.create(null); var spacingValue = document.getElementById('gridOption_spacing_number').value; - grid['spacing'] = typeof spacingValue == 'string' ? + grid['spacing'] = typeof spacingValue === 'string' ? parseInt(spacingValue) : spacingValue; var lengthValue = document.getElementById('gridOption_length_number').value; - grid['length'] = typeof lengthValue == 'string' ? + grid['length'] = typeof lengthValue === 'string' ? parseInt(lengthValue) : lengthValue; grid['colour'] = document.getElementById('gridOption_colour_text').value; if (!readonly) { @@ -1164,19 +1164,19 @@ WorkspaceFactoryController.prototype.readOptions_ = function() { document.getElementById('zoomOption_wheel_checkbox').checked; var startScaleValue = document.getElementById('zoomOption_startScale_number').value; - zoom['startScale'] = typeof startScaleValue == 'string' ? + zoom['startScale'] = typeof startScaleValue === 'string' ? Number(startScaleValue) : startScaleValue; var maxScaleValue = document.getElementById('zoomOption_maxScale_number').value; - zoom['maxScale'] = typeof maxScaleValue == 'string' ? + zoom['maxScale'] = typeof maxScaleValue === 'string' ? Number(maxScaleValue) : maxScaleValue; var minScaleValue = document.getElementById('zoomOption_minScale_number').value; - zoom['minScale'] = typeof minScaleValue == 'string' ? + zoom['minScale'] = typeof minScaleValue === 'string' ? Number(minScaleValue) : minScaleValue; var scaleSpeedValue = document.getElementById('zoomOption_scaleSpeed_number').value; - zoom['scaleSpeed'] = typeof scaleSpeedValue == 'string' ? + zoom['scaleSpeed'] = typeof scaleSpeedValue === 'string' ? Number(scaleSpeedValue) : scaleSpeedValue; optionsObj['zoom'] = zoom; } @@ -1235,7 +1235,7 @@ WorkspaceFactoryController.prototype.importBlocks = function(file, format) { (Blockly.Xml.workspaceToDom(controller.toolboxWorkspace)); BlocklyDevTools.Analytics.onImport('BlockDefinitions' + - (format == 'JSON' ? '.json' : '.js')); + (format === 'JSON' ? '.json' : '.js')); } catch (e) { msg = 'Cannot read blocks from file.'; alert(msg); diff --git a/demos/blockfactory/workspacefactory/wfactory_generator.js b/demos/blockfactory/workspacefactory/wfactory_generator.js index 0e583657c..312e51029 100644 --- a/demos/blockfactory/workspacefactory/wfactory_generator.js +++ b/demos/blockfactory/workspacefactory/wfactory_generator.js @@ -55,7 +55,7 @@ WorkspaceFactoryGenerator.prototype.generateToolboxXml = function() { this.appendHiddenWorkspaceToDom_(xmlDom); } else { // Toolbox has categories. - // Assert that selected != null + // Assert that selected !== null if (!this.model.getSelected()) { throw Error('Selected is null when the toolbox is empty.'); } @@ -69,19 +69,19 @@ WorkspaceFactoryGenerator.prototype.generateToolboxXml = function() { // groups in the flyout. for (var i = 0; i < toolboxList.length; i++) { var element = toolboxList[i]; - if (element.type == ListElement.TYPE_SEPARATOR) { + if (element.type === ListElement.TYPE_SEPARATOR) { // If the next element is a separator. var nextElement = Blockly.utils.xml.createElement('sep'); - } else if (element.type == ListElement.TYPE_CATEGORY) { + } else if (element.type === ListElement.TYPE_CATEGORY) { // If the next element is a category. var nextElement = Blockly.utils.xml.createElement('category'); nextElement.setAttribute('name', element.name); // Add a colour attribute if one exists. - if (element.colour != null) { + if (element.colour !== null) { nextElement.setAttribute('colour', element.colour); } // Add a custom attribute if one exists. - if (element.custom != null) { + if (element.custom !== null) { nextElement.setAttribute('custom', element.custom); } // Load that category to hidden workspace, setting user-generated shadow @@ -129,10 +129,10 @@ WorkspaceFactoryGenerator.prototype.generateInjectString = function() { } var str = ''; for (var key in obj) { - if (key == 'grid' || key == 'zoom') { + if (key === 'grid' || key === 'zoom') { var temp = tabChar + key + ' : {\n' + addAttributes(obj[key], tabChar + '\t') + tabChar + '}, \n'; - } else if (typeof obj[key] == 'string') { + } else if (typeof obj[key] === 'string') { var temp = tabChar + key + ' : \'' + obj[key] + '\', \n'; } else { var temp = tabChar + key + ' : ' + obj[key] + ', \n'; diff --git a/demos/blockfactory/workspacefactory/wfactory_init.js b/demos/blockfactory/workspacefactory/wfactory_init.js index 4c2fd6536..3d95e3ad6 100644 --- a/demos/blockfactory/workspacefactory/wfactory_init.js +++ b/demos/blockfactory/workspacefactory/wfactory_init.js @@ -61,7 +61,7 @@ WorkspaceFactoryInit.initColourPicker_ = function(controller) { var row = []; for (var i = 0; i < colours.length; i++) { row.push(colours[i]); - if (row.length == maxCols) { + if (row.length === maxCols) { grid.push(row); row = []; } @@ -235,7 +235,7 @@ WorkspaceFactoryInit.assignWorkspaceFactoryClickHandlers_ = function() { var selected = controller.model.getSelected(); // Return if a category is not selected. - if (selected.type != ListElement.TYPE_CATEGORY) { + if (selected.type !== ListElement.TYPE_CATEGORY) { return; } document.getElementById('categoryName').value = selected.name; @@ -304,14 +304,14 @@ WorkspaceFactoryInit.addWorkspaceFactoryEventListeners_ = function(controller) { // Don't let arrow keys have any effect if not in Workspace Factory // editing the toolbox. if (!(controller.keyEventsEnabled && controller.selectedMode - == WorkspaceFactoryController.MODE_TOOLBOX)) { + === WorkspaceFactoryController.MODE_TOOLBOX)) { return; } - if (e.keyCode == 38) { + if (e.keyCode === 38) { // Arrow up. controller.moveElement(-1); - } else if (e.keyCode == 40) { + } else if (e.keyCode === 40) { // Arrow down. controller.moveElement(1); } @@ -334,9 +334,9 @@ WorkspaceFactoryInit.addWorkspaceFactoryEventListeners_ = function(controller) { // Not listening for Blockly create events because causes the user to drop // blocks when dragging them into workspace. Could cause problems if ever // load blocks into workspace directly without calling updatePreview. - if (e.type == Blockly.Events.BLOCK_MOVE || - e.type == Blockly.Events.BLOCK_DELETE || - e.type == Blockly.Events.BLOCK_CHANGE) { + if (e.type === Blockly.Events.BLOCK_MOVE || + e.type === Blockly.Events.BLOCK_DELETE || + e.type === Blockly.Events.BLOCK_CHANGE) { controller.saveStateFromWorkspace(); controller.updatePreview(); } @@ -345,8 +345,8 @@ WorkspaceFactoryInit.addWorkspaceFactoryEventListeners_ = function(controller) { // Only enable "Edit Block" when a block is selected and it has a // surrounding parent, meaning it is nested in another block (blocks that // are not nested in parents cannot be shadow blocks). - if (e.type == Blockly.Events.BLOCK_MOVE || - e.type == Blockly.Events.SELECTED) { + if (e.type === Blockly.Events.BLOCK_MOVE || + e.type === Blockly.Events.SELECTED) { var selected = Blockly.common.getSelected(); // Show shadow button if a block is selected. Show "Add Shadow" if @@ -361,7 +361,7 @@ WorkspaceFactoryInit.addWorkspaceFactoryEventListeners_ = function(controller) { WorkspaceFactoryInit.displayRemoveShadow_(false); } - if (selected != null && selected.getSurroundParent() != null && + if (selected !== null && selected.getSurroundParent() !== null && !controller.isUserGenShadowBlock(selected.getSurroundParent().id)) { // Selected block is a valid shadow block or could be a valid shadow // block. @@ -378,7 +378,7 @@ WorkspaceFactoryInit.addWorkspaceFactoryEventListeners_ = function(controller) { } else { // Selected block cannot be a valid shadow block. - if (selected != null && isInvalidBlockPlacement(selected)) { + if (selected !== null && isInvalidBlockPlacement(selected)) { // Selected block breaks shadow block rules. // Invalid shadow block if (1) a shadow block no longer has a valid // parent, or (2) a normal block is inside of a shadow block. @@ -403,7 +403,7 @@ WorkspaceFactoryInit.addWorkspaceFactoryEventListeners_ = function(controller) { // be a shadow block. // Remove possible 'invalid shadow block placement' warning. - if (selected != null && controller.isDefinedBlock(selected) && + if (selected !== null && controller.isDefinedBlock(selected) && (!FactoryUtils.hasVariableField(selected) || !controller.isUserGenShadowBlock(selected.id))) { selected.setWarningText(null); @@ -419,7 +419,7 @@ WorkspaceFactoryInit.addWorkspaceFactoryEventListeners_ = function(controller) { // Convert actual shadow blocks added from the toolbox to user-generated // shadow blocks. - if (e.type == Blockly.Events.BLOCK_CREATE) { + if (e.type === Blockly.Events.BLOCK_CREATE) { controller.convertShadowBlocks(); // Let the user create a Variables or Functions category if they use diff --git a/demos/blockfactory/workspacefactory/wfactory_model.js b/demos/blockfactory/workspacefactory/wfactory_model.js index c97e8d091..44986a94f 100644 --- a/demos/blockfactory/workspacefactory/wfactory_model.js +++ b/demos/blockfactory/workspacefactory/wfactory_model.js @@ -54,8 +54,8 @@ WorkspaceFactoryModel = function() { */ WorkspaceFactoryModel.prototype.hasCategoryByName = function(name) { for (var i = 0; i < this.toolboxList.length; i++) { - if (this.toolboxList[i].type == ListElement.TYPE_CATEGORY && - this.toolboxList[i].name == name) { + if (this.toolboxList[i].type === ListElement.TYPE_CATEGORY && + this.toolboxList[i].name === name) { return true; } } @@ -95,9 +95,9 @@ WorkspaceFactoryModel.prototype.hasElements = function() { */ WorkspaceFactoryModel.prototype.addElementToList = function(element) { // Update state if the copied category has a custom tag. - this.hasVariableCategory = element.custom == 'VARIABLE' ? true : + this.hasVariableCategory = element.custom === 'VARIABLE' ? true : this.hasVariableCategory; - this.hasProcedureCategory = element.custom == 'PROCEDURE' ? true : + this.hasProcedureCategory = element.custom === 'PROCEDURE' ? true : this.hasProcedureCategory; // Add element to toolboxList. this.toolboxList.push(element); @@ -115,9 +115,9 @@ WorkspaceFactoryModel.prototype.deleteElementFromList = function(index) { return; // No entry to delete. } // Check if need to update flags. - this.hasVariableCategory = this.toolboxList[index].custom == 'VARIABLE' ? + this.hasVariableCategory = this.toolboxList[index].custom === 'VARIABLE' ? false : this.hasVariableCategory; - this.hasProcedureCategory = this.toolboxList[index].custom == 'PROCEDURE' ? + this.hasProcedureCategory = this.toolboxList[index].custom === 'PROCEDURE' ? false : this.hasProcedureCategory; // Remove element. this.toolboxList.splice(index, 1); @@ -130,7 +130,7 @@ WorkspaceFactoryModel.prototype.deleteElementFromList = function(index) { * of blocks displayed. */ WorkspaceFactoryModel.prototype.createDefaultSelectedIfEmpty = function() { - if (this.toolboxList.length == 0) { + if (this.toolboxList.length === 0) { this.flyout = new ListElement(ListElement.TYPE_FLYOUT); this.selected = this.flyout; } @@ -158,7 +158,7 @@ WorkspaceFactoryModel.prototype.moveElementToIndex = function(element, newIndex, /** * Returns the ID of the currently selected element. Returns null if there are - * no categories (if selected == null). + * no categories (if selected === null). * @return {string} The ID of the element currently selected. */ WorkspaceFactoryModel.prototype.getSelectedId = function() { @@ -167,7 +167,7 @@ WorkspaceFactoryModel.prototype.getSelectedId = function() { /** * Returns the name of the currently selected category. Returns null if there - * are no categories (if selected == null) or the selected element is not + * are no categories (if selected === null) or the selected element is not * a category (in which case its name is null). * @return {string} The name of the category currently selected. */ @@ -200,7 +200,7 @@ WorkspaceFactoryModel.prototype.setSelectedById = function(id) { */ WorkspaceFactoryModel.prototype.getIndexByElementId = function(id) { for (var i = 0; i < this.toolboxList.length; i++) { - if (this.toolboxList[i].id == id) { + if (this.toolboxList[i].id === id) { return i; } } @@ -215,7 +215,7 @@ WorkspaceFactoryModel.prototype.getIndexByElementId = function(id) { */ WorkspaceFactoryModel.prototype.getElementById = function(id) { for (var i = 0; i < this.toolboxList.length; i++) { - if (this.toolboxList[i].id == id) { + if (this.toolboxList[i].id === id) { return this.toolboxList[i]; } } @@ -259,7 +259,7 @@ WorkspaceFactoryModel.prototype.getToolboxList = function() { */ WorkspaceFactoryModel.prototype.getCategoryIdByName = function(name) { for (var i = 0; i < this.toolboxList.length; i++) { - if (this.toolboxList[i].name == name) { + if (this.toolboxList[i].name === name) { return this.toolboxList[i].id; } } @@ -293,7 +293,7 @@ WorkspaceFactoryModel.prototype.addShadowBlock = function(blockId) { */ WorkspaceFactoryModel.prototype.removeShadowBlock = function(blockId) { for (var i = 0; i < this.shadowBlocks.length; i++) { - if (this.shadowBlocks[i] == blockId) { + if (this.shadowBlocks[i] === blockId) { this.shadowBlocks.splice(i, 1); return; } @@ -308,7 +308,7 @@ WorkspaceFactoryModel.prototype.removeShadowBlock = function(blockId) { */ WorkspaceFactoryModel.prototype.isShadowBlock = function(blockId) { for (var i = 0; i < this.shadowBlocks.length; i++) { - if (this.shadowBlocks[i] == blockId) { + if (this.shadowBlocks[i] === blockId) { return true; } } @@ -341,14 +341,14 @@ WorkspaceFactoryModel.prototype.getShadowBlocksInWorkspace = */ WorkspaceFactoryModel.prototype.addCustomTag = function(category, tag) { // Only update list elements that are categories. - if (category.type != ListElement.TYPE_CATEGORY) { + if (category.type !== ListElement.TYPE_CATEGORY) { return; } // Only update the tag to be 'VARIABLE' or 'PROCEDURE'. - if (tag == 'VARIABLE') { + if (tag === 'VARIABLE') { this.hasVariableCategory = true; category.custom = 'VARIABLE'; - } else if (tag == 'PROCEDURE') { + } else if (tag === 'PROCEDURE') { this.hasProcedureCategory = true; category.custom = 'PROCEDURE'; } @@ -397,7 +397,7 @@ WorkspaceFactoryModel.prototype.getAllUsedBlockTypes = function() { // Add block types if not already in list. for (var i = 0; i < blocks.length; i++) { var type = blocks[i].getAttribute('type'); - if (list.indexOf(type) == -1) { + if (list.indexOf(type) === -1) { list.push(type); } } @@ -410,7 +410,7 @@ WorkspaceFactoryModel.prototype.getAllUsedBlockTypes = function() { // If has categories, add block types for each category. for (var i = 0, category; category = this.toolboxList[i]; i++) { - if (category.type == ListElement.TYPE_CATEGORY) { + if (category.type === ListElement.TYPE_CATEGORY) { pushBlockTypesToList(category.xml, blockTypeList); } } @@ -446,9 +446,9 @@ WorkspaceFactoryModel.prototype.updateLibBlockTypes = function(blockTypes) { */ WorkspaceFactoryModel.prototype.isDefinedBlockType = function(blockType) { var isStandardBlock = - StandardCategories.coreBlockTypes.indexOf(blockType) != -1; - var isLibBlock = this.libBlockTypes.indexOf(blockType) != -1; - var isImportedBlock = this.importedBlockTypes.indexOf(blockType) != -1; + StandardCategories.coreBlockTypes.indexOf(blockType) !== -1; + var isLibBlock = this.libBlockTypes.indexOf(blockType) !== -1; + var isImportedBlock = this.importedBlockTypes.indexOf(blockType) !== -1; return (isStandardBlock || isLibBlock || isImportedBlock); }; @@ -498,8 +498,8 @@ ListElement.TYPE_FLYOUT = 'flyout'; */ ListElement.prototype.saveFromWorkspace = function(workspace) { // Only save XML for categories and flyouts. - if (this.type == ListElement.TYPE_FLYOUT || - this.type == ListElement.TYPE_CATEGORY) { + if (this.type === ListElement.TYPE_FLYOUT || + this.type === ListElement.TYPE_CATEGORY) { this.xml = Blockly.Xml.workspaceToDom(workspace); } }; @@ -512,7 +512,7 @@ ListElement.prototype.saveFromWorkspace = function(workspace) { */ ListElement.prototype.changeName = function(name) { // Only update list elements that are categories. - if (this.type != ListElement.TYPE_CATEGORY) { + if (this.type !== ListElement.TYPE_CATEGORY) { return; } this.name = name; @@ -525,7 +525,7 @@ ListElement.prototype.changeName = function(name) { * or null if none. */ ListElement.prototype.changeColour = function(colour) { - if (this.type != ListElement.TYPE_CATEGORY) { + if (this.type !== ListElement.TYPE_CATEGORY) { return; } this.colour = colour; diff --git a/demos/blockfactory/workspacefactory/wfactory_view.js b/demos/blockfactory/workspacefactory/wfactory_view.js index cf1681e58..e97b2d056 100644 --- a/demos/blockfactory/workspacefactory/wfactory_view.js +++ b/demos/blockfactory/workspacefactory/wfactory_view.js @@ -35,7 +35,7 @@ WorkspaceFactoryView.prototype.addCategoryRow = function(name, id) { var count = table.rows.length; // Delete help label and enable category buttons if it's the first category. - if (count == 0) { + if (count === 0) { document.getElementById('categoryHeader').textContent = 'Your categories:'; } @@ -95,7 +95,7 @@ WorkspaceFactoryView.prototype.addEmptyCategoryMessage = function() { WorkspaceFactoryView.prototype.updateState = function(selectedIndex, selected) { // Disable/enable editing buttons as necessary. document.getElementById('button_editCategory').disabled = selectedIndex < 0 || - selected.type != ListElement.TYPE_CATEGORY; + selected.type !== ListElement.TYPE_CATEGORY; document.getElementById('button_remove').disabled = selectedIndex < 0; document.getElementById('button_up').disabled = selectedIndex <= 0; var table = document.getElementById('categoryTable'); @@ -135,7 +135,7 @@ WorkspaceFactoryView.prototype.setCategoryTabSelection = * @param {!Function} func Function to be executed on click. */ WorkspaceFactoryView.prototype.bindClick = function(el, func) { - if (typeof el == 'string') { + if (typeof el === 'string') { el = document.getElementById(el); } el.addEventListener('click', func, true); @@ -233,7 +233,7 @@ WorkspaceFactoryView.prototype.addSeparatorTab = function(id) { var table = document.getElementById('categoryTable'); var count = table.rows.length; - if (count == 0) { + if (count === 0) { document.getElementById('categoryHeader').textContent = 'Your categories:'; } // Create separator. @@ -271,9 +271,9 @@ WorkspaceFactoryView.prototype.disableWorkspace = function(disable) { * @return {boolean} True if the workspace should be disabled, false otherwise. */ WorkspaceFactoryView.prototype.shouldDisableWorkspace = function(category) { - return category != null && category.type != ListElement.TYPE_FLYOUT && - (category.type == ListElement.TYPE_SEPARATOR || - category.custom == 'VARIABLE' || category.custom == 'PROCEDURE'); + return category !== null && category.type !== ListElement.TYPE_FLYOUT && + (category.type === ListElement.TYPE_SEPARATOR || + category.custom === 'VARIABLE' || category.custom === 'PROCEDURE'); }; /** @@ -340,13 +340,13 @@ WorkspaceFactoryView.prototype.unmarkShadowBlock = function(block) { * (WorkspaceFactoryController.MODE_TOOLBOX or WorkspaceFactoryController.MODE_PRELOAD). */ WorkspaceFactoryView.prototype.setModeSelection = function(mode) { - document.getElementById('tab_preload').className = mode == + document.getElementById('tab_preload').className = mode === WorkspaceFactoryController.MODE_PRELOAD ? 'tabon' : 'taboff'; - document.getElementById('preload_div').style.display = mode == + document.getElementById('preload_div').style.display = mode === WorkspaceFactoryController.MODE_PRELOAD ? 'block' : 'none'; - document.getElementById('tab_toolbox').className = mode == + document.getElementById('tab_toolbox').className = mode === WorkspaceFactoryController.MODE_TOOLBOX ? 'tabon' : 'taboff'; - document.getElementById('toolbox_div').style.display = mode == + document.getElementById('toolbox_div').style.display = mode === WorkspaceFactoryController.MODE_TOOLBOX ? 'block' : 'none'; }; @@ -356,7 +356,7 @@ WorkspaceFactoryView.prototype.setModeSelection = function(mode) { * WorkspaceFactoryController.MODE_PRELOAD). */ WorkspaceFactoryView.prototype.updateHelpText = function(mode) { - if (mode == WorkspaceFactoryController.MODE_TOOLBOX) { + if (mode === WorkspaceFactoryController.MODE_TOOLBOX) { var helpText = 'Drag blocks into the workspace to configure the toolbox ' + 'in your custom workspace.'; } else { diff --git a/demos/blockfactory_old/blocks.js b/demos/blockfactory_old/blocks.js index 467eca2af..369f6e58d 100644 --- a/demos/blockfactory_old/blocks.js +++ b/demos/blockfactory_old/blocks.js @@ -87,21 +87,21 @@ Blockly.Blocks['factory_base'] = { var outputExists = this.getInput('OUTPUTTYPE'); var topExists = this.getInput('TOPTYPE'); var bottomExists = this.getInput('BOTTOMTYPE'); - if (option == 'LEFT') { + if (option === 'LEFT') { if (!outputExists) { this.addTypeInput_('OUTPUTTYPE', 'output type'); } } else if (outputExists) { this.removeInput('OUTPUTTYPE'); } - if (option == 'TOP' || option == 'BOTH') { + if (option === 'TOP' || option === 'BOTH') { if (!topExists) { this.addTypeInput_('TOPTYPE', 'top type'); } } else if (topExists) { this.removeInput('TOPTYPE'); } - if (option == 'BOTTOM' || option == 'BOTH') { + if (option === 'BOTTOM' || option === 'BOTH') { if (!bottomExists) { this.addTypeInput_('BOTTOMTYPE', 'bottom type'); } @@ -530,7 +530,7 @@ Blockly.Blocks['type_group'] = { for (var i = 0; i < this.typeCount_; i++) { var input = this.appendValueInput('TYPE' + i) .setCheck('Type'); - if (i == 0) { + if (i === 0) { input.appendField('any of'); } } @@ -561,7 +561,7 @@ Blockly.Blocks['type_group'] = { // Disconnect any children that don't belong. for (var i = 0; i < this.typeCount_; i++) { var connection = this.getInput('TYPE' + i).connection.targetConnection; - if (connection && connections.indexOf(connection) == -1) { + if (connection && connections.indexOf(connection) === -1) { connection.disconnect(); } } @@ -590,7 +590,7 @@ Blockly.Blocks['type_group'] = { for (var i = 0; i < this.typeCount_; i++) { if (!this.getInput('TYPE' + i)) { var input = this.appendValueInput('TYPE' + i); - if (i == 0) { + if (i === 0) { input.appendField('any of'); } } @@ -760,7 +760,7 @@ function fieldNameCheck(referenceBlock) { for (var i = 0, block; block = blocks[i]; i++) { var otherName = block.getFieldValue('FIELDNAME'); if (!block.disabled && !block.getInheritedDisabled() && - otherName && otherName.toLowerCase() == name) { + otherName && otherName.toLowerCase() === name) { count++; } } @@ -785,7 +785,7 @@ function inputNameCheck(referenceBlock) { for (var i = 0, block; block = blocks[i]; i++) { var otherName = block.getFieldValue('INPUTNAME'); if (!block.disabled && !block.getInheritedDisabled() && - otherName && otherName.toLowerCase() == name) { + otherName && otherName.toLowerCase() === name) { count++; } } diff --git a/demos/blockfactory_old/factory.js b/demos/blockfactory_old/factory.js index 6486bc4f2..90c65507e 100644 --- a/demos/blockfactory_old/factory.js +++ b/demos/blockfactory_old/factory.js @@ -34,7 +34,7 @@ function formatChange() { var mask = document.getElementById('blocklyMask'); var languagePre = document.getElementById('languagePre'); var languageTA = document.getElementById('languageTA'); - if (document.getElementById('format').value == 'Manual') { + if (document.getElementById('format').value === 'Manual') { Blockly.common.getMainWorkspace().hideChaff(); mask.style.display = 'block'; languagePre.style.display = 'none'; @@ -97,7 +97,7 @@ function formatJson_(blockType, rootBlock) { if (!contentsBlock.disabled && !contentsBlock.getInheritedDisabled()) { var fields = getFieldsJson_(contentsBlock.getInputTargetBlock('FIELDS')); for (var i = 0; i < fields.length; i++) { - if (typeof fields[i] == 'string') { + if (typeof fields[i] === 'string') { message.push(fields[i].replace(/%/g, '%%')); } else { args.push(fields[i]); @@ -107,7 +107,7 @@ function formatJson_(blockType, rootBlock) { var input = {type: contentsBlock.type}; // Dummy inputs don't have names. Other inputs do. - if (contentsBlock.type != 'input_dummy') { + if (contentsBlock.type !== 'input_dummy') { input.name = contentsBlock.getFieldValue('INPUTNAME'); } var check = JSON.parse(getOptTypesFrom(contentsBlock, 'TYPE') || 'null'); @@ -115,7 +115,7 @@ function formatJson_(blockType, rootBlock) { input.check = check; } var align = contentsBlock.getFieldValue('ALIGN'); - if (align != 'LEFT') { + if (align !== 'LEFT') { input.align = align; } args.push(input); @@ -126,11 +126,11 @@ function formatJson_(blockType, rootBlock) { contentsBlock.nextConnection.targetBlock(); } // Remove last input if dummy and not empty. - if (lastInput && lastInput.type == 'input_dummy') { + if (lastInput && lastInput.type === 'input_dummy') { var fields = lastInput.getInputTargetBlock('FIELDS'); - if (fields && getFieldsJson_(fields).join('').trim() != '') { + if (fields && getFieldsJson_(fields).join('').trim() !== '') { var align = lastInput.getFieldValue('ALIGN'); - if (align != 'LEFT') { + if (align !== 'LEFT') { JS.lastDummyAlign0 = align; } args.pop(); @@ -142,9 +142,9 @@ function formatJson_(blockType, rootBlock) { JS.args0 = args; } // Generate inline/external switch. - if (rootBlock.getFieldValue('INLINE') == 'EXT') { + if (rootBlock.getFieldValue('INLINE') === 'EXT') { JS.inputsInline = false; - } else if (rootBlock.getFieldValue('INLINE') == 'INT') { + } else if (rootBlock.getFieldValue('INLINE') === 'INT') { JS.inputsInline = true; } // Generate output, or next/previous connections. @@ -199,7 +199,7 @@ function formatJavaScript_(blockType, rootBlock) { if (!contentsBlock.disabled && !contentsBlock.getInheritedDisabled()) { var name = ''; // Dummy inputs don't have names. Other inputs do. - if (contentsBlock.type != 'input_dummy') { + if (contentsBlock.type !== 'input_dummy') { name = escapeString(contentsBlock.getFieldValue('INPUTNAME')); } code.push(' this.' + TYPES[contentsBlock.type] + '(' + name + ')'); @@ -208,7 +208,7 @@ function formatJavaScript_(blockType, rootBlock) { code.push(' .setCheck(' + check + ')'); } var align = contentsBlock.getFieldValue('ALIGN'); - if (align != 'LEFT') { + if (align !== 'LEFT') { code.push(' .setAlign(Blockly.ALIGN_' + align + ')'); } var fields = getFieldsJs_(contentsBlock.getInputTargetBlock('FIELDS')); @@ -222,9 +222,9 @@ function formatJavaScript_(blockType, rootBlock) { contentsBlock.nextConnection.targetBlock(); } // Generate inline/external switch. - if (rootBlock.getFieldValue('INLINE') == 'EXT') { + if (rootBlock.getFieldValue('INLINE') === 'EXT') { code.push(' this.setInputsInline(false);'); - } else if (rootBlock.getFieldValue('INLINE') == 'INT') { + } else if (rootBlock.getFieldValue('INLINE') === 'INT') { code.push(' this.setInputsInline(true);'); } // Generate output, or next/previous connections. @@ -305,11 +305,11 @@ function getFieldsJs_(block) { Number(block.getFieldValue('PRECISION')) ]; // Remove any trailing arguments that aren't needed. - if (args[3] == 0) { + if (args[3] === 0) { args.pop(); - if (args[2] == Infinity) { + if (args[2] === Infinity) { args.pop(); - if (args[1] == -Infinity) { + if (args[1] === -Infinity) { args.pop(); } } @@ -424,7 +424,7 @@ function getFieldsJson_(block) { fields.push({ type: block.type, name: block.getFieldValue('FIELDNAME'), - checked: block.getFieldValue('CHECKED') == 'TRUE' + checked: block.getFieldValue('CHECKED') === 'TRUE' }); break; case 'field_colour': @@ -489,11 +489,11 @@ function escapeString(string) { */ function getOptTypesFrom(block, name) { var types = getTypesFrom_(block, name); - if (types.length == 0) { + if (types.length === 0) { return undefined; - } else if (types.indexOf('null') != -1) { + } else if (types.indexOf('null') !== -1) { return 'null'; - } else if (types.length == 1) { + } else if (types.length === 1) { return types[0]; } else { return '[' + types.join(', ') + ']'; @@ -512,9 +512,9 @@ function getTypesFrom_(block, name) { var types; if (!typeBlock || typeBlock.disabled) { types = []; - } else if (typeBlock.type == 'type_other') { + } else if (typeBlock.type === 'type_other') { types = [escapeString(typeBlock.getFieldValue('TYPE'))]; - } else if (typeBlock.type == 'type_group') { + } else if (typeBlock.type === 'type_group') { types = []; for (var i = 0; i < typeBlock.typeCount_; i++) { types = types.concat(getTypesFrom_(typeBlock, 'TYPE' + i)); @@ -569,7 +569,7 @@ function updateGenerator(block) { " = block.getFieldValue('" + name + "');"); } else if (field instanceof Blockly.FieldCheckbox) { code.push(makeVar('checkbox', name) + - " = block.getFieldValue('" + name + "') == 'TRUE';"); + " = block.getFieldValue('" + name + "') === 'TRUE';"); } else if (field instanceof Blockly.FieldDropdown) { code.push(makeVar('dropdown', name) + " = block.getFieldValue('" + name + "');"); @@ -583,11 +583,11 @@ function updateGenerator(block) { } var name = input.name; if (name) { - if (input.type == Blockly.INPUT_VALUE) { + if (input.type === Blockly.INPUT_VALUE) { code.push(makeVar('value', name) + " = Blockly." + language + ".valueToCode(block, '" + name + "', Blockly." + language + ".ORDER_ATOMIC);"); - } else if (input.type == Blockly.NEXT_STATEMENT) { + } else if (input.type === Blockly.NEXT_STATEMENT) { code.push(makeVar('statements', name) + " = Blockly." + language + ".statementToCode(block, '" + name + "');"); @@ -626,11 +626,11 @@ var oldDir = null; function updatePreview() { // Toggle between LTR/RTL if needed (also used in first display). var newDir = document.getElementById('direction').value; - if (oldDir != newDir) { + if (oldDir !== newDir) { if (previewWorkspace) { previewWorkspace.dispose(); } - var rtl = newDir == 'rtl'; + var rtl = newDir === 'rtl'; previewWorkspace = Blockly.inject('preview', {rtl: rtl, media: '../../media/', @@ -641,7 +641,7 @@ function updatePreview() { // Fetch the code and determine its format (JSON or JavaScript). var format = document.getElementById('format').value; - if (format == 'Manual') { + if (format === 'Manual') { var code = document.getElementById('languageTA').value; // If the code is JSON, it will parse, otherwise treat as JS. try { @@ -668,14 +668,14 @@ function updatePreview() { Blockly.Blocks[prop] = backupBlocks[prop]; } - if (format == 'JSON') { + if (format === 'JSON') { var json = JSON.parse(code); Blockly.Blocks[json.type || UNNAMED] = { init: function() { this.jsonInit(json); } }; - } else if (format == 'JavaScript') { + } else if (format === 'JavaScript') { eval(code); } else { throw 'Unknown format: ' + format; @@ -684,8 +684,8 @@ function updatePreview() { // Look for a block on Blockly.Blocks that does not match the backup. var blockType = null; for (var type in Blockly.Blocks) { - if (typeof Blockly.Blocks[type].init == 'function' && - Blockly.Blocks[type] != backupBlocks[type]) { + if (typeof Blockly.Blocks[type].init === 'function' && + Blockly.Blocks[type] !== backupBlocks[type]) { blockType = type; break; } @@ -730,7 +730,7 @@ function injectCode(code, id) { function getRootBlock() { var blocks = mainWorkspace.getTopBlocks(false); for (var i = 0, block; block = blocks[i]; i++) { - if (block.type == 'factory_base') { + if (block.type === 'factory_base') { return block; } } @@ -742,7 +742,7 @@ function getRootBlock() { */ function disableEnableLink() { var linkButton = document.getElementById('linkButton'); - linkButton.disabled = document.getElementById('format').value == 'Manual'; + linkButton.disabled = document.getElementById('format').value === 'Manual'; } /** diff --git a/demos/code/code.js b/demos/code/code.js index 399893719..254fdb78e 100644 --- a/demos/code/code.js +++ b/demos/code/code.js @@ -107,7 +107,7 @@ Code.getLang = function() { * @return {boolean} True if RTL, false if LTR. */ Code.isRtl = function() { - return Code.LANGUAGE_RTL.indexOf(Code.LANG) != -1; + return Code.LANGUAGE_RTL.indexOf(Code.LANG) !== -1; }; /** @@ -185,7 +185,7 @@ Code.changeCodingLanguage = function() { * @param {!Function} func Event handler to bind. */ Code.bindClick = function(el, func) { - if (typeof el == 'string') { + if (typeof el === 'string') { el = document.getElementById(el); } el.addEventListener('click', func, true); @@ -322,7 +322,7 @@ Code.tabClick = function(clickedName) { Code.renderContent(); // The code menu tab is on if the blocks tab is off. var codeMenuTab = document.getElementById('tab_code'); - if (clickedName == 'blocks') { + if (clickedName === 'blocks') { Code.workspace.setVisible(true); codeMenuTab.className = 'taboff'; } else { @@ -331,7 +331,7 @@ Code.tabClick = function(clickedName) { // Sync the menu's value with the clicked tab value if needed. var codeMenu = document.getElementById('code_menu'); for (var i = 0; i < codeMenu.options.length; i++) { - if (codeMenu.options[i].value == clickedName) { + if (codeMenu.options[i].value === clickedName) { codeMenu.selectedIndex = i; break; } @@ -345,29 +345,29 @@ Code.tabClick = function(clickedName) { Code.renderContent = function() { var content = document.getElementById('content_' + Code.selected); // Initialize the pane. - if (content.id == 'content_xml') { + if (content.id === 'content_xml') { var xmlTextarea = document.getElementById('content_xml'); var xmlDom = Blockly.Xml.workspaceToDom(Code.workspace); var xmlText = Blockly.Xml.domToPrettyText(xmlDom); xmlTextarea.value = xmlText; xmlTextarea.focus(); - } else if (content.id == 'content_json') { + } else if (content.id === 'content_json') { var jsonTextarea = document.getElementById('content_json'); jsonTextarea.value = JSON.stringify( Blockly.serialization.workspaces.save(Code.workspace), null, 2); jsonTextarea.focus(); - } else if (content.id == 'content_javascript') { + } else if (content.id === 'content_javascript') { Code.attemptCodeGeneration(Blockly.JavaScript); - } else if (content.id == 'content_python') { + } else if (content.id === 'content_python') { Code.attemptCodeGeneration(Blockly.Python); - } else if (content.id == 'content_php') { + } else if (content.id === 'content_php') { Code.attemptCodeGeneration(Blockly.PHP); - } else if (content.id == 'content_dart') { + } else if (content.id === 'content_dart') { Code.attemptCodeGeneration(Blockly.Dart); - } else if (content.id == 'content_lua') { + } else if (content.id === 'content_lua') { Code.attemptCodeGeneration(Blockly.Lua); } - if (typeof PR == 'object') { + if (typeof PR === 'object') { PR.prettyPrint(); } }; @@ -397,13 +397,13 @@ Code.checkAllGeneratorFunctionsDefined = function(generator) { for (var i = 0; i < blocks.length; i++) { var blockType = blocks[i].type; if (!generator[blockType]) { - if (missingBlockGenerators.indexOf(blockType) == -1) { + if (missingBlockGenerators.indexOf(blockType) === -1) { missingBlockGenerators.push(blockType); } } } - var valid = missingBlockGenerators.length == 0; + var valid = missingBlockGenerators.length === 0; if (!valid) { var msg = 'The generator code for the following blocks not specified for ' + generator.name_ + ':\n - ' + missingBlockGenerators.join('\n - '); @@ -451,7 +451,7 @@ Code.init = function() { // TODO: Clean up the message files so this is done explicitly instead of // through this for-loop. for (var messageKey in MSG) { - if (messageKey.indexOf('cat') == 0) { + if (messageKey.indexOf('cat') === 0) { Blockly.Msg[messageKey.toUpperCase()] = MSG[messageKey]; } } @@ -553,7 +553,7 @@ Code.initLanguage = function() { var tuple = languages[i]; var lang = tuple[tuple.length - 1]; var option = new Option(tuple[0], lang); - if (lang == Code.LANG) { + if (lang === Code.LANG) { option.selected = true; } languageMenu.options.add(option); @@ -585,7 +585,7 @@ Code.initLanguage = function() { */ Code.runJS = function(event) { // Prevent code from being executed twice on touchscreens. - if (event.type == 'touchend') { + if (event.type === 'touchend') { event.preventDefault(); } diff --git a/demos/custom-dialogs/custom-dialog.js b/demos/custom-dialogs/custom-dialog.js index 0dd45f406..04793e3da 100644 --- a/demos/custom-dialogs/custom-dialog.js +++ b/demos/custom-dialogs/custom-dialog.js @@ -133,11 +133,11 @@ CustomDialog.show = function(title, message, options) { dialogInput.focus(); dialogInput.onkeyup = function(event) { - if (event.keyCode == 13) { + if (event.keyCode === 13) { // Process as OK when user hits enter. onOkay(); return false; - } else if (event.keyCode == 27) { + } else if (event.keyCode === 27) { // Process as cancel when user hits esc. onCancel(); return false; diff --git a/demos/custom-fields/turtle/blocks.js b/demos/custom-fields/turtle/blocks.js index deb28f99f..6648e0714 100644 --- a/demos/custom-fields/turtle/blocks.js +++ b/demos/custom-fields/turtle/blocks.js @@ -42,12 +42,12 @@ Blockly.Blocks['turtle_nullifier'] = { pattern: newValue.pattern, hat: newValue.hat, }; - if ((newValue.turtleName == 'Leonardo' && newValue.hat == 'Mask') || - (newValue.turtleName == 'Yertle' && newValue.hat == 'Crown') || - (newValue.turtleName == 'Franklin') && newValue.hat == 'Propeller') { + if ((newValue.turtleName === 'Leonardo' && newValue.hat === 'Mask') || + (newValue.turtleName === 'Yertle' && newValue.hat === 'Crown') || + (newValue.turtleName === 'Franklin') && newValue.hat === 'Propeller') { var currentValue = this.getValue(); - if (newValue.turtleName != currentValue.turtleName) { + if (newValue.turtleName !== currentValue.turtleName) { // Turtle name changed. this.cachedValidatedValue_.turtleName = null; } else { diff --git a/demos/custom-fields/turtle/field_turtle.js b/demos/custom-fields/turtle/field_turtle.js index 8c268b4d5..c6454a3d1 100644 --- a/demos/custom-fields/turtle/field_turtle.js +++ b/demos/custom-fields/turtle/field_turtle.js @@ -129,7 +129,7 @@ CustomFields.FieldTurtle.prototype.updateEditable = function() { // Gets the text to display when the block is collapsed CustomFields.FieldTurtle.prototype.getText = function() { var text = this.value_.turtleName + ' wearing a ' + this.value_.hat; - if (this.value_.hat == 'Stovepipe' || this.value_.hat == 'Propeller') { + if (this.value_.hat === 'Stovepipe' || this.value_.hat === 'Propeller') { text += ' hat'; } return text; @@ -143,23 +143,23 @@ CustomFields.FieldTurtle.prototype.doClassValidation_ = function(newValue) { // Undefined signals that we want the value to remain unchanged. This is a // special feature of turtle fields, but could be useful for other // multi-part fields. - if (newValue.pattern == undefined) { + if (newValue.pattern === undefined) { newValue.pattern = this.displayValue_ && this.displayValue_.pattern; // We only want to allow patterns that are part of our pattern list. // Anything else is invalid, so we return null. - } else if (CustomFields.FieldTurtle.PATTERNS.indexOf(newValue.pattern) == -1) { + } else if (CustomFields.FieldTurtle.PATTERNS.indexOf(newValue.pattern) === -1) { newValue.pattern = null; } - if (newValue.hat == undefined) { + if (newValue.hat === undefined) { newValue.hat = this.displayValue_ && this.displayValue_.hat; - } else if (CustomFields.FieldTurtle.HATS.indexOf(newValue.hat) == -1) { + } else if (CustomFields.FieldTurtle.HATS.indexOf(newValue.hat) === -1) { newValue.hat = null; } - if (newValue.turtleName == undefined) { + if (newValue.turtleName === undefined) { newValue.turtleName = this.displayValue_ && this.displayValue_.turtleName; - } else if (CustomFields.FieldTurtle.NAMES.indexOf(newValue.turtleName) == -1) { + } else if (CustomFields.FieldTurtle.NAMES.indexOf(newValue.turtleName) === -1) { newValue.turtleName = null; } @@ -483,13 +483,13 @@ CustomFields.FieldTurtle.prototype.applyColour = function() { var child = this.turtleGroup_.firstChild; while(child) { // If it is a text node, continue. - if (child.nodeType == 3) { + if (child.nodeType === 3) { child = child.nextSibling; continue; } // Or if it is a non-turtle node, continue. var className = child.getAttribute('class'); - if (!className || className.indexOf('turtleBody') == -1) { + if (!className || className.indexOf('turtleBody') === -1) { child = child.nextSibling; continue; } diff --git a/demos/generator/index.html b/demos/generator/index.html index 6f8744398..127a128d8 100644 --- a/demos/generator/index.html +++ b/demos/generator/index.html @@ -133,7 +133,7 @@ // Generate JavaScript code and run it. window.LoopTrap = 1000; Blockly.JavaScript.INFINITE_LOOP_TRAP = - 'if (--window.LoopTrap == 0) throw "Infinite loop.";\n'; + 'if (--window.LoopTrap === 0) throw "Infinite loop.";\n'; var code = Blockly.JavaScript.workspaceToCode(demoWorkspace); Blockly.JavaScript.INFINITE_LOOP_TRAP = null; try { diff --git a/demos/graph/index.html b/demos/graph/index.html index da2922e0f..766665233 100644 --- a/demos/graph/index.html +++ b/demos/graph/index.html @@ -196,7 +196,7 @@