PageRenderTime 38ms CodeModel.GetById 11ms RepoModel.GetById 0ms app.codeStats 0ms

/sites/all/modules/drulenium/js/blockly/generators/javascript.js

https://gitlab.com/Drulenium-test/pantheon-travis
JavaScript | 212 lines | 115 code | 14 blank | 83 comment | 13 complexity | ce4c4573ae1115daabcb7dbe3689b5da MD5 | raw file
  1. /**
  2. * @license
  3. * Visual Blocks Language
  4. *
  5. * Copyright 2012 Google Inc.
  6. * https://developers.google.com/blockly/
  7. *
  8. * Licensed under the Apache License, Version 2.0 (the "License");
  9. * you may not use this file except in compliance with the License.
  10. * You may obtain a copy of the License at
  11. *
  12. * http://www.apache.org/licenses/LICENSE-2.0
  13. *
  14. * Unless required by applicable law or agreed to in writing, software
  15. * distributed under the License is distributed on an "AS IS" BASIS,
  16. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17. * See the License for the specific language governing permissions and
  18. * limitations under the License.
  19. */
  20. /**
  21. * @fileoverview Helper functions for generating JavaScript for blocks.
  22. * @author fraser@google.com (Neil Fraser)
  23. */
  24. 'use strict';
  25. goog.provide('Blockly.JavaScript');
  26. goog.require('Blockly.Generator');
  27. /**
  28. * JavaScript code generator.
  29. * @type {!Blockly.Generator}
  30. */
  31. Blockly.JavaScript = new Blockly.Generator('JavaScript');
  32. /**
  33. * List of illegal variable names.
  34. * This is not intended to be a security feature. Blockly is 100% client-side,
  35. * so bypassing this list is trivial. This is intended to prevent users from
  36. * accidentally clobbering a built-in object or function.
  37. * @private
  38. */
  39. Blockly.JavaScript.addReservedWords(
  40. 'Blockly,' + // In case JS is evaled in the current window.
  41. // https://developer.mozilla.org/en/JavaScript/Reference/Reserved_Words
  42. 'break,case,catch,continue,debugger,default,delete,do,else,finally,for,function,if,in,instanceof,new,return,switch,this,throw,try,typeof,var,void,while,with,' +
  43. 'class,enum,export,extends,import,super,implements,interface,let,package,private,protected,public,static,yield,' +
  44. 'const,null,true,false,' +
  45. // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects
  46. 'Array,ArrayBuffer,Boolean,Date,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,Error,eval,EvalError,Float32Array,Float64Array,Function,Infinity,Int16Array,Int32Array,Int8Array,isFinite,isNaN,Iterator,JSON,Math,NaN,Number,Object,parseFloat,parseInt,RangeError,ReferenceError,RegExp,StopIteration,String,SyntaxError,TypeError,Uint16Array,Uint32Array,Uint8Array,Uint8ClampedArray,undefined,uneval,URIError,' +
  47. // https://developer.mozilla.org/en/DOM/window
  48. 'applicationCache,closed,Components,content,_content,controllers,crypto,defaultStatus,dialogArguments,directories,document,frameElement,frames,fullScreen,globalStorage,history,innerHeight,innerWidth,length,location,locationbar,localStorage,menubar,messageManager,mozAnimationStartTime,mozInnerScreenX,mozInnerScreenY,mozPaintCount,name,navigator,opener,outerHeight,outerWidth,pageXOffset,pageYOffset,parent,performance,personalbar,pkcs11,returnValue,screen,screenX,screenY,scrollbars,scrollMaxX,scrollMaxY,scrollX,scrollY,self,sessionStorage,sidebar,status,statusbar,toolbar,top,URL,window,' +
  49. 'addEventListener,alert,atob,back,blur,btoa,captureEvents,clearImmediate,clearInterval,clearTimeout,close,confirm,disableExternalCapture,dispatchEvent,dump,enableExternalCapture,escape,find,focus,forward,GeckoActiveXObject,getAttention,getAttentionWithCycleCount,getComputedStyle,getSelection,home,matchMedia,maximize,minimize,moveBy,moveTo,mozRequestAnimationFrame,open,openDialog,postMessage,print,prompt,QueryInterface,releaseEvents,removeEventListener,resizeBy,resizeTo,restore,routeEvent,scroll,scrollBy,scrollByLines,scrollByPages,scrollTo,setCursor,setImmediate,setInterval,setResizable,setTimeout,showModalDialog,sizeToContent,stop,unescape,updateCommands,XPCNativeWrapper,XPCSafeJSObjectWrapper,' +
  50. 'onabort,onbeforeunload,onblur,onchange,onclick,onclose,oncontextmenu,ondevicemotion,ondeviceorientation,ondragdrop,onerror,onfocus,onhashchange,onkeydown,onkeypress,onkeyup,onload,onmousedown,onmousemove,onmouseout,onmouseover,onmouseup,onmozbeforepaint,onpaint,onpopstate,onreset,onresize,onscroll,onselect,onsubmit,onunload,onpageshow,onpagehide,' +
  51. 'Image,Option,Worker,' +
  52. // https://developer.mozilla.org/en/Gecko_DOM_Reference
  53. 'Event,Range,File,FileReader,Blob,BlobBuilder,' +
  54. 'Attr,CDATASection,CharacterData,Comment,console,DocumentFragment,DocumentType,DomConfiguration,DOMError,DOMErrorHandler,DOMException,DOMImplementation,DOMImplementationList,DOMImplementationRegistry,DOMImplementationSource,DOMLocator,DOMObject,DOMString,DOMStringList,DOMTimeStamp,DOMUserData,Entity,EntityReference,MediaQueryList,MediaQueryListListener,NameList,NamedNodeMap,Node,NodeFilter,NodeIterator,NodeList,Notation,Plugin,PluginArray,ProcessingInstruction,SharedWorker,Text,TimeRanges,Treewalker,TypeInfo,UserDataHandler,Worker,WorkerGlobalScope,' +
  55. 'HTMLDocument,HTMLElement,HTMLAnchorElement,HTMLAppletElement,HTMLAudioElement,HTMLAreaElement,HTMLBaseElement,HTMLBaseFontElement,HTMLBodyElement,HTMLBRElement,HTMLButtonElement,HTMLCanvasElement,HTMLDirectoryElement,HTMLDivElement,HTMLDListElement,HTMLEmbedElement,HTMLFieldSetElement,HTMLFontElement,HTMLFormElement,HTMLFrameElement,HTMLFrameSetElement,HTMLHeadElement,HTMLHeadingElement,HTMLHtmlElement,HTMLHRElement,HTMLIFrameElement,HTMLImageElement,HTMLInputElement,HTMLKeygenElement,HTMLLabelElement,HTMLLIElement,HTMLLinkElement,HTMLMapElement,HTMLMenuElement,HTMLMetaElement,HTMLModElement,HTMLObjectElement,HTMLOListElement,HTMLOptGroupElement,HTMLOptionElement,HTMLOutputElement,HTMLParagraphElement,HTMLParamElement,HTMLPreElement,HTMLQuoteElement,HTMLScriptElement,HTMLSelectElement,HTMLSourceElement,HTMLSpanElement,HTMLStyleElement,HTMLTableElement,HTMLTableCaptionElement,HTMLTableCellElement,HTMLTableDataCellElement,HTMLTableHeaderCellElement,HTMLTableColElement,HTMLTableRowElement,HTMLTableSectionElement,HTMLTextAreaElement,HTMLTimeElement,HTMLTitleElement,HTMLTrackElement,HTMLUListElement,HTMLUnknownElement,HTMLVideoElement,' +
  56. 'HTMLCanvasElement,CanvasRenderingContext2D,CanvasGradient,CanvasPattern,TextMetrics,ImageData,CanvasPixelArray,HTMLAudioElement,HTMLVideoElement,NotifyAudioAvailableEvent,HTMLCollection,HTMLAllCollection,HTMLFormControlsCollection,HTMLOptionsCollection,HTMLPropertiesCollection,DOMTokenList,DOMSettableTokenList,DOMStringMap,RadioNodeList,' +
  57. 'SVGDocument,SVGElement,SVGAElement,SVGAltGlyphElement,SVGAltGlyphDefElement,SVGAltGlyphItemElement,SVGAnimationElement,SVGAnimateElement,SVGAnimateColorElement,SVGAnimateMotionElement,SVGAnimateTransformElement,SVGSetElement,SVGCircleElement,SVGClipPathElement,SVGColorProfileElement,SVGCursorElement,SVGDefsElement,SVGDescElement,SVGEllipseElement,SVGFilterElement,SVGFilterPrimitiveStandardAttributes,SVGFEBlendElement,SVGFEColorMatrixElement,SVGFEComponentTransferElement,SVGFECompositeElement,SVGFEConvolveMatrixElement,SVGFEDiffuseLightingElement,SVGFEDisplacementMapElement,SVGFEDistantLightElement,SVGFEFloodElement,SVGFEGaussianBlurElement,SVGFEImageElement,SVGFEMergeElement,SVGFEMergeNodeElement,SVGFEMorphologyElement,SVGFEOffsetElement,SVGFEPointLightElement,SVGFESpecularLightingElement,SVGFESpotLightElement,SVGFETileElement,SVGFETurbulenceElement,SVGComponentTransferFunctionElement,SVGFEFuncRElement,SVGFEFuncGElement,SVGFEFuncBElement,SVGFEFuncAElement,SVGFontElement,SVGFontFaceElement,SVGFontFaceFormatElement,SVGFontFaceNameElement,SVGFontFaceSrcElement,SVGFontFaceUriElement,SVGForeignObjectElement,SVGGElement,SVGGlyphElement,SVGGlyphRefElement,SVGGradientElement,SVGLinearGradientElement,SVGRadialGradientElement,SVGHKernElement,SVGImageElement,SVGLineElement,SVGMarkerElement,SVGMaskElement,SVGMetadataElement,SVGMissingGlyphElement,SVGMPathElement,SVGPathElement,SVGPatternElement,SVGPolylineElement,SVGPolygonElement,SVGRectElement,SVGScriptElement,SVGStopElement,SVGStyleElement,SVGSVGElement,SVGSwitchElement,SVGSymbolElement,SVGTextElement,SVGTextPathElement,SVGTitleElement,SVGTRefElement,SVGTSpanElement,SVGUseElement,SVGViewElement,SVGVKernElement,' +
  58. 'SVGAngle,SVGColor,SVGICCColor,SVGElementInstance,SVGElementInstanceList,SVGLength,SVGLengthList,SVGMatrix,SVGNumber,SVGNumberList,SVGPaint,SVGPoint,SVGPointList,SVGPreserveAspectRatio,SVGRect,SVGStringList,SVGTransform,SVGTransformList,' +
  59. 'SVGAnimatedAngle,SVGAnimatedBoolean,SVGAnimatedEnumeration,SVGAnimatedInteger,SVGAnimatedLength,SVGAnimatedLengthList,SVGAnimatedNumber,SVGAnimatedNumberList,SVGAnimatedPreserveAspectRatio,SVGAnimatedRect,SVGAnimatedString,SVGAnimatedTransformList,' +
  60. 'SVGPathSegList,SVGPathSeg,SVGPathSegArcAbs,SVGPathSegArcRel,SVGPathSegClosePath,SVGPathSegCurvetoCubicAbs,SVGPathSegCurvetoCubicRel,SVGPathSegCurvetoCubicSmoothAbs,SVGPathSegCurvetoCubicSmoothRel,SVGPathSegCurvetoQuadraticAbs,SVGPathSegCurvetoQuadraticRel,SVGPathSegCurvetoQuadraticSmoothAbs,SVGPathSegCurvetoQuadraticSmoothRel,SVGPathSegLinetoAbs,SVGPathSegLinetoHorizontalAbs,SVGPathSegLinetoHorizontalRel,SVGPathSegLinetoRel,SVGPathSegLinetoVerticalAbs,SVGPathSegLinetoVerticalRel,SVGPathSegMovetoAbs,SVGPathSegMovetoRel,ElementTimeControl,TimeEvent,SVGAnimatedPathData,' +
  61. 'SVGAnimatedPoints,SVGColorProfileRule,SVGCSSRule,SVGExternalResourcesRequired,SVGFitToViewBox,SVGLangSpace,SVGLocatable,SVGRenderingIntent,SVGStylable,SVGTests,SVGTextContentElement,SVGTextPositioningElement,SVGTransformable,SVGUnitTypes,SVGURIReference,SVGViewSpec,SVGZoomAndPan');
  62. /**
  63. * Order of operation ENUMs.
  64. * https://developer.mozilla.org/en/JavaScript/Reference/Operators/Operator_Precedence
  65. */
  66. Blockly.JavaScript.ORDER_ATOMIC = 0; // 0 "" ...
  67. Blockly.JavaScript.ORDER_MEMBER = 1; // . []
  68. Blockly.JavaScript.ORDER_NEW = 1; // new
  69. Blockly.JavaScript.ORDER_FUNCTION_CALL = 2; // ()
  70. Blockly.JavaScript.ORDER_INCREMENT = 3; // ++
  71. Blockly.JavaScript.ORDER_DECREMENT = 3; // --
  72. Blockly.JavaScript.ORDER_LOGICAL_NOT = 4; // !
  73. Blockly.JavaScript.ORDER_BITWISE_NOT = 4; // ~
  74. Blockly.JavaScript.ORDER_UNARY_PLUS = 4; // +
  75. Blockly.JavaScript.ORDER_UNARY_NEGATION = 4; // -
  76. Blockly.JavaScript.ORDER_TYPEOF = 4; // typeof
  77. Blockly.JavaScript.ORDER_VOID = 4; // void
  78. Blockly.JavaScript.ORDER_DELETE = 4; // delete
  79. Blockly.JavaScript.ORDER_MULTIPLICATION = 5; // *
  80. Blockly.JavaScript.ORDER_DIVISION = 5; // /
  81. Blockly.JavaScript.ORDER_MODULUS = 5; // %
  82. Blockly.JavaScript.ORDER_ADDITION = 6; // +
  83. Blockly.JavaScript.ORDER_SUBTRACTION = 6; // -
  84. Blockly.JavaScript.ORDER_BITWISE_SHIFT = 7; // << >> >>>
  85. Blockly.JavaScript.ORDER_RELATIONAL = 8; // < <= > >=
  86. Blockly.JavaScript.ORDER_IN = 8; // in
  87. Blockly.JavaScript.ORDER_INSTANCEOF = 8; // instanceof
  88. Blockly.JavaScript.ORDER_EQUALITY = 9; // == != === !==
  89. Blockly.JavaScript.ORDER_BITWISE_AND = 10; // &
  90. Blockly.JavaScript.ORDER_BITWISE_XOR = 11; // ^
  91. Blockly.JavaScript.ORDER_BITWISE_OR = 12; // |
  92. Blockly.JavaScript.ORDER_LOGICAL_AND = 13; // &&
  93. Blockly.JavaScript.ORDER_LOGICAL_OR = 14; // ||
  94. Blockly.JavaScript.ORDER_CONDITIONAL = 15; // ?:
  95. Blockly.JavaScript.ORDER_ASSIGNMENT = 16; // = += -= *= /= %= <<= >>= ...
  96. Blockly.JavaScript.ORDER_COMMA = 17; // ,
  97. Blockly.JavaScript.ORDER_NONE = 99; // (...)
  98. /**
  99. * Initialise the database of variable names.
  100. * @param {!Blockly.Workspace} workspace Workspace to generate code from.
  101. */
  102. Blockly.JavaScript.init = function(workspace) {
  103. // Create a dictionary of definitions to be printed before the code.
  104. Blockly.JavaScript.definitions_ = Object.create(null);
  105. // Create a dictionary mapping desired function names in definitions_
  106. // to actual function names (to avoid collisions with user functions).
  107. Blockly.JavaScript.functionNames_ = Object.create(null);
  108. if (!Blockly.JavaScript.variableDB_) {
  109. Blockly.JavaScript.variableDB_ =
  110. new Blockly.Names(Blockly.JavaScript.RESERVED_WORDS_);
  111. } else {
  112. Blockly.JavaScript.variableDB_.reset();
  113. }
  114. var defvars = [];
  115. var variables = Blockly.Variables.allVariables(workspace);
  116. for (var i = 0; i < variables.length; i++) {
  117. defvars[i] = 'var ' +
  118. Blockly.JavaScript.variableDB_.getName(variables[i],
  119. Blockly.Variables.NAME_TYPE) + ';';
  120. }
  121. Blockly.JavaScript.definitions_['variables'] = defvars.join('\n');
  122. };
  123. /**
  124. * Prepend the generated code with the variable definitions.
  125. * @param {string} code Generated code.
  126. * @return {string} Completed code.
  127. */
  128. Blockly.JavaScript.finish = function(code) {
  129. // Convert the definitions dictionary into a list.
  130. var definitions = [];
  131. for (var name in Blockly.JavaScript.definitions_) {
  132. definitions.push(Blockly.JavaScript.definitions_[name]);
  133. }
  134. // Clean up temporary data.
  135. delete Blockly.JavaScript.definitions_;
  136. delete Blockly.JavaScript.functionNames_;
  137. Blockly.JavaScript.variableDB_.reset();
  138. return definitions.join('\n\n') + '\n\n\n' + code;
  139. };
  140. /**
  141. * Naked values are top-level blocks with outputs that aren't plugged into
  142. * anything. A trailing semicolon is needed to make this legal.
  143. * @param {string} line Line of generated code.
  144. * @return {string} Legal line of code.
  145. */
  146. Blockly.JavaScript.scrubNakedValue = function(line) {
  147. return line + ';\n';
  148. };
  149. /**
  150. * Encode a string as a properly escaped JavaScript string, complete with
  151. * quotes.
  152. * @param {string} string Text to encode.
  153. * @return {string} JavaScript string.
  154. * @private
  155. */
  156. Blockly.JavaScript.quote_ = function(string) {
  157. // TODO: This is a quick hack. Replace with goog.string.quote
  158. string = string.replace(/\\/g, '\\\\')
  159. .replace(/\n/g, '\\\n')
  160. .replace(/'/g, '\\\'');
  161. return '\'' + string + '\'';
  162. };
  163. /**
  164. * Common tasks for generating JavaScript from blocks.
  165. * Handles comments for the specified block and any connected value blocks.
  166. * Calls any statements following this block.
  167. * @param {!Blockly.Block} block The current block.
  168. * @param {string} code The JavaScript code created for this block.
  169. * @return {string} JavaScript code with comments and subsequent blocks added.
  170. * @private
  171. */
  172. Blockly.JavaScript.scrub_ = function(block, code) {
  173. var commentCode = '';
  174. // Only collect comments for blocks that aren't inline.
  175. if (!block.outputConnection || !block.outputConnection.targetConnection) {
  176. // Collect comment for this block.
  177. var comment = block.getCommentText();
  178. if (comment) {
  179. commentCode += Blockly.JavaScript.prefixLines(comment, '// ') + '\n';
  180. }
  181. // Collect comments for all value arguments.
  182. // Don't collect comments for nested statements.
  183. for (var x = 0; x < block.inputList.length; x++) {
  184. if (block.inputList[x].type == Blockly.INPUT_VALUE) {
  185. var childBlock = block.inputList[x].connection.targetBlock();
  186. if (childBlock) {
  187. var comment = Blockly.JavaScript.allNestedComments(childBlock);
  188. if (comment) {
  189. commentCode += Blockly.JavaScript.prefixLines(comment, '// ');
  190. }
  191. }
  192. }
  193. }
  194. }
  195. var nextBlock = block.nextConnection && block.nextConnection.targetBlock();
  196. var nextCode = Blockly.JavaScript.blockToCode(nextBlock);
  197. return commentCode + code + nextCode;
  198. };