├── README.md ├── index.html ├── lab ├── base.css ├── export-to-html.html ├── lab.codemirror.css ├── lab.codemirror.js ├── lab.css ├── lab.js ├── lab.png-baker.js ├── vendor │ ├── codemirror │ │ ├── codemirror.css │ │ ├── codemirror.js │ │ ├── css.js │ │ ├── htmlmixed.js │ │ ├── javascript.js │ │ ├── matchbrackets.js │ │ └── xml.js │ ├── foundation.css │ └── png-baker.js └── worker.js ├── tiny-turtle.js └── tutorial ├── glossary.html ├── highlight.css ├── highlight.js └── index.html /README.md: -------------------------------------------------------------------------------- 1 | **TinyTurtle** is a minimalist [Turtle Graphics][] implementation using 2 | the [Canvas element][], consisting of about 60 lines of JavaScript code. 3 | 4 | The library is intended for use in teaching scenarios where learners 5 | have access to a simple HTML editing environment such as [Thimble][] or 6 | [jsbin][]. Learners should have a basic knowledge of HTML, but do 7 | not need any JavaScript experience. 8 | 9 | The implementation is kept as minimal as possible so that learners are 10 | encouraged to view its source, understand it, and build upon it. 11 | 12 | ## Basic Usage 13 | 14 | For absolute beginners, the `TinyTurtle` constructor can be applied to 15 | the `window` object so that learners don't need to worry about lots 16 | of typing, dot notation, inheritance, and so forth. Here's a trivial 17 | example of a few squares being drawn: 18 | 19 | ```html 20 | 21 | 22 | TinyTurtle Box Example 23 | 24 | 25 | 43 | ``` 44 | 45 | ## Instantiation and Chaining 46 | 47 | The constructor can also be instantiated to allow for 48 | multiple turtles to co-exist on a page, while also avoiding pollution 49 | of the global namespace. Most methods also return `this` to 50 | support chaining. Here's an equivalent replacement for the JavaScript 51 | in the previous snippet which uses these more advanced techniques: 52 | 53 | ```javascript 54 | var t = new TinyTurtle(); 55 | 56 | t.box = function box(length) { 57 | for (var i = 0; i < 4; i++) this.forward(length).right(90); 58 | return this; 59 | }; 60 | 61 | t.penStyle = 'purple'; 62 | t.box(90).left(10).box(80).left(10).box(70); 63 | ``` 64 | 65 | This hopefully allows learners to start doing interesting things in an 66 | incremental way. 67 | 68 | ## CoffeeScript 69 | 70 | The `TinyTurtle` class can also be extended in [CoffeeScript][], if one 71 | wishes to teach (or learn) it as an alternative to JavaScript. For 72 | example: 73 | 74 | ```coffeescript 75 | class MyTurtle extends TinyTurtle 76 | box: (length) -> 77 | for i in [1..4] 78 | this.forward length 79 | this.right 90 80 | 81 | t = new MyTurtle 82 | 83 | t.penStyle = 'purple' 84 | t.box 90 85 | t.left 10 86 | t.box 80 87 | t.left 10 88 | t.box 70 89 | ``` 90 | 91 | ## API 92 | 93 | The `TinyTurtle` constructor takes only one optional argument, which is 94 | the [HTMLCanvasElement][] to draw on. If not present, the first canvas 95 | element on the page is used. 96 | 97 | ### Methods 98 | 99 | **forward(amount)** 100 | 101 | Move the turtle forward by the given number of pixels. If the pen is 102 | down, a line is drawn from its previous position to its new position. 103 | 104 | The `fd` method can be used as shorthand for this. 105 | 106 | **left(degrees)** 107 | 108 | Rotate the turtle to its left by the given number of degrees. 109 | 110 | The `lt` method can be used as shorthand for this. 111 | 112 | **right(degrees)** 113 | 114 | Rotate the turtle to its right by the given number of degrees. 115 | 116 | The `rt` method can be used as shorthand for this. 117 | 118 | **stamp()** 119 | 120 | Draw the turtle as a triangle that represents its current state in the 121 | following ways: 122 | 123 | * The triangle is drawn at the turtle's current position. 124 | * The triangle is pointing in the direction that the turtle is currently 125 | oriented towards. 126 | * If the pen is up, the triangle is drawn as an outline; otherwise, it's 127 | filled. 128 | * The color and outline of the triangle is drawn using the current pen 129 | style and pen width. 130 | 131 | **penUp()** 132 | 133 | Put the pen up, so that movements by the turtle don't draw anything on 134 | the canvas. 135 | 136 | **penDown()** 137 | 138 | Put the pen down, so that movements by the turtle draw a path on the canvas. 139 | 140 | ### Properties 141 | 142 | **penStyle** (read/write) 143 | 144 | A string describing the style that the turtle's path is drawn in. This 145 | can be represented as any one of: 146 | 147 | * A hexadecimal color like `#00FF00` 148 | * A [RGBA][] quad like `rgba(0, 255, 0, 0.5)` 149 | * A [HSLA][] quad like `hsla(50, 100%, 50%, 0.5)` 150 | * A [CSS color name][] like `red`. 151 | 152 | **penWidth** (read/write) 153 | 154 | The width of the turtle's path, in pixels. 155 | 156 | **canvas** (read-only) 157 | 158 | The [HTMLCanvasElement][] the turtle is drawing on. 159 | 160 | **rotation** (read-only) 161 | 162 | The current rotation of the turtle, in degrees. 163 | 164 | **position** (read-only) 165 | 166 | The current position of the turtle, as an object with `x` and `y` 167 | properties. 168 | 169 | **pen** (read-only) 170 | 171 | The string `up` or `down` indicating the current state of the turtle's 172 | pen. 173 | 174 | ## Supported Browsers 175 | 176 | This code has been tested on Internet Explorer 10, 177 | Safari 6 (desktop and iOS), Chrome 30, Opera 17, and Firefox 24. 178 | 179 | ## License 180 | 181 | Public Domain [CC0 1.0 Universal][cczero]. 182 | 183 | [Turtle Graphics]: http://en.wikipedia.org/wiki/Turtle_graphics 184 | [Canvas element]: http://en.wikipedia.org/wiki/Canvas_element 185 | [Thimble]: https://thimble.webmaker.org/ 186 | [jsbin]: http://jsbin.com/ 187 | [CoffeeScript]: http://coffeescript.org/ 188 | [HTMLCanvasElement]: https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement 189 | [RGBA]: http://www.w3.org/TR/css3-color/#rgba-color 190 | [HSLA]: http://www.w3.org/TR/css3-color/#hsla-color 191 | [CSS color name]: http://www.w3.org/TR/css3-color/#svg-color 192 | [cczero]: http://creativecommons.org/publicdomain/zero/1.0/ 193 | -------------------------------------------------------------------------------- /index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | TinyTurtle Lab 4 | 5 | 6 | 7 | 8 | 9 |

TinyTurtle Lab

10 |
11 | 17 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 71 | 72 | -------------------------------------------------------------------------------- /lab/base.css: -------------------------------------------------------------------------------- 1 | @media (max-width: 900px) { 2 | body { 3 | margin: 0 10px; 4 | } 5 | } 6 | 7 | @media (min-width: 900px) { 8 | body { 9 | width: 880px; 10 | margin: 0 auto; 11 | } 12 | } 13 | 14 | a { 15 | color: inherit; 16 | text-decoration: underline; 17 | } 18 | 19 | a:hover { 20 | color: inherit; 21 | background: yellow; 22 | } 23 | 24 | footer { 25 | text-align: center; 26 | font-size: smaller; 27 | } 28 | -------------------------------------------------------------------------------- /lab/export-to-html.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 20 | Export to HTML 21 |

Export to HTML

22 |

23 | Here is the HTML for your creation. Copy and paste it into a 24 | site like Thimble, 25 | jsbin, or your favorite 26 | text editor. 27 |

