mitx_markdown.js 11 KB
Newer Older
1 2
var schematic_height = 220;
var schematic_width = 400;
3 4
var styling_height_delta = 2; //How many pixels are added to the height of the box because of styling (like a shadow)
var styling_width_delta = 2;
5 6 7

var schematic_editor_height = 300;
var schematic_editor_width = 500;
8

9 10
$(function(){
  $(document).ready(function() {
11
	  //$("a[rel*=leanModal]").leanModal(); //TODO: Make this work with the new modal library. Try and integrate this with the "slices"
12
    
13 14 15 16 17 18 19 20 21 22 23
    $("body").append('\
    <div id="circuit_editor_modal" class="modal hide fade"> \
      <div class="modal-body"> \
        <input class="schematic" height="' + schematic_editor_height + '" width="' + schematic_editor_width + '" id="schematic_editor" name="schematic" type="hidden" value=""/> \
      </div> \
      <div class="modal-footer"> \
        <button type="button" id="circuit_save_btn" class="btn btn-primary" data-dismiss="modal"> \
          Save circuit \
        </button> \
      </div> \
    </div>');
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
    
    //This is the editor that pops up as a modal
    var editorCircuit = $("#schematic_editor").get(0);
    //This is the circuit that they last clicked. The one being edited.
    var editingCircuit = null;
    //Notice we use live, because new circuits can be inserted  
    $(".schematic_open").live("click", function() {
      //Find the new editingCircuit. Transfer its contents to the editorCircuit
      editingCircuit = $(this).children("input.schematic").get(0);
        
      editingCircuit.schematic.update_value();
      var circuit_so_far = $(editingCircuit).val();
        
	    var n = editorCircuit.schematic.components.length;
	    for (var i = 0; i < n; i++)
		    editorCircuit.schematic.components[n - 1 - i].remove();
        
      editorCircuit.schematic.load_schematic(circuit_so_far, "");
42
      editorCircuit.schematic.zoomall();
43 44 45 46 47 48 49 50 51 52 53 54
    });
    
    $("#circuit_save_btn").click(function () {
      //Take the circuit from the editor and put it back into editingCircuit 
      editorCircuit.schematic.update_value();
      var saving_circuit = $(editorCircuit).val();
        
	    var n = editingCircuit.schematic.components.length;
	    for (var i = 0; i < n; i++)
		    editingCircuit.schematic.components[n - 1 - i].remove();
        
      editingCircuit.schematic.load_schematic(saving_circuit, "");
55
      editingCircuit.schematic.zoomall();
56 57
      
      if (editingCircuit.codeMirrorLine) {
58
        editingCircuit.codeMirrorLine.replace(0, null, "circuit-schematic:" + saving_circuit);
59 60 61 62 63
      }
    });
  });
});

64

