define([ 'jquery', '/api/config', '/bower_components/marked/marked.min.js', '/common/common-hash.js', '/common/common-util.js', '/common/hyperscript.js', '/common/inner/common-mediatag.js', '/common/media-tag.js', '/common/highlight/highlight.pack.js', '/customize/messages.js', '/bower_components/diff-dom/diffDOM.js', '/bower_components/tweetnacl/nacl-fast.min.js', 'css!/common/highlight/styles/github.css' ],function ($, ApiConfig, Marked, Hash, Util, h, MT, MediaTag, Highlight, Messages) { var DiffMd = {}; var DiffDOM = window.diffDOM; var renderer = new Marked.Renderer(); var restrictedRenderer = new Marked.Renderer(); var pluginLoaded = Util.mkEvent(); DiffMd.onPluginLoaded = pluginLoaded.reg; var mermaidThemeCSS = //".node rect { fill: #DDD; stroke: #AAA; } " + "rect.task, rect.task0, rect.task2 { stroke-width: 1 !important; rx: 0 !important; } " + "g.grid g.tick line { opacity: 0.25; }" + "g.today line { stroke: red; stroke-width: 1; stroke-dasharray: 3; opacity: 0.5; }"; var Mermaid = { __stubbed: true, init: function () { var args = Util.slice(arguments); require([ 'mermaid', 'css!/code/mermaid-new.css' ], function (_Mermaid) { console.debug("loaded mermaid"); if (Mermaid.__stubbed) { Mermaid = _Mermaid; Mermaid.initialize({ gantt: { axisFormat: '%m-%d', }, "themeCSS": mermaidThemeCSS, }); } Mermaid.init.call(args); pluginLoaded.fire(); }); } }; var Mathjax = { __stubbed: true, tex2svg: function (a, b) { require([ '/bower_components/MathJax/es5/tex-svg.js', ], function () { console.debug("Loaded mathjax"); if (Mathjax.__stubbed) { Mathjax = window.MathJax; } Mathjax.tex2svg(a, b); pluginLoaded.fire(); }); } }; var drawMarkmap; var MarkMapTransform; var Markmap; var markmapLoaded = false; var loadMarkmap = function ($el) { require([ '/lib/markmap/transform.min.js', '/lib/markmap/view.min.js', ], function (_Transform, _View) { if (!markmapLoaded) { console.debug("Loaded markmap"); MarkMapTransform = _Transform; Markmap = _View; markmapLoaded = true; } drawMarkmap($el); pluginLoaded.fire(); }); }; var sfCommon; var fixMathjaxClickables = function ($svg) { // find all links in the tree and do the following for each one var onClick = function (e) { e.preventDefault(); e.stopImmediatePropagation(); var $el = $(e.target); // Open links only from the preview modal if (!sfCommon) { return void console.error('No sfCommon'); } var href = $el.attr('href'); if (!href || !/^(https?:\/\/|\/)/.test(href)) { return; } if (/^http/.test(href)) { sfCommon.openUnsafeURL(href); return; } sfCommon.openURL(href); }; $svg.find('a').click(onClick); // make sure the links added later by collapsing/expading the map are also safe var observer = new MutationObserver(function(mutations) { mutations.forEach(function(mutation) { if (mutation.type === 'childList') { var n; for (var i = 0; i < mutation.addedNodes.length; i++) { n = mutation.addedNodes[i]; if (n.nodeName === "A") { return void n.addEventListener('click', onClick); } $(n).find('a').click(onClick); } } }); }); observer.observe($svg[0], { childList: true, subtree: true }); }; drawMarkmap = function ($el) { if (!markmapLoaded) { return void loadMarkmap($el); } if (!$el) { return console.error("no element provided"); } var data = MarkMapTransform.transform($el[0].getAttribute("markmap-source")); $el[0].innerHTML = ""; Markmap.markmap($el[0].firstChild, data); fixMathjaxClickables($el); }; var highlighter = function () { return function(code, lang) { if (lang) { try { return Highlight.highlight(lang, code).value; } catch (e) { return code; } } return code; }; }; Marked.setOptions({ //sanitize: true, // Disable HTML renderer: renderer, highlight: highlighter(), }); var toc = []; var getTOC = function () { var content = [h('h2', Messages.markdown_toc)]; toc.forEach(function (obj) { // Only include level 2 headings var level = obj.level - 1; if (level < 1) { return; } var a = h('a.cp-md-toc-link', { href: '#', 'data-href': obj.id, }); a.innerHTML = obj.title; content.push(h('p.cp-md-toc-'+level, ['• ', a])); }); return h('div.cp-md-toc', content).outerHTML; }; DiffMd.render = function (md, sanitize, restrictedMd) { Marked.setOptions({ renderer: restrictedMd ? restrictedRenderer : renderer, }); var r = Marked(md, { sanitize: sanitize }); // Add Table of Content if (!restrictedMd) { r = r.replace(/
'+Util.fixHTML(code)+''; } else if (language === 'markmap') { return '
'+Util.fixHTML(code)+''; } else if (language === 'mathjax') { var svg = Mathjax.tex2svg(code, {display: true}); if (!svg) { return defaultCode.apply(renderer, arguments); } return '
'+ svg.innerHTML.replace(/xlink:href/g, "href") +''; } else { return defaultCode.apply(renderer, arguments); } }; restrictedRenderer.code = renderer.code; renderer.heading = function (text, level) { var i = 0; var safeText = text.toLowerCase().replace(/[^\w]+/g, '-'); var getId = function () { return 'cp-md-' + i + '-' + safeText; }; var id = getId(); var isAlreadyUsed = function (obj) { return obj.id === id; }; while (toc.some(isAlreadyUsed)) { i++; id = getId(); } toc.push({ level: level, id: id, title: Util.stripTags(text) }); return "
)?\[[xX]\](<\/p>)?\s*/; var uncheckedTaskItemPtn = /^\s*(
)?\[ ?\](<\/p>)?\s*/; var bogusCheckPtn = //; var bogusUncheckPtn = //; renderer.listitem = function (text) { var isCheckedTaskItem = checkedTaskItemPtn.test(text); var isUncheckedTaskItem = uncheckedTaskItemPtn.test(text); var hasBogusCheckedInput = bogusCheckPtn.test(text); var hasBogusUncheckedInput = bogusUncheckPtn.test(text); var isCheckbox = true; if (isCheckedTaskItem) { text = text.replace(checkedTaskItemPtn, '') + '\n'; } else if (isUncheckedTaskItem) { text = text.replace(uncheckedTaskItemPtn, '') + '\n'; } else if (hasBogusCheckedInput) { text = text.replace(bogusCheckPtn, '') + '\n'; } else if (hasBogusUncheckedInput) { text = text.replace(bogusUncheckPtn, '') + '\n'; } else { isCheckbox = false; } var cls = (isCheckbox) ? ' class="todo-list-item"' : ''; return '
' + p + '
\n'; }; renderer.paragraph = function (p) { if (p === '[TOC]') { return ''; } return renderParagraph(p); }; restrictedRenderer.paragraph = function (p) { return renderParagraph(p); }; var forbiddenTags = [ 'SCRIPT', 'IFRAME', 'OBJECT', 'APPLET', 'VIDEO', // privacy implications of videos are the same as images 'AUDIO', // same with audio ]; var unsafeTag = function (info) { /*if (info.node && $(info.node).parents('media-tag').length) { // Do not remove elements inside a media-tag return true; }*/ if (['addAttribute', 'modifyAttribute'].indexOf(info.diff.action) !== -1) { if (/^on/i.test(info.diff.name)) { console.log("Rejecting forbidden element attribute with name", info.diff.name); return true; } } if (['addElement', 'replaceElement'].indexOf(info.diff.action) !== -1) { var msg = "Rejecting forbidden tag of type (%s)"; if (info.diff.element && forbiddenTags.indexOf(info.diff.element.nodeName.toUpperCase()) !== -1) { console.log(msg, info.diff.element.nodeName); return true; } else if (info.diff.newValue && forbiddenTags.indexOf(info.diff.newValue.nodeName.toUpperCase()) !== -1) { console.log("Replacing restricted element type (%s) with PRE", info.diff.newValue.nodeName); info.diff.newValue.nodeName = 'PRE'; } } }; var slice = function (coll) { return Array.prototype.slice.call(coll); }; var removeNode = function (node) { if (!(node && node.parentElement)) { return; } var parent = node.parentElement; if (!parent) { return; } console.log('removing %s tag', node.nodeName); parent.removeChild(node); }; var removeForbiddenTags = function (root) { if (!root) { return; } if (forbiddenTags.indexOf(root.nodeName.toUpperCase()) !== -1) { removeNode(root); } slice(root.children).forEach(removeForbiddenTags); }; /* remove listeners from the DOM */ var removeListeners = function (root) { if (!root) { return; } slice(root.attributes).map(function (attr) { if (/^on/i.test(attr.name)) { console.log('removing attribute', attr.name, root.attributes[attr.name]); root.attributes.removeNamedItem(attr.name); } }); // all the way down slice(root.children).forEach(removeListeners); }; var domFromHTML = function (html) { var Dom = new DOMParser().parseFromString(html, "text/html"); Dom.normalize(); removeForbiddenTags(Dom.body); removeListeners(Dom.body); return Dom; }; var DD = new DiffDOM({ preDiffApply: function (info) { if (unsafeTag(info)) { return true; } }, }); var makeDiff = function (A, B, id) { var Err; var Els = [A, B].map(function (frag) { if (typeof(frag) === 'object') { if (!frag || (frag && !frag.body)) { Err = "No body"; return; } var els = frag.body.querySelectorAll('#'+id); if (els.length) { return els[0]; } } Err = 'No candidate found'; }); if (Err) { return Err; } var patch = DD.diff(Els[0], Els[1]); return patch; }; var plugins = {}; var removeMermaidClickables = function ($el) { // find all links in the tree and do the following for each one $el.find('a').each(function (index, a) { var parent = a.parentElement; if (!parent) { return; } // iterate over the links' children and transform them into preceding children // to preserve their visible ordering slice(a.children).forEach(function (child) { parent.insertBefore(child, a); }); // remove the link once it has been emptied $(a).remove(); }); // finally, find all 'clickable' items and remove the class $el.find('.clickable').removeClass('clickable'); }; plugins.mermaid = { name: 'mermaid', attr: 'mermaid-source', render: function ($el) { Mermaid.init(undefined, $el); // clickable elements in mermaid don't work well with our sandboxing setup // the function below strips clickable elements but still leaves behind some artifacts // tippy tooltips might still be useful, so they're not removed. It would be // preferable to just support links, but this covers up a rough edge in the meantime removeMermaidClickables($el); } }; plugins.markmap = { name: 'markmap', attr: 'markmap-source', render: function ($el) { drawMarkmap($el); } }; DiffMd.apply = function (newHtml, $content, common) { if (!sfCommon) { sfCommon = common; } var contextMenu = common.importMediaTagMenu(); var id = $content.attr('id'); if (!id) { throw new Error("The element must have a valid id"); } var pattern = /(