28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 65 | -------------------------------------------------------------------------------- /lab/lab.codemirror.css: -------------------------------------------------------------------------------- 1 | /* This is based on the elegant theme that ships with CodeMirror. */ 2 | 3 | .cm-s-lab span.cm-number, .cm-s-lab span.cm-string, .cm-s-lab span.cm-atom {color: #762;} 4 | .cm-s-lab span.cm-comment {color: #262; font-style: italic; line-height: 1em;} 5 | .cm-s-lab span.cm-meta {color: #555; font-style: italic; line-height: 1em;} 6 | .cm-s-lab span.cm-variable {color: black;} 7 | .cm-s-lab span.cm-variable-2 {color: #b11;} 8 | .cm-s-lab span.cm-qualifier {color: #555;} 9 | .cm-s-lab span.cm-keyword {color: #730;} 10 | .cm-s-lab span.cm-builtin {color: #30a;} 11 | .cm-s-lab span.cm-link {color: #762;} 12 | .cm-s-lab span.cm-error {background-color: #fdd;} 13 | 14 | .cm-s-lab .CodeMirror-activeline-background {background: #e8f2ff !important;} 15 | .cm-s-lab .CodeMirror-matchingbracket { 16 | text-decoration: underline; 17 | color: black !important; 18 | } 19 | -------------------------------------------------------------------------------- /lab/lab.codemirror.js: -------------------------------------------------------------------------------- 1 | Lab.codeMirrorOptions = { 2 | lineNumbers: true, 3 | matchBrackets: true, 4 | theme: 'lab', 5 | mode: 'javascript' 6 | }; 7 | 8 | Lab.creationHooks.push(function(lab) { 9 | var render = lab.render; 10 | var codeMirror; 11 | 12 | function initCodeMirror() { 13 | var options = {}; 14 | 15 | Object.keys(Lab.codeMirrorOptions).forEach(function(option) { 16 | options[option] = Lab.codeMirrorOptions[option]; 17 | }); 18 | 19 | options.value = lab.code.value; 20 | codeMirror = CodeMirror(function(element) { 21 | element.classList.add("code"); 22 | lab.code.parentNode.replaceChild(element, lab.code); 23 | }, options); 24 | codeMirror.on("change", function propagateChangeToUnderlyingCode() { 25 | var event = document.createEvent('HTMLEvents'); 26 | event.initEvent('change', true, true); 27 | lab.code.value = codeMirror.getValue(); 28 | lab.code.dispatchEvent(event); 29 | }); 30 | } 31 | 32 | lab.render = function() { 33 | if (!codeMirror) initCodeMirror(); 34 | 35 | // See if the underlying code has been programmatically changed. 36 | if (codeMirror.getValue() != lab.code.value) 37 | codeMirror.setValue(lab.code.value); 38 | 39 | render.call(lab); 40 | }; 41 | }); 42 | -------------------------------------------------------------------------------- /lab/lab.css: -------------------------------------------------------------------------------- 1 | .lab * { 2 | box-sizing: border-box; 3 | -moz-box-sizing: border-box; 4 | -webkit-box-sizing: border-box; 5 | } 6 | 7 | .lab { 8 | position: relative; 9 | height: 280px; 10 | } 11 | 12 | .lab .canvas { 13 | position: absolute; 14 | top: 0; 15 | right: 0; 16 | border: 1px dotted gray; 17 | } 18 | 19 | .lab .code:focus { 20 | outline: 0; 21 | } 22 | 23 | .lab .code { 24 | position: absolute; 25 | top: 0; 26 | left: 0; 27 | width: -webkit-calc(100% - 260px); 28 | width: -moz-calc(100% - 260px); 29 | width: calc(100% - 260px); 30 | height: 250px; 31 | resize: none; 32 | border: none; 33 | background: #f0f0f0; 34 | font-family: Menlo, Monaco, "Lucida Console", monospace; 35 | font-size: small; 36 | } 37 | 38 | .lab textarea.code { 39 | padding: 4px; 40 | } 41 | 42 | .lab .error { 43 | position: absolute; 44 | top: 252px; 45 | left: 0; 46 | right: 0; 47 | color: red; 48 | /* Errors can take some time to fade in b/c we don't want to 49 | * needlessly distract the user. */ 50 | transition: opacity 1s 0.25s; 51 | -moz-transition: opacity 1s 0.25s; 52 | -webkit-transition: opacity 1s 0.25s; 53 | } 54 | 55 | .lab .error:not(.shown) { 56 | opacity: 0; 57 | /* Errors should disappear instantaneously to let the user know 58 | * everything is okay now. */ 59 | transition: opacity 0.25s 0.01s; 60 | -moz-transition: opacity 0.25s 0.01s; 61 | -webkit-transition: opacity 0.25s 0.01s; 62 | } 63 | -------------------------------------------------------------------------------- /lab/lab.js: -------------------------------------------------------------------------------- 1 | var Lab = typeof(window) == 'undefined' 2 | ? {} // We're in a web worker. 3 | : (function(TinyTurtle) { // We're in a web page. 4 | var DEFAULT_CANVAS_SIZE = 250; 5 | var TURTLE_WIDTH = 10; 6 | var TURTLE_HEIGHT = 10; 7 | var RENDER_DELAY_MS = 100; 8 | var WORKER_TIMEOUT_MS = 2000; 9 | 10 | var baseURL = Lab.baseURL = (function() { 11 | // http://stackoverflow.com/a/3326554/2422398 12 | var scripts = document.getElementsByTagName('script'); 13 | var myURL = scripts[scripts.length - 1].src; 14 | return myURL.split('/').slice(0, -1).join('/') + '/'; 15 | })(); 16 | 17 | function Lab(parent) { 18 | if (!parent) parent = document.createElement('div'); 19 | if (parent.render) return parent; 20 | 21 | var $ = parent.querySelector.bind(parent); 22 | var turtle; 23 | var worker; 24 | var source; 25 | var renderDelayTimeout; 26 | var workerTimeout; 27 | var workerURL = baseURL + 'worker.js'; 28 | var code = $(".code"); 29 | var canvasImg = $(".canvas"); 30 | var canvas = document.createElement('canvas'); 31 | var error = $(".error"); 32 | var script = $("script"); 33 | 34 | function queueRendering() { 35 | clearTimeout(renderDelayTimeout); 36 | renderDelayTimeout = setTimeout(render, RENDER_DELAY_MS); 37 | } 38 | 39 | function killWorker() { 40 | if (!worker) return; 41 | clearTimeout(workerTimeout); 42 | worker.terminate(); 43 | worker = null; 44 | } 45 | 46 | function drawCmds(cmds) { 47 | canvas.getContext('2d').clearRect(0, 0, canvas.width, canvas.height); 48 | cmds.forEach(function(cmd) { 49 | if (cmd.msg == 'turtle-propset') 50 | Lab.Validation.setProperty(turtle, cmd.property, cmd.value); 51 | else if (cmd.msg == 'turtle-methodcall') 52 | Lab.Validation.callMethod(turtle, cmd.method, cmd.args); 53 | }); 54 | } 55 | 56 | function finishWorker(cmds, err) { 57 | killWorker(); 58 | if (err) { 59 | error.classList.add("shown"); 60 | error.textContent = (err.lineno ? "Line " + err.lineno + ": " : '') + 61 | err.message; 62 | // If nothing was displayed, don't draw an empty canvas, b/c we don't 63 | // want to unnecessarily distract the user if they're in the middle 64 | // of typing. 65 | if (!cmds.length) return; 66 | // Otherwise, show what was drawn before the error as a debugging 67 | // aid. 68 | } else { 69 | // Note that we would just use classList.toggle() with !!err as 70 | // the second arg, but it appears to be broken in IE10. 71 | error.classList.remove("shown"); 72 | } 73 | drawCmds(cmds); 74 | var event = document.createEvent('CustomEvent'); 75 | event.initCustomEvent('render', true, true, {canvas: canvas}); 76 | var wasDefaultPrevented = !parent.dispatchEvent(event); 77 | if (!wasDefaultPrevented) canvasImg.src = canvas.toDataURL(); 78 | } 79 | 80 | function render() { 81 | var cmds = []; 82 | 83 | if (code.value == source) return; 84 | source = code.value; 85 | killWorker(); 86 | turtle = new TinyTurtle(canvas); 87 | worker = new Worker(workerURL); 88 | worker.onmessage = function(e) { 89 | if (e.data.msg == 'done') 90 | finishWorker(cmds, null); 91 | else 92 | cmds.push(e.data); 93 | }; 94 | worker.onerror = finishWorker.bind(null, cmds); 95 | worker.postMessage({ 96 | source: code.value, 97 | height: canvas.height, 98 | width: canvas.width 99 | }); 100 | workerTimeout = setTimeout(function() { 101 | finishWorker(cmds, new Error(Lab.Strings.WORKER_TIMEOUT_MSG)); 102 | }, WORKER_TIMEOUT_MS); 103 | } 104 | 105 | parent.setAttribute('contextmenu', Lab.contextMenu.id); 106 | parent.setAttribute('data-role', 'lab'); 107 | parent.classList.add('lab'); 108 | if (!canvasImg) { 109 | canvasImg = document.createElement('img'); 110 | canvasImg.classList.add('canvas'); 111 | canvasImg.setAttribute('width', DEFAULT_CANVAS_SIZE); 112 | canvasImg.setAttribute('height', DEFAULT_CANVAS_SIZE); 113 | parent.appendChild(canvasImg); 114 | } 115 | if (!code) { 116 | code = document.createElement('textarea'); 117 | code.classList.add('code'); 118 | code.setAttribute('spellcheck', 'false'); 119 | parent.appendChild(code); 120 | } 121 | if (script) code.value = script.textContent.trim(); 122 | if (!error) { 123 | error = document.createElement('div'); 124 | error.classList.add('error'); 125 | parent.appendChild(error); 126 | } 127 | 128 | canvas.width = canvasImg.getAttribute('width'); 129 | canvas.height = canvasImg.getAttribute('height'); 130 | code.addEventListener('keyup', queueRendering, false); 131 | code.addEventListener('change', queueRendering, false); 132 | 133 | parent.render = render; 134 | parent.code = code; 135 | parent.canvasImage = canvasImg; 136 | 137 | Lab.creationHooks.forEach(function(hook) { hook(parent); }); 138 | 139 | return parent; 140 | } 141 | 142 | return Lab; 143 | })(TinyTurtle); 144 | 145 | Lab.creationHooks = []; 146 | 147 | Lab.Strings = { 148 | EXPORT_TO_HTML: "Export to HTML", 149 | WORKER_TIMEOUT_MSG: "Your code has taken too long to execute. " + 150 | "Perhaps it contains an infinite loop?" 151 | }; 152 | 153 | Lab.Validation = { 154 | properties: ['penStyle', 'penWidth'], 155 | methods: ['penUp', 'penDown', 'forward', 'fd', 'left', 'lt', 156 | 'right', 'rt', 'stamp'], 157 | isValidType: function(value) { 158 | return ~['string', 'number'].indexOf(typeof(value)); 159 | }, 160 | setProperty: function(obj, property, val) { 161 | if (!~this.properties.indexOf(property)) return; 162 | if (!this.isValidType(val)) return; 163 | obj[property] = val; 164 | }, 165 | callMethod: function(obj, method, args) { 166 | if (!~this.methods.indexOf(method)) return; 167 | for (var i = 0; i < args.length; i++) 168 | if (!this.isValidType(args[i])) return; 169 | obj[method].apply(obj, args); 170 | } 171 | }; 172 | 173 | if (typeof(document) != 'undefined') { 174 | document.addEventListener("DOMContentLoaded", function activateLabs() { 175 | var i; 176 | var scriptLabs = document.querySelectorAll('script[data-role="lab"]'); 177 | var labs = document.querySelectorAll('div[data-role="lab"]'); 178 | 179 | for (i = 0; i < scriptLabs.length; i++) { 180 | var scriptLab = scriptLabs[i]; 181 | var lab = document.createElement('div'); 182 | scriptLab.parentNode.replaceChild(lab, scriptLab); 183 | lab.appendChild(scriptLab); 184 | Lab(lab); 185 | lab.code.value = scriptLab.textContent.trim(); 186 | lab.render(); 187 | } 188 | for (i = 0; i < labs.length; i++) 189 | Lab(labs[i]).render(); 190 | }, false); 191 | 192 | Lab.contextMenu = (function() { 193 | var menu = document.getElementById('tiny-turtle-context-menu'); 194 | 195 | if (!menu) { 196 | menu = document.createElement('menu'); 197 | menu.setAttribute('type', 'context'); 198 | menu.id = 'tiny-turtle-context-menu'; 199 | document.body.appendChild(menu); 200 | } 201 | 202 | // The associated DOM element that a context menu item is activated 203 | // with doesn't seem to be communicated with the menu item's 204 | // click event, so we'll keep track of it ourselves here. 205 | menu.relatedLab = null; 206 | 207 | Lab.creationHooks.push(function(lab) { 208 | lab.addEventListener("contextmenu", function() { 209 | menu.relatedLab = this; 210 | }, false); 211 | }); 212 | 213 | return menu; 214 | })(); 215 | 216 | (function AddExportToHTML() { 217 | var exportItem = document.createElement('menuitem'); 218 | 219 | exportItem.label = Lab.Strings.EXPORT_TO_HTML; 220 | exportItem.onclick = function() { 221 | var code = this.parentNode.relatedLab.code.value; 222 | var url = Lab.baseURL + 'export-to-html.html?code=' + 223 | encodeURIComponent(code); 224 | window.open(url); 225 | }; 226 | 227 | Lab.contextMenu.appendChild(exportItem); 228 | })(); 229 | } 230 | -------------------------------------------------------------------------------- /lab/lab.png-baker.js: -------------------------------------------------------------------------------- 1 | Lab.creationHooks.push(function(lab) { 2 | var bakedImgURL; 3 | 4 | function onDragEvent(e) { 5 | if (e.type == 'drop') { 6 | if (e.dataTransfer.files.length) { 7 | var file = e.dataTransfer.files[0]; 8 | if (file.type == 'image/png') { 9 | var reader = new FileReader(); 10 | reader.onloadend = function() { 11 | var baker = new PNGBaker(reader.result); 12 | var bakedSource = baker.textChunks['tiny-turtle-source']; 13 | if (bakedSource) { 14 | lab.code.value = decodeURIComponent(bakedSource); 15 | lab.render(); 16 | } 17 | }; 18 | reader.readAsArrayBuffer(file); 19 | e.stopPropagation(); 20 | e.preventDefault(); 21 | } 22 | } 23 | return; 24 | } else { 25 | e.stopPropagation(); 26 | e.preventDefault(); 27 | } 28 | } 29 | 30 | ['dragenter', 'dragleave', 'dragover', 'drop'].forEach(function(type) { 31 | lab.addEventListener(type, onDragEvent); 32 | }); 33 | 34 | if (navigator.msSaveOrOpenBlob) 35 | // IE10's "Save Picture As..." strips out the tEXt chunks from our 36 | // PNG, so we'll override things to provide our own functionality. 37 | lab.canvasImage.addEventListener('contextmenu', function(e) { 38 | if (!this.blob) return; 39 | navigator.msSaveOrOpenBlob(this.blob, 'canvas.png'); 40 | e.preventDefault(); 41 | }); 42 | 43 | lab.addEventListener('render', function bakeSourceCodeIntoImage(e) { 44 | var canvasImg = lab.canvasImage; 45 | var source = lab.code.value; 46 | var canvas = e.detail.canvas; 47 | var baker = new PNGBaker(canvas.toDataURL()); 48 | var URL = window.URL || window.webkitURL; 49 | baker.textChunks['tiny-turtle-source'] = encodeURIComponent(source); 50 | if (bakedImgURL) URL.revokeObjectURL(bakedImgURL); 51 | canvasImg.blob = baker.toBlob(); 52 | canvasImg.src = bakedImgURL = URL.createObjectURL(canvasImg.blob); 53 | e.preventDefault(); 54 | }, false); 55 | }); 56 | -------------------------------------------------------------------------------- /lab/vendor/codemirror/codemirror.css: -------------------------------------------------------------------------------- 1 | /* BASICS */ 2 | 3 | .CodeMirror { 4 | /* Set height, width, borders, and global font properties here */ 5 | font-family: monospace; 6 | height: 300px; 7 | } 8 | .CodeMirror-scroll { 9 | /* Set scrolling behaviour here */ 10 | overflow: auto; 11 | } 12 | 13 | /* PADDING */ 14 | 15 | .CodeMirror-lines { 16 | padding: 4px 0; /* Vertical padding around content */ 17 | } 18 | .CodeMirror pre { 19 | padding: 0 4px; /* Horizontal padding of content */ 20 | } 21 | 22 | .CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler { 23 | background-color: white; /* The little square between H and V scrollbars */ 24 | } 25 | 26 | /* GUTTER */ 27 | 28 | .CodeMirror-gutters { 29 | border-right: 1px solid #ddd; 30 | background-color: #f7f7f7; 31 | white-space: nowrap; 32 | } 33 | .CodeMirror-linenumbers {} 34 | .CodeMirror-linenumber { 35 | padding: 0 3px 0 5px; 36 | min-width: 20px; 37 | text-align: right; 38 | color: #999; 39 | } 40 | 41 | /* CURSOR */ 42 | 43 | .CodeMirror div.CodeMirror-cursor { 44 | border-left: 1px solid black; 45 | z-index: 3; 46 | } 47 | /* Shown when moving in bi-directional text */ 48 | .CodeMirror div.CodeMirror-secondarycursor { 49 | border-left: 1px solid silver; 50 | } 51 | .CodeMirror.cm-keymap-fat-cursor div.CodeMirror-cursor { 52 | width: auto; 53 | border: 0; 54 | background: #7e7; 55 | z-index: 1; 56 | } 57 | /* Can style cursor different in overwrite (non-insert) mode */ 58 | .CodeMirror div.CodeMirror-cursor.CodeMirror-overwrite {} 59 | 60 | .cm-tab { display: inline-block; } 61 | 62 | /* DEFAULT THEME */ 63 | 64 | .cm-s-default .cm-keyword {color: #708;} 65 | .cm-s-default .cm-atom {color: #219;} 66 | .cm-s-default .cm-number {color: #164;} 67 | .cm-s-default .cm-def {color: #00f;} 68 | .cm-s-default .cm-variable {color: black;} 69 | .cm-s-default .cm-variable-2 {color: #05a;} 70 | .cm-s-default .cm-variable-3 {color: #085;} 71 | .cm-s-default .cm-property {color: black;} 72 | .cm-s-default .cm-operator {color: black;} 73 | .cm-s-default .cm-comment {color: #a50;} 74 | .cm-s-default .cm-string {color: #a11;} 75 | .cm-s-default .cm-string-2 {color: #f50;} 76 | .cm-s-default .cm-meta {color: #555;} 77 | .cm-s-default .cm-qualifier {color: #555;} 78 | .cm-s-default .cm-builtin {color: #30a;} 79 | .cm-s-default .cm-bracket {color: #997;} 80 | .cm-s-default .cm-tag {color: #170;} 81 | .cm-s-default .cm-attribute {color: #00c;} 82 | .cm-s-default .cm-header {color: blue;} 83 | .cm-s-default .cm-quote {color: #090;} 84 | .cm-s-default .cm-hr {color: #999;} 85 | .cm-s-default .cm-link {color: #00c;} 86 | 87 | .cm-negative {color: #d44;} 88 | .cm-positive {color: #292;} 89 | .cm-header, .cm-strong {font-weight: bold;} 90 | .cm-em {font-style: italic;} 91 | .cm-link {text-decoration: underline;} 92 | 93 | .cm-s-default .cm-error {color: #f00;} 94 | .cm-invalidchar {color: #f00;} 95 | 96 | div.CodeMirror span.CodeMirror-matchingbracket {color: #0f0;} 97 | div.CodeMirror span.CodeMirror-nonmatchingbracket {color: #f22;} 98 | .CodeMirror-activeline-background {background: #e8f2ff;} 99 | 100 | /* STOP */ 101 | 102 | /* The rest of this file contains styles related to the mechanics of 103 | the editor. You probably shouldn't touch them. */ 104 | 105 | .CodeMirror { 106 | line-height: 1; 107 | position: relative; 108 | overflow: hidden; 109 | background: white; 110 | color: black; 111 | } 112 | 113 | .CodeMirror-scroll { 114 | /* 30px is the magic margin used to hide the element's real scrollbars */ 115 | /* See overflow: hidden in .CodeMirror */ 116 | margin-bottom: -30px; margin-right: -30px; 117 | padding-bottom: 30px; padding-right: 30px; 118 | height: 100%; 119 | outline: none; /* Prevent dragging from highlighting the element */ 120 | position: relative; 121 | -moz-box-sizing: content-box; 122 | box-sizing: content-box; 123 | } 124 | .CodeMirror-sizer { 125 | position: relative; 126 | } 127 | 128 | /* The fake, visible scrollbars. Used to force redraw during scrolling 129 | before actuall scrolling happens, thus preventing shaking and 130 | flickering artifacts. */ 131 | .CodeMirror-vscrollbar, .CodeMirror-hscrollbar, .CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler { 132 | position: absolute; 133 | z-index: 6; 134 | display: none; 135 | } 136 | .CodeMirror-vscrollbar { 137 | right: 0; top: 0; 138 | overflow-x: hidden; 139 | overflow-y: scroll; 140 | } 141 | .CodeMirror-hscrollbar { 142 | bottom: 0; left: 0; 143 | overflow-y: hidden; 144 | overflow-x: scroll; 145 | } 146 | .CodeMirror-scrollbar-filler { 147 | right: 0; bottom: 0; 148 | } 149 | .CodeMirror-gutter-filler { 150 | left: 0; bottom: 0; 151 | } 152 | 153 | .CodeMirror-gutters { 154 | position: absolute; left: 0; top: 0; 155 | padding-bottom: 30px; 156 | z-index: 3; 157 | } 158 | .CodeMirror-gutter { 159 | white-space: normal; 160 | height: 100%; 161 | -moz-box-sizing: content-box; 162 | box-sizing: content-box; 163 | padding-bottom: 30px; 164 | margin-bottom: -32px; 165 | display: inline-block; 166 | /* Hack to make IE7 behave */ 167 | *zoom:1; 168 | *display:inline; 169 | } 170 | .CodeMirror-gutter-elt { 171 | position: absolute; 172 | cursor: default; 173 | z-index: 4; 174 | } 175 | 176 | .CodeMirror-lines { 177 | cursor: text; 178 | } 179 | .CodeMirror pre { 180 | /* Reset some styles that the rest of the page might have set */ 181 | -moz-border-radius: 0; -webkit-border-radius: 0; border-radius: 0; 182 | border-width: 0; 183 | background: transparent; 184 | font-family: inherit; 185 | font-size: inherit; 186 | margin: 0; 187 | white-space: pre; 188 | word-wrap: normal; 189 | line-height: inherit; 190 | color: inherit; 191 | z-index: 2; 192 | position: relative; 193 | overflow: visible; 194 | } 195 | .CodeMirror-wrap pre { 196 | word-wrap: break-word; 197 | white-space: pre-wrap; 198 | word-break: normal; 199 | } 200 | .CodeMirror-code pre { 201 | border-right: 30px solid transparent; 202 | width: -webkit-fit-content; 203 | width: -moz-fit-content; 204 | width: fit-content; 205 | } 206 | .CodeMirror-wrap .CodeMirror-code pre { 207 | border-right: none; 208 | width: auto; 209 | } 210 | .CodeMirror-linebackground { 211 | position: absolute; 212 | left: 0; right: 0; top: 0; bottom: 0; 213 | z-index: 0; 214 | } 215 | 216 | .CodeMirror-linewidget { 217 | position: relative; 218 | z-index: 2; 219 | overflow: auto; 220 | } 221 | 222 | .CodeMirror-widget {} 223 | 224 | .CodeMirror-wrap .CodeMirror-scroll { 225 | overflow-x: hidden; 226 | } 227 | 228 | .CodeMirror-measure { 229 | position: absolute; 230 | width: 100%; 231 | height: 0; 232 | overflow: hidden; 233 | visibility: hidden; 234 | } 235 | .CodeMirror-measure pre { position: static; } 236 | 237 | .CodeMirror div.CodeMirror-cursor { 238 | position: absolute; 239 | visibility: hidden; 240 | border-right: none; 241 | width: 0; 242 | } 243 | .CodeMirror-focused div.CodeMirror-cursor { 244 | visibility: visible; 245 | } 246 | 247 | .CodeMirror-selected { background: #d9d9d9; } 248 | .CodeMirror-focused .CodeMirror-selected { background: #d7d4f0; } 249 | 250 | .cm-searching { 251 | background: #ffa; 252 | background: rgba(255, 255, 0, .4); 253 | } 254 | 255 | /* IE7 hack to prevent it from returning funny offsetTops on the spans */ 256 | .CodeMirror span { *vertical-align: text-bottom; } 257 | 258 | @media print { 259 | /* Hide the cursor when printing */ 260 | .CodeMirror div.CodeMirror-cursor { 261 | visibility: hidden; 262 | } 263 | } 264 | -------------------------------------------------------------------------------- /lab/vendor/codemirror/css.js: -------------------------------------------------------------------------------- 1 | CodeMirror.defineMode("css", function(config, parserConfig) { 2 | "use strict"; 3 | 4 | if (!parserConfig.propertyKeywords) parserConfig = CodeMirror.resolveMode("text/css"); 5 | 6 | var indentUnit = config.indentUnit || config.tabSize || 2, 7 | hooks = parserConfig.hooks || {}, 8 | atMediaTypes = parserConfig.atMediaTypes || {}, 9 | atMediaFeatures = parserConfig.atMediaFeatures || {}, 10 | propertyKeywords = parserConfig.propertyKeywords || {}, 11 | colorKeywords = parserConfig.colorKeywords || {}, 12 | valueKeywords = parserConfig.valueKeywords || {}, 13 | allowNested = !!parserConfig.allowNested, 14 | type = null; 15 | 16 | function ret(style, tp) { type = tp; return style; } 17 | 18 | function tokenBase(stream, state) { 19 | var ch = stream.next(); 20 | if (hooks[ch]) { 21 | // result[0] is style and result[1] is type 22 | var result = hooks[ch](stream, state); 23 | if (result !== false) return result; 24 | } 25 | if (ch == "@") {stream.eatWhile(/[\w\\\-]/); return ret("def", stream.current());} 26 | else if (ch == "=") ret(null, "compare"); 27 | else if ((ch == "~" || ch == "|") && stream.eat("=")) return ret(null, "compare"); 28 | else if (ch == "\"" || ch == "'") { 29 | state.tokenize = tokenString(ch); 30 | return state.tokenize(stream, state); 31 | } 32 | else if (ch == "#") { 33 | stream.eatWhile(/[\w\\\-]/); 34 | return ret("atom", "hash"); 35 | } 36 | else if (ch == "!") { 37 | stream.match(/^\s*\w*/); 38 | return ret("keyword", "important"); 39 | } 40 | else if (/\d/.test(ch) || ch == "." && stream.eat(/\d/)) { 41 | stream.eatWhile(/[\w.%]/); 42 | return ret("number", "unit"); 43 | } 44 | else if (ch === "-") { 45 | if (/\d/.test(stream.peek())) { 46 | stream.eatWhile(/[\w.%]/); 47 | return ret("number", "unit"); 48 | } else if (stream.match(/^[^-]+-/)) { 49 | return ret("meta", "meta"); 50 | } 51 | } 52 | else if (/[,+>*\/]/.test(ch)) { 53 | return ret(null, "select-op"); 54 | } 55 | else if (ch == "." && stream.match(/^-?[_a-z][_a-z0-9-]*/i)) { 56 | return ret("qualifier", "qualifier"); 57 | } 58 | else if (ch == ":") { 59 | return ret("operator", ch); 60 | } 61 | else if (/[;{}\[\]\(\)]/.test(ch)) { 62 | return ret(null, ch); 63 | } 64 | else if (ch == "u" && stream.match("rl(")) { 65 | stream.backUp(1); 66 | state.tokenize = tokenParenthesized; 67 | return ret("property", "variable"); 68 | } 69 | else { 70 | stream.eatWhile(/[\w\\\-]/); 71 | return ret("property", "variable"); 72 | } 73 | } 74 | 75 | function tokenString(quote, nonInclusive) { 76 | return function(stream, state) { 77 | var escaped = false, ch; 78 | while ((ch = stream.next()) != null) { 79 | if (ch == quote && !escaped) 80 | break; 81 | escaped = !escaped && ch == "\\"; 82 | } 83 | if (!escaped) { 84 | if (nonInclusive) stream.backUp(1); 85 | state.tokenize = tokenBase; 86 | } 87 | return ret("string", "string"); 88 | }; 89 | } 90 | 91 | function tokenParenthesized(stream, state) { 92 | stream.next(); // Must be '(' 93 | if (!stream.match(/\s*[\"\']/, false)) 94 | state.tokenize = tokenString(")", true); 95 | else 96 | state.tokenize = tokenBase; 97 | return ret(null, "("); 98 | } 99 | 100 | return { 101 | startState: function(base) { 102 | return {tokenize: tokenBase, 103 | baseIndent: base || 0, 104 | stack: [], 105 | lastToken: null}; 106 | }, 107 | 108 | token: function(stream, state) { 109 | 110 | // Use these terms when applicable (see http://www.xanthir.com/blog/b4E50) 111 | // 112 | // rule** or **ruleset: 113 | // A selector + braces combo, or an at-rule. 114 | // 115 | // declaration block: 116 | // A sequence of declarations. 117 | // 118 | // declaration: 119 | // A property + colon + value combo. 120 | // 121 | // property value: 122 | // The entire value of a property. 123 | // 124 | // component value: 125 | // A single piece of a property value. Like the 5px in 126 | // text-shadow: 0 0 5px blue;. Can also refer to things that are 127 | // multiple terms, like the 1-4 terms that make up the background-size 128 | // portion of the background shorthand. 129 | // 130 | // term: 131 | // The basic unit of author-facing CSS, like a single number (5), 132 | // dimension (5px), string ("foo"), or function. Officially defined 133 | // by the CSS 2.1 grammar (look for the 'term' production) 134 | // 135 | // 136 | // simple selector: 137 | // A single atomic selector, like a type selector, an attr selector, a 138 | // class selector, etc. 139 | // 140 | // compound selector: 141 | // One or more simple selectors without a combinator. div.example is 142 | // compound, div > .example is not. 143 | // 144 | // complex selector: 145 | // One or more compound selectors chained with combinators. 146 | // 147 | // combinator: 148 | // The parts of selectors that express relationships. There are four 149 | // currently - the space (descendant combinator), the greater-than 150 | // bracket (child combinator), the plus sign (next sibling combinator), 151 | // and the tilda (following sibling combinator). 152 | // 153 | // sequence of selectors: 154 | // One or more of the named type of selector chained with commas. 155 | 156 | state.tokenize = state.tokenize || tokenBase; 157 | if (state.tokenize == tokenBase && stream.eatSpace()) return null; 158 | var style = state.tokenize(stream, state); 159 | if (style && typeof style != "string") style = ret(style[0], style[1]); 160 | 161 | // Changing style returned based on context 162 | var context = state.stack[state.stack.length-1]; 163 | if (style == "variable") { 164 | if (type == "variable-definition") state.stack.push("propertyValue"); 165 | return state.lastToken = "variable-2"; 166 | } else if (style == "property") { 167 | var word = stream.current().toLowerCase(); 168 | if (context == "propertyValue") { 169 | if (valueKeywords.hasOwnProperty(word)) { 170 | style = "string-2"; 171 | } else if (colorKeywords.hasOwnProperty(word)) { 172 | style = "keyword"; 173 | } else { 174 | style = "variable-2"; 175 | } 176 | } else if (context == "rule") { 177 | if (!propertyKeywords.hasOwnProperty(word)) { 178 | style += " error"; 179 | } 180 | } else if (context == "block") { 181 | // if a value is present in both property, value, or color, the order 182 | // of preference is property -> color -> value 183 | if (propertyKeywords.hasOwnProperty(word)) { 184 | style = "property"; 185 | } else if (colorKeywords.hasOwnProperty(word)) { 186 | style = "keyword"; 187 | } else if (valueKeywords.hasOwnProperty(word)) { 188 | style = "string-2"; 189 | } else { 190 | style = "tag"; 191 | } 192 | } else if (!context || context == "@media{") { 193 | style = "tag"; 194 | } else if (context == "@media") { 195 | if (atMediaTypes[stream.current()]) { 196 | style = "attribute"; // Known attribute 197 | } else if (/^(only|not)$/.test(word)) { 198 | style = "keyword"; 199 | } else if (word == "and") { 200 | style = "error"; // "and" is only allowed in @mediaType 201 | } else if (atMediaFeatures.hasOwnProperty(word)) { 202 | style = "error"; // Known property, should be in @mediaType( 203 | } else { 204 | // Unknown, expecting keyword or attribute, assuming attribute 205 | style = "attribute error"; 206 | } 207 | } else if (context == "@mediaType") { 208 | if (atMediaTypes.hasOwnProperty(word)) { 209 | style = "attribute"; 210 | } else if (word == "and") { 211 | style = "operator"; 212 | } else if (/^(only|not)$/.test(word)) { 213 | style = "error"; // Only allowed in @media 214 | } else { 215 | // Unknown attribute or property, but expecting property (preceded 216 | // by "and"). Should be in parentheses 217 | style = "error"; 218 | } 219 | } else if (context == "@mediaType(") { 220 | if (propertyKeywords.hasOwnProperty(word)) { 221 | // do nothing, remains "property" 222 | } else if (atMediaTypes.hasOwnProperty(word)) { 223 | style = "error"; // Known property, should be in parentheses 224 | } else if (word == "and") { 225 | style = "operator"; 226 | } else if (/^(only|not)$/.test(word)) { 227 | style = "error"; // Only allowed in @media 228 | } else { 229 | style += " error"; 230 | } 231 | } else if (context == "@import") { 232 | style = "tag"; 233 | } else { 234 | style = "error"; 235 | } 236 | } else if (style == "atom") { 237 | if(!context || context == "@media{" || context == "block") { 238 | style = "builtin"; 239 | } else if (context == "propertyValue") { 240 | if (!/^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/.test(stream.current())) { 241 | style += " error"; 242 | } 243 | } else { 244 | style = "error"; 245 | } 246 | } else if (context == "@media" && type == "{") { 247 | style = "error"; 248 | } 249 | 250 | // Push/pop context stack 251 | if (type == "{") { 252 | if (context == "@media" || context == "@mediaType") { 253 | state.stack[state.stack.length-1] = "@media{"; 254 | } 255 | else { 256 | var newContext = allowNested ? "block" : "rule"; 257 | state.stack.push(newContext); 258 | } 259 | } 260 | else if (type == "}") { 261 | if (context == "interpolation") style = "operator"; 262 | // Pop off end of array until { is reached 263 | while(state.stack.length){ 264 | var removed = state.stack.pop(); 265 | if(removed.indexOf("{") > -1){ 266 | break; 267 | } 268 | } 269 | } 270 | else if (type == "interpolation") state.stack.push("interpolation"); 271 | else if (type == "@media") state.stack.push("@media"); 272 | else if (type == "@import") state.stack.push("@import"); 273 | else if (context == "@media" && /\b(keyword|attribute)\b/.test(style)) 274 | state.stack[state.stack.length-1] = "@mediaType"; 275 | else if (context == "@mediaType" && stream.current() == ",") 276 | state.stack[state.stack.length-1] = "@media"; 277 | else if (type == "(") { 278 | if (context == "@media" || context == "@mediaType") { 279 | // Make sure @mediaType is used to avoid error on { 280 | state.stack[state.stack.length-1] = "@mediaType"; 281 | state.stack.push("@mediaType("); 282 | } 283 | else state.stack.push("("); 284 | } 285 | else if (type == ")") { 286 | // Pop off end of array until ( is reached 287 | while(state.stack.length){ 288 | var removed = state.stack.pop(); 289 | if(removed.indexOf("(") > -1){ 290 | break; 291 | } 292 | } 293 | } 294 | else if (type == ":" && state.lastToken == "property") state.stack.push("propertyValue"); 295 | else if (context == "propertyValue" && type == ";") state.stack.pop(); 296 | else if (context == "@import" && type == ";") state.stack.pop(); 297 | 298 | return state.lastToken = style; 299 | }, 300 | 301 | indent: function(state, textAfter) { 302 | var n = state.stack.length; 303 | if (/^\}/.test(textAfter)) 304 | n -= state.stack[n-1] == "propertyValue" ? 2 : 1; 305 | return state.baseIndent + n * indentUnit; 306 | }, 307 | 308 | electricChars: "}", 309 | blockCommentStart: "/*", 310 | blockCommentEnd: "*/", 311 | fold: "brace" 312 | }; 313 | }); 314 | 315 | (function() { 316 | function keySet(array) { 317 | var keys = {}; 318 | for (var i = 0; i < array.length; ++i) { 319 | keys[array[i]] = true; 320 | } 321 | return keys; 322 | } 323 | 324 | var atMediaTypes = keySet([ 325 | "all", "aural", "braille", "handheld", "print", "projection", "screen", 326 | "tty", "tv", "embossed" 327 | ]); 328 | 329 | var atMediaFeatures = keySet([ 330 | "width", "min-width", "max-width", "height", "min-height", "max-height", 331 | "device-width", "min-device-width", "max-device-width", "device-height", 332 | "min-device-height", "max-device-height", "aspect-ratio", 333 | "min-aspect-ratio", "max-aspect-ratio", "device-aspect-ratio", 334 | "min-device-aspect-ratio", "max-device-aspect-ratio", "color", "min-color", 335 | "max-color", "color-index", "min-color-index", "max-color-index", 336 | "monochrome", "min-monochrome", "max-monochrome", "resolution", 337 | "min-resolution", "max-resolution", "scan", "grid" 338 | ]); 339 | 340 | var propertyKeywords = keySet([ 341 | "align-content", "align-items", "align-self", "alignment-adjust", 342 | "alignment-baseline", "anchor-point", "animation", "animation-delay", 343 | "animation-direction", "animation-duration", "animation-iteration-count", 344 | "animation-name", "animation-play-state", "animation-timing-function", 345 | "appearance", "azimuth", "backface-visibility", "background", 346 | "background-attachment", "background-clip", "background-color", 347 | "background-image", "background-origin", "background-position", 348 | "background-repeat", "background-size", "baseline-shift", "binding", 349 | "bleed", "bookmark-label", "bookmark-level", "bookmark-state", 350 | "bookmark-target", "border", "border-bottom", "border-bottom-color", 351 | "border-bottom-left-radius", "border-bottom-right-radius", 352 | "border-bottom-style", "border-bottom-width", "border-collapse", 353 | "border-color", "border-image", "border-image-outset", 354 | "border-image-repeat", "border-image-slice", "border-image-source", 355 | "border-image-width", "border-left", "border-left-color", 356 | "border-left-style", "border-left-width", "border-radius", "border-right", 357 | "border-right-color", "border-right-style", "border-right-width", 358 | "border-spacing", "border-style", "border-top", "border-top-color", 359 | "border-top-left-radius", "border-top-right-radius", "border-top-style", 360 | "border-top-width", "border-width", "bottom", "box-decoration-break", 361 | "box-shadow", "box-sizing", "break-after", "break-before", "break-inside", 362 | "caption-side", "clear", "clip", "color", "color-profile", "column-count", 363 | "column-fill", "column-gap", "column-rule", "column-rule-color", 364 | "column-rule-style", "column-rule-width", "column-span", "column-width", 365 | "columns", "content", "counter-increment", "counter-reset", "crop", "cue", 366 | "cue-after", "cue-before", "cursor", "direction", "display", 367 | "dominant-baseline", "drop-initial-after-adjust", 368 | "drop-initial-after-align", "drop-initial-before-adjust", 369 | "drop-initial-before-align", "drop-initial-size", "drop-initial-value", 370 | "elevation", "empty-cells", "fit", "fit-position", "flex", "flex-basis", 371 | "flex-direction", "flex-flow", "flex-grow", "flex-shrink", "flex-wrap", 372 | "float", "float-offset", "flow-from", "flow-into", "font", "font-feature-settings", 373 | "font-family", "font-kerning", "font-language-override", "font-size", "font-size-adjust", 374 | "font-stretch", "font-style", "font-synthesis", "font-variant", 375 | "font-variant-alternates", "font-variant-caps", "font-variant-east-asian", 376 | "font-variant-ligatures", "font-variant-numeric", "font-variant-position", 377 | "font-weight", "grid-cell", "grid-column", "grid-column-align", 378 | "grid-column-sizing", "grid-column-span", "grid-columns", "grid-flow", 379 | "grid-row", "grid-row-align", "grid-row-sizing", "grid-row-span", 380 | "grid-rows", "grid-template", "hanging-punctuation", "height", "hyphens", 381 | "icon", "image-orientation", "image-rendering", "image-resolution", 382 | "inline-box-align", "justify-content", "left", "letter-spacing", 383 | "line-break", "line-height", "line-stacking", "line-stacking-ruby", 384 | "line-stacking-shift", "line-stacking-strategy", "list-style", 385 | "list-style-image", "list-style-position", "list-style-type", "margin", 386 | "margin-bottom", "margin-left", "margin-right", "margin-top", 387 | "marker-offset", "marks", "marquee-direction", "marquee-loop", 388 | "marquee-play-count", "marquee-speed", "marquee-style", "max-height", 389 | "max-width", "min-height", "min-width", "move-to", "nav-down", "nav-index", 390 | "nav-left", "nav-right", "nav-up", "opacity", "order", "orphans", "outline", 391 | "outline-color", "outline-offset", "outline-style", "outline-width", 392 | "overflow", "overflow-style", "overflow-wrap", "overflow-x", "overflow-y", 393 | "padding", "padding-bottom", "padding-left", "padding-right", "padding-top", 394 | "page", "page-break-after", "page-break-before", "page-break-inside", 395 | "page-policy", "pause", "pause-after", "pause-before", "perspective", 396 | "perspective-origin", "pitch", "pitch-range", "play-during", "position", 397 | "presentation-level", "punctuation-trim", "quotes", "region-break-after", 398 | "region-break-before", "region-break-inside", "region-fragment", 399 | "rendering-intent", "resize", "rest", "rest-after", "rest-before", "richness", 400 | "right", "rotation", "rotation-point", "ruby-align", "ruby-overhang", 401 | "ruby-position", "ruby-span", "shape-inside", "shape-outside", "size", 402 | "speak", "speak-as", "speak-header", 403 | "speak-numeral", "speak-punctuation", "speech-rate", "stress", "string-set", 404 | "tab-size", "table-layout", "target", "target-name", "target-new", 405 | "target-position", "text-align", "text-align-last", "text-decoration", 406 | "text-decoration-color", "text-decoration-line", "text-decoration-skip", 407 | "text-decoration-style", "text-emphasis", "text-emphasis-color", 408 | "text-emphasis-position", "text-emphasis-style", "text-height", 409 | "text-indent", "text-justify", "text-outline", "text-overflow", "text-shadow", 410 | "text-size-adjust", "text-space-collapse", "text-transform", "text-underline-position", 411 | "text-wrap", "top", "transform", "transform-origin", "transform-style", 412 | "transition", "transition-delay", "transition-duration", 413 | "transition-property", "transition-timing-function", "unicode-bidi", 414 | "vertical-align", "visibility", "voice-balance", "voice-duration", 415 | "voice-family", "voice-pitch", "voice-range", "voice-rate", "voice-stress", 416 | "voice-volume", "volume", "white-space", "widows", "width", "word-break", 417 | "word-spacing", "word-wrap", "z-index", "zoom", 418 | // SVG-specific 419 | "clip-path", "clip-rule", "mask", "enable-background", "filter", "flood-color", 420 | "flood-opacity", "lighting-color", "stop-color", "stop-opacity", "pointer-events", 421 | "color-interpolation", "color-interpolation-filters", "color-profile", 422 | "color-rendering", "fill", "fill-opacity", "fill-rule", "image-rendering", 423 | "marker", "marker-end", "marker-mid", "marker-start", "shape-rendering", "stroke", 424 | "stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin", 425 | "stroke-miterlimit", "stroke-opacity", "stroke-width", "text-rendering", 426 | "baseline-shift", "dominant-baseline", "glyph-orientation-horizontal", 427 | "glyph-orientation-vertical", "kerning", "text-anchor", "writing-mode" 428 | ]); 429 | 430 | var colorKeywords = keySet([ 431 | "aliceblue", "antiquewhite", "aqua", "aquamarine", "azure", "beige", 432 | "bisque", "black", "blanchedalmond", "blue", "blueviolet", "brown", 433 | "burlywood", "cadetblue", "chartreuse", "chocolate", "coral", "cornflowerblue", 434 | "cornsilk", "crimson", "cyan", "darkblue", "darkcyan", "darkgoldenrod", 435 | "darkgray", "darkgreen", "darkkhaki", "darkmagenta", "darkolivegreen", 436 | "darkorange", "darkorchid", "darkred", "darksalmon", "darkseagreen", 437 | "darkslateblue", "darkslategray", "darkturquoise", "darkviolet", 438 | "deeppink", "deepskyblue", "dimgray", "dodgerblue", "firebrick", 439 | "floralwhite", "forestgreen", "fuchsia", "gainsboro", "ghostwhite", 440 | "gold", "goldenrod", "gray", "grey", "green", "greenyellow", "honeydew", 441 | "hotpink", "indianred", "indigo", "ivory", "khaki", "lavender", 442 | "lavenderblush", "lawngreen", "lemonchiffon", "lightblue", "lightcoral", 443 | "lightcyan", "lightgoldenrodyellow", "lightgray", "lightgreen", "lightpink", 444 | "lightsalmon", "lightseagreen", "lightskyblue", "lightslategray", 445 | "lightsteelblue", "lightyellow", "lime", "limegreen", "linen", "magenta", 446 | "maroon", "mediumaquamarine", "mediumblue", "mediumorchid", "mediumpurple", 447 | "mediumseagreen", "mediumslateblue", "mediumspringgreen", "mediumturquoise", 448 | "mediumvioletred", "midnightblue", "mintcream", "mistyrose", "moccasin", 449 | "navajowhite", "navy", "oldlace", "olive", "olivedrab", "orange", "orangered", 450 | "orchid", "palegoldenrod", "palegreen", "paleturquoise", "palevioletred", 451 | "papayawhip", "peachpuff", "peru", "pink", "plum", "powderblue", 452 | "purple", "red", "rosybrown", "royalblue", "saddlebrown", "salmon", 453 | "sandybrown", "seagreen", "seashell", "sienna", "silver", "skyblue", 454 | "slateblue", "slategray", "snow", "springgreen", "steelblue", "tan", 455 | "teal", "thistle", "tomato", "turquoise", "violet", "wheat", "white", 456 | "whitesmoke", "yellow", "yellowgreen" 457 | ]); 458 | 459 | var valueKeywords = keySet([ 460 | "above", "absolute", "activeborder", "activecaption", "afar", 461 | "after-white-space", "ahead", "alias", "all", "all-scroll", "alternate", 462 | "always", "amharic", "amharic-abegede", "antialiased", "appworkspace", 463 | "arabic-indic", "armenian", "asterisks", "auto", "avoid", "avoid-column", "avoid-page", 464 | "avoid-region", "background", "backwards", "baseline", "below", "bidi-override", "binary", 465 | "bengali", "blink", "block", "block-axis", "bold", "bolder", "border", "border-box", 466 | "both", "bottom", "break", "break-all", "break-word", "button", "button-bevel", 467 | "buttonface", "buttonhighlight", "buttonshadow", "buttontext", "cambodian", 468 | "capitalize", "caps-lock-indicator", "caption", "captiontext", "caret", 469 | "cell", "center", "checkbox", "circle", "cjk-earthly-branch", 470 | "cjk-heavenly-stem", "cjk-ideographic", "clear", "clip", "close-quote", 471 | "col-resize", "collapse", "column", "compact", "condensed", "contain", "content", 472 | "content-box", "context-menu", "continuous", "copy", "cover", "crop", 473 | "cross", "crosshair", "currentcolor", "cursive", "dashed", "decimal", 474 | "decimal-leading-zero", "default", "default-button", "destination-atop", 475 | "destination-in", "destination-out", "destination-over", "devanagari", 476 | "disc", "discard", "document", "dot-dash", "dot-dot-dash", "dotted", 477 | "double", "down", "e-resize", "ease", "ease-in", "ease-in-out", "ease-out", 478 | "element", "ellipse", "ellipsis", "embed", "end", "ethiopic", "ethiopic-abegede", 479 | "ethiopic-abegede-am-et", "ethiopic-abegede-gez", "ethiopic-abegede-ti-er", 480 | "ethiopic-abegede-ti-et", "ethiopic-halehame-aa-er", 481 | "ethiopic-halehame-aa-et", "ethiopic-halehame-am-et", 482 | "ethiopic-halehame-gez", "ethiopic-halehame-om-et", 483 | "ethiopic-halehame-sid-et", "ethiopic-halehame-so-et", 484 | "ethiopic-halehame-ti-er", "ethiopic-halehame-ti-et", 485 | "ethiopic-halehame-tig", "ew-resize", "expanded", "extra-condensed", 486 | "extra-expanded", "fantasy", "fast", "fill", "fixed", "flat", "footnotes", 487 | "forwards", "from", "geometricPrecision", "georgian", "graytext", "groove", 488 | "gujarati", "gurmukhi", "hand", "hangul", "hangul-consonant", "hebrew", 489 | "help", "hidden", "hide", "higher", "highlight", "highlighttext", 490 | "hiragana", "hiragana-iroha", "horizontal", "hsl", "hsla", "icon", "ignore", 491 | "inactiveborder", "inactivecaption", "inactivecaptiontext", "infinite", 492 | "infobackground", "infotext", "inherit", "initial", "inline", "inline-axis", 493 | "inline-block", "inline-table", "inset", "inside", "intrinsic", "invert", 494 | "italic", "justify", "kannada", "katakana", "katakana-iroha", "keep-all", "khmer", 495 | "landscape", "lao", "large", "larger", "left", "level", "lighter", 496 | "line-through", "linear", "lines", "list-item", "listbox", "listitem", 497 | "local", "logical", "loud", "lower", "lower-alpha", "lower-armenian", 498 | "lower-greek", "lower-hexadecimal", "lower-latin", "lower-norwegian", 499 | "lower-roman", "lowercase", "ltr", "malayalam", "match", 500 | "media-controls-background", "media-current-time-display", 501 | "media-fullscreen-button", "media-mute-button", "media-play-button", 502 | "media-return-to-realtime-button", "media-rewind-button", 503 | "media-seek-back-button", "media-seek-forward-button", "media-slider", 504 | "media-sliderthumb", "media-time-remaining-display", "media-volume-slider", 505 | "media-volume-slider-container", "media-volume-sliderthumb", "medium", 506 | "menu", "menulist", "menulist-button", "menulist-text", 507 | "menulist-textfield", "menutext", "message-box", "middle", "min-intrinsic", 508 | "mix", "mongolian", "monospace", "move", "multiple", "myanmar", "n-resize", 509 | "narrower", "ne-resize", "nesw-resize", "no-close-quote", "no-drop", 510 | "no-open-quote", "no-repeat", "none", "normal", "not-allowed", "nowrap", 511 | "ns-resize", "nw-resize", "nwse-resize", "oblique", "octal", "open-quote", 512 | "optimizeLegibility", "optimizeSpeed", "oriya", "oromo", "outset", 513 | "outside", "outside-shape", "overlay", "overline", "padding", "padding-box", 514 | "painted", "page", "paused", "persian", "plus-darker", "plus-lighter", "pointer", 515 | "polygon", "portrait", "pre", "pre-line", "pre-wrap", "preserve-3d", "progress", "push-button", 516 | "radio", "read-only", "read-write", "read-write-plaintext-only", "rectangle", "region", 517 | "relative", "repeat", "repeat-x", "repeat-y", "reset", "reverse", "rgb", "rgba", 518 | "ridge", "right", "round", "row-resize", "rtl", "run-in", "running", 519 | "s-resize", "sans-serif", "scroll", "scrollbar", "se-resize", "searchfield", 520 | "searchfield-cancel-button", "searchfield-decoration", 521 | "searchfield-results-button", "searchfield-results-decoration", 522 | "semi-condensed", "semi-expanded", "separate", "serif", "show", "sidama", 523 | "single", "skip-white-space", "slide", "slider-horizontal", 524 | "slider-vertical", "sliderthumb-horizontal", "sliderthumb-vertical", "slow", 525 | "small", "small-caps", "small-caption", "smaller", "solid", "somali", 526 | "source-atop", "source-in", "source-out", "source-over", "space", "square", 527 | "square-button", "start", "static", "status-bar", "stretch", "stroke", 528 | "sub", "subpixel-antialiased", "super", "sw-resize", "table", 529 | "table-caption", "table-cell", "table-column", "table-column-group", 530 | "table-footer-group", "table-header-group", "table-row", "table-row-group", 531 | "telugu", "text", "text-bottom", "text-top", "textarea", "textfield", "thai", 532 | "thick", "thin", "threeddarkshadow", "threedface", "threedhighlight", 533 | "threedlightshadow", "threedshadow", "tibetan", "tigre", "tigrinya-er", 534 | "tigrinya-er-abegede", "tigrinya-et", "tigrinya-et-abegede", "to", "top", 535 | "transparent", "ultra-condensed", "ultra-expanded", "underline", "up", 536 | "upper-alpha", "upper-armenian", "upper-greek", "upper-hexadecimal", 537 | "upper-latin", "upper-norwegian", "upper-roman", "uppercase", "urdu", "url", 538 | "vertical", "vertical-text", "visible", "visibleFill", "visiblePainted", 539 | "visibleStroke", "visual", "w-resize", "wait", "wave", "wider", 540 | "window", "windowframe", "windowtext", "x-large", "x-small", "xor", 541 | "xx-large", "xx-small" 542 | ]); 543 | 544 | function tokenCComment(stream, state) { 545 | var maybeEnd = false, ch; 546 | while ((ch = stream.next()) != null) { 547 | if (maybeEnd && ch == "/") { 548 | state.tokenize = null; 549 | break; 550 | } 551 | maybeEnd = (ch == "*"); 552 | } 553 | return ["comment", "comment"]; 554 | } 555 | 556 | CodeMirror.defineMIME("text/css", { 557 | atMediaTypes: atMediaTypes, 558 | atMediaFeatures: atMediaFeatures, 559 | propertyKeywords: propertyKeywords, 560 | colorKeywords: colorKeywords, 561 | valueKeywords: valueKeywords, 562 | hooks: { 563 | "<": function(stream, state) { 564 | function tokenSGMLComment(stream, state) { 565 | var dashes = 0, ch; 566 | while ((ch = stream.next()) != null) { 567 | if (dashes >= 2 && ch == ">") { 568 | state.tokenize = null; 569 | break; 570 | } 571 | dashes = (ch == "-") ? dashes + 1 : 0; 572 | } 573 | return ["comment", "comment"]; 574 | } 575 | if (stream.eat("!")) { 576 | state.tokenize = tokenSGMLComment; 577 | return tokenSGMLComment(stream, state); 578 | } 579 | }, 580 | "/": function(stream, state) { 581 | if (stream.eat("*")) { 582 | state.tokenize = tokenCComment; 583 | return tokenCComment(stream, state); 584 | } 585 | return false; 586 | } 587 | }, 588 | name: "css" 589 | }); 590 | 591 | CodeMirror.defineMIME("text/x-scss", { 592 | atMediaTypes: atMediaTypes, 593 | atMediaFeatures: atMediaFeatures, 594 | propertyKeywords: propertyKeywords, 595 | colorKeywords: colorKeywords, 596 | valueKeywords: valueKeywords, 597 | allowNested: true, 598 | hooks: { 599 | ":": function(stream) { 600 | if (stream.match(/\s*{/)) { 601 | return [null, "{"]; 602 | } 603 | return false; 604 | }, 605 | "$": function(stream) { 606 | stream.match(/^[\w-]+/); 607 | if (stream.peek() == ":") { 608 | return ["variable", "variable-definition"]; 609 | } 610 | return ["variable", "variable"]; 611 | }, 612 | ",": function(_stream, state) { 613 | if (state.stack[state.stack.length - 1] == "propertyValue") { 614 | return ["operator", ";"]; 615 | } 616 | }, 617 | "/": function(stream, state) { 618 | if (stream.eat("/")) { 619 | stream.skipToEnd(); 620 | return ["comment", "comment"]; 621 | } else if (stream.eat("*")) { 622 | state.tokenize = tokenCComment; 623 | return tokenCComment(stream, state); 624 | } else { 625 | return ["operator", "operator"]; 626 | } 627 | }, 628 | "#": function(stream) { 629 | if (stream.eat("{")) { 630 | return ["operator", "interpolation"]; 631 | } else { 632 | stream.eatWhile(/[\w\\\-]/); 633 | return ["atom", "hash"]; 634 | } 635 | } 636 | }, 637 | name: "css" 638 | }); 639 | })(); 640 | -------------------------------------------------------------------------------- /lab/vendor/codemirror/htmlmixed.js: -------------------------------------------------------------------------------- 1 | CodeMirror.defineMode("htmlmixed", function(config, parserConfig) { 2 | var htmlMode = CodeMirror.getMode(config, {name: "xml", htmlMode: true}); 3 | var cssMode = CodeMirror.getMode(config, "css"); 4 | 5 | var scriptTypes = [], scriptTypesConf = parserConfig && parserConfig.scriptTypes; 6 | scriptTypes.push({matches: /^(?:text|application)\/(?:x-)?(?:java|ecma)script$|^$/i, 7 | mode: CodeMirror.getMode(config, "javascript")}); 8 | if (scriptTypesConf) for (var i = 0; i < scriptTypesConf.length; ++i) { 9 | var conf = scriptTypesConf[i]; 10 | scriptTypes.push({matches: conf.matches, mode: conf.mode && CodeMirror.getMode(config, conf.mode)}); 11 | } 12 | scriptTypes.push({matches: /./, 13 | mode: CodeMirror.getMode(config, "text/plain")}); 14 | 15 | function html(stream, state) { 16 | var tagName = state.htmlState.tagName; 17 | var style = htmlMode.token(stream, state.htmlState); 18 | if (tagName == "script" && /\btag\b/.test(style) && stream.current() == ">") { 19 | // Script block: mode to change to depends on type attribute 20 | var scriptType = stream.string.slice(Math.max(0, stream.pos - 100), stream.pos).match(/\btype\s*=\s*("[^"]+"|'[^']+'|\S+)[^<]*$/i); 21 | scriptType = scriptType ? scriptType[1] : ""; 22 | if (scriptType && /[\"\']/.test(scriptType.charAt(0))) scriptType = scriptType.slice(1, scriptType.length - 1); 23 | for (var i = 0; i < scriptTypes.length; ++i) { 24 | var tp = scriptTypes[i]; 25 | if (typeof tp.matches == "string" ? scriptType == tp.matches : tp.matches.test(scriptType)) { 26 | if (tp.mode) { 27 | state.token = script; 28 | state.localMode = tp.mode; 29 | state.localState = tp.mode.startState && tp.mode.startState(htmlMode.indent(state.htmlState, "")); 30 | } 31 | break; 32 | } 33 | } 34 | } else if (tagName == "style" && /\btag\b/.test(style) && stream.current() == ">") { 35 | state.token = css; 36 | state.localMode = cssMode; 37 | state.localState = cssMode.startState(htmlMode.indent(state.htmlState, "")); 38 | } 39 | return style; 40 | } 41 | function maybeBackup(stream, pat, style) { 42 | var cur = stream.current(); 43 | var close = cur.search(pat), m; 44 | if (close > -1) stream.backUp(cur.length - close); 45 | else if (m = cur.match(/<\/?$/)) { 46 | stream.backUp(cur.length); 47 | if (!stream.match(pat, false)) stream.match(cur[0]); 48 | } 49 | return style; 50 | } 51 | function script(stream, state) { 52 | if (stream.match(/^<\/\s*script\s*>/i, false)) { 53 | state.token = html; 54 | state.localState = state.localMode = null; 55 | return html(stream, state); 56 | } 57 | return maybeBackup(stream, /<\/\s*script\s*>/, 58 | state.localMode.token(stream, state.localState)); 59 | } 60 | function css(stream, state) { 61 | if (stream.match(/^<\/\s*style\s*>/i, false)) { 62 | state.token = html; 63 | state.localState = state.localMode = null; 64 | return html(stream, state); 65 | } 66 | return maybeBackup(stream, /<\/\s*style\s*>/, 67 | cssMode.token(stream, state.localState)); 68 | } 69 | 70 | return { 71 | startState: function() { 72 | var state = htmlMode.startState(); 73 | return {token: html, localMode: null, localState: null, htmlState: state}; 74 | }, 75 | 76 | copyState: function(state) { 77 | if (state.localState) 78 | var local = CodeMirror.copyState(state.localMode, state.localState); 79 | return {token: state.token, localMode: state.localMode, localState: local, 80 | htmlState: CodeMirror.copyState(htmlMode, state.htmlState)}; 81 | }, 82 | 83 | token: function(stream, state) { 84 | return state.token(stream, state); 85 | }, 86 | 87 | indent: function(state, textAfter) { 88 | if (!state.localMode || /^\s*<\//.test(textAfter)) 89 | return htmlMode.indent(state.htmlState, textAfter); 90 | else if (state.localMode.indent) 91 | return state.localMode.indent(state.localState, textAfter); 92 | else 93 | return CodeMirror.Pass; 94 | }, 95 | 96 | electricChars: "/{}:", 97 | 98 | innerMode: function(state) { 99 | return {state: state.localState || state.htmlState, mode: state.localMode || htmlMode}; 100 | } 101 | }; 102 | }, "xml", "javascript", "css"); 103 | 104 | CodeMirror.defineMIME("text/html", "htmlmixed"); 105 | -------------------------------------------------------------------------------- /lab/vendor/codemirror/javascript.js: -------------------------------------------------------------------------------- 1 | // TODO actually recognize syntax of TypeScript constructs 2 | 3 | CodeMirror.defineMode("javascript", function(config, parserConfig) { 4 | var indentUnit = config.indentUnit; 5 | var statementIndent = parserConfig.statementIndent; 6 | var jsonMode = parserConfig.json; 7 | var isTS = parserConfig.typescript; 8 | 9 | // Tokenizer 10 | 11 | var keywords = function(){ 12 | function kw(type) {return {type: type, style: "keyword"};} 13 | var A = kw("keyword a"), B = kw("keyword b"), C = kw("keyword c"); 14 | var operator = kw("operator"), atom = {type: "atom", style: "atom"}; 15 | 16 | var jsKeywords = { 17 | "if": kw("if"), "while": A, "with": A, "else": B, "do": B, "try": B, "finally": B, 18 | "return": C, "break": C, "continue": C, "new": C, "delete": C, "throw": C, 19 | "var": kw("var"), "const": kw("var"), "let": kw("var"), 20 | "function": kw("function"), "catch": kw("catch"), 21 | "for": kw("for"), "switch": kw("switch"), "case": kw("case"), "default": kw("default"), 22 | "in": operator, "typeof": operator, "instanceof": operator, 23 | "true": atom, "false": atom, "null": atom, "undefined": atom, "NaN": atom, "Infinity": atom, 24 | "this": kw("this") 25 | }; 26 | 27 | // Extend the 'normal' keywords with the TypeScript language extensions 28 | if (isTS) { 29 | var type = {type: "variable", style: "variable-3"}; 30 | var tsKeywords = { 31 | // object-like things 32 | "interface": kw("interface"), 33 | "class": kw("class"), 34 | "extends": kw("extends"), 35 | "constructor": kw("constructor"), 36 | 37 | // scope modifiers 38 | "public": kw("public"), 39 | "private": kw("private"), 40 | "protected": kw("protected"), 41 | "static": kw("static"), 42 | 43 | "super": kw("super"), 44 | 45 | // types 46 | "string": type, "number": type, "bool": type, "any": type 47 | }; 48 | 49 | for (var attr in tsKeywords) { 50 | jsKeywords[attr] = tsKeywords[attr]; 51 | } 52 | } 53 | 54 | return jsKeywords; 55 | }(); 56 | 57 | var isOperatorChar = /[+\-*&%=<>!?|~^]/; 58 | 59 | function chain(stream, state, f) { 60 | state.tokenize = f; 61 | return f(stream, state); 62 | } 63 | 64 | function nextUntilUnescaped(stream, end) { 65 | var escaped = false, next; 66 | while ((next = stream.next()) != null) { 67 | if (next == end && !escaped) 68 | return false; 69 | escaped = !escaped && next == "\\"; 70 | } 71 | return escaped; 72 | } 73 | 74 | // Used as scratch variables to communicate multiple values without 75 | // consing up tons of objects. 76 | var type, content; 77 | function ret(tp, style, cont) { 78 | type = tp; content = cont; 79 | return style; 80 | } 81 | function jsTokenBase(stream, state) { 82 | var ch = stream.next(); 83 | if (ch == '"' || ch == "'") 84 | return chain(stream, state, jsTokenString(ch)); 85 | else if (ch == "." && stream.match(/^\d+(?:[eE][+\-]?\d+)?/)) 86 | return ret("number", "number"); 87 | else if (/[\[\]{}\(\),;\:\.]/.test(ch)) 88 | return ret(ch); 89 | else if (ch == "0" && stream.eat(/x/i)) { 90 | stream.eatWhile(/[\da-f]/i); 91 | return ret("number", "number"); 92 | } 93 | else if (/\d/.test(ch)) { 94 | stream.match(/^\d*(?:\.\d*)?(?:[eE][+\-]?\d+)?/); 95 | return ret("number", "number"); 96 | } 97 | else if (ch == "/") { 98 | if (stream.eat("*")) { 99 | return chain(stream, state, jsTokenComment); 100 | } 101 | else if (stream.eat("/")) { 102 | stream.skipToEnd(); 103 | return ret("comment", "comment"); 104 | } 105 | else if (state.lastType == "operator" || state.lastType == "keyword c" || 106 | /^[\[{}\(,;:]$/.test(state.lastType)) { 107 | nextUntilUnescaped(stream, "/"); 108 | stream.eatWhile(/[gimy]/); // 'y' is "sticky" option in Mozilla 109 | return ret("regexp", "string-2"); 110 | } 111 | else { 112 | stream.eatWhile(isOperatorChar); 113 | return ret("operator", null, stream.current()); 114 | } 115 | } 116 | else if (ch == "#") { 117 | stream.skipToEnd(); 118 | return ret("error", "error"); 119 | } 120 | else if (isOperatorChar.test(ch)) { 121 | stream.eatWhile(isOperatorChar); 122 | return ret("operator", null, stream.current()); 123 | } 124 | else { 125 | stream.eatWhile(/[\w\$_]/); 126 | var word = stream.current(), known = keywords.propertyIsEnumerable(word) && keywords[word]; 127 | return (known && state.lastType != ".") ? ret(known.type, known.style, word) : 128 | ret("variable", "variable", word); 129 | } 130 | } 131 | 132 | function jsTokenString(quote) { 133 | return function(stream, state) { 134 | if (!nextUntilUnescaped(stream, quote)) 135 | state.tokenize = jsTokenBase; 136 | return ret("string", "string"); 137 | }; 138 | } 139 | 140 | function jsTokenComment(stream, state) { 141 | var maybeEnd = false, ch; 142 | while (ch = stream.next()) { 143 | if (ch == "/" && maybeEnd) { 144 | state.tokenize = jsTokenBase; 145 | break; 146 | } 147 | maybeEnd = (ch == "*"); 148 | } 149 | return ret("comment", "comment"); 150 | } 151 | 152 | // Parser 153 | 154 | var atomicTypes = {"atom": true, "number": true, "variable": true, "string": true, "regexp": true, "this": true}; 155 | 156 | function JSLexical(indented, column, type, align, prev, info) { 157 | this.indented = indented; 158 | this.column = column; 159 | this.type = type; 160 | this.prev = prev; 161 | this.info = info; 162 | if (align != null) this.align = align; 163 | } 164 | 165 | function inScope(state, varname) { 166 | for (var v = state.localVars; v; v = v.next) 167 | if (v.name == varname) return true; 168 | } 169 | 170 | function parseJS(state, style, type, content, stream) { 171 | var cc = state.cc; 172 | // Communicate our context to the combinators. 173 | // (Less wasteful than consing up a hundred closures on every call.) 174 | cx.state = state; cx.stream = stream; cx.marked = null, cx.cc = cc; 175 | 176 | if (!state.lexical.hasOwnProperty("align")) 177 | state.lexical.align = true; 178 | 179 | while(true) { 180 | var combinator = cc.length ? cc.pop() : jsonMode ? expression : statement; 181 | if (combinator(type, content)) { 182 | while(cc.length && cc[cc.length - 1].lex) 183 | cc.pop()(); 184 | if (cx.marked) return cx.marked; 185 | if (type == "variable" && inScope(state, content)) return "variable-2"; 186 | return style; 187 | } 188 | } 189 | } 190 | 191 | // Combinator utils 192 | 193 | var cx = {state: null, column: null, marked: null, cc: null}; 194 | function pass() { 195 | for (var i = arguments.length - 1; i >= 0; i--) cx.cc.push(arguments[i]); 196 | } 197 | function cont() { 198 | pass.apply(null, arguments); 199 | return true; 200 | } 201 | function register(varname) { 202 | function inList(list) { 203 | for (var v = list; v; v = v.next) 204 | if (v.name == varname) return true; 205 | return false; 206 | } 207 | var state = cx.state; 208 | if (state.context) { 209 | cx.marked = "def"; 210 | if (inList(state.localVars)) return; 211 | state.localVars = {name: varname, next: state.localVars}; 212 | } else { 213 | if (inList(state.globalVars)) return; 214 | state.globalVars = {name: varname, next: state.globalVars}; 215 | } 216 | } 217 | 218 | // Combinators 219 | 220 | var defaultVars = {name: "this", next: {name: "arguments"}}; 221 | function pushcontext() { 222 | cx.state.context = {prev: cx.state.context, vars: cx.state.localVars}; 223 | cx.state.localVars = defaultVars; 224 | } 225 | function popcontext() { 226 | cx.state.localVars = cx.state.context.vars; 227 | cx.state.context = cx.state.context.prev; 228 | } 229 | function pushlex(type, info) { 230 | var result = function() { 231 | var state = cx.state, indent = state.indented; 232 | if (state.lexical.type == "stat") indent = state.lexical.indented; 233 | state.lexical = new JSLexical(indent, cx.stream.column(), type, null, state.lexical, info); 234 | }; 235 | result.lex = true; 236 | return result; 237 | } 238 | function poplex() { 239 | var state = cx.state; 240 | if (state.lexical.prev) { 241 | if (state.lexical.type == ")") 242 | state.indented = state.lexical.indented; 243 | state.lexical = state.lexical.prev; 244 | } 245 | } 246 | poplex.lex = true; 247 | 248 | function expect(wanted) { 249 | return function(type) { 250 | if (type == wanted) return cont(); 251 | else if (wanted == ";") return pass(); 252 | else return cont(arguments.callee); 253 | }; 254 | } 255 | 256 | function statement(type) { 257 | if (type == "var") return cont(pushlex("vardef"), vardef1, expect(";"), poplex); 258 | if (type == "keyword a") return cont(pushlex("form"), expression, statement, poplex); 259 | if (type == "keyword b") return cont(pushlex("form"), statement, poplex); 260 | if (type == "{") return cont(pushlex("}"), block, poplex); 261 | if (type == ";") return cont(); 262 | if (type == "if") return cont(pushlex("form"), expression, statement, poplex, maybeelse); 263 | if (type == "function") return cont(functiondef); 264 | if (type == "for") return cont(pushlex("form"), expect("("), pushlex(")"), forspec1, expect(")"), 265 | poplex, statement, poplex); 266 | if (type == "variable") return cont(pushlex("stat"), maybelabel); 267 | if (type == "switch") return cont(pushlex("form"), expression, pushlex("}", "switch"), expect("{"), 268 | block, poplex, poplex); 269 | if (type == "case") return cont(expression, expect(":")); 270 | if (type == "default") return cont(expect(":")); 271 | if (type == "catch") return cont(pushlex("form"), pushcontext, expect("("), funarg, expect(")"), 272 | statement, poplex, popcontext); 273 | return pass(pushlex("stat"), expression, expect(";"), poplex); 274 | } 275 | function expression(type) { 276 | return expressionInner(type, false); 277 | } 278 | function expressionNoComma(type) { 279 | return expressionInner(type, true); 280 | } 281 | function expressionInner(type, noComma) { 282 | var maybeop = noComma ? maybeoperatorNoComma : maybeoperatorComma; 283 | if (atomicTypes.hasOwnProperty(type)) return cont(maybeop); 284 | if (type == "function") return cont(functiondef); 285 | if (type == "keyword c") return cont(noComma ? maybeexpressionNoComma : maybeexpression); 286 | if (type == "(") return cont(pushlex(")"), maybeexpression, expect(")"), poplex, maybeop); 287 | if (type == "operator") return cont(noComma ? expressionNoComma : expression); 288 | if (type == "[") return cont(pushlex("]"), commasep(expressionNoComma, "]"), poplex, maybeop); 289 | if (type == "{") return cont(pushlex("}"), commasep(objprop, "}"), poplex, maybeop); 290 | return cont(); 291 | } 292 | function maybeexpression(type) { 293 | if (type.match(/[;\}\)\],]/)) return pass(); 294 | return pass(expression); 295 | } 296 | function maybeexpressionNoComma(type) { 297 | if (type.match(/[;\}\)\],]/)) return pass(); 298 | return pass(expressionNoComma); 299 | } 300 | 301 | function maybeoperatorComma(type, value) { 302 | if (type == ",") return cont(expression); 303 | return maybeoperatorNoComma(type, value, false); 304 | } 305 | function maybeoperatorNoComma(type, value, noComma) { 306 | var me = noComma == false ? maybeoperatorComma : maybeoperatorNoComma; 307 | var expr = noComma == false ? expression : expressionNoComma; 308 | if (type == "operator") { 309 | if (/\+\+|--/.test(value)) return cont(me); 310 | if (value == "?") return cont(expression, expect(":"), expr); 311 | return cont(expr); 312 | } 313 | if (type == ";") return; 314 | if (type == "(") return cont(pushlex(")", "call"), commasep(expressionNoComma, ")"), poplex, me); 315 | if (type == ".") return cont(property, me); 316 | if (type == "[") return cont(pushlex("]"), maybeexpression, expect("]"), poplex, me); 317 | } 318 | function maybelabel(type) { 319 | if (type == ":") return cont(poplex, statement); 320 | return pass(maybeoperatorComma, expect(";"), poplex); 321 | } 322 | function property(type) { 323 | if (type == "variable") {cx.marked = "property"; return cont();} 324 | } 325 | function objprop(type, value) { 326 | if (type == "variable") { 327 | cx.marked = "property"; 328 | if (value == "get" || value == "set") return cont(getterSetter); 329 | } else if (type == "number" || type == "string") { 330 | cx.marked = type + " property"; 331 | } 332 | if (atomicTypes.hasOwnProperty(type)) return cont(expect(":"), expressionNoComma); 333 | } 334 | function getterSetter(type) { 335 | if (type == ":") return cont(expression); 336 | if (type != "variable") return cont(expect(":"), expression); 337 | cx.marked = "property"; 338 | return cont(functiondef); 339 | } 340 | function commasep(what, end) { 341 | function proceed(type) { 342 | if (type == ",") { 343 | var lex = cx.state.lexical; 344 | if (lex.info == "call") lex.pos = (lex.pos || 0) + 1; 345 | return cont(what, proceed); 346 | } 347 | if (type == end) return cont(); 348 | return cont(expect(end)); 349 | } 350 | return function(type) { 351 | if (type == end) return cont(); 352 | else return pass(what, proceed); 353 | }; 354 | } 355 | function block(type) { 356 | if (type == "}") return cont(); 357 | return pass(statement, block); 358 | } 359 | function maybetype(type) { 360 | if (type == ":") return cont(typedef); 361 | return pass(); 362 | } 363 | function typedef(type) { 364 | if (type == "variable"){cx.marked = "variable-3"; return cont();} 365 | return pass(); 366 | } 367 | function vardef1(type, value) { 368 | if (type == "variable") { 369 | register(value); 370 | return isTS ? cont(maybetype, vardef2) : cont(vardef2); 371 | } 372 | return pass(); 373 | } 374 | function vardef2(type, value) { 375 | if (value == "=") return cont(expressionNoComma, vardef2); 376 | if (type == ",") return cont(vardef1); 377 | } 378 | function maybeelse(type, value) { 379 | if (type == "keyword b" && value == "else") return cont(pushlex("form"), statement, poplex); 380 | } 381 | function forspec1(type) { 382 | if (type == "var") return cont(vardef1, expect(";"), forspec2); 383 | if (type == ";") return cont(forspec2); 384 | if (type == "variable") return cont(formaybein); 385 | return pass(expression, expect(";"), forspec2); 386 | } 387 | function formaybein(_type, value) { 388 | if (value == "in") return cont(expression); 389 | return cont(maybeoperatorComma, forspec2); 390 | } 391 | function forspec2(type, value) { 392 | if (type == ";") return cont(forspec3); 393 | if (value == "in") return cont(expression); 394 | return pass(expression, expect(";"), forspec3); 395 | } 396 | function forspec3(type) { 397 | if (type != ")") cont(expression); 398 | } 399 | function functiondef(type, value) { 400 | if (type == "variable") {register(value); return cont(functiondef);} 401 | if (type == "(") return cont(pushlex(")"), pushcontext, commasep(funarg, ")"), poplex, statement, popcontext); 402 | } 403 | function funarg(type, value) { 404 | if (type == "variable") {register(value); return isTS ? cont(maybetype) : cont();} 405 | } 406 | 407 | // Interface 408 | 409 | return { 410 | startState: function(basecolumn) { 411 | return { 412 | tokenize: jsTokenBase, 413 | lastType: null, 414 | cc: [], 415 | lexical: new JSLexical((basecolumn || 0) - indentUnit, 0, "block", false), 416 | localVars: parserConfig.localVars, 417 | globalVars: parserConfig.globalVars, 418 | context: parserConfig.localVars && {vars: parserConfig.localVars}, 419 | indented: 0 420 | }; 421 | }, 422 | 423 | token: function(stream, state) { 424 | if (stream.sol()) { 425 | if (!state.lexical.hasOwnProperty("align")) 426 | state.lexical.align = false; 427 | state.indented = stream.indentation(); 428 | } 429 | if (state.tokenize != jsTokenComment && stream.eatSpace()) return null; 430 | var style = state.tokenize(stream, state); 431 | if (type == "comment") return style; 432 | state.lastType = type == "operator" && (content == "++" || content == "--") ? "incdec" : type; 433 | return parseJS(state, style, type, content, stream); 434 | }, 435 | 436 | indent: function(state, textAfter) { 437 | if (state.tokenize == jsTokenComment) return CodeMirror.Pass; 438 | if (state.tokenize != jsTokenBase) return 0; 439 | var firstChar = textAfter && textAfter.charAt(0), lexical = state.lexical; 440 | // Kludge to prevent 'maybelse' from blocking lexical scope pops 441 | for (var i = state.cc.length - 1; i >= 0; --i) { 442 | var c = state.cc[i]; 443 | if (c == poplex) lexical = lexical.prev; 444 | else if (c != maybeelse || /^else\b/.test(textAfter)) break; 445 | } 446 | if (lexical.type == "stat" && firstChar == "}") lexical = lexical.prev; 447 | if (statementIndent && lexical.type == ")" && lexical.prev.type == "stat") 448 | lexical = lexical.prev; 449 | var type = lexical.type, closing = firstChar == type; 450 | 451 | if (type == "vardef") return lexical.indented + (state.lastType == "operator" || state.lastType == "," ? 4 : 0); 452 | else if (type == "form" && firstChar == "{") return lexical.indented; 453 | else if (type == "form") return lexical.indented + indentUnit; 454 | else if (type == "stat") 455 | return lexical.indented + (state.lastType == "operator" || state.lastType == "," ? statementIndent || indentUnit : 0); 456 | else if (lexical.info == "switch" && !closing && parserConfig.doubleIndentSwitch != false) 457 | return lexical.indented + (/^(?:case|default)\b/.test(textAfter) ? indentUnit : 2 * indentUnit); 458 | else if (lexical.align) return lexical.column + (closing ? 0 : 1); 459 | else return lexical.indented + (closing ? 0 : indentUnit); 460 | }, 461 | 462 | electricChars: ":{}", 463 | blockCommentStart: jsonMode ? null : "/*", 464 | blockCommentEnd: jsonMode ? null : "*/", 465 | lineComment: jsonMode ? null : "//", 466 | fold: "brace", 467 | 468 | helperType: jsonMode ? "json" : "javascript", 469 | jsonMode: jsonMode 470 | }; 471 | }); 472 | 473 | CodeMirror.defineMIME("text/javascript", "javascript"); 474 | CodeMirror.defineMIME("text/ecmascript", "javascript"); 475 | CodeMirror.defineMIME("application/javascript", "javascript"); 476 | CodeMirror.defineMIME("application/ecmascript", "javascript"); 477 | CodeMirror.defineMIME("application/json", {name: "javascript", json: true}); 478 | CodeMirror.defineMIME("application/x-json", {name: "javascript", json: true}); 479 | CodeMirror.defineMIME("text/typescript", { name: "javascript", typescript: true }); 480 | CodeMirror.defineMIME("application/typescript", { name: "javascript", typescript: true }); 481 | -------------------------------------------------------------------------------- /lab/vendor/codemirror/matchbrackets.js: -------------------------------------------------------------------------------- 1 | (function() { 2 | var ie_lt8 = /MSIE \d/.test(navigator.userAgent) && 3 | (document.documentMode == null || document.documentMode < 8); 4 | 5 | var Pos = CodeMirror.Pos; 6 | 7 | var matching = {"(": ")>", ")": "(<", "[": "]>", "]": "[<", "{": "}>", "}": "{<"}; 8 | function findMatchingBracket(cm, where, strict) { 9 | var state = cm.state.matchBrackets; 10 | var maxScanLen = (state && state.maxScanLineLength) || 10000; 11 | 12 | var cur = where || cm.getCursor(), line = cm.getLineHandle(cur.line), pos = cur.ch - 1; 13 | var match = (pos >= 0 && matching[line.text.charAt(pos)]) || matching[line.text.charAt(++pos)]; 14 | if (!match) return null; 15 | var forward = match.charAt(1) == ">", d = forward ? 1 : -1; 16 | if (strict && forward != (pos == cur.ch)) return null; 17 | var style = cm.getTokenTypeAt(Pos(cur.line, pos + 1)); 18 | 19 | var stack = [line.text.charAt(pos)], re = /[(){}[\]]/; 20 | function scan(line, lineNo, start) { 21 | if (!line.text) return; 22 | var pos = forward ? 0 : line.text.length - 1, end = forward ? line.text.length : -1; 23 | if (line.text.length > maxScanLen) return null; 24 | if (start != null) pos = start + d; 25 | for (; pos != end; pos += d) { 26 | var ch = line.text.charAt(pos); 27 | if (re.test(ch) && cm.getTokenTypeAt(Pos(lineNo, pos + 1)) == style) { 28 | var match = matching[ch]; 29 | if (match.charAt(1) == ">" == forward) stack.push(ch); 30 | else if (stack.pop() != match.charAt(0)) return {pos: pos, match: false}; 31 | else if (!stack.length) return {pos: pos, match: true}; 32 | } 33 | } 34 | } 35 | for (var i = cur.line, found, e = forward ? Math.min(i + 100, cm.lineCount()) : Math.max(-1, i - 100); i != e; i+=d) { 36 | if (i == cur.line) found = scan(line, i, pos); 37 | else found = scan(cm.getLineHandle(i), i); 38 | if (found) break; 39 | } 40 | return {from: Pos(cur.line, pos), to: found && Pos(i, found.pos), 41 | match: found && found.match, forward: forward}; 42 | } 43 | 44 | function matchBrackets(cm, autoclear) { 45 | // Disable brace matching in long lines, since it'll cause hugely slow updates 46 | var maxHighlightLen = cm.state.matchBrackets.maxHighlightLineLength || 1000; 47 | var found = findMatchingBracket(cm); 48 | if (!found || cm.getLine(found.from.line).length > maxHighlightLen || 49 | found.to && cm.getLine(found.to.line).length > maxHighlightLen) 50 | return; 51 | 52 | var style = found.match ? "CodeMirror-matchingbracket" : "CodeMirror-nonmatchingbracket"; 53 | var one = cm.markText(found.from, Pos(found.from.line, found.from.ch + 1), {className: style}); 54 | var two = found.to && cm.markText(found.to, Pos(found.to.line, found.to.ch + 1), {className: style}); 55 | // Kludge to work around the IE bug from issue #1193, where text 56 | // input stops going to the textare whever this fires. 57 | if (ie_lt8 && cm.state.focused) cm.display.input.focus(); 58 | var clear = function() { 59 | cm.operation(function() { one.clear(); two && two.clear(); }); 60 | }; 61 | if (autoclear) setTimeout(clear, 800); 62 | else return clear; 63 | } 64 | 65 | var currentlyHighlighted = null; 66 | function doMatchBrackets(cm) { 67 | cm.operation(function() { 68 | if (currentlyHighlighted) {currentlyHighlighted(); currentlyHighlighted = null;} 69 | if (!cm.somethingSelected()) currentlyHighlighted = matchBrackets(cm, false); 70 | }); 71 | } 72 | 73 | CodeMirror.defineOption("matchBrackets", false, function(cm, val, old) { 74 | if (old && old != CodeMirror.Init) 75 | cm.off("cursorActivity", doMatchBrackets); 76 | if (val) { 77 | cm.state.matchBrackets = typeof val == "object" ? val : {}; 78 | cm.on("cursorActivity", doMatchBrackets); 79 | } 80 | }); 81 | 82 | CodeMirror.defineExtension("matchBrackets", function() {matchBrackets(this, true);}); 83 | CodeMirror.defineExtension("findMatchingBracket", function(pos, strict){ 84 | return findMatchingBracket(this, pos, strict); 85 | }); 86 | })(); 87 | -------------------------------------------------------------------------------- /lab/vendor/codemirror/xml.js: -------------------------------------------------------------------------------- 1 | CodeMirror.defineMode("xml", function(config, parserConfig) { 2 | var indentUnit = config.indentUnit; 3 | var multilineTagIndentFactor = parserConfig.multilineTagIndentFactor || 1; 4 | var multilineTagIndentPastTag = parserConfig.multilineTagIndentPastTag || true; 5 | 6 | var Kludges = parserConfig.htmlMode ? { 7 | autoSelfClosers: {'area': true, 'base': true, 'br': true, 'col': true, 'command': true, 8 | 'embed': true, 'frame': true, 'hr': true, 'img': true, 'input': true, 9 | 'keygen': true, 'link': true, 'meta': true, 'param': true, 'source': true, 10 | 'track': true, 'wbr': true}, 11 | implicitlyClosed: {'dd': true, 'li': true, 'optgroup': true, 'option': true, 'p': true, 12 | 'rp': true, 'rt': true, 'tbody': true, 'td': true, 'tfoot': true, 13 | 'th': true, 'tr': true}, 14 | contextGrabbers: { 15 | 'dd': {'dd': true, 'dt': true}, 16 | 'dt': {'dd': true, 'dt': true}, 17 | 'li': {'li': true}, 18 | 'option': {'option': true, 'optgroup': true}, 19 | 'optgroup': {'optgroup': true}, 20 | 'p': {'address': true, 'article': true, 'aside': true, 'blockquote': true, 'dir': true, 21 | 'div': true, 'dl': true, 'fieldset': true, 'footer': true, 'form': true, 22 | 'h1': true, 'h2': true, 'h3': true, 'h4': true, 'h5': true, 'h6': true, 23 | 'header': true, 'hgroup': true, 'hr': true, 'menu': true, 'nav': true, 'ol': true, 24 | 'p': true, 'pre': true, 'section': true, 'table': true, 'ul': true}, 25 | 'rp': {'rp': true, 'rt': true}, 26 | 'rt': {'rp': true, 'rt': true}, 27 | 'tbody': {'tbody': true, 'tfoot': true}, 28 | 'td': {'td': true, 'th': true}, 29 | 'tfoot': {'tbody': true}, 30 | 'th': {'td': true, 'th': true}, 31 | 'thead': {'tbody': true, 'tfoot': true}, 32 | 'tr': {'tr': true} 33 | }, 34 | doNotIndent: {"pre": true}, 35 | allowUnquoted: true, 36 | allowMissing: true 37 | } : { 38 | autoSelfClosers: {}, 39 | implicitlyClosed: {}, 40 | contextGrabbers: {}, 41 | doNotIndent: {}, 42 | allowUnquoted: false, 43 | allowMissing: false 44 | }; 45 | var alignCDATA = parserConfig.alignCDATA; 46 | 47 | // Return variables for tokenizers 48 | var tagName, type; 49 | 50 | function inText(stream, state) { 51 | function chain(parser) { 52 | state.tokenize = parser; 53 | return parser(stream, state); 54 | } 55 | 56 | var ch = stream.next(); 57 | if (ch == "<") { 58 | if (stream.eat("!")) { 59 | if (stream.eat("[")) { 60 | if (stream.match("CDATA[")) return chain(inBlock("atom", "]]>")); 61 | else return null; 62 | } else if (stream.match("--")) { 63 | return chain(inBlock("comment", "-->")); 64 | } else if (stream.match("DOCTYPE", true, true)) { 65 | stream.eatWhile(/[\w\._\-]/); 66 | return chain(doctype(1)); 67 | } else { 68 | return null; 69 | } 70 | } else if (stream.eat("?")) { 71 | stream.eatWhile(/[\w\._\-]/); 72 | state.tokenize = inBlock("meta", "?>"); 73 | return "meta"; 74 | } else { 75 | var isClose = stream.eat("/"); 76 | tagName = ""; 77 | var c; 78 | while ((c = stream.eat(/[^\s\u00a0=<>\"\'\/?]/))) tagName += c; 79 | if (!tagName) return "tag error"; 80 | type = isClose ? "closeTag" : "openTag"; 81 | state.tokenize = inTag; 82 | return "tag"; 83 | } 84 | } else if (ch == "&") { 85 | var ok; 86 | if (stream.eat("#")) { 87 | if (stream.eat("x")) { 88 | ok = stream.eatWhile(/[a-fA-F\d]/) && stream.eat(";"); 89 | } else { 90 | ok = stream.eatWhile(/[\d]/) && stream.eat(";"); 91 | } 92 | } else { 93 | ok = stream.eatWhile(/[\w\.\-:]/) && stream.eat(";"); 94 | } 95 | return ok ? "atom" : "error"; 96 | } else { 97 | stream.eatWhile(/[^&<]/); 98 | return null; 99 | } 100 | } 101 | 102 | function inTag(stream, state) { 103 | var ch = stream.next(); 104 | if (ch == ">" || (ch == "/" && stream.eat(">"))) { 105 | state.tokenize = inText; 106 | type = ch == ">" ? "endTag" : "selfcloseTag"; 107 | return "tag"; 108 | } else if (ch == "=") { 109 | type = "equals"; 110 | return null; 111 | } else if (ch == "<") { 112 | state.tokenize = inText; 113 | var next = state.tokenize(stream, state); 114 | return next ? next + " error" : "error"; 115 | } else if (/[\'\"]/.test(ch)) { 116 | state.tokenize = inAttribute(ch); 117 | state.stringStartCol = stream.column(); 118 | return state.tokenize(stream, state); 119 | } else { 120 | stream.eatWhile(/[^\s\u00a0=<>\"\']/); 121 | return "word"; 122 | } 123 | } 124 | 125 | function inAttribute(quote) { 126 | var closure = function(stream, state) { 127 | while (!stream.eol()) { 128 | if (stream.next() == quote) { 129 | state.tokenize = inTag; 130 | break; 131 | } 132 | } 133 | return "string"; 134 | }; 135 | closure.isInAttribute = true; 136 | return closure; 137 | } 138 | 139 | function inBlock(style, terminator) { 140 | return function(stream, state) { 141 | while (!stream.eol()) { 142 | if (stream.match(terminator)) { 143 | state.tokenize = inText; 144 | break; 145 | } 146 | stream.next(); 147 | } 148 | return style; 149 | }; 150 | } 151 | function doctype(depth) { 152 | return function(stream, state) { 153 | var ch; 154 | while ((ch = stream.next()) != null) { 155 | if (ch == "<") { 156 | state.tokenize = doctype(depth + 1); 157 | return state.tokenize(stream, state); 158 | } else if (ch == ">") { 159 | if (depth == 1) { 160 | state.tokenize = inText; 161 | break; 162 | } else { 163 | state.tokenize = doctype(depth - 1); 164 | return state.tokenize(stream, state); 165 | } 166 | } 167 | } 168 | return "meta"; 169 | }; 170 | } 171 | 172 | var curState, curStream, setStyle; 173 | function pass() { 174 | for (var i = arguments.length - 1; i >= 0; i--) curState.cc.push(arguments[i]); 175 | } 176 | function cont() { 177 | pass.apply(null, arguments); 178 | return true; 179 | } 180 | 181 | function pushContext(tagName, startOfLine) { 182 | var noIndent = Kludges.doNotIndent.hasOwnProperty(tagName) || (curState.context && curState.context.noIndent); 183 | curState.context = { 184 | prev: curState.context, 185 | tagName: tagName, 186 | indent: curState.indented, 187 | startOfLine: startOfLine, 188 | noIndent: noIndent 189 | }; 190 | } 191 | function popContext() { 192 | if (curState.context) curState.context = curState.context.prev; 193 | } 194 | 195 | function element(type) { 196 | if (type == "openTag") { 197 | curState.tagName = tagName; 198 | curState.tagStart = curStream.column(); 199 | return cont(attributes, endtag(curState.startOfLine)); 200 | } else if (type == "closeTag") { 201 | var err = false; 202 | if (curState.context) { 203 | if (curState.context.tagName != tagName) { 204 | if (Kludges.implicitlyClosed.hasOwnProperty(curState.context.tagName.toLowerCase())) { 205 | popContext(); 206 | } 207 | err = !curState.context || curState.context.tagName != tagName; 208 | } 209 | } else { 210 | err = true; 211 | } 212 | if (err) setStyle = "error"; 213 | return cont(endclosetag(err)); 214 | } 215 | return cont(); 216 | } 217 | function endtag(startOfLine) { 218 | return function(type) { 219 | var tagName = curState.tagName; 220 | curState.tagName = curState.tagStart = null; 221 | if (type == "selfcloseTag" || 222 | (type == "endTag" && Kludges.autoSelfClosers.hasOwnProperty(tagName.toLowerCase()))) { 223 | maybePopContext(tagName.toLowerCase()); 224 | return cont(); 225 | } 226 | if (type == "endTag") { 227 | maybePopContext(tagName.toLowerCase()); 228 | pushContext(tagName, startOfLine); 229 | return cont(); 230 | } 231 | return cont(); 232 | }; 233 | } 234 | function endclosetag(err) { 235 | return function(type) { 236 | if (err) setStyle = "error"; 237 | if (type == "endTag") { popContext(); return cont(); } 238 | setStyle = "error"; 239 | return cont(arguments.callee); 240 | }; 241 | } 242 | function maybePopContext(nextTagName) { 243 | var parentTagName; 244 | while (true) { 245 | if (!curState.context) { 246 | return; 247 | } 248 | parentTagName = curState.context.tagName.toLowerCase(); 249 | if (!Kludges.contextGrabbers.hasOwnProperty(parentTagName) || 250 | !Kludges.contextGrabbers[parentTagName].hasOwnProperty(nextTagName)) { 251 | return; 252 | } 253 | popContext(); 254 | } 255 | } 256 | 257 | function attributes(type) { 258 | if (type == "word") {setStyle = "attribute"; return cont(attribute, attributes);} 259 | if (type == "endTag" || type == "selfcloseTag") return pass(); 260 | setStyle = "error"; 261 | return cont(attributes); 262 | } 263 | function attribute(type) { 264 | if (type == "equals") return cont(attvalue, attributes); 265 | if (!Kludges.allowMissing) setStyle = "error"; 266 | else if (type == "word") {setStyle = "attribute"; return cont(attribute, attributes);} 267 | return (type == "endTag" || type == "selfcloseTag") ? pass() : cont(); 268 | } 269 | function attvalue(type) { 270 | if (type == "string") return cont(attvaluemaybe); 271 | if (type == "word" && Kludges.allowUnquoted) {setStyle = "string"; return cont();} 272 | setStyle = "error"; 273 | return (type == "endTag" || type == "selfCloseTag") ? pass() : cont(); 274 | } 275 | function attvaluemaybe(type) { 276 | if (type == "string") return cont(attvaluemaybe); 277 | else return pass(); 278 | } 279 | 280 | return { 281 | startState: function() { 282 | return {tokenize: inText, cc: [], indented: 0, startOfLine: true, tagName: null, tagStart: null, context: null}; 283 | }, 284 | 285 | token: function(stream, state) { 286 | if (!state.tagName && stream.sol()) { 287 | state.startOfLine = true; 288 | state.indented = stream.indentation(); 289 | } 290 | if (stream.eatSpace()) return null; 291 | 292 | setStyle = type = tagName = null; 293 | var style = state.tokenize(stream, state); 294 | state.type = type; 295 | if ((style || type) && style != "comment") { 296 | curState = state; curStream = stream; 297 | while (true) { 298 | var comb = state.cc.pop() || element; 299 | if (comb(type || style)) break; 300 | } 301 | } 302 | state.startOfLine = false; 303 | if (setStyle) 304 | style = setStyle == "error" ? style + " error" : setStyle; 305 | return style; 306 | }, 307 | 308 | indent: function(state, textAfter, fullLine) { 309 | var context = state.context; 310 | // Indent multi-line strings (e.g. css). 311 | if (state.tokenize.isInAttribute) { 312 | return state.stringStartCol + 1; 313 | } 314 | if ((state.tokenize != inTag && state.tokenize != inText) || 315 | context && context.noIndent) 316 | return fullLine ? fullLine.match(/^(\s*)/)[0].length : 0; 317 | // Indent the starts of attribute names. 318 | if (state.tagName) { 319 | if (multilineTagIndentPastTag) 320 | return state.tagStart + state.tagName.length + 2; 321 | else 322 | return state.tagStart + indentUnit * multilineTagIndentFactor; 323 | } 324 | if (alignCDATA && /", 336 | 337 | configuration: parserConfig.htmlMode ? "html" : "xml", 338 | helperType: parserConfig.htmlMode ? "html" : "xml" 339 | }; 340 | }); 341 | 342 | CodeMirror.defineMIME("text/xml", "xml"); 343 | CodeMirror.defineMIME("application/xml", "xml"); 344 | if (!CodeMirror.mimeModes.hasOwnProperty("text/html")) 345 | CodeMirror.defineMIME("text/html", {name: "xml", htmlMode: true}); 346 | -------------------------------------------------------------------------------- /lab/vendor/png-baker.js: -------------------------------------------------------------------------------- 1 | // png-baker.js 2 | // 2013-10-11 3 | // Public Domain. 4 | // For more information, see http://github.com/toolness/png-baker.js. 5 | 6 | function PNGBaker(thing) { 7 | if (!(this instanceof PNGBaker)) return new PNGBaker(thing); 8 | 9 | var buffer = thing; 10 | 11 | if (typeof(thing) == 'string') buffer = this._dataURLtoBuffer(thing); 12 | 13 | if (!(buffer instanceof ArrayBuffer)) 14 | throw new Error("first argument must be a data URI or ArrayBuffer"); 15 | 16 | this.buffer = buffer; 17 | this.textChunks = {}; 18 | this._chunks = []; 19 | this._ensurePNGsignature(); 20 | for (var i = this.PNG_SIGNATURE.length; 21 | i < buffer.byteLength; 22 | i += this._readNextChunk(i)); 23 | if (!this._chunks.length || this._chunks[0].type != "IHDR") 24 | throw new Error("first chunk must be IHDR"); 25 | if (this._chunks[this._chunks.length-1].type != "IEND") 26 | throw new Error("last chunk must be IEND"); 27 | } 28 | 29 | PNGBaker.prototype = { 30 | PNG_SIGNATURE: [137, 80, 78, 71, 13, 10, 26, 10], 31 | _ensurePNGsignature: function() { 32 | var bytes = new Uint8Array(this.buffer, 0, this.PNG_SIGNATURE.length); 33 | for (var i = 0; i < this.PNG_SIGNATURE.length; i++) 34 | if (bytes[i] != this.PNG_SIGNATURE[i]) 35 | throw new Error("PNG signature mismatch at byte " + i); 36 | }, 37 | _readNextChunk: function(byteOffset) { 38 | var i = byteOffset; 39 | var buffer = this.buffer; 40 | var data = new DataView(buffer); 41 | var chunkLength = data.getUint32(i); i += 4; 42 | var crcData = new Uint8Array(buffer, i, chunkLength+4); 43 | var ourCRC = this._crc32(crcData); 44 | var chunkType = this._arrayToStr(new Uint8Array(buffer, i, 4)); i += 4; 45 | var chunkBytes = new Uint8Array(buffer, i, chunkLength); 46 | 47 | i += chunkLength; 48 | 49 | var chunkCRC = data.getUint32(i); i += 4; 50 | 51 | if (chunkCRC != ourCRC) 52 | throw new Error("CRC mismatch for chunk type " + chunkType); 53 | 54 | if (chunkType == 'tEXt') 55 | this._readTextChunk(chunkBytes); 56 | else this._chunks.push({ 57 | type: chunkType, 58 | data: chunkBytes 59 | }); 60 | 61 | return i - byteOffset; 62 | }, 63 | _readTextChunk: function(bytes) { 64 | var keyword, text; 65 | for (var i = 0; i < bytes.length; i++) 66 | if (bytes[i] == 0) { 67 | keyword = this._arrayToStr([].slice.call(bytes, 0, i)); 68 | text = this._arrayToStr([].slice.call(bytes, i+1)); 69 | break; 70 | } 71 | if (!keyword) throw new Error("malformed tEXt chunk"); 72 | this.textChunks[keyword] = text; 73 | }, 74 | _arrayToStr: function(array) { 75 | return [].map.call(array, function(charCode) { 76 | return String.fromCharCode(charCode); 77 | }).join(''); 78 | }, 79 | // http://stackoverflow.com/a/7261048 80 | _strToArray: function(byteString) { 81 | var buffer = new ArrayBuffer(byteString.length); 82 | var bytes = new Uint8Array(buffer); 83 | 84 | for (var i = 0; i < byteString.length; i++) 85 | bytes[i] = byteString.charCodeAt(i); 86 | return bytes; 87 | }, 88 | // http://stackoverflow.com/a/7261048 89 | _dataURLtoBuffer: function(url) { 90 | // convert base64 to raw binary data held in a string 91 | // doesn't handle URLEncoded DataURIs - see SO answer #6850276 for code 92 | // that does this 93 | var byteString = atob(url.split(',')[1]); 94 | 95 | return this._strToArray(byteString).buffer; 96 | }, 97 | // https://gist.github.com/Yaffle/1287361 98 | _crc32: function(s) { 99 | var polynomial = 0x04C11DB7, 100 | initialValue = 0xFFFFFFFF, 101 | finalXORValue = 0xFFFFFFFF, 102 | crc = initialValue, 103 | table = [], i, j, c; 104 | 105 | function reverse(x, n) { 106 | var b = 0; 107 | while (n) { 108 | b = b * 2 + x % 2; 109 | x /= 2; 110 | x -= x % 1; 111 | n--; 112 | } 113 | return b; 114 | } 115 | 116 | for (i = 255; i >= 0; i--) { 117 | c = reverse(i, 32); 118 | 119 | for (j = 0; j < 8; j++) { 120 | c = ((c * 2) ^ (((c >>> 31) % 2) * polynomial)) >>> 0; 121 | } 122 | 123 | table[i] = reverse(c, 32); 124 | } 125 | 126 | // This is a fix for Safari, which dislikes Uint8 arrays, but only 127 | // when Web Inspector is disabled. 128 | s = [].slice.call(s); 129 | 130 | for (i = 0; i < s.length; i++) { 131 | c = s[i]; 132 | if (c > 255) { 133 | throw new RangeError(); 134 | } 135 | j = (crc % 256) ^ c; 136 | crc = ((crc / 256) ^ table[j]) >>> 0; 137 | } 138 | 139 | return (crc ^ finalXORValue) >>> 0; 140 | }, 141 | _makeChunk: function(chunk) { 142 | var i; 143 | var buffer = new ArrayBuffer(chunk.data.length + 12); 144 | var data = new DataView(buffer); 145 | var crcData = new Uint8Array(buffer, 4, chunk.data.length + 4); 146 | 147 | data.setUint32(0, chunk.data.length); 148 | for (i = 0; i < 4; i++) 149 | data.setUint8(4 + i, chunk.type.charCodeAt(i)); 150 | for (i = 0; i < chunk.data.length; i++) 151 | data.setUint8(8 + i, chunk.data[i]); 152 | data.setUint32(8 + chunk.data.length, this._crc32(crcData)); 153 | return buffer; 154 | }, 155 | toBlob: function() { 156 | var parts = [new Uint8Array(this.PNG_SIGNATURE).buffer]; 157 | var makeChunk = this._makeChunk.bind(this); 158 | 159 | parts.push(makeChunk(this._chunks[0])); 160 | parts.push.apply(parts, Object.keys(this.textChunks).map(function(k) { 161 | return makeChunk({ 162 | type: 'tEXt', 163 | data: this._strToArray(k + '\0' + this.textChunks[k]) 164 | }); 165 | }, this)); 166 | parts.push.apply(parts, this._chunks.slice(1).map(makeChunk)); 167 | 168 | return new Blob(parts, {type: 'image/png'}); 169 | } 170 | }; 171 | -------------------------------------------------------------------------------- /lab/worker.js: -------------------------------------------------------------------------------- 1 | var evaluate = function(code) { eval(code); }; 2 | 3 | // The above code should always be the very first line of this file, as 4 | // exceptions thrown from the code evaluated in it will be relative to 5 | // the line the eval statement is on (in some browsers, at least). 6 | 7 | importScripts('../tiny-turtle.js', 'lab.js'); 8 | 9 | function interceptProperties(obj) { 10 | Lab.Validation.properties.forEach(function(propName) { 11 | var value = obj[propName]; 12 | Object.defineProperty(obj, propName, { 13 | get: function() { return value; }, 14 | set: function(newValue) { 15 | value = newValue; 16 | postMessage({ 17 | msg: 'turtle-propset', 18 | property: propName, 19 | value: value 20 | }); 21 | return value; 22 | } 23 | }); 24 | }); 25 | } 26 | 27 | function interceptMethods(obj) { 28 | Lab.Validation.methods.forEach(function(methodName) { 29 | var method = obj[methodName]; 30 | obj[methodName] = function() { 31 | var retval = method.apply(this, arguments); 32 | postMessage({ 33 | msg: 'turtle-methodcall', 34 | method: methodName, 35 | args: [].slice.call(arguments) 36 | }); 37 | return retval; 38 | }; 39 | }); 40 | } 41 | 42 | onmessage = function(e) { 43 | var noop = function() {} 44 | var fakeCanvas = { 45 | width: e.data.width, 46 | height: e.data.height, 47 | getContext: function() { return this; }, 48 | beginPath: noop, 49 | moveTo: noop, 50 | lineTo: noop, 51 | stroke: noop, 52 | save: noop, 53 | restore: noop, 54 | fill: noop, 55 | translate: noop, 56 | rotate: noop, 57 | closePath: noop 58 | }; 59 | TinyTurtle.call(self, fakeCanvas); 60 | interceptMethods(self); 61 | interceptProperties(self); 62 | evaluate(e.data.source); 63 | postMessage({msg: 'done'}); 64 | }; 65 | -------------------------------------------------------------------------------- /tiny-turtle.js: -------------------------------------------------------------------------------- 1 | // tiny-turtle.js 2 | // 2013-10-11 3 | // Public Domain. 4 | // For more information, see http://github.com/toolness/tiny-turtle. 5 | 6 | function TinyTurtle(canvas) { 7 | canvas = canvas || document.querySelector('canvas'); 8 | 9 | var self = this; 10 | var rotation = 90; 11 | var position = { 12 | // See http://diveintohtml5.info/canvas.html#pixel-madness for 13 | // details on why we're offsetting by 0.5. 14 | x: canvas.width / 2 + 0.5, 15 | y: canvas.height / 2 + 0.5 16 | }; 17 | var isPenDown = true; 18 | var radians = function(r) {return 2 * Math.PI * (r / 360) }; 19 | var triangle = function(ctx, base, height) { 20 | ctx.beginPath(); ctx.moveTo(0, -base / 2); ctx.lineTo(height, 0); 21 | ctx.lineTo(0, base / 2); ctx.closePath(); 22 | }; 23 | var rotate = function(deg) { 24 | rotation = (rotation + deg) % 360; 25 | if (rotation < 0) rotation += 360; 26 | }; 27 | 28 | self.penStyle = 'black'; 29 | self.penWidth = 1; 30 | self.penUp = function() { isPenDown = false; return self; }; 31 | self.penDown = function() { isPenDown = true; return self; }; 32 | self.forward = self.fd = function(distance) { 33 | var origX = position.x, origY = position.y; 34 | position.x += Math.cos(radians(rotation)) * distance; 35 | position.y -= Math.sin(radians(rotation)) * distance; 36 | if (!isPenDown) return; 37 | var ctx = canvas.getContext('2d'); 38 | ctx.strokeStyle = self.penStyle; 39 | ctx.lineWidth = self.penWidth; 40 | ctx.beginPath(); 41 | ctx.moveTo(origX, origY); 42 | ctx.lineTo(position.x, position.y); 43 | ctx.stroke(); 44 | return self; 45 | }; 46 | self.stamp = function(size) { 47 | var ctx = canvas.getContext('2d'); 48 | ctx.save(); 49 | ctx.strokeStyle = ctx.fillStyle = self.penStyle; 50 | ctx.lineWidth = self.penWidth; 51 | ctx.translate(position.x, position.y); 52 | ctx.rotate(-radians(rotation)); 53 | triangle(ctx, size || 10, (size || 10) * 1.5); 54 | isPenDown ? ctx.fill() : ctx.stroke(); 55 | ctx.restore(); 56 | return self; 57 | }; 58 | self.left = self.lt = function(deg) { rotate(deg); return self; }; 59 | self.right = self.rt = function(deg) { rotate(-deg); return self; }; 60 | 61 | Object.defineProperties(self, { 62 | canvas: {get: function() { return canvas; }}, 63 | rotation: {get: function() { return rotation; }}, 64 | position: {get: function() { return {x: position.x, y: position.y}; }}, 65 | pen: {get: function() { return isPenDown ? 'down' : 'up'; }} 66 | }); 67 | 68 | return self; 69 | } 70 | -------------------------------------------------------------------------------- /tutorial/glossary.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | TinyTurtle Tutorial Glossary 7 |

TinyTurtle Tutorial Glossary

8 | 9 |

10 | Here's some terminology used in the tutorial that you 11 | might be unfamiliar with. 12 |

13 | 14 |
15 |
API
16 |
17 |
18 | APIs are the filament that connects what i want to do 19 | with what i want to learn. 20 | Diana Kimball, 21 | Coding 22 | as a Liberal Art 23 | 24 |
25 |

26 | Technically, API stands for Application Programming 27 | Interface. Practically speaking, it's really just a 28 | collection of (hopefully) well-documented functions and similar 29 | abstractions that allow you to do what you want to do with a 30 | programming language. 31 |

32 |

33 | If a programming language is a language, then an API 34 | is a bit like a specialized dictionary, providing useful 35 | nouns and verbs that programs can use to do their job. 36 |

37 |

38 | See the TinyTurtle 39 | API for an example. 40 |

41 |
42 | 43 |
Function
44 |
45 |

46 | A function is like a verb, or action, in a programming 47 | language. It's easy to create your own; see the 48 | Making new 49 | functions section of JavaScript for Cats to 50 | learn how. 51 |

52 |

53 | In some programming languages, functions are referred to as 54 | procedures or subroutines. They're all basically 55 | the same thing. 56 |

57 |
58 | 59 |
JavaScript
60 |
61 |
62 | JavaScript is an astonishing language, in the very worst sense. 63 | 64 | Douglas Crockford 65 |
66 |

67 | JavaScript is a programming language created by Brendan Eich in 1995 68 | under the time constraints of the First Browser War 69 | and some marketing constraints imposed by Netscape's partnership 70 | with Sun Microsystems. These contributed to it being a very 71 | misunderstood programming language. 72 |

73 |

74 | Because of this, JavaScript is not a very easy language to learn, 75 | and it's a lot less readable than languages that lacked its 76 | constraints. However, it's also ubiquitous: it runs in web pages, 77 | which makes it extremely easy to share, and it can also be used to 78 | program robots, financial trading platforms, web servers, and 79 | a lot more. In other words, if there's something you want to do, 80 | there's probably an API for it in JavaScript, 81 | which makes it an extremely useful language despite its flaws. 82 |

83 |
84 |
85 | 86 | 87 | -------------------------------------------------------------------------------- /tutorial/highlight.css: -------------------------------------------------------------------------------- 1 | a[id][href^='#'] { 2 | transition: background-color 1s; 3 | -moz-transition: background-color 1s; 4 | -webkit-transition: background-color 1s; 5 | color: inherit; 6 | text-decoration: none; 7 | } 8 | 9 | a[id][href^='#']:hover { 10 | background: inherit; 11 | } 12 | 13 | a[id][href^='#']:hover:after { 14 | opacity: 0.5; 15 | content: ' #'; 16 | } 17 | 18 | a.highlight[id][href^='#'] { 19 | background: yellow; 20 | } 21 | -------------------------------------------------------------------------------- /tutorial/highlight.js: -------------------------------------------------------------------------------- 1 | (function() { 2 | highlight.DURATION = 1000; 3 | 4 | function highlight(el) { 5 | if (el.classList.contains('highlight')) return; 6 | el.classList.add('highlight'); 7 | setTimeout(function() { 8 | el.classList.remove('highlight'); 9 | }, highlight.DURATION); 10 | } 11 | 12 | function highlightLocationHash() { 13 | var el = document.querySelector(location.hash); 14 | 15 | if (el) highlight(el); 16 | } 17 | 18 | function highlightLinkTarget(e) { 19 | if (e.target.nodeName != 'A') return; 20 | 21 | var href = e.target.getAttribute('href'); 22 | 23 | if (href && href[0] == '#') highlight(document.querySelector(href)); 24 | } 25 | 26 | window.addEventListener('load', highlightLocationHash, false); 27 | window.addEventListener('hashchange', highlightLocationHash, false); 28 | document.addEventListener('click', highlightLinkTarget, false); 29 | })(); 30 | -------------------------------------------------------------------------------- /tutorial/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | TinyTurtle Tutorial 10 |

TinyTurtle Tutorial

11 | 12 |

13 | Before embarking on this journey, you may want to check out 14 | JavaScript For Cats or 15 | Eloquent JavaScript to 16 | understand the basics of the language. Or you can just start hacking 17 | and learn things from the glossary as you go. 18 |

19 | 20 | 49 | 50 |

I. Square

51 | 52 |
53 | Turtle geometry is a different style of doing geometry, just as Euclid’s 54 | axiomatic style and Descartes’s analytic style are different from one 55 | another. Euclid’s is a logical style. Descartes’s is an 56 | algebraic style. Turtle geometry is a computational 57 | style of geometry. 58 | Seymour Papert, Mindstorms 59 |
60 | 61 |

62 | The TinyTurtle API makes it easy to 63 | experiment with Turtle geometry. 64 |

65 | 66 |

67 | The forward function tells the Turtle to move forward by 68 | some number of pixels. 69 |

70 | 71 |

72 | The right function tells it to turn right by 73 | some number of degrees. 74 |

75 | 76 |

77 | The stamp function tells it to draw its current 78 | state: that is, its position and orientation. This is 79 | visualized as a small, pointy triangle. 80 |

81 | 82 |

83 | Can you add to the code below to make the Turtle draw a square 84 | 100 pixels wide and end with the same state that it started? 85 |

86 | 87 | 93 | 94 | 107 | 108 | 113 | 114 |

II. Squares

115 | 116 |

117 | If we encapsulate our square-drawing code into a 118 | function that takes an 119 | argument specifying the size of square to draw, we can use it as a building 120 | block for more interesting things. 121 |

122 | 123 |

124 | Can you complete the code below? 125 |

126 | 127 | 140 | 141 | 158 | 159 | 185 | 186 |

III. Triangle

187 | 188 |

One of the principles of Turtle geometry is called the Total 189 | Turtle Trip Theorem: 190 |

191 | 192 |
193 | If a Turtle takes a trip around the boundary of any area and ends up in 194 | the state in which it started, then the sum of all turns will be 195 | 360 degrees. 196 | Seymour Papert, Mindstorms 197 |
198 | 199 |

200 | Can you use this theorem to fix the code below, which is trying to 201 | draw an equilateral triangle and finish with the Turtle in the same 202 | state that it started? You just need to replace SOMETHING 203 | with an actual number. 204 |

205 | 206 | 214 | 215 | 227 | 228 |

IV. Circle

229 | 230 |

231 | Can you use the Turtle Total Trip Theorem to finish this function that 232 | draws a circle based on a given circumference, and returns with the 233 | Turtle in its original state? 234 |

235 | 236 | 244 | 245 | 261 | 262 | 267 | 268 |

Going Further

269 | 270 |

271 | Playing with Turtle Graphics in this tutorial is nice, but you might 272 | be wondering how to put your design into a real webpage. See the 273 | TinyTurtle 274 | documentation for instructions on how to do this. 275 |

276 | 277 |

278 | You might also want to take a look at the TinyTurtle source code, 279 | tiny-turtle.js, to see how it works. It's pretty short, and reading other 280 | people's code—especially code you use yourself—is one of the 281 | best ways to learn. If you find bugs, you can even 282 | file an 283 | issue and fix it. 284 |

285 | 286 |

287 | Finally, consider reading Mindstorms by Seymour Papert, which 288 | explains the pedagogy behind Turtle graphics, among many other 289 | revolutionary ideas about education. 290 |

291 | 292 | 293 | 294 | 295 | 296 | 297 | 298 | 299 | 300 | 301 | 302 | 322 | --------------------------------------------------------------------------------