65 66
CodeMirror.defineMode("mitx_markdown", function(cmCfg, modeCfg) {

67 68
  var htmlFound = CodeMirror.mimeModes.hasOwnProperty("text/html");
  var htmlMode = CodeMirror.getMode(cmCfg, htmlFound ? "text/html" : "text/plain");
69 70 71 72 73 74 75 76 77 78 79

  var header   = 'header'
  ,   code     = 'comment'
  ,   quote    = 'quote'
  ,   list     = 'string'
  ,   hr       = 'hr'
  ,   linktext = 'link'
  ,   linkhref = 'string'
  ,   em       = 'em'
  ,   strong   = 'strong'
  ,   emstrong = 'emstrong';
80 81 82

  var hrRE = /^([*\-=_])(?:\s*\1){2,}\s*$/
  ,   ulRE = /^[*\-+]\s+/
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
  ,   olRE = /^[0-9]+\.\s+/
  ,   headerRE = /^(?:\={3,}|-{3,})$/
  ,   textRE = /^[^\[*_\\<>`]+/
  ,   circuitRE = /^circuit-schematic:(.*)$/;

  function switchInline(stream, state, f) {
    state.f = state.inline = f;
    return f(stream, state);
  }

  function switchBlock(stream, state, f) {
    state.f = state.block = f;
    return f(stream, state);
  }


  // Blocks

101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
  function blankLine(state) {
    // Reset EM state
    state.em = false;
    // Reset STRONG state
    state.strong = false;
    if (!htmlFound && state.f == htmlBlock) {
      state.f = inlineNormal;
      state.block = blockNormal;
    }
    return null;
  }
  
  function escapeHtml(unsafe) {
      return unsafe
           .replace(/&/g, "&amp;")
           .replace(/</g, "&lt;")
           .replace(/>/g, "&gt;")
           .replace(/"/g, "&quot;")
           .replace(/'/g, "&#039;");
   }
  
  var circuit_formatter = {
    creator: function(text) {
      var circuit_value = text.match(circuitRE)[1]
      
      circuit_value = escapeHtml(circuit_value);
      
128
      var html = "<div style='display:block;line-height:0;' class='schematic_container'><a href='#circuit_editor_modal' data-toggle='modal' class='schematic_open' style='display:inline-block;'>" + 
129 130 131 132 133
                  "<input type='hidden' parts='' value='" + circuit_value + "' width='" + schematic_width + "' height='" + schematic_height + "' analyses='' class='schematic ctrls'/></a></div>";
                   
      return html;
    },
    size: function(text) {
134
      return {width: schematic_width + styling_width_delta, height:schematic_height + styling_height_delta};
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
    },
    callback: function(node, line) {
      try {
        update_schematics();
        var schmInput = node.firstChild.firstChild;
        schmInput.codeMirrorLine = line;
        if (schmInput.schematic) { //This is undefined if there was an error making the schematic
          schmInput.schematic.canvas.style.display = "block"; //Otherwise, it gets line height and is a weird size
          schmInput.schematic.always_draw_grid = true;
          schmInput.schematic.redraw_background();
        }
      } catch (err) {
        console.log("Error in mitx_markdown callback: " + err);
      }

    }
  };

153 154
  function blockNormal(stream, state) {
    var match;
155
    if (stream.sol() && stream.match(circuitRE)) {
156 157
      stream.skipToEnd();
      return circuit_formatter;
158 159
    } else if (state.indentationDiff >= 4) {
      state.indentation -= state.indentationDiff;
160 161 162 163 164 165 166 167 168 169 170
      stream.skipToEnd();
      return code;
    } else if (stream.eatSpace()) {
      return null;
    } else if (stream.peek() === '#' || stream.match(headerRE)) {
      state.header = true;
    } else if (stream.eat('>')) {
      state.indentation++;
      state.quote = true;
    } else if (stream.peek() === '[') {
      return switchInline(stream, state, footnoteLink);
171 172
    } else if (stream.match(hrRE, true)) {
      return hr;
173 174 175 176 177 178 179 180 181 182
    } else if (match = stream.match(ulRE, true) || stream.match(olRE, true)) {
      state.indentation += match[0].length;
      return list;
    }
    
    return switchInline(stream, state, state.inline);
  }

  function htmlBlock(stream, state) {
    var style = htmlMode.token(stream, state.htmlState);
183 184 185 186 187
    if (htmlFound && style === 'tag' && state.htmlState.type !== 'openTag' && !state.htmlState.context) {
      state.f = inlineNormal;
      state.block = blockNormal;
    }
    if (state.md_inside && stream.current().indexOf(">")!=-1) {
188 189
      state.f = inlineNormal;
      state.block = blockNormal;
190
      state.htmlState.context = undefined;
191 192 193 194 195 196 197
    }
    return style;
  }


  // Inline
  function getType(state) {
198
    var styles = [];
199
    
200 201
    if (state.strong) { styles.push(state.em ? emstrong : strong); }
    else if (state.em) { styles.push(em); }
202
    
203 204 205 206
    if (state.header) { styles.push(header); }
    if (state.quote) { styles.push(quote); }

    return styles.length ? styles.join(' ') : null;
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
  }

  function handleText(stream, state) {
    if (stream.match(textRE, true)) {
      return getType(state);
    }
    return undefined;        
  }

  function inlineNormal(stream, state) {
    var style = state.text(stream, state)
    if (typeof style !== 'undefined')
      return style;
    
    var ch = stream.next();
    
    if (ch === '\\') {
      stream.next();
      return getType(state);
    }
    if (ch === '`') {
      return switchInline(stream, state, inlineElement(code, '`'));
    }
    if (ch === '[') {
      return switchInline(stream, state, linkText);
    }
    if (ch === '<' && stream.match(/^\w/, false)) {
234 235 236 237 238 239 240
      var md_inside = false;
      if (stream.string.indexOf(">")!=-1) {
        var atts = stream.string.substring(1,stream.string.indexOf(">"));
        if (/markdown\s*=\s*('|"){0,1}1('|"){0,1}/.test(atts)) {
          state.md_inside = true;
        }
      }
241 242 243
      stream.backUp(1);
      return switchBlock(stream, state, htmlBlock);
    }
244 245 246 247 248 249
      
    if (ch === '<' && stream.match(/^\/\w*?>/)) {
      state.md_inside = false;
      return "tag";
    }
      
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
    var t = getType(state);
    if (ch === '*' || ch === '_') {
      if (stream.eat(ch)) {
        return (state.strong = !state.strong) ? getType(state) : t;
      }
      return (state.em = !state.em) ? getType(state) : t;
    }
    
    return getType(state);
  }

  function linkText(stream, state) {
    while (!stream.eol()) {
      var ch = stream.next();
      if (ch === '\\') stream.next();
      if (ch === ']') {
        state.inline = state.f = linkHref;
        return linktext;
      }
    }
    return linktext;
  }

  function linkHref(stream, state) {
    stream.eatSpace();
    var ch = stream.next();
    if (ch === '(' || ch === '[') {
      return switchInline(stream, state, inlineElement(linkhref, ch === '(' ? ')' : ']'));
    }
    return 'error';
  }

  function footnoteLink(stream, state) {
    if (stream.match(/^[^\]]*\]:/, true)) {
      state.f = footnoteUrl;
      return linktext;
    }
    return switchInline(stream, state, inlineNormal);
  }

  function footnoteUrl(stream, state) {
    stream.eatSpace();
    stream.match(/^[^\s]+/, true);
    state.f = state.inline = inlineNormal;
    return linkhref;
  }

  function inlineRE(endChar) {
    if (!inlineRE[endChar]) {
      // match any not-escaped-non-endChar and any escaped char
      // then match endChar or eol
      inlineRE[endChar] = new RegExp('^(?:[^\\\\\\' + endChar + ']|\\\\.)*(?:\\' + endChar + '|$)');
    }
    return inlineRE[endChar];
  }

  function inlineElement(type, endChar, next) {
    next = next || inlineNormal;
    return function(stream, state) {
      stream.match(inlineRE(endChar));
      state.inline = state.f = next;
      return type;
    };
  }

  return {
    startState: function() {
      return {
        f: blockNormal,
        
        block: blockNormal,
321
        htmlState: CodeMirror.startState(htmlMode),
322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339
        indentation: 0,
        
        inline: inlineNormal,
        text: handleText,
        em: false,
        strong: false,
        header: false,
        quote: false
      };
    },

    copyState: function(s) {
      return {
        f: s.f,
        
        block: s.block,
        htmlState: CodeMirror.copyState(htmlMode, s.htmlState),
        indentation: s.indentation,
340
          
341 342 343 344 345
        inline: s.inline,
        text: s.text,
        em: s.em,
        strong: s.strong,
        header: s.header,
346 347
        quote: s.quote,
        md_inside: s.md_inside
348 349 350 351 352
      };
    },

    token: function(stream, state) {
      if (stream.sol()) {
353 354
        if (stream.match(/^\s*$/, true)) { return blankLine(state); }

355 356 357 358 359 360
        // Reset state.header
        state.header = false;
        // Reset state.quote
        state.quote = false;

        state.f = state.block;
361 362 363 364
        var indentation = stream.match(/^\s*/, true)[0].replace(/\t/g, '    ').length;
        state.indentationDiff = indentation - state.indentation;
        state.indentation = indentation;
        if (indentation > 0) { return null; }
365 366 367 368
      }
      return state.f(stream, state);
    },

369 370
    blankLine: blankLine,

371 372 373
    getType: getType
  };

374
}, "xml");
375 376

CodeMirror.defineMIME("text/x-markdown", "markdown");