markdownRenderer.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. /*---------------------------------------------------------------------------------------------
  2. * Copyright (c) Microsoft Corporation. All rights reserved.
  3. * Licensed under the MIT License. See License.txt in the project root for license information.
  4. *--------------------------------------------------------------------------------------------*/
  5. var _a;
  6. import * as DOM from './dom.js';
  7. import { DomEmitter } from './event.js';
  8. import { createElement } from './formattedTextRenderer.js';
  9. import { StandardMouseEvent } from './mouseEvent.js';
  10. import { renderLabelWithIcons } from './ui/iconLabel/iconLabels.js';
  11. import { onUnexpectedError } from '../common/errors.js';
  12. import { Event } from '../common/event.js';
  13. import { parseHrefAndDimensions, removeMarkdownEscapes } from '../common/htmlContent.js';
  14. import { markdownEscapeEscapedIcons } from '../common/iconLabels.js';
  15. import { defaultGenerator } from '../common/idGenerator.js';
  16. import { insane } from '../common/insane/insane.js';
  17. import * as marked from '../common/marked/marked.js';
  18. import { parse } from '../common/marshalling.js';
  19. import { FileAccess, Schemas } from '../common/network.js';
  20. import { cloneAndChange } from '../common/objects.js';
  21. import { resolvePath } from '../common/resources.js';
  22. import { escape } from '../common/strings.js';
  23. import { URI } from '../common/uri.js';
  24. const _ttpInsane = (_a = window.trustedTypes) === null || _a === void 0 ? void 0 : _a.createPolicy('insane', {
  25. createHTML(value, options) {
  26. return insane(value, options);
  27. }
  28. });
  29. /**
  30. * Low-level way create a html element from a markdown string.
  31. *
  32. * **Note** that for most cases you should be using [`MarkdownRenderer`](./src/vs/editor/browser/core/markdownRenderer.ts)
  33. * which comes with support for pretty code block rendering and which uses the default way of handling links.
  34. */
  35. export function renderMarkdown(markdown, options = {}, markedOptions = {}) {
  36. var _a;
  37. const element = createElement(options);
  38. const _uriMassage = function (part) {
  39. let data;
  40. try {
  41. data = parse(decodeURIComponent(part));
  42. }
  43. catch (e) {
  44. // ignore
  45. }
  46. if (!data) {
  47. return part;
  48. }
  49. data = cloneAndChange(data, value => {
  50. if (markdown.uris && markdown.uris[value]) {
  51. return URI.revive(markdown.uris[value]);
  52. }
  53. else {
  54. return undefined;
  55. }
  56. });
  57. return encodeURIComponent(JSON.stringify(data));
  58. };
  59. const _href = function (href, isDomUri) {
  60. const data = markdown.uris && markdown.uris[href];
  61. if (!data) {
  62. return href; // no uri exists
  63. }
  64. let uri = URI.revive(data);
  65. if (isDomUri) {
  66. if (href.startsWith(Schemas.data + ':')) {
  67. return href;
  68. }
  69. // this URI will end up as "src"-attribute of a dom node
  70. // and because of that special rewriting needs to be done
  71. // so that the URI uses a protocol that's understood by
  72. // browsers (like http or https)
  73. return FileAccess.asBrowserUri(uri).toString(true);
  74. }
  75. if (URI.parse(href).toString() === uri.toString()) {
  76. return href; // no transformation performed
  77. }
  78. if (uri.query) {
  79. uri = uri.with({ query: _uriMassage(uri.query) });
  80. }
  81. return uri.toString();
  82. };
  83. // signal to code-block render that the
  84. // element has been created
  85. let signalInnerHTML;
  86. const withInnerHTML = new Promise(c => signalInnerHTML = c);
  87. const renderer = new marked.Renderer();
  88. renderer.image = (href, title, text) => {
  89. let dimensions = [];
  90. let attributes = [];
  91. if (href) {
  92. ({ href, dimensions } = parseHrefAndDimensions(href));
  93. href = _href(href, true);
  94. try {
  95. const hrefAsUri = URI.parse(href);
  96. if (options.baseUrl && hrefAsUri.scheme === Schemas.file) { // absolute or relative local path, or file: uri
  97. href = resolvePath(options.baseUrl, href).toString();
  98. }
  99. }
  100. catch (err) { }
  101. attributes.push(`src="${href}"`);
  102. }
  103. if (text) {
  104. attributes.push(`alt="${text}"`);
  105. }
  106. if (title) {
  107. attributes.push(`title="${title}"`);
  108. }
  109. if (dimensions.length) {
  110. attributes = attributes.concat(dimensions);
  111. }
  112. return '<img ' + attributes.join(' ') + '>';
  113. };
  114. renderer.link = (href, title, text) => {
  115. // Remove markdown escapes. Workaround for https://github.com/chjj/marked/issues/829
  116. if (href === text) { // raw link case
  117. text = removeMarkdownEscapes(text);
  118. }
  119. href = _href(href, false);
  120. if (options.baseUrl) {
  121. const hasScheme = /^\w[\w\d+.-]*:/.test(href);
  122. if (!hasScheme) {
  123. href = resolvePath(options.baseUrl, href).toString();
  124. }
  125. }
  126. title = removeMarkdownEscapes(title);
  127. href = removeMarkdownEscapes(href);
  128. if (!href
  129. || href.match(/^data:|javascript:/i)
  130. || (href.match(/^command:/i) && !markdown.isTrusted)
  131. || href.match(/^command:(\/\/\/)?_workbench\.downloadResource/i)) {
  132. // drop the link
  133. return text;
  134. }
  135. else {
  136. // HTML Encode href
  137. href = href.replace(/&/g, '&amp;')
  138. .replace(/</g, '&lt;')
  139. .replace(/>/g, '&gt;')
  140. .replace(/"/g, '&quot;')
  141. .replace(/'/g, '&#39;');
  142. return `<a href="#" data-href="${href}" title="${title || href}">${text}</a>`;
  143. }
  144. };
  145. renderer.paragraph = (text) => {
  146. if (markdown.supportThemeIcons) {
  147. const elements = renderLabelWithIcons(text);
  148. text = elements.map(e => typeof e === 'string' ? e : e.outerHTML).join('');
  149. }
  150. return `<p>${text}</p>`;
  151. };
  152. if (options.codeBlockRenderer) {
  153. renderer.code = (code, lang) => {
  154. const value = options.codeBlockRenderer(lang, code);
  155. // when code-block rendering is async we return sync
  156. // but update the node with the real result later.
  157. const id = defaultGenerator.nextId();
  158. const promise = Promise.all([value, withInnerHTML]).then(values => {
  159. const span = element.querySelector(`div[data-code="${id}"]`);
  160. if (span) {
  161. DOM.reset(span, values[0]);
  162. }
  163. }).catch(_err => {
  164. // ignore
  165. });
  166. if (options.asyncRenderCallback) {
  167. promise.then(options.asyncRenderCallback);
  168. }
  169. return `<div class="code" data-code="${id}">${escape(code)}</div>`;
  170. };
  171. }
  172. if (options.actionHandler) {
  173. const onClick = options.actionHandler.disposables.add(new DomEmitter(element, 'click'));
  174. const onAuxClick = options.actionHandler.disposables.add(new DomEmitter(element, 'auxclick'));
  175. options.actionHandler.disposables.add(Event.any(onClick.event, onAuxClick.event)(e => {
  176. const mouseEvent = new StandardMouseEvent(e);
  177. if (!mouseEvent.leftButton && !mouseEvent.middleButton) {
  178. return;
  179. }
  180. let target = mouseEvent.target;
  181. if (target.tagName !== 'A') {
  182. target = target.parentElement;
  183. if (!target || target.tagName !== 'A') {
  184. return;
  185. }
  186. }
  187. try {
  188. const href = target.dataset['href'];
  189. if (href) {
  190. options.actionHandler.callback(href, mouseEvent);
  191. }
  192. }
  193. catch (err) {
  194. onUnexpectedError(err);
  195. }
  196. finally {
  197. mouseEvent.preventDefault();
  198. }
  199. }));
  200. }
  201. // Use our own sanitizer so that we can let through only spans.
  202. // Otherwise, we'd be letting all html be rendered.
  203. // If we want to allow markdown permitted tags, then we can delete sanitizer and sanitize.
  204. // We always pass the output through insane after this so that we don't rely on
  205. // marked for sanitization.
  206. markedOptions.sanitizer = (html) => {
  207. const match = markdown.isTrusted ? html.match(/^(<span[^>]+>)|(<\/\s*span>)$/) : undefined;
  208. return match ? html : '';
  209. };
  210. markedOptions.sanitize = true;
  211. markedOptions.silent = true;
  212. markedOptions.renderer = renderer;
  213. // values that are too long will freeze the UI
  214. let value = (_a = markdown.value) !== null && _a !== void 0 ? _a : '';
  215. if (value.length > 100000) {
  216. value = `${value.substr(0, 100000)}…`;
  217. }
  218. // escape theme icons
  219. if (markdown.supportThemeIcons) {
  220. value = markdownEscapeEscapedIcons(value);
  221. }
  222. const renderedMarkdown = marked.parse(value, markedOptions);
  223. // sanitize with insane
  224. element.innerHTML = sanitizeRenderedMarkdown(markdown, renderedMarkdown);
  225. // signal that async code blocks can be now be inserted
  226. signalInnerHTML();
  227. // signal size changes for image tags
  228. if (options.asyncRenderCallback) {
  229. for (const img of element.getElementsByTagName('img')) {
  230. const listener = DOM.addDisposableListener(img, 'load', () => {
  231. listener.dispose();
  232. options.asyncRenderCallback();
  233. });
  234. }
  235. }
  236. return element;
  237. }
  238. function sanitizeRenderedMarkdown(options, renderedMarkdown) {
  239. var _a;
  240. const insaneOptions = getInsaneOptions(options);
  241. return (_a = _ttpInsane === null || _ttpInsane === void 0 ? void 0 : _ttpInsane.createHTML(renderedMarkdown, insaneOptions)) !== null && _a !== void 0 ? _a : insane(renderedMarkdown, insaneOptions);
  242. }
  243. function getInsaneOptions(options) {
  244. const allowedSchemes = [
  245. Schemas.http,
  246. Schemas.https,
  247. Schemas.mailto,
  248. Schemas.data,
  249. Schemas.file,
  250. Schemas.vscodeFileResource,
  251. Schemas.vscodeRemote,
  252. Schemas.vscodeRemoteResource,
  253. ];
  254. if (options.isTrusted) {
  255. allowedSchemes.push(Schemas.command);
  256. }
  257. return {
  258. allowedSchemes,
  259. // allowedTags should included everything that markdown renders to.
  260. // Since we have our own sanitize function for marked, it's possible we missed some tag so let insane make sure.
  261. // HTML tags that can result from markdown are from reading https://spec.commonmark.org/0.29/
  262. // HTML table tags that can result from markdown are from https://github.github.com/gfm/#tables-extension-
  263. allowedTags: ['ul', 'li', 'p', 'code', 'blockquote', 'ol', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'em', 'pre', 'table', 'thead', 'tbody', 'tr', 'th', 'td', 'div', 'del', 'a', 'strong', 'br', 'img', 'span'],
  264. allowedAttributes: {
  265. 'a': ['href', 'name', 'target', 'data-href'],
  266. 'img': ['src', 'title', 'alt', 'width', 'height'],
  267. 'div': ['class', 'data-code'],
  268. 'span': ['class', 'style'],
  269. // https://github.com/microsoft/vscode/issues/95937
  270. 'th': ['align'],
  271. 'td': ['align']
  272. },
  273. filter(token) {
  274. if (token.tag === 'span' && options.isTrusted) {
  275. if (token.attrs['style'] && (Object.keys(token.attrs).length === 1)) {
  276. return !!token.attrs['style'].match(/^(color\:#[0-9a-fA-F]+;)?(background-color\:#[0-9a-fA-F]+;)?$/);
  277. }
  278. else if (token.attrs['class']) {
  279. // The class should match codicon rendering in src\vs\base\common\codicons.ts
  280. return !!token.attrs['class'].match(/^codicon codicon-[a-z\-]+( codicon-modifier-[a-z\-]+)?$/);
  281. }
  282. return false;
  283. }
  284. return true;
  285. }
  286. };
  287